v9.1.1
Menu

Multi-Head Attention Forward Pass (Simplified)

hardPROTransformersNeural Networks, Matrix MathAdvanced Architectures

Implement a simplified Multi-Head Self-Attention (MHSA) forward pass.

Given input embeddings X∈RN×DX \in \mathbb{R}^{N \times D} and weight matrix WQKV∈RD×3DW_{QKV} \in \mathbb{R}^{D \times 3D}:

  1. Compute [Q,K,V]=X⋅WQKV[Q, K, V] = X \cdot W_{QKV} (split into three D-dimensional matrices)
  2. Compute attention: A=Q⋅KTA = Q \cdot K^T (unscaled, no softmax)
  3. Apply residual: Y=X+A⋅VY = X + A \cdot V

Simplifications:

  • Single head (no multi-head concatenation)
  • No softmax or scaling factor D\sqrt{D}
  • No output projection WOW_O
  • No layer normalization or MLP

Example

Input
X = [[1, 0], [0, 1]]
W_QKV = [[1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1]]
Output
[[2.0, 0.0], [0.0, 2.0]]
Reasoning
  • Inputs: X is N=2N = 2 tokens with D=2D = 2 features, the identity II. W_QKV is 2×62 \times 6: three 2×22 \times 2 blocks (query, key, value), each II, so WQKV=[ I∣I∣I ]W_{QKV} = [\,I \mid I \mid I\,].
  • Projection: XWQKVX W_{QKV} is 2×62 \times 6; its column blocks of width DD are QQ, KK, VV. With identity blocks, Q=K=V=X=IQ = K = V = X = I.
  • Scores: A=QKTA = Q K^T is N×NN \times N; entry aija_{ij} is the dot product of token ii's query with token jj's key. Here a11=a22=1a_{11} = a_{22} = 1 and a12=a21=0a_{12} = a_{21} = 0, so A=IA = I: each token attends only to itself, with raw weight 1 (no scaling, no softmax).
  • Mix + residual: AV=IA V = I, so Y=X+AV=I+IY = X + A V = I + I, giving [[2.0, 0.0], [0.0, 2.0]], an N×DN \times D result like XX.
  • Notice: with all-ones XX, every score is 2, AVAV is all 4s and YY is all 5s: unnormalised scores grow fast.

Constraints

  • NN (Sequence Length): 2-4
  • DD (Embedding Dimension): 2-3
  • Input XX and WQKVW_{QKV} are provided as numpy arrays

Learn this in

More from Advanced Architectures

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.