GenAI Course · Module 5 · Session 19

Advanced Attention

⏱ 14 min read🎯 Intermediate🖼 4 diagrams🧪 2 live demos🐍 Python code

Attention is powerful, but it has a price: every token looks at every other token. Double the text, and the work becomes four times bigger. In this session, let us see how real models handle this, look at attention on real sentences, and understand what goes wrong when the context becomes very long.

In this session

  • Why attention cost grows with length² (with a live calculator)
  • Efficient variants: sliding window, sparse, FlashAttention, MQA and GQA
  • Attention maps on real sentences, and how to see them in code
  • What breaks as context grows: memory, “lost in the middle”, position limits

01The n² problem

For n tokens, attention builds an n × n table of scores, in every head of every layer. So the work grows with n²:

2× the tokens → 4× the score table. 10× the tokens → 100×.
Demo · Context length calculatorExample: Llama 3.1 8B (32 layers, 8 KV heads × 128, FP16)
Full score table = n × n × 2 bytes, per head, per layer, if stored. KV cache = 128 KB per token for this model.
🤝

Like everyone at a function shaking hands with everyone else. With 10 guests it’s quick. With 1,000 guests, it takes forever, because the number of handshakes grows much faster than the number of guests.

02Efficient attention variants

Researchers have found many ways to make attention cheaper. Some approximate it (look at fewer pairs), and some compute it exactly but smarter.

Coloured cells = pairs that are computed. Sliding window and sparse patterns skip most pairs.
TechniqueIdea in one lineExact?Used in
Sliding-window (local)Each token looks only at the last W tokensNo, approximateLongformer, Mistral 7B (window 4,096)
Sparse + global tokensLocal window plus a few tokens that see everythingNo, approximateLongformer, BigBird
Linear / low-rankApproximate the n × n table with smaller matricesNo, approximateLinformer, Performer
FlashAttentionCompute attention in small tiles inside fast GPU memory, never storing the full tableYesMost modern training and serving stacks
Multi-query (MQA)All heads share one set of keys and valuesYes (different architecture)PaLM, Falcon
Grouped-query (GQA)Groups of query heads share keys and valuesYes (different architecture)Llama 2 70B, Llama 3, Mistral

MHA vs GQA vs MQA

During generation, the model stores the keys and values of all previous tokens (the KV cache). With many heads, this cache becomes huge. GQA and MQA let several query heads share the same keys and values:

Llama 3 8B uses GQA: 32 query heads share 8 key-value heads, so the KV cache is 4× smaller than full multi-head attention.
FlashAttention is the big win in practice. It gives the same answer as normal attention but avoids writing the n × n table to slow GPU memory, so it is much faster and uses memory that grows only linearly with length. In PyTorch, torch.nn.functional.scaled_dot_product_attention uses such fused kernels automatically when available.

03Attention on real sentences

Change one word at the end of the sentence and see how the attention of “it” moves:

Demo · Attention heatmap

You can see real attention weights from any Hugging Face model by asking for them:

see_attention.py
from transformers import AutoTokenizer, AutoModel

tok = AutoTokenizer.from_pretrained("bert-base-uncased")
model = AutoModel.from_pretrained("bert-base-uncased", output_attentions=True)

inputs = tok("The animal didn't cross the street because it was too tired", return_tensors="pt")
out = model(**inputs)

print(len(out.attentions))        # one entry per layer
print(out.attentions[0].shape)    # (batch, heads, tokens, tokens)
12 torch.Size([1, 12, 15, 15])

For a visual, interactive view of every head, try the open-source BertViz library (pip install bertviz) in a notebook.

Careful when reading attention maps. High attention does not always mean “this word caused the answer”. Attention is one useful window into the model, not a full explanation.

04What breaks as context grows

Modern models advertise 128K or even 1M-token windows. That does not mean they use every token equally well. Here is what goes wrong:

highlow start of promptmiddleend of prompt Where the needed fact is placed in a long prompt answer accuracy facts in the middle get missed
The “lost in the middle” pattern reported by Liu et al. (2023). The shape is illustrative; the exact drop varies by model.

Practical tips for long prompts

05Summary

06Quick quiz

1. You double the number of tokens. The attention score table becomes…

2. Which technique gives exactly the same result as normal attention, only faster?

3. What does grouped-query attention (GQA) mainly reduce?

4. “Lost in the middle” means…

5. True or false: high attention weight always proves a word caused the answer.

07References

Created by Ajeetkumar