Skip to content
StackDecode
LLM Library
Inside the TransformerAnimated

Causal Masking

A mask that hides future tokens during training and generation.

The idea

A language model must predict the next token without seeing it, so each position may only attend to itself and earlier positions. This also lets all positions be trained in parallel.

Watch it work

Press play, pause, or step through. Some animations have settings you can change.

causal maskt1t2t3t4t5t6t7t8t9t10t11t12
  • current token sees
  • other tokens see

Causal mask: a token can look at itself and earlier tokens but never the future, so the model can be trained to predict the next token.

query token:
1
sees:
1
1/12

Rows are the token asking (query); columns are the tokens it may look at (keys).

Step by step

  1. 1Compute attention scores
  2. 2Set scores for future positions to minus infinity
  3. 3Softmax makes those weights zero
  4. 4Each token only uses its past

Where it is used

All decoder-only models such as GPT and Llama.

Watch out for

Encoders such as BERT skip the mask and see both directions.