Best on a larger screen — the animation and controls have more room to breathe.
Inputs

Causal Masking & Autoregressive Training

Causal masking lets a Transformer train on every next-token position in a sequence at once without letting a position read its future. Training supplies the known sequence and compares each output with the following token. During ordinary autoregressive generation, the model must choose and append a new token before predicting another.

The whole sentence can sit in memory while each prediction sees only its permitted prefix. That distinction is the useful one: having the answers in the batch does not mean granting every position access to them. You can test the boundary by changing a future token and checking whether an earlier output changes.

How Causal Masking Works

Label input positions i and key positions j. At input position i, predict the token at i + 1. A causal attention mask allows j ≤ i and blocks j > i:

M[i,j] = 0       when j ≤ i
M[i,j] = −∞      when j > i
attention = softmax(QKᵀ / √d + M)

The mask is added before softmax. Since exp(−∞) = 0, blocked keys receive zero attention weight. Replacing their scores with zero would leave a positive numerator, exp(0) = 1. The diagonal stays visible: the current input token is part of the context for predicting the next one. This mask-and-shift pairing is the decoder dependency described in Attention Is All You Need.

All input tokens are known during training. Each row computes its attention from the same layer's input vectors, so rows can be evaluated together. Layers still run in dependency order. For a deep decoder, every cross-position path must respect causality; masking only the last layer cannot remove future information already mixed into earlier hidden states.

Teacher forcing means that the inputs come from the dataset even when a prediction is wrong. The model does not substitute its own guesses into the next position of this training pass. For each position, take the probability assigned to the actual next token, compute −ln(p), and average those losses. This is the negative log-likelihood of the autoregressive factorization, normalized by the number of predicted tokens:

Pr(sequence | BOS) = product of Pr(next token | its prefix)
L = mean of −ln Pr(actual next token | its prefix)

Every position uses the same parameters. Their gradient contributions combine into one parameter update; there is no separate model for each position.

Causal Masking & Autoregressive Training Step by Step

The default uses causal visibility and this symbolic sequence:

Input position01234
InputBOSABAB
Next-token targetABABEOS
  1. Align the targets. Remove EOS from the input row and BOS from the target row. The B at input position 2 is responsible for predicting A, the token at sequence position 3.
  2. Block future keys. Query 2 may read BOS, A, and itself, B. Its attention weights are approximately [0.280588, 0.280588, 0.438825, 0, 0]. These are weights over input positions, not probabilities over output tokens.
  3. Predict all five targets. The small model produces a distribution over [A, B, C, EOS] at each position. At position 2 it assigns about 0.175593 to the actual target A and 0.559143 to B. B wins the argmax, but the next training input remains the dataset's A.
  4. Test future independence. Compare the selected sequence against a reference whose last input is C. The prefix through position 2, its target A, and the parameters remain identical. The maximum difference between the earlier output distributions is exactly zero with the causal mask. Without the mask, the same C→B edit produces a difference of about 0.074192.
  5. Compute the training objective. The five losses are approximately 1.386294, 2.079778, 1.739587, 1.911317, and 2.068714 nats. Their mean is 1.837138 nats/token. The B prediction at position 2 is wrong, so the loss uses A's probability, not the winner's.
  6. Update one shared output head. Sum the contributions to the gradient of the mean loss. One SGD step with learning rate 0.25 changes the output head while attention stays fixed. Re-evaluating the same example gives 1.678507 nats/token. This is one small update, not a demonstration that the model has learned language.
  7. Generate with the updated parameters. Start with only [BOS, A, B]. The highest next-token probability is B, about 0.532694; append B. The longer prefix then predicts B again, with probability about 0.575930. The display stops after two choices. It has not selected EOS.

The five prefix rows show the layer inputs available to each query. Their prediction arrows move together because no row waits for another row’s prediction. The future-access arrow stops at the causal boundary; removing that boundary lets key 4 influence query 2.

The default update view follows one parameter. Choose One shared update to expand the full output-head matrix. Both views use the same computation.

The shaded upper triangle shows forbidden dependencies. The suffix comparison tests their effect. The final two lanes separate known dataset inputs, which can be scored together, from generated tokens, which must arrive before the following prediction can use them.

Why Training Can Be Parallel While Generation Is Sequential

Teacher-forced trainingOrdinary autoregressive generation
Available inputThe known dataset sequenceThe prompt and tokens already chosen
Output usedOne next-token distribution per training positionThe last available position's distribution
Source of the next inputDatasetDecoding choice appended to the prefix
ParametersUpdated after gradients are combinedFixed during the generation shown here

Parallel scoring means parallel work across positions within a layer, not constant-time training. Materializing single-head attention for n tokens of width d costs O(n²d) arithmetic; the output projection adds O(ndV) for output vocabulary size V. This implementation stores attention, hidden states, outputs, and the head: O(n² + nd + nV + dV) space. Its five positions do not establish a fivefold hardware speedup.

Edge Cases

  • First position: BOS can attend to itself. There is always a permitted key; no row is fully masked in this lesson.
  • Last input: every input key is at or before it, so the final attention row has no blocked future entries. EOS is its target, not an extra visible input.
  • C→C control: both mask settings produce zero difference because nothing changed. One unchanged output does not prove the implementation is causal.
  • Changed targets: editing input position 4 also changes the target at position 3. Earlier predictions may remain identical while the total sequence loss changes. The comparison fixes parameters and inspects position 2; it does not compare separately trained models.
  • Unmasked control: a lower loss can use information unavailable at generation time. It is not a fair improvement to the causal next-token objective.

Common Mistakes

  • Masking with zero scores. Apply the blocking mask before normalization with a value that contributes zero softmax mass.
  • Predicting an unshifted target. With the diagonal or residual path available, the input already contains that target and permits copying.
  • Feeding argmax back during teacher forcing. That changes the training procedure and loses the fixed-input parallel pass being taught here.
  • Confusing attention weights with token probabilities. The former sum over visible keys; the latter sum over the output vocabulary.
  • Masking only the final layer. Earlier layers must also prevent cross-position future access.

A Note on Simplification

This model uses five symbolic input tokens, fixed one-hot embeddings, identity Q/K/V projections, one attention head, and a residual addition. Its four-output head starts with a 1 at the coordinate matching each output symbol and zeros elsewhere. Only that head receives one SGD update. There is no positional encoding, normalization, feed-forward network, dropout, or trained language ability. Generation uses two greedy choices and recomputes prefixes without a KV cache.

A causal mask controls time-directed access. A padding mask excludes padding, while masked-language modeling hides selected input tokens for reconstruction; these are different operations. Packed sequence boundaries, padding losses, full-model optimization, and speculative decoding are outside this experiment. Continue to Next-Token Prediction for real GPT-2 outputs, or Softmax & Cross-Entropy for the loss gradient.