Free self-study · No account needed · Progress stays in this browser. Back it up before clearing site data or changing devices.

← Week 3: Transformers and Language Models

Week 03 / Lesson 2

Calculating causal attention

Calculate attention weights and prevent access to future tokens.

Section 2.1 1 of 7

Overview

Focus

Calculate attention weights and prevent access to future tokens.

Your route through the lesson

  • 2.2 Query, key, and value projections
  • 2.3 Scaled scores and softmax
  • 2.4 Causal masking and multiple attention heads
  • 2.5 Put it into practice
  • 2.6 Guided comparison
  • 2.7 A future-token leakage bug

All required teaching is included here. Review selections are saved. Choose a correct answer for every question to continue; retries are unlimited. Study time and personal notes are optional.

Section 2.2 2 of 7

Query, key, and value projections

Focus

Form queries, keys, and values from hidden vectors and identify their roles.

Self-attention allows each token position to combine information from positions in the same sequence. A learned projection produces three representations: a query asks what the current position seeks, a key describes how another position can match, and a value carries information to mix into the result. These names describe mathematical roles, not three literal database tables.

If hidden states H are shaped (T,d), multiplying by learned projection matrices creates Q,K,V. For one attention head, queries and keys must have the same comparison width. The score matrix Q@K.T has shape (T,T): row i contains the current query's scores against every key. Values can have a different output width, so their role is separate from matching.

With query [1,0], keys [1,0] and [0,1] have dot-product scores 1 and 0. A dot product multiplies corresponding coordinates and sums them. Similarity of these projected representations helps decide information flow; it does not provide a citation or prove the truth of a token.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A query [1,0] compares with keys [1,0] and [0,1]. What are the dot products?
2. Queries and keys each have three positions. What shape has their all-position score matrix?
3. Which attention representation carries the vectors combined after weighting?

Section 2.3 3 of 7

Scaled scores and softmax

Focus

Turn scaled scores into a weighted mixture and interpret the result.

Large dot products can make probability normalization too sharp as comparison width grows. Scaled dot-product attention divides scores by the square root of key width. Softmax then exponentiates each allowed score and divides by the row's sum, producing nonnegative weights that add to one.

For scores [0,0], exp(0)=1, so weights are [0.5,0.5]. If values are [2,0] and [0,4], the weighted mixture is 0.5×[2,0]+0.5×[0,4]=[1,2]. Attention therefore computes a mixture, not simply the name of the highest-scoring token.

The formula for one head is softmax(Q@K.T/sqrt(d_key))@V. Check dimensions at both multiplications. A weight row sums over key positions; normalizing the wrong axis answers a different question. Attention weights describe this computation, and their existence alone does not establish a faithful explanation of an entire model's reasoning.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Softmax receives scores [0,0]. What weights result?
2. Weights [0.5,0.5] combine values [2,0] and [0,4]. What output is produced?
3. Why divide attention scores by the square root of comparison width?

Section 2.4 4 of 7

Causal masking and multiple attention heads

Focus

Prevent future-token access and combine multiple learned attention heads.

During next-token training, later tokens are present in the training sequence but must not be visible to earlier positions. A causal mask allows positions at or before the current one and blocks future positions. Add negative infinity to forbidden scores before softmax; their exponentials become zero. Setting a forbidden score to zero is insufficient because exp(0)=1.

For three all-zero score rows, the causal attention weights are [1,0,0], [0.5,0.5,0], and [1/3,1/3,1/3]. Each row sums to one over allowed positions. Test a stronger invariant: changing the final input token must not change outputs at earlier positions when the model is in evaluation mode.

Multiple heads learn different query/key/value projections, calculate their mixtures, concatenate them, and project the combined output. They do not grant access to future tokens. Each head still obeys the causal mask. PyTorch's boolean attention mask uses True for blocked positions in the module used by this lab; always check the particular interface's mask convention.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A forbidden attention score is set to zero before softmax. Why can information still leak?
2. For three all-zero scores with a causal mask, what is the first position’s weight row?
3. Does adding more attention heads permit a causal decoder to read future tokens?

Section 2.5 5 of 7

Put it into practice

Focus

Implement causal attention and verify a future-token perturbation test.

Download week03.py and run python week03.py --lesson 2. The lab first performs explicit score, mask, softmax, and value operations with tiny tensors. In Python, .T transposes a two-dimensional tensor. torch.triu constructs the upper-triangular future-position region, and masked_fill assigns negative infinity to those blocked scores.

Predict the three causal rows for an all-zero score matrix before running the assertions. Then inspect the broken version where future scores are set to zero. Its nonzero future weights show why a program can execute successfully while learning from forbidden information.

The lab also compares earlier outputs before and after changing the last token. A correct causal implementation leaves earlier outputs unchanged within numerical tolerance. Use evaluation mode so random dropout does not confuse that comparison. This invariant checks information flow beyond merely inspecting whether a mask variable exists.

Download this week’s Python lab ↓

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. An attention lab changes only the last input token. What should remain unchanged in a causal model?
2. Why run the perturbation comparison with dropout disabled through evaluation mode?
3. A script contains a mask variable but still assigns future weights positive values. Is the boundary verified?

Section 2.6 6 of 7

Guided comparison

Focus

Calculate all allowed rows and distinguish a causal mask from a padding mask.

For a three-token sequence with zero allowed scores, position zero can use only itself, giving [1,0,0]. Position one can use positions zero and one, giving [0.5,0.5,0]. Position two can use all three and gives thirds. The weights differ despite identical raw scores because each row has a different allowed set.

A causal mask prevents access to future sequence content. A padding mask hides artificial fill positions used to batch unequal-length sequences. Their purposes differ, and a batched decoder may need both. A padding token placed in the middle of a tensor is not automatically blocked just because its integer identifier is zero.

An all-blocked row needs explicit handling: softmax over only negative infinities can produce undefined numerical results. Design inputs and masks so real queries have allowed keys, and check for finite outputs. Causal masking is an architectural condition, while training and validation splitting is a dataset condition; both are needed for a meaningful language-model evaluation.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Three allowed scores are equal at the final position of a three-token causal sequence. What weights result?
2. What is the role of a padding mask?
3. A query has every key blocked with negative infinity. What numerical risk should be checked?

Section 2.7 7 of 7

A future-token leakage bug

Focus

Diagnose a language model that improves only because it sees future tokens.

A training run reports very low next-token loss, but its attention implementation permits every position to read the whole input sequence. Because shifted targets occur later in that same sequence, the model may obtain answer information that will not exist at generation time. The attractive training score is then measuring an easier, invalid task.

Keep the dataset split fixed and repair the mask. Check future weights, perturb a later token, and rerun training. Loss may become higher after the repair because the shortcut is gone. That increase is not evidence that the correct mask is worse engineering; it restores the intended prediction problem.

Also inspect input/target alignment. If position i predicts token i+1, its allowed context ends at i. Passing the answer token as the current input while asking the model to predict that same token creates another shortcut even with a mask. A causal-flow test and a shifted-label fixture detect different mistakes and should both be retained.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A next-token model can attend to later training tokens. Why may its loss look unrealistically low?
2. Repairing a future-token leak increases training loss. What does that mean by itself?
3. A position receives token B and is trained to predict B instead of the next token. What else needs checking?

Your personal notes

Optional, ungraded, and saved only in this browser. Export a backup from the Academy homepage to keep them.

References and further reading
Ask your own AI assistant

Copy this prompt into an assistant you already use. Nothing is sent automatically, and your personal notes are not included.

Next lesson: Building a transformer block and generating tokens →