🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

LLM Inference Optimization: KV Cache to Batching

đŸŸĸ Free Lesson

LLM Inference Optimization

Getting more generated tokens per second out of the GPU you already pay for.

Serving

Prerequisites

  • !Transformer attention and masked self-attention
  • !GPU memory vs compute trade-offs
  • !How autoregressive decoding emits one token at a time

What You'll Learn

  • 1Explain why prefill and decode have opposite performance profiles
  • 2Trace what a KV cache stores and quantify its memory cost
  • 3Describe the accept step that makes speculative decoding lossless
  • 4Choose between static batching, continuous batching and quantization for a given latency budget

Serving is a bandwidth problem, not a math problem

Ask a team why their chatbot feels slow and the first answer is usually "the model is too big". Bigger models are slower, but size is not the real story. During generation the GPU performs a matrix multiply against a single token vector — a compute operation so small that the chip spends most of its time waiting for weights to arrive from memory. FLOPs sit idle while HBM bandwidth becomes the bottleneck.

That single fact organizes every technique in this lesson. Anything that reduces memory traffic per generated token — caching attention states, shrinking weights, keeping more requests in flight — buys more than anything that adds arithmetic. Optimizing inference is therefore mostly bookkeeping: store what you have already computed, avoid recomputing it, and pack independent work into the same memory pass.

The practical payoff is large. A 7B model that streams 20 tokens per second can often reach 60 or 80 with the same weights and the same hardware, without a single line of application code changing. Everything below is a different way of paying less bandwidth for the same output.

This also explains why scaling a model up hurts inference far more than scaling it up hurts training. Training amortizes weight reads across thousands of tokens in a batch, so a big model still keeps its arithmetic units busy. Generation reads those same weights once per single token, so doubling parameters roughly doubles the bytes each token must drag through memory. Teams that plan capacity from training throughput numbers routinely end up with serving bills several times larger than expected.

What the KV cache stores and why it pays for itself

During attention, every layer keeps the keys and values produced for each earlier token so later tokens can attend to them. Without a cache, producing token number 500 would mean re-running attention over all 499 previous positions again — quadratic work for a linear-time requirement. The cache turns that into a lookup: append the new key and value, then read the whole sequence back.

The trade is memory for compute. A rough sizing rule is:

Architecture Diagram
cache_bytes = 2 × layers × hidden × bytes_per_param × sequence_length × batch

For a 7B model with 32 layers, a 4096-wide hidden state, fp16 weights and a batch of 8 at 4096 context, the cache runs to roughly 14 GB — often rivaling the weights themselves. Long-context workloads fail on cache memory long before they fail on model size.

python
import torch

class KVCache:
    """Pre-allocated key/value cache for one decode stream."""

    def __init__(self, num_layers, num_heads, head_dim, max_len, dtype=torch.float16):
        self.keys = [
            torch.zeros(1, num_heads, max_len, head_dim, dtype=dtype)
            for _ in range(num_layers)
        ]
        self.values = [
            torch.zeros(1, num_heads, max_len, head_dim, dtype=dtype)
            for _ in range(num_layers)
        ]
        self.pos = 0

    def update(self, layer_idx, key, value):
        seq = key.shape[2]
        self.keys[layer_idx][:, :, self.pos:self.pos + seq] = key
        self.values[layer_idx][:, :, self.pos:self.pos + seq] = value
        if layer_idx == len(self.keys) - 1:
            self.pos += seq
        return (
            self.keys[layer_idx][:, :, :self.pos],
            self.values[layer_idx][:, :, :self.pos],
        )

Modern engines improve on this with paged attention, which stores the cache in fixed-size blocks and lets the allocator fill fragmentation gaps the way an operating system pages memory. The result is more concurrent sequences per GPU with the same quality.

Prefill and decode have opposite bottlenecks

Every request has two phases, and they behave almost inversely. Understanding which phase you are optimizing prevents wasted effort.

PhaseWhat it doesBottleneckMetric that matters
PrefillReads the whole prompt in one forward passCompute (large GEMMs)Time to first token
DecodeEmits one token per step using the cacheMemory bandwidthTokens per second
Chunked prefillSplits a long prompt into piecesBalancedTail latency under load

A 2000-token prompt might spend two seconds in prefill and then generate for a minute. Optimizing prefill improves responsiveness; optimizing decode improves sustained throughput. Most serving frameworks therefore mix the two, running chunked prefill steps alongside decode steps so one long prompt cannot stall every other user in the batch.

Speculative decoding: cheap guesses, expensive verification

If each token costs a full model pass, why not let a small model write several tokens and have the large model check them in one pass? The verifier scores a whole draft sequence at once — parallel, not sequential — so it can accept or reject several tokens for roughly the price of generating one. The output distribution stays identical to the large model's, which is what makes the trick safe rather than approximate.

python
def speculative_step(draft, target, tokens, gamma=5):
    """Draft gamma tokens, verify them in a single target pass."""
    draft_tokens = draft.greedy(tokens, n=gamma)
    probs = target.probs(torch.cat([tokens, draft_tokens]))

    accepted = []
    for i, tok in enumerate(draft_tokens):
        p = probs[len(tokens) + i - 1, tok]
        q = draft.prob(i, tok)
        if torch.rand(1) < min(1.0, p / q):
            accepted.append(tok)
        else:
            rejected = target.sample_from(probs[len(tokens) + i - 1])
            accepted.append(rejected)
            break
    return torch.stack(accepted)

Speedups land between 1.5× and 3× whenever the draft model agrees with the target most of the time — boilerplate, code scaffolding and repetitive formats are the best cases, while creative prose gains less.

Continuous batching keeps the GPU busy

Static batching waits for the slowest sequence before starting the next one, so a single long answer idles hundreds of otherwise free slots. Continuous batching decouples the two: the scheduler runs one decode iteration across every active sequence, then immediately slots in newly finished requests and admits waiting ones. Capacity is recycled the moment a stream ends rather than at batch boundaries.

The rule of thumb is that throughput scales roughly with batch size until weights and cache stop fitting, while per-token latency rises with batch size because each step reads more cache. Teams tune an operating point on that curve rather than maximizing either number alone. The table below shows a typical shape for a 13B model on a single A100.

Batch sizeTokens/secMedian latencyMemory used
14224 ms28 GB
821048 ms40 GB
32520130 ms61 GB
64610300 ms92 GB

Choosing a technique for your latency budget

Start by measuring: log time to first token, inter-token latency and tokens per second separately, because a fix for one often hurts another. Interactive assistants need a fast first token and steady streaming, so chunked prefill with a modest batch matters more than raw throughput. Batch backfills and offline summarization jobs want the opposite — push batch size and quantization as far as memory allows and ignore tail latency.

# Baseline: measure before changing anything
python bench.py --model llama-7b --batch 1 --prompt-len 512 --gen 256
python bench.py --model llama-7b --batch 32 --prompt-len 512 --gen 256

# Then isolate one variable at a time
python bench.py --model llama-7b --batch 32 --kv-page 16 --spec-decode draft-1b

When quality is non-negotiable, KV caching, continuous batching and speculative decoding are free — they preserve the output distribution exactly. Quantization is the one lever that trades a small, measurable quality change for a large memory win, so treat it as a product decision rather than an infrastructure one.

💡Measure decode separately from prefill

Log time to first token and inter-token latency as two distinct metrics. A single average hides which phase regressed, and most regressions are phase-specific.

Common Mistakes

Optimizing prompt processing when users complain about streaming speed

Fix: Split metrics by phase first — decode latency is almost always the complaint behind perceived slowness.

Letting the KV cache grow unbounded across a long conversation

Fix: Cap context with sliding-window eviction or summarization, and monitor cache bytes per session.

Assuming a larger batch always means more throughput

Fix: Plot tokens/sec against batch size and stop when cache memory evicts weights or latency passes your budget.

Best Practices

  • Keep the exact-model techniques — KV cache, continuous batching, speculative decoding — as your first pass, since they cost no quality
  • Chunk long prefills so one 8k prompt cannot stall every other request in flight
  • Report time to first token and tokens per second separately in every benchmark
  • Quantize weights only after you have a golden set of prompts to compare before and after

Key Takeaways

  • Decode is memory-bound: reducing bytes read per token beats adding arithmetic
  • The KV cache trades memory for linear-time generation and can rival weights in size at long context
  • Prefill and decode have opposite bottlenecks and need separate metrics
  • Speculative decoding preserves the target distribution while cutting latency 1.5× to 3×
  • Continuous batching recycles capacity per iteration instead of waiting for the slowest sequence
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Generative AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement