TurboQuant KV Cache — Getting Started
This tutorial loads a Gemma checkpoint, replaces the KV cache of its global attention layers with a compressed one, and measures two things: how many bytes the cache takes, and whether the model still picks the same tokens. The variants are explained in The KV Cache Family.
Prerequisites
-
JDK 21+.
-
A Gemma GGUF, for example
functiongemma-270m-it-BF16.gguf. -
A SKaiNET-transformers release that contains
TurboQuantKVCache.
Step 1: Dependencies
dependencies {
implementation(platform("sk.ainet.transformers:skainet-transformers-bom:<version>"))
implementation("sk.ainet.transformers:skainet-transformers-inference-gemma")
}
Step 2: Load the model
import sk.ainet.apps.llm.OptimizedLLMMode
import sk.ainet.apps.llm.OptimizedLLMRuntime
import sk.ainet.context.DirectCpuExecutionContext
import sk.ainet.io.JvmRandomAccessSource
import sk.ainet.lang.nn.Module
import sk.ainet.lang.nn.transformer.MultiHeadAttention
import sk.ainet.lang.nn.transformer.PositionalKVCache
import sk.ainet.lang.nn.transformer.TurboQuantKVCache
import sk.ainet.lang.nn.transformer.TurboQuantKvPreset
import sk.ainet.lang.types.FP32
import sk.ainet.models.gemma.GEMMA_DEQUANTIZE_ALL
import sk.ainet.models.gemma.GemmaNetworkLoader
import sk.ainet.models.gemma.GemmaWeightLoader
val ctx = DirectCpuExecutionContext.create()
val weights = GemmaWeightLoader(
randomAccessProvider = { JvmRandomAccessSource.open("functiongemma-270m-it-BF16.gguf") },
weightForm = GEMMA_DEQUANTIZE_ALL,
).loadToMapStreaming<FP32, Float>(ctx, FP32::class) // suspend: call from a coroutine
val model = GemmaNetworkLoader.fromWeights(ctx, weights, FP32::class)
The builder has already given every sliding-window layer a ring cache and every global layer a
full-history PositionalKVCache.
Step 3: Pick a preset
| Preset | Keys | Values | Use it when |
|---|---|---|---|
|
8 bit |
4 bit |
you want the saving with little change in output |
|
4 bit |
4 bit |
memory is tight and you have measured the quality |
|
3 bit |
3 bit |
you are exploring; expect different tokens |
Start with SAFE_LOWBIT.
Step 4: Replace the caches of the global layers
MultiHeadAttention.kvCache is assignable. Walk the module tree and swap every full-history
cache; leave the rings and the shared followers alone.
fun attentionLayers(m: Module<FP32, Float>, out: MutableList<MultiHeadAttention<FP32, Float>> = ArrayList()):
List<MultiHeadAttention<FP32, Float>> {
if (m is MultiHeadAttention<FP32, Float>) out += m else m.modules.forEach { attentionLayers(it, out) }
return out
}
val compressed = ArrayList<TurboQuantKVCache<FP32, Float>>()
attentionLayers(model).forEachIndexed { layer, mha ->
val cache = mha.kvCache
if (cache is PositionalKVCache<FP32, Float> && cache.window == null) { // full history only
val tq = TurboQuantKVCache<FP32, Float>(
cache.maxSeqLen, cache.nKVHeads, cache.headDim,
TurboQuantKvPreset.SAFE_LOWBIT, cache.name, seed = layer,
)
compressed += tq
mha.kvCache = tq
}
}
seed makes the rotations of each layer different. Do the swap before the first token: a cache
replaced in the middle of a sequence starts empty.
Step 5: Decode
val runtime = OptimizedLLMRuntime(model, ctx, OptimizedLLMMode.DIRECT, FP32::class)
var token = weights.metadata.bosTokenId
repeat(48) {
val logits = runtime.forward(token).data.copyToFloatArray()
token = logits.indices.maxBy { logits[it] } // greedy
}
Nothing else changes. Each step, a compressed layer encodes its new row and decodes its history for the attention call.
Step 6: Read the memory
val stored = compressed.sumOf { it.storedBytes }
val dense = compressed.sumOf { it.denseBytes }
println("KV payload: $stored bytes instead of $dense (${dense.toDouble() / stored}x smaller)")
storedBytes counts packed codes, scales and seeds; denseBytes is what the same history takes
as floats. For FunctionGemma 270M after 48 tokens with SAFE_LOWBIT:
KV payload: 65664 bytes instead of 294912 (4.49x smaller)
Step 7: Check the output
Compression changes the logits. To see how much, run the same tokens through an unmodified model and compare.
val reference = OptimizedLLMRuntime(
GemmaNetworkLoader.fromWeights(ctx, weights, FP32::class), ctx, OptimizedLLMMode.DIRECT, FP32::class,
)
fun argmax(a: FloatArray) = a.indices.maxBy { a[it] }
var same = 0
var next = weights.metadata.bosTokenId
repeat(48) {
val expected = reference.forward(next).data.copyToFloatArray()
val actual = runtime.forward(next).data.copyToFloatArray() // a fresh runtime over the compressed model
if (argmax(actual) == argmax(expected)) same++
next = argmax(expected) // both follow the reference's tokens
}
println("same top token on $same of 48 steps")
On FunctionGemma 270M, 48 greedy steps, global layers compressed:
| Preset | Smaller by | Same top token | Relative logit error |
|---|---|---|---|
|
4.5× |
47 of 48 |
2.4 % |
|
6.2× |
41 of 48 |
14.7 % |
|
7.8× |
27 of 48 |
24.0 % |
RealGemmaTurboQuantKvTest in llm-inference/gemma is this measurement as a test
(GEMMA_GGUF=… ./gradlew :llm-inference:gemma:jvmTest -PincludeIntegration --tests 'RealGemmaTurboQuantKvTest').
When not to use it
-
Sliding-window layers: the ring already bounds their memory, without error.
-
Short contexts: the cache is small either way, and decoding the history costs time every step.
-
StableHLO export: the cache encodes nothing while recording, so the exported graph is unaffected and gains nothing.
Where to look next
-
The KV Cache Family for the other variants and the ring.
-
Parallel Attention Heads via Schedules for how attention reads a cache.