Multi-Head Attention Forward Pass (Simplified)
Implement a simplified Multi-Head Self-Attention (MHSA) forward pass.
Given input embeddings XβRNΓD and weight matrix WQKVββRDΓ3D:
- Compute [Q,K,V]=Xβ WQKVβ (split into three D-dimensional matrices)
- Compute attention: A=Qβ KT (unscaled, no softmax)
- Apply residual: Y=X+Aβ V
Simplifications:
- Single head (no multi-head concatenation)
- No softmax or scaling factor Dβ
- No output projection WOβ
- No layer normalization or MLP
Example:
X = [[1,0],[0,1]], W_QKV = 2x6 identity-like matrix
2x2 matrix Y after residual connection
Q, K, V are derived from X @ W_QKV split into thirds. A = QK^T computes attention scores. Y = X + AV applies residual.
Constraints:
- N (Sequence Length): 2-4
- D (Embedding Dimension): 2-3
- Input X and WQKVβ are provided as numpy arrays
1. Background Knowledge
Multi-Head Self-Attention (MHSA) is the core mechanism of Transformer models, enabling sequences to attend to different representation subspaces in parallel. In self-attention, input embeddings XβRNΓD (where N is sequence length, D is embedding dimension) are linearly projected into Query (Q), Key (K), and Value (V) matrices via a shared weight matrix WQKVββRDΓ3D.
The standard attention computes similarity scores as A=\text{softmax}\left(\frac{QK^T}{dkββ}\right)V, where each row of A represents attention weights for a position across the sequence. This problem simplifies to unscaled dot-product attention (A=QKT) without softmax, followed by a residual connection Y=X+AV. Multi-head variants split Q,K,V into h heads, compute attention independently, then concatenate and projectβbut here it's single-head for simplicity.
Prerequisites: Matrix multiplication, NumPy array slicing, understanding XWQKVβ yields concatenated [Qβ£Kβ£V] each of shape RNΓD.
2. Algorithm Approach
The forward pass follows the standard Transformer encoder attention block, stripped to essentials:
- Linear projection: Z=XWQKVββRNΓ3D
- Split: Q=Z[:,:D], K=Z[:,D:2D], V=Z[:,2D:] (each RNΓD)
- Attention scores: A=QKTβRNΓN (raw dot products)
- Weighted values: AVβRNΓD
- Residual: Y=X+AVβRNΓD
This mirrors the mathematical foundation in Transformer papers, focusing on pairwise sequence interactions without scaling or normalization.
Continue the full explanation
You're reading the free preview. Unlock the complete walkthrough, the code editor, test runner and reference solution with Premium.
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.