Advanced

The KV cache

Autoregressive decoding stores past attention keys and values; in Qwen3.8-27B only the 16 full-attention layers cache, at 64 KiB per token and 16 GiB per full-length sequence.

Updated

01 · Concept

Concept

Suppose you serve Qwen3.8-27B and a user opens a conversation that grows toward the model’s native 262,144-token context. The weights are a fixed cost. What is not fixed is the memory that conversation holds hostage while it is active — and to size it, you need to know exactly what the KV cache is and, for this model, which layers actually keep one.

A decoder-only model generates one token, appends it, and repeats. A naive implementation would rerun the entire network over the growing sequence at every step, redoing identical work on the prefix. The KV cache stores the attention states future tokens need, turning repeated computation into reusable memory. In one attention layer, every token produces query, key, and value projections. During causal decode only the newest position needs a new output: its query attends to cached keys and mixes cached values, while past queries are never needed again. So the cache retains past keys and values, and the new token computes only its own qtq_t, ktk_t, and vtv_t. For one head,

ot=softmax(qtKtdk)Vt,o_t=\operatorname{softmax}\left(\frac{q_tK_{\leq t}^{\top}}{\sqrt{d_k}}\right)V_{\leq t},

where the cached matrices grow as ktk_t and vtv_t are appended. This is a consequence of exact causal attention, not an approximation to it. Ignoring allocator overhead, the memory model is

  1. KV heads4
  2. Head dimension256
  3. Keys and values× 2
  4. bfloat16× 2 B
  5. 4 KiB per tokenper layer

4 KV heads × 256 dimensions × 2 (keys and values) × 2 bytes = 4 KiB, for every token, in every layer that attends.

  1. Assumed: all layers cache64 layers → 64 GiB

Multiply by all 64 layers and you get 256 KiB per token, or 64 GiB at full context. This is wrong. It assumes every layer is an attention layer.

  1. Gated DeltaNet layers48 layers · ~144 MiB total, constant
  2. Full-attention layers16 layers · 64 KiB per token · 16 GiB at full context

Only 16 layers are full attention; the other 48 are Gated DeltaNet and cache nothing per token. That gives 64 KiB per token and 16 GiB at full context — beside a DeltaNet state of about 144 MiB that never grows.

Why only 16 of 64 layers cacheThe cache grows per token, but only in the full-attention layers. Assuming every layer caches is the classic wrong turn, and it overstates the budget fourfold.
bytes2LTHkvDB,\text{bytes}\approx 2\,L\,T\,H_{kv}\,D\,B,

with the factor two for keys plus values, LL cached layers, TT positions, HkvH_{kv} KV heads, DD head dimension, and BB bytes per element.

Now plug in Qwen3.8-27B — carefully, because there is a classic wrong turn here. The config says 64 layers, 4 KV heads, head dimension 256, bf16. Per token per layer: 4×256×2×2 B=4096 B=4 KiB4 \times 256 \times 2 \times 2\ \text{B} = 4096\ \text{B} = 4\ \text{KiB}. Multiply by 64 layers and you get 256 KiB per token, and at full context 256 KiB×262,144=64 GiB256\ \text{KiB} \times 262{,}144 = 64\ \text{GiB} for a single sequence — which, next to 54 GB of bf16 weights, would fill a 192 GB accelerator to the brim at two users and overflow it at three. That estimate is wrong, and wrong in an instructive way: it assumes every layer is an attention layer.

Lesson 4.16 showed that only 16 of the 64 layers are full attention; the other 48 are Gated DeltaNet layers, which keep a fixed-size recurrent state and cache nothing per token. The correct derivation:

4 KV heads×256×2(K+V)×2 B=4 KiB per token per layer,4\ \text{KV heads} \times 256 \times 2\,(K{+}V) \times 2\ \text{B} = 4\ \text{KiB per token per layer}, 4 KiB×16 caching layers=64 KiB per token,4\ \text{KiB} \times 16\ \text{caching layers} = 64\ \text{KiB per token}, 64 KiB×262,144 tokens=16 GiB per sequence at full native context.64\ \text{KiB} \times 262{,}144\ \text{tokens} = 16\ \text{GiB per sequence at full native context}.

The wrong assumption quadrupled the answer. Sixteen gibibytes is still enormous — about a fifth of an 80 GB card for one conversation — but it is the real number, and every capacity plan in tracks 8 and 9 builds on it.

The 48 DeltaNet layers are the counterpoint. The reference Transformers implementation keeps the recurrent matrix state in float32: 48 value heads × 128 × 128 × 4 bytes = 3 MiB per layer, or 144 MiB across all 48, excluding a much smaller short-convolution state. That figure is constant in sequence length. Token one and token 262,144 cost the matrix state the same memory. Other runtimes may choose a different state dtype, so inspect the realized allocation; the architectural bargain is the flat shape, not a universal byte count.

Even within the caching layers, the 4 KV heads are themselves a saving: the model asks 24 query heads to share 4 K/V heads (grouped-query attention), shrinking HkvH_{kv} and therefore cache size and decode bandwidth. Lesson 7.6 compares this choice against MQA and MLA numerically. Quantized cache formats shrink BB; sliding windows shrink effective TT at the price of forgetting.

Sizing is only half the engineering. Decode reads a long history to produce little new computation, so moving K/V data can dominate; kernels need friendly layouts while sequences grow unpredictably. Reserving every request’s maximum 16 GiB up front would be ruinous; paged allocation hands out fixed-size blocks on demand instead (lesson 7.8). Prefix caching shares blocks between requests that begin with the exact same token sequence, such as a common system prompt — safe only under the same model, adapter, and positional treatment, and never across authorization boundaries.

One last correction to the intuition: the cache does not make decode constant-time in context. Prefix re-projection disappears, but each new query in the 16 attention layers still reads and attends over everything retained. The durable model is a transcript — computation already performed becomes memory, saving arithmetic at the price of growing bandwidth, capacity, lifecycle, and privacy responsibilities — kept, in this model, by only a quarter of the layers.

02 · Analogy

Analogy

A courtroom stenographer keeps an indexed transcript of everything already said. When a new question arrives, the judge consults the transcript instead of asking every witness to repeat the hearing from the beginning. The transcript grows each turn and must preserve the exact order and case identity. The KV cache is that transcript for attention: prior keys are the index entries, prior values are the stored testimony, and the new query reads them.

03 · Teach it back

Teach it back

Derive the KV-cache size of one full-length Qwen3.8-27B sequence, stating explicitly which layers cache and which do not, and contrast the result with the DeltaNet state.

Minimum: 80 characters and 15 words. Your writing stays only in this browser.

Waiting for your explanation.

Compare with a model answer

Each cached layer stores, per past token, keys and values for the 4 KV heads at head dimension 256 in bf16: 4 × 256 × 2 (K and V) × 2 bytes = 4 KiB per token per layer. Only the 16 full-attention layers cache — the other 48 Gated DeltaNet layers keep fixed-size recurrent states instead — so per token the cache is 16 × 4 KiB = 64 KiB, and at the native 262,144-token context one sequence holds 64 KiB × 262,144 = 16 GiB. In the Transformers reference path, each DeltaNet layer keeps a float32 matrix state of 3 MiB; all 48 total 144 MiB per sequence, constant in sequence length and excluding the small convolution state.

04 · Check your understanding

Check your understanding

01In Qwen3.8-27B, which layers append keys and values to the cache during decode?
Answer and explanation

Only the 16 full-attention layers; the 48 Gated DeltaNet layers keep fixed-size state instead — The hybrid layout from lesson 4.16 places one full-attention layer in every four; only those layers have per-token K/V to store.

02Roughly how much KV-cache memory does one bf16 sequence at Qwen3.8-27B's full 262,144-token native context occupy?
Answer and explanation

16 GiB — 64 KiB per token × 262,144 tokens = 16 GiB; 64 GiB is the wrong-layer-count estimate, 144 MiB is the reference float32 DeltaNet matrix state, and 54 GB is the bf16 weights.

Complete the teach-back and answer the quiz correctly to finish this lesson.

◎ · Evidence marker

Sources

  1. Qwen Team (2026). Qwen3.8-27B Model Card.
  2. Qwen Team (2026). Qwen3.8-27B config.json.
  3. Hugging Face Transformers (2026). Qwen3.5 reference implementation.
  4. Woosuk Kwon et al. (2023). Efficient Memory Management for Large Language Model Serving with PagedAttention.