Cheat sheets

Inference Optimization: KV Cache, Quantization, Batching

KV cache, quantization, batching and speculation. Formulas, scheduler numbers and the mistakes that cost latency.

  • Concepts and terms
  • Tasks and commands
  • Annotated code
  • Diagrams
  • Defaults and numbers
  • Troubleshooting
  • Questions and tips

Source

Inference pipeline#

arrivereuse prefixblocks freeprompt doneappendreadclientRequestqueue and arrivalstorePrefixCacheshared prompt trieprocessAdmitfree KV blocksstoreKVCacheK and V per tokengpuPrefillchunked promptgpuDecodeone token per steparrivereuse prefixblocks freeprompt doneappendreadclientRequestqueue and arrivalstorePrefixCacheshared prompt trieprocessAdmitfree KV blocksstoreKVCacheK and V per tokengpuPrefillchunked promptgpuDecodeone token per step

One decode step#

1Writekv_cache.update stores the new K and V for eachlayer.2ReadThe cache returns the slices up to the currentlength.3Attendscaled_dot_product_attention runs over thecached prefix.4AdvanceOn a one-token decode, kv_cache.advance(1) movesthe length.

Core softmax update#

new_m = max(m, *scores)running max
if m == float("-inf"):
exp_old = 0.0
else:
exp_old = math.exp(m - new_m)rescale old sums
exp_new = [math.exp(sc - new_m) for sc in scores]
s = s * exp_old + sum(exp_new)running sum

Task reference#

TaskCode
Count KV cache byteskv_cache_bytes(N, n_layers, n_heads_kv, d_head, dtype=2)
Tiled attention outputtiled_softmax_dot(q, Ks, Vs, tile=4)
Simulate batchingsimulate_continuous_batching(requests, batch_size)
Cache a shared prefixPrefixCache(max_entries=1000)
Speculate tokensspeculative_decode(draft_model, target_model, context, num_speculative=5)
Check memory fitmemory_budget(config, gpu_memory_gb)

Defaults#

SettingDefaultNote
dtype in kv_cache_bytes2Bytes per value. fp16 or bf16
tile in tiled_softmax_dot4Keys per tile
max_entries in PrefixCache1000Trie node limit
num_speculative5Draft tokens per round
acceptance_rate in DraftModel0.8Simulated accept rate
CHUNK_SIZE512Prefill tokens per slice
KV_BLOCK_SIZE16Tokens per KV block
KV_BLOCKS_AVAILABLE1800Toy block budget

Formulas#

KV cache bytes
2 * N * n_layers * n_heads_kv * d_head * dtype.
Per token KV
two tensors times layers, KV heads, head size and item size.
Running max softmax
the output matches a full softmax. Only one tile is held.
Block count
ceiling of total tokens divided by the block size.
Quantization scale
abs max divided by the integer range maximum.

Glossary#

KV cache
Stored keys and values for past tokens, so they are not recomputed.
Prefill
Processing the whole prompt before the first output token.
Decode
Producing one output token per step.
TTFT
Time to first token. Set when prefill ends.
ITL
Inter-token latency. Time between output tokens.

Troubleshooting#

SymptomCauseFix
Prefix lookup returns 0First tokens differ, so the trie walk stopsKeep the shared prompt identical from token one
Trie stops insertingmax_entries reachedRaise max_entries
Batch slots sit idleStatic batch waits for the longest outputUse continuous batching
Decode stalls on a long promptPrefill is not chunkedSet chunked so prefill uses CHUNK_SIZE
Speculation is slowerLow acceptance rateMeasure the rate before enabling it
Model does not fitWeights exceed GPU memoryQuantize or add GPUs

Questions#

Why store K and V?
Each decode step reads them instead of recomputing the prefix.
Why is static batching wasteful?
Every row waits for the largest output length.
Why chunk prefill?
A long prompt would block the decode tokens of other requests.
Why do benchmark tools disagree on TPOT?
One counts the TTFT time in the rate and the other does not.

Tips#

  • Report P99 latency, not the mean. Check each request against all three limits.
  • Derive the chunk size and block count from the scheduler constants.
  • Keep the shared prompt prefix identical across requests.
  • Check KV memory against the budget before raising the batch size.