Masked attention is self-attention that prevents a sequence position from accessing later positions. Standard self-attention lets each token attend to every token; a causal attention mask instead leaves each token able to attend only to itself and earlier tokens. In a transformer decoder, this lets the model predict the next token without seeing future input tokens. section 4.1.1 section 2.1.2
To use the mask for next-token training:
- Prepare an input sequence and a target shifted one position ahead. For a caption, [<start>, two, bears, fight] is paired with [two, bears, fight, <end>]. section 4.1.1
- Apply the causal mask to self-attention weights, hiding positions above the main diagonal. At each input position, the decoder can use its current token and earlier tokens, but not later ones. section 4.1.1
- Compare the decoder’s predictions with the shifted targets using cross-entropy loss. The targets supply the training signal; they are not fed to the decoder as its input sequence. section 4.1.2
Figure 4.3 How the causal attention mask works
The causal-mask diagram contrasts attention to every sequence position with attention restricted to the current position and those before it. section 4.1.1
In an encoder–decoder transformer, masked multi-head self-attention is the first sublayer of each decoder block. Cross-attention then connects the decoder state to the encoder output, followed by a feed-forward sublayer. For image captioning, the encoder supplies image embeddings while masked self-attention keeps caption generation dependent on preceding caption tokens. Word embeddings and positional encodings form the decoder input. section 4.1.2 section 4.3.2
What each caption position may use
With [<start>, two, bears, fight] as input, the first position uses <start> to predict two. The next uses <start> and two to predict bears, without accessing the later input tokens. The final position can use the full input sequence to predict <end>. The same restriction applies within the decoder layers during training. section 4.1.1 section 4.1.2





