CourseTransformers: From Attention to Trained, Served and Interpreted Models · Module 2: Self-Attention Mechanics · part 16 of 111
Part 16 · Module 2: Self-Attention Mechanics

Lesson 4: Masking, built, tested and broken on purpose

19 min read·
Module 2 · Lesson 4 · About 50 minutes · Needs: Module 2, Lessons 1 and 2 (naive_attention, its mask argument, 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.

LOG-PROBS OF THREE GENERATED TOKENS unpadded prompt forward -8.3152 -5.5587 -3.0973 generate -8.3152 -5.5587 -3.0973 padded prompt forward -2.6509 -10.6300 -7.5426 generate -2.7818 -10.6300 -7.5426 one mismatch: the padded prompt's first new token
In issue #18388 every log-probability from forward matched generate (green) except the padded prompt's first generated token, -2.6509 against -2.7818 (red, the failure).

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.

RIGHT PADDING LEFT PADDING M a y a pad next gap before the new token 0 1 2 3 4 5 pad M a y a next prompt ends at the edge - 0 1 2 3 4 positions counted from the mask
Right padding leaves a pad (grey) between Maya and the token the model generates next (amber); left padding puts every prompt's end in the last column, and the position-id code must then count positions from the mask.

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.

python
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 5 on the author's Mac.
python
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 = 11 and set_seed().
python
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 out

Code walkthrough

  • Unchanged from Lesson 2. Today's line is masked_fill(~mask, float("-inf")): a False cell scores minus infinity, which the softmax turns into exactly 0.
ROWS: QUERIES, COLUMNS: KEYS M a y a M a y a True: may read score kept False: blocked score set to -inf weight 0 exactly
An attention mask is a grid with one row per query and one column per key: open cells (blue, the normal path) keep their score, blocked cells (grey) score minus infinity and get a weight of 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.

causal prefix 5 document window 3 the same 11 tokens: <doc>Maya<doc>Tariq
Four masks on the packed row <doc>Maya<doc>Tariq: causal reads the past, prefix opens the first five tokens both ways, document keeps each name to itself, and window 3 reads only the last three tokens.

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.

python
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_mask then opens the top-left square.
  • padding_mask marks real tokens and adds a middle axis, so one column rule covers every query in that sequence.
  • document_mask labels each position with its document by counting <doc> tokens (cumsum), keeps same-document pairs, and stays causal.
  • sliding_window_mask cuts the triangle to a band; Lesson 5 measures what it saves.
OPEN CELLS OUT OF 121, MEASURED HERE prefix 5 76 causal 66 document 36 window 3 30
Of 121 cells, the prefix mask opens 76, causal 66, document 36 and window 3 just 30; the 30 cells the document mask closes are exactly where Tariq would read Maya.

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.

python
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

  • keep marks four real keys and two pads. additive is the same rule as numbers added to the scores: 0 keeps, minus infinity blocks. F.scaled_dot_product_attention takes either.
  • nn.MultiheadAttention with identity weights is plain attention, so it should match mine. Its key_padding_mask gets keep inverted, then as it is.
SDPA attn_mask True: take part matches naive: 3.6e-07 MHA key_padding_mask True: ignored same tensor: off by 3.40 one convention in the lab, converted at the edge
The same boolean tensor means opposite things in PyTorch: scaled_dot_product_attention reads True as take part (green, matched), MultiheadAttention's key_padding_mask reads True as ignore (red, off by 3.40 measured here).

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.

ONE BATCH, SHAPE (2, 5) M a y a pad 32 45 68 45 0 T a r i q 39 45 61 53 60 Maya Tariq pad id 0
The running example: Maya (ids 32, 45, 68, 45) is padded with one <pad> (grey, id 0) so it fits a (2, 5) batch with Tariq.

MaskLab is Lesson 2's two-block model with one change: forward takes the mask, and optionally the positions, from the caller.

python
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

  • MaskBlock is a pre-norm, one-head block that attends with the mask it is given. Module 3 builds the real block.
  • MaskLab adds 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=None means positions 0, 1, 2 ...; passing pos says where each token really sits.
PADDING MASK FOR MAYA'S ROW M a y a pad M a y a pad the pad column is closed for every query
A padding mask closes the pad's column (grey) for every query in Maya's row, so no real token can read the pad; it is shape (B, 1, T) and broadcasts over the rows.

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.

python
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

  • lab is untrained: a correct mask gives equal outputs whatever the weights, so wiring tests need no training.
  • tampered puts q (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.
no padding mask pad changed: moved 0.1311 batch vs alone: 0.187 padding mask pad changed: moved 0.0000 batch vs alone: 4.8e-07 Maya's four real outputs, measured here
Without a padding mask, junk in the pad slot moved Maya's outputs by 0.1311 (red); with it, nothing moved and Maya in the batch matched Maya alone to 4.8e-07 (green), float32 rounding.

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).

LEFT-PADDED MAYA pad M a y a 0..4 from mask 0 0 1 0 2 1 3 2 4 3 Maya read as 1..4 Maya read as 0..3 positions = cumsum(real) - 1
Left padding shifts Maya to positions 1 to 4 (red), so learned positions read her differently; counting real tokens from the mask puts her back at 0 to 3 (green).

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.

python
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) - 1 counts 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.
LEFT-PADDED MAYA VS MAYA ALONE positions 0..4 1.772 from the mask 6.0e-07 largest logit difference, measured here
With raw positions, left-padded Maya's logits differ from Maya alone by 1.772 (red); with positions counted from the mask, by 6.0e-07 (green): the opener's mismatch, reproduced and fixed.

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.

python
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

  • bad lacks the self-read, so the pad's row is all False. torch.isnan(...) counts, per name, positions with any NaN logit.
  • The last line gives PyTorch's built-in a fully blocked row.
pad row all -inf softmax 0 / 0 = NaN layer 2 0 x NaN = NaN Maya 5 of 5 NaN Tariq: 0 NaN SDPA returned 0 for the same row
A row with nothing to read turns into NaN, and in layer 2 that NaN value spreads to all five of Maya's positions (red) while Tariq's row stays clean (green); PyTorch's fused function returned 0 instead.

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 INFLUENCE MAP, ONE COLUMN AT A TIME M a y a change token j rerun model output i moved by? causal: every output before j must move exactly 0
The influence map checks a mask by behaviour: change one input token (amber), rerun, and record how far every output moved; for a causal model every output before the change must move exactly 0.

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.

python
@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

  • influence runs 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.
ROWS: OUTPUTS, COLUMNS: EDITED TOKEN M a y a M 1.902 0 0 0 a 0.221 1.811 0 0 y 0.204 0.180 1.612 0 a 0.142 0.085 0.180 1.827
The measured causal influence map on Maya: every cell above the diagonal is exactly 0 (grey), not small, while the cells on and below it (amber) moved by 0.085 to 1.902.

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.

python
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.
TRIL(1): EACH LAYER READS ONE AHEAD M a y a M 1.852 0.212 0.019 0 a 0.133 1.795 0.178 0.013 y 0.182 0.151 1.603 0.160 a 0.131 0.088 0.181 1.819
With tril(1) the cells above the diagonal turn red: 0.212 one step ahead, and 0.019 two steps ahead because two layers each read one token ahead (measured here).

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.

A COPY-TASK ROW: 33 TOKENS 16 random tokens 0 the same 16 again floor: ln 31 = 3.434 nats learnable: copy causal twin bidirectional twin same model, data, seed, 300 steps; only the mask differs
The twins train on the copy task, identical except for the mask: the first 16 tokens are random (grey), so no honest model can beat ln 31 = 3.434 nats there (arithmetic).

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.

python
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.
python
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_twin trains a 32-token MaskLab for 300 steps of 64 rows. mask=None lets every position read every other: bidirectional attention.
  • twins pairs 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.
LOSS ON THE 15 RANDOM TARGETS, NATS honest floor 3.434 causal 3.4555 bidirectional 0.0015 512 held-out rows, measured here
On random tokens the causal twin sits at the 3.434 floor (green) while the bidirectional twin claims 0.0015 nats (red), an impossible score that can only come from reading the answer.

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.

python
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

  • whole scores every position with the full window; prefix scores each again with the input cut just after it.
  • The loop generates: take the most likely next token, append, repeat 16 times. copied is the share matching the original.
SAME POSITIONS, FUTURE PRESENT OR CUT causal, whole 1.6224 causal, prefix 1.6224 bidir, whole 0.0015 bidir, prefix 4.6250
Scoring the same positions with the future cut off changes nothing for the causal twin (green, 1.6224 both ways) and sends the bidirectional twin from 0.0015 to 4.6250 nats (red).

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).

TOKENS COPIED IN GENERATION causal, 3 seeds 100% bidir, seed 11 85.9% bidir, seed 12 96.4% bidir, seed 13 92.2%
Generating the copy one token at a time, the causal twin was right on 100% of tokens for all three seeds (green); the bidirectional twin, whose loss promised near certainty, got 85.9% to 96.4% (red).

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.

PREFIX LANGUAGE MODEL <d> M a y a <d> T a r i q read both ways generated left to right
A prefix mask lets the known input (blue) be read in both directions, while the answer (amber, what the model predicts) is still generated left to right.

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.

python
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 > 0 prints 1 wherever an edit moved an output. The prints check both halves of the rule.
MEASURED INFLUENCE, PREFIX OF 5 prefix answer full square causal after
The influence map of a five-token prefix, measured on the packed row: a full square where the prefix reads both ways, then exactly 0.0 above the diagonal for every later position.

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.

causal blocks full blocks decoder: packed documents encoder: short inputs batched
A block-diagonal mask seals groups of positions apart: with causal blocks (left) it is the decoder's document mask, with full blocks (right) it batches several encoder inputs in one row.

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.

PADDED: 2 ROWS OF 6, ONE PAD <d> M a y a pad <d> T a r i q PACKED: 1 ROW OF 11, NO PADS <d> M a y a <d> T a r i q attention can cross the boundary
Padding spends slots on pads (grey); packing spends none but puts Maya (blue) and Tariq (amber) in one row, where attention can cross from one to the other (red).

Documents reading each other is cross-contamination. The test is the padding test again: Tariq in the packed row must equal Tariq alone.

python
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

  • restart gives 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.
TARIQ PACKED VS TARIQ ALONE plain causal 1.74 document mask 1.73 restart positions 0.370 both 5.4e-07 largest logit difference, measured here
Packed Tariq matches Tariq alone only with both fixes (green, 5.4e-07): the document mask alone leaves the position shift (1.73), and restarted positions alone leave Maya leaking in (0.370).

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 PACKING: NO T BY T MASK <d> M a y a <d> T a r i q document starts 0 5 position_ids 0 1 2 3 4 0 1 2 3 4 5 HF blog: up to 2x throughput, same validation loss
Fused kernels take where each document starts and position ids that restart per document, the two fixes measured above; Hugging Face reports up to 2x training throughput with identical validation loss.

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: True means may read.
  • Position ids counted from the mask, for left padding and packing.
  • influence and the "same as alone" check, for tests/test_m02_attention.py.
  • The causal and bidirectional twins. The module lab saves all of these into the package.

Check yourself

  1. Maya in a right-padded batch differs from Maya alone by 0.187. What is missing?
  2. Why did one blocked row make all of Maya's positions NaN, but none of Tariq's?
  3. An influence map shows 0.019 two cells above the diagonal. Which bug does that?
  4. A loss of 0.0015 nats on random tokens from 31 choices. Conclusion?
  5. With a document mask, packed Tariq still differs from Tariq alone by 1.73. Why?
  1. The padding mask: her queries read the pad.
  2. 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.
  3. A one-step leak such as tril(1), compounded over two layers.
  4. It reads the future; the floor is ln 31 = 3.434.
  5. 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.

python
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_batch left-pads, builds the three-rule mask and counts positions. The check compares each name's last len(n) outputs with the name alone and rejects NaN. Delete the torch.eye term, or the positions, and see which assert fails.

Key terms

TermMeaning
Attention maskA boolean grid, True where a query may read a key
Causal maskEach token reads itself and earlier tokens only
Padding maskBlocks the columns of pad tokens so no query reads them
Influence mapHow far output i moves when input j is changed; zero cells prove a mask holds
Bidirectional attentionEvery token reads every other, the future included
Prefix maskA prefix read both ways, the rest causal
Block-diagonal maskGroups of positions sealed off from each other
Cross-contaminationPacked 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