Skip to main content

The Long-Context Tax: Token 32,768 Costs 20x Token 1

· 35 min read
Vadim Nicolai
Senior Software Engineer

This week brought two very different answers to the same problem. Qwen4 uses Gated DeltaNet in 30 of its 40 layers. Amazon's Ergo, a 1.1T-parameter open-weight model, uses sliding-window plus grouped-query attention. The problem both are solving: every token an LLM generates re-reads the keys and values of every earlier token, in every layer.

I wanted the actual size of that tax, so I built the decode step from scratch in numpy and measured it on my MacBook (M4 Pro, 24 GB): six attention designs, one Qwen3-4B-shaped model, contexts from 0 to 32,768 tokens. Nothing was downloaded; random weights at real model shapes time exactly like trained ones. The full script is at the end.

Every token you generate re-reads the entire conversation: what token 32,768 costs in units of token 1, at 32 concurrent users

What token 32,768 costs in units of token 1, with 32 users sharing the server:

  1. Multi-head attention (MHA): 78x, and an 18.0 GiB KV cache per user.
  2. Grouped-query attention (GQA, 8 KV heads), the default of most open models: 20x, 4.5 GiB.
  3. Multi-head latent attention (MLA), DeepSeek's design: 6.4x, 1.27 GiB.
  4. A 3:1 DeltaNet hybrid, Qwen4's layer ratio: 4.9x, 1.15 GiB.
  5. A 4K sliding window, the building block of Ergo and Gemma: 3.4x, 0.56 GiB.
  6. Gated DeltaNet (linear attention) alone: 1.0x, 0.04 GiB.

Then I ran the config.json of 19 open models through the same arithmetic. Per 128K-token conversation, Llama 3.1 70B keeps 40 GiB of cache, Amazon Ergo 8.1 GiB, Qwen4 2.6 GiB and DeepSeek V4 Flash 0.68 GiB.

I think the KV cache, not FLOPs, is now the main design constraint of open LLMs. Every architecture trend of 2026 shrinks the bytes kept per token; none of them makes the matrix multiplications cheaper.

Btw, for a single user the tax is only 1.6x on a GQA model at the bandwidth floor. It explodes when a server batches users, which is what everyone paying for inference does. The rest of this post is the measurements behind each number, an architecture gallery of what each design stores, the 19-model simulation, and how this week's releases read through it.

1. The setup​

The model is shaped like Qwen3-4B: 36 layers, hidden size 2,560, 32 query heads of dimension 128, feed-forward width 9,728. I timed one decoder layer and multiplied by 36, since every layer is identical in these designs.

A decode step has two parts:

  1. Weights. Multiply the one new token through every weight matrix. This does not depend on context length. Measured: 2.31 ms per layer in fp32, 83.6 ms for the model.
  2. Attention over the cache. Compare the new token's query against every cached key, then take a weighted sum of every cached value. This grows with context.

The six attention variants differ only in part 2:

def attn_full(q, K, V, n):            # MHA when KV heads == query heads, GQA when fewer
s = softmax(q @ K[:, :, :n + 1] / np.sqrt(HD)) # one score per cached token, per head
return s @ V[:, :n + 1] # weighted sum of every cached value

def attn_window(q, K, V, n): # sliding window: only the last 4,096 tokens
lo = max(0, n + 1 - WIN)
return attn_full(q, K[:, :, lo:], V[:, lo:], n - lo)

def attn_mla(q_lat, q_rope, C, R, n): # MLA, absorbed form: attend over a 512-dim latent per token
s = softmax((q_lat @ C[:, :n + 1] + q_rope @ R[:, :n + 1]) / np.sqrt(HD + ROPE))
return s @ CT[:n + 1]

def deltanet_step(S, q, k, v, beta=0.5): # linear attention: a fixed 128x128 state per head
Sk = np.einsum("hij,hj->hi", S, k)
S += beta * np.einsum("hi,hj->hij", v - Sk, k) # delta rule: correct the state toward v
return np.einsum("hij,hj->hi", S, q) # cost independent of context length

The hybrid is three DeltaNet layers for every GQA layer, the layout of Qwen3-Next and Qwen4 (30 of 40 layers linear).

2. Why cache at all: the no-cache baseline​

The cache exists because the alternative is worse. Without it, every step recomputes the keys and values of every earlier token. I checked that the cached and recomputed outputs match (largest difference 1e-14 on a small test stack), then timed both:

ContextRecompute K,V (ms/layer)Read from cache (ms/layer)Cache speedup
2561.170.148.4x
1,0244.120.537.7x
4,09613.862.355.9x

Recomputing is linear per step and quadratic over a reply; the cache turns it into a read. The rest of this post is about the price of that read.

3. Measured: decode time per token vs context​

Measured decode time for one new token vs context length for six attention designs

With one user, my from-scratch kernels show:

  • MHA goes from 84 ms to 1,901 ms per token by 32K: a 22.7x tax.
  • GQA, which almost every open model uses, goes to 910 ms: 10.9x.
  • MLA reaches 535 ms (6.3x), the hybrid 296 ms (3.3x), the sliding window flattens at 173 ms once it passes 4K (2.1x).
  • Linear attention stays at 91 ms whatever the context.

One honest caveat. These numpy kernels are naive: they read the cache at 12–21 GB/s, while this Mac's memory moves 127 GB/s. A fused kernel (FlashDecoding, llama.cpp's Metal kernels) gets far closer to the bus. So the measured curve overstates the single-user tax. Its shape is right; its slope is too steep. To get the slope right, I computed the floor next.

4. The floor: decode is a bandwidth division​

A decode step cannot finish faster than the time it takes to move its bytes through memory. I measured this Mac's bandwidth (127.4 GB/s on a 256 MiB copy) and its fp32 matmul speed (2.77 TFLOP/s on Accelerate). The ratio is about 22 FLOPs per byte: an operation needs at least that much arithmetic per byte read to be compute-bound.

Decode is nowhere near it:

  • A weight matrix times one token does 2 FLOPs per weight. In bf16 that is 1 FLOP per byte: about 20x below the line.
  • Attention over a GQA cache does about 2 FLOPs per byte (each cached key serves four query heads). MHA does 0.5.
  • Prefill, by contrast, multiplies thousands of prompt tokens by the same weights: hundreds of FLOPs per byte, solidly compute-bound.

So for decode, time is bytes divided by bandwidth:

step time ≥ (weight bytes + streams × KV bytes per stream) / 127 GB/s

For one user on a bf16 4B model, the weights are 8 GB (62.8 ms) and the GQA cache at 32K is 4.8 GB (38 ms). The floor tax is only 1.6x. MHA, 3.4x. For one user, the long-context tax is real but tolerable.

5. Where the tax bites: many users at once​

Servers do not run one user. They batch, and batching changes the arithmetic. The weights are read once per step no matter how many users share it. Each user's KV cache is read separately.

At 32 concurrent users, the long-context tax per attention design vs context length

At 32 users, one step on the GQA model reads 8 GB of weights and 32 × 4.8 GB of cache. The cache is now 95% of the bytes, and token 32,768 costs 20x token 1. MHA hits 78x. That is the number in the headline, and it is why long-context serving is priced the way it is.

I also timed it with the naive kernels at 8K context. The GQA model plateaus at about 5.8 tokens/s from 32 streams up, while the hybrid keeps climbing to 18.7 tokens/s at 64: 3.2x the throughput from the same weights. These runs reuse one cache buffer to time the reads, so they measure speed, not whether 64 caches would fit. They would not: 64 GQA users at 8K need 72 GiB.

6. Memory: the cache fills the GPU, not the model​

KV cache and recurrent state per stream vs context, six attention designs

The 4B model is 8 GB in bf16. One MHA user at 32K needs 18 GiB of cache on top. One GQA user needs 4.5 GiB, so a 24 GB Mac fits three of them. One hybrid user needs 1.15 GiB; one linear-attention user needs 40 MiB of fixed state, at any length.

The formula behind every one of these numbers:

KV bytes per token = 2 (K and V) × layers × KV heads × head dim × bytes per value
MHA: 2 × 36 × 32 × 128 × 2 = 576 KiB per token
GQA: 2 × 36 × 8 × 128 × 2 = 144 KiB per token
MLA: 36 × (512 + 64) × 2 = 40.5 KiB per token

7. How each design cuts the tax​

What each attention design keeps for every token it has seen: KV cache per token per layer for MHA, GQA, MLA, sliding window, Gated DeltaNet and a 3:1 hybrid

The whole tax comes down to one number per design: the bytes it keeps for every token it has seen. Per layer, in bf16, at the Qwen3-4B shape:

DesignWhat it keeps per token, per layerBytesAll 36 layersPer user at 32K
MHAa key and a value for each of 32 heads of 128 dims16,384576 KiB18.0 GiB
GQAa key and a value for each of 8 shared heads4,096144 KiB4.5 GiB
MLAone 512-dim latent plus one 64-dim RoPE key1,15240.5 KiB1.27 GiB
Sliding window 4Kthe same as GQA, for the last 4,096 tokens only4,096144 KiB0.56 GiB
Gated DeltaNetnothing; one 128 × 128 state per head, updated in place00 (36 MiB fixed)0.04 GiB
Hybrid 3:1GQA in 1 layer of 4, a DeltaNet state in the other 31,024 (average)36 KiB1.15 GiB

Multiply the per-token bytes by the context and the number of users, divide by memory bandwidth, and you have each design's tax to first order. That is all the floor model in section 4 does.

  • GQA shares one key/value head across four query heads: 4x less cache than MHA, and every open model since Llama 2 70B uses some version of it. It cuts the tax 4x; it does not remove it.
  • MLA (DeepSeek, now in several US models) stores one compressed latent per token and attends over it directly. Another 3.6x smaller than GQA here.
  • Sliding window caps the cache at the window. Pure windows lose long-range recall, so models such as Amazon Ergo and Gemma mix them with a few global layers, which brings part of the tax back.
  • Linear attention (Gated DeltaNet, Mamba) replaces the cache with a fixed-size state updated by the delta rule. Zero tax, but a fixed state cannot hold everything, which is why no frontier model is purely linear.
  • Hybrids keep a few full-attention layers for recall and make the rest linear. At 3:1 they keep 75% of the tax off.

8. Simulating 19 open models from their config.json​

Six toy variants are one thing. To see what this year's models actually do, I pointed the same arithmetic at the public config.json of 19 open models (a few KB each, no weights) and computed, layer by layer, what each layer keeps per token and what one decode step reads from it. The rule per layer is short:

def gqa(kvh, hd):  return 2 * kvh * hd * BF16                   # a key and a value per KV head
def mla(c): return (c["kv_lora_rank"] + c["qk_rope_head_dim"]) * BF16 # one latent per token

def full(b): return (b, lambda n: n * b, 0) # store every token, read every token
def window(b, w): return (0, lambda n: min(n, w) * b, w * b) # a ring buffer of w tokens
def sparse(b, k): return (b, lambda n: min(n, k) * b, 0) # store every token, read the top k
def state(nbytes): return (0, lambda n: nbytes, nbytes) # a fixed recurrent state, read every step

Each model is then a list of those, read straight from its config: Ergo's global_attention_every_n_layers: 4 and local_attention_window: 512, Qwen4's layer_types and indexer_budget, DeepSeek V4's per-layer compress_ratios, Mistral Large 4's kv_source_layers, Kimi K3.1's full_attn_layers, Nemotron's layers_block_type.

What 19 open models keep for one 128K-token conversation and what they read for each new token, computed layer by layer from each model's config.json

ModelAttention, from config.jsonKV per tokenFixed per userPer user at 128KRead per new token at 128K
Llama 3.1 70BGQA320 KiB040.00 GiB40.00 GiB
Qwen3-4B (my bench shape)GQA144 KiB018.00 GiB18.00 GiB
MiniMax M3GQA + sparse reads120 KiB015.00 GiB0.99 GiB
GLM-5.3MLA + sparse reads87.75 KiB010.97 GiB0.17 GiB
Gemma 3 27Bwindow 5:1 + GQA80 KiB416 MiB10.41 GiB10.41 GiB
Mistral Large 4MLA + sparse + shared KV70.88 KiB08.86 GiB0.16 GiB
DeepSeek V3MLA68.62 KiB08.58 GiB8.58 GiB
Muse Spark Open 816Bwindow + GQA64 KiB368 MiB8.36 GiB8.36 GiB
Qwen3.8-27B (no MoE)DeltaNet 3:1 + GQA64 KiB144 MiB8.14 GiB8.14 GiB
Amazon Ergowindow 3:1 + GQA64 KiB96 MiB8.09 GiB8.09 GiB
LongCat-2.5MLA + sparse reads42.75 KiB05.34 GiB0.13 GiB
gpt-oss-120bwindow 1:1 + GQA36 KiB4.5 MiB4.50 GiB4.50 GiB
Kimi K3.1 ProKDA + MLA sparse27 KiB414 MiB3.78 GiB0.46 GiB
Qwen3-Next 80B-A3BDeltaNet 3:1 + GQA24 KiB72 MiB3.07 GiB3.07 GiB
Qwen4 35B-A3BDeltaNet 3:1 + sparse20 KiB60 MiB2.56 GiB0.098 GiB
Ling 3.1 FlashKDA 7:1 + MLA10.12 KiB252 MiB1.51 GiB1.51 GiB
DeepSeek V4 Procompressed + sparse7.74 KiB7.8 MiB0.98 GiB0.067 GiB
Nemotron 3.5 Lightning 30BMamba-2 + GQA6 KiB46 MiB0.79 GiB0.80 GiB
DeepSeek V4 Flashcompressed + sparse5.41 KiB5.5 MiB0.68 GiB0.035 GiB

What I take from the table:

  1. The spread is 59x. Llama 3.1 70B keeps 320 KiB per token, 40 GiB for one 128K conversation; DeepSeek V4 Flash keeps 5.4 KiB, 0.68 GiB. In 1 TiB of GPU memory that is 25 conversations against 1,503.
  2. Five tricks, usually stacked: fewer KV heads (GQA); a latent instead of a key and a value (MLA, 1,152 bytes per layer in DeepSeek V3, GLM-5.3, LongCat-2.5, Mistral Large 4, Kimi K3.1 and Ling 3.1 alike); windows (Gemma 3, gpt-oss, Muse Spark, Ergo); linear layers with a fixed state (the Qwen hybrids, Kimi K3.1, Ling 3.1, Nemotron 3.5); and compression (DeepSeek V4 keeps one entry per 4 tokens in its CSA layers and one per 128 in its HCA layers). Mistral Large 4 adds a sixth: 9 of its 72 layers reuse layer 35's cache instead of keeping their own.
  3. Sparse attention cuts the reads, not the memory. MiniMax M3 stores 15 GiB per 128K conversation but reads 0.99 GiB per new token; GLM-5.3 stores 11 GiB and reads 0.17 GiB. Each step gets cheaper; the number of users that fit does not change.
  4. Four routes, one bill. Ergo and Muse Spark (windows plus global GQA), Qwen3.8-27B (DeltaNet 3:1) and DeepSeek V3 (MLA) all keep 8.1 to 8.6 GiB per 128K conversation.
  5. Linear layers pay up front. Kimi K3.1 Pro's 69 KDA layers hold 414 MiB of state per user before the first token, and at 128K reading that state is about 90% of its cache reads. Gemma 3's windows cost 416 MiB the same way.
  6. DeepSeek V4 Pro keeps 7.7 KiB per token, 11.3% of DeepSeek V3's MLA cache by my arithmetic. DeepSeek's model card says 10% of V3.2's at 1M tokens, so reading the config this way holds up. At 1M tokens that is 7.7 GiB per user against 68.6 GiB.
  7. Qwen4 keeps 20 KiB per token (2.56 GiB at 128K) and reads 0.10 GiB per new token at 128K: 10 sparse-attention layers that read at most 2,048 tokens each, plus 60 MiB of DeltaNet state. That is what makes its 1M-token context believable.
  8. GLM-5.4's loop, simulated on GLM-5.3's layout (also 78 layers): if each of the 106 layer applications keeps its own cache, 87.75 KiB per token becomes 119 KiB, 36% more. GLM-5.4's own config is gated, so this is a scenario, not a reading.

My read of the table: 2026 split the problem in two. MLA, compression, windows and linear layers shrink what you store; sparse attention shrinks what you read. DeepSeek V4 and Qwen4 already do both, and I think the open models of 2027 all will.

Btw, the single-user column in models.csv makes the other point of this post. For one user at 128K, the cache is 0.1 to 2.3% of the bytes a big sparse MoE reads per token (the active weights are the rest), 7% for Ergo, 23% for Llama 3.1 70B and 71% for my 4B shape. The cache bill arrives with the users.

9. Reading this week's releases through the tax​

Three releases in ten days, three different bets on the same cost. The architecture facts are from Sebastian Raschka's posts; the cost reading is mine, from the measurements above.

ReleaseAttention designWhat it does to the tax
Qwen4 (35B, plus a 20B n-gram table)Gated DeltaNet in 30 of 40 layers, Qwen Sparse Attention in the other 10A per-token cache in only 10 of 40 layers, and sparse attention reads a subset of even those. My 3:1 hybrid: 4.9x at 32 users, against 20x for GQA.
Amazon Ergo (1.1T total, 55B active)Sliding-window plus grouped-query attention, RoPE and NoPE layers, squared ReLU in the experts48 of its 64 layers keep a 512-token window; the 16 global GQA layers keep the full tax: 64 KiB per token, 8.1 GiB per 128K conversation. Decode reads the 55B active parameters per token, not 1.1T.
GLM-5.4 (78 decoder layers)Looped: the middle 28 layers run twice, 106 layer applications per tokenWeights held in memory: 78 layers' worth. Weights read per token: 106/78 = 1.36x. If each pass keeps its own keys and values, the straightforward implementation, the cache grows like a 106-layer model's.

Raschka ran Qwen4 against the dense Qwen3.8-27B on a DGX Spark with llama.cpp, at 8K context and 4-bit weights: 55 vs 11.5 tokens/s, 4.8x. The configs say how to read that gap. Qwen3.8-27B is itself a 3:1 Gated DeltaNet hybrid (48 linear layers, 16 attention layers with 4 KV heads), so both models already carry small caches, and at 8K the cache and state are only 4 to 6% of the bytes either one reads per token. Nearly all of the 4.8x is mixture-of-experts: about 3B active parameters against 27B. At 0.57 bytes per parameter (Qwen4's 32.5 GB peak RAM over its 57B stored parameters: 35B, plus the 20B n-gram embedding and 2B of MTP) and the DGX Spark's 273 GB/s, the bandwidth floor is 150 tokens/s for Qwen4 and 17 for Qwen3.8-27B, a ratio of 8.9x. llama.cpp reached 68% of the floor on the dense model and 37% on the MoE, the usual gap for small experts at batch 1.

Update: an earlier version of this section credited about 1.9x of that gap to Qwen4's attention design. That compared Qwen4 with a plain GQA model; Qwen3.8-27B's config shows it is a hybrid too.

His peak-RAM numbers make the single-user point of section 5: 32.5 GB for Qwen4 against 20.2 GB for Qwen3.8-27B. At one user and 8K context, memory is mostly weights, and Qwen4 stores more of them. The cache saving is per user, so it pays when a server holds many users at once.

GLM-5.4 is the counter-trend worth watching. Looping buys compute per token without new weights, but decode is bandwidth-bound, so on a GPU the second pass is paid in bytes: the 28 looped layers' weights cross the memory bus twice. In the terms of this post, looping raises the weight term of the floor, the one part of the step that does not depend on context. My guess is that looped models will pair with small caches, because a design that re-reads its weights cannot also afford to re-read a large cache.

Raschka's November count says the same thing at the scale of the whole field: in the second half of 2026, new open models split evenly between hybrids that keep some full attention and models with no full attention at all, and none use full attention in every layer.

It also changes how serving systems should think. Narwhal splits prefill and decode across GPUs and moves the KV cache between them (its first lesson on a Mac). Its decode profiles assume that per-token cost grows with context. For a linear or hybrid model that assumption mostly disappears, the handoff shrinks to a fixed state, and prefix caching gets harder: a recurrent state cannot be cut at any token, so it has to be snapshotted.

One request, two engines: prompt, prefill engine, KV cache transfer, decode loop, router and role controller

10. What to take from it​

  • For one user, the long-context tax is 1.6x on a modern GQA model at the bandwidth floor. Annoying, not fatal.
  • For a server with 32 users, it is 20x, and the KV cache is 95% of the bytes each step reads. Long-context pricing follows from that.
  • The fixes are architectural: shrink the bytes per cached token (GQA, MLA) or stop caching per token (sliding windows, linear layers). This year's open models do both at once.
  • Sparse attention makes each step cheaper but leaves the cache as large as before; read both columns before you size a server.
  • Read the bytes kept per token on every new model card. For long-context serving cost it predicts more than the parameter count does.
  • Batching only pays if the caches are small. A 3:1 hybrid served 3.2x the tokens of GQA from the same weights in my runs.

Method and reproduction​

Everything ran on an M4 Pro (24 GB) with numpy on Apple Accelerate, fp32, on the CPU and its matrix units rather than the GPU; nothing was downloaded. Timings are medians of 15 runs after 3 warm-ups. Floors use bf16 byte counts and the measured 127.4 GB/s copy bandwidth. The sliding window and linear curves include their fixed costs; the hybrid is computed as 0.75 × linear + 0.25 × GQA per layer. The naive kernels read the cache at 12–21 GB/s, so measured single-user taxes overstate what a tuned kernel shows; the floor chart is the lower bound. The full benchmark script is below; it writes every number in this post to CSV in about two minutes. The 19-model simulation (simulate.py, also below) reads each model's public config.json and nothing else: KV caches in bf16, recurrent states in fp32; the small index keys of sparse-attention layers, conv states and MTP heads are not counted; where a config does not mark dense layers, all attention layers are treated alike (GLM-5.3, LongCat-2.5).

bench.py: the complete benchmark (numpy only)
"""The long-context tax, measured from scratch with numpy (Apple Accelerate) on an M4 Pro.

No model downloads: random weights at Qwen3-4B-like shapes. Speed does not depend on weight values.
One decoder layer is timed and scaled by LAYERS; every layer of these designs is identical.

Run: python3 -I bench.py -> results/*.csv
"""
import csv
import time
from pathlib import Path

import warnings

import numpy as np

warnings.filterwarnings("ignore", category=RuntimeWarning) # Accelerate raises spurious FP flags in matmul

OUT = Path(__file__).parent / "results"
OUT.mkdir(exist_ok=True)
rng = np.random.default_rng(0)
F = np.float32
D, H, HD, KVH, FF, LAYERS = 2560, 32, 128, 8, 9728, 36 # Qwen3-4B-like
LAT, ROPE, WIN = 512, 64, 4096 # MLA latent, MLA rope dims, sliding window
DEPTHS = [0, 512, 1024, 2048, 4096, 8192, 12288, 16384, 24576, 32768]
NMAX = DEPTHS[-1] + 1


def med(fn, reps=15, warm=3):
for _ in range(warm):
fn()
ts = []
for _ in range(reps):
t = time.perf_counter()
fn()
ts.append(time.perf_counter() - t)
return float(np.median(ts))


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


# ---------- attention for ONE new token against a cache of n tokens (per layer) ----------
def attn_full(q, K, V, n): # q (KVH, G, HD); K stored transposed (KVH, HD, NMAX); V (KVH, NMAX, HD)
s = softmax(q @ K[:, :, :n + 1] / np.sqrt(HD)) # GQA when G>1, MHA when KVH==H
return s @ V[:, :n + 1]


def attn_window(q, K, V, n):
lo = max(0, n + 1 - WIN)
return attn_full(q, K[:, :, lo:], V[:, lo:], n - lo)


def attn_mla(q_lat, q_rope, C, R, n): # absorbed MLA: scores on the latent directly
s = softmax((q_lat @ C[:, :n + 1] + q_rope @ R[:, :n + 1]) / np.sqrt(HD + ROPE))
return s @ CT[:n + 1] # (H, LAT), up-projected later


def deltanet_step(S, q, k, v, beta=0.5): # S (H, HD, HD): fixed-size state, independent of n
Sk = np.einsum("hij,hj->hi", S, k)
S += beta * np.einsum("hi,hj->hij", v - Sk, k)
return np.einsum("hij,hj->hi", S, q)


def main():
rows = []
# weights: the context-independent part of a decode step (matvecs over all layer weights)
W = {"qkv": rng.standard_normal((D, (H + 2 * KVH) * HD), dtype=F) * 0.02,
"o": rng.standard_normal((H * HD, D), dtype=F) * 0.02,
"up": rng.standard_normal((D, 2 * FF), dtype=F) * 0.02,
"down": rng.standard_normal((FF, D), dtype=F) * 0.02}
x = rng.standard_normal((1, D), dtype=F)

def weights_step(b=1):
xb = np.repeat(x, b, 0)
h = xb @ W["qkv"]
h = h[:, : H * HD] @ W["o"]
u = xb @ W["up"]
return (u[:, :FF] * u[:, FF:]) @ W["down"]

t_w = med(weights_step)
wbytes = sum(a.nbytes for a in W.values())

# caches, allocated once at max depth
Kg, Vg = rng.standard_normal((KVH, HD, NMAX), dtype=F), rng.standard_normal((KVH, NMAX, HD), dtype=F)
Km, Vm = rng.standard_normal((H, HD, NMAX), dtype=F), rng.standard_normal((H, NMAX, HD), dtype=F)
global CT
C = rng.standard_normal((LAT, NMAX), dtype=F) # latent stored transposed for scores
CT = np.ascontiguousarray(C.T) # and row-major for the value sum (MLA reuses one latent)
R = rng.standard_normal((ROPE, NMAX), dtype=F)
S = np.zeros((H, HD, HD), F)
qg = rng.standard_normal((KVH, H // KVH, HD), dtype=F)
qm = rng.standard_normal((H, 1, HD), dtype=F)
ql = rng.standard_normal((H, LAT), dtype=F)
qr = rng.standard_normal((H, ROPE), dtype=F)
kv = [rng.standard_normal((H, HD), dtype=F) for _ in range(3)]
t_lin = med(lambda: deltanet_step(S, *kv), reps=30)

for n in DEPTHS:
a = {"MHA (32 KV heads)": med(lambda: attn_full(qm, Km, Vm, n)),
"GQA (8 KV heads)": med(lambda: attn_full(qg, Kg, Vg, n)),
"MLA (512 latent)": med(lambda: attn_mla(ql, qr, C, R, n)),
"Sliding window 4K": med(lambda: attn_window(qg, Kg, Vg, n)),
"Linear (DeltaNet)": t_lin}
a["Hybrid 3:1 (Qwen-Next style)"] = 0.75 * t_lin + 0.25 * a["GQA (8 KV heads)"]
for name, ta in a.items():
kv_tok = {"MHA (32 KV heads)": 2 * H * HD * 2, "GQA (8 KV heads)": 2 * KVH * HD * 2,
"MLA (512 latent)": (LAT + ROPE) * 2, "Sliding window 4K": 2 * KVH * HD * 2,
"Linear (DeltaNet)": 0, "Hybrid 3:1 (Qwen-Next style)": 2 * KVH * HD * 2 / 4}[name]
ctx = min(n, WIN) if "window" in name else n
rows.append({"variant": name, "depth": n, "attn_ms_layer": ta * 1e3,
"token_ms_model": (ta + t_w) * LAYERS * 1e3,
"kv_mib_bf16": kv_tok * ctx * LAYERS / 2**20})
print(n, {k: round(v * 1e3, 3) for k, v in a.items()})
with open(OUT / "decode_vs_depth.csv", "w", newline="") as f:
w = csv.DictWriter(f, rows[0].keys())
w.writeheader()
w.writerows(rows)

# no cache: recompute K,V for every earlier token at every step (projection cost alone)
wkv = W["qkv"][:, H * HD:]
nc = []
for n in [256, 512, 1024, 2048, 4096]:
X = rng.standard_normal((n, D), dtype=F)
t_nc = med(lambda: X @ wkv, reps=7)
t_c = med(lambda: attn_full(qg, Kg, Vg, n), reps=7)
nc.append({"depth": n, "recompute_ms_layer": t_nc * 1e3, "cached_ms_layer": t_c * 1e3})
with open(OUT / "no_cache.csv", "w", newline="") as f:
w = csv.DictWriter(f, nc[0].keys())
w.writeheader()
w.writerows(nc)

# roofline of this machine
big = rng.standard_normal(256 * 2**20 // 4, dtype=F)
dst = np.empty_like(big)
t_bw = med(lambda: np.copyto(dst, big), reps=10)
bw = 2 * big.nbytes / t_bw / 1e9
A = rng.standard_normal((4096, 4096), dtype=F)
t_mm = med(lambda: A @ A, reps=5)
flops = 2 * 4096**3 / t_mm / 1e12

# batching at 8K depth: weights read once per step, attention per stream
bt = []
for b in [1, 2, 4, 8, 16, 32, 64]:
tw = med(lambda: weights_step(b), reps=7)
ta = med(lambda: attn_full(qg, Kg, Vg, 8192), reps=7)
for name, per in [("GQA (8 KV heads)", ta), ("Hybrid 3:1 (Qwen-Next style)", 0.75 * t_lin + 0.25 * ta)]:
step = (tw + b * per) * LAYERS
bt.append({"variant": name, "streams": b, "tok_per_s": b / step,
"kv_gib_bf16": b * 8192 * LAYERS * 2 * KVH * HD * 2 / 2**30 * (0.25 if "Hybrid" in name else 1)})
with open(OUT / "batching.csv", "w", newline="") as f:
w = csv.DictWriter(f, bt[0].keys())
w.writeheader()
w.writerows(bt)

# correctness: cached decode == recompute-everything, on a tiny GQA attention stack
d, T = 64, 24
Wq, Wk, Wv = (rng.standard_normal((d, d), dtype=np.float64) for _ in range(3))
Xs = rng.standard_normal((T, d))
full = []
for t in range(T): # no cache: recompute K, V for the prefix each step
k, v = Xs[: t + 1] @ Wk, Xs[: t + 1] @ Wv
full.append(softmax((Xs[t] @ Wq) @ k.T / 8) @ v)
Kc, Vc, cached = [], [], []
for t in range(T): # cache: append one row per step
Kc.append(Xs[t] @ Wk)
Vc.append(Xs[t] @ Wv)
cached.append(softmax((Xs[t] @ Wq) @ np.array(Kc).T / 8) @ np.array(Vc))
err = float(np.abs(np.array(full) - np.array(cached)).max())
assert err < 1e-12, err

with open(OUT / "machine.csv", "w", newline="") as f:
w = csv.writer(f)
w.writerow(["metric", "value"])
w.writerows([["copy_bandwidth_GBps", round(bw, 1)], ["fp32_matmul_TFLOPs", round(flops, 2)],
["weights_ms_per_layer", round(t_w * 1e3, 3)], ["weight_MB_per_layer_fp32", round(wbytes / 1e6)],
["deltanet_ms_per_layer", round(t_lin * 1e3, 3)], ["cache_equivalence_max_err", err]])
print("bw GB/s", round(bw, 1), "TFLOPs", round(flops, 2), "weights ms/layer", round(t_w * 1e3, 3), "err", err)


if __name__ == "__main__":
main()
simulate.py: the 19-model cache simulation (stdlib only, reads config.json)
"""The long-context tax of real open models, computed layer by layer from their config.json.

No weights: each model's public config.json (a few KB) is fetched once into configs/ and read here. For every layer
the script decides what that layer keeps per token (KV entries, an MLA latent, a compressed entry, or a fixed
recurrent state) and what one decode step reads from it at context n (all entries, a window, a sparse top-k, or
compressed entries). Units: KV caches in bf16 (2 bytes), recurrent states in fp32 (4 bytes, the dtype the Qwen and
Nemotron configs name). Not counted: the small index keys that sparse-attention layers also cache (one 128-dim key
per token in DSA-style indexers), conv states, MTP and draft heads. Halve the KV numbers for an FP8 KV cache.

Run: python3 simulate.py -> results/models.csv
"""
import csv
import json
import urllib.request
from pathlib import Path

HERE = Path(__file__).parent
CFG = HERE / "configs"
BF16, FP32 = 2, 4

MODELS = [ # repo, label, active params (B) as the model card / Raschka states them, first listed
("NousResearch/Meta-Llama-3.1-70B-Instruct", "Llama 3.1 70B", 70.6, "2024-07"),
("Qwen/Qwen3-4B", "Qwen3-4B (my bench shape)", 4.0, "2025-04"),
("unsloth/gemma-3-27b-it", "Gemma 3 27B", 27.0, "2025-03"),
("deepseek-ai/DeepSeek-V3", "DeepSeek V3", 37.0, "2024-12"),
("openai/gpt-oss-120b", "gpt-oss-120b", 5.1, "2025-08"),
("Qwen/Qwen3-Next-80B-A3B-Instruct", "Qwen3-Next 80B-A3B", 3.0, "2025-09"),
("amd/Muse-Spark-Open-816B-A42B-Quark-MXFP4", "Muse Spark Open 816B", 42.0, "2026-10"),
("MiniMaxAI/MiniMax-M3", "MiniMax M3", 23.0, "2026-10"),
("mistralai/Mistral-Large-4-1T-A52B", "Mistral Large 4", 52.0, "2026-10"),
("inclusionAI/Ling-3.1-flash", "Ling 3.1 Flash", 25.0, "2026-10"),
("nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-NVFP4", "Nemotron 3.5 Lightning 30B", 3.0, "2026-10"),
("meituan-longcat/LongCat-2.5", "LongCat-2.5", 48.0, "2026-11"),
("zai-org/GLM-5.3", "GLM-5.3", None, "2026-11"),
("deepseek-ai/DeepSeek-V4-Flash", "DeepSeek V4 Flash", 13.0, "2026-07"),
("deepseek-ai/DeepSeek-V4-Pro", "DeepSeek V4 Pro", 49.0, "2026-08"),
("moonshotai/Kimi-K3.1-Pro", "Kimi K3.1 Pro", 104.0, "2026-11"),
("Qwen/Qwen3.8-27B", "Qwen3.8-27B (no MoE)", 27.0, "2026-11"),
("Amazon-FMR/Ergo", "Amazon Ergo", 55.0, "2026-12"),
("Qwen/Qwen4-35B-A3B", "Qwen4 35B-A3B", 3.0, "2026-12"),
]


DESIGN = {
"Llama 3.1 70B": "GQA",
"Qwen3-4B (my bench shape)": "GQA",
"Gemma 3 27B": "window 5:1 + GQA",
"DeepSeek V3": "MLA",
"gpt-oss-120b": "window 1:1 + GQA",
"Qwen3-Next 80B-A3B": "DeltaNet 3:1 + GQA",
"Muse Spark Open 816B": "window + GQA",
"MiniMax M3": "GQA + sparse reads",
"Mistral Large 4": "MLA + sparse + shared KV",
"Ling 3.1 Flash": "KDA 7:1 + MLA",
"Nemotron 3.5 Lightning 30B": "Mamba-2 + GQA",
"LongCat-2.5": "MLA + sparse reads",
"GLM-5.3": "MLA + sparse reads",
"DeepSeek V4 Flash": "compressed + sparse",
"DeepSeek V4 Pro": "compressed + sparse",
"Kimi K3.1 Pro": "KDA + MLA sparse",
"Qwen3.8-27B (no MoE)": "DeltaNet 3:1 + GQA",
"Amazon Ergo": "window 3:1 + GQA",
"Qwen4 35B-A3B": "DeltaNet 3:1 + sparse",
}
MIRRORS = {"NousResearch", "unsloth", "amd"} # re-uploads: their listing date is not the release date


def listed(repo):
"""Month the official repo was CREATED on Hugging Face (API createdAt), which can precede the public release."""
if repo.split("/")[0] in MIRRORS:
return None
req = urllib.request.Request(f"https://huggingface.co/api/models/{repo}", headers={"User-Agent": "kv-sim/1.0"})
try:
return json.loads(urllib.request.urlopen(req, timeout=30).read()).get("createdAt", "")[:7] or None
except OSError:
return None


def spark_check():
"""Raschka's DGX Spark run (llama.cpp, Q4_K_M, 8K context, one user): Qwen4 55 tok/s vs Qwen3.8-27B 11.5 tok/s.
Bandwidth floor at 273 GB/s (NVIDIA's DGX Spark spec). 0.57 bytes per parameter is Qwen4's measured peak RAM
(32.5 GB) over its 57B stored parameters (35B + 20B n-gram embedding + 2B MTP); KV f16, states fp32."""
bw, bpp, n = 273e9, 32.5e9 / 57e9, 8192
out = {}
for repo, active, measured in [("Qwen/Qwen4-35B-A3B", 3.0, 55.0), ("Qwen/Qwen3.8-27B", 27.0, 11.5)]:
s = simulate(repo)
w, c = active * 1e9 * bpp, s["read"](n)
floor = bw / (w + c)
out[repo] = (floor, measured, c / (w + c))
print(f"{repo:22s} weights {w / 1e9:5.2f} GB cache+state read {c / 1e9:5.3f} GB ({c / (w + c):.1%}) "
f"floor {floor:5.1f} tok/s measured {measured} ({measured / floor:.0%} of floor)")
q4, q38 = out["Qwen/Qwen4-35B-A3B"], out["Qwen/Qwen3.8-27B"]
print(f"floor ratio {q4[0] / q38[0]:.1f}x vs measured {q4[1] / q38[1]:.1f}x")


def config(repo):
p = CFG / (repo.replace("/", "__") + ".json")
if not p.exists():
req = urllib.request.Request(f"https://huggingface.co/{repo}/raw/main/config.json", headers={"User-Agent": "kv-sim/1.0"})
CFG.mkdir(exist_ok=True)
p.write_bytes(urllib.request.urlopen(req, timeout=30).read())
c = json.loads(p.read_text())
return c.get("text_config", c)


# A layer is (stored_per_token, read(n), fixed_bytes): bytes kept per token, bytes one decode step reads at context n,
# bytes held regardless of context (windows, recurrent states).
def gqa(kvh, hd):
return 2 * kvh * hd * BF16 # a key and a value per KV head


def mla(c):
return (c["kv_lora_rank"] + c["qk_rope_head_dim"]) * BF16 # one latent + one RoPE key, K and V rebuilt from it


def full(b):
return (b, lambda n: n * b, 0)


def window(b, w):
return (0, lambda n: min(n, w) * b, w * b) # a ring buffer: fixed size once the window is full


def sparse(b, k):
return (b, lambda n: min(n, k) * b, 0) # stores every token, reads only the top-k selected ones


def state(nbytes):
return (0, lambda n: nbytes, nbytes) # fixed recurrent state, read every step


def layers(repo, c):
L = c.get("num_hidden_layers") or c.get("num_layers")
if repo.startswith("NousResearch") or repo == "Qwen/Qwen3-4B":
hd = c.get("head_dim") or c["hidden_size"] // c["num_attention_heads"]
return [full(gqa(c["num_key_value_heads"], hd))] * L
if "gemma-3" in repo: # 5 local layers (window 1024) then 1 global, repeating
b = gqa(c["num_key_value_heads"], c["head_dim"])
return [full(b) if (i + 1) % c["sliding_window_pattern"] == 0 else window(b, c["sliding_window"]) for i in range(L)]
if repo == "openai/gpt-oss-120b" or "Muse-Spark" in repo:
b = gqa(c["num_key_value_heads"], c["head_dim"])
types = c.get("layer_types") or ["full_attention"] * L
return [window(b, c["sliding_window"]) if t.startswith("sliding") else full(b) for t in types]
if repo == "deepseek-ai/DeepSeek-V3":
return [full(mla(c))] * L
if repo in ("zai-org/GLM-5.3", "meituan-longcat/LongCat-2.5"): # MLA + DSA lightning indexer (top-k)
k = c["index_topk"] + c.get("index_local_tokens", 0) + c.get("index_init_tokens", 0)
return [sparse(mla(c), k)] * L
if "Mistral-Large-4" in repo: # MLA + indexed (sparse) attention; 9 layers reuse layer 35's KV
src = c["kv_source_layers"]
return [(mla(c) if src[i] == i else 0, (lambda n, b=mla(c), k=c["index_topk"]: min(n, k) * b), 0) for i in range(L)]
if "Kimi-K3" in repo: # 69 KDA (linear) + 24 Gated DSA (MLA storage, top-k reads)
la = c["linear_attn_config"]
kda = state(la["num_heads"] * la["head_dim"] ** 2 * FP32)
fa = set(la["full_attn_layers"])
return [sparse(mla(c), c.get("index_topk", 2048)) if i + 1 in fa else kda for i in range(L)]
if "Ling-3.1" in repo: # 63 KDA + 9 Gated MLA, 7:1 (model card)
kda = state(c["num_attention_heads"] * c["head_dim"] ** 2 * FP32)
g = c["layer_group_size"]
return [full(mla(c)) if (i + 1) % g == 0 else kda for i in range(L)]
if "Nemotron" in repo: # Mamba-2 + a few GQA layers; MoE blocks hold no cache
mamba = state(c["mamba_num_heads"] * c["mamba_head_dim"] * c["ssm_state_size"] * FP32)
b = gqa(c["num_key_value_heads"], c["head_dim"])
return [full(b) if t == "attention" else mamba for t in c["layers_block_type"] if t != "moe"]
if "DeepSeek-V4" in repo: # CSA (ratio 4, sparse top-k over compressed entries), HCA (128)
e, w = c["head_dim"] * BF16, c["sliding_window"] # one 512-dim shared entry; every layer also keeps 128 raw tokens
out = []
for r in c["compress_ratios"]:
if r == 0:
out.append(window(e, w))
elif r == 4:
out.append((e / r, lambda n, e=e, r=r: (min(n / r, c["index_topk"]) + min(n, w)) * e, w * e))
else:
out.append((e / r, lambda n, e=e, r=r: (n / r + min(n, w)) * e, w * e))
return out
if repo == "MiniMaxAI/MiniMax-M3": # GQA storage; MSA reads 16 blocks of 128 + the local block
sa = c["sparse_attention_config"]
b = gqa(c["num_key_value_heads"], c["head_dim"])
k = (sa["sparse_topk_blocks"] + sa["sparse_local_block"]) * sa["sparse_block_size"]
return [sparse(b, k) if f else full(b) for f in sa["sparse_attention_freq"]]
if repo == "Amazon-FMR/Ergo": # every 4th layer global GQA, the rest a 512-token window
b = gqa(c["num_key_value_heads"], c["head_dim"])
n4 = c["global_attention_every_n_layers"]
return [full(b) if (i + 1) % n4 == 0 else window(b, c["local_attention_window"]) for i in range(L)]
if repo.startswith("Qwen/"): # Qwen3-Next, Qwen3.8, Qwen4: 3 Gated DeltaNet : 1 attention
delta = state(c["linear_num_value_heads"] * c["linear_key_head_dim"] * c["linear_value_head_dim"] * FP32)
b = gqa(c["num_key_value_heads"], c["head_dim"])
att = sparse(b, c["indexer_budget"]) if "indexer_budget" in c else full(b) # Qwen4: Qwen Sparse Attention
types = c.get("layer_types") or ["full_attention" if (i + 1) % c["full_attention_interval"] == 0
else "linear_attention" for i in range(L)]
return [att if t == "full_attention" else delta for t in types]
raise ValueError(repo)


def simulate(repo):
ls = layers(repo, config(repo))
per_tok = sum(s for s, _, _ in ls)
fixed = sum(f for _, _, f in ls)
mem = lambda n: sum(min(s * n, s * n) for s, _, _ in ls) + fixed
read = lambda n: sum(r(n) for _, r, _ in ls)
return {"layers": len(ls), "per_tok": per_tok, "fixed": fixed, "mem": mem, "read": read}


def main():
K128, M1 = 131072, 1048576
rows = []
for repo, label, active, rel in MODELS:
s = simulate(repo)
rel = listed(repo) or rel
w = active * 1e9 * BF16 if active else None
rows.append({
"model": label, "design": DESIGN[label], "repo": repo, "hf_repo_created": rel, "layers_with_state": s["layers"],
"kv_kib_per_token": round(s["per_tok"] / 1024, 2), "fixed_mib_per_user": round(s["fixed"] / 2**20, 1),
"gib_per_user_128k": round(s["mem"](K128) / 2**30, 2), "gib_per_user_1m": round(s["mem"](M1) / 2**30, 1),
"read_gib_per_token_128k": round(s["read"](K128) / 2**30, 3),
"users_per_tib_128k": int(2**40 // s["mem"](K128)),
"cache_share_of_reads_128k_1user": round(s["read"](K128) / (w + s["read"](K128)), 3) if w else "",
})
out = HERE / "results" / "models.csv"
with out.open("w", newline="") as f:
wr = csv.DictWriter(f, fieldnames=list(rows[0]))
wr.writeheader()
wr.writerows(rows)
for r in sorted(rows, key=lambda r: -r["gib_per_user_128k"]):
print(f"{r['model']:28s} {r['kv_kib_per_token']:8.2f} KiB/tok fixed {r['fixed_mib_per_user']:7.1f} MiB "
f"128K {r['gib_per_user_128k']:6.2f} GiB 1M {r['gib_per_user_1m']:6.1f} GiB read@128K "
f"{r['read_gib_per_token_128k']:7.3f} GiB users/TiB {r['users_per_tib_128k']:5d} cache share {r['cache_share_of_reads_128k_1user']}")
# cross-check against DeepSeek's own claim: V4-Pro needs "10% of KV cache compared with DeepSeek-V3.2" at 1M.
v4 = simulate("deepseek-ai/DeepSeek-V4-Pro")["mem"](M1)
v32 = simulate("deepseek-ai/DeepSeek-V3")["mem"](M1) # V3.2 keeps V3's MLA cache (plus index keys, not counted)
spark_check()
print(f"\nDeepSeek V4-Pro cache at 1M vs V3/V3.2 MLA cache: {v4 / v32:.1%} (DeepSeek's model card: 10%)")


if __name__ == "__main__":
main()