rumblr Work in progressWIP

● The AI Primer · Lesson 20 · Part 3: how it is run

Inference

what happens, and what it costs, when a model generates

This lesson covers Why the first token is slow and the rest are cheap, and what memory a conversation costs

Members · open during launch 35 min10 figures and diagrams9 interactive

What this is

What is inference?

Inference is running a trained AI model to get an answer: for a language model, everything between a prompt arriving and the last word of its reply. Training happens once, but inference runs on every request, so it is where the serving bill and the waiting come from. A reply is written one token at a time. How fast that goes, and how many conversations one GPU can hold, are set more by the GPU's memory than by its arithmetic.

Why it matters: The day a language model leaves the notebook, someone asks why the first token takes two seconds, or how many users one GPU can serve. Both answers are a few lines of arithmetic on the language model's size and the GPU's memory.

At a glance

Key takeaways

  1. Each generated token reads every weight from memory, and memory is much slower than arithmetic, so decode waits on memory.
  2. Prefill reads the whole prompt in one parallel pass and sets the time to the first token; decode writes one token per pass and sets tokens per second.
  3. The KV cache keeps every earlier token's keys and values, so each step computes only the new token; it trades GPU memory for speed.
  4. Weights take parameters × bytes: a 70B model is 140 GB at 16-bit. The cache takes 2 × layers × KV heads × head size × bytes for every token: 32k tokens on a Llama-3-8B-shaped model is about 4 GB.
  5. Temperature reshapes the probabilities, and top-k and top-p cut the unlikely tail. Temperature 0 makes output more repeatable but does not guarantee it.
  6. In speculative decoding a small model drafts and the big one checks every draft in one pass; the output follows the big model's distribution.
  7. Quantization makes each read of the weights smaller, continuous batching keeps every slot of a batch busy, and prompt caching skips the prefill of a prefix that requests share.

How it works, from scratch

The time and money a reply costs come from one fact:

Generating one token requires reading every weight of the model from memory, and memory is much slower than arithmetic.

A reply is made in two phases, and they meet this fact in opposite ways.

Chapter 1

Two phases: prefill and decode

Suppose you are handed a letter and asked to reply. Reading the letter is fast: your eyes take in whole lines at once. Writing the reply is slow, because before each word you must walk to a filing cabinet and leaf through an entire reference binder. The walk, not the thinking, takes the time.

A language model answers a prompt the same way. Prefill reads the whole prompt in one parallel pass. Decode then writes the answer one token at a time, and each token means reading all the weights from GPU memory again. That read is the walk to the cabinet.

Take an 8-billion-parameter model stored at 16 bits, which is 16 GB of weights, on a GPU that reads 3.35 TB/s from memory and does about 10¹⁵ 16-bit operations per second:

  • Prefill of a 1,000-token prompt: 2 × 8×10⁹ × 1,000 = 1.6×10¹³ operations, about 16 ms.
  • Decode: read 16 GB for every token, 16×10⁹ / 3.35×10¹² s = 4.78 ms per token, at most about 209 tokens per second for a single user.

Figure 1 · Diagram

Reading it: time runs downward. Above the loop is prefill: one parallel pass over the whole prompt, which also stores the prompt's keys and values in a KV cache (the next chapter explains it). Prefill sets the time to first token. Inside the loop is decode, one small pass per token, each reading the cache and adding one entry to it. Decode sets tokens per second. A long prompt delays the first token; a long answer stretches the whole reply.

The two phases differ in their arithmetic intensity: how many operations they do for each byte they read from memory.

The formula and its symbols

Symbols

Symbol Meaning here Shape / range
arithmetic intensity: operations per byte of weights read FLOPs/byte
tokens processed in one pass (1 when decoding, the prompt length when prefilling) ≥ 1
one multiply plus one add per weight per token
bytes per weight (2 at 16-bit, 0.5 at 4-bit)
number of parameters (weights) e.g. 8×10⁹
BW memory bandwidth: bytes the GPU can read per second e.g. 3.35×10¹²
FLOPS arithmetic throughput: operations per second e.g. 10¹⁵
"roughly": these are lower bounds that ignore overheads

In words: decode does two operations per two-byte weight it reads, so its speed is set by memory bandwidth; prefill reuses each weight for every prompt token, so its speed is set by arithmetic.

On the worked example: decode I = 2 × 1 / 2 = 1 FLOP per byte; prefill of 1,000 tokens I = 1,000. The GPU breaks even at 10¹⁵ / 3.35×10¹² ≈ 299 FLOPs per byte, so decode sits far below it (memory-bound) and prefill far above (compute-bound).

In Python
# 8 billion weights at 2 bytes each (16-bit)
P, b = 8e9, 2
# bytes read per second, operations per second
BW, FLOPS = 3.35e12, 1e15
def I(n):
    # operations per byte of weights read
    return 2 * n / b
# decode, then a 1,000-token prefill
I(1), I(1000)  # → (1.0, 1000.0)
# the break-even intensity
round(FLOPS / BW)  # → 299
# t_decode, in milliseconds per token
round(P * b / BW * 1000, 2)  # → 4.78
# t_prefill for 1,000 tokens, in milliseconds
round(2 * P * 1000 / FLOPS * 1000, 1)  # → 16.0

New to Σ, ∂ or ‖x‖? The symbols reference decodes each one as a few lines of Python.

Figure 2 · Chart

1 0 0 1 0 1 1 0 2 1 0 3 1 0 4 arithmetic intensity (FLOPs per byte of weights read) 1 0 1 2 1 0 1 3 1 0 1 4 1 0 1 5 attainable FLOP/s Decode is memory-bound; prefill is compute-bound break-even ≈ 299 FLOPs/byte decode, 1 user (I = 1) decode, batch of 64 (I = 64) prefill, 1,000 tokens (I = 1000)

Decode for 1 user uses 0.3% of the GPU's compute and a batch of 64 reaches 21%, while a 1,000-token prefill passes the 299 break-even to run at full speed

Reading it: a chart of this kind is called a roofline. The x-axis is arithmetic intensity (log scale) and the y-axis is the speed the GPU can reach. Follow the roof from the left: on its slope memory sets the speed (bandwidth × intensity), and past the corner at about 299 the flat arithmetic limit takes over. Decode for one user (blue) sits at intensity 1, far down the slope, using well under 1% of the GPU's arithmetic. A batch of 64 users (red) sits further up, because one read of the weights serves all 64; that is why inference servers batch many users together. A 1,000-token prefill (green) is on the flat part, past the corner.

So when a system feels slow, first ask which phase is slow. A slow first token means a long prompt: trim it, or cache it. Slow streaming means decode is waiting on memory, and the fix is to read fewer bytes or to make each read of the weights serve more tokens.

In code: arithmetic_intensity, ridge_point and bottleneck place a pass on the roofline; decode_seconds_per_token and prefill_seconds give the two time bounds. View source

Slide the number of tokens in one pass, and watch the dot climb the slope to the roof and the time of the pass change.

Chapter 2

The KV cache

Reading the weights is not decode's only cost. To write each new token, attention compares it with every token before it, through each earlier token's key and value (see Attention). Because of causal masking, an earlier token's key and value never change when later tokens arrive. They can be computed once and kept in a KV cache, instead of being worked out again at every step.

Take an 8-token prompt followed by 16 generated tokens.

  • Without a cache, step k re-processes the whole sequence so far: 8 + 9 + … + 23 = 248 token positions.
  • With a cache: prefill the 8 prompt tokens once, then 1 new position for each of the next 15 tokens = 23 token positions.

In a small decoder that counts its own operations, that is about 11× fewer operations for this short run. The gap grows with length: without a cache the total work grows with the square of the length, and with one it grows in a straight line.

Figure 3 · Diagram

Reading it: in the top row every step starts over, on a sequence one token longer than the step before. In the bottom row prefill stores the prompt's keys and values once, and each later step computes only the newest token's query, key and value, reading everything older from the cache. Both rows write the same tokens (the small decoder's outputs agree to 10 decimal places); only the cost differs.

Figure 4 · Chart

0 5 10 15 20 25 30 tokens generated after an 8-token prompt 0.0 0.2 0.4 0.6 0.8 1.0 1.2 total FLOPs so far (TinyDecoder) 1e7 The KV cache turns quadratic work into linear work no cache: recompute the whole sequence KV cache: compute only the new token

Without a cache, total work curves upward to about 20 times the cached total after 32 tokens; with the cache it grows in a straight line

Reading it: the x-axis counts tokens generated after an 8-token prompt, and the y-axis is the total operations spent so far. Without a cache the line bends upward, because each step costs more than the last. With the cache it stays straight, because each step costs about the same. By 32 tokens the uncached total is about 20 times the cached one.

In code: TinyDecoder.generate writes with or without the cache and counts the work, using TinyDecoder.forward_full for a whole sequence and TinyDecoder.forward_step for one new token. View source

Write the answer one token at a time, with and without the cache, and compare the work on each side.

Chapter 3

Memory math: will it fit?

The cache trades memory for speed, and memory is what limits how many conversations one GPU can serve at once. The GPU's memory holds the weights, which never change size, and one KV cache for every active conversation, which grows with the conversation's length. When the memory is full, the next request waits. Both parts are short multiplications:

  • Weights: 70×10⁹ parameters × 2 bytes (16-bit) = 140 GB: more than one 80 GB GPU. At 4 bits (half a byte) it is 35 GB and fits on one.
  • KV cache per token for a Llama-3-8B-shaped model (32 layers, 8 KV heads, 128 dimensions per head, 16-bit): 2 × 32 × 8 × 128 × 2 = 131,072 bytes, about 128 KB.
  • A 32,000-token conversation: 32,000 × 131,072 ≈ 4.2 GB of cache.
  • An 80 GB GPU holding 16 GB of weights has 64 GB left: room for 15 such conversations at once.
The formula and its symbols

Symbols

Symbol Meaning here Shape / range
number of parameters e.g. 7×10¹⁰
bits / 8 bytes per parameter (16 bits = 2 bytes)
one key and one value per token
number of transformer layers, each with its own cache e.g. 32
number of key/value heads (fewer than query heads with grouped-query attention) e.g. 8
dimensions per head e.g. 128
bytes per stored number 2 at 16-bit

In words: weights cost parameters times bytes each; the cache costs, for every token, one key and one value per layer per KV head.

On the worked example: 7×10¹⁰ × 16/8 = 1.4×10¹¹ bytes = 140 GB; and 2 × 32 × 8 × 128 × 2 = 131,072 bytes per token.

In Python
P = 7e10
# weight GB at 16 bits, then at 4 bits
P * 16 / 8 / 1e9, P * 4 / 8 / 1e9  # → (140.0, 35.0)
L, H_kv, d_h, b = 32, 8, 128, 2
# KV bytes per token: a key and a value, per layer, per KV head
2 * L * H_kv * d_h * b  # → 131072
# GB of cache for a 32,000-token conversation
round(32_000 * 131_072 / 1e9, 1)  # → 4.2

Figure 5 · Chart

0 20 40 60 80 100 120 context length per request (thousands of tokens) 0 10 20 30 40 50 60 70 KV cache for one request (GB) Long contexts eat GPU memory; fewer KV heads help 32 KV heads (multi-head attention) 8 KV heads (grouped-query, Llama-3-8B) free memory: 80 GB GPU − 16 GB weights

At 128k tokens, 32 KV heads need 67 GB, more than the 64 GB free, while 8 KV heads need 17 GB, so three such requests fit

Reading it: each line is the cache one request needs as its context grows to the right. The steep line has 32 KV heads, one for every query head (classic multi-head attention). The shallow line has 8, because several query heads share each key and value head (grouped-query attention, as in Llama 3). The dashed line is the 64 GB left on an 80 GB GPU after 16 GB of weights. At 128k tokens the steep line is above it, so one such request does not fit; the shallow line needs 17 GB, so three fit.

Figure 6 · Interactive · computed from the lesson's code

KV cache memory calculator

Try it: pick a model shape, then drag the context length and the number of requests. The bar is one GPU's memory: grey for the weights, colour for the KV cache. Watch a long context push the cache past the weights, and compare 8 KV heads with 32.

In code: weight_bytes and kv_cache_bytes_per_token are the two formulas, kv_cache_bytes scales the cache to a context and batch, and max_concurrent_requests counts how many conversations fit beside the weights. View source

The same two formulas, with a slider on every factor. Move one and watch how many conversations still fit.

Chapter 4

Sampling: from scores to one token

So far a decode step has been a cost: one read of the weights and one more entry in the cache. What the step produces is a score for every token in the vocabulary, its logit. Which token is written next is decided by settings sent with the request. Greedy decoding always takes the top score. Sampling turns the scores into probabilities and draws one token by a lottery weighted by them.

Three settings shape that lottery. Temperature divides every score before the scores become probabilities: below 1 the favourite pulls further ahead, and above 1 the long shots catch up. Top-k keeps only the k likeliest tokens, and top-p keeps the fewest tokens whose probabilities add up to p.

With scores 2, 1 and 0 for three tokens, temperature moves the probabilities like this:

temperature probabilities
0 (greedy) 1, 0, 0
0.5 0.867, 0.117, 0.016
1 0.665, 0.245, 0.090
2 0.506, 0.307, 0.186

With probabilities 0.5, 0.3, 0.15, 0.05: top-k = 2 keeps 0.5 and 0.3, renormalised to 0.625 and 0.375. Top-p = 0.9 keeps 0.5, 0.3 and 0.15 (the first set whose total reaches 0.9) and cuts the 0.05 tail.

Figure 7 · Diagram

Reading it: the language model produces only the logits on the left; every box after them runs on the settings in the request. Temperature reshapes the whole distribution, then top-k and top-p cut off the unlikely tail, so a rare nonsense token cannot be drawn by bad luck.
The formula and its symbols

Symbols

Symbol Meaning here Shape / range
the model's score (logit) for vocabulary token i any real
temperature > 0; T → 0 approaches greedy
the exponential function; makes every score positive and stretches gaps
sum over every token j in the vocabulary, so the add to 1
probability of drawing token i 0 … 1

In words: divide every score by the temperature, exponentiate, and divide by the total so the results sum to one.

On the worked example: T = 0.5 turns (2, 1, 0) into (4, 2, 0); e⁴ = 54.6, e² = 7.39, e⁰ = 1, total 63.0; probabilities 0.867, 0.117, 0.016.

In Python
import math
z, T = [2.0, 1.0, 0.0], 0.5
# e^(z_i / T)
exps = [math.exp(z_i / T) for z_i in z]
# Σ_j e^(z_j / T)
round(sum(exps), 1)  # → 63.0
# p_i
[round(e / sum(exps), 3) for e in exps]  # → [0.867, 0.117, 0.016]

Figure 8 · Chart

0 1 2 3 4 candidate token 0.0 0.2 0.4 0.6 0.8 probability T = 0.5 0 1 2 3 4 candidate token T = 1.0 0 1 2 3 4 candidate token T = 2.0 Temperature reshapes the distribution; top-p (hatched = cut) trims the tail

Five tokens at three temperatures: at T = 0.5 the favourite takes 79% and top-p 0.9 cuts three tokens; at T = 2 it falls to 38% and only one is cut

Reading it: the same five tokens at three temperatures, rising from left to right. Watch the favourite's bar: 79% at T = 0.5, 38% at T = 2, where even the least likely token reaches 7%. Then count the hatched bars, the tokens top-p = 0.9 cuts: three at T = 0.5, two at T = 1, one at T = 2. When the distribution is confident, a few tokens reach 90% and top-p cuts the rest; when it is unsure, top-p keeps more. A fixed top-k keeps the same number either way.

Use a low temperature where there is one right answer, as in extraction, classification and tool calls, and a higher one for brainstorming and creative text.

Temperature 0 is not a determinism guarantee. Floating-point addition isn't associative, which means the order of the additions changes the sum: in 32-bit floats, (10⁸ + 1) − 10⁸ = 0 but (10⁸ − 10⁸) + 1 = 1. On a GPU the order of additions can depend on the kernel chosen and on what else is in the batch, so two nearly tied tokens can swap places between otherwise identical requests.

In code: sample_next chains temperature_probs, top_k_filter and top_p_filter into one draw; greedy_pick_with_summation_order shows a near tie flipping with the order of additions. View source

Turn each setting and watch the probabilities move, then draw tokens and watch the tally.

Chapter 5

Speculative decoding

Each pass of the language model ends in one sampled token, and every pass reads all the weights. Speculative decoding gets several tokens out of one pass. Picture a junior writer who drafts the next few sentences quickly, and a senior editor who reads the whole draft at once, keeps every sentence they would have written themselves, rewrites the first one they wouldn't, and throws away the rest. The senior reads fast and writes slowly, so the pair moves at the junior's speed and produces the senior's text.

Here the junior is a small language model and the senior is the big one. The check is cheap because decode is memory-bound: scoring 5 draft tokens in one pass of the big model costs about the same as generating 1.

Suppose the big model's next-token probabilities are (0.5, 0.3, 0.2) and the small model's are (0.3, 0.3, 0.4). A draft survives with probability equal to the overlap of the two, the sum of the smaller probability for each token: 0.3 + 0.3 + 0.2 = 0.8. Drafting 4 tokens per round then yields on average (1 − 0.8⁵) / (1 − 0.8) = 3.36 tokens per pass of the big model instead of 1.

Figure 9 · Diagram

Reading it: the loop in the middle walks the drafts in order. A draft the big model likes at least as much as the small one did (p ≥ q) is always kept; one it likes less is kept with probability p/q. The first rejected draft is replaced by a token drawn from the probability the small model under-proposed, max(0, p − q), and the drafts after it are dropped. That replacement makes the output follow the same distribution as sampling from the big model alone, which a test confirms over 20,000 sampled rounds.
The formula and its symbols

Symbols

Symbol Meaning here Shape / range
the big (target) model's probability for token x 0 … 1
the small (draft) model's probability for token x 0 … 1
the smaller of a and b
alpha, the acceptance rate: how often a draft survives 0 … 1
gamma, how many tokens the small model drafts per round e.g. 4
expected value: the long-run average

In words: keep a draft with probability "how much the big model likes it compared with the small one, capped at 1"; the average number of tokens per big-model pass is a geometric series in the acceptance rate.

On the worked example: α = 0.8, γ = 4: (1 − 0.8⁵)/(1 − 0.8) = (1 − 0.328)/0.2 = 3.36.

In Python
# big model
p = [0.5, 0.3, 0.2]
# small model
q = [0.3, 0.3, 0.4]
# P(keep x) for each token
[round(min(1.0, p_x / q_x), 2) for p_x, q_x in zip(p, q)]  # → [1.0, 1.0, 0.5]
alpha = sum(min(p_x, q_x) for p_x, q_x in zip(p, q))
round(alpha, 2)  # → 0.8
gamma = 4
# expected tokens per big-model pass
round((1 - alpha ** (gamma + 1)) / (1 - alpha), 2)  # → 3.36

In code: acceptance_rate computes α and expected_tokens_per_round the geometric series; speculative_round runs the draft, verify and replace loop once, and speculative_generate repeats it until enough tokens exist. View source

Move the small model's guesses towards the big model's or away from them and watch how many drafts survive, then draft and check one round at a time.

Chapter 6

Quantization: fewer bits per weight

Speculative decoding gets more tokens from each read of the weights. Quantization makes the read smaller. A weight stored in 16 bits can be stored in 8 or 4 instead. Lay a ruler with evenly spaced marks over a row of weights, store each weight as the number of its nearest mark, and multiply back when the weight is used. Fewer bits mean fewer marks, so each weight lands further from where it was. Each row of a weight matrix gets its own ruler, so one huge weight coarsens only its own row.

Take the row of weights (0.5, −1.27, 0.02).

  • int8: the largest magnitude, 1.27, maps to 127, so the step size is 0.01. Codes: 50, −127, 2. Decoding gives back exactly (0.5, −1.27, 0.02).
  • int4: only 15 levels (−7 … 7), step size 1.27/7 = 0.181. Codes: 3, −7, 0. Decoding gives (0.544, −1.27, 0): the small weight vanished.
The formula and its symbols

Symbols

Symbol Meaning here Shape / range
the j-th original weight in the row real
the largest absolute value in the row ≥ 0
the largest code: 127 for 8 bits, 7 for 4 bits
the scale (step size), one per row > 0
the stored integer code −127…127 or −7…7
the weight as reconstructed at inference time ("w-hat") real

In words: pick a step size so the largest weight lands on the largest code, store each weight as the nearest whole number of steps, and multiply back at run time.

On the worked example: int4: s = 1.27/7 = 0.181; 0.5/0.181 = 2.76 → 3; 3 × 0.181 = 0.544.

In Python
w = [0.5, -1.27, 0.02]
def quantize(w, bits):
    # the step size
    s = max(abs(w_j) for w_j in w) / (2 ** (bits - 1) - 1)
    # c_j: whole steps
    return s, [round(w_j / s) for w_j in w]
s, c = quantize(w, bits=8)
round(s, 3), c  # → (0.01, [50, -127, 2])
s, c = quantize(w, bits=4)
round(s, 3), c  # → (0.181, [3, -7, 0])
# ŵ_j = s · c_j: the 0.02 is gone
[round(s * c_j, 3) for c_j in c]  # → [0.544, -1.27, 0.0]

Rounding to 8 bits is nearly lossless. At 4 bits plain rounding erases small weights, as the 0.02 shows, so 4-bit methods such as GPTQ and AWQ round more carefully and keep most of the quality at a quarter of the memory. Fewer bytes per weight also make memory-bound decode faster.

In code: quantize and dequantize make the round trip, and quantization_error measures how far it lands from the original weights. View source

Drag the weights and change the bits, and watch where each weight snaps and how far it lands from where it started.

Chapter 7

Continuous batching

Quantization shrinks each read of the weights; batching shares it. On the roofline, one read served a batch of 64 users and the GPU's arithmetic use rose from 0.3% to 21%. How the batch is kept full decides how much of that is real work.

A server writes many answers at once, each in its own place in the batch, called a slot, for as many decode steps as the answer has tokens, and answers differ in length. Static batching fills every slot and waits for the longest answer to finish before it seats anyone new, so slots sit empty. Continuous batching seats the next request the moment any slot frees.

Take four requests needing 4, 1, 1 and 1 decode steps, on two slots. Static: {4, 1} runs 4 steps with one slot idle for 3, then {1, 1} runs 1: 5 steps, 70% of slot-steps busy. Continuous: the short requests slide into the freed slot while the long one runs: 4 steps, 87.5% busy.

Figure 10 · Chart

0 2 4 6 slot static batching: 433 steps, 60% of slot-steps busy 0 50 100 150 200 250 300 decode step 0 2 4 6 slot continuous batching: 318 steps, 82% of slot-steps busy

With 32 requests on 8 slots, static batching leaves idle gaps and needs 433 steps at 60% busy; continuous batching needs 318 steps at 82%

Reading it: each row is a slot and time runs to the right in decode steps; each colour is a request and an empty stretch is an idle slot. This run has 32 requests of varied length on 8 slots. In the static timeline (top), find the empty gaps, left wherever a short request finished before the longest one in its batch. The continuous timeline (bottom) has almost none, and finishes the same work in 318 steps instead of 433, at 82% utilisation against 60%.
The formula and its symbols

Symbols

Symbol Meaning here Shape / range
utilisation: the share of slot-steps doing real work 0 … 1
useful slot-steps total decode steps all requests need integer
steps × slots the capacity the GPU offered while serving them integer

In words: utilisation is the work the requests needed divided by the work capacity the server spent serving them.

On the worked example: 7 useful slot-steps; static 7/(5×2) = 0.70, continuous 7/(4×2) = 0.875.

In Python
# decode steps the four requests need
useful = 4 + 1 + 1 + 1
slots = 2
# static takes 5 steps, continuous 4
useful / (5 * slots), useful / (4 * slots)  # → (0.7, 0.875)

Continuous batching, together with KV-cache memory handed out in fixed-size pages (as in vLLM), is a large part of how modern inference servers reach high throughput.

In code: simulate_static_batching and simulate_continuous_batching play out the two policies step by step and measure U. View source

Set how many steps each request needs and compare the two timelines.

Chapter 8

Prompt caching: reuse the prefill of a shared prefix

Batching shares work between requests; prompt caching skips work that requests repeat. The KV cache normally lives for one request. Prompt caching keeps it across requests: if many calls start with the same long system prompt, tool definitions or reference document, the provider stores that prefix's keys and values and skips its prefill next time. It is only valid up to the first differing token, because every token's keys depend on everything before it, so put stable content first and volatile content last.

Take 100 requests, each a 10,000-token shared prefix plus a 500-token question, at $3 per million input tokens, with cache writes at 1.25× and cache reads at 0.1× (typical of providers; check current pricing):

  • Without caching: 100 × 10,500 × $3/10⁶ = $3.15.
  • With caching: the first call writes the cache ($0.039); each of the other 99 costs $0.0045. Total $0.48, an 85% saving, and each cached call also skips 10,000 tokens of prefill, so its first token arrives sooner.

Figure 11 · Diagram

Reading it: the prompt is read left to right, and the cache covers only an unbroken run from the start. The stable parts go first, so every request shares the longest possible prefix, and the question that changes on every call goes last. A timestamp or request ID at the top would differ on the first token, and nothing would be reused.

In code: reusable_prefix_tokens counts how many leading tokens two prompts share, and prompt_cache_cost prices a run of requests with and without the cache. View source

Move the parts of a prompt, add a timestamp at the top, and watch how much the cache can reuse and what 100 requests cost.

Test yourself

9 questions

Answer each one out loud or on paper before you open it.

Question 1Q: Why is decoding slow even on a huge GPU?Think it through, then reveal

A: Each token needs every weight read from memory but does only about one operation per byte read, far below the GPU's break-even (~300 FLOPs/byte). The arithmetic units mostly wait on memory.

Question 2Q: What is the KV cache, and why does it matter for serving cost?Think it through, then reveal

A: Stored keys and values of all earlier tokens, so each new token is computed once instead of recomputing the whole sequence. It grows with context length and batch size, and that memory caps how many requests a GPU serves at once.

Question 3Q: How much memory does a 70B model need at 16-bit and at 4-bit?Think it through, then reveal

A: 140 GB and 35 GB for weights alone, plus KV cache and activations.

Question 4Q: Estimate the KV cache for one 32k-token request on a Llama-3-8B-shaped model.Think it through, then reveal

A: 2 × 32 × 8 × 128 × 2 = 131,072 bytes per token; × 32,000 ≈ 4.2 GB.

Question 5Q: Why does grouped-query attention make serving cheaper?Think it through, then reveal

A: It shares each key/value head among several query heads, shrinking the KV cache (4× for 32 → 8 KV heads), so more requests fit per GPU.

Question 6Q: Why isn't temperature 0 perfectly deterministic?Think it through, then reveal

A: Floating-point addition isn't associative, and GPU reduction order can change with kernels and batch composition, so nearly tied logits can flip.

Question 7Q: How can speculative decoding be faster yet produce the same distribution?Think it through, then reveal

A: Verifying several draft tokens costs one memory-bound pass of the big model, about the same as generating one. The min(1, p/q) accept rule plus resampling from max(0, p − q) on rejection makes the output exactly the big model's distribution.

Question 8Q: What does continuous batching fix?Think it through, then reveal

A: Idle slots: static batches wait for their longest request, while continuous batching refills any freed slot immediately, raising utilisation.

Question 9Q: How do you structure a prompt to benefit from prompt caching?Think it through, then reveal

A: Put stable content (system prompt, tool definitions, reference documents) first and anything that varies (the question, timestamps, IDs) last, because a cache is valid only up to the first differing token.

Primary sources

The papers behind this lesson

Leviathan, Kalman & Matias, Fast Inference from Transformers via Speculative Decoding (2022): Introduced the draft-then-verify scheme with an accept/reject rule that provably preserves the target model's output distribution.

Read on rumblr →The paper

Kwon et al., Efficient Memory Management for Large Language Model Serving with PagedAttention (2023): Stored the KV cache in fixed-size pages like an operating system's virtual memory, eliminating fragmentation and enabling vLLM's high-throughput continuous batching.

Read on rumblr →The paper

Dao et al., FlashAttention (2022): Computed exact attention in GPU-memory-sized tiles, cutting the slow memory traffic that dominates long-context inference.

Read on rumblr →The paper

Dettmers et al., LLM.int8(): 8-bit Matrix Multiplication for Transformers at Scale (2022): Showed that a few outlier features break naive 8-bit quantization and handled them separately.

The paper

Frantar et al., GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers (2022): Made 3-4-bit weight quantization practical with error-compensating rounding.

The paper

Holtzman et al., The Curious Case of Neural Text Degeneration (2019): Introduced nucleus (top-p) sampling.

The paper

Researcher's shelf

Further reading

  • vLLM documentation: https://docs.vllm.ai/
  • Hugging Face, Text generation strategies: https://huggingface.co/docs/transformers/generation_strategies
  • Anthropic, Prompt caching: https://docs.claude.com/en/docs/build-with-claude/prompt-caching
  • Thinking Machines Lab, Defeating Nondeterminism in LLM Inference: https://thinkingmachines.ai/blog/defeating-nondeterminism-in-llm-inference/
  • Grattafiori et al., The Llama 3 Herd of Models (2024): https://arxiv.org/abs/2407.21783

About this lesson. This is the illustrated edition of a lesson from the open-source AI Primer ↗. Its text, figures and numbers are generated from the Primer's source at commit f8b43d1, so the two always agree: the explanation, the code that builds it and the tests that prove it.