LLM inference systems
Count KV storage, schedule decoding slots and verify speculative probability mass.
Separate prefill and decode
Four requests need two, five, one and three output tokens. If a server reserves two slots for a whole batch, one short request can finish while its slot remains unavailable to waiting work. Language-model serving has to schedule repeated decoding steps and the memory retained between them.
The traces and model dimensions below are independently specified teaching inputs. No weights were loaded, no provider was called and no device speed was measured.
A request occupies many iterations
An autoregressive model produces a token conditional on the prefix, appends it and repeats until a stopping condition. Requests therefore differ in both prompt length and output length. Grouping them only at admission can leave unused capacity when shorter outputs finish. Iteration-level scheduling, developed in Orca, permits the active group to change between decoding steps (Yu et al.).
Prefill prepares the state; decode extends it
During prefill, the engine processes the known prompt and constructs keys and values for its tokens. During decode, each new position attends to the retained state and adds its own keys and values. The causal mask permits parallel processing of known prompt positions; future output tokens still depend on earlier generated ones.
Prefill can expose substantial matrix parallelism. Small-batch decode often spends much of its time moving weights and cache data relative to useful arithmetic. These are workload tendencies, not a guarantee that every prefill is compute-bound or every decode memory-bound. Context length, batch size, kernel, quantization and hardware change the bottleneck.
Count retained cache elements
Count the cache elements
For a decoder with layers, key/value heads, head dimension , retained tokens and bytes per element, the unsharded cache size is
The factor two stores a key and a value. Each layer retains elements of each type per token. With fictional dimensions , , , and , this is 9,437,184 bytes, exactly 9 MiB. Query-head count need not equal key/value-head count in grouped-query attention. The estimate excludes weights, activation workspace, allocator metadata and replication across devices.
Memory rises with concurrent retained tokens, not merely the number of requests. Admission control must budget long prompts and possible continuations. A request limit that works for short inputs can run out of memory on a different length distribution.
Reuse finished decoding slots
Release finished slots at the next step
Use two decode slots and four requests A–D, all ready at tick zero, with output lengths . One tick emits one token for every active request. Ignore prefill and assume tick cost does not change with occupancy.
| Tick | Continuous active requests | What becomes possible next |
|---|---|---|
| 1 | A, B | Both continue |
| 2 | A, B | A finishes; C can enter |
| 3 | B, C | C finishes; D can enter |
| 4 | B, D | Both continue |
| 5 | B, D | B finishes |
| 6 | D | D finishes |
A scheduler that fixes batches as (A,B), then (C,D), keeps the first pair's slots reserved for five ticks and the second pair's slots for three. Individual completion ticks are if completed results can be returned early. With continuous admission they are . The last completion moves from tick 8 to tick 6. Useful slot occupancy is versus .
The eleven useful token steps are unchanged. We removed idle reserved slots; we did not reduce the number of tokens. Real engines also schedule prefill, respect token budgets and contend for memory. This trace is a mechanism demonstration, not an Orca or vLLM benchmark.
Count block waste
Allocate blocks instead of a maximum-length reservation
PagedAttention maps logical sequence positions to physical cache blocks so a sequence need not occupy one contiguous maximum-sized allocation (Kwon et al.). For a simple allocation exercise, choose blocks of 32 token positions and sequence lengths . They require blocks, or positions. There are 192 allocated positions for 108 used positions: 84 unused.
For each sequence, the last block wastes fewer than 32 positions, so total internal waste is less than . This bound concerns only partial final blocks. It does not include block-table metadata, free blocks kept in reserve or other GPU allocations. Shared immutable prefixes can further reduce duplicate storage, with copy-on-write needed when branches diverge.
Reuse prefixes and correct proposals
Reuse a prefix only when its computation matches
A prefix cache reuses previously computed key/value state for an identical eligible token prefix and compatible model execution. It saves work on that prefix's prefill; it does not eliminate decoding new output tokens. vLLM documents that distinction explicitly. Model, tokenizer and relevant execution changes can invalidate reuse, and access boundaries must prevent an unintended cross-user cache channel.
A stable system instruction at the start of several requests can create reuse opportunities. Semantically similar sentences are not necessarily the same token prefix. This mechanism also differs from returning an entire cached response.
Speculate, then correct the distribution
A cheap draft distribution proposes a token; the target distribution checks it. For a proposal with , accept with probability . On rejection, sample from a distribution proportional to . This is the exact sampling correction of Leviathan, Kalman and Matias, applied here to a new three-symbol example.
Verify the emitted distribution
Take and . Accepted mass is the elementwise minimum , totaling 0.8. Rejection has probability 0.2. The missing mass normalizes to . Adding rejection probability times that distribution recovers exactly.
More generally, accepted mass for is . The rejection branch adds . Their sum is . If the distributions coincide, rejection has probability zero and no residual normalization is needed. This reasoning applies at a given prefix; later proposals must be validated against the correct conditional prefix as well.
Where a speedup could come from
Several proposed positions can be checked together by the target. That can reduce serial target invocations while doing extra draft work. Distributional correctness does not prove a runtime saving. Record draft time, verification time, accepted tokens and rejected work before claiming faster execution.
When speculation loses
A poor draft causes frequent rejection. A costly draft can erase the saving even with high acceptance. A memory-constrained batch may lose capacity when another model is loaded. The optimal proposal length depends on these costs and on the changing prefixes; our probability example deliberately makes no hardware-speed claim.
Measure useful completions
Measure what the caller experiences
Time to first token (TTFT) runs from the chosen request boundary to the first output token and includes waiting under that definition. Time per output token (TPOT) measures subsequent generation; state whether it is averaged per request or across token intervals. A request with one output token has no subsequent interval. End-to-end completion time also depends on output length.
Throughput counts completed requests or generated tokens per time, with the unit stated. Goodput counts only work meeting a declared usefulness and latency criterion. A scheduler can raise token throughput while making a small request wait behind long prefills. Examine distributions and workload classes rather than only one overall rate.
Choose an engine for a tested contract
An engine supplies kernels, cache management and scheduling. Compatibility depends on the architecture, quantization format, device and required output behaviour. vLLM is a concrete open implementation of the discussed cache ideas, but a current feature list is not an evaluation of our application. Pin the engine revision and test correctness and resource use with permitted model artifacts before deployment.
What changed
The scheduling trace reclaims idle slots without changing output lengths. The allocation exercise bounds one source of cache waste. The sampling calculation preserves the target distribution while leaving performance as a separate measurement.
Limits
The trace assumes constant tick cost and immediate admission. The memory formula assumes a simple retained KV layout and no sharding. The sampling calculation uses exact finite probabilities. Real implementations add numerical rounding, kernels, preemption, long-context attention and distributed communication. None of those systems was benchmarked by these exercises.
What to retain
Separate prefill from decode. Budget retained tokens. Schedule at iteration boundaries when possible. Distinguish block waste from all allocated memory. Verify speculative sampling separately from its speed. Report latency and useful throughput for a stated workload.
Next
Rolling out models asks how a verified artifact reaches users and how to limit exposure when a replacement behaves differently.
References
- Gyeong-In Yu, Joo Seong Jeong, Geon-Woo Kim, Soojeong Kim and Byung-Gon Chun. Orca: A Distributed Serving System for Transformer-Based Generative Models. OSDI, 2022: iteration-level scheduling. No source trace or benchmark reused.
- Woosuk Kwon, Zhuohan Li, Siyuan Zhuang, Ying Sheng, Lianmin Zheng, Cody Hao Yu, Joseph E. Gonzalez, Hao Zhang and Ion Stoica. Efficient Memory Management for Large Language Model Serving with PagedAttention. SOSP, 2023: logical cache blocks and sharing.
- vLLM contributors. Automatic Prefix Caching and Paged Attention, checked 13 November 2026: prefill reuse and historical cache layout. The Paged Attention page explicitly describes an older kernel, not current vLLM implementation details.
- Yaniv Leviathan, Matan Kalman and Yossi Matias. Fast Inference from Transformers via Speculative Decoding. ICML, 2023, section 2 and appendix A.1: exact sampling correction. The finite probability vectors above are original.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Go deeper — optional
Code and labs do not count toward the main percentage or the certificate.
- KV slots and speculative probability massoptional
No model or accelerator is run. Token ticks have equal cost by assumption. KV arithmetic excludes weights and workspaces; block waste means final-block slack only. Exact probability correction does not establish a runtime speedup.
~20 min · easier on a computer · The corresponding lesson and basic Python functions.
Self-check in the notebook — not part of mastery or the certificate.
Answers are saved on the server and tied to this browser until you sign in.