4.1.11 · D4Transformer Architecture

Exercises — Masked attention for autoregression

2,874 words13 min readBack to topic

This is your self-testing gym for masked attention. Work each problem before opening the solution. Difficulty climbs in five levels:

  • L1 Recognition — can you spot the right object?
  • L2 Application — can you run the machine?
  • L3 Analysis — can you explain why it behaves that way?
  • L4 Synthesis — can you combine masking with other ideas?
  • L5 Mastery — can you handle the edge cases and design decisions?

Every symbol used here is defined the moment it appears. If you ever feel a term arrived unearned, that is a bug — but let us re-anchor the objects we lean on most:

Before the problems, fix the geometry in your head with the figure below. Refer back to it whenever a solution says "row " or "the diagonal" — it is the map every exercise navigates.

Figure — Masked attention for autoregression

We use softmax (and not, say, "just normalize by dividing") because we want a differentiable function that always yields positive weights summing to one — that is what lets us treat attention weights as probabilities and train them with gradients.


Level 1 — Recognition

Recall Solution

Answer: . A valid causal mask keeps the diagonal and everything below it at (past + self allowed), and sets everything above the diagonal () to (future silenced). That is a lower-triangular-of-zeros pattern — exactly the teal+orange cells of Figure s01.

  • : diagonal and below are , strictly-upper is . ✅
  • : this is the transpose — it silences the past instead of the future. Wrong.
  • : it masks the diagonal too (), which would forbid a token from attending to itself. That is the "diagonal-mask" error — a token must be allowed to attend to itself (we prove why in L5.2, where masking the diagonal makes the very first row empty and produces NaN). Wrong.
Recall Solution

Position may attend to . For : . It may not see (the future). Count of allowed keys .


Level 2 — Application

Recall Solution

Position may see ; positions are future set to . Masked row: . Softmax over the two survivors: , , sum . Weights sum to , and the future columns are exactly . ✅

Recall Solution

Step 1 — scores . ( answers "similarity of each query to each key" — a dot product is large when two vectors point the same way, which is why it measures alignment.) Step 2 — scale by (recall from the top of the page: this divides by to stop the dot products from growing with ): . Step 3 — mask. Row 1 () may see only : . Row 2 () sees : . Step 4 — softmax. Row 1: only one survivor . Row 2: , , sum . Step 5 — weights . Position 1: . Position 2: . Output . Notice: token 1's output is pure — it had no choice but itself. That is the causal constraint made visible.


Level 3 — Analysis

Recall Solution

No mask: every position attends to all positions edges. Causal mask: position attends to positions, so Ratio (causal / full) . For : . So masking keeps just over half the edges — the lower triangle plus the diagonal. Insight: the cost is still ; masking halves the count but not the asymptotic order. This is why long-context attention is expensive with or without a mask.

Recall Solution

The masked cell's weight after softmax is underflows to in floating point, so numerically it is identical to for any realistic real score (typically ). The difference only ever appears in pathological arithmetic where a genuine score also reaches ; that never happens for scaled dot products. So is a safe, common implementation choice — and it avoids the hazard that can occur if an entire row is masked.

Recall Solution

Softmax computes NaN (not-a-number). A single NaN propagates through the whole network and poisons the loss. Cure: never mask a query's own diagonal (a token always keeps itself — see L5.2), or drop fully-padded query rows before softmax, or use the trick from L3.2 which yields a uniform-but-finite row instead of NaN. This is the degenerate case masking must survive.


Level 4 — Synthesis

Recall Solution

At step we have only ever created keys/values for positions ; positions do not exist yet, so there is physically nothing future to attend to. The cache holds exactly . Softmaxing over these keys is identical to row of the masked training matrix (the survivors are ). So the mask is "baked into" the geometry of incremental decoding — we get causality for free. This is why KV Caching and causal masking are consistent: training with the lower-triangular mask makes each row match what inference will later see.

Recall Solution

Teacher Forcing hands the model the whole ground-truth sequence at once so all predictions can be computed in one parallel pass (fast). But parallelism means every position could peek at every other — including the answer sitting one slot to the right. The causal mask restores the promise "position only sees ", so the parallel computation produces exactly the same conditioning that the slow, one-at-a-time inference of L4.1 uses. Mask = the bridge that lets us train fast but behave sequentially.

Recall Solution

(a) Decoder self-attention — masked. The decoder is generating autoregressively, so it must not see its own future tokens. (b) Cross-attention — not masked. The encoder has already read the entire source sentence (it is the input, fully available), so a decoder token is allowed to attend to all encoder positions. Blocking future source positions would throw away legitimately available information. Rule of thumb: mask only where a "future" would be cheating — that is only inside the decoder's self-attention.


Level 5 — Mastery

Recall Solution

Because each is on a distinct axis, the weighted sum separates coordinate-by-coordinate: Matching to : . Sanity checks: all ✅, sum ✅ (a valid softmax distribution), no future column (there is none for ) ✅.

Recall Solution

For the allowed set becomes empty (there is no position in our 1-based numbering). The score row is entirely , and (L3.3) softmax returns NaN. The first token would have nothing to attend to, poisoning training instantly. This is precisely why the correct mask keeps the diagonal (): every position, including the first, always has at least itself to attend to.

Recall Solution

The output is with For , . Therefore No with appears. Its coefficient is exactly , independent of the value . Causality is guaranteed for every row, every quadrant of the matrix — the future has zero influence by construction.


Recall Quick self-quiz (cover the answers)

What triangle of the mask holds ? ::: The strictly-upper triangle (), the future. Why mask before softmax, not after? ::: So weights renormalize over survivors and still sum to . Why keep the diagonal unmasked? ::: A token must attend to at least itself; masking it gives an empty row and NaN for . Why divide scores by ? ::: A dot product of -long vectors grows like ; dividing keeps softmax out of the vanishing-gradient spike. Does cross-attention in an encoder-decoder get a causal mask? ::: No — the full source is available; only decoder self-attention is masked. Fraction of edges kept for large ? ::: About one half, .

Related pages: Self-Attention Mechanism · Decoder Architecture · Attention Score Scaling · Positional Encoding · KV Caching · Teacher Forcing · Encoder-Decoder Models.