← Inference From First Principles

Implementing Scheduling and Caching

A scheduler, the engine's own books for cache memory and a copying prefix cache added to the capstone behind two flags: what they change on a real model when the compute is still serial, and a bounded cancellation enumeration over 368 real-model runs, with explicit limits on what it proves.

Twelve requests arrived at once, each carrying the same 328-token system prompt and a different order message. The serial engine of Chapter 41 gave the median request its first token after 3.28 seconds. The scheduler of this chapter, allowing eight requests to advance per iteration but still making one backend call per sequence, gave it after 0.68 seconds; adding a copying prefix cache gave 0.53 seconds. The paired median ratios were 0.206 and 0.160 of the serial first-token time, respectively. Median last-finish times were similar: 7.06, 7.04 and 7.00 seconds, with paired ratios that also show run-to-run variation. The median request finished later, not sooner: 4.70 seconds against 3.80, because interleaving makes everyone wait for everyone’s tokens. The interleaving configuration did not fuse decode calls or show a throughput improvement: it changed the order in which requests waited. Prefix reuse did reduce repeated prefill computation, at a memory cost. These distinct mechanisms should not be credited with the same effect.

That is the honest size of what a scheduler does when the model is called once per sequence per token, and it is the first half of the chapter. The second half is about what it takes to let many requests share a machine without leaking it. In 368 enumerated single-request cancellation runs on the real model, across four configurations, the checks reported no surviving sequence, cache-book allocation or increase in CUDA allocated bytes relative to a post-warm-up baseline, after dropping the prefix cache. This is a finite, observed property of the tested scenarios, not a proof of every cancellation interleaving or of all GPU memory being returned to the operating system. An earlier cancellation sweep also found no problem, but its uncancelled control runs had never preempted a request or reused a prefix: the test had not exercised the mechanisms it purported to qualify. The first version of the prefix cache itself, in its first run, had zero hits.

The question

Chapter 41 gave the runtime contracts and a serial engine. Two subsystems were left on the deferred list: a scheduler, which decides which requests run and when, and a cache manager, which decides what memory they may hold and what is worth keeping. This chapter builds both, minimally, behind feature flags, and asks three questions of them. What do they change on a real model, measured against the serial engine on the same requests? What does it cost in altered output tokens, copied cache memory, repeated prefill and tail latency? And how do we know that ending a request, in any of the ways a request can end, releases everything it held and disturbs nothing else? The outcomes are reported separately: latency redistribution, token agreement with the serial reference, resource-accounting agreement and cancellation cleanup. Passing one is not a substitute for passing the others.

The third question demands a bounded safety argument: construct a finite set of cancellation interventions, execute each one, and verify both internal invariants and independent observations. It is stronger than checking a few happy paths, but it is not formal verification of all possible schedules or faults. The scheduling and reuse questions are empirical comparisons on the single recorded model and machine.

Where this sits

Chapters 14 to 16 measured paged caches and prefix caches in isolation, Chapters 15 and 27 measured continuous batching and concurrent streams on GPT-2, where one call really did decode a batch, and Chapter 26 measured admission control. This chapter does not repeat them. At the Chapter 42 measurement milestone, the capstone backends advanced sequences separately; Chapter 43 was reserved for a backend that decodes a batch in one call. The current repository can contain later extensions, so the claims below are about the saved Chapter 42 experiment rather than every capability subsequently added to inference_lab. Here each running sequence is advanced by its own call, so the scheduler changes who runs and when and cannot by itself turn several decode passes into one fused pass. That limit is a choice, made so that one request’s failure cannot end another’s (the lesson of Chapter 30), and it makes the results below cleaner to read and smaller than the batching results of the earlier chapters.

The design reuses Chapter 41’s contracts and extends them in three places: a fork operation on backends, a CacheAccounting contract for the engine’s logical block books, and an iteration-level BatchEngine. Chapter 43 will need the first to survive batching and Chapter 44 will run the whole engine on Chapter 40’s suite. The block books are intentionally not a physical allocator: Tensor memory remains the backend’s responsibility, so the runtime needs independent checks to establish whether reported ownership corresponds to actual allocations.

Where the starter was wrong

The starter’s MiniScheduler is a list with a limit of four. Its MiniCache is a dictionary keyed by request id. In its demo each of five requests is submitted once, so a lookup of a request’s own id never finds anything: the number of cache hits is zero by construction, whatever the flags. The starter’s “4 of 5 scheduled” is merely a queue-limit observation; its “cancellation cleaned up” means list.remove changed a Python list, not that inference state was released. Nothing in it holds memory, so there is nothing to clean up, and no request runs, so there is nothing to cancel.

The corrections are structural. A scheduler has to act on requests that hold things: a backend sequence, blocks on the engine’s books, a place in a queue, perhaps a claim on a cached prefix. A cache has to be keyed by content, not by identity, to ever hit. And cleanup has to be checked against something other than the object that did the cleaning. The original file and its test are unchanged. This makes the new baseline meaningful: the same prompt, arrival pattern and generated-token target can be run serially and through a scheduler, and the resulting timestamps, tokens and allocations can be compared.

The design

At this milestone, one iteration of BatchEngine.step comprises four ordered phases. The order is observable—especially when a deadline, eviction or failure occurs between phases—and is part of the contract rather than an implementation detail.

  1. Expire. Waiting and running requests past their deadlines are ended with TIMEOUT at the iteration boundary; the single-threaded step is not interrupted midway by an external cancellation.
  2. Admit. Waiting requests are taken in arrival order while a running slot is free and the cache can hold them. The first request that does not fit stops admission; none is skipped. An admitted request has a backend sequence opened for it, possibly forked from the prefix cache, and its prompt prefilled.
  3. Advance. Every running request, in admission order, samples at most one output token and—if it continues—is decoded in its own backend call in the measured Chapter 42 implementation. A request that reaches its length, a stop token or its context ends here.
  4. End. Under the tested successful-cleanup paths, ending releases the backend sequence and its logical blocks, then records one FinishEvent; a backend whose release fails requires a separate recovery or independent leak alarm. A failure in a backend call ends that request in ERROR and nobody else’s.
    flowchart LR
    S[submit] -->|too large, queue full| R[refused: one ERROR event]
    S --> W[waiting]
    W -->|slot free and blocks free| A[admit: fork a cached prefix or start empty, prefill the rest]
    A --> RUN[running]
    RUN -->|each iteration: sample, emit, decode| RUN
    RUN -->|blocks short, preemption on| W
    RUN -->|stop, length, cancel, deadline, error| E[end: release sequence, release blocks, one FinishEvent]
    W -->|cancel, deadline| E
    A -->|prompt computed| P[prefix index: keep a copy of whole blocks]
    P -->|least recently used, to make room| X[evict: release copy and its blocks]
  

Two flags and two numbers shape it.

max_running caps how many requests can be running and advanced in one scheduling iteration, not the number of sequences computed in a single GPU forward pass at this milestone. With 1 the engine is the serial engine with a queue in front of it, and the measurements use that as a check on the engine itself: the one-running configuration had a median paired first-token ratio of 0.995 (range 0.931–1.057 over five trials) and a last-finish ratio of 1.014. These are descriptive paired ratios, not confidence intervals or proof of equivalence.

preemption chooses how blocks are promised. Switched off, a request is admitted only when blocks for its prompt and its longest possible output are free, and it keeps them until it ends; it can never run out of cache, and it wastes whatever it does not generate (Chapter 14). Switched on, it is admitted with blocks for its prompt, takes one more when it crosses a block boundary, and when none is available the selected running victim is released and placed at the front of the waiting queue, then its prompt plus already emitted tokens are recomputed on re-admission. The measured policy chooses the most recently admitted running request; a different victim policy is also deliberately tested as conforming. Its per-request random stream is not reset, preserving the draw sequence for subsequent tokens. Identical output still depends on numerical path and sampler behaviour; stream ownership alone cannot guarantee bitwise token identity across recomputation.

prefix_cache keeps, as soon as a prompt has been computed, an independently allocated copy of its first whole blocks, made using the backend’s fork. A later request that shares whole blocks with an entry forks from it and prefills only the rest. The details matter more than the idea, and the first version got them wrong; they are in their own section. This is neither paged attention nor memory deduplication: a reused prefix avoids prefill operations, but each fork still owns its own key-value tensors.

The books. BlockCache counts blocks of 16 tokens per owner and does not use the backend as the source of truth for allocation decisions. This follows Chapter 41’s lesson that a backend’s account of its own memory cannot be used to check the backend. A request is an owner, and so is each prefix entry. The contract (CacheAccounting) says an owner is charged ceil(tokens/block_size) logical blocks, allocation growth cannot exceed the total, a refused allocation is atomic, and freeing an unknown owner is an error. Those arithmetic guarantees say what the scheduler has reserved, not the CUDA allocator’s live or peak bytes. A production admission rule must budget weights, copied prefixes, temporary tensors, fragmentation and non-cache memory separately.

The prefix cache, twice

The first design kept, for each finished prompt, an entry holding that prompt’s whole block-aligned prefix, and matched a new prompt against entries that were a prefix of it. Its first run on the real model, one trial of the burst, had 12 inserts, 12 misses and no hits. That zero-hit result was an experiment-design failure, not evidence that shared prefixes were absent. Every request’s prompt was 328 shared tokens followed by 50 to 76 of its own, so each entry was the shared part plus its owner’s own tail, and no entry was a prefix of any other prompt.

The revised design compares prompt token sequences and chooses the entry with the longest block-aligned common prefix. It forks only that common portion: fork(seq, n) makes a new sequence containing the first n tokens of the cached sequence. It also cuts entries back. The first time a new prompt shares a start with an existing entry that is longer than the shared part, the entry is released and replaced by a copy of only the shared blocks, which is the part a third prompt can use. A prompt is never matched to its full length; at least one prompt token is always left to prefill, because a fork has no logits of its own. Entries are compared on the tokens, never on a hash alone. The index also needs a clear cache identity: the token sequence is sufficient for the homogeneous, single-model, single-tenant experiment, but a general system must scope entries by model revision, tokenizer, adapter state, positional semantics and tenant permission. None of those cross-tenant cases was exercised here.

In the burst of five trials the cache then reused 17,600 prompt tokens and prefilled 5,921, against 23,521 prefilled without it. The reused count is 5 × 11 × 320 = 17,600: in each trial the 11 requests after the first reused 20 complete, 16-token blocks from the 328-token shared start. These counters measure tokens skipped by prefill, not dollars, bytes saved, or an observed decrease in energy consumption.

This implementation trades computation for memory; it does not offer memory sharing. The framework adapter’s cache is one tensor per layer per sequence, and sharing storage between two sequences needs attention kernels that read a block table, which this book does not write. An entry costs its own blocks, and so does every request forked from it. The peak CUDA allocation shows it: peak CUDA allocated-memory growth over the run baseline was 93 MB for serial, 405 MB for eight running, and 424 MB with the prefix index in float16; the corresponding float32 measurements were 137, 790 and 954 MB. The measured peaks combine active requests, cached prefixes and transient allocations. They are not the sizes of the prefix entries alone, and are not total GPU memory consumption.

The backend’s fork has its own contract, five checks: the fork’s later logits equal those of a sequence prefilled in one piece within the backend’s tolerance; the fork and its parent are independent in both directions, and a fork outlives its parent; the fork is an independent owner of key-value memory; a number of tokens outside the sequence raises and opens nothing; an unknown handle raises. The Hugging Face adapter’s fork builds compact copies of the first n tokens of each layer’s keys and values. I had first written it as a deep copy followed by a crop, and replaced it before measuring, because a crop that returns a view would keep the longer tensor alive while the adapter reported the shorter length. The suite’s memory check reads the adapter’s own report and could not see that; the allocator can, and every cancellation run below reads it. The original fork implementation was changed before these measurements. Its passing tests therefore provide evidence for the compact-copy implementation, not for the discarded deep-copy-and-crop design. Allocator observations complement the adapter’s report but do not prove the absence of every reference or reserved-memory retention problem.

The checks

The engine’s promises are in three ADRs: 010 (iteration-level scheduling, arrival order, one call per sequence, refusals as terminal events), 011 (the engine’s own books, the two ways of promising blocks, the copying prefix cache), 012 (cancellation, deadlines and failures end a request completely and at once). They are held by 24 new checks, seven for the block books, five for fork and twelve for the engine, bringing the Chapter 42 snapshot to 71 named checks (47 inherited and 24 new). As in Chapter 41, a test fails an ADR that names a check which does not exist and a check that no ADR names. The names are traceability links, not a proof that every implication in an ADR has been covered. Changes made by later capstone chapters must have their own acceptance evidence.

The twelve engine checks are scenario checks. A scenario is a script: which request arrives at which iteration, which are cancelled when, at which backend call a failure is injected. The reference scenarios are deterministic given their inputs, and a StepClock advances logical time without sleeping; wall-clock races and cancellation during a GPU operation are outside their model. After every iteration the engine is audited against two sets of books. One is the engine’s own (audit()): no request in two queues, none finished and still queued, running within its limit, the block owners exactly the running requests and the prefix entries, each owner holding blocks for at least the tokens its sequence has. The other is kept from outside, by a TrackingBackend that wraps the backend and records which sequences are open: the set the backend has open must equal the set the engine accounts for, and, where the bytes per token are known, the backend’s reported logical key-value memory is checked against analytic bytes-per-token times tracked sequence length. That calculation is independent of the backend’s own memory report, but not a physical allocator inspection.

The checks are these: parity (random scenarios under every flag combination, compared with the serial engine alone on the same requests: a request that completes has the serial engine’s tokens, one that was cancelled has a prefix of them, and an error that was not provoked is a failure), audited_every_step, one_finish_each, cancel_exhaustive, cancel_while_queued, fault_isolation, deadlines, admission_limits, preemption, prefix_reuse, arrival_order and close_cleans_up. The saved CPU evidence records all twelve checks passing: 160 seeded parity scenarios against the serial reference, another 160 scenarios with 3,304 audited iterations, 256 enumerated cancellations in one scenario shape and 20 fault-isolation cases. These are observations for the generated scenarios, not a bound over all schedules. The parity check must treat an unexpected ERROR as a failed experiment rather than accepting it as a legitimate completion; that weakness was identified and repaired during mutation testing.

One audit was worthless at first. The engine’s first audit() checked that free blocks plus used blocks equal the total. The cache computes free as total minus used, so the sum is an identity, and a test that corrupted the books to see whether the audit noticed found that it could not. The audit now checks that each owner holds the ceiling of its tokens in blocks and that the blocks held do not exceed the cache’s size. The negative corruption test remains in the suite. This is an important example of a check that was initially tautological: reproducing the same internally computed quantity is not independent verification.

Testing the tests

The method is Chapter 41’s: write faulty implementations, declare in advance which checks must fail them, and read the surprises. The final Chapter 42 campaign includes 24 deliberately faulty implementations: six block caches, five forks and thirteen engines. Engine faults are made by overriding a seam, a method that holds exactly one decision: a release that does not happen, a cancel that leaves a queued request queued, an admission with no limit, a prefix match on any entry whatever its tokens, a failure that ends the whole batch, a cancel that produces two terminal events, a victim policy. A changed preemption victim is deliberately not classified as faulty if it maintains the contract; policy freedom is distinct from an invariant violation.

Kind Mutants Killed Failed every declared check
cache 6 6 6
fork 5 5 5
engine 13 13 13
all 24 24 24

The saved matrix contains 82 failing mutant–check pairs, 13 mutants with at least one failure beyond their declared checks, and no new check left untouched by every mutant. These are counts of detections within an author-designed defect set, not an estimate of production defect coverage. One variant is not in that table: an engine that, when it must preempt, chooses the request that has been running longest instead of the newest. It is a different policy and not a fault, and it passed every check. A contract that cannot tell two correct policies apart is doing its job, and a test that fixed the victim would have been testing the implementation.

The matrix as it stands is the second. The initial matrix had 23 mutants and two survivors—evidence that the first version of the checks was incomplete. A request whose deadline passed while it waited had never been caught, because the mutant let it start and the deadline expired a step later, and the check accepted a timeout either way. The check now requires that a request which expires while waiting has produced no token. An engine that never evicted a prefix entry to make room for a new request survived because the only eviction the scenarios exercised was the one inside insertion; a scenario was added in which an entry fills the cache and a request needs all of it. Two other mutants were caught by checks other than those declared for them, and parity now counts an unprovoked error as a failure, which also caught an engine that admits a request whether or not its blocks are free. Two mutants were added for the two checks no mutant had failed. Keep the original failing matrix as regression evidence: repairing tests after inspecting survivors is legitimate test development, but it must not be confused with a blind validation set. A fresh set of faults or an independent reviewer would be a stronger next test of the checks.

Cancellation, by exhaustion

The gate asks for reproducible concurrency scenarios and a cleanup argument that can be falsified. A proof over all schedules is not available, since a schedule space is unbounded. A complete enumeration of a specified finite test domain is available, and that is what cancel_exhaustive provides: a scenario of four requests (three of them sharing a 34-token prefix, two of them sampled, one with top-k; arrivals at iterations 0, 0, 1 and 3; a cache of 10 blocks and three running), and every request cancelled at every iteration from the first to the last of the uncancelled run, in each of the four flag combinations. 256 runs on the numpy backend. Within that finite domain, the engine audit and the separately maintained tracking backend agreed after each iteration; the survivors’ tokens were the serial engine’s; the cancelled request had one terminal event and its tokens were a prefix of its serial tokens; and once the prefix cache was dropped, no sequence was open, the backend held no bytes and the books held no block.

What that does and does not cover is worth saying exactly. It covers every enumerated pair of one target request and one cancellation point in a single scenario with specific arrivals, flags and block counts. It does not cover cancelling two requests, a cancel during an iteration (the engine is single-threaded and a cancel is a method call between iterations), or a different shape of scenario; the random scenarios cover some of that by sampling. Even for the finite domain, the result is an executable exhaustive test, conditional on the correctness of the harness and observations, rather than a mathematical proof of the implementation. Tests should report the complete enumeration count and confirm that the relevant mechanisms were active in the uncancelled control runs.

The same exhaustion ran on Qwen3-0.6B. The scenario had four requests of 407, 399, 391 and 394 tokens sharing 328, with 12, 12, 16 and 10 new tokens, and three running at most. For each flag combination, four target requests were separately cancelled at each of 23 iteration indices, giving 4 × 23 = 92 runs and 368 in total. After dropping any prefix entries, each run checked the CUDA allocated-byte count against a post-warm-up baseline as well as logical owners, open sequences, emitted tokens and terminal events. None had a problem. None had a token that differed from the serial engine’s. Allocated bytes returned to the recorded baseline in every tested run; this does not establish that CUDA reserved bytes returned to the driver or that cleanup survives release failures or asynchronous cancellation. The GPU cancellation scenario had arrivals at iterations 0, 0, 1 and 2 according to the saved result, unlike the smaller CPU reference scenario above, which specifies 0, 0, 1 and 3.

The first version of this experiment passed too, 328 runs with no problem, and I discarded it. Its cache was too small for any prefix entry to survive or for any request to be preempted: the uncancelled runs showed zero tokens reused and zero preemptions in every configuration, so what it had shown was admission and cancellation of requests that ran to completion under reservation. A claim that cancellation cleans up the machinery of preemption and prefix sharing needs a run in which the machinery was active. After resizing, the uncancelled runs show it: with the prefix cache on and 110 blocks, 960 prompt tokens were reused and 631 prefilled against 1,591; with preemption on and 78 blocks, one request was preempted and 401 tokens recomputed; with both flags on at 98 blocks, 640 prompt tokens were reused but no preemption occurred. The key interaction remains untested: no uncancelled control run exercised both a prefix hit and a preemption together, so the 368 cancellation outcomes cannot certify that combination. The allocator baseline in the first run was also wrong, taken before the process’s one-time library allocation of 8,519,680 bytes, which made every run look as if it had grown by exactly that. The baseline error—reading the allocator before its one-time library allocation—also shows why a passing memory test requires a documented warm-up and an independently checked baseline.

What the scheduler did on the real model

Three workloads, each run under several configurations, five trials in float16 and two in float32. within each trial the configurations saw the same request set, but the serial reference always ran first, and the remaining configurations were randomised. The comparisons are paired by workload, but the serial-first order is a potential systematic bias. Medians over trials with the range in brackets; the ratios are of each trial’s configuration to its own serial run. The reported brackets are observed trial ranges, not confidence intervals. Five and two trials cannot establish stable tail behaviour, and no service-level capacity claim follows from these finite bursts on one machine.

A burst with a shared prefix. Twelve requests at once, each a 14-rule system prompt and one order message of 378 to 404 tokens in the first trial, 16 generated tokens per request; the shared prefix contains 328 tokens, but the full prompts also contain unique tails.

float16 First token, median request (s) Ratio to serial Median request finished (s) Last request finished (s) Peak CUDA over start (MB)
serial engine 3.28 (3.19 to 3.45) 1 3.80 7.06 (6.88 to 7.47) 93
batch engine, 1 running 3.33 (3.22 to 3.41) 0.995 (0.931 to 1.057) 3.88 7.14 93
8 running 0.68 (0.66 to 0.71) 0.206 (0.198 to 0.211) 4.70 (ratio 1.226) 7.04 (ratio 1.001) 405
8 running, prefix cache 0.53 (0.49 to 0.61) 0.160 (0.150 to 0.179) 4.66 (ratio 1.231) 7.00 (ratio 0.976, 0.957 to 1.018) 424

Generated tokens were compared with the serial engine’s on the same requests: 60 of 60 requests (five trials of 12) were identical in the one-running and eight-running configurations. With the prefix cache it was 59 of 60: one request in one of the five trials produced different token IDs. That is a quality-parity failure under a strict identical-token gate, even though most observed tokens matched. In float32, two trials, all 24 of 24 were identical, and the last request finished at 5.94, 6.09 and 5.40 seconds (a paired ratio of 0.911 and 0.908 for the cache), possibly because avoiding prefill is more valuable in that setting; prefill and decode costs were not isolated, so the cause was not established. The cache saved 7,040 prompt-token prefills across those two trials.

Three readings. First, interleaving is what moved the first-token time: the one-running engine did nothing and the eight-running engine cut the median fivefold, with roughly the same number of per-sequence decode calls, with the same model and no fused batching. Second, the cache’s contribution is small in time in float16: first tokens 0.68 to 0.53 seconds, last finish 1.001 to 0.976 of serial. At this model size a 400-token prefill is cheap next to the 16 decode steps that follow it, so skipping repeated prompt prefills corresponded to a paired median last-finish ratio of 0.976; the observed range (0.957–1.018) includes both improvement and regression, so this sample does not demonstrate a reliable makespan gain. Third, the one different request is the price of the copy. Prefilling the first 320 tokens in one call and the remaining 50 to 76 in another is a different computation from prefilling all of them together, and Chapter 39 found that a different shape of computation changes the bits. This is a plausible numerical-shape explanation, not an isolated causal test: in half precision it changed a token once in 60 requests, and in single precision not once in 24.

A long request ahead of short ones. One request needing 96 output tokens starts at time zero, followed by seven 16-token requests separated by 0.1 seconds. This deliberately exposes head-of-line blocking, rather than representing a measured arrival-rate distribution.

float16 Short requests: first token (s) Short: finished (s) Slowest short: finished (s) Long request: finished (s) Last finish (s)
serial engine 4.73 (4.68 to 4.84) 5.29 (5.26 to 5.40) 6.82 (6.76 to 6.87) 3.38 (3.29 to 3.44) 7.52 (7.46 to 7.57)
8 running 0.29 (0.27 to 0.35) 4.17 (4.05 to 4.54) 4.27 (4.15 to 4.64) 7.42 (7.24 to 8.26) 7.42
paired ratio 0.063 (0.056 to 0.074) 0.792 (0.768 to 0.848) 0.630 (0.613 to 0.677) 2.26 (2.12 to 2.44) 0.986 (0.970 to 1.091)

This is the textbook case, and the serial engine’s weakness is as large as the textbook says: a short request waited 4.7 seconds for its first token, behind a request that took 3.4 seconds and the short ones ahead of it. The scheduler gave short requests their first token in 0.29 seconds, made them finish earlier by a fifth, and took it out of the long request, which finished 2.26 times later (7.42 seconds against 3.38). The median last-finish time changed little across five trials, and its range of paired ratios included both faster and slower completions. Tokens were identical in 40 of 40 requests. A deployment would decide whether that trade is wanted; the scheduler has no notion of priority to make it for them. This is a fairness decision, not a free improvement: lower short-request latency was purchased with higher latency for the long request. A production scheduler would need stated priority, aging and starvation policies and a workload-specific SLO rather than treating one favourable median as a universal gain.

A cache too small for what is admitted. Ten requests at once, 64 new tokens each, 28 logical cache blocks of 16 tokens and at most eight running requests. The experiment forces a policy choice between reserving the possible output and allowing preemption/recomputation.

float16 First token, median (s) Ratio to serial Median request finished (s) Ratio Last finish ratio Preemptions (five trials)
serial engine 10.64 (9.85 to 11.18) 1 12.80 1 1 none
reserve prompt and output 9.05 (7.84 to 9.47) 0.857 (0.701 to 0.903) 14.74 1.099 (1.089 to 1.252) 1.008 (0.992 to 1.032) none
admit on the prompt, preempt 4.64 (3.93 to 8.14) 0.440 (0.395 to 0.765) 15.98 1.248 (1.181 to 1.315) 1.020 (1.001 to 1.077) 23, 2,239 tokens recomputed

Reserving the longest possible output admitted about three requests at a time in that cache (each reserved about nine of the 28 blocks). Admitting on the prompt let more of them start, at the price of 23 preemptions in five trials and 2,239 tokens prefilled a second time (6,289 prefilled against 4,050). First tokens came about twice as soon as under reservation, requests finished later in the median, and the whole job took two percent longer than the serial engine. It restates the Chapter 14 trade-off: conservative reservation holds blocks for possible output, while prompt-only admission may repeatedly destroy and reconstruct prefixes under pressure. All 50 requests in each float16 configuration and all 20 in each float32 configuration matched the corresponding serial token sequences, including the preempted cases. This is observed parity for those cases, not a guarantee for longer or numerically marginal generations. That is better than the prefix cache did. A preempted request recomputes its tokens in one call where the serial engine produced them one at a time, so by the same Chapter 39 argument its later logits should differ in the last digits; in these workloads that never changed a token.

The cost of the engine itself

The engine’s own work per token, measured on a backend that returns fixed logits so that nothing else is in the timing, was 314 microseconds with one request running (range over five repetitions 307 to 371), 334 with four (311 to 420), 328 with eight (321 to 347) and 513 with sixteen (321 to 516), against 510 for the serial engine in the same run and 335 in Chapter 41’s run. The variation between runs is comparable to or larger than the measured differences, so the per-token scheduling overhead cannot be isolated precisely from these numbers. About 300 microseconds of each is the sampler’s float64 conversion and argmax over 151,936 logits; the scheduling, the books and the events are the rest and below the noise. Approximately 0.3 ms per token is under 1% of the roughly 35 ms GPU decode-step scale observed in Chapter 41, but these are measurements of different workloads and cannot simply be subtracted to obtain scheduler cost under serving load. The audit itself measured about 6.5 microseconds per call with eight running requests on this fixed-logit setup; production validation policy remains a separate decision.

What the numbers do not show

  • No fused batching in the Chapter 42 experiments, so no throughput claim. The scheduler changes the order of the same work. The last request’s finish changed by no more than 2.4% on the median trial in any float16 configuration, and the paired ratios ranged from 0.945 to 1.091. A throughput gain from batching decodes is Chapter 43’s to measure and is not claimed here.
  • Five trials, and two. The ranges are over five paired trials in float16 and two in float32 and no interval is computed. The burst’s variation in first-token ratios was narrow (0.198 to 0.211); the pressure workload’s ranged from 0.395 to 0.765. In every trial the serial run came first, which could favour or penalise it by an amount I did not measure.
  • One shape of arrival. Bursts and a fixed stagger. Nothing here is a load, a closed loop or Chapter 40’s suite, and no claim about behaviour at a rate of arrivals follows from it.
  • The prefix cache has no tenant-isolation contract. One cache serves every request; Chapter 16 measured that a request that hits a cached prefix is distinguishable from one that misses by its timing, every time in 40 trials, for that chapter’s cache. I did not measure it for this one and I would expect the same. It is a non-goal of the milestone and a reason not to put this cache in front of mutually distrustful users.
  • Cancellation enumeration is bounded, not an arbitrary-schedule proof. The proof covers each request cancelled at each iteration of one scenario on the real model (and one on the numpy model), not two cancellations at once, not an arbitrary schedule, and not a cancel that interrupts an iteration. The random scenarios sample the rest and are not a proof.
  • Mechanisms were not exercised together. In the real-model cancellation experiment no configuration had both a prefix hit and a preemption in one run.
  • The first sequence of a process leaves 8.5 MB allocated and I did not identify what it is; every measurement was taken after a warm-up that absorbs it.
  • The sources are not reproduced. Orca’s throughput figure against FasterTransformer, and what vLLM and SGLang do for prefix reuse, are as their pages describe them and none was run.
  • Further qualification requirements. Two further limitations should govern adoption. First, the check of resource release can only observe the allocation and ownership quantities it inspects; exceptions inside backend release, overlapping cancellations, and failure to reclaim reserved GPU memory are distinct hazards. Second, observed parity is not universal: the shared-prefix float16 run already contained one differing request, so a strict quality gate would not yet promote that configuration unchanged.

Inference Lab increment

cache.py adds BlockCache for logical ownership accounting, and PrefixIndex for token-sequence matching, longest block-aligned common prefixes and least-recently-used eviction. Neither component owns the physical CUDA allocation or implements shared paged tensors. scheduler.py adds SchedulerFlags and BatchEngine with submit, cancel, step, run, close, drop_prefix_cache and audit. Both backends gain fork. contracts.py adds ForkableBackend, CacheAccounting, CacheFull, UnknownOwner and DELIVERED, and DEFERRED loses the scheduler and the cache manager and NON_GOALS gains three entries. contract_tests.py adds run_cache_suite and run_fork_suite; scenario_tests.py adds Scenario, random_scenario, run_scenario, TrackingBackend, StepClock and run_scenario_suite; mutants_sched.py adds the 24 mutants and the conforming variant. ADRs 010, 011 and 012 are new, ADR-009 is amended, and examples/ch42/sched_lab.py holds the four measurement commands. These statements describe the Chapter 42 acceptance snapshot. Later capstone work may extend the same modules with batched decode, so current source-level capabilities and saved Chapter 42 experiment capabilities must not be conflated.

To run the Chapter 42 test targets and rebuild the aggregate results from already saved measurements (not to repeat the GPU experiments):

python -m pytest tests/test_ch42_scheduler_lab.py tests/test_ch41_inference_lab.py -q
python research/ch42/build_results.py

To rerun the selected real-model workloads and the bounded cancellation sweep with a locally cached Qwen model and the recorded environment (these commands are not part of this editorial review):

python examples/ch42/sched_lab.py workloads --dtype float16 --trials 5 --out research/ch42/measurements/workloads_cuda_float16.json
python examples/ch42/sched_lab.py cancel --dtype float16 --out research/ch42/measurements/cancel_cuda_float16.json

The rule this adds: keep the engine’s own books for every resource a request holds, and check them against books you do not keep; reuse a prefix only by content and only by the blocks actually shared; give every way a request can end the same cleanup; enumerate a clearly bounded set of cancellation interventions and state exactly which dimensions were not varied; check that an experiment exercised the mechanism it claims to test; and report a scheduler’s effect as who waits, not as speed, until the backend can do less work. The acceptance boundary is therefore fourfold: check the runtime’s ownership books, check an independent backend/allocator witness, check final events and token parity, and verify the test actually exercised reuse or preemption before promoting the claim.

What you should now be able to do

  • Say what a scheduler changes when the backend runs one sequence per call, and predict which latency it improves and which it worsens.
  • Write the invariants of a block cache, an engine’s books and a tracking backend, and audit an engine against both after every iteration.
  • Choose between reserving a request’s longest output and preempting on demand, and state the cost of each in blocks and in recomputation.
  • Explain why a prefix cache that copies saves prefill and not memory, and why its entries should be cut back to the shared blocks.
  • Establish a bounded cancellation result by identifying the finite schedule, enumerating each intervention, checking independent resource observers, and demonstrating in uncancelled controls that every claimed mechanism was exercised.
  • Explain why a fixed batch of interleaved requests can improve time-to-first-token without increasing model throughput, and why a copying cache can save prefill time while increasing memory use.
  • Identify which conditions must be added before a shared-prefix cache can safely serve mutually distrustful tenants.

Key terms

  • Iteration: one pass of the scheduler, advancing every running request by one token.
  • Admission: moving a request from waiting to running when a slot and its blocks are free.
  • Block: a fixed token-count unit of logical KV reservation in this engine; unlike a paged-attention block it does not denote an independently shared physical allocation.
  • Reservation: taking blocks for a request’s prompt and longest output at admission.
  • Preemption: releasing a running request’s cache and returning it to the queue to be recomputed.
  • Prefix entry: a copy of the cache of a prompt’s first whole blocks, kept for later requests.
  • Fork: a new sequence made from the first tokens of another, with its own memory.
  • Audit: a comparison of the engine’s books with its own state and with books kept from outside.
  • Exhaustive cancellation (bounded): cancelling each possible target request at each enumerated iteration in a specified finite scenario; it makes no claim about all concurrent schedules.
  • Conforming variant: a different policy that must pass every check.
  • Independent resource witness: a view of open sequences or allocated bytes maintained outside the component whose cleanup is being checked.
  • Mechanism coverage: evidence that a test control run actually performed the preemption, prefix hit or failure it claims to qualify.

Reader exercises

  1. Make the victim of preemption the request with the most remaining output, and say which workload it helps and which check, if any, notices.
  2. Add a scenario with a confirmed prefix hit and preemption in the same uncancelled control run; then enumerate cancellations across every request and iteration, reporting the new domain size and any allocator drift.
  3. Replace first come first served with shortest prompt first and measure the head-of-line workload again. What does the arrival-order check say?
  4. Make the prefix index share storage with reference counts in the numpy backend, and say what the books must now count.
  5. Enumerate pairs of request cancellations, both at the same iteration and at different iterations. Specify how duplicate orderings are excluded, calculate the domain size, and test whether independent cleanup still holds.
  6. Add chunked prefill so that a long prompt is prefilled over several iterations. Which of the twelve checks should change?
  7. Measure whether a request that hits the prefix cache can be told from one that misses by its first-token time, in the manner of Chapter 16.
  8. Find a leak that the audit and the tracking backend both miss.
  9. Inject an exception from the backend’s release method, not just from prefill or decode. Does every request receive exactly one terminal event, and does independent allocator accounting expose a retained cache?
  10. Repeat the prefix experiment with numerically sensitive greedy choices. Report exact token agreement, first divergence, and whether a performance comparison would still pass a predeclared quality gate.
  11. Design a tenant-scoped prefix-index key and a timing-side-channel test; explain why a matching token prefix is not, by itself, authorisation for cross-tenant reuse.

References

Evidence in this chapter

Claim Category
In a burst of 12 requests with a shared prompt, 8 running cut the median first-token time to 0.206 of the serial engine’s (0.198 to 0.211 over five paired trials) and the last request finished at 1.001 of the serial time; the median request finished later (ratio 1.226) Book result (one model, one machine)
The prefix cache reused 17,600 of 23,521 prompt tokens in five trials, cut the first-token ratio to 0.160 and the last finish to 0.976, at 424 MB peak against 405 Book result
Tokens equalled the serial engine’s for 60 of 60 requests without the cache and 59 of 60 with it in float16, and 24 of 24 in float32 Book result; small samples
A long request ahead of seven short ones: short first tokens at 0.063 of the serial time, short completions 0.792, the long request 2.26 times later Book result
In a cache too small for the admitted requests, preemption halved the first-token time against reservation, finished the median request later, and recomputed 2,239 tokens in 23 preemptions; tokens were identical for 50 of 50 requests Book result
In a bounded sweep of one target request at one iteration (4 target requests × 23 iterations × 4 flag configurations = 368 GPU runs), every run finished with no tracked open sequence, logical block, or CUDA allocated-byte growth relative to the post-warm-up baseline; 256 such CPU reference-model cases likewise passed Book result for enumerated scenarios, not formal proof of arbitrary concurrent cancellation or exception-safe release
The first cancellation experiment and the first prefix cache would have shown a pass and a zero hit rate while not exercising the mechanism Book result; the history of the experiments
All 24 author-written cache, fork and scheduler mutants were detected and failed their declared checks; 13 had additional failing checks; one deliberately conforming victim-policy variant passed Book result; limited to tested mutations, not an exhaustive fault-coverage claim
The first audit could not fail; the first matrix let 2 of 23 mutants survive Book result; the history of the suite
The engine’s own cost on fixed logits is 0.3 to 0.5 ms a token, within the noise of the serial engine’s Book result; spread reported
Iteration-level scheduling, the paged cache and prefix-reuse designs of Orca, PagedAttention, SGLang and vLLM Reported by the sources; not reproduced
A shared prefix is detectable by timing Established in Chapter 16 for that cache; NOT_RUN for this one
Batching in one backend call, throughput under load, other engines, chunked prefill, shared KV storage, both prefix reuse and preemption together in one GPU cancellation control run, cancellations arriving mid-iteration, and release failures NOT_RUN for this chapter milestone

Implementation status

  • Manuscript: content/books/inference/42-chapter.md
  • Runnable examples: examples/ch42/integration.py (original, unchanged), examples/ch42/sched_lab.py (the measurements), and in examples/inference_lab/: cache.py, scheduler.py, scenario_tests.py, mutants_sched.py, the cache and fork suites in contract_tests.py, fork in both backends, and ADRs 010 to 012
  • Tests: tests/test_ch42_integration.py (original), tests/test_ch42_scheduler_lab.py (29 tests: the block books and their suite and mutants, the prefix index, the batch engine’s interleaving, refusals, cancellation, errors, entry splitting, preemption, deadlines, audit and close, scenario reproducibility, the reference engine and a conforming variant passing, each engine mutant failing the checks declared for it, failure isolation, the tracking backend seeing a leak, the dependency rules and ADRs, and on a random two-layer Qwen3 the fork suite, the compactness of a fork and the batch engine’s agreement with the serial engine under every flag); tests/test_ch41_inference_lab.py was updated for the amended package
  • Evidence boundary: the current inference_lab code also contains features subsequently added by later capstone chapters, including optional batched decoding in BatchEngine. The Chapter 42 results file is the milestone authority for what was measured here; reviewing current implementation code does not retroactively turn that later functionality into a Chapter 42 experiment. The revised manuscript proposes engineering follow-ups, but no repository code, tests or measurements were changed by this editorial patch.