cd ..
← Part 1 · How LLMs Work Part 2 · Advanced · no math required

How a large language model runs fast — and cheap

You know how an LLM works — tokens, attention, next-token prediction, prefill vs decode. This part is the other half: how a 140-gigabyte model gets squeezed onto a single GPU and made to answer in milliseconds. Every chapter is one trick, and every trick beats one of these bottlenecks.

Compute-bound doing the math (prefill) Memory-bandwidth-bound moving weights in & out (decode) Memory-capacity-bound fitting it all in VRAM
Scroll to begin · 9 short chapters
01 / THE TWO BOTTLENECKS

Reading your prompt is fast. Writing the reply is the slow part.

Running a model splits in two. Prefill reads your whole prompt in one parallel pass — lots of math at once, so the GPU's math units are the limit (compute-bound). Decode writes the answer one token at a time, and for every token the GPU must stream all the model's weights out of memory just to take one step. The math is tiny; the memory traffic is huge (memory-bandwidth-bound). That one re-read is what the whole page is about.

Prefill vs decodecomputebandwidth
idle
GPU math units
0%
Memory bandwidth
0%

THE TELL →  During decode the math bar sits nearly empty while the bandwidth bar is pinned at 100%. The GPU is mostly waiting on memory, not computing — so faster memory helps generation more than faster math.

MythGenerating a token is slow because the model "thinks hard."
RealityThe math for one token is trivial. The cost is physically moving every weight from memory to the compute units — once per token.
02 / HOW A WEIGHT IS STORED

Every weight is a number — and numbers cost bits

A weight is a floating-point number in three parts: a sign (±), an exponent (roughly how big), and a mantissa (the precise digits). fp32 spends 32 bits per weight, fp16 16, bf16 also 16 but trades mantissa precision for more range. Fewer bits = less to store and less to move — and since decode is bottlenecked on moving weights, fewer bits is fewer milliseconds.

One weight, bit by bitcapacitybandwidth
sign
exponent · range
mantissa · precision
the value 0.1 becomes
0.1 → 0.10000000
bytes / weight
4

RANGE vs PRECISION →  fp16 and bf16 are both 16 bits, but bf16 keeps a wide exponent (won't overflow) at the cost of a shorter mantissa (coarser steps). Same size, different trade — that's why training loves bf16.

03 / FEWER BITS, ALMOST FREE

Quantization: store weights in far fewer bits

Weights don't need full precision — the model shrugs off small rounding. Quantization maps a range of real values onto a small set of evenly spaced levels: pick a scale, then round each weight to the nearest level. 8-bit gives 256 levels, 4-bit just 16 — and it still works. A 70-billion-parameter model is ~140 GB in fp16, but ~35 GB in 4-bit: the difference between four GPUs and one.

Quantization mapper · weights snapping to levelscapacitybandwidth
70B model in memory
35 GB · int4 tiny quality drop
levels  ·  avg rounding error
16 levels

THE HARD PART →  A few giant outlier weights stretch the range so everyone else crams into a handful of levels. Per-group scales (a separate scale per small block) and protecting outliers (keeping the few big ones in high precision — the idea behind GPTQ/AWQ) rescue the precision. Modern low-bit formats: int4 · nf4 · fp8 · mxfp4 · nvfp4.

MythA 4-bit model is a crippled, 4×-worse model.
RealityThe memory is 4× smaller; the quality drop is small and non-linear. The weights were never that precise to begin with.
04 / DON'T REDO THE PAST

The KV cache: remember what you already computed

In attention, each new token needs the keys and values of every earlier token — and those never change as you generate. So compute each token's K and V once and cache them; each new token then only computes its own and reads the rest. Decode goes from redoing all past work every step to doing just one token's worth. The catch: the cache grows with every token, and at long context it can outweigh the model itself.

Recompute vs cachesaves bandwidthcosts capacity
work this step
low
KV-cache memory (illustrative, 70B-class)
■ weights (int4, 35 GB)■ KV cache 4 GB

THE NEW PROBLEM →  Push context and concurrency up and the cache balloons — soon rivalling the weights. That's what the next chapter's paging and quantized KV cache exist to tame.

MythThe KV cache stores the text of the conversation.
RealityIt stores computed key/value vectors, not tokens — and it grows with context and concurrency, which is why long chats get expensive.
05 / MANAGE MEMORY LIKE AN OS

Paged attention & prefix caching

Two problems with the growing cache, two fixes. Reserve each request's maximum cache up front and most of it sits empty — paged attention (the idea behind vLLM) chops the cache into fixed pages placed wherever there's room, like an OS's virtual memory, so far more requests fit. And when many requests share a prefix — a system prompt, a document, earlier chat turns — prefix caching computes it once and reuses it.

Paging · fit more requests in the same memorycapacity
requests served
2
memory wasted
58%
Prefix caching · compute the shared part oncecompute
prefill tokens saved
0

MULTI-TURN →  Each new turn of a chat reuses the cache of all previous turns — the shared prefix (system prompt + history) is computed once and simply extended. Paging never changes the answer; it's pure memory management.

06 / MANY TOKENS PER STEP

Speculative decoding: guess ahead, verify in one pass

Decode's expensive step reads the whole model to make one token — wasteful. So a small fast draft model proposes several tokens cheaply; the big target model then checks them all in a single parallel pass and keeps the longest run it agrees with, rejecting from the first disagreement. When the draft is right, you get several tokens for the price of one expensive step — and the output is exactly what the target would have written alone.

Draft → verify → accept / rejectbandwidth
draft length k:
The quick brown fox jumps over the lazy
tokens committed
0
expensive steps
0
tokens / step
0.0×
plain decode — 1 token per expensive step
speculative — several per step (when the draft agrees)
MythThe small model's mistakes leak into the answer.
RealityEvery token is verified by the target; rejects are thrown away. The text is exactly what the target alone would have written — this is speed, not a quality change.
07 / SHARE THE WEIGHT-READ

Continuous batching: read the weights once, serve many

One decode step reads the entire model no matter what — so push many requests' tokens through that single read at once, and the expensive weight-read is amortized across everyone. Static batching wastes it by waiting for the whole batch to finish; continuous batching swaps a finished request out and a new one in every step, keeping the GPU near 100% busy.

Slots over time · green = a token was producedthroughput
GPU utilization
96%
throughput
~2×

THROUGHPUT ≠ LATENCY →  Batching multiplies total tokens/second across users; it doesn't make any single reply arrive sooner. It's the reason a served model can answer thousands of people at once for the same weight-reads.

08 / THE REST OF THE TOOLKIT

Four more ideas, one line each

A quick sweep of the other big levers — each with the bottleneck it beats.

FlashAttention

Compute attention in small tiles that stay in the GPU's fast on-chip memory, so the huge N×N attention matrix is never written out to slow memory.

beats: bandwidth

Mixture-of-Experts

Split the feed-forward layer into many experts and route each token to just one or two — huge total capacity, but only a slice of the weights runs per token.

beats: computecosts: capacity

Distillation

Train a small "student" model to imitate a big "teacher" — much of the quality at a fraction of the size and cost. A genuinely smaller model to run.

computebandwidthcapacity

Early-exit & cascades

Answer easy tokens or queries with cheap computation — fewer layers, or a small model first — and only escalate the hard ones to the full model.

beats: compute
09 / THE WHOLE TOOLKIT

Every trick, mapped to the bottleneck it beats

The payoff. ● compute-bound · ● memory-bandwidth · ● memory-capacity. A dashed ◇ marks a cost the trick adds.

TechniqueComputeBandwidthCapacity

So which do you reach for?

won't fit in memory →quantize the weights, or use a Mixture-of-Experts model
throughput too low →continuous batching — amortize the weight-read across many users
latency too high →speculative decoding, and prefix caching for shared prompts
context too long →paged + quantized KV cache to keep the cache in bounds
quantization
Storing weights in fewer bits by rounding them onto a small set of levels (scale + zero-point). 4-bit ≈ ¼ the memory.
per-group scales
A separate scale for each small block of weights, so a few outliers can't blow the precision for everyone.
PTQ vs QAT
Quantize a finished model (post-training) vs train it to expect the rounding (quantization-aware) — more work, better at very low bits.
KV cache
Cached key/value vectors of past tokens so decode does one token's work per step, not the whole sequence's. Grows with context.
paged attention
Manage the KV cache in fixed pages like OS memory, so it doesn't fragment and far more requests fit (vLLM).
prefix caching
Reuse the computed cache of a shared prompt prefix instead of re-running prefill for every request.
speculative decoding
A small draft proposes tokens; the big target verifies them in one pass. Several tokens per expensive step, identical output.
continuous batching
Add and drop requests every step so one weight-read serves a full batch. Multiplies throughput, not single-request latency.
FlashAttention
Tile attention so the big score matrix never touches slow memory — a bandwidth win with identical math.
mixture-of-experts
Many expert sub-networks, only a couple active per token. Big total capacity, small per-token compute.
distillation
A small student trained to match a big teacher's outputs — a smaller model that keeps much of the quality.
MythThese tricks make the model dumber to make it faster.
RealityMost are lossless or nearly so. They change how the same computation is scheduled and stored — not what the model says.