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:
- Inference only. We don't touch training or the weights. The model computes the same math; we only change how its cache is stored and read. In fact we only change the decode step (generating one token at a time). Processing the prompt (prefill) is compute-bound rather than memory-bound, so it stays stock.
- Global attention layers only. The sliding-window layers keep their normal cache. Their cache is already capped at the window size, so the global layers are where the memory goes, and that's what we optimize.
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.
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.
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%.
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.
For each tile of cached tokens, the kernel:
- Loads the
vtile once from GPU memory. The two small rotary blocks are re-read from the cache lines that were just fetched, so they cost no extra memory traffic. - Rebuilds the rotated Key blocks in registers. Sines and cosines come from the angle-addition formula: 64 sines and 64 cosines per tile rather than per token, plus a few multiply-adds per element.
- Computes the attention scores as three dot products that add up exactly to
q·k: one 512-wide product against the rawv(withwfolded into the query), plus two 64-wide products against the rebuilt rotary blocks. - Reuses the same
vtile for the output (softmax · V), with no second read.
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:
- Same text: all 128 greedily generated tokens are identical, and the top-1 prediction agrees 100% of the time. Each global layer's output matches stock attention to within bf16 rounding (max relative error 1.75%, mean 0.35%).
- Half the global cache: 18.00 MiB → 9.00 MiB measured at 1,152 tokens, i.e. 8 KB per token, or about 1 GB per 128K-token sequence.
- Fast: the kernel reaches 858 GB/s, about 85% of the 4090's peak memory bandwidth, at batch 4 and 32K context.
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
- Gemma Team, Gemma 4 technical report, arXiv:2607.02770, 2026. huggingface.co/papers/2607.02770
- K. Bainsla, Storing the Gemma 4 K=V Cache Once: Exact Global-KV Memory Savings in a Paged Serving Engine with Unchanged Attention Kernels, arXiv:2611.23035v2, 2026. arxiv.org/html/2611.23035v2