CASSQ: Spending KV Cache Bits Only Where the Context Needs Them
Standard quantization treats a cryptographic key in your prompt and the word "the" exactly the same way. Every token in a 32,000-token context gets the same number of bits, whether it is a variable name the model will need in 20,000 tokens or a line of boilerplate it will never look at again. On a local GPU, where the KV cache is what runs out first, that felt wasteful to me.
So I worked out an idea I call CASSQ, Context-Aware Semantic Salience Quantization. GPTQ and AWQ decide precision once, offline, from weight statistics and calibration activations. CASSQ decides at inference time, per token: a cheap entropy score reads each token's hidden state and decides whether that token's keys and values are stored at 8 bits or squeezed down to 2.
This post has the maths (including the page from my notebook), working code, the memory numbers, and the problems I have not solved yet. There are no benchmarks yet; that is the next post.
The idea in one paragraph
Not every token needs the same precision to be useful later. Low-salience tokens (grammar, filler, repeated boilerplate) can survive heavy compression. High-salience tokens (identifiers, numbers, keys, logical operators) need to stay sharp, because attention will come back to them. CASSQ sits next to the attention layer: when a block of tokens is written into the KV cache, it scores each token and quantizes that token's K and V rows to b_high or b_low bits.
Weights or KV cache?
My first draft quantized the projection weights per token. That does not work: a weight matrix is shared by every token, so there is no "weight column for token 17" to compress. The thing that really is stored per token is the KV cache, and at long context it is also the thing that eats your VRAM. So CASSQ applies to the cache. The weights stay quantized however you normally load them (4-bit AWQ, 8-bit, whatever fits).
The maths
Take the hidden states of one layer, H ∈ ℝB×L×D (batch, sequence length, hidden size). This is how I first wrote it out by hand:
Typed up, with one correction to the quantizer that I explain below.
Step 1: a probability distribution per token. For token position t, softmax over the hidden features:
P_t(i) = exp(H_t,i) / Σ_{j=1..D} exp(H_t,j)
Step 2: normalized Shannon entropy. Dividing by ln D maps the entropy to [0, 1]. A flat distribution gives a value near 1; a peaked one gives a value near 0:
E(t) = − (1 / ln D) · Σ_{i=1..D} P_t(i) · ln( P_t(i) + ε ), ε = 10⁻⁹
The ε only stops ln(0) from blowing up.
Step 3: salience. Flip it so that 1 means "concentrated, specific information":
S(t) = 1 − E(t)
Step 4: bit allocation. A hard step against a threshold τ that you tune per model:
b_t = b_high if S(t) ≥ τ
b_t = b_low if S(t) < τ
Step 5: quantize the token's K and V rows. For a row x with range [α, β] = [min x, max x]:
Δ_t = (β_t − α_t) / (2^b_t − 1)
z_t = round( −α_t / Δ_t )
q = clamp( round(x / Δ_t) + z_t, 0, 2^b_t − 1 )
x̃ = (q − z_t) · Δ_t
The correction. In my notebook I used the asymmetric step Δ = (β − α)/(2b − 1) but clamped to the symmetric range [−2b−1, 2b−1 − 1] with no zero point. Those two do not match. For a row whose values are all positive, the top half of the codes would be clipped. Either use the zero point z as above (asymmetric), or use a symmetric step Δ = max|x| / (2b−1 − 1) with the signed clamp. I use the asymmetric one, because K rows are often not centred on zero.
Step 6: attention as usual, on the dequantized cache:
Attention(Q, K̃, Ṽ) = softmax( Q·K̃ᵀ / √d ) · Ṽ
The code
Here is a reference implementation, written for clarity, not speed. It quantizes each token's K and V rows per head, so every head row gets its own scale and zero point.
import torch
def salience(hidden: torch.Tensor) -> torch.Tensor:
"""hidden: [B, T, D] -> salience in [0, 1] for each token, shape [B, T]."""
p = torch.softmax(hidden.float(), dim=-1)
entropy = -(p * torch.log(p + 1e-9)).sum(-1)
return 1.0 - entropy / torch.log(torch.tensor(float(hidden.shape[-1])))
def quantize(x: torch.Tensor, bits: int):
"""Asymmetric quantization along the last dim. Returns codes, scale, zero point."""
lo, hi = x.amin(-1, keepdim=True), x.amax(-1, keepdim=True)
qmax = 2 ** bits - 1
scale = (hi - lo).clamp(min=1e-8) / qmax
zero = torch.round(-lo / scale)
q = torch.clamp(torch.round(x / scale) + zero, 0, qmax).to(torch.uint8)
return q, scale, zero
def dequantize(q, scale, zero):
return (q.float() - zero) * scale
class CASSQKVCache:
def __init__(self, high_bits=8, low_bits=2, tau=0.35):
self.high_bits, self.low_bits, self.tau = high_bits, low_bits, tau
self.chunks = []
def append(self, hidden, k, v):
"""hidden: [B, T, D]; k, v: [B, H, T, d]. One precision decision per position."""
keep = salience(hidden).mean(0) >= self.tau # [T]
groups = []
for bits, mask in ((self.high_bits, keep), (self.low_bits, ~keep)):
if mask.any():
groups.append((mask, quantize(k[:, :, mask], bits), quantize(v[:, :, mask], bits)))
self.chunks.append((k.shape, groups))
def read(self):
ks, vs = [], []
for shape, groups in self.chunks:
k, v = torch.empty(shape), torch.empty(shape)
for mask, kq, vq in groups:
k[:, :, mask] = dequantize(*kq)
v[:, :, mask] = dequantize(*vq)
ks.append(k)
vs.append(v)
return torch.cat(ks, dim=2), torch.cat(vs, dim=2)
Two things in this version would not survive a real deployment. The 2-bit codes are stored one per uint8, so they save nothing until you pack four codes into each byte. And read() dequantizes the whole cache every step. A real implementation packs the codes and dequantizes inside the attention kernel, which is how KIVI-style KV quantization gets its speed.
What it saves
Take a 27B-to-32B-class model with grouped-query attention: 64 layers, 8 KV heads, head size 128. Each token stores K and V for every layer:
values per token = 2 × 64 × 8 × 128 = 131,072
FP16 bytes per token = 131,072 × 2 = 256 KiB
| Cache format | Avg bits per value | Per token | 32k context |
|---|---|---|---|
| FP16 | 16 | 256 KiB | 8.0 GiB |
| Uniform 8-bit | 8 + 0.25 | 132 KiB | 4.1 GiB |
| Uniform 4-bit | 4 + 0.25 | 68 KiB | 2.1 GiB |
| CASSQ, 30% of tokens at 8 bits, 70% at 2 | 3.8 + 0.25 | 65 KiB | 2.0 GiB |
| CASSQ, 15% at 8 bits, 85% at 2 | 2.9 + 0.25 | 50 KiB | 1.6 GiB |
The extra 0.25 bits are the FP16 scale and zero point stored for every 128-value row.
Be honest about this table. At a 30/70 split, CASSQ uses about the same memory as plain 4-bit. The bet is not that it is smaller. The bet is that it spends the same bits better: 8 bits on the tokens that matter, instead of 4 bits on everything. Real savings only come if salient tokens are rare, around 15% or fewer, and only a quality benchmark can show whether that holds.
It also does not let you fit a 70B model on a small GPU. The weights of a 70B model at 4 bits are around 40 GB no matter what you do to the cache. CASSQ helps the long-context part of the budget, not the weights.
Where it can break
These are the problems I already know about:
- Entropy over hidden features is a proxy, not semantics. It measures how peaked a token's activation vector is. Large models also have a few "massive activation" channels that are huge on almost every token. A softmax over the hidden dimension can be dominated by those channels, making nearly every token look salient. You may need to drop those channels, normalize per channel, or score after the layer norm.
- Salience is decided when the token is written. A token that looks boring at position 500 can become crucial at position 30,000, when the user asks about it. Once it is stored at 2 bits, that precision is gone. Methods that score by attention received (H2O, ZipCache and others) see how the model actually uses a token, but only after the fact.
- 2 bits is brutal for keys. Keys have strong outlier channels. KIVI quantizes keys per channel and values per token for exactly this reason. CASSQ may need the same split, with salience only choosing the bit width.
- The threshold is per model. τ = 0.35 is a starting guess, not a constant. It should be set from a target share of high-precision tokens (say, the top 20% per layer) rather than a fixed number.
- Overhead. Computing a softmax and an entropy for every token at every layer is cheap compared with attention, but it is not free. It should be fused into the kernel that writes the cache.
What I will measure next
The plan for the follow-up post:
- Perplexity on long documents at 8k, 32k and 64k context: FP16, uniform 4-bit, uniform 2-bit and CASSQ at several thresholds.
- Needle-in-a-haystack retrieval, where the needle is exactly the kind of rare token CASSQ is meant to protect.
- Long-context code questions, where variable names a few thousand lines back decide the answer.
- The share of tokens that actually end up at 8 bits, layer by layer.
If CASSQ beats uniform 4-bit at the same memory, it is worth building a real kernel. If it does not, the entropy proxy is the first suspect, and attention-based salience is the next thing to try.