π§© The Subspace Resolution Dilemma: Moving Beyond Averaged Attention
While single-head Scaled Dot-Product Attention successfully establishes direct $O(1)$ pairwise routing across sequential positions, it suffers from a fundamental mathematical constraint: an averaging bottleneck across distinct semantic subspaces. In a single attention head, a token vector at position $i$ must compute a single probability distribution over all sequence positions. If the token "bank" needs to simultaneously attend to its syntactic modifier ("river"), resolve a long-range co-referent pronoun ("it"), and track structural verb arguments across a clause, a single Softmax distribution is forced to compromiseβblurring distinct linguistic relationships into a single weighted average. Multi-Head Attention (MHA) resolves this representational bottleneck by projecting Queries, Keys, and Values $h$ times with independently learned linear transformations into lower-dimensional representation subspaces ($d_k = d_{\text{model}} / h$). Each head specializes in parallelβcapturing syntactic dependencies, positional offsets, factual assertions, and semantic analogiesβbefore their contextual outputs are concatenated and projected back into the model's unified embedding space.
MULTI-HEAD ATTENTION ARCHITECTURAL FLOW (h HEADS IN PARALLEL):
Queries Q Keys K Values V
(N Γ d_model) (M Γ d_model) (M Γ d_model)
β β β
ββββββββββββββββββΌββββββββββββββββ β ββββββββββββββββββΌββββββββββββββββ
β Linear W_Q1 β Linear W_Q2 β... β β Linear W_V1 β Linear W_V2 β...
βΌ βΌ βΌ βΌ βΌ βΌ βΌ
Q_1 (NΓd_k) Q_2 (NΓd_k) Q_h ... V_1 (NΓd_v) V_2 (NΓd_v) V_h
β β β β β β
ββββββββββββββββββ΄ββββββββββββββββΌβββββββββββββββββΌβββββββββββββββββ΄ββββββββββββββββ€
βΌ βΌ βΌ βΌ
βββββββββββ βββββββββββ βββββββββββ βββββββββββ
β HEAD 1 β β HEAD 2 β β HEAD 1 β β HEAD 2 β
β Attn(Q1,β β Attn(Q2,β Β·Β·Β· β Attn(Q1,β β Attn(Q2,β
β K1, V1)β β K2, V2)β β K1, V1)β β K2, V2)β
ββββββ¬βββββ ββββββ¬βββββ ββββββ¬βββββ ββββββ¬βββββ
β β β β
β Context head_1 β R^{N Γ d_v} β Context head_2 β β
ββββββββββββββββββββββββββββββββββ΄βββββββββ¬ββββββββ΄βββββββββββββββββββββββββββββββββ
β
βΌ Concatenate Along Feature Dimension
βββββββββββββββββββββββββββββββββββββ
β Concat(head_1, head_2, ..., head_h)β β R^{N Γ (h Β· d_v)} = R^{N Γ d_model}
βββββββββββββββββββ¬ββββββββββββββββββ
β
βΌ Linear Final Output Projection W_O β R^{d_model Γ d_model}
βββββββββββββββββββββββββββββββββββββ
β MultiHead(Q, K, V) β R^{N Γ d_model}
βββββββββββββββββββββββββββββββββββββ
MATHEMATICAL DEFINITION OF MULTI-HEAD ATTENTION:
Given input query matrix Q β R^{N Γ d_model}, key matrix K β R^{M Γ d_model}, and value matrix V β R^{M Γ d_model}:
1. HEAD COMPUTATION:
For each head i β {1, 2, ..., h}:
head_i = Attention( Q Β· W_i^Q, K Β· W_i^K, V Β· W_i^V )
where the learned linear projection parameter matrices are:
β’ W_i^Q β R^{d_model Γ d_k} : Query projection matrix for head i
β’ W_i^K β R^{d_model Γ d_k} : Key projection matrix for head i
β’ W_i^V β R^{d_model Γ d_v} : Value projection matrix for head i
2. SCALED DOT-PRODUCT ATTENTION PER HEAD:
head_i = Softmax β (Q W_i^Q)(K W_i^K)^T β Β· (V W_i^V)
β ββββββββββββββββββββ β
β βd_k β
where head_i β R^{N Γ d_v}
3. CONCATENATION & FINAL PROJECTION:
MultiHead(Q, K, V) = Concat(head_1, head_2, ..., head_h) Β· W^O
where:
β’ Concat(head_1, ..., head_h) β R^{N Γ (h Β· d_v)}
β’ W^O β R^{(h Β· d_v) Γ d_model} : Output projection parameter matrix
4. STANDARD DIMENSIONAL CONSTRAINTS (Vaswani et al., 2017):
Typically, to maintain total model dimension parity:
d_k = d_v = d_model / h
h Β· d_v = d_model
Therefore: W^O β R^{d_model Γ d_model}
PARAMETER AND FLOP PROFILING FOR MULTI-HEAD ATTENTION:
1. PARAMETER FOOTPRINT BREAKDOWN:
Assuming standard convention where d_k = d_v = d_model / h:
β’ Query Projections : h Γ (d_model Γ d_k) = h Γ (d_model Γ (d_model / h)) = d_model^2
β’ Key Projections : h Γ (d_model Γ d_k) = h Γ (d_model Γ (d_model / h)) = d_model^2
β’ Value Projections : h Γ (d_model Γ d_v) = h Γ (d_model Γ (d_model / h)) = d_model^2
β’ Output Projection : (h Γ d_v) Γ d_model = d_model Γ d_model = d_model^2
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Total Trainable Parameters = 4 Β· d_model^2 (Independent of head count h!)
Example: LLaMA-3-8B (d_model = 4096, h = 32):
Params = 4 Γ (4096)^2 = 4 Γ 16,777,216 β 67.1 Million parameters per attention layer.
2. FLOP COUNT BREAKDOWN (Sequence Length N):
For a single layer processing sequence of length N:
β’ Linear Projections (Q, K, V) : 3 Γ (2 Β· N Β· d_model^2) = 6 N d_model^2
β’ Attention Score (Q Β· K^T) : h Γ (2 Β· N Β· N Β· d_k) = 2 N^2 d_model
β’ Softmax + Masking : h Γ (3 Β· N^2) = 3 h N^2
β’ Value Accumulation (A Β· V) : h Γ (2 Β· N Β· N Β· d_v) = 2 N^2 d_model
β’ Final Output Linear (W_O) : 2 Β· N Β· d_model^2 = 2 N d_model^2
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Total FLOPs per Layer β 8 N d_model^2 + 4 N^2 d_model
3. DOMINANCE TRANSITIONS OVER SEQUENCE LENGTH N:
β’ Short Sequences (N << d_model): The term 8 N d_model^2 dominates (Compute-bound linear projections).
β’ Long Sequences (N >> d_model) : The term 4 N^2 d_model dominates (Quadratic attention score scaling).
THE ATTENTION ARCHITECTURE SPECTRUM (MHA vs. MQA vs. GQA):
1. MULTI-HEAD ATTENTION (MHA) 2. MULTI-QUERY ATTENTION (MQA) 3. GROUPED-QUERY ATTENTION (GQA)
(Standard Transformer - Vaswani) (Shazeer, 2019 - PaLM, Falcon) (Ainslie et al., 2023 - LLaMA-3)
Equal Q, K, V Heads (e.g., 8 Q, 8 K, 8 V)Single shared K, V Head across all Q Grouped K, V Heads (e.g. 8 Q, 2 K, 2 V)
Q1 Q2 Q3 Q4 Q5 Q6 Q7 Q8 Q1 Q2 Q3 Q4 Q5 Q6 Q7 Q8 Q1 Q2 Q3 Q4 Q5 Q6 Q7 Q8
β β β β β β β β β β β β β β β β βββββ¬ββββ βββββ¬ββββ βββββ¬ββββ βββββ¬ββββ
βΌ βΌ βΌ βΌ βΌ βΌ βΌ βΌ β β β β β β β β βΌ βΌ βΌ βΌ
K1 K2 K3 K4 K5 K6 K7 K8 βββββ΄ββββ΄ββββΌββββ΄ββββ΄ββββ΄ββββ Group 1 Group 2 Group 3 Group 4
V1 V2 V3 V4 V5 V6 V7 V8 βΌ βΌ βΌ βΌ βΌ
K1, V1 K1, V1 K2, V2 K3, V3 K4, V4
(Shared by ALL Queries) (Shared by 2 Queries each)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
THE INFERENCE KV-CACHE MEMORY BOTTLENECK:
During autoregressive token generation, previous Key and Value vectors must be cached in GPU VRAM
to avoid recomputing historical tokens:
KV-Cache Size per Token = 2 Γ (2 bytes) Γ n_layers Γ n_kv_heads Γ d_k
For a 70B Model (80 layers, d_k = 128, context length = 8192):
β’ Standard MHA (n_kv_heads = 64) : Cache size = 2 Γ 2 Γ 80 Γ 64 Γ 128 Γ 8192 β 21.4 GB per user request!
β’ Multi-Query (n_kv_heads = 1) : Cache size = 2 Γ 2 Γ 80 Γ 1 Γ 128 Γ 8192 β 0.33 GB (98% reduction! but loses capacity)
β’ Grouped-Query(n_kv_heads = 8) : Cache size = 2 Γ 2 Γ 80 Γ 8 Γ 128 Γ 8192 β 2.68 GB (87% reduction; matches MHA quality!)
THE EFFICIENT 4D BATCHED TENSOR RESHAPING PIPELINE:
STEP 1: FUSED LINEAR PROJECTION (Single GPU Kernel Launch)
Input X β R^{B Γ S Γ d_model} βββΊ W_qkv β R^{d_model Γ (3 Β· d_model)} βββΊ QKV β R^{B Γ S Γ (3 Β· d_model)}
STEP 2: RESHAPE TO SEPARATE HEADS
Split the feature dimension into [3, num_heads, head_dim]:
QKV.view(B, S, 3, H, D) where D = d_model / H
STEP 3: PERMUTE AXES FOR BATCH MATRIX MULTIPLICATION
Transpose dimensions so that Batch (B) and Heads (H) become the leading batch dimensions:
permute(2, 0, 3, 1, 4)
Resulting Query tensor: Q β R^{B Γ H Γ S_q Γ D}
Resulting Key tensor: K β R^{B Γ H Γ S_k Γ D}
Resulting Value tensor: V β R^{B Γ H Γ S_k Γ D}
STEP 4: HARDWARE BATCH GEMM OVER (B Γ H)
The GPU treats (B Γ H) as an expanded batch dimension!
scores = (Q @ K.transpose(-2, -1)) / βD βββΊ Shape: (B Γ H Γ S_q Γ S_k)
context = Softmax(scores) @ V βββΊ Shape: (B Γ H Γ S_q Γ D)
STEP 5: RECOMBINE HEADS (CONTIGUOUS RESHAPE)
Transpose back: context.transpose(1, 2) βββΊ Shape: (B Γ S_q Γ H Γ D)
Flatten heads: .contiguous().view(B, S_q, d_model)
Project out: @ W_O βββΊ Shape: (B Γ S_q Γ d_model)
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class MultiHeadAttention(nn.Module):
"""
Vectorized Multi-Head Attention (MHA) conforming to the Transformer standard.
Processes all heads in parallel using fused projections and 4D tensor batching.
"""
def __init__(self, d_model: int, num_heads: int, dropout_p: float = 0.0, bias: bool = True):
super().__init__()
assert d_model % num_heads == 0, f"d_model ({d_model}) must be divisible by num_heads ({num_heads})"
self.d_model = d_model
self.num_heads = num_heads
self.head_dim = d_model // num_heads
self.scale = 1.0 / math.sqrt(self.head_dim)
# Fused linear projection for Q, K, V (Reduces 3 matrix multiplications to 1)
self.qkv_projection = nn.Linear(d_model, 3 * d_model, bias=bias)
# Final output projection
self.out_projection = nn.Linear(d_model, d_model, bias=bias)
self.dropout = nn.Dropout(dropout_p)
def forward(self, x: torch.Tensor, mask: torch.Tensor = None) -> tuple:
"""
x : Input tensor of shape (Batch_Size, Seq_Len, d_model)
mask : Optional boolean or additive mask broadcastable to (Batch, 1, Seq_Len, Seq_Len)
Returns:
output : Contextual representation of shape (Batch_Size, Seq_Len, d_model)
attn_weights : Normalized attention matrix of shape (Batch_Size, num_heads, Seq_Len, Seq_Len)
"""
batch_size, seq_len, _ = x.shape
# 1. Project input to fused Queries, Keys, and Values: (B, S, 3 * d_model)
qkv = self.qkv_projection(x)
# 2. Reshape and unbind into separate Q, K, V tensors:
# (B, S, 3, H, D) -> Permute to (3, B, H, S, D)
qkv = qkv.view(batch_size, seq_len, 3, self.num_heads, self.head_dim)
qkv = qkv.permute(2, 0, 3, 1, 4)
q, k, v = qkv[0], qkv[1], qkv[2] # Each has shape: (B, H, S, D)
# 3. Compute Scaled Dot-Product Scores: (B, H, S, D) x (B, H, D, S) -> (B, H, S, S)
scores = torch.matmul(q, k.transpose(-2, -1)) * self.scale
# 4. Apply Mask (Padding or Causal)
if mask is not None:
if mask.dtype == torch.bool:
scores = scores.masked_fill(~mask, float('-inf'))
else:
scores = scores + mask
# 5. Softmax Normalization across Key sequence dimension (-1)
attn_weights = F.softmax(scores, dim=-1)
attn_weights = torch.nan_to_num(attn_weights, nan=0.0) # Handle completely masked rows safely
# Apply dropout to attention weights
attn_dropped = self.dropout(attn_weights)
# 6. Weighted Value Accumulation: (B, H, S, S) x (B, H, S, D) -> (B, H, S, D)
context = torch.matmul(attn_dropped, v)
# 7. Concatenate Heads: (B, H, S, D) -> (B, S, H, D) -> (B, S, d_model)
context = context.permute(0, 2, 1, 3).contiguous().view(batch_size, seq_len, self.d_model)
# 8. Final Output Affine Projection
output = self.out_projection(context)
return output, attn_weights
# ------------------------------------------------------------------------------
# Runtime Execution & Mathematical Verification Suite
# ------------------------------------------------------------------------------
if __name__ == "__main__":
torch.manual_seed(42)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
B, S, D_model, Heads = 4, 16, 512, 8
print("[*] Initializing Vectorized Multi-Head Attention Module...")
mha = MultiHeadAttention(d_model=D_model, num_heads=Heads, dropout_p=0.0).to(device)
# Synthetic Input Sequence (Batch=4, SeqLen=16, d_model=512)
input_tensor = torch.randn(B, S, D_model, device=device, requires_grad=True)
# Construct Causal Autoregressive Mask
causal_mask = torch.tril(torch.ones(S, S, device=device, dtype=torch.bool)).unsqueeze(0).unsqueeze(0)
# Forward Computation
out, weights = mha(input_tensor, mask=causal_mask)
print(f"[β] Forward Pass Success:")
print(f" β’ Output Tensor Shape : {out.shape} (Expected: [{B}, {S}, {D_model}])")
print(f" β’ Attention Weights Shape: {weights.shape} (Expected: [{B}, {Heads}, {S}, {S}])")
print(f" β’ Row Normalization Sum : {weights[0, 0, 0].sum().item():.4f} (Must equal 1.0)")
print(f" β’ Causal Future Value Check: {weights[0, 0, 0, 1].item():.4f} (Must be strictly 0.0)")
# Backward Gradient Computation
loss = out.sum()
loss.backward()
print(f"[β] Backward Propagation Verification:")
print(f" β’ Input Gradient Shape : {input_tensor.grad.shape}")
print(f" β’ Input Gradient L2 Norm : {input_tensor.grad.norm().item():.4f}")
print(f" β’ QKV Weights Grad Norm : {mha.qkv_projection.weight.grad.norm().item():.4f}")
print(f" β’ Out Projection Grad Norm: {mha.out_projection.weight.grad.norm().item():.4f}")
SELF-ATTENTION vs. CROSS-ATTENTION COMPARISON:
1. SELF-ATTENTION (Decoder or Encoder Self-Attention):
Queries, Keys, and Values ALL derive from the SAME input sequence X:
Q = X Β· W_Q, K = X Β· W_K, V = X Β· W_V
Goal: Models relationships BETWEEN tokens within the SAME sequence.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
2. CROSS-ATTENTION (Seq2Seq Decoders & Diffusion Conditioning):
Queries derive from DECODER sequence Y; Keys and Values derive from ENCODER sequence X:
Target Representation Y βββΊ Q = Y Β· W_Q (Query: "What information does the decoder need?")
β
βΌ
βββββββββββββββββββββββββββββ
β Cross-Attention Softmax β βββ K = X Β· W_K (Key: "What information does
β (Q Β· K^T / βd_k) β the encoder offer?")
βββββββββββββββ¬ββββββββββββββ
β
βΌ
Context Output = Attention Β· V βββ V = X Β· W_V (Value: The actual content)
APPLICATIONS OF CROSS-ATTENTION:
β’ Neural Machine Translation: English Queries attend to French Encoder Keys/Values.
β’ Stable Diffusion: Image latent spatial tokens (Queries) attend to text prompt embeddings (Keys/Values).
β’ Speech Recognition (Whisper): Text tokens attend to audio mel-spectrogram convolutional features.
MULTI-HEAD ATTENTION ANOMALIES & REMEDIATIONS:
1. THE "RESHAPE-WITHOUT-TRANSPOSE" CATASTROPHE:
β’ Symptom: The model trains, but loss plateaus at a high value; attention heads display gibberish weights.
β’ Cause: Reshaping from (B, S, d_model) to (B, H, S, D) directly using '.view()' WITHOUT permuting!
view(B, H, S, D) chops the sequence dimension across heads, corrupting token representations!
β’ Correct Code:
x = x.view(B, S, H, D).permute(0, 2, 1, 3) # (B, H, S, D)
2. SILENT GRADIENT DEGRADATION: OMITTING THE OUTPUT PROJECTION W_O:
β’ Symptom: Multi-head attention performs no better than single-head attention despite having 16 heads.
β’ Cause: Concatenating head outputs and feeding them directly to the Feed-Forward Network without W_O.
Without W_O, there is NO mechanism to linearly mix representations across the different subspaces!
β’ Remediation: Always apply the learned output projection: output = self.out_projection(concat_heads).
3. CALLING .VIEW() ON NON-CONTIGUOUS TENSORS:
β’ Symptom: RuntimeError: "view size is not compatible with input tensor's size and stride.
Call .contiguous() before .view()".
β’ Cause: The '.permute()' operation modifies memory strides without moving data in physical VRAM.
β’ Remediation: Insert '.contiguous()' immediately following the permute before calling view():
context = context.permute(0, 2, 1, 3).contiguous().view(B, S, d_model)
4. HEAD DIMENSION NON-DIVISIBILITY BUG:
β’ Symptom: Assertion error or runtime crash during initialization.
β’ Cause: Setting d_model = 512 with num_heads = 14 (512 is not divisible by 14!).
β’ Remediation: Ensure d_model % num_heads == 0. Standard pairings:
d_model = 768 (12 heads Γ 64), d_model = 4096 (32 heads Γ 128).
MULTI-HEAD ATTENTION (MHA) SPECIFICATION MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββ
β ARCHITECTURAL COMPONENT β MATHEMATICAL FORMULATION β TENSOR SHAPE β PRIMARY OPERATIONAL ROLE β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββββ€
β Fused QKV Projection β X Β· W_qkv β (B, S, 3Β·d_model)β Generates Q, K, V in 1 kernel β
β Subspace Dimension β d_k = d_v = d_model / h β Scalar β Dimensionality of single head β
β Multi-Head Query Q β permute(2,0,3,1,4)[0] β (B, H, S_q, d_k) β Independent query subspaces β
β Multi-Head Key K β permute(2,0,3,1,4)[1] β (B, H, S_k, d_k) β Independent key subspaces β
β Multi-Head Value V β permute(2,0,3,1,4)[2] β (B, H, S_k, d_v) β Independent value subspaces β
β Batched Attention Score β (Q Β· K^T) / βd_k β (B, H, S_q, S_k) β Subspace pairwise affinity β
β Head Concatenation β Concat(head_1, ..., head_h) β (B, S_q, d_model)β Reassembles parallel subspaces β
β Output Projection W_O β Concat Β· W_O β (B, S_q, d_model)β Inter-subspace feature mixing β
β Multi-Query Attention β 1 Shared KV Head across Q β (B, 1, S_k, d_k) β Slashes inference KV-Cache 98% β
β Grouped-Query Attention β G Groups of Q share 1 KV Headβ (B, G, S_k, d_k) β Modern standard (LLaMA-3) β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββ€
β TOP 5 MULTI-HEAD ATTENTION AXIOMS FOR AI ENGINEERS: β
β 1. Subspaces Prevent Blurring: Multi-Head Attention allows the model to attend simultaneously to syntactic, β
β positional, and semantic information across distinct representation spaces. β
β 2. Parameter Invariance Across Heads: Splitting into h heads preserves the exact parameter count and β
β computational cost of a single large head: 4 Β· d_model^2 parameters. β
β 3. Fuse Linear Projections: Always project Q, K, and V in a single fused linear layer (3 Β· d_model) to β
β maximize GPU arithmetic intensity and minimize kernel dispatch latency. β
β 4. Permute Before View: Never reshape directly across the sequence dimension; use permute(0, 2, 1, 3) β
β followed by contiguous() to prevent token representation corruption. β
β 5. GQA for Foundation Serving: Always prefer Grouped-Query Attention (GQA) over MHA in production LLMs to β
β reduce KV-Cache VRAM usage by 8Γ during high-concurrency inference. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ