Attention & Transformers

Efficient Attention at Scale: KV Cache, GQA & FlashAttention

How attention becomes practical at long context: KV caching for decoding, grouped-query attention, and IO-aware kernels like FlashAttention.

status: publishedimportance: importantdifficulty 4/5math: graduateread: 20mlive demo
Editorial transformer-systems illustration of KV-cache sharing, grouped query lanes, and reduced memory bandwidth.

Concept Structure

Efficient Attention at Scale: KV Cache, GQA & FlashAttention

01Intuition

Start with the picture, metaphor, or geometric mechanism.

02Math

Make the objects explicit and connect them with notation.

03Code

Mirror the equations with runnable implementation details.

04Interactive Demo

Manipulate the mechanism and watch the idea respond.

3prerequisites
4next concepts
4related links

Learning map

Efficient Attention at Scale: KV Cache, GQA & FlashAttention
BeforeScaled Dot-Product Attention & Transformer LayersNow4/4 sections readyTryManipulate one control and predict the visible change.NextLLM Serving at Scale: Prefill, Decode & Continuous Batching

Object flow

4/4 sections readyAsk about thisResearch room
ConceptEfficient Attention at Scale: KV Cache, GQA & FlashAttentionAttention & Transformers
3 sources attachedLocal snapshot ready
concept:attention-transformers/efficient-attention

Conceptual Bridge

What should feel connected as you move through this page.

Carry inScaled Dot-Product Attention & Transformer Layers

Bring the mental model from Scaled Dot-Product Attention & Transformer Layers; this page will reuse it instead of restarting from zero.

Work hereEfficient Attention at Scale: KV Cache, GQA & FlashAttention

How attention becomes practical at long context: KV caching for decoding, grouped-query attention, and IO-aware kernels like FlashAttention.

Carry outLLM Serving at Scale: Prefill, Decode & Continuous Batching

The next edge should feel earned: use the demo prediction here before following LLM Serving at Scale: Prefill, Decode & Continuous Batching.

Test the linkManipulate one control and predict the visible change.Then continue to LLM Serving at Scale: Prefill, Decode & Continuous Batching
01

01

Intuition

Build the mental picture first so the rest of the page has something to attach to.

Section prompt

"Attention is O(T2)O(T^2)" is true on paper, but in production the pain often feels different:

  • During decoding, you only compute attention for the new token, but you must attend over all past tokens.
  • You therefore store past keys/values in a KV cache. At long context, the KV cache can dominate memory.

Modern serving is mostly a game of managing memory bandwidth and cache size:

  • KV cache avoids recomputing keys/values for all past tokens.
  • Grouped-query attention (GQA) reduces KV cache size by sharing keys/values across multiple query heads.
  • FlashAttention keeps the exact attention math but changes how it is computed so the attention matrix is never materialized in slow memory.
02

02

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

Section prompt

With a KV cache, the attention output for the new token at time tt is:

ot=softmax ⁣(qtK1:tdk)V1:t,o_t = \mathrm{softmax}\!\left(\frac{q_t K_{1:t}^{\top}}{\sqrt{d_k}}\right) V_{1:t},

where (K1:t,V1:t)(K_{1:t},V_{1:t}) are cached.

KV cache memory scaling

Across a batch of BB sequences and LL layers, the KV cache stores keys and values for all TT positions:

MemKVBLTHkvdhead2bytes.\mathrm{Mem}_{KV} \approx B\cdot L\cdot T\cdot H_{kv}\cdot d_{\mathrm{head}}\cdot 2 \cdot \mathrm{bytes}.

The factor of 2 is for storing both KK and VV.

Grouped-query attention (GQA)

Let there be HqH_q query heads but only HkvH_{kv} key/value heads, with a mapping g(h)g(h) from query head hh to a KV head:

oh=softmax ⁣(QhKg(h)dk)Vg(h).o_h = \mathrm{softmax}\!\left(\frac{Q_h K_{g(h)}^{\top}}{\sqrt{d_k}}\right) V_{g(h)}.

This reduces the KV cache to roughly Hkv/HqH_{kv}/H_q of full multi-head attention. Equivalently: the KV cache becomes about (Hkv/Hq)(H_{kv}/H_q) of full multi-head attention (so it’s reduced by roughly Hq/Hkv×H_q/H_{kv}\times when Hkv<HqH_{kv} < H_q).

For the dedicated head-sharing invariant, selected Q-to-KV mapping, and cache-ratio prediction exercise, see Grouped-Query Attention.

03

03

Code

Keep the implementation aligned with the notation so the algorithm is legible.

Section prompt
def kv_cache_gb(T, layers, h_kv, d_head, batch=1, bytes_per_elem=2):
    elems = batch * layers * T * h_kv * d_head * 2  # keys + values
    return elems * bytes_per_elem / 1e9

T, layers, d_head, batch = 128_000, 80, 128, 1
full = kv_cache_gb(T, layers, h_kv=64, d_head=d_head, batch=batch)

for h_q, h_kv in [(64, 64), (64, 8), (64, 1)]:
    gb = kv_cache_gb(T, layers, h_kv=h_kv, d_head=d_head, batch=batch)  # fp16
    print(f"Hq={h_q:>2} Hkv={h_kv:>2}  KV ~ {gb:6.1f} GB  ({gb/full:.1%} of full)")
04

04

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

Section prompt

Use the demo to explore how KV cache size grows with context length, and how GQA changes the memory/latency tradeoff without changing the basic attention mechanism.

Live Concept Demo

Explore Efficient Attention at Scale: KV Cache, GQA & FlashAttention

The stage is code-native and interactive. Use it to test the explanation against the mechanism.

difficulty 4/5graduatecode-aligned
Demo Prediction Checkpoint

Manipulate one control and predict the visible change.

Commit to what Efficient Attention at Scale: KV Cache, GQA & FlashAttention should make visible before reading the result.

After The First Pass

Turn the concept into an inspected object.

Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.

Mechanism Storyboard

See the idea move before the page explains it

How attention becomes practical at long context: KV caching for decoding, grouped-query attention, and IO-aware kernels like FlashAttention.

Prediction open01 / Intuition
Editorial transformer-systems illustration of KV-cache sharing, grouped query lanes, and reduced memory bandwidth.
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change Efficient Attention at Scale: KV Cache, GQA & FlashAttention should make visible.

Visual Inquiry

Make the image answer a mathematical question

How attention becomes practical at long context: KV caching for decoding, grouped-query attention, and IO-aware kernels like FlashAttention.

4/4 stages readyLive demo connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make Efficient Attention at Scale: KV Cache, GQA & FlashAttention easier to reason about before the page gives the answer.

Source Grounding

Canonical references for the mechanism on this page.

paper · 2019Fast Transformer Decoding: One Write-Head is All You NeedShazeer

Grounds the KV-cache bandwidth motivation for sharing keys and values across query heads during decoding.

Open source
paper · 2023GQA: Training Generalized Multi-Query Transformer Models from Multi-Head CheckpointsAinslie et al.

Introduces grouped-query attention as the practical middle point between multi-head quality and MQA memory savings.

Open source
paper · 2022FlashAttention: Fast and Memory-Efficient Exact Attention with IO-AwarenessDao et al.

Grounds the IO-aware attention kernel: tiling plus online softmax avoids materializing the full attention matrix.

Open source

Claim Review

How attention becomes practical at long context: KV caching for decoding, grouped-query attention, and IO-aware kernels like FlashAttention.

Status1 substantive review recorded

Claims without a substantive review badge still need exact source-support review.

Sources3 references

shazeer-2019-mqa, ainslie-2023-gqa, dao-2022-flashattention

Witnesses4 local objects

Use equation, code, and demo objects to check whether the source support is operational.

Substantively reviewedAt incremental decoding time, KV cache reads can become a memory-bandwidth bottleneck; sharing key/value heads with MQA or GQA reduces KV tensor size while preserving multiple query heads.Claim metadata: source checked

Shazeer identifies repeated loading of large key/value tensors as an incremental-decoding bottleneck and proposes sharing keys and values across heads; Ainslie et al. present GQA as an intermediate between MHA quality and MQA speed/memory savings.

Sources: Fast Transformer Decoding: One Write-Head is All You Need, GQA: Training Generalized Multi-Query Transformer Models from Multi-Head CheckpointsThis checks KV-sharing memory/bandwidth and cache-size scaling for autoregressive decoding only; it is not a universal latency, quality, hardware, checkpoint-conversion, or model-adoption guarantee.A bounded review summary is present; still check caveats and exact source scope.

Shazeer supports the bottleneck/mechanism: incremental decoding reloads large K/V tensors, so memory bandwidth can dominate, and MQA removes the K/V heads dimension while keeping query heads. Ainslie et al. support GQA/MQA: MQA uses one KV head; GQA shares KV heads per query-head group, reducing KV-cache size and loads roughly in proportion to Hkv/Hq.

Reviewer: codex+oracle; reviewed 2026-05-07

Practice Loop

Try the idea before it explains itself

How attention becomes practical at long context: KV caching for decoding, grouped-query attention, and IO-aware kernels like FlashAttention.

Readiness0/3 checks ready
Predict

Before touching the demo, predict one visible change that should happen in Efficient Attention at Scale: KV Cache, GQA & FlashAttention.

Hint 1

Reveal when your model needs a nudge.

Hint 2

Reveal when your model needs a nudge.

Hint 3

Reveal when your model needs a nudge.

Object research drawerClose
ConceptEfficient Attention at Scale: KV Cache, GQA & FlashAttentionAttention & Transformers

Research Room

Attach the question to an exact object

Pick the concept, equation, source, code witness, claim, misconception, or demo state before asking for help. The handoff stays grounded to that object.
Next local actionNo local draft saved yet

Open the draft below to save one note and next action in this browser.

conceptAttention & Transformers

Efficient Attention at Scale: KV Cache, GQA & FlashAttention

Anchored question

What is the smallest example that makes Efficient Attention at Scale: KV Cache, GQA & FlashAttention click without losing the math?

Local action draftNo local draft saved yetExpand only when ready to capture one local next action
Local action draft

This draft stays locally in this browser for concept:attention-transformers/efficient-attention.

No local draft saved.
Evidence to inspect
  • Source ids to inspect: shazeer-2019-mqa, ainslie-2023-gqa, dao-2022-flashattention
  • Definition, prerequisite, and contrast concept links
  • The equation or code witness that makes the concept operational
  • One demo state that shows the invariant instead of a slogan
What would resolve this
  • The learner can state the mechanism in their own words
  • The learner can name the prerequisite that would repair confusion
  • The learner can predict how the mechanism changes under one perturbation
Grounded AI handoff

I am working in Continuous Function's research reading room. Object: concept - Efficient Attention at Scale: KV Cache, GQA & FlashAttention Object key: concept:attention-transformers/efficient-attention Context: Attention & Transformers Anchor id: concept/concept-notebook/attention-transformers/efficient-attention Open question: What is the smallest example that makes Efficient Attention at Scale: KV Cache, GQA & FlashAttention click without losing the math? Evidence to inspect: - Source ids to inspect: shazeer-2019-mqa, ainslie-2023-gqa, dao-2022-flashattention - Definition, prerequisite, and contrast concept links - The equation or code witness that makes the concept operational - One demo state that shows the invariant instead of a slogan What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action.

Open source object
concept/concept-notebook/attention-transformers/efficient-attention concept:attention-transformers/efficient-attention