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:

  1. Packed QKV projection & head split: Compute qkv = x @ w_qkv + b_qkv, where x has shape (batch, seq_len, d_model), w_qkv has shape (d_model, 3 * d_model), and b_qkv has shape (3 * d_model,). Split qkv into three equal slices q, k, v (in that order) along the last axis. Partition each into n_heads heads of width head_dim = d_model // n_heads, where head h takes channels h * head_dim through (h + 1) * head_dim - 1.
  2. Scaled dot-product logits: Scale each head's query-key dot products by 1 / sqrt(head_dim) before taking exponentials. Promote float16 inputs to at least float32 for intermediate arithmetic so raw inner products never overflow float16's 65,504 ceiling.
  3. Causal & key-padding masks: Query token i may attend only to key positions j <= i. When key_padding_mask is supplied (a (batch, seq_len) boolean array with True for real tokens and False for padding), also disallow every key position j where key_padding_mask[b, j] is False.
  4. 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), output 0.0 across all channels at that position rather than NaN.
  5. Head merge & dtype preservation: Weight v by the attention probabilities and merge heads 0 .. n_heads - 1 back into shape (batch, seq_len, d_model) in x.dtype without 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 <= 512
  • 1 <= n_heads <= d_model <= 512, and d_model % n_heads == 0.
  • x.dtype is np.float16, np.float32, or np.float64; the returned array must match (batch, seq_len, d_model) and x.dtype with no NaN or inf entries whenever inputs are finite.
  • key_padding_mask, if provided, is a boolean np.ndarray of shape (batch, seq_len).

Step-by-step walkthrough

  1. 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 i may look at past and present positions 0 .. i but never at future positions j > i. In multi-head self-attention, the model splits each token's d_model-dimensional vector into n_heads smaller chunks of size head_dim = d_model // n_heads so 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 C
    

    Next, separate the two reported training symptoms so we verify every root cause instead of guessing:

    1. Loss fails to converge: Either gradients through attention are vanishing (missing score scaling), or representations are scrambled across positions (missing/broken head merge).
    2. NaNs appear after a few hundred steps: Something either overflows to +inf (unscaled dot products growing during training until (+inf) - (+inf) = NaN inside softmax, the function exp(s_j) / sum_k exp(s_k) that turns raw scores into probabilities summing to 1) or produces (-inf) - (-inf) = NaN on 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 checking torch.isfinite(out).all(), turn on torch.autograd.set_detect_anomaly(True) for one failing step to pinpoint the exact backward op that emits NaN, and run a perturbation test verifying that changing x[:, t:] never alters out[:, :t].

  2. 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 of q and k has mean 0 and variance 1. Their dot product adds d = head_dim independent 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 deviation sqrt(64) = 8 instead of 1. Look at what a gap of 8 versus 1 does to softmax probabilities and their gradient factor p * (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 almost 100% of its weight onto whichever key happens to have the largest initial dot product, starving q and k of gradients so the loss stalls. Worse, as optimizer steps push q and k norms slightly above 1, unscaled dot products grow sqrt(head_dim) times larger and can overflow to +inf after a few hundred iterations — especially under float16 mixed precision (whose max finite value is 65,504). Once any allowed score hits +inf, softmax subtracts row_max = +inf and produces (+inf) - (+inf) = NaN!

    Always divide by sqrt(head_dim) (not sqrt(d_model), since each head sums head_dim products), and apply the scale to q before matmul so intermediate products stay small.

  3. Flaw 2: Unmerged heads break output shape and leak future tokens

    Look at the last line of the buggy forward method:

    return torch.matmul(probs, v)    # returns [batch, n_heads, seq_len, head_dim]!
    

    SelfAttention takes [batch_size, seq_len, d_model] and must return [batch_size, seq_len, d_model] so the Transformer block can add the residual connection x + attn(x). Returning a 4D tensor [batch_size, n_heads, seq_len, head_dim] breaks the layer contract (and also skips the standard output projection nn.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 for n_heads = 2, seq_len = 4, head_dim = 1, where h0_t2 means "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 masked j > i in scores in the right direction — the silent causal leak happens if heads are reshaped back without swapping the n_heads and seq_len axes first!

  4. Flaw 3: CPU-only mask creation and all-(-inf) rows turning into NaN

    Two bugs lurk in the masking and softmax lines:

    1. Hardcoded CPU tensor: torch.ones(t, t) creates a float32 tensor on the CPU on every forward pass. As soon as x lives on a GPU (cuda:0), scores.masked_fill(causal == 0, ...) crashes with a device mismatch error. Always build boolean masks directly on x.device.
    2. All--inf query rows produce NaN: To compute softmax(row) without exp() overflowing on large numbers, libraries use the max-shift trick: subtract M = max(row) from every element before calling exp(), since exp(s_j - M) / sum_k exp(s_k - M) algebraically cancels exp(-M) and keeps every exponent <= 0. With a causal mask alone, row i always keeps at least j = 0 .. i (i + 1 >= 1 entries). 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, so M = -inf and (-inf) - (-inf) = NaN!

    Our masked_softmax helper prevents both overflow and empty-row NaNs 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
    
  5. Why float('-inf') must be handled carefully alongside scaling

    float('-inf') is mathematically ideal for masking because exp(-inf) == 0.0 exactly, giving masked future tokens strictly zero attention weight rather than 1e-5 leakage. However, IEEE-754 infinity arithmetic creates three traps when scaling is missing or misplaced:

    1. Unscaled overflow (+inf) colliding with -inf: Without 1 / sqrt(head_dim), scores grow ~8x larger (for head_dim = 64). In float16, 64 * 32 * 32 = 65,536 > 65,504, overflowing to +inf (whereas scaling q by 1/8 first gives 8,192, well inside float16 range). If someone applies an additive mask attn_scores + causal_bias (where causal_bias is 0 or -inf), an overflowed +inf at a masked future token computes (+inf) + (-inf) = NaN, poisoning the entire row! Even with masked_fill, an overflowed +inf at an allowed position makes row_max = +inf and (+inf) - (+inf) = NaN.
    2. Multiplying -inf by 0: If downstream code multiplies already-masked scores by a 0/1 float mask (scores * mask), IEEE-754 evaluates (-inf) * 0.0 = NaN.
    3. Finite stand-ins (-1e4 or -1e9) break when scores are unscaled: Engineers sometimes replace float('-inf') with -1e4 (since -1e9 overflows float16). 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 q before the matmul, compute softmax in float32, use boolean masked_fill with -inf, and guard rows that have zero allowed keys before softmax runs.

  6. Corrected PyTorch SelfAttention forward pass

    Here is the corrected PyTorch SelfAttention module (preserving __init__ from the prompt; in a full Transformer architecture you would also add self.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 before F.softmax: if you let F.softmax produce NaN on an empty row and only overwrite attn_weights with 0.0 afterwards, PyTorch's backward pass still multiplies 0.0 * NaN = NaN inside SoftmaxBackward!

  7. NumPy implementation and worked numeric trace

    Because the test sandbox runs pure NumPy without PyTorch installed, solution.py implements the exact same fixed forward pass in self_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 so q = k = v = x, and two tokens x0 = [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]
    
  8. 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]:

  1. Pre-scale queries: Divide q by sqrt(4) = 2, giving q0 = [1, 0, 1, 0] and q1 = [1, 1, 0, 0].
  2. Score and mask: Row 0 has scores [q0 . k0, q0 . k1] = [4, 2] -> causal mask blocks j = 1 -> [4, -inf]. Row 1 has [q1 . k0, q1 . k1] = [2, 4] -> both j = 0, 1 allowed -> [2, 4].
  3. Stable softmax: Row 0 subtracts max 4 -> [exp(0), exp(-inf)] = [1, 0]. Row 1 subtracts max 4 -> [exp(-2), exp(0)] / (exp(-2) + 1) = [0.1192, 0.8808] (healthy, non-saturated weights!).
  4. Blend and merge: Position 0 outputs 1.0 * v0 = [2, 0, 2, 0]; position 1 outputs 0.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 is seq_len, and C is d_model (H * head_dim). Projecting x of shape (B, T, C) by w_qkv of shape (C, 3C) does 3 * B * T * C^2 multiply-adds, while computing q_scaled @ k^T and weights @ v across all H heads does 2 * B * H * T^2 * head_dim = 2 * B * T^2 * C multiply-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) scores and weights tensors takes O(B * H * T^2) memory — the main bottleneck on long contexts.

Edge cases

  • Single-token sequence (seq_len = 1): Position 0 can attend only to itself with weight 1.0, so the output equals v_0 (x[:, 0] @ W_v + b_v) with zero NaNs.
  • Left-padded sequences (all-masked query rows): Queries before the first real token have allowed == False across every key; replacing non-finite row_max with 0.0 and zero-sum denominators with 1.0 produces clean 0.0 outputs instead of NaN.
  • Extreme input magnitudes (x * 1000): Subtracting safe_row_max before np.exp keeps the largest exponent at 0.0, preventing exp(score) from overflowing to +inf even when scores are in the millions.
  • Half-precision (float16) inputs: Entry values around +-70 in head_dim = 16 produce raw dot products of 16 * 70 * 70 = 78,400, exceeding float16's 65,504 ceiling; promoting to float32 and scaling q before 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 1 new query against T_past cached keys ((1, T_past) rather than square (T, T)), requiring causal masks indexed by absolute token positions rather than torch.tril(ones(T, T)).

Common mistakes

  • Scaling by sqrt(d_model) instead of sqrt(head_dim): Each head's dot product sums head_dim coordinates, not d_model, so dividing by sqrt(d_model) over-dampens scores by sqrt(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: transpose returns a non-contiguous stride view, so .view(...) raises RuntimeError unless preceded by .contiguous() (or replaced by .reshape(...)).
  • Patching NaNs after F.softmax with nan_to_num or masked_fill: In PyTorch autograd, overwriting NaN outputs after F.softmax still leaves NaN inside SoftmaxBackward (0.0 * NaN = NaN), corrupting gradients during .backward().
  • Replacing -inf with -1e4 on unscaled scores: If legitimate negative scores drop below -10,000, -1e4 becomes the maximum entry in the row and shifts nearly 100% 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 value matmul lines with F.scaled_dot_product_attention(q, k, v, is_causal=True) (available in PyTorch 2.0+). FlashAttention is an exact IO-aware GPU kernel that tiles q, k, and v in 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 full T x T score matrix is never written to GPU HBM. Make sure inputs are in float16 or bfloat16 on a supported GPU and avoid passing a dense custom float attn_mask when pure causal masking suffices, since is_causal=True unlocks the fastest fused FlashAttention kernel (for variable-length padded batches, pack unpadded tokens and use flash_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_weights directly and assert attn_weights[..., i, j] == 0.0 for all j > i while every non-empty row sums to 1.0. (2) Future-perturbation invariance: run forward(x), overwrite future tokens x_mod[:, t:] with random noise for every cutoff t, and assert out_mod[:, :t] matches out[:, :t] up to floating-point tolerance while out_mod[:, t] changes. (3) Backward gradient check: compute out[:, i].sum().backward() and assert x.grad[:, i+1:] == 0 everywhere so no gradient leaks backward from future inputs into past losses, alongside edge-case tests for seq_len = 1, left-padded all-masked rows, and float16 large-norm inputs.
  • How do float16, bfloat16, and float32 differ in their susceptibility to overflow and NaN errors here? float16 uses only 5 exponent bits (maximum finite value 65,504) and 10 fraction bits, so unscaled q @ k^T scores easily overflow 65,504 to +inf once entry magnitudes reach ~32 at head_dim = 64, immediately triggering (+inf) - (+inf) = NaN in softmax. bfloat16 (bf16, brain floating point) uses 8 exponent bits — the exact same dynamic range as float32, up to ~3.4 * 10^38 — so overflow NaNs almost never happen, though its 7 fraction bits give coarse rounding (at score 100 adjacent bf16 values are 0.5 apart, distorting exp(score) by up to e^0.25 = 28% unless softmax runs in float32). float32 has both wide range (~3.4 * 10^38) and fine precision (23 fraction bits), which is why production mixed-precision training runs qkv_proj and matmul in bf16/float16 (after pre-scaling q) while casting attention logits to float32 for softmax.

Follow-up questions

Similar questions

More Lila interview questions

All 2 Lila questions →