In an encoder–decoder transformer with and 8 heads, a decoder layer cross-attends to an encoder output of length while it has target tokens. What are the shapes of , and and of the score matrix, which projections cost the most, and why does cross-attention need no causal mask?
Sequence models and transformers, Transformers
Level L3 Intermediate. Length Medium. Nature Mat Mathematical.
What's being asked
Whether you can track tensor shapes in cross-attention, where queries and keys come from sequences of different length.
Key idea
In cross-attention, queries come from the decoder () while keys and values come from the encoder (), so the score matrix is per head, not square.
Steps
- Shapes. With model width , decoder states give of size . Encoder output gives and , each .
- Per head . Scores are per head, so entries over the layer. Softmax over the source positions gives rows summing to . Multiplying by (size ) gives per head, then after concatenation and the output projection.
- Parameters. are each , so , the same as self-attention. They do not depend on or .
- FLOPs (floating-point operations, counting per multiply–add). projection M, and projections M each, output projection M, total M. The two attention matrix products cost M each, so about M together. The and projections cost the most at these lengths.
- Caching. and depend only on the encoder output, so they are computed once and reused for every decoding step. Only the new query is computed per step.
- No causal mask. The whole source sentence is available in advance, so every target position may look at every source position. A padding mask is still needed if the batch contains padded source positions. Causality is needed only in the decoder's self-attention.
Common mistakes
- Making and have rows. Their length is the source length .
- Saying the score matrix is square. It is per head.
- Applying a causal mask to cross-attention, which would stop the decoder from using later source words.
- Forgetting the padding mask on the source side.
How long your answer should be
Half a page with a shape table; 4 minutes.
Read this
Previous in Sequence models and transformers: An encoder gives states , and . The decoder state is . Bahdanau (additive) attention scores each state as , here with and . Compute the attention weights and the context vector, and say when additive attention is preferred to dot-product scoring?
Next in Sequence models and transformers: How much GPU memory do model states take when fine-tuning a -billion-parameter model with mixed-precision Adam under (a) full fine-tuning, (b) LoRA with million trainable adapter parameters on an fp16 base, and (c) QLoRA with a -bit NormalFloat base? How do NF4, double quantisation and paged optimisers work, and what is the trade-off?