Fix Causal Multi-Head Self-Attention Bugs
Medium · Software Engineering Fundamentals · Machine Learning Engineer · Onsite
Problem Statement
While training an autoregressive decoder Transformer, the validation loss plateaus immediately and activations blow up to NaN within a few hundred gradient updates. Bisecting the model layers isolates the failure to the causal multi-head self-attention block sketched below:
import torch
import torch.nn.functional as F
class SelfAttention(torch.nn.Module):
def __init__(self, d_model, n_heads):
super().__init__()
self.d_model = d_model
self.n_heads = n_heads
self.head_dim = d_model // n_heads
self.qkv_proj = torch.nn.Linear(d_model, 3 * d_model)
def forward(self, x):
# x has shape (batch_size, seq_len, d_model)
b, t, _ = x.shape
q, k, v = self.qkv_proj(x).chunk(3, dim=-1)
q = q.view(b, t, self.n_heads, self.head_dim).transpose(1, 2)
k = k.view(b, t, self.n_heads, self.head_dim).transpose(1, 2)
v = v.view(b, t, self.n_heads, self.head_dim).transpose(1, 2)
scores = torch.matmul(q, k.transpose(-2, -1))
causal = torch.tril(torch.ones(t, t)).view(1, 1, t, t)
scores = scores.masked_fill(causal == 0, float("-inf"))
probs = F.softmax(scores, dim=-1)
return torch.matmul(probs, v)
Diagnose the mathematical, shape, and numerical-stability defects in this module (including how unscaled dot products, -inf masks, fully masked rows, and head reshaping interact), and implement the repaired forward pass in pure NumPy:
def self_attention(
x: np.ndarray,
w_qkv: np.ndarray,
b_qkv: np.ndarray,
n_heads: int,
key_padding_mask: Optional[np.ndarray] = None,
) -> np.ndarray:
Your implementation must obey every rule below:
- Packed QKV projection & head split: Compute
qkv = x @ w_qkv + b_qkv, wherexhas shape(batch, seq_len, d_model),w_qkvhas shape(d_model, 3 * d_model), andb_qkvhas shape(3 * d_model,). Splitqkvinto three equal slicesq,k,v(in that order) along the last axis. Partition each inton_headsheads of widthhead_dim = d_model // n_heads, where headhtakes channelsh * head_dimthrough(h + 1) * head_dim - 1. - Scaled dot-product logits: Scale each head's query-key dot products by
1 / sqrt(head_dim)before taking exponentials. Promotefloat16inputs to at leastfloat32for intermediate arithmetic so raw inner products never overflowfloat16's65,504ceiling. - Causal & key-padding masks: Query token
imay attend only to key positionsj <= i. Whenkey_padding_maskis supplied (a(batch, seq_len)boolean array withTruefor real tokens andFalsefor padding), also disallow every key positionjwherekey_padding_mask[b, j]isFalse. - Numerically stable softmax with empty-row protection: Subtract the maximum allowed logit per row before exponentiating so large activations never overflow
exp(). If a query position has no allowed keys at all (such as leading left-padding positions), output0.0across all channels at that position rather thanNaN. - Head merge & dtype preservation: Weight
vby the attention probabilities and merge heads0 .. n_heads - 1back into shape(batch, seq_len, d_model)inx.dtypewithout mixing features across different token positions.
Examples
Example 1
Input:
d_model = 4, n_heads = 1 (head_dim = 4)
w_qkv = [I_4, I_4, I_4] (shape (4, 12)), b_qkv = zeros(12)
x = np.array([[[2.0, 0.0, 2.0, 0.0],
[2.0, 2.0, 0.0, 0.0]]], dtype=np.float32)
Output:
array([[[2.0, 0.0, 2.0, 0.0],
[2.0, 1.761594, 0.238406, 0.0]]], dtype=float32)
Walk-through: With identity weights, q = k = v = x. Dividing q by sqrt(4) = 2 yields q_scaled = [[1, 0, 1, 0], [1, 1, 0, 0]].
- Query 0 has scaled logits [4.0, 2.0]; causal masking blocks j = 1 ([4.0, -inf]), giving weights [1.0, 0.0] and output v[0] = [2, 0, 2, 0].
- Query 1 sees both keys with scaled logits [2.0, 4.0], giving softmax weights [1 / (1 + e^2), e^2 / (1 + e^2)] ≈ [0.119203, 0.880797] and output 0.119203 * [2, 0, 2, 0] + 0.880797 * [2, 2, 0, 0] ≈ [2.0, 1.761594, 0.238406, 0.0].
Example 2
Input:
d_model = 4, n_heads = 2 (head_dim = 2)
w_qkv = [I_4, I_4, I_4] (shape (4, 12)), b_qkv = zeros(12)
x = np.array([[[9.0, 9.0, 9.0, 9.0],
[1.0, 0.0, 0.0, 2.0],
[1.0, 0.0, 2.0, 0.0]]], dtype=np.float32)
key_padding_mask = np.array([[False, True, True]])
Output:
array([[[0.0, 0.0, 0.0, 0.0 ],
[1.0, 0.0, 0.0, 2.0 ],
[1.0, 0.0, 1.888391, 0.111608]]], dtype=float32)
Walk-through: Token 0 is left-padding (False), while tokens 1 and 2 are real (True).
- Query 0 can causally see only j = 0, which is masked out as padding, so it has zero allowed keys and safely returns [0, 0, 0, 0].
- Query 1 ignores padded key 0 and attends 100% to key 1, returning [1, 0, 0, 2].
- Query 2 attends over keys {1, 2} with 1 / sqrt(2) scaling: Head 0 (channels 0..1) scores both keys equally and outputs [1, 0]; Head 1 (channels 2..3) scores [0, 2 * sqrt(2)], yielding weights [0.055804, 0.944196] and output [1.888391, 0.111608]. Concatenating both heads produces [1.0, 0.0, 1.888391, 0.111608].
Constraints
1 <= batch, seq_len <= 5121 <= n_heads <= d_model <= 512, andd_model % n_heads == 0.x.dtypeisnp.float16,np.float32, ornp.float64; the returned array must match(batch, seq_len, d_model)andx.dtypewith noNaNorinfentries whenever inputs are finite.key_padding_mask, if provided, is a booleannp.ndarrayof shape(batch, seq_len).
Step-by-step walkthrough
Map every tensor shape and triage the symptoms
In autoregressive sequence generation, a Transformer predicts one token at a time from left to right, meaning position
imay look at past and present positions0 .. ibut never at future positionsj > i. In multi-head self-attention, the model splits each token'sd_model-dimensional vector inton_headssmaller chunks of sizehead_dim = d_model // n_headsso different heads can focus on different relationships in parallel.Before touching unfamiliar code, write down the expected tensor shapes from input to output and compare them against what the buggy snippet actually produces:
Tensor Expected shape Buggy snippet shape Meaning of axes ------------- ---------------- -------------------- ----------------------------------------- x (B, T, C) (B, T, C) B = batch_size, T = seq_len, C = d_model q, k, v (B, H, T, d) (B, H, T, d) H = n_heads, d = head_dim = C // H scores (B, H, T, T) (B, H, T, T) row i = query token, col j = key token probs (B, H, T, T) (B, H, T, T) probabilities across allowed keys j <= i return value (B, T, C) (B, H, T, d) <-- ! must merge H heads of size d back into CNext, separate the two reported training symptoms so we verify every root cause instead of guessing:
- Loss fails to converge: Either gradients through attention are vanishing (missing score scaling), or representations are scrambled across positions (missing/broken head merge).
- NaNs appear after a few hundred steps: Something either overflows to
+inf(unscaled dot products growing during training until(+inf) - (+inf) = NaNinside softmax, the functionexp(s_j) / sum_k exp(s_k)that turns raw scores into probabilities summing to1) or produces(-inf) - (-inf) = NaNon a fully masked query row.
In a real repository, you confirm both hypotheses in minutes without editing model weights: attach a forward hook logging
scores.abs().max()and checkingtorch.isfinite(out).all(), turn ontorch.autograd.set_detect_anomaly(True)for one failing step to pinpoint the exact backward op that emitsNaN, and run a perturbation test verifying that changingx[:, t:]never altersout[:, :t].Flaw 1: Missing 1 / sqrt(head_dim) scaling saturates softmax and causes overflow
Look at how the buggy snippet computes attention scores:
scores = torch.matmul(q, k.transpose(-2, -1)) # BUG: missing / sqrt(head_dim)Why do we divide by
sqrt(head_dim)? Suppose each coordinate ofqandkhas mean0and variance1. Their dot product addsd = head_dimindependent product terms:q . k = q_0 * k_0 + q_1 * k_1 + ... + q_{d-1} * k_{d-1} Var(q . k) = d * 1 = d ===> standard deviation = sqrt(d)When
head_dim = 64, raw dot products have standard deviationsqrt(64) = 8instead of1. Look at what a gap of8versus1does to softmax probabilities and their gradient factorp * (1 - p)on two keys:Unscaled scores [0, 8] --> softmax = [0.00034, 0.99966] --> p*(1 - p) = 0.00034 (vanishing!) Scaled scores [0, 1] --> softmax = [0.26894, 0.73106] --> p*(1 - p) = 0.19661 (~580x larger!)Without
1 / sqrt(head_dim), softmax snaps almost100%of its weight onto whichever key happens to have the largest initial dot product, starvingqandkof gradients so the loss stalls. Worse, as optimizer steps pushqandknorms slightly above1, unscaled dot products growsqrt(head_dim)times larger and can overflow to+infafter a few hundred iterations — especially underfloat16mixed precision (whose max finite value is65,504). Once any allowed score hits+inf, softmax subtractsrow_max = +infand produces(+inf) - (+inf) = NaN!Always divide by
sqrt(head_dim)(notsqrt(d_model), since each head sumshead_dimproducts), and apply the scale toqbeforematmulso intermediate products stay small.Flaw 2: Unmerged heads break output shape and leak future tokens
Look at the last line of the buggy
forwardmethod:return torch.matmul(probs, v) # returns [batch, n_heads, seq_len, head_dim]!SelfAttentiontakes[batch_size, seq_len, d_model]and must return[batch_size, seq_len, d_model]so the Transformer block can add the residual connectionx + attn(x). Returning a 4D tensor[batch_size, n_heads, seq_len, head_dim]breaks the layer contract (and also skips the standard output projectionnn.Linear(d_model, d_model)that mixes information across heads).Even more dangerous is the classic bug engineers introduce when "fixing" that 4D return shape: calling
.view(batch_size, seq_len, d_model)directly without.transpose(1, 2)first! Trace what happens in memory forn_heads = 2,seq_len = 4,head_dim = 1, whereh0_t2means "head 0's output at token position 2":head_out shape (1, 2, 4, 1): head 0: [h0_t0, h0_t1, h0_t2, h0_t3] head 1: [h1_t0, h1_t1, h1_t2, h1_t3] WRONG: head_out.view(1, 4, 2) (flattens head-major memory directly into (seq_len=4, d_model=2)): pos 0 gets [h0_t0, h0_t1] <-- leaks future token 1 into position 0! pos 1 gets [h0_t2, h0_t3] <-- leaks future tokens 2 and 3 into position 1! pos 2 gets [h1_t0, h1_t1] pos 3 gets [h1_t2, h1_t3] RIGHT: head_out.transpose(1, 2).contiguous().view(1, 4, 2): pos 0 gets [h0_t0, h1_t0] <-- only token 0's head outputs pos 1 gets [h0_t1, h1_t1] <-- only token 1's head outputs pos 2 gets [h0_t2, h1_t2] pos 3 gets [h0_t3, h1_t3]Notice that the snippet's lower-triangular mask (
torch.tril) actually maskedj > iinscoresin the right direction — the silent causal leak happens if heads are reshaped back without swapping then_headsandseq_lenaxes first!Flaw 3: CPU-only mask creation and all-(-inf) rows turning into NaN
Two bugs lurk in the masking and softmax lines:
- Hardcoded CPU tensor:
torch.ones(t, t)creates afloat32tensor on the CPU on every forward pass. As soon asxlives on a GPU (cuda:0),scores.masked_fill(causal == 0, ...)crashes with a device mismatch error. Always build boolean masks directly onx.device. - All-
-infquery rows produceNaN: To computesoftmax(row)withoutexp()overflowing on large numbers, libraries use the max-shift trick: subtractM = max(row)from every element before callingexp(), sinceexp(s_j - M) / sum_k exp(s_k - M)algebraically cancelsexp(-M)and keeps every exponent<= 0. With a causal mask alone, rowialways keeps at leastj = 0 .. i(i + 1 >= 1entries). However, as soon as a batch includes left-padding (common in batched autoregressive generation so sequences end at the right edge) or a custom attention mask, padding positions at the start of a sequence have zero allowed keys! Every entry in that row is-inf, soM = -infand(-inf) - (-inf) = NaN!
Our
masked_softmaxhelper prevents both overflow and empty-rowNaNs cleanly:def masked_softmax(scores: np.ndarray, allowed: np.ndarray) -> np.ndarray: """Softmax over the last axis using only the allowed entries. A row with no allowed entry returns all zeros instead of NaN. """ masked = np.where(allowed, scores, -np.inf) row_max = masked.max(axis=-1, keepdims=True) # Replace -inf row_max with 0.0 BEFORE subtracting so we never compute (-inf) - (-inf) = NaN. safe_row_max = np.where(np.isfinite(row_max), row_max, 0.0) weights = np.exp(masked - safe_row_max) row_sum = weights.sum(axis=-1, keepdims=True) safe_denom = np.where(row_sum > 0.0, row_sum, 1.0) return weights / safe_denom- Hardcoded CPU tensor:
Why float('-inf') must be handled carefully alongside scaling
float('-inf')is mathematically ideal for masking becauseexp(-inf) == 0.0exactly, giving masked future tokens strictly zero attention weight rather than1e-5leakage. However, IEEE-754 infinity arithmetic creates three traps when scaling is missing or misplaced:- Unscaled overflow (
+inf) colliding with-inf: Without1 / sqrt(head_dim), scores grow ~8xlarger (forhead_dim = 64). Infloat16,64 * 32 * 32 = 65,536 > 65,504, overflowing to+inf(whereas scalingqby1/8first gives8,192, well insidefloat16range). If someone applies an additive maskattn_scores + causal_bias(wherecausal_biasis0or-inf), an overflowed+infat a masked future token computes(+inf) + (-inf) = NaN, poisoning the entire row! Even withmasked_fill, an overflowed+infat an allowed position makesrow_max = +infand(+inf) - (+inf) = NaN. - Multiplying
-infby0: If downstream code multiplies already-masked scores by a0/1float mask (scores * mask), IEEE-754 evaluates(-inf) * 0.0 = NaN. - Finite stand-ins (
-1e4or-1e9) break when scores are unscaled: Engineers sometimes replacefloat('-inf')with-1e4(since-1e9overflowsfloat16). If scores are unscaled, legitimate dot products can easily fall below-10,000(say[-20000, -15000]), making the-10000"masked" future token the largest number in the row so softmax puts~100%weight on the forbidden future token!
The clean rule: scale
qbefore the matmul, compute softmax infloat32, use booleanmasked_fillwith-inf, and guard rows that have zero allowed keys before softmax runs.- Unscaled overflow (
Corrected PyTorch SelfAttention forward pass
Here is the corrected PyTorch
SelfAttentionmodule (preserving__init__from the prompt; in a full Transformer architecture you would also addself.out_proj = torch.nn.Linear(d_model, d_model)after merging heads):import math import torch import torch.nn.functional as F class SelfAttention(torch.nn.Module): def __init__(self, d_model, n_heads): super().__init__() self.d_model = d_model self.n_heads = n_heads self.head_dim = d_model // n_heads self.qkv_proj = torch.nn.Linear(d_model, 3 * d_model) def forward(self, x, key_padding_mask=None): batch_size, seq_len, _ = x.shape q, k, v = self.qkv_proj(x).chunk(3, dim=-1) q = q.view(batch_size, seq_len, self.n_heads, self.head_dim).transpose(1, 2) k = k.view(batch_size, seq_len, self.n_heads, self.head_dim).transpose(1, 2) v = v.view(batch_size, seq_len, self.n_heads, self.head_dim).transpose(1, 2) # 1. Scale q before matmul and accumulate softmax in float32 for numerical stability. q = q * (1.0 / math.sqrt(self.head_dim)) attn_scores = torch.matmul(q, k.transpose(-2, -1)).float() # 2. Build causal mask directly on x.device and combine optional key_padding_mask. allowed = torch.ones(seq_len, seq_len, dtype=torch.bool, device=x.device).tril() if key_padding_mask is not None: allowed = allowed & key_padding_mask[:, None, None, :] # 3. Guard all-masked rows BEFORE softmax so neither forward nor backward sees NaN. attn_scores = attn_scores.masked_fill(~allowed, float("-inf")) has_any_key = allowed.any(dim=-1, keepdim=True) safe_scores = torch.where(has_any_key, attn_scores, 0.0) attn_weights = F.softmax(safe_scores, dim=-1) attn_weights = torch.where(has_any_key, attn_weights, 0.0) # 4. Weighted value sum, then transpose(1, 2) BEFORE view() to merge heads safely. out = torch.matmul(attn_weights.to(v.dtype), v) return out.transpose(1, 2).contiguous().view(batch_size, seq_len, self.d_model)Notice why
safe_scores = torch.where(has_any_key, attn_scores, 0.0)happens beforeF.softmax: if you letF.softmaxproduceNaNon an empty row and only overwriteattn_weightswith0.0afterwards, PyTorch's backward pass still multiplies0.0 * NaN = NaNinsideSoftmaxBackward!NumPy implementation and worked numeric trace
Because the test sandbox runs pure NumPy without PyTorch installed,
solution.pyimplements the exact same fixed forward pass inself_attention(x, w_qkv, b_qkv, n_heads, key_padding_mask).Let's verify every step on Example 1:
batch = 1,seq_len = 2,d_model = 4,n_heads = 1(head_dim = 4), identity weights soq = k = v = x, and two tokensx0 = [2, 0, 2, 0],x1 = [2, 2, 0, 0]:1. Scale q by 1 / sqrt(4) = 0.5: q0_scaled = [1, 0, 1, 0], q1_scaled = [1, 1, 0, 0] k0 = [2, 0, 2, 0], k1 = [2, 2, 0, 0] 2. Scaled dot-product scores (q_scaled @ k^T): row 0 (query 0): [q0_scaled . k0, q0_scaled . k1] = [4.0, 2.0] row 1 (query 1): [q1_scaled . k0, q1_scaled . k1] = [2.0, 4.0] 3. Apply lower-triangular causal mask (j <= i): row 0: [4.0, -inf] --> softmax = [1.000, 0.000] row 1: [2.0, 4.0] --> softmax = [1 / (1 + e^2), e^2 / (1 + e^2)] = [0.1192, 0.8808] 4. Multiply weights @ v: out[0] = 1.0000 * [2, 0, 2, 0] + 0.0000 * [2, 2, 0, 0] = [2.0000, 0.0000, 2.0000, 0.0] out[1] = 0.1192 * [2, 0, 2, 0] + 0.8808 * [2, 2, 0, 0] = [2.0000, 1.7616, 0.2384, 0.0]Complete solution
from typing import Optional import numpy as np def masked_softmax(scores: np.ndarray, allowed: np.ndarray) -> np.ndarray: """Softmax over the last axis using only the allowed entries. A row with no allowed entry returns all zeros instead of NaN. """ # Replace disallowed key positions with -inf so exp(-inf) evaluates to exact 0.0. masked = np.where(allowed, scores, -np.inf) # Subtract each row's maximum allowed score so exp() never overflows to +inf. row_max = masked.max(axis=-1, keepdims=True) # If an entire row is disallowed (all -inf), row_max is -inf and (-inf) - (-inf) = NaN. # Replace non-finite row_max with 0.0 so masked - row_max stays -inf and exp(-inf) = 0.0. safe_row_max = np.where(np.isfinite(row_max), row_max, 0.0) weights = np.exp(masked - safe_row_max) row_sum = weights.sum(axis=-1, keepdims=True) # Guard against 0.0 / 0.0 = NaN on fully masked rows by dividing by 1.0 when row_sum == 0. safe_denom = np.where(row_sum > 0.0, row_sum, 1.0) return weights / safe_denom def self_attention( x: np.ndarray, w_qkv: np.ndarray, b_qkv: np.ndarray, n_heads: int, key_padding_mask: Optional[np.ndarray] = None, ) -> np.ndarray: """Causal multi-head self-attention: the fixed forward pass of SelfAttention. x: (batch, seq_len, d_model). w_qkv: (d_model, 3 * d_model), b_qkv: (3 * d_model,): qkv = x @ w_qkv + b_qkv, split into q, k, v (in that order) along the last axis. key_padding_mask: optional (batch, seq_len) bool array, True for real tokens. Returns (batch, seq_len, d_model) in x's dtype. """ batch, seq_len, d_model = x.shape head_dim = d_model // n_heads # Promote float16 inputs to float32 during intermediate math so dot products do not # overflow float16's 65,504 ceiling before softmax runs. compute_dtype = np.promote_types(x.dtype, np.float32) # Phase 1: project input into packed Q, K, V and split along the feature axis. # qkv shape: (batch, seq_len, 3 * d_model) qkv = x.astype(compute_dtype) @ w_qkv.astype(compute_dtype) + b_qkv.astype(compute_dtype) q, k, v = np.split(qkv, 3, axis=-1) # Reshape each tensor to (batch, seq_len, n_heads, head_dim), then swap axes 1 and 2 # so each attention head has its own (seq_len, head_dim) matrix: (batch, n_heads, seq_len, head_dim). q = q.reshape(batch, seq_len, n_heads, head_dim).transpose(0, 2, 1, 3) k = k.reshape(batch, seq_len, n_heads, head_dim).transpose(0, 2, 1, 3) v = v.reshape(batch, seq_len, n_heads, head_dim).transpose(0, 2, 1, 3) # Phase 2: scaled dot-product scores. # Divide q by sqrt(head_dim) BEFORE multiplying by k^T: unscaled dot products have # variance ~head_dim, which saturates softmax gradients and overflows low-precision floats. scale = np.array(1.0 / np.sqrt(head_dim), dtype=compute_dtype) q_scaled = q * scale # scores shape: (batch, n_heads, seq_len, seq_len), where [b, h, i, j] scores query i -> key j. scores = q_scaled @ k.transpose(0, 1, 3, 2) # Phase 3: causal mask (and optional key padding mask) + numerically stable softmax. # Lower-triangular mask keeps j <= i so token i never reads future tokens j > i. allowed = np.tril(np.ones((seq_len, seq_len), dtype=bool)) if key_padding_mask is not None: # Broadcast (batch, seq_len) -> (batch, 1, 1, seq_len) to mask out padded key columns. allowed = allowed & key_padding_mask[:, None, None, :] weights = masked_softmax(scores, allowed) # Phase 4: weighted sum of values and head concatenation. # head_out shape: (batch, n_heads, seq_len, head_dim) head_out = weights @ v # Transpose back to (batch, seq_len, n_heads, head_dim) BEFORE reshaping to (batch, seq_len, d_model). # Reshaping without transposing first would mix future token positions into earlier rows! merged = head_out.transpose(0, 2, 1, 3).reshape(batch, seq_len, d_model) return merged.astype(x.dtype) if __name__ == "__main__": rng = np.random.default_rng(0) d_model, n_heads = 8, 2 x = rng.normal(size=(1, 4, d_model)).astype(np.float32) w = rng.normal(size=(d_model, 3 * d_model)).astype(np.float32) / np.sqrt(d_model) b = np.zeros(3 * d_model, dtype=np.float32) print(self_attention(x, w, b, n_heads).shape)✅ Submit now — all tests should pass.
Intuition & how it works
Picture multi-head self-attention (a layer where every token gathers context from earlier tokens through several parallel lookup heads) as H spotlight operators reading a script from left to right. At word i, each operator compares word i's question (q) against every word's label (k), turns a dimmer knob (1 / sqrt(head_dim)) so one booming score does not drown out every other word, puts a black curtain (causal mask, a rule blocking access to future positions j > i) over upcoming words, converts the allowed scores into percentages via softmax (a formula exp(s_j) / sum_k exp(s_k) that turns scores into positive weights summing to 1), and blends the earlier words' values (v). Finally, all H operators must staple their notes back together grouped by word, not grouped by operator.
The provided snippet breaks at three points. First, omitting 1 / sqrt(head_dim) leaves dot products with standard deviation sqrt(head_dim) (for example, 8 when head_dim = 64), pushing softmax close to [0, ..., 1, ..., 0] where gradients nearly vanish and growing activations eventually overflow to +inf and NaN. Second, forward returns [batch, n_heads, seq_len, head_dim] without merging heads back into [batch, seq_len, d_model] — and naively calling .view(batch, seq_len, d_model) without .transpose(1, 2) first scrambles future words' outputs into earlier word positions. Third, creating the mask on CPU breaks GPU runs, and any query row where all keys are masked out (such as left-padded tokens) fills the whole row with -inf, causing softmax's max-subtraction step to compute (-inf) - (-inf) = NaN.
Walk through Example 1 (seq_len = 2, d_model = 4, n_heads = 1, head_dim = 4) with identity QKV weights (q = k = v = x) on x0 = [2, 0, 2, 0] and x1 = [2, 2, 0, 0]:
- Pre-scale queries: Divide
qbysqrt(4) = 2, givingq0 = [1, 0, 1, 0]andq1 = [1, 1, 0, 0]. - Score and mask: Row 0 has scores
[q0 . k0, q0 . k1] = [4, 2]-> causal mask blocksj = 1->[4, -inf]. Row 1 has[q1 . k0, q1 . k1] = [2, 4]-> bothj = 0, 1allowed ->[2, 4]. - Stable softmax: Row 0 subtracts max
4->[exp(0), exp(-inf)] = [1, 0]. Row 1 subtracts max4->[exp(-2), exp(0)] / (exp(-2) + 1) = [0.1192, 0.8808](healthy, non-saturated weights!). - Blend and merge: Position 0 outputs
1.0 * v0 = [2, 0, 2, 0]; position 1 outputs0.1192 * v0 + 0.8808 * v1 = [2.0, 1.7616, 0.2384, 0].
Complexity
- Time: O(B * T * C^2 + B * T^2 * C), where B is
batch_size, T isseq_len, and C isd_model(H * head_dim). Projectingxof shape(B, T, C)byw_qkvof shape(C, 3C)does3 * B * T * C^2multiply-adds, while computingq_scaled @ k^Tandweights @ vacross allHheads does2 * B * H * T^2 * head_dim = 2 * B * T^2 * Cmultiply-adds (quadratic in sequence length T). - Space: O(B * T * C + B * H * T^2). Storing
q,k,v, and the merged output takes O(B * T * C) memory, while materializing the(B, H, T, T)scoresandweightstensors takes O(B * H * T^2) memory — the main bottleneck on long contexts.
Edge cases
- Single-token sequence (
seq_len = 1): Position0can attend only to itself with weight1.0, so the output equalsv_0(x[:, 0] @ W_v + b_v) with zeroNaNs. - Left-padded sequences (all-masked query rows): Queries before the first real token have
allowed == Falseacross every key; replacing non-finiterow_maxwith0.0and zero-sum denominators with1.0produces clean0.0outputs instead ofNaN. - Extreme input magnitudes (
x * 1000): Subtractingsafe_row_maxbeforenp.expkeeps the largest exponent at0.0, preventingexp(score)from overflowing to+infeven when scores are in the millions. - Half-precision (
float16) inputs: Entry values around+-70inhead_dim = 16produce raw dot products of16 * 70 * 70 = 78,400, exceedingfloat16's65,504ceiling; promoting tofloat32and scalingqbefore the matrix multiplication prevents overflow. - Incremental decoding with a KV cache: A KV cache stores keys and values from past tokens so generation passes only
1new query againstT_pastcached keys ((1, T_past)rather than square(T, T)), requiring causal masks indexed by absolute token positions rather thantorch.tril(ones(T, T)).
Common mistakes
- Scaling by
sqrt(d_model)instead ofsqrt(head_dim): Each head's dot product sumshead_dimcoordinates, notd_model, so dividing bysqrt(d_model)over-dampens scores bysqrt(n_heads)and makes attention overly uniform. - Flattening heads with
.view(B, T, C)without.transpose(1, 2): Reshaping(B, H, T, d)directly into(B, T, C)silently mixes future token positions into past positions without raising a shape error. - Calling
.view()right after.transpose(1, 2)in PyTorch:transposereturns a non-contiguous stride view, so.view(...)raisesRuntimeErrorunless preceded by.contiguous()(or replaced by.reshape(...)). - Patching
NaNs afterF.softmaxwithnan_to_numormasked_fill: In PyTorch autograd, overwritingNaNoutputs afterF.softmaxstill leavesNaNinsideSoftmaxBackward(0.0 * NaN = NaN), corrupting gradients during.backward(). - Replacing
-infwith-1e4on unscaled scores: If legitimate negative scores drop below-10,000,-1e4becomes the maximum entry in the row and shifts nearly100%of attention onto masked-out future tokens.
Follow-up questions
- How can you refactor the attention computation to leverage FlashAttention and cut memory usage? Replace the manual
matmul, causal mask,softmax, and valuematmullines withF.scaled_dot_product_attention(q, k, v, is_causal=True)(available in PyTorch 2.0+). FlashAttention is an exact IO-aware GPU kernel that tilesq,k, andvin fast on-chip SRAM using an online running-max softmax update, reducing attention memory from O(B * H * T^2) to O(B * H * T) because the fullT x Tscore matrix is never written to GPU HBM. Make sure inputs are infloat16orbfloat16on a supported GPU and avoid passing a dense custom floatattn_maskwhen pure causal masking suffices, sinceis_causal=Trueunlocks the fastest fused FlashAttention kernel (for variable-length padded batches, pack unpadded tokens and useflash_attn_varlen_func). - What unit tests would you write to guarantee that future tokens cannot leak into earlier positions? Check causality from three independent angles: (1) Weight matrix check: inspect
attn_weightsdirectly and assertattn_weights[..., i, j] == 0.0for allj > iwhile every non-empty row sums to1.0. (2) Future-perturbation invariance: runforward(x), overwrite future tokensx_mod[:, t:]with random noise for every cutofft, and assertout_mod[:, :t]matchesout[:, :t]up to floating-point tolerance whileout_mod[:, t]changes. (3) Backward gradient check: computeout[:, i].sum().backward()and assertx.grad[:, i+1:] == 0everywhere so no gradient leaks backward from future inputs into past losses, alongside edge-case tests forseq_len = 1, left-padded all-masked rows, andfloat16large-norm inputs. - How do float16, bfloat16, and float32 differ in their susceptibility to overflow and NaN errors here?
float16uses only5exponent bits (maximum finite value65,504) and10fraction bits, so unscaledq @ k^Tscores easily overflow65,504to+infonce entry magnitudes reach ~32athead_dim = 64, immediately triggering(+inf) - (+inf) = NaNin softmax.bfloat16(bf16, brain floating point) uses8exponent bits — the exact same dynamic range asfloat32, up to~3.4 * 10^38— so overflowNaNs almost never happen, though its7fraction bits give coarse rounding (at score100adjacentbf16values are0.5apart, distortingexp(score)by up toe^0.25 = 28%unless softmax runs infloat32).float32has both wide range (~3.4 * 10^38) and fine precision (23fraction bits), which is why production mixed-precision training runsqkv_projandmatmulinbf16/float16(after pre-scalingq) while casting attention logits tofloat32for softmax.
Follow-up questions
- How can you refactor the attention computation to leverage FlashAttention and cut memory usage?
- What unit tests would you write to guarantee that future tokens cannot leak into earlier positions?
- How do float16, bfloat16, and float32 differ in their susceptibility to overflow and NaN errors here?
Similar questions
- Iterative Active Learning for Synthetic DNA Design
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager