Skip to main content
Open In Colab The earlier pages of this chapter built self-attention. Every token of a sequence XX (T×dT \times d) is projected into a query, a key and a value, Q=XWq,K=XWk,V=XWv,Q = XW^q, \qquad K = XW^k, \qquad V = XW^v, and each output row is a weighted sum of the values, with weights given by how well that row’s query matches every key: Attention(Q,K,V)=softmax ⁣(QK⊤dk)V.\text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right) V. Two questions were left open. The first is about order: nothing in this formula knows which token came first. The second is about sources: QQ, KK and VV all come from the same XX, but a translation model must relate an English sentence to a French one, and a vision language model must relate text to an image. This section answers both. It covers the causal mask that separates a decoder from an encoder, cross-attention between two sequences, and the ways of encoding position. The vision chapters rely on all three: a vision transformer is an encoder with learned position embeddings, and the connectors of vision language models use cross-attention.

Attention ignores order

Shuffle the rows of XX and the rows of QQ, KK and VV 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.
“dog bites man” and “man bites dog” contain the same tokens, so without extra information a transformer would produce the same outputs for both, only reordered. The model needs the position of each token as part of its input. The last part of this section shows how it gets it.

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 ii must then be prevented from seeing tokens i+1,…,Ti+1, \dots, T, 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 −∞-\infty, so its weight becomes zero. Mij={0j≤i−∞j>i,softmax ⁣(QK⊤dk+M)V.M_{ij} = \begin{cases} 0 & j \le i \\ -\infty & j > i \end{cases}, \qquad \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}} + M\right) V. 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.
The weights above the diagonal are zero, and each row still sums to one over the tokens it may see.

Cross-attention

In cross-attention the queries come from one sequence and the keys and values from another. Let YY (Ty×dT_y \times d) be the sequence that asks and ZZ (Tz×dT_z \times d) the sequence it reads from: Q=YWq,K=ZWk,V=ZWv,softmax ⁣(QK⊤dk)V.Q = YW^q, \qquad K = ZW^k, \qquad V = ZW^v, \qquad \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right) V. The weight matrix is Ty×TzT_y \times T_z: one row per query, one column per key. The output has one row per query, Ty×dT_y \times d, whatever the length of ZZ. Each row is a mixture of the values of ZZ, chosen by the query of the corresponding row of YY. 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 ZZ, and a sequence YY reads from them. In Flamingo, the text tokens are YY, through cross-attention layers inserted into a frozen language model (Alayrac et al., 2022). In BLIP-2, YY 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.
The four outputs keep their shape when the image produces 256 features instead of 64. The queries decide how many tokens leave the layer, and the image decides only what they contain. LLaVA connects the two models differently: a small MLP maps each image feature to a token of the language model, so the number of image tokens equals the number of patches, and the language model’s own self-attention relates them to the text. The LLaVA deep dive compares the two designs.

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: X+PX + P, with P∈RTmax⁡×dP \in \mathbb{R}^{T_{\max} \times d}. BERT, GPT-2 and the vision transformer use it. It is flexible, but the model has no vector for a position beyond Tmax⁡T_{\max}, 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 tt gets a vector whose entries are sines and cosines of tt at geometrically spaced frequencies: pt,2i=sin⁡ ⁣(t100002i/d),pt,2i+1=cos⁡ ⁣(t100002i/d),i=0,…,d/2−1.p_{t, 2i} = \sin\!\left(\frac{t}{10000^{2i/d}}\right), \qquad p_{t, 2i+1} = \cos\!\left(\frac{t}{10000^{2i/d}}\right), \qquad i = 0, \dots, d/2 - 1. 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 t+kt + k is a fixed rotation of the encoding of position tt. As a consequence, the dot product pt⋅pt+k\mathbf{p}_t \cdot \mathbf{p}_{t+k} depends only on the offset kk, not on tt.
Output from cell 7 The dot product with position 64 is largest at 64 and falls off on both sides, so nearby positions have similar encodings without any training.

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 qm\mathbf{q}_m at position mm are grouped into pairs, and pair ii is rotated by the angle mθim\theta_i, with the same frequencies θi=10000−2i/d\theta_i = 10000^{-2i/d} as the sinusoidal encoding. The key kn\mathbf{k}_n at position nn is rotated by nθin\theta_i. A rotation by mθm\theta followed by the inverse of a rotation by nθn\theta is a rotation by (n−m)θ(n-m)\theta, so (Rmq)⊤(Rnk)=q⊤Rn−m k.(R_m \mathbf{q})^\top (R_n \mathbf{k}) = \mathbf{q}^\top R_{n-m}\, \mathbf{k}. The attention score depends on the content of the two tokens and on their offset n−mn - m, 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).
The first two scores are equal because the offset is 4 in both cases. The third uses an offset of 5 and differs.

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

  1. Add the sinusoidal encodings to XX in the permutation test above. Is the self-attention output still permutation equivariant? Explain.
  2. 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.
  3. 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?
  4. Show that the sinusoidal encoding of position t+kt + k is a linear function of the encoding of position tt: find the 2×22 \times 2 matrix that maps the pair (pt,2i,pt,2i+1)(p_{t,2i}, p_{t,2i+1}) to (pt+k,2i,pt+k,2i+1)(p_{t+k,2i}, p_{t+k,2i+1}).

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.