liveBook · Manning

Masked attention

As explained in Deep Learning with R, Third Edition

Causal attention is attention constrained so that each position can use information from past and present positions but not future positions.

Masked attention restricts self-attention so each position uses only permitted context. Causal attention allows a token to attend to itself and earlier tokens, preventing future-token leakage during next-token prediction. section 15.3.3

Lower-triangular causal mask

For five target positions, a causal mask is: 1 0 0 0 0; 1 1 0 0 0; 1 1 1 0 0; 1 1 1 1 0; 1 1 1 1 1. Row i specifies which positions token i may attend to, reproducing one-directional information flow without a bidirectional shortcut. section 15.3.3

Use causal masking when:

  • Training a Transformer decoder to predict the next word without exposing the label it must predict. section 15.3.3
  • Generating text autoregressively, where each new position may depend on past and present tokens but not future tokens. section 16.2.3
  • Calling Keras MultiHeadAttention with use_causal_mask to create the required lower-triangular restriction. section 15.3.3

The mask also enables efficient generation: because future positions cannot change past key and value vectors, implementations can cache those vectors and compute one position at a time. section 16.2.3

How Deep Learning with R, Third Edition covers it

How deep it goes
Explains information flow, displays the triangular mask, names the Keras option, and connects masking to key-value caching.
Examples
Uses a lower-triangular mask, Transformer translation decoding, and mini-GPT text generation as concrete examples.
What it assumes
Assumes familiarity with attention and sequence prediction while contrasting causal information flow with bidirectional attention and RNN decoding.
What you can do after
Apply it via Keras MultiHeadAttention and reason about cached autoregressive generation.
How it connects
Connects causal attention to self-attention, Transformer decoders, RNNs, cross-attention, language modeling, and key-value caching.

Also explained in

Compare how 6 books explain masked attention →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Deep Learning with R, Third Edition. The section links point to the parts of the book it draws on.