CD0002 Debug Causal Attention Mask

Mode A · Bug Hunt 30 Min PyTorch 2.x · FP16 4 Masking Bugs

OpenAI’s serving stack runs batched causal attention over left-padded, variable-length prompts, where a mask that is off by one diagonal quietly leaks future tokens. In an LLM engineering interview there, you are handed an AI-generated PyTorch module for batched causal self-attention. It must support variable-length sequences with left-padding and run under FP16 autocast. Its unit test passes on a single unpadded sequence in FP32, and in that setting the code never throws.

Code Under Review (Spot the 4 Silent Bugs):

01  import math
02  import torch
03  import torch.nn as nn
04  import torch.nn.functional as F
05
06  NEG_INF = -1e9
07
08  class CausalSelfAttention(nn.Module):
09      def __init__(self, d_model, n_head, p_drop=0.1):
10          super().__init__()
11          assert d_model % n_head == 0
12          self.h, self.d = n_head, d_model // n_head
13          self.qkv = nn.Linear(d_model, 3 * d_model)
14          self.proj = nn.Linear(d_model, d_model)
15          self.p_drop = p_drop
16
17      def forward(self, x, attn_mask):
18          # x: (B, T, C); attn_mask: (B, T) with 1 = real token, 0 = left pad
19          B, T, C = x.shape
20          q, k, v = self.qkv(x).split(C, dim=-1)
21          q, k, v = (t.view(B, T, self.h, self.d).transpose(1, 2) for t in (q, k, v))
22          scores = q @ k.transpose(-2, -1) / math.sqrt(self.d)  # (B, H, T, T)
23          causal = torch.triu(torch.ones(T, T, device=x.device), diagonal=0)
24          scores = scores.masked_fill(causal == 0, NEG_INF)
25          pad = torch.zeros(B, T, device=x.device, dtype=scores.dtype)
26          pad = pad.masked_fill(attn_mask == 0, float("-inf"))
27          scores = scores + pad.view(B, 1, T, 1)
28          scores = F.dropout(scores, p=self.p_drop, training=self.training)
29          attn = F.softmax(scores, dim=-1)
30          out = attn @ v  # (B, H, T, D)
31          out = out.transpose(1, 2).contiguous().view(B, T, C)
32          return self.proj(out)

Once the module is deployed in a batched evaluation harness, it fails in three ways. (1) On unpadded sequences, teacher-forced perplexity on held-out text collapses toward 1 (loss near zero), yet free-running generation produces gibberish. (2) Whenever a batch contains left-padded sequences, the attention output fills with NaN at the padded positions and contaminates every later layer. (3) Under FP16 autocast, the forward pass crashes with a RuntimeError: value cannot be converted to type at::Half without overflow.

Inspect the numbered attention module and pinpoint the 4 silent masking and broadcasting bugs. Explain how each one corrupts the attention weight matrix or the softmax denominator. Then write the corrected implementation and a unit test that verifies causal invariance and padding safety.

A unit test box marked PASS and an eval harness box with left-padded FP16 batches both feed an AI-generated causal self-attention module marked with a question mark, which fans out to three symptom boxes: perplexity near 1 with gibberish generation, NaN at padded positions, and an FP16 overflow RuntimeError

Figure 1: the same attention module passes a single-sequence FP32 test but fails three different ways once it meets left-padded batches and FP16 autocast.

Interactive PyTorch Workspace: Switch to the split-screen workspace to fix all 4 masking bugs in the live editor and run causal, left-padding, and FP16 checks.

Open in Colab ↗
Progressive Hints (Free · Zero Spoilers)
1Inspection Checklist (Where to Look)

(1) Causal Direction: Confirm which triangle blocks keys with j > i while preserving the diagonal.
(2) Broadcast Axes: Decide whether a (B, T) padding mask should block query rows or key columns of (B, H, T, T).
(3) Dtype-Aware Fill: Every constant written into scores must fit IEEE-754 FP16 as well as FP32/BF16.
(4) Post-Mask Ops: Check every operation between masking and attn @ v to ensure masked entries stay zero.

2Visual Review Map (Figure 2)
Snake-shaped data flow of the attention module: input, QKV projection, scores of shape B H T T, causal mask, padding mask, then dropout, softmax, attention times V, merge heads and projection, and output; the four mask-sensitive stages carry question-mark markers

Figure 2: The score tensor passes through four mask-sensitive stages between the matmul and the softmax; the stages marked “?” are where a reviewer digs next.

3Interviewer Nudge & Line Focus

Trace a 4 x 4 score matrix with 2 left-pad tokens and answer each check below:

Causal Triangle & Range: Write out torch.triu(ones(4, 4), diagonal=0): which triangle is zeroed when masking causal == 0? Also check whether every fill constant fits IEEE-754 float16 (max 65,504).
Padding Broadcast Axis: In scores of shape (B, H, T_q, T_k), does pad.view(B, 1, T, 1) mask padded key columns or entire padded query rows? What does softmax([-inf, -inf, -inf, -inf]) evaluate to?
Fill Constant vs Dtype Range: NEG_INF = -1e9 (line 6) is consumed by masked_fill inside autocast at line 24. What happens when the fill must cast into a float16 tensor whose max finite is 65,504? Would torch.finfo(scores.dtype).min fit every dtype, and what does a fully masked row softmax to under it?
Dropout vs Softmax Order: If F.dropout randomly zeroes a large negative masked logit before F.softmax, what probability weight does exp(0.0) assign to that forbidden token?
Answer
Login to view more content

Log in to track your progress

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *