Skip to content
BIASED

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 LL layers, HkvH_{kv} key/value heads, head dimension dd, TT retained tokens and ss bytes per element, the unsharded cache size is

MKV=2LHkvdTs.M_{KV}=2LH_{kv}dTs.

The factor two stores a key and a value. Each layer retains HkvdH_{kv}d elements of each type per token. With fictional dimensions L=12L=12, Hkv=4H_{kv}=4, d=64d=64, T=768T=768 and s=2s=2, 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 [2,5,1,3][2,5,1,3]. 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 [2,5,6,8][2,5,6,8] if completed results can be returned early. With continuous admission they are [2,5,3,6][2,5,3,6]. The last completion moves from tick 8 to tick 6. Useful slot occupancy is 11/16=68.75%11/16=68.75\% versus 11/12≈91.67%11/12\approx91.67\%.

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 [33,65,10][33,65,10]. They require [2,3,1][2,3,1] blocks, or [64,96,32][64,96,32] 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 3⋅32=963\cdot32=96. 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 qq proposes a token; the target distribution pp checks it. For a proposal with q(x)>0q(x)>0, accept with probability min⁡(1,p(x)/q(x))\min(1,p(x)/q(x)). On rejection, sample from a distribution proportional to max⁡(p(x)−q(x),0)\max(p(x)-q(x),0). This is the exact sampling correction of Leviathan, Kalman and Matias, applied here to a new three-symbol example.

Verify the emitted distribution

Take p=(0.2,0.5,0.3)p=(0.2,0.5,0.3) and q=(0.4,0.4,0.2)q=(0.4,0.4,0.2). Accepted mass is the elementwise minimum (0.2,0.4,0.2)(0.2,0.4,0.2), totaling 0.8. Rejection has probability 0.2. The missing mass (0,0.1,0.1)(0,0.1,0.1) normalizes to (0,0.5,0.5)(0,0.5,0.5). Adding rejection probability times that distribution recovers (0.2,0.5,0.3)(0.2,0.5,0.3) exactly.

More generally, accepted mass for xx is q(x)min⁡(1,p(x)/q(x))=min⁡(p(x),q(x))q(x)\min(1,p(x)/q(x))=\min(p(x),q(x)). The rejection branch adds max⁡(p(x)−q(x),0)\max(p(x)-q(x),0). Their sum is p(x)p(x). 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

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.

Full notes

Answers are saved on the server and tied to this browser until you sign in.