In an encoder–decoder transformer with dmodel=512 and 8 heads, a decoder layer cross-attends to an encoder output of length S=50 while it has T=20 target tokens. What are the shapes of Q, K and V 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 (T×dmodel) while keys and values come from the encoder (S×dmodel), so the score matrix is T×S per head, not square.

Steps

  1. Shapes. With model width d=dmodel=512, decoder states T×512 give Q=XdecWQ of size 20×512. Encoder output gives K=XencWK and V=XencWV, each 50×512.
  2. Per head dk=512/8=64. Scores QK⊤/64 are 20×50 per head, so 8×20×50=8000 entries over the layer. Softmax over the S source positions gives rows summing to 1. Multiplying by V (size 50×64) gives 20×64 per head, then 20×512 after concatenation and the output projection.
  3. Parameters. WQ,WK,WV,WO are each 512×512, so 4×5122=1,048,576, the same as self-attention. They do not depend on S or T.
  4. FLOPs (floating-point operations, counting 2 per multiply–add). Q projection 2Td2=10.5M, K and V projections 2Sd2=26.2M each, output projection 10.5M, total 73.4M. The two attention matrix products cost 2TSd=1.02M each, so about 2.0M together. The K and V projections cost the most at these lengths.
  5. Caching. K and V 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.
  6. 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

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 h1=(1,0), h2=(0,1) and h3=(−1,1). The decoder state is s=(1,1). Bahdanau (additive) attention scores each state as ej=v⊤tanh⁡(Wss+Whhj), here with Ws=Wh=I and v=(1,−1). 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 7-billion-parameter model with mixed-precision Adam under (a) full fine-tuning, (b) LoRA with 20 million trainable adapter parameters on an fp16 base, and (c) QLoRA with a 4-bit NormalFloat base? How do NF4, double quantisation and paged optimisers work, and what is the trade-off?