Braj Kishore
JourneyVaultML FoundationsAI PM GuideAgenticNewsWork With MeMentorshipPulseNow
Say hi

Hiring · Building · Investing

Have a system — or a team —that needs to scale?

info@avyxon.ai

Usually replies within a day · track record here

JourneyVaultML FoundationsAI PM GuideAgenticNewsWork With MeMentorshipPulseNow
LinkedInXYouTubeSubstackInstagramThreadsFacebookDiscordGitHubTopmate
© 2026 Braj Kishore · Bengaluru, INThink Big · Start Small · Scale Fast
Agentic engineering
Lesson 19Working

How inference actually works

Two open models are both called 7B. Their weights differ by less than a gigabyte. Put them on the same card at the same context length and one serves 124 people while the other serves 55. The number that explains the gap is not in either name.

Most engineers treat inference as a black box with a price list. That works until it does not. Then latency moves, the bill moves, and nobody can say why.

This lesson opens the box. Not to make you an infrastructure engineer — to make you an engineering leader who can tell a good serving plan from an expensive one. The whole argument rests on a single asymmetry, and the diagram below is the fastest way to see it.

Interactive · one request, top to bottom

One wide pass, then five hundred narrow ones

Time runs downward. The shape is the argument: prefill reads your whole prompt in a single pass, and then every output token costs one more trip through the entire cache. Select any step for what is actually happening.

repeat once per output tokenClientyour appSchedulervLLM engineGPU computethe matmulsKV cachein VRAMpromptadmit to batchprefillwrite KVread all KVone tokenappend KVfree blocks
admitprefill · compute-bounddecode · bandwidth-boundrelease
decode · bandwidth-bound

Decode step — read the entire cache back

To produce one token, the GPU reads the keys and values for every token so far. The arithmetic is tiny and the memory traffic is enormous, which is why decode is limited by memory bandwidth rather than by compute. The expensive card spends most of this step waiting.

DistServe and the phase splitOSDI 2024 · arXiv 2401.09670vLLM engine argumentsdocs.vllm.ai

Two halves, two different bottlenecks

Serving a request has two phases, and they are not alike. Prefill reads your whole prompt in one pass. Every token is processed in parallel, so it is a large dense matrix multiplication. That saturates the GPU’s compute units.

Decode is the opposite. It produces one token at a time. Each step reads back the keys and values of every token so far. The arithmetic is tiny and the memory traffic is enormous. The DistServe authors put it plainly: decode “incurs a similar level of I/O to the prefill phase, making it constrained by the GPU’s memory bandwidth.”

That is not a distinction between fast and slow. It is a distinction between two different scarce resources. A change that helps one phase often does nothing for the other.

The cleanest measurement of the gap comes from Google. On PaLM 540B across 64 chips, model FLOPS utilisation is 43% during prefill and 14% during decode when tuned for latency. Tuned for throughput it is 76% and 33%. Same hardware, same model, a two-to-four-fold gap in how much of the machine is doing work.

A second measurement makes it visceral. Microsoft capped GPU power from 700W to 350W. The decode phase barely noticed. You cannot halve the power available to a compute-bound job for free; you can to a job that is waiting on memory.

Prefill is compute-bound. Decode is bandwidth-bound. Almost every surprising thing about LLM serving — the pricing, the batching, the routing, the hardware choice — falls out of those two sentences.

Note the historical accident here. Shazeer derived the asymmetry from first principles in 2019, before anyone was serving these models at scale. His measurement is the whole story in one pair of numbers: multi-query attention took decode from 46µs to 3.8µs per token, and moved the encoder from 1.7µs to 1.5µs. A twelvefold win on one half and nothing on the other.

The cache is the capacity

The thing decode reads back has a name. It is the KV cache — the keys and values for every token seen so far, kept in GPU memory so they never have to be recomputed.

It is not a small optimisation. It is your capacity limit. Weights are fixed and load once. Everything left over is cache, and the cache grows with every user and every token they hold.

The size per token comes from four numbers in the model’s configuration file: layers, key-value heads, head dimension, and bytes per value. Multiply them, double it for keys and values, and you have it. That is the whole formula.

One of those four is doing most of the work. Grouped-query attention lets several attention heads share one set of cached keys and values. The paper states the effect directly: moving to a single shared head reduces the cache “by a factor of H.” Its measured cost is nearly nothing — quality of 47.1 against 47.2, at a fifth of the inference time.

So two models with the same parameter count can differ enormously in what they cost to serve. The figure below works that out from published configs rather than asserting it.

Interactive · from each model’s own config

How many people fit on one card

Weights are measured exactly from each model’s safetensors index. The rest is arithmetic on the numbers in its config.json — layers, attention heads, key-value heads. Two of these models are both called 7B.

context per user
concurrent users at 8k context, one 80 GB card
1241,017,870 tokens of cache in total
weights, then whatever is left for cache15.2 GB / 73.6 GB
weightskv cache budget

28 layers · 28 attention heads sharing 4 key-value heads · head dim 128 · 56 KB of cache per token

what grouped-query attention is worth

Qwen2.5 7B gives 28 attention heads only 4 sets of keys and values, so the cache is 7 times smaller than attention alone would need. Run the same sum without it and this card holds 17 users instead of 124. One line in a config file, most of your serving capacity.

Honest limits. Weight bytes are measured; everything downstream is arithmetic, not a benchmark — no GPU was involved. The card is 80 GB with 92% treated as usable, which is vLLM’s default; the rest goes to activations, the CUDA context and fragmentation. And this assumes every user holds a full context, so read it as a ceiling rather than a forecast. Configs fetched 2 September 2026.

Qwen2.5 7B InstructHugging FaceMistral 7B Instruct v0.3Hugging Face

Qwen2.5 7B gives 28 attention heads only four sets of keys and values. Mistral 7B has slightly smaller weights, more layers and twice the key-value heads. The result is 56 KB per token against 128 KB. Both are called 7B. Only one of those numbers appears in the name.

Run the counterfactual in the figure and you see what the technique is worth. Take grouped-query attention away from the Qwen model and the same card holds seventeen users instead of 124. One line in a configuration file, most of your serving capacity.

Why the memory is wasted, and what fixed it

Knowing the cache size is only half the problem. The other half is that early serving systems managed that memory badly.

They reserved a contiguous block per request, sized for the longest output the request might produce. Most requests are far shorter. The reserved space sits idle, and what is left fragments.

The vLLM authors measured it. In existing systems, only 20.4% to 38.2% of KV cache memory held actual token state. Their system reached 96.3%. Most of a very expensive resource was being wasted on nothing.

The fix is borrowed wholesale from operating systems. Store the cache in fixed-size blocks rather than one contiguous reservation. Then a finished request frees blocks that anything can reuse, and there is no hole left behind that nothing fits into. Hence the name: PagedAttention.

The scheduling half of the answer arrived two years earlier, and from somewhere less expected.

🇰🇷 Seoul National University and FriendliAI

Orca, and the technique everyone renamed

36.9×
throughput over FasterTransformer at matched latency
175B
parameters, on eight A100s over NVLink
2022
a year before the serving stack caught up

Orca asked a simple question. Why does a batch have to finish together? Their answer was to schedule at the level of a single step rather than a whole request. A finished request leaves the batch immediately, and a waiting one joins it mid-flight. Nobody waits for the slowest member.

The result was 36.9× the throughput of NVIDIA’s FasterTransformer at the same latency, on a 175B model. It is now in every serving stack in the world. It is also worth knowing what the paper actually calls it: “iteration-level scheduling”. The phrase “continuous batching” appears nowhere in it — that name was applied later by other people. If you say Orca invented continuous batching you will be understood, and you will be slightly wrong.

Be careful which multiplier you repeat. Orca’s 36.9× is against FasterTransformer. vLLM’s headline is a more modest 2–4×, and it is measured against Orca — because Orca had already solved the scheduling half, and vLLM was solving the memory half. The widely quoted “23× from continuous batching” is a vendor benchmark against naive static batching. None of these three numbers compose.

What this does to your bill

Two consequences follow, and one of them is worth being careful about.

The careful one first. Every current Claude model prices output at exactly five times base input. The mechanism above is the obvious explanation — a thousand input tokens are one wide pass, a thousand output tokens are a thousand narrow ones. But I could find no provider that documents this link. Treat it as a sound inference, not a sourced fact. The ratio being identical across very different architectures suggests a commercial simplification rather than a cost pass-through.

The second consequence is firmer, and it changes how you should ask the self-hosting question. Idle GPUs still cost money. So the cost per token of a self-hosted model is set mostly by how busy you keep it.

One measurement study puts the same H100 running the same model at $15.25 per million output tokens at one request per second, and $0.87 at twenty-five. Same GPU, same model, a seventeenfold difference. Below roughly two requests per second, the study finds a hosted API is simply cheaper.

That is a single-author preprint on a synthetic workload, and I would not stake a budget on the exact dollars. There appears to be no peer-reviewed study of this question at all, which is itself worth knowing. But the shape survives the caveats, and the shape is the lesson: “should we self-host?” is a question about your traffic, not about hardware prices.

Qwen2.5 72B InstructHugging FaceClaude model pricingplatform.claude.comBeyond Per-Token PricingarXiv 2606.11690 · preprint

There is one wall this lesson cannot climb. Load the 72B model in the figure and it does not fit at all. Its weights are 145.4 GB against 73.6 GB of usable memory on an 80 GB card. No context length helps. No batching strategy helps.

At that point serving stops being a memory-arithmetic problem and becomes a distributed systems problem. That is lesson 20.

Calibrate to your stage

Interactive · calibrate to your stage

What to actually do about this, at your size

Nearly all guidance on this topic is written for one company size and then read by everyone. Pick yours — the list re-sorts, and what you should deliberately not build drops to the bottom.

  • Knowing your KV cache per tokenDo it

    The four numbers from your model's config, multiplied out, written down somewhere.

    At this stage · Now beside your actual context lengths, because the figure only means something against the contexts your traffic really uses.

  • Recording your input/output token ratioDo it

    Splitting the two directions in your telemetry and watching the shape of real traffic.

    At this stage · It is now the single input to every serving decision you will make. Prefill-heavy and decode-heavy traffic want different hardware and different routing.

  • Prefix cachingDo it

    Reusing the cached keys and values for a prompt prefix that has been seen before.

    At this stage · Now with the prefix designed rather than accidental — system prompt and tool definitions first, anything volatile last.

  • Self-hosting an open-weight modelSkip it

    Running vLLM on your own or rented GPUs instead of calling somebody's API.

    At this stage · Still skip, unless a data residency rule forces your hand. Your traffic is still spiky and an engineer's month is worth more than the saving.

  • Prefill/decode disaggregationSkip it

    Running the two phases on separate machines so neither interferes with the other.

    At this stage · Still skip. The failure mode here is adopting a research-grade architecture to solve a problem a bigger batch would fix.

2 of 5 deliberately skipped at this stage. Knowing which controls you are choosing not to build, and being able to say why, is a stronger signal than having built all of them.

What to carry out of this

  1. 1
    Prefill and decode are limited by different things

    One is compute-bound, the other bandwidth-bound. Measured on the same model and hardware, utilisation differs two to four fold between them. Every serving decision downstream — batching, routing, hardware, price — is an answer to that split.

  2. 2
    Parameter count is the wrong number to plan with

    Two models both called 7B differ more than twofold in cache cost per token, because of layers and key-value heads. Read the config, not the name. The four numbers you need are in a file you can open in a browser.

  3. 3
    Your token ratio decides everything else

    A 1,500-token prompt with a 13-token answer and a short prompt with a long answer are different workloads on different bottlenecks. Split the two directions in your telemetry now, before anyone asks you to size a fleet.

  4. 4
    Self-hosting is a utilisation question

    The same card serving the same model can cost seventeen times more per token at low traffic than at saturation. Ask what your request rate actually looks like at 3am, not what an H100 costs per hour.

Sources

Every source in this lesson

Primary sources wherever one exists. Where a claim is contested or vendor-reported, the lesson says so at the point it is made.

Paper
  • PagedAttention and vLLMSOSP 2023 · arXiv 2309.06180

    Kwon, Li et al., UC Berkeley. The paper that made the KV cache an operating-systems problem. Its Figure 2 is the number worth carrying: existing serving systems put only 20.4–38.2% of their KV cache memory to actual use, against vLLM's 96.3%. Read section 3 for where the waste goes — reserved slots, internal fragmentation, external fragmentation.

  • Orca and iteration-level schedulingOSDI 2022 · USENIX

    Yu, Jeong et al., Seoul National University and FriendliAI. The origin of what everyone now calls continuous batching — a name that appears nowhere in the paper, which says “iteration-level scheduling”. Measured 36.9× throughput over NVIDIA FasterTransformer at matched latency on GPT-3 175B, 8×A100 over NVLink.

  • DistServe and the phase splitOSDI 2024 · arXiv 2401.09670

    The cleanest statement of the asymmetry this lesson is built on: prefill “tends to be compute-bound”, while decode “incurs a similar level of I/O to the prefill phase, making it constrained by the GPU's memory bandwidth.” Appendix A gives the threshold — on an A100-80GB an operation is compute-bound above an arithmetic intensity of 156.

  • Splitwise production tracesISCA 2024 · arXiv 2311.18677

    Microsoft, but peer-reviewed and with the traces released. Two things to take from it. Median output length in their production coding service is 13 tokens against a 1,500-token median prompt. And capping GPU power by more than half, 700W to 350W, costs the decode phase almost no latency — an independent confirmation that decode is not compute-limited.

  • Efficiently Scaling Transformer InferenceMLSys 2023 · arXiv 2211.05102

    Pope et al., Google. The measured version of the asymmetry. Table 2, PaLM 540B on 64 TPU v4 chips: model FLOPS utilisation is 43% in prefill and 14% in decode at low latency, 76% and 33% tuned for throughput. TPU rather than GPU, so read it as the shape of the gap rather than a number for your hardware.

  • Grouped-query attentionEMNLP 2023 · arXiv 2305.13245

    Ainslie et al., Google Research. The one-line version: “Going from MHA to MQA reduces H key and value heads to a single key and value head, reducing the size of the key-value cache… by a factor of H.” Table 1 is the argument — T5-XXL inference falls from 1.51s to 0.28s with eight groups, at 47.1 average quality against 47.2.

  • One Write-Head is All You NeedarXiv 1911.02150

    Shazeer, 2019. A preprint rather than a reviewed paper, and still the clearest first-principles derivation of why decode is bandwidth-bound. Its measurement is the asymmetry in miniature: multi-query attention takes decode from 46µs to 3.8µs per token while barely moving the encoder, 1.7µs to 1.5µs. The fix that helps decode twelvefold does nothing for prefill.

  • Beyond Per-Token PricingarXiv 2606.11690 · preprint

    Flagged deliberately: a single-author preprint, not peer-reviewed, on rented Azure H100s with a synthetic fixed-length workload. There appears to be no reviewed study of this question at all. Its shape survives the caveats — the same GPU running the same model costs $15.25 per million output tokens at 1 request per second and $0.87 at 25. Utilisation, not hardware, sets your cost.

Code
  • Qwen2.5 7B InstructHugging Face

    The config that carries this lesson's argument. 28 layers, 28 attention heads, and only 4 key-value heads — so seven attention heads share each set of cached keys and values. Weights measured exactly at 15,231,233,024 bytes from the safetensors index. The result is 56 KB of KV cache per token, the cheapest context of the four models measured.

  • Mistral 7B Instruct v0.3Hugging Face

    The counterweight, and the reason parameter count is the wrong number to plan with. Weights of 14,496,047,104 bytes — slightly smaller than the Qwen model — but 32 layers and 8 key-value heads give it 128 KB per token, two and a third times the cache cost. Same nominal size, same card, less than half the concurrent users.

  • Qwen2.5 72B InstructHugging Face

    Where the single-card conversation ends. The safetensors index reports 145,412,407,296 bytes of weights against 73.6 GB of usable memory on an 80 GB card. No context length or batching strategy closes that gap, which is what forces the sharding problem into the next lesson.

Docs
  • vLLM engine argumentsdocs.vllm.ai

    The setting every concurrency number on this page depends on. gpu_memory_utilization is “The fraction of GPU memory to be used for the model executor, which can range from 0 to 1… If unspecified, will use the default value of 0.92.” Worth reading the wording carefully: the documentation does not say what the remaining fraction covers, so this lesson does not either.

  • Claude model pricingplatform.claude.com

    Checked because this lesson wanted to explain the input/output price gap and would not assert it unsourced. The page gives the numbers — every current model prices output at exactly five times base input — and offers no reason for the ratio. That the multiple is identical across architectures suggests a commercial simplification rather than a cost pass-through.

Lesson 18
Observability and tracing
Lesson 20
Serving a GPU fleet