Inference: how a model answers
What happens, and what does it cost, between typing and the answer appearing?
Lesson complete
If you like:
You type a question and press Enter. A moment later the first word appears, then the rest, one after another. What is the model doing all that time? And what does it cost?
No voice: the lesson advances on its own with subtitles.
The voice for this lesson is being recorded: for now it advances on its own with subtitles.
Review modeComment on this stepI finished the lesson
What you will achieve
- Explain the two phases of an answer: prefill, which reads your message all at once, and decode, which writes one token per turn.
- Describe what the KV cache keeps, what work it saves, and why it takes more memory the longer the conversation is.
- Estimate the cost of a task from its input and output tokens, and recognize what makes it costlier or slower: long context, long output, small batch.
Key ideas
- An answer has two phases. Prefill processes your whole message at once and sets the wait until the first token; decode writes one token per turn and sets how long the rest takes.
- The KV cache keeps the keys and values of earlier tokens, which never change, so they are not recomputed: in the example, 15 cells instead of 105. In exchange it takes memory that grows with every token and every conversation.
- On every turn the GPU reads all the weights (and the caches) from its memory and does very little arithmetic: bandwidth sets the pace. Tokens per second ≤ bandwidth ÷ bytes read per turn.
- Serving several people in a batch shares that read: throughput rises and the cost per token falls, but each person gets fewer tokens per second (more latency).
- Cost of a task = input × its price + output × its price, and output costs several times more. Mixture of experts saves arithmetic per token, not memory.
What many people believe
Common belief Answering is “computing”: with a GPU that does twice as many operations per second, the model would write twice as fast.
What is true When writing, the GPU waits for data, not for arithmetic: with one person it uses under one percent of its compute. Memory bandwidth rules, together with the bytes to read per turn (weights and caches), the context length, and the batch size.
Check yourself
Four questions. No grade, no account: they just show whether the idea stuck.
Under the hoodFor those who want the math and the code. You do not need it to follow the course.
Two phases, two bottlenecks
A dense model with parameters does about operations for every token it processes (one multiplication and one addition per parameter; Kaplan et al., 2020; Pope et al., 2022), plus an attention term that grows with context.
Prefill (the message’s tokens at once; blocks, = heads × head dimension):
These are large matrix multiplications: the GPU works close to its peak. The lesson assumes 40% of peak (Llama 3 reports 38 to 43% in training; Pope et al. reach 76% in prefill with large batches). With the 8B model and 2,000 tokens: FLOPs ÷ ≈ 84 ms.
Decode ( conversations of context tokens each). Every turn has a memory time and a compute time (Pope et al., §2), and the larger one rules:
with the bytes of weights, the cache bytes per token, BW the bandwidth, and the useful compute (the lesson uses half the peak). With there are operations for every bytes, that is operations per byte: one, in FP16. The H100 can do per byte, so one person’s decode uses about 0.3% of the compute. Pope et al. put it this way: at small batch sizes and sequence lengths, loading the weights dominates; at large batches and long sequences, loading the KV cache does.
The KV cache, inside
The 2 is key and value; the number of key-value heads; the head dimension and the bytes per number. Llama 3 8B (Llama Team, 2024, table 3): bytes per token (in the scene, numbers per key per block). With full multi-head attention (32 KV heads) it would be : Llama 3 uses grouped-query attention (GQA, Ainslie et al., 2023), which shares each pair among four query heads, “to reduce the size of key-value caches during decoding.” The same count gives Kwon et al.’s (2023) value for OPT-13B: bytes, about 800 KB per token.
Without a cache, generating tokens after input tokens processes positions; with a cache, . With and : versus . The toy transformer in the scene (2 blocks, 2 heads, , random weights with a fixed seed; tiny.ts) runs both paths: it counts 105 and 15 passes, 498,240 and 72,960 multiply-adds, and its logits match with a maximum difference of 0.
Speed ceiling, batches, and cost
With the 8B in FP16 on an H100, 8,000 tokens of context, and 2 USD per GPU hour (assumption): gives 196 tokens/s and 2.84 USD per million; , the most that fit, gives 42 tokens/s per person, 2,545 in total, and 0.22 USD per million: about thirteen times cheaper on the same machine. With 128,000 tokens of context only 3 conversations fit.
What an API user pays
On the lists consulted on October 12, 2026, output costs five times the input price on every Anthropic model, and five to more than eight times on Google’s. The scene’s prices ($3 and $15 per million) are an example with that ratio. If the start of your message repeats (instructions, a base document), prompt caching charges much less for it: on Anthropic’s list, reading from the cache costs 0.1 times the input price (0.05 or 0.025 on some models), and writing to it, valid for five minutes, 1.25 times.
The waits in the scene are estimates with the 8B model on one H100 and a single person: prefill at 40% of peak, and every writing turn with the memory time above.
Mixture of experts
Each block replaces its network with experts and a router that picks per token:
Mixtral 8x7B (Jiang et al., 2024, table 1): , , , , . That gives 46.7 billion in total and 12.9 active. The paper puts it this way: compute is proportional to the active parameters, but “the memory costs for serving Mixtral are proportional to its sparse parameter count, 47B.” If each token picked its two experts at random (assumption: real routing is uneven), a batch of tokens would touch a fraction of the experts in each block: 25% at , 90% at , 99% at .
In code
Cache, speed ceiling, and cost with the Llama 3 8B architecture:
layers, kv_heads, head_dim, bytes_num = 32, 8, 128, 2
kv_per_token = 2 * layers * kv_heads * head_dim * bytes_num # 2 = key and value
print(kv_per_token) # bytes per token
weights = 8.03e9 * 2 # FP16: 2 bytes per parameter
print(round(kv_per_token * 128_000 / 1e9, 2)) # GB of one 128,000-token conversation
bandwidth = 3.35e12 # H100 SXM: 3.35 TB/s
print(round(bandwidth / weights, 1)) # tokens/s ceiling for one person
def serve(people, context, usd_per_hour=2.0):
bytes_per_turn = weights + people * context * kv_per_token # weights + one cache per person
t = bytes_per_turn / bandwidth # seconds per turn
throughput = people / t # tokens/s of the whole system
return round(1 / t, 1), round(throughput), round(usd_per_hour / (3600 * throughput) * 1e6, 3)
print(serve(1, 8000)) # (tokens/s per person, total tokens/s, US$ per million)
print(serve(60, 8000))
# 131072
# 16.78
# 208.6
# (195.8, 196, 2.837)
# (42.4, 2545, 0.218)
The cache does not change the result: single-head attention with and without a cache.
import numpy as np
rng = np.random.default_rng(0)
d = 8
Wq, Wk, Wv = (rng.normal(size=(d, d)) for _ in range(3))
x = rng.normal(size=(6, d)) # 6 tokens (already turned into vectors)
def attention_no_cache(x): # recomputes K and V for every token
q, k, v = x @ Wq, x @ Wk, x @ Wv
s = q @ k.T / np.sqrt(d)
s = np.where(np.tril(np.ones_like(s)) == 1, s, -np.inf) # causal mask
w = np.exp(s - s.max(1, keepdims=True)); w /= w.sum(1, keepdims=True)
return w @ v
K, V, out = [], [], [] # with a cache: one token per turn
for t in range(len(x)):
q = x[t] @ Wq
K.append(x[t] @ Wk); V.append(x[t] @ Wv) # only the new pair enters the cache
s = np.array(K) @ q / np.sqrt(d)
w = np.exp(s - s.max()); w /= w.sum()
out.append(w @ np.array(V))
print(np.allclose(attention_no_cache(x), np.array(out)))
# True
What comes next
Real systems add more pieces: PagedAttention splits the cache into blocks so memory is not wasted (vLLM: 2 to 4 times the throughput at the same latency as earlier systems, Kwon et al., 2023); continuous batching adds and removes conversations from the batch at every turn (Orca, Yu et al., 2022); and speculative decoding gave 2 to 3 times the speed on T5-XXL “with identical outputs” (Leviathan et al., 2023) and 2 to 2.5 times on Chinchilla 70B (Chen et al., 2023). All of this serves a base model; turning it into an assistant starts with fine-tuning, in lesson 27.
Decision lens
What this idea means if your job is to decide, not to code.
- Cost per task = input tokens × input price + output tokens × output price. Ask for the breakdown by task type: summarizing (long input, short output) is nothing like drafting (the reverse). Estimate your real token volume before budgeting.
- The wait depends on context length: the first token takes longer the more text you send, and every later token comes out slower with long contexts. Ask for time to first token and tokens per second measured with texts as long as yours, not the ones on the spec sheet.
- Ask about prompt caching. If the start of your messages repeats (instructions, a base document), reusing it cuts cost and wait: on Anthropic’s list, reading from that cache costs a tenth of the input price or less (writing it the first time costs a bit more: 1.25 times).
- When comparing models or providers, look beyond “parameters”: active parameters (mixture of experts), context length, input and output price. If you host the model yourself, the cost per token depends on how full you keep the GPU: under the lesson’s assumptions, serving one person alone costs about thirteen times more per token than a full batch.
Terms in this lesson
- Inference Using an already trained model to answer a new case, with frozen parameters.
- Parameter Each of the numbers a model adjusts while training and in which it stores what it learned.
- Weight (w) In a linear model, the number that multiplies the input: the slope of the line. It tells how much the prediction rises for each unit the input grows.
- Language model A model that, given some text (the context), gives a probability to every word or piece that can come next. It writes by adding one piece at a time.
- Token A piece of text (a word, a word fragment, a symbol, or a basic code) taken from the vocabulary. It is the unit the model reads and generates, and the unit you are billed for.
- Autoregression Writing one piece at a time using what has already been written as input: each word produced becomes part of the context for the next.
- Attention A mechanism by which each token decides how much to look at the others: it compares its query with everyone’s keys, turns the scores into weights with softmax, and builds its new vector as the blend of the values with those weights.
- Query, key, and value (Q, K, V) The three vectors each token produces: the query says what it is looking for, the key how it gets found, and the value what it hands over. They come from multiplying its vector by three learned weight matrices.
- Causal mask In attention, it replaces the scores toward future tokens with minus infinity before softmax, which then gives them zero weight. Each token then looks only at earlier tokens and itself, and the model cannot copy the answer during training.
- Transformer A neural-network architecture made of a stack of blocks with the same shape. Each block combines attention (between tokens) and a network applied to each token, with residual connections and normalization. It was introduced in “Attention Is All You Need” (2017).
- GPU Graphics processing unit: a chip with hundreds or thousands of simple cores, built to draw graphics and very efficient at multiplying matrices in parallel, the central operation of training.
- Batch A small set of examples, picked at random, used to estimate the gradient in one training step.
- FLOP, FLOPs Floating-point operation: an addition or a multiplication with decimals. A training run’s compute is counted in total FLOPs (≈ 6·N·D); a chip’s speed, in FLOPs per second.
- Memory bandwidth How many bytes per second can travel from memory to the cores: 3,350 GB/s on an H100. When generating text token by token it is usually the speed limit, because every token requires reading all the parameters.
- VRAM (GPU memory) A GPU’s own memory, on the same board as its cores. The parameters and data it computes with must be there. It is measured in gigabytes: 80 on an H100, 12 on an RTX 3060. On data-center GPUs it is a very fast type called HBM.
- FP16 (and FP32, INT8, INT4) Formats for storing each number in a model. FP16 uses 2 bytes and keeps about 3 significant digits; FP32, 4 bytes and about 7. INT8 (1 byte) and INT4 (½ byte) store an integer that, multiplied by a scale, approximates the value. BF16 is a 2-byte variant with FP32’s range.
- Quantization Storing a trained model’s parameters with fewer bits (8 or 4 instead of 16), rounding each one to the nearest mark of a scale shared by its group. It reduces memory and read time, with a loss of quality that has to be measured.
- Base model A language model that has only gone through pretraining: it can continue texts, but it is not tuned to follow instructions or converse like an assistant.
- Inference serving Running an already trained model to answer real requests: with fixed weights, for many people at once, while managing wait time and cost.
- KV cache (keys and values) Memory that keeps the keys and values already computed for earlier tokens so they are not recomputed on every turn. It saves arithmetic, but takes memory that grows with the context and with every conversation.
- Prefill First phase of inference: the whole input message is processed at once and the KV cache is filled. The wait until the first token depends on it.
- Decode Second phase: tokens are generated one at a time, and each one requires a full turn through the model that reads all the weights and the cache. It is usually limited by memory bandwidth.
- Throughput Tokens per second delivered by the whole system, summed over everyone served. It rises with batch size, at the expense of the speed each person gets (latency).
- Mixture of experts (MoE) An architecture in which each block has several networks (experts) and a router picks a few for every token. There are many parameters in total and few active per token: it saves arithmetic, not memory.
Full transcript
Sources
- Pope, R., Douglas, S., Chowdhery, A., Devlin, J., Bradbury, J., Levskaya, A., Heek, J., Xiao, K., Agrawal, S., Dean, J. (2022). Efficiently Scaling Transformer Inference
- Llama Team, AI @ Meta (2024). The Llama 3 Herd of Models (tabla 3: arquitectura de 8B; GQA con 8 cabezas de clave-valor; contexto de hasta 128K)
- NVIDIA (2023). NVIDIA H100 Tensor Core GPU (ficha: 80 GB, 3.35 TB/s; FLOPS «con dispersión»)
- Kwon, W., Li, Z., Zhuang, S., Sheng, Y., Zheng, L., Yu, C. H., Gonzalez, J. E., Zhang, H., Stoica, I. (2023). Efficient Memory Management for Large Language Model Serving with PagedAttention
- Jiang, A. Q., Sablayrolles, A., Roux, A., Mensch, A., Savary, B., et al. (2024). Mixtral of Experts
- Leviathan, Y., Kalman, M., Matias, Y. (2023). Fast Inference from Transformers via Speculative Decoding
- Chen, C., Borgeaud, S., Irving, G., Lespiau, J.-B., Sifre, L., Jumper, J. (2023). Accelerating Large Language Model Decoding with Speculative Sampling
- Kaplan, J., McCandlish, S., Henighan, T., Brown, T. B., Chess, B., Child, R., Gray, S., Radford, A., Wu, J., Amodei, D. (2020). Scaling Laws for Neural Language Models (2N operaciones por token en la pasada hacia delante)
- Chowdhery, A., et al. (2022). PaLM: Scaling Language Modeling with Pathways (apéndice B: FLOPs de la atención por token)
- Ainslie, J., Lee-Thorp, J., de Jong, M., Zemlyanskiy, Y., Lebrón, F., Sanghai, S. (2023). GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints
- Yu, G.-I., Jeong, J. S., Kim, G.-W., Kim, S., Chun, B.-G. (2022). Orca: A Distributed Serving System for Transformer-Based Generative Models
- Anthropic (2026). Pricing (lista de precios de la API, consultada el 12 de octubre de 2026)
- Google (2026). Gemini Developer API pricing (consultada el 12 de octubre de 2026)
CommentsThis lesson’s public conversation: questions, facts to check, ideas.
Comments live in GitHub Discussions, in the course’s public repository; writing one requires a GitHub account. They load from giscus.app when you open this section. The course reviewers read them, and if a change is accepted, it is applied in both languages. Open the thread on GitHub