Quantize a KV cache to int8 per token and head
Why it matters Int8 and lower-bit KV caches let servers fit more concurrent long-context requests on the same GPU.
The KV cache often dominates memory for long contexts. Storing it in int8 with one fp16 scale per token and head roughly halves its size.
Write quantize_kv(K). K has shape (H, T, D). For each head h and token t, scale[h, t] = max|K[h, t, :]| / 127 (0 becomes 1). q = clip(round(K / scale), -127, 127) as int8. Return a dict {"q": q, "scale": scale (H, T), "max_err": the largest absolute error between K and q * scale, "bytes_fp16": H * T * D * 2, "bytes_int8": H * T * D + H * T * 2 (int8 values plus fp16 scales)}.
def quantize_kv(K)Example
K [[[1, -2, 0.5]]] gives q [[[64, -127, 32]]], scale [[2/127]], bytes_fp16 6, bytes_int8 5, max_err 0.0079 (from 1 -> 64 * 2/127).
Understand the idea
Quantizing the KV cache is like saving photos as compressed files: you keep one small header per photo (the scale) and store each pixel with fewer bits. Each token's key vector is its own photo, because some tokens have much larger keys than others. Worked example: key [1, -2, 0.5]. The largest magnitude is 2, so scale = 2 / 127. Dividing gives [63.5, -127, 31.75], which rounds to [64, -127, 32]. Reconstructing 64 x 2 / 127 = 1.0079, an error of 0.0079. Memory: 3 values in fp16 is 6 bytes; int8 is 3 bytes plus a 2-byte scale, 5 bytes. Rule: s = max|k| / 127, q = round(k / s). For real head sizes like 128, the scale overhead is tiny and the cache shrinks almost by half.
Shapes and data flow
K (H, T, D) -> scale (H, T) -> q (H, T, D) int8