Attention ignores order
Shuffle the rows of and the rows of , and are shuffled the same way. Each query still meets the same set of keys, so each output row is unchanged, and it lands in the shuffled position. Self-attention is permutation equivariant: it treats the input as a set, not a sequence. The cell checks this with random matrices.Encoders and decoders
An encoder reads a whole input at once, and every token may attend to every other token, in both directions. BERT and the vision transformer are encoders. Their outputs are representations of the input, used for classification or as input to another model. A decoder generates a sequence one token at a time, and each new token is predicted from the tokens before it. During training the whole target sequence is available, and all positions are trained in parallel. Token must then be prevented from seeing tokens , otherwise it could copy the answer. The causal mask does this: before the softmax, the score of every key that comes after the query is set to , so its weight becomes zero. GPT and the language model inside every vision language model are decoders. The cell builds the mask and checks its effect: changing the last token changes the last output, and none of the outputs before it.Cross-attention
In cross-attention the queries come from one sequence and the keys and values from another. Let () be the sequence that asks and () the sequence it reads from: The weight matrix is : one row per query, one column per key. The output has one row per query, , whatever the length of . Each row is a mixture of the values of , chosen by the query of the corresponding row of . The original transformer used cross-attention to translate (Vaswani et al., 2017). The encoder reads the source sentence, and each block of the decoder has a self-attention layer with a causal mask over the target words written so far, followed by a cross-attention layer whose queries come from those target words and whose keys and values come from the encoder outputs. The decoder decides which source words to look at while it writes each target word. Vision language models use the same layer to connect an image to text. The image encoder produces a sequence of patch features , and a sequence reads from them. In Flamingo, the text tokens are , through cross-attention layers inserted into a frozen language model (Alayrac et al., 2022). In BLIP-2, is a small set of learned query vectors (Li et al., 2023): 32 queries read from the 257 features of the image encoder and return 32 outputs, a summary of fixed size that is then passed to the language model. The decoder of the Segment Anything Model uses cross-attention in both directions between prompt tokens and the image embedding. The cell builds the BLIP-2 pattern on a small scale: 4 learned queries attend to 64 image features and return 4 vectors.Encoding position
A transformer gets order back by adding information about position to its input or to its attention scores. Three methods are in common use.Learned absolute embeddings
The simplest is a table of learned vectors, one per position, added to the token embeddings: , with . BERT, GPT-2 and the vision transformer use it. It is flexible, but the model has no vector for a position beyond , and nothing in it says that positions 5 and 6 are neighbors. That has to be learned.Sinusoidal encodings
The original transformer used a fixed encoding instead (Vaswani et al., 2017). Position gets a vector whose entries are sines and cosines of at geometrically spaced frequencies: The first dimensions oscillate quickly and tell neighboring positions apart. The last ones change slowly and tell the beginning of a long sequence from its end, like the hands of a clock. Each pair of dimensions is a point on a circle that turns by a fixed angle per step, so the encoding of position is a fixed rotation of the encoding of position . As a consequence, the dot product depends only on the offset , not on .
Rotary position embeddings
Most current language models, including Llama, Qwen and SmolLM2, use rotary position embeddings (RoPE, arXiv:2104.09864). Instead of adding a vector to the input, RoPE rotates the query and the key inside every attention layer. The dimensions of a query at position are grouped into pairs, and pair is rotated by the angle , with the same frequencies as the sinusoidal encoding. The key at position is rotated by . A rotation by followed by the inverse of a rotation by is a rotation by , so The attention score depends on the content of the two tokens and on their offset , and not on where the pair sits in the sequence. Position enters exactly where it is used, in the comparison of a query with a key. The cell checks the property: the same query and key give the same score at positions (3, 7) and (103, 107).Positions in two dimensions
Image patches have a row and a column. The vision transformer numbers its patches row by row and learns one embedding per number, and the learned embeddings end up encoding the 2D layout. The vision transformer section shows this, and shows how the table is interpolated when the image size changes. Some vision language models apply RoPE to the row and the column separately. Qwen2-VL splits the rotary dimensions into three groups, for time, height and width, so that the same mechanism handles text, images and video (arXiv:2409.12191).Exercises
- Add the sinusoidal encodings to in the permutation test above. Is the self-attention output still permutation equivariant? Explain.
- Implement a single decoder block for translation: causal self-attention over the target, then cross-attention to an encoder output, then an MLP, each with a residual connection and layer norm. Check the output shapes for a source of 10 tokens and a target of 7.
- In the BLIP-2 example, compute the attention weights of each of the 4 queries over the 64 image features and check that every row sums to one. How many tokens would the language model receive from a LLaVA-style MLP connector for the same 64 features?
- Show that the sinusoidal encoding of position is a linear function of the encoding of position : find the matrix that maps the pair to .
Key references
Vaswani et al. introduced the encoder and decoder, cross-attention and the sinusoidal encoding (Vaswani et al., 2017). Flamingo (Alayrac et al., 2022) and BLIP-2 (Li et al., 2023) use cross-attention to connect an image encoder to a language model.References
- Alayrac, J., Donahue, J., Luc, P., Miech, A., Barr, I., et al. (2022). Flamingo: a Visual Language Model for Few-Shot Learning. arXiv [cs.CV].
- Li, J., Li, D., Savarese, S., Hoi, S. (2023). BLIP-2: Bootstrapping language-image pre-training with frozen image encoders and large language models. arXiv [cs.CV].
- Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., et al. (2017). Attention Is All You Need. arXiv [cs.CL].
Found an error on this page? Report an issue.

