Lesson 4: Masking, built, tested and broken on purpose
Module 2 · Lesson 4 · About 50 minutes · Needs: Module 2, Lessons 1 and 2 (naive_attention, itsmaskargument, the copy task)
The situation
Sol 405 at Aurora Station. naive_attention has had a mask argument since Lesson 1, but the lab has only ever passed the causal triangle. Kofi Mensah sets a rule: "A name's outputs must not depend on its neighbours in a batch, or on what comes after it. Test each mask, and show me what leaks when one is wrong."
The running example is two crew names in the shared character tokeniser: Maya (ids 32, 45, 68, 45) and Tariq (39, 45, 61, 53, 60). You will batch, pad and pack them, and measure every leak.
A real case, first
On 1 August 2022 LaurenceA opened issue #18388 on Hugging Face transformers, "Mismatch between logits from generate and forward with an attention mask for most GPT models" (github.com/huggingface/transformers/issues/18388). Two prompts, one padded on the right, went through generate and then forward. Every log-probability matched except the padded prompt's first generated token: -2.6509 against -2.7818.
It happened with distilgpt2, gpt2, gpt-neo-125M and gpt-neo-1.3B, not gpt-j-6B. The maintainer, gante, answered that "with decoder-only models, such as the ones you mentioned, padding should be done on the left", because the library's position-id code "has left-sided padding in mind", and added: "Not being aware that left-sided padding should be used for these models is a common issue." A warning for right padding followed, and the issue closed on 28 September 2022.
The point for this lesson: a mask never works alone. It must agree with the positions, the padding side and the loss. Section 2 reproduces this mismatch in the lab.
What you will be able to do
- Build causal, padding, prefix, document and sliding-window masks in one convention.
- Prove a padded batch gives each name the same outputs as running it alone.
- Check causality by editing one token and measuring what moves.
- Measure what a bidirectional model leaks when it generates.
- Pack documents into one row without cross-talk.
1. The attention mask gallery (Essential)
Every mask in this course is one boolean grid with one meaning, so one line of naive_attention handles them all. Get the meaning backwards and nothing crashes; the model just reads what it should not. Paste the torch setup cell, shared block 1 and Lesson 2's naive_attention.
import torch
DEVICE = "cuda" if torch.cuda.is_available() else "cpu" # every lesson runs on "cpu"; a GPU is optional
torch.manual_seed(11) # the course seed (see course-guide/06)
print("torch", torch.__version__, "| device", DEVICE, "| CPU threads", torch.get_num_threads())Code walkthrough
- The course's torch setup cell. It printed
torch 2.14.1 | device cpu | CPU threads 5on the author's Mac.
import random
import torch
COURSE_DATE = "2026-10-09" # versions, model names and prices checked on this day
SEED = 11 # every generator in the course starts from this seed
SNAPSHOT_SOL = 400 # the corpus is the station record up to sol 399
def set_seed(seed=SEED):
"""Seed Python and PyTorch so a cell gives the same numbers every run."""
random.seed(seed)
torch.manual_seed(seed)
set_seed()
print("torch", torch.__version__, "| threads", torch.get_num_threads())Code walkthrough
- Shared block 1, as written:
SEED = 11andset_seed().
import math
import torch.nn.functional as F
def naive_attention(q, k, v, mask=None, return_weights=False, scale=None):
"""Lesson 2's version. mask: boolean, True where a query may read a key."""
scores = q @ k.transpose(-2, -1)
scores = scores * (1 / math.sqrt(q.shape[-1]) if scale is None else scale)
if mask is not None:
scores = scores.masked_fill(~mask, float("-inf"))
weights = scores.softmax(dim=-1)
out = weights @ v
return (out, weights) if return_weights else outCode walkthrough
- Unchanged from Lesson 2. Today's line is
masked_fill(~mask, float("-inf")): aFalsecell scores minus infinity, which the softmax turns into exactly 0.
An attention mask is a grid of yes and no, one row per query, one column per key. Yes means "this query may read this key". It is broadcast against the scores: one (T, T) grid serves a whole batch; a (B, 1, T) grid gives each sequence its own rule.
Pack Maya and Tariq into one 11-token row, each after a <doc> token (id 1). Four masks give it four meanings: causal reads the past; prefix lets the first five tokens read each other; document never crosses names; a sliding window reads the last three.
PAD, DOC = 0, 1 # shared block 7: <pad> is id 0, <doc> is id 1
def causal_mask(T):
return torch.ones(T, T, dtype=torch.bool).tril() # query i reads keys 0..i
def padding_mask(ids):
return (ids != PAD)[:, None, :] # (B, 1, T): nobody reads a pad key
def prefix_mask(T, prefix):
m = causal_mask(T)
m[:prefix, :prefix] = True # the prefix reads itself both ways
return m
def document_mask(ids):
doc = (ids == DOC).cumsum(-1) # which document each token belongs to
return (doc[:, :, None] == doc[:, None, :]) & causal_mask(ids.shape[1])
def sliding_window_mask(T, window):
return causal_mask(T) & torch.ones(T, T, dtype=torch.bool).triu(-(window - 1))
def show(m):
for row in m.int().tolist():
print(" ".join("1" if c else "." for c in row))
packed = torch.tensor([[DOC, 32, 45, 68, 45, DOC, 39, 45, 61, 53, 60]]) # <doc>Maya<doc>Tariq
gallery = {"causal": causal_mask(11), "prefix 5": prefix_mask(11, 5),
"document": document_mask(packed)[0], "window 3": sliding_window_mask(11, 3)}
for name, m in gallery.items():
print(f"{name:9} {int(m.sum()):3d} of {m.numel()} cells open")
show(gallery["document"])Code walkthrough
tril()keeps the lower triangle and diagonal: the causal mask.prefix_maskthen opens the top-left square.padding_maskmarks real tokens and adds a middle axis, so one column rule covers every query in that sequence.document_masklabels each position with its document by counting<doc>tokens (cumsum), keeps same-document pairs, and stays causal.sliding_window_maskcuts the triangle to a band; Lesson 5 measures what it saves.
Open cells out of 121 (measured here): prefix 76, causal 66, document 36, window 30. The 30 cells the document mask closes are where Tariq would read Maya. The next trap is what True means: PyTorch is not consistent.
set_seed()
q, k, v = (torch.randn(1, 6, 8) for _ in range(3))
keep = torch.tensor([True, True, True, True, False, False]) # the last two keys are padding
mine = naive_attention(q, k, v, keep)
additive = torch.zeros(6).masked_fill(~keep, float("-inf")) # the same mask as numbers to add
print("SDPA, boolean mask :", (mine - F.scaled_dot_product_attention(q, k, v, attn_mask=keep)).abs().max().item())
print("SDPA, additive mask:", (mine - F.scaled_dot_product_attention(q, k, v, attn_mask=additive)).abs().max().item())
mha = torch.nn.MultiheadAttention(8, 1, bias=False, batch_first=True)
with torch.no_grad(): # identity weights: plain attention
mha.in_proj_weight.copy_(torch.cat([torch.eye(8)] * 3)); mha.out_proj.weight.copy_(torch.eye(8))
for name, kpm in [("~keep", ~keep[None]), ("keep ", keep[None])]:
out, _ = mha(q, k, v, key_padding_mask=kpm)
print(f"MultiheadAttention, key_padding_mask={name}:", round((mine - out).abs().max().item(), 4))Code walkthrough
keepmarks four real keys and two pads.additiveis the same rule as numbers added to the scores: 0 keeps, minus infinity blocks.F.scaled_dot_product_attentiontakes either.nn.MultiheadAttentionwith identity weights is plain attention, so it should matchmine. Itskey_padding_maskgetskeepinverted, then as it is.
Both SDPA forms match to 3.6e-07; MultiheadAttention matches (0.0) only inverted, and is off by 3.40 otherwise (measured here). The PyTorch 2.14 documentation (checked October 2026) says why: in scaled_dot_product_attention, True "should take part in attention"; in key_padding_mask, True "will be ignored". The lab keeps one convention and converts at the edge.
2. Padding masks and variable-length batches (Essential)
A batch is a rectangle and names are not. Pad Maya to Tariq's length and, without a mask, her outputs depend on whatever fills the pad slot. The test: a name in a batch must give the same outputs as the name alone.
MaskLab is Lesson 2's two-block model with one change: forward takes the mask, and optionally the positions, from the caller.
import torch.nn as nn
class MaskBlock(nn.Module):
def __init__(self, d):
super().__init__()
self.norm1, self.norm2 = nn.LayerNorm(d), nn.LayerNorm(d)
self.qkv, self.out = nn.Linear(d, 3 * d, bias=False), nn.Linear(d, d, bias=False)
self.ff = nn.Sequential(nn.Linear(d, 4 * d), nn.GELU(), nn.Linear(4 * d, d))
def forward(self, x, mask):
q, k, v = self.qkv(self.norm1(x)).chunk(3, dim=-1)
x = x + self.out(naive_attention(q, k, v, mask))
return x + self.ff(self.norm2(x))
class MaskLab(nn.Module):
"""Two one-head blocks with learned positions; the caller passes the mask and, if needed, positions."""
def __init__(self, vocab=69, d=64, layers=2, context=32):
super().__init__()
self.embed, self.pos = nn.Embedding(vocab, d), nn.Embedding(context, d)
self.blocks = nn.ModuleList(MaskBlock(d) for _ in range(layers))
self.head = nn.Sequential(nn.LayerNorm(d), nn.Linear(d, vocab))
def forward(self, ids, mask, pos=None):
pos = torch.arange(ids.shape[1]) if pos is None else pos
x = self.embed(ids) + self.pos(pos)
for block in self.blocks:
x = block(x, mask)
return self.head(x)Code walkthrough
MaskBlockis a pre-norm, one-head block that attends with the mask it is given. Module 3 builds the real block.MaskLabadds a token table, a learned position table (one trained vector per position, 0 to 31), two blocks and 69 output logits, one per token.pos=Nonemeans positions 0, 1, 2 ...; passingpossays where each token really sits.
Right-pad Maya with one <pad>. A padding mask closes the pad's column, so no query reads it. Then tamper with the pad slot and see whether Maya's real outputs move.
set_seed()
lab = MaskLab().eval() # random weights are enough to test wiring
batch = torch.tensor([[32, 45, 68, 45, PAD], # Maya, right-padded
[39, 45, 61, 53, 60]]) # Tariq
alone = torch.tensor([[32, 45, 68, 45]])
tampered = batch.clone(); tampered[0, 4] = 61 # junk in Maya's pad slot
with torch.no_grad():
for name, m in [("no mask ", None), ("padding mask", padding_mask(batch))]:
real = lab(batch, m)[0, :4] # Maya's four real positions
moved = (real - lab(tampered, m)[0, :4]).abs().max().item()
vs_alone = (real - lab(alone, None)[0]).abs().max().item()
print(f"{name} pad slot changed: {moved:.4f} | batch vs alone: {vs_alone:.2e}")Code walkthrough
labis untrained: a correct mask gives equal outputs whatever the weights, so wiring tests need no training.tamperedputsq(id 61) in the pad slot. For each setting, the loop measures how far Maya's four real outputs move, and how far they are from Maya alone.
Without the mask the pad moved Maya by 0.1311, and batch differed from alone by 0.187. With it: 0.0000, and 4.8e-07, float32 rounding (measured here).
Now the opener's bug. A decoder pads on the left so every prompt ends in the last column, where the next token goes. But then Maya sits at positions 1 to 4, not 0 to 3.
left = torch.tensor([[PAD, 32, 45, 68, 45], # Maya, left-padded
[39, 45, 61, 53, 60]])
real = left != PAD
mask = (padding_mask(left) & causal_mask(5)) | torch.eye(5, dtype=torch.bool) # a pad may read itself
pos = (real.cumsum(-1) - 1).clamp_min(0) # count real tokens: Maya gets 0, 1, 2, 3
with torch.no_grad():
want = lab(alone, causal_mask(4))[0] # Maya alone, causal
naive_pos = (lab(left, mask)[0, 1:] - want).abs().max().item()
fixed_pos = (lab(left, mask, pos)[0, 1:] - want).abs().max().item()
print("positions", pos.tolist())
print(f"left pad, positions 0..4: {naive_pos:.3f} | positions from the mask: {fixed_pos:.1e}")Code walkthrough
- The mask joins three rules: no pad keys, no future keys, and each token may read itself (
torch.eye). The break-it below shows why the last one matters. real.cumsum(-1) - 1counts real tokens, so Maya gets positions 0 to 3 (the pad is clamped to 0): the idea behind the position-id code gante pointed to.
Raw positions: 1.772 from Maya alone. Positions from the mask: 6.0e-07 (measured here). That is issue #18388 in miniature: the mask was right, the positions were not, and only the padded prompt suffered. Pads must also stay out of the loss; Module 6 builds that mask.
Break it: a row with nothing to read
Drop the | torch.eye(...) term, and the left pad's query may read no key at all.
bad = padding_mask(left) & causal_mask(5) # no self-read for the pad
with torch.no_grad():
out = lab(left, bad, pos)
print("row 0 of the mask:", bad[0, 0].tolist())
print("NaN positions per name:", torch.isnan(out).any(-1).sum(-1).tolist())
print("SDPA on the same scores:", F.scaled_dot_product_attention(q[:, :1], k[:, :1], v[:, :1],
attn_mask=torch.tensor([[False]])).abs().max().item())Code walkthrough
badlacks the self-read, so the pad's row is allFalse.torch.isnan(...)counts, per name, positions with any NaN logit.- The last line gives PyTorch's built-in a fully blocked row.
A softmax over a row of minus infinities is 0 divided by 0: NaN. In layer 2 that NaN is a value, and 0 times NaN is NaN, so all five of Maya's positions failed while Tariq stayed clean. PyTorch's built-in returned 0 for that row (both measured here, torch 2.14.1), so a model can pass fused and fail by hand. Every row needs one open cell.
3. Causal masking and checking it (Essential)
A language model predicts token t+1 from tokens up to t. If position t can read t+1, training loss looks wonderful and generation fails, because t+1 does not exist yet. Module 1's incident file (PyTorch issue #96941) showed a flag named is_causal masking nothing, so the lab checks behaviour, not flags.
The check is an influence map: change input j, rerun, record how far output i moved. For a causal model every cell above the diagonal must be exactly zero, whatever the weights.
@torch.no_grad()
def influence(model, ids, mask, pos=None):
"""inf[i, j]: the largest change in output i when input token j is changed."""
base = model(ids, mask, pos)
T, V = ids.shape[1], model.embed.num_embeddings
inf = torch.zeros(T, T)
for j in range(T):
edited = ids.clone()
edited[0, j] = (edited[0, j] + 1) % V # change one token
inf[:, j] = (model(edited, mask, pos) - base)[0].abs().amax(-1)
return inf
I = influence(lab, alone, causal_mask(4))
print(I.numpy().round(3))
print("largest cell above the diagonal:", I.triu(1).max().item())Code walkthrough
influenceruns the model once as given, then once per position with that token changed to the next id.amax(-1)keeps each output's largest logit change.I.triu(1)keeps the cells above the diagonal: outputs moved by a later token.
Above the diagonal every cell is exactly 0.0, not small (measured here); below, 0.09 to 0.22. This test goes into tests/test_m02_attention.py.
Break it: tril(1)
One character makes a leak: tril(1) keeps one diagonal more, so each token reads the next.
off_by_one = torch.ones(4, 4, dtype=torch.bool).tril(1)
show(off_by_one)
I_bad = influence(lab, alone, off_by_one)
print(I_bad.numpy().round(3))
print("largest cell above the diagonal:", round(I_bad.triu(1).max().item(), 3))
print("output 0 reads token 2 through two layers:", round(I_bad[0, 2].item(), 3))Code walkthrough
tril(1)keeps one band above the diagonal. The map is computed as before; the prints read cells that must be zero.
The test fails: 0.212 above the diagonal (measured here). Leaks compound: each layer reads one ahead, so output 0 is moved by token 2 (0.019). A shape test passes this bug.
4. Bidirectional attention leaking in generation (Essential)
An encoder reads both ways: right for understanding a message, wrong for predicting the next token. Trained on next-token prediction, its loss can look perfect. Measure how much of it is real.
Train twins on Module 1's copy task (shared block 9): 16 random tokens, a separator, the same 16 again. No honest model can predict the random half: its floor is ln 31 = 3.434 nats (arithmetic). Both twins train on every position; only the mask differs.
from typing import NamedTuple
class TaskData(NamedTuple):
name: str
vocab_size: int
inputs: torch.Tensor # (n, T) token ids
targets: torch.Tensor # (n, T) the next token at every position
mask: torch.Tensor # (n, T) 1 where the answer is scored, 0 elsewhere
def _shift(name, vocab, seq, scored_from):
inputs, targets = seq[:, :-1], seq[:, 1:]
mask = torch.zeros_like(inputs)
mask[:, scored_from:] = 1
return TaskData(name, vocab, inputs, targets, mask)
def make_task(name, n=4096, length=16, vocab=32, seed=SEED):
"""copy, reverse or induction. Token 0 is the separator; content tokens are 1 to vocab - 1."""
g = torch.Generator().manual_seed(seed)
body = torch.randint(1, vocab, (n, length), generator=g)
sep = torch.zeros(n, 1, dtype=torch.long)
if name == "copy":
seq = torch.cat([body, sep, body], dim=1)
elif name == "reverse":
seq = torch.cat([body, sep, body.flip(1)], dim=1)
elif name == "induction": # random tokens, then the same random tokens again
seq = torch.cat([body, body], dim=1)
return _shift(name, vocab, seq, scored_from=length)
TASKS = {name: make_task(name) for name in ["copy", "reverse", "induction"]}
for t in TASKS.values():
print(t.name, tuple(t.inputs.shape), "scored positions per row:", int(t.mask[0].sum()))Code walkthrough
- Shared block 9, as written. Only
TASKS["copy"]is used.
import time
task = TASKS["copy"]
def train_twin(mask, steps=300, seed=SEED):
"""Next-token loss on every position; the mask is the only switch."""
set_seed(seed)
model, g = MaskLab(vocab=32), torch.Generator().manual_seed(seed)
opt = torch.optim.AdamW(model.parameters(), lr=3e-3)
for _ in range(steps):
i = torch.randint(0, len(task.inputs) - 512, (64,), generator=g)
loss = F.cross_entropy(model(task.inputs[i], mask).flatten(0, 1), task.targets[i].flatten())
opt.zero_grad(); loss.backward(); opt.step()
return model.eval()
t0 = time.perf_counter()
twins = {"causal": (train_twin(causal_mask(32)), causal_mask), "bidirectional": (train_twin(None), lambda T: None)}
print(f"trained both in {time.perf_counter() - t0:.1f} s")
xv, yv = task.inputs[-512:], task.targets[-512:] # 512 held-out rows
with torch.no_grad():
for name, (model, mask_for) in twins.items():
loss = F.cross_entropy(model(xv, mask_for(32)).transpose(1, 2), yv, reduction="none")
print(f"{name:13} loss on the random half {loss[:, :15].mean():.4f} | on the copied half {loss[:, 16:].mean():.4f}")Code walkthrough
train_twintrains a 32-tokenMaskLabfor 300 steps of 64 rows.mask=Nonelets every position read every other: bidirectional attention.twinspairs each model with a function that builds its mask for any length.reduction="none"keeps one loss per position:[:, :15]are the random targets. Training took about 3 s (2.8 to 3.3 s over four runs) on the author's Mac; allow four times that in Colab.
On the random half the causal twin scores 3.4555, near the floor; the bidirectional twin 0.0015 (measured here). Predicting random tokens is impossible, so it reads the answer, one position to its right.
with torch.no_grad():
for name, (model, mask_for) in twins.items():
whole = F.cross_entropy(model(xv, mask_for(32)).transpose(1, 2), yv, reduction="none").mean(0)
prefix = torch.stack([F.cross_entropy(model(xv[:, :p + 1], mask_for(p + 1))[:, p], yv[:, p])
for p in range(32)]) # score position p with nothing after it
ids = xv[:, :17] # 16 tokens and the separator
for _ in range(16): # generate the copy one token at a time
nxt = model(ids, mask_for(ids.shape[1]))[:, -1].argmax(-1, keepdim=True)
ids = torch.cat([ids, nxt], dim=1)
copied = (ids[:, 17:] == xv[:, :16]).float().mean().item()
print(f"{name:13} whole window {whole.mean():.4f} | prefix only {prefix.mean():.4f} | copied {copied:.1%}")Code walkthrough
wholescores every position with the full window;prefixscores each again with the input cut just after it.- The loop generates: take the most likely next token, append, repeat 16 times.
copiedis the share matching the original.
The causal twin scores 1.6224 both ways: its mask already hid the future. The bidirectional twin goes from 0.0015 to 4.6250, worse than guessing (measured here).
In generation the causal twin copied 100.0% of tokens, the bidirectional twin 85.9% (seed 11; seeds 12 and 13 gave 96.4% and 92.2%, causal 100% on all; measured here). It still copies most, since the earlier copy is visible, but its loss promised near certainty. The prefix-only score is the general test for this leak in any evaluation.
5. Prefix and block-diagonal masks (Recommended)
Two useful shapes sit between causal and bidirectional. Knowing them lets you read a model's mask from its influence map.
A prefix mask lets a known input, such as a question, be read both ways while the answer is generated left to right: the prefix language model of Module 7. Its test changes: inside the prefix, later tokens may move earlier ones; after it, nothing may.
I_prefix = influence(lab, packed, prefix_mask(11, 5))
show(I_prefix > 0)
print("prefix reads both ways:", bool((I_prefix[:5, :5] > 0).all()))
print("largest cell above the diagonal after the prefix:", I_prefix.triu(1)[5:].max().item())Code walkthrough
I_prefix > 0prints 1 wherever an edit moved an output. The prints check both halves of the rule.
The prefix square is full, and after it 0.0 above the diagonal (measured here). A prefix model can read its prefix, so its loss must cover the answer only.
A block-diagonal mask seals groups of positions apart. With causal blocks it is section 1's document mask; with full blocks an encoder can batch short inputs in one row.
6. Packed sequences and document boundaries (Recommended)
Pretraining does not pad: it joins documents and cuts windows, wasting nothing. Mario Michael Krell and colleagues at Graphcore ("Efficient Sequence Packing without Cross-contamination", 2021, arXiv:2107.02027) report that "up to 50% of all tokens can be padding" in common datasets. The price: one row holds unrelated documents.
Documents reading each other is cross-contamination. The test is the padding test again: Tariq in the packed row must equal Tariq alone.
tariq = torch.tensor([[DOC, 39, 45, 61, 53, 60]])
restart = torch.cat([torch.arange(5), torch.arange(6)])[None] # Maya at 0..4, Tariq at 0..5
with torch.no_grad():
want = lab(tariq, causal_mask(6))[0]
for name, m, pos in [("plain causal ", causal_mask(11), None),
("document mask only ", document_mask(packed), None),
("restarted positions ", causal_mask(11), restart),
("document mask + both ", document_mask(packed), restart)]:
print(name, f"Tariq vs alone: {(lab(packed, m, pos)[0, 5:] - want).abs().max().item():.2e}")
print("Maya's largest pull on Tariq with plain causal:", round(influence(lab, packed, causal_mask(11))[5:, :5].max().item(), 3))Code walkthrough
restartgives Maya positions 0 to 4 and Tariq 0 to 5. The loop compares Tariq's six packed outputs with Tariq alone under four setups.- The last line reads, from
influence, Maya's largest pull on Tariq.
Plain causal: 1.74. Document mask alone: 1.73, since positions still differ. Restarted positions alone: 0.370, Maya leaking in. Both: 5.4e-07 (measured here). The packed row now computes what two rows would, with no pads.
In production
Fused kernels take document starts, not a (T, T) mask. Hugging Face's post "Improving Hugging Face Training Efficiency Through Packing with Flash Attention 2" (Rhui Dih Lee, Arthur Zucker and colleagues, 21 August 2024, huggingface.co/blog/packing-with-FA2) says that "previous implementations of packing did not consider example boundaries when using Flash Attention 2". Its DataCollatorWithFlattening passes position_ids that restart per example: both fixes above. It reports up to 2x training throughput on FLAN (1.4x on OrcaMath), about 20% less peak memory on FLAN, and validation loss identical to padding. This interface changes fast; check it when you use it.
What you added to tinyformer-lab
- Five mask builders for
tinyformer/attention.py, one convention:Truemeans may read. - Position ids counted from the mask, for left padding and packing.
influenceand the "same as alone" check, fortests/test_m02_attention.py.- The causal and bidirectional twins. The module lab saves all of these into the package.
Check yourself
- Maya in a right-padded batch differs from Maya alone by 0.187. What is missing?
- Why did one blocked row make all of Maya's positions NaN, but none of Tariq's?
- An influence map shows 0.019 two cells above the diagonal. Which bug does that?
- A loss of 0.0015 nats on random tokens from 31 choices. Conclusion?
- With a document mask, packed Tariq still differs from Tariq alone by 1.73. Why?
- The padding mask: her queries read the pad.
- In layer 2 the pad's NaN value reached every query of its own sequence (0 x NaN = NaN); sequences in a batch never mix.
- A one-step leak such as
tril(1), compounded over two layers. - It reads the future; the floor is ln 31 = 3.434.
- Positions 5 to 10 instead of 0 to 5. Restart them at each
<doc>.
Exercise
Left-pad Maya, Tariq and Hana (27, 45, 57, 45). Write left_batch so every name matches itself alone under a causal mask. Try it before reading ours.
def left_batch(names):
"""Left-pad id lists; return ids, mask and positions for a causal decoder."""
T = max(len(n) for n in names)
ids = torch.tensor([[PAD] * (T - len(n)) + n for n in names])
real = ids != PAD
mask = (padding_mask(ids) & causal_mask(T)) | torch.eye(T, dtype=torch.bool)
pos = (real.cumsum(-1) - 1).clamp_min(0)
return ids, mask, pos
names = [[32, 45, 68, 45], [39, 45, 61, 53, 60], [27, 45, 57, 45]]
ids, mask, pos = left_batch(names)
with torch.no_grad():
out = lab(ids, mask, pos)
for row, n in enumerate(names):
solo = lab(torch.tensor([n]), causal_mask(len(n)))[0]
assert torch.allclose(out[row, -len(n):], solo, atol=1e-5), f"row {row} leaks"
assert not torch.isnan(out).any(), "a row has nothing to read"
print("check passed: every name matches itself alone")Code walkthrough
left_batchleft-pads, builds the three-rule mask and counts positions. The check compares each name's lastlen(n)outputs with the name alone and rejects NaN. Delete thetorch.eyeterm, or the positions, and see which assert fails.
Key terms
| Term | Meaning |
|---|---|
| Attention mask | A boolean grid, True where a query may read a key |
| Causal mask | Each token reads itself and earlier tokens only |
| Padding mask | Blocks the columns of pad tokens so no query reads them |
| Influence map | How far output i moves when input j is changed; zero cells prove a mask holds |
| Bidirectional attention | Every token reads every other, the future included |
| Prefix mask | A prefix read both ways, the rest causal |
| Block-diagonal mask | Groups of positions sealed off from each other |
| Cross-contamination | Packed documents reading each other through attention |
Sources
- LaurenceA, gante and others, "Mismatch between logits from generate and forward with an attention mask for most GPT models", Hugging Face transformers issue #18388, 2022. https://github.com/huggingface/transformers/issues/18388
- Rhui Dih Lee, Arthur Zucker, Achintya Kundu, Laura Wynter, Raghu Ganti, Mayank Mishra, "Improving Hugging Face Training Efficiency Through Packing with Flash Attention 2", Hugging Face blog, 2024. https://huggingface.co/blog/packing-with-FA2
- Mario Michael Krell, Matej Kosec, Sergio P. Perez, Andrew Fitzgibbon (Graphcore), "Efficient Sequence Packing without Cross-contamination", 2021. https://arxiv.org/abs/2107.02027
- PyTorch,
torch.nn.functional.scaled_dot_product_attention, documentation for version 2.14, checked October 2026. https://docs.pytorch.org/docs/2.14/generated/torch.nn.functional.scaled_dot_product_attention.html - PyTorch,
torch.nn.MultiheadAttention, documentation for version 2.14, checked October 2026. https://docs.pytorch.org/docs/2.14/generated/torch.nn.MultiheadAttention.html