TExcelTAD
Home › NLP, Transformers & LLM Fine-Tuning › Self-Attention and Cross-Attention for Language

Self-Attention and Cross-Attention for Language

You already built attention: queries, keys and values, the d\sqrt{d} scaling, padding and causal masks and multi-head attention as a reshape, all checked against PyTorch in Attention from Scratch. This lesson asks the questions that matter once attention is applied to text. What do the heads of a trained language model actually compute? How does a decoder read from an encoder (cross-attention), and how does that differ from the self-attention and causal attention you know? And why is attention over long documents expensive, quadratically so? The math is in Dot-Product Attention and Causal Masking; here everything is code you can run.

What heads learn in language

Interpretability work on trained transformers keeps finding the same few head types, in models of very different sizes:

  • Previous-token heads put almost all their weight on position i−1i - 1. They copy "what came just before me" into the current position, which later layers need for anything that depends on word pairs.
  • Positional and delimiter heads attend to the first token, a [CLS] or [SEP], or a full stop. Such a head often acts as a "no-op": when nothing in the sentence is relevant, the softmax still has to put its weight somewhere, and a fixed sink token is a harmless place.
  • Syntactic heads link a word to its grammatical partner: a verb to its subject, a determiner to its noun, a pronoun to the noun it refers to, even across intervening words. Clark et al. (2019) found individual BERT heads that track specific dependency relations well above a position-only baseline.
  • Induction (copy) heads complete repeated patterns: if "fox ran" appeared earlier and the current token is "fox", attend to the token that followed the earlier "fox" and predict "ran". Olsson et al. (2022) linked these heads to in-context learning, the ability to continue patterns that appear only in the prompt.

An induction head needs two layers working together, and that is easy to see by building one by hand. Below, tokens and positions are one-hot vectors, and the attention weights are chosen, not learned. Head 1 is a previous-token head: its query for position ii is "position i−1i - 1" and its keys are positions, so it copies the previous token into a new slot of the residual stream. Head 2 is the induction head: its query is "my token", its keys are "the token before you" (the slot head 1 wrote), and its values are the key positions' own tokens. Both use the causal mask, so they only look backwards.

python · try it yourself
import numpy as np

def softmax(z):
    z = z - z.max(axis=-1, keepdims=True)
    e = np.exp(z)
    return e / e.sum(axis=-1, keepdims=True)

vocab = ["<s>", "red", "fox", "ran", "past", "old", "mill", "then", "slept"]
seq = ["<s>", "old", "fox", "ran", "past", "red", "mill", "then", "old", "fox", "ran", "past", "red"]
ids = np.array([vocab.index(w) for w in seq])
T, V = len(ids), len(vocab)
tok = np.eye(V)[ids]                      # (T, V) one-hot tokens
pos = np.eye(T)                           # (T, T) one-hot positions
causal = np.tril(np.ones((T, T), dtype=bool))

def head(Q, K, Vals, beta):
    S = np.where(causal, beta * Q @ K.T, -np.inf)
    A = softmax(S)
    return A @ Vals, A

# Head 1, previous-token head: query "position i" matches key "position i - 1".
shift = np.eye(T, k=-1)                   # row i has a 1 in column i - 1
prev_tok, A1 = head(pos @ shift, pos, tok, beta=10.0)
print("head 1, position 7 ('mill') attends to:", seq[int(A1[6].argmax())], round(float(A1[6].max()), 3))
print("head 1 argmax per position:", A1.argmax(axis=1).tolist())

# Head 2, induction head: query "my token" matches key "the token before you" (written by head 1),
# and copies the key position's token: "last time my token appeared, what came next?"
out2, A2 = head(tok, prev_tok, tok, beta=10.0)
pred = out2.argmax(axis=1)
for i in range(8, T):
    j = int(A2[i].argmax())
    print(f"pos {i + 1:2d} '{seq[i]}': looks at pos {j + 1} ('{seq[j]}', w={A2[i, j]:.2f}) -> predicts '{vocab[pred[i]]}'")
print("pos 4 'ran' (first time, nothing to copy):", np.round(A2[3, :4], 2).tolist())
head 1, position 7 ('mill') attends to: red 1.0
head 1 argmax per position: [0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
pos  9 'old': looks at pos 3 ('fox', w=1.00) -> predicts 'fox'
pos 10 'fox': looks at pos 4 ('ran', w=1.00) -> predicts 'ran'
pos 11 'ran': looks at pos 5 ('past', w=1.00) -> predicts 'past'
pos 12 'past': looks at pos 6 ('red', w=1.00) -> predicts 'red'
pos 13 'red': looks at pos 7 ('mill', w=1.00) -> predicts 'mill'
pos 4 'ran' (first time, nothing to copy): [0.25, 0.25, 0.25, 0.25]

Head 1 is a perfect shift: each position attends to the one before it (position 1 attends to itself; it has no predecessor). Head 2 does nothing useful the first time through the sequence: at position 4, "ran" has never been seen after any earlier token, so no key matches and the weights are uniform (0.25 over 4 keys). From position 9 on, the second "old fox ran past red" is predicted token by token, each time by attending to the position just after the earlier occurrence of the current token. Nothing in the weights knows these words; the mechanism copies any repeated sequence. Trained models learn soft versions of exactly this circuit. The factor beta=10 plays the role of a large dot product: it makes the softmax nearly one-hot, like a low temperature.

Self, causal and cross-attention

All three are the same function softmax⁡(QK⊤/d+M) V\operatorname{softmax}(Q K^\top / \sqrt{d} + M)\, V. They differ in where the queries and the keys come from and in the mask MM:

self-attention (encoder) keys q T x T, every key causal self-attention keys q T x T, keys j <= i cross-attention encoder keys dec q T_dec x T_enc green = allowed query-key pair, red = masked (score set to -inf)
Kind Queries from Keys and values from Mask Weight matrix Used in
Self-attention the sequence the same sequence padding only T×TT \times T encoders (BERT)
Causal self-attention the sequence the same sequence, positions j≤ij \le i causal + padding T×TT \times T decoders (GPT), the decoder of T5
Cross-attention the decoder states the encoder output (the "memory") source padding Tdec×TencT_{\text{dec}} \times T_{\text{enc}} encoder-decoder models (T5, BART, Whisper)

In cross-attention the decoder asks and the encoder answers: a target token being translated looks for the source tokens it corresponds to. The source is complete before decoding starts, so there is no causal mask over source positions; only padding in the source is masked. The causal structure comes from the decoder's own self-attention, which sits in the same block just before the cross-attention. The example builds all three with one function and checks those properties.

python · try it yourself
import numpy as np

def softmax(z):
    z = z - z.max(axis=-1, keepdims=True)
    e = np.exp(z)
    return e / e.sum(axis=-1, keepdims=True)

def attention(q_in, kv_in, Wq, Wk, Wv, mask=None):
    """Queries from q_in (Tq, E), keys and values from kv_in (Tk, E)."""
    Q, K, V = q_in @ Wq, kv_in @ Wk, kv_in @ Wv
    S = Q @ K.T / np.sqrt(Q.shape[-1])
    if mask is not None:
        S = np.where(mask, S, -np.inf)
    A = softmax(S)
    return A @ V, A

rng = np.random.default_rng(0)
E, S_len, T_len = 8, 5, 3
enc = rng.normal(size=(S_len, E))        # encoder output ("memory"): 5 source tokens
dec = rng.normal(size=(T_len, E))        # decoder states: 3 target tokens so far
Wq, Wk, Wv = (rng.normal(0, E ** -0.5, (E, E)) for _ in range(3))

y_self, A_self = attention(enc, enc, Wq, Wk, Wv)                    # encoder self-attention
causal = np.tril(np.ones((T_len, T_len), dtype=bool))
y_causal, A_causal = attention(dec, dec, Wq, Wk, Wv, causal)        # decoder self-attention
y_cross, A_cross = attention(dec, enc, Wq, Wk, Wv)                  # cross-attention
for name, A, y in [("self (encoder)", A_self, y_self), ("causal (decoder)", A_causal, y_causal),
                   ("cross (dec -> enc)", A_cross, y_cross)]:
    print(f"{name:18s} weights {A.shape}  output {y.shape}  rows sum to 1: {np.allclose(A.sum(1), 1)}")
print("cross weights of target token 1:", np.round(A_cross[0], 3).tolist())

# Source padding: the last 2 source positions are padding, so they are removed as KEYS.
src_ok = np.array([True, True, True, False, False])
_, A_pad = attention(dec, enc, Wq, Wk, Wv, src_ok[None, :])
print("with source padding:", np.round(A_pad[0], 3).tolist())

# No causal mask is needed in cross-attention: the whole source is known before decoding starts.
# Changing a LATER target token changes nothing for earlier target tokens' cross-attention:
dec2 = dec.copy(); dec2[2] += 3.0
print("cross output of tokens 1-2 unchanged:", np.allclose(attention(dec2, enc, Wq, Wk, Wv)[0][:2], y_cross[:2]))
# ...but changing a source token changes every target token's output.
enc2 = enc.copy(); enc2[4] += 3.0
print("changing source token 5 moves all 3 outputs:",
      [not np.allclose(a, b) for a, b in zip(attention(dec, enc2, Wq, Wk, Wv)[0], y_cross)])
self (encoder)     weights (5, 5)  output (5, 8)  rows sum to 1: True
causal (decoder)   weights (3, 3)  output (3, 8)  rows sum to 1: True
cross (dec -> enc) weights (3, 5)  output (3, 8)  rows sum to 1: True
cross weights of target token 1: [0.037, 0.626, 0.078, 0.241, 0.017]
with source padding: [0.05, 0.844, 0.106, 0.0, 0.0]
cross output of tokens 1-2 unchanged: True
changing source token 5 moves all 3 outputs: [True, True, True]

The shapes say it all: the cross-attention weights are 3×53 \times 5 (one row per target token, one column per source token), and the output has one vector per target token, 3×83 \times 8. With the last two source positions marked as padding, their weights become 0 and the rest are renormalised (0.626 on source token 2 becomes 0.844). Changing the third target token leaves the first two targets' cross-attention output untouched, because in cross-attention each query is computed independently; changing source token 5 moves all three. In a real layer, WQW_Q acts on decoder states and WK,WVW_K, W_V on encoder states, and they are separate weights from those of the self-attention sub-layer. The encoder-decoder lesson assembles a full model from these parts.

The lab: a causal row at low temperature

The lab is the "the cat sat on the mat" heatmap from the deep-learning course, now with the causal mask on, as in a decoder, and at temperature T=0.5T = 0.5. It starts on query 6, "mat". The last token of a sequence is the one row the causal mask never changes, since nothing lies in its future: its weights are 0.348 on "cat", 0.341 on "sat" and 0.302 on itself, with an entropy of 1.66 bits. Now step through the queries. Row 1 is always 1.000 on itself: under a causal mask the first token has nothing else to look at. Row 5, the second "the", splits its weight equally between itself and the first "the" (0.315 each): with no positional information, identical tokens give identical keys, the toy version of a "duplicate token" head. Raise TT to 2 and every row flattens; lower it to 0.1 and each row becomes a hard argmax.

Weights A (row = query)key →thecatsatonthemat1 the2 cat3 sat4 on5 the6 mat1.00·····0.001.00····0.000.090.91···0.230.140.170.46··0.320.040.050.280.32·0.000.350.340.010.000.30row sum1.0001.0001.0001.0001.0001.000T = 0.5; d = 4; causal mask: later keys get weight 0Query "mat" (row 6)keyweightthes = 0.86 → 0.001cats = 3.62 → 0.348sats = 3.60 → 0.341ons = 1.64 → 0.007thes = 0.86 → 0.001mats = 3.54 → 0.302

The quadratic cost

The score matrix has one entry per (query, key) pair: T2T^2 numbers per head, per layer, per sequence. Computing it costs about 2T2d2T^2 d floating-point operations for QK⊤Q K^\top and the same again for the product with VV:

memory∝h⋅T2,FLOPs≈4 T2d per head\text{memory} \propto h \cdot T^2, \qquad \text{FLOPs} \approx 4\, T^2 d \text{ per head}

The projections and the MLP cost O(Td2)O(T d^2), linear in TT, so for short texts they dominate and attention is cheap. For long documents the T2T^2 term wins. The example measures the score matrix's real size and times attention in NumPy.

python · try it yourself
import time
import numpy as np

def softmax(z):
    z = z - z.max(axis=-1, keepdims=True)
    e = np.exp(z)
    return e / e.sum(axis=-1, keepdims=True)

rng = np.random.default_rng(0)
d = 64
times = {}
for T in (256, 512, 1024, 2048):
    Q, K, V = (rng.normal(size=(T, d)).astype(np.float32) for _ in range(3))
    t0 = time.perf_counter()
    S = (Q @ K.T / np.sqrt(d)).astype(np.float32)   # (T, T): the part that grows quadratically
    out = softmax(S) @ V
    times[T] = time.perf_counter() - t0
    flops = 2 * T * T * d * 2             # Q K^T and A V, multiply-adds counted as 2
    print(f"T = {T:4d}: scores {S.shape}, {S.nbytes / 2**20:5.2f} MiB float32, {flops / 1e9:.2f} GFLOP")
print("doubling T multiplies the score memory by", 2048 * 2048 // (1024 * 1024))
print("time(2048) > 4 x time(512):", times[2048] > 4 * times[512])

# A real model keeps one such matrix per head, layer and sequence (unless a fused kernel avoids it):
T, heads, layers = 8192, 32, 32
print(f"T = {T}, {heads} heads, one layer: {T * T * heads * 2 / 2**30:.0f} GiB of float16 scores")
T =  256: scores (256, 256),  0.25 MiB float32, 0.02 GFLOP
T =  512: scores (512, 512),  1.00 MiB float32, 0.07 GFLOP
T = 1024: scores (1024, 1024),  4.00 MiB float32, 0.27 GFLOP
T = 2048: scores (2048, 2048), 16.00 MiB float32, 1.07 GFLOP
doubling T multiplies the score memory by 4
time(2048) > 4 x time(512): True
T = 8192, 32 heads, one layer: 4 GiB of float16 scores

Doubling TT multiplies the score matrix by 4, and from 512 to 2048 tokens (4 times longer) the measured time grows by more than 4 times, as T2T^2 predicts. At 8192 tokens with 32 heads a single layer's float16 scores would need 4 GiB. Production kernels such as FlashAttention compute the softmax block by block and never store the full matrix, which removes the memory problem but not the O(T2)O(T^2) compute. Sparse, sliding-window and linear-attention variants trade some quality for lower cost; many long-context models instead combine full attention with a cache of past keys and values (inside a decoder-only LM).

Attention in a real BERT

Hand-built heads are tidy; trained heads are messy. The recorded example loads the small BERT cached in the course image (2 layers, 2 heads, hidden size 128) and asks for its attention weights with output_attentions=True. Since Transformers may run attention with a fused kernel that does not return weights, the model is loaded with attn_implementation="eager". For each head it reports the mean weight on the previous token, on the token itself and on [CLS] plus [SEP], and, for every word, the token it attends to most.

python · try it yourself
import torch
from transformers import AutoTokenizer, AutoModel
from transformers.utils import logging
logging.set_verbosity_error()

name = "google/bert_uncased_L-2_H-128_A-2"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModel.from_pretrained(name, attn_implementation="eager").eval()   # eager: weights can be returned
enc = tok("the dog that chased the cat barked at the mailman .", return_tensors="pt")
words = tok.convert_ids_to_tokens(enc["input_ids"][0])
with torch.no_grad():
    out = model(**enc, output_attentions=True)
print("tokens:", words)
print("layers:", len(out.attentions), " shape per layer:", tuple(out.attentions[0].shape))   # (B, heads, T, T)

T = len(words)
for layer, A in enumerate(out.attentions):
    for h in range(A.shape[1]):
        a = A[0, h]
        prev = a[torch.arange(1, T), torch.arange(0, T - 1)].mean().item()   # weight on token i-1
        self_w = a.diagonal().mean().item()
        special = (a[:, 0] + a[:, -1]).mean().item()                       # on [CLS] + [SEP]
        top = [words[j] for j in a.argmax(dim=-1).tolist()]
        print(f"layer {layer} head {h}: prev {prev:.2f} self {self_w:.2f} [CLS]+[SEP] {special:.2f}")
        print("   most attended:", " ".join(f"{w}->{t}" for w, t in zip(words[1:-1], top[1:-1])))
tokens: ['[CLS]', 'the', 'dog', 'that', 'chased', 'the', 'cat', 'barked', 'at', 'the', 'mail', '##man', '.', '[SEP]']
layers: 2  shape per layer: (1, 2, 14, 14)
layer 0 head 0: prev 0.05 self 0.36 [CLS]+[SEP] 0.41
   most attended: the->[CLS] dog->dog that->[CLS] chased->chased the->[CLS] cat->cat barked->barked at->[CLS] the->[CLS] mail->mail ##man->##man .->[CLS]
layer 0 head 1: prev 0.09 self 0.04 [CLS]+[SEP] 0.15
   most attended: the->dog dog->##man that->barked chased->dog the->dog cat->##man barked->dog at->[SEP] the->mail mail->##man ##man->mail .->at
layer 1 head 0: prev 0.32 self 0.12 [CLS]+[SEP] 0.53
   most attended: the->[CLS] dog->[CLS] that->[CLS] chased->that the->[CLS] cat->the barked->cat at->[CLS] the->[CLS] mail->the ##man->[CLS] .->[CLS]
layer 1 head 1: prev 0.07 self 0.13 [CLS]+[SEP] 0.48
   most attended: the->[CLS] dog->[CLS] that->[CLS] chased->the the->[CLS] cat->barked barked->at at->[CLS] the->[CLS] mail->##man ##man->[CLS] .->[CLS]

How to read it:

  • out.attentions is a tuple with one tensor per layer, each (batch, heads, T, T): rows are queries, columns are keys, and every row sums to 1.
  • Layer 1, head 0 is the closest thing to a previous-token head in this tiny model: 0.32 of each token's weight goes to the token before it on average, and "chased" attends most to "that", "cat" to "the", "barked" to "cat", "mail" to "the".
  • Layer 0, head 0 mostly attends to the token itself (0.36) or to [CLS]/[SEP] (0.41), the "sink" pattern.
  • Layer 0, head 1 is the most content-driven: "the" looks at "dog", "chased" looks back at its subject "dog", "barked" at "dog" too (the main clause's verb and subject, across the relative clause "that chased the cat"), and the two halves of "mail ##man" look at each other.
  • Both layer-1 heads send about half their weight to [CLS] and [SEP].

This BERT has 4 heads in total; BERT-base has 144 (12 layers of 12), and the clean syntactic heads in the literature were found among those. Treat a single sentence as an anecdote: claims about a head need many sentences and a baseline (for example, "always attend to the previous token"). Attention weights also show where information is read, not how much it matters for the output, so "the model attends to X" is not an explanation of a prediction.

Pitfalls

  • Reading attention maps as explanations. High weight does not mean high influence: the value vector may be tiny, and later layers may ignore the result. Use ablations or gradient-based attribution for claims about causes.
  • Asking a fused kernel for weights. SDPA and FlashAttention kernels do not materialise the weights. Load with attn_implementation="eager" when you need output_attentions=True (slower, more memory).
  • A causal mask in cross-attention. The whole source is available; masking it causally hides the end of the input sentence from every early target token. Only the decoder's self-attention is causal.
  • Swapping the inputs of cross-attention. Queries come from the decoder, keys and values from the encoder. The reverse still runs if the widths match, but returns one vector per source token instead of per target token.
  • Forgetting the source padding mask in cross-attention. Padding in the source batch then leaks into every target token.
  • Budgeting long contexts by parameters only. Attention memory and compute grow with T2T^2 (without a fused kernel) and the KV cache with TT, independently of the number of parameters.

Practice

  1. In the induction-head example, append "mill" to seq (after the last "red") and rerun. What does position 14 predict, and why?
Answer

"then". At position 14 the current token is "mill"; head 2 finds the key whose previous token is "mill", which is position 8 ("then", the token after the first "mill"), and copies its token. The induction head keeps continuing the earlier pattern as long as it repeats.

  1. In the cross-attention example, what are the shapes of the weights and the output if the source has 50 tokens, the target 7, and E=8E = 8? How many weights does cross-attention compute for a batch of 16 such pairs with 8 heads?
Answer

Weights 7×507 \times 50, output 7×87 \times 8 (one vector per target token). For the batch: 16⋅8⋅7⋅50=44,80016 \cdot 8 \cdot 7 \cdot 50 = 44{,}800 weights.

  1. In the lab, set the mask to causal, T=1T = 1 and query 4, "on". Compare its row with the same row without the mask. Which keys lost their weight, and where did it go?
Answer

With the causal mask, "on" can see "the", "cat", "sat" and itself: 0.244, 0.193, 0.213 and 0.350. The later "the" and "mat" are masked; the weight they had without the mask is redistributed proportionally over the four allowed keys, because the softmax renormalises over what is left.

  1. A model has 24 layers and 16 heads and runs on sequences of 4096 tokens in float16. How much memory would the attention scores of one sequence take if every layer stored them at once? Why does a fused kernel help so much here?
Answer

24⋅16⋅40962⋅224 \cdot 16 \cdot 4096^2 \cdot 2 bytes =12,884,901,888= 12{,}884{,}901{,}888 bytes, 12 GiB. A fused kernel computes the softmax in tiles and keeps only the outputs, so the stored memory becomes O(Td)O(T d) per head instead of O(T2)O(T^2); the backward pass recomputes the tiles instead of storing them.

Test yourself

In cross-attention of an encoder-decoder model, where do queries, keys and values come from?

  1. All three from the encoder output
  2. Queries from the decoder states, keys and values from the encoder output
  3. Queries from the encoder, keys and values from the decoder
  4. All three from the decoder states

Which mask does cross-attention normally use?

  1. A causal mask over source positions
  2. Only the source padding mask
  3. No mask at all, even with padding
  4. A causal mask over target positions

An induction head predicts the next token by…

  1. attending to the previous position only
  2. finding an earlier occurrence of the current token and copying the token that followed it
  3. averaging all earlier tokens
  4. attending to [CLS]

Doubling the context length TT multiplies the size of one head's attention score matrix by…

  1. 2
  2. 4
  3. 8
  4. it does not change

In the recorded BERT example, why is the model loaded with attn_implementation="eager"?

  1. Eager attention is faster
  2. Fused attention kernels do not return the weights that output_attentions=True asks for
  3. The tiny BERT has no other implementation
  4. It turns off dropout