← All posts

Inference · GPU kernels

Halving the global KV cache for Gemma 4 K=V with a fused attention kernel

In my day job I've had plenty of chances to improve services and backend codebases, but I'd never worked on inference-time optimizations. While reading the Gemma 4 technical report and this paper on storing the Gemma 4 K=V cache once, an interesting optimization came up: it looked possible to store only the Value (not the Key and Value) in the cache of the model (the so called KV cache). This post is mostly meant to help other people who are curious about inference optimization. It isn't meant to be a research paper; I did this mostly for learning and fun.

When a language model generates text, it stores intermediate results for every token it has already seen so it doesn't have to recompute them.  That store is the KV cache, and for long contexts it often takes up more GPU memory than the model weights.

This post is about making that cache smaller. It does not change how much the model computes or what it outputs. It changes what we keep so we can skip storing redundant tensors that we can build on the fly. In practice that means that you can serve much longer contexts with the same hardware. We do that with a single fused GPU kernel that reconstructs the missing piece inside the attention computation.

The result: the KV cache of Gemma 4's global attention layers shrinks by 50%. On the real gemma-4-12B that's 8 KB saved per token, or about 1 GB per 128K-token sequence, with the same output. The result isn't groundbreaking but it's a nice improvement that would result in substantial resource savings for a high QPS system serving this model.

One caveat up front: the trick only works for the K=V variant of Gemma 4, where the model's Keys and Values come from the same projection. Among the Gemma 4 checkpoints that's gemma-4-12B, 26B-A4B and 31B; E2B and E4B don't use it. In a standard transformer, Keys and Values are genuinely different tensors, so there is nothing to share.

Background

If you already know how transformers, KV caches and Gemma's attention layers work, skip ahead to what the repo does. Otherwise, open whichever section you need.

What the repo does

The code is on GitHub: mdragus/optimizing_kernel_function. It has the Triton kernel, a plain-PyTorch reference implementation, tests, benchmarks and the end-to-end check against Gemma 4.

Two things to be clear about first:

In a K=V global layer, a standard inference stack still caches the Key (with RoPE already applied) and the Value for every token, even though both came from the same vector. That's 1,024 values per token per KV head for two copies of essentially the same information.

This isn't a new observation. The Gemma 4 technical report notes that reusing the key as the value, together with p-RoPE, cuts the global KV cache by up to 37.5%, and a recent paper by Bainsla shows how to serve that in vLLM. The idea is to store v plus only the 128 rotated Key dimensions, because the other 384 can be rebuilt from v. That's 640 values per token and works with unchanged attention kernels. The paper leaves the last step open: dropping those 128 dimensions too needs a new kernel, because every token is rotated by a different angle. That kernel is what this repo is.

Standard K + V1,024
K
V
v + 128 rotated K dims640 (−37.5%)
k_R
v
This kernel: v only512 (−50%)
v
Values cached per token per KV head in a Gemma 4 global layer. At 16 bits per value that's 2,048, 1,280 and 1,024 bytes.

We cache only v, once per token. During decode, a fused Triton kernel reads each cached v from GPU memory once and uses it twice: it rebuilds that token's Key in registers (rescale by w, rotate the 128 rotary dimensions by that token's angle), and it uses the same registers as the Value. The Key is never written to memory. Rebuilding it is a handful of multiply-adds, which is far cheaper than reading another 128 to 512 values per token from memory.

L4global
L3local
L2local
L1local
token
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Standard cache
44
Fused K=V cache
34
Vectors saved
10
Memory saved
23%

Drag the slider to the right: the local layers flatten out at 8 vectors each, while the global layer keeps growing. The longer the context, the more the global layer dominates the cache, and the closer the total saving gets to 50%.

A toy 4-layer model: three sliding-window layers (window = 4) and one global layer. Each small bar is one vector held in the cache. Local layers only keep the last 4 tokens, so their cost stops growing. The global layer keeps every token, and that is the only place we change anything: one shared KV vector per token instead of a separate K and V.

In the toy model the saving is modest at short lengths, because the local layers' fixed-size caches are still a big share of the total. As the context grows, the global layers take over the cache and the saving on the whole cache approaches the 50% we save on each global layer.

Inside the kernel

The hard part is RoPE. It rotates pairs of dimensions, and to rotate one number you need its partner: for a pair (a, b), the results are a·cos − b·sin and b·cos + a·sin. In Gemma 4 the rotated dimension i is paired with i + 256, so pair 0 is dimensions 0 and 256, pair 1 is 1 and 257, and so on up to pair 63. On a GPU, a block of cached vectors (a tile) is split across many threads, each holding a few numbers in its own registers. With a 512-wide tile, a number and its partner 256 dimensions away usually sit in different threads, and swapping them costs extra instructions in the hottest loop of the kernel.

The way around it: all the first members of the pairs form one contiguous block, dimensions [0, 64), and all their partners form another, [256, 320). The kernel loads each block as its own 64-wide tile. Slot i of the first tile is then always the partner of slot i of the second, and both land in the same thread, so the rotation becomes simple element-wise math with no data moving between threads.

Without reordering: one 512-wide tile, 16 dimensions per thread
thread012345678910111213141516171819202122232425262728293031064256320512swap between threads
Dimension 5 lives in thread 0, but its partner 261 lives in thread 16. To rotate the pair, the two threads have to exchange values first. The same is true for all 64 pairs.
With two 64-wide tiles: 2 slots of each tile per thread
thread012345678910111213141516171819202122232425262728293031A0–63B256–319slot 5 of both tiles → thread 2Each colour is one thread: the colours line up between A and B, for every pair.
Thread 2 holds slots 4 and 5 of both tiles: dimensions 4 and 5, and their partners 260 and 261. It can rotate its pairs on its own, with no exchange:
a′ = a·cos − b·sin, b′ = b·cos + a·sin
An example thread layout, simplified to one cached vector and one group of 32 threads; real kernels split tiles across threads in more elaborate ways, but the problem and the fix are the same. Drag the slider to pick a pair: without reordering, the two halves of every pair land 16 threads apart; with the two tiles, every thread holds both halves of its own pairs.

For each tile of cached tokens, the kernel:

Does it work?

The repo plugs the kernel into Hugging Face's real google/gemma-4-12B (bf16, RTX 4090, 1,024-token prompt plus 128 generated tokens) and compares it with the stock model:

Two honest caveats. The whole-model saving is below 50%, because the sliding-window layers keep their normal cache. And at this short length peak GPU memory didn't drop, since weights and prefill buffers dominate; the saving pays off at long contexts and large batches. Still to measure: a 512-vs-640 speed comparison on a GPU, long-context peak memory on a larger GPU, and H100 numbers.

References