Designing the Inference Runtime
The capstone runtime specified before it is optimised: typed contracts, nine decision records tied to forty-seven checks, a dependency table enforced by reading the imports, and thirty-nine deliberately faulty adapters used to find out whether the checks can fail.
The first Inference Lab runtime milestone specifies five interface Protocols, six value types, nine architecture decision records (ADRs), and 47 named architectural checks: 42 behavioural contract checks, four dependency checks and one ADR-consistency check. I then challenged the behavioural suite with 39 deliberately faulty adapters. All 39 failed at least one check, and each failed every check identified for it in advance. The first version had not achieved that: it let one of 29 mutants survive, while eight of its 42 behavioural checks had no mutant capable of making them fail. The improved result measures detection of the faults we constructed, not correctness of all possible implementations.
A different experiment found the harder boundary. A faulty Hugging Face adapter released a sequence from its registry and reported zero live cache bytes but secretly retained the CUDA cache tensors. It passed all 14 backend checks. After 20 requests, the measured PyTorch CUDA allocation remained 272,957,440 bytes higher than for the honest adapter: exactly 20 retained caches of 119 tokens at 114,688 bytes per token. The independent allocator reading exposed a defect that an adapter’s own accounting could not.
That is the capstone’s starting argument: architecture is a set of falsifiable promises across boundaries, not a drawing of components. A testable promise needs a named check, a plausible defect that proves the check can fail, and an explicit account of blind spots. Here the missing independent memory oracle proved more informative than the headline 39/39 mutant score.
The question
Chapters 42–44 will add scheduling and cache management, more backends, and a comparison with established inference engines. Without contracts, each change could silently alter another subsystem’s semantics—whether releasing a sequence actually frees resources, whether sampling consumes another request’s randomness, or whether timing begins before the model sees a prompt. This chapter freezes a first set of interfaces and test obligations before pursuing optimisation. The practical questions are: what crosses each boundary; who owns mutable state; which failures become events; which invariants survive swapping implementations; and what independent evidence can catch an implementation that lies?
The milestone answers these questions at four levels. contracts.py defines Python Protocol interfaces and validated values, but type annotations alone do not enforce behaviour. contract_tests.py exercises the interfaces with named checks. ADR files map each design decision to checks that should fail when it is violated. Finally, mutation and dependency testing establish that the checks detect a specified fault catalogue. The outcome is an executable qualification harness, not a mathematical proof of runtime correctness.
Where this sits
This opens Part 8’s Inference Lab capstone. Chapter 40 established the need to freeze workloads, system configurations and the meaning of a benchmark result; Chapter 41 freezes the baseline runtime contracts those benchmarks will later exercise. Chapters 42–44 can then extend the package and must requalify the same boundaries rather than replacing the design with an unrelated demonstration. Results in this chapter refer to the recorded Chapter 41 milestone, not a claim that the entire capstone is already implemented.
The design incorporates earlier experiments rather than merely citing them. Chapter 30’s streaming result motivates a terminal outcome and cache release on all normal paths. Chapter 34’s protocol-marker injection motivates distinguishing trusted control tokens from untrusted text. Chapter 36’s latency work motivates monotonic clock injection and timestamp semantics. Chapter 39’s batch and seed experiments motivate separate notions of deterministic execution, batch invariance and per-request random streams. An ADR records each link; it does not turn the earlier experiment into a guarantee for this new runtime.
The deliverable is a reusable package under examples/inference_lab/, plus a set of acceptance artifacts: machine-readable test results, the mutation matrix, the dependency graph and the nine ADRs. The authoring discipline is simple: every important decision names a check capable of failing it. Because the reverse is also useful, every named check must have an ADR that explains why it exists.
Where the starter was wrong
The starter’s examples/ch41/contracts.py defines a one-method Backend and a ToyBackend that echoes a prompt with extra characters. Its validate_contract checks for the literal result of generate("hi", 2), a test that can succeed only for the toy’s convention rather than for every conforming backend. A Python Protocol can describe a callable signature, but neither its presence nor a successful toy example establishes cache consistency, release semantics, numerical equivalence or error handling. Two short strings labelled as decisions likewise provide no executable traceability.
The replacement milestone distinguishes three requirements. A behavioural invariant must admit multiple implementations and reject plausible faulty ones. An ADR must record the choice and name its checks, including consequences and limitations. And interchangeability must be tested: two algorithms can implement the same sampling distribution yet differ in seeded output and speed. The new package supplies evidence for these claims within its limited corpus. The original starter and its tests are preserved unchanged.
The design
An inference runtime needs boundaries for request state, tokenisation and protocol, execution and key-value state, sampling, lifecycle management, scheduling, telemetry and memory allocation. The separation here is a capstone design, not a universal mapping of other systems. vLLM’s documented V1 design groups the scheduler and KV-cache management in an engine-core process; PagedAttention introduces an explicit memory-management mechanism; SGLang separates a program-facing language from its serving runtime; the pinned DeepInfer documentation describes other execution concerns and some exclusions. These sources explain why the boundaries matter, but they do not validate this book’s precise Protocol signatures. The other systems were not executed as part of Chapter 41.
The following inventory describes the saved Chapter 41 baseline, not the state of the package after later capstone chapters have extended it. A backend’s privately owned DynamicCache is not yet the independent cache manager planned for Chapter 42.
| Subsystem | Chapter 41 contract or type | Chapter 41 implementation | Scope at this milestone |
|---|---|---|---|
| Request and outcome | Request, SamplingParams, TokenEvent, FinishEvent, FinishReason |
Frozen dataclasses | Validated values and tested lifecycle paths |
| Text boundary | Tokenizer, TokenizerIdentity |
ByteTokenizer, HFTokenizer |
Encoding and reserved-token checks, not prompt-injection immunity |
| Model execution | ModelBackend, BackendIdentity |
TinyBackend (NumPy), HFBackend (Qwen3-0.6B) |
Real-model adapter calls use one sequence at a time |
| Sampling | Sampler, RandomStream |
ReferenceSampler, InverseCdfSampler |
Common distribution contracts; seeded outputs may differ |
| Engine | Composition of the above interfaces | SerialEngine |
Serial request lifecycle, no cross-request scheduler |
| Clock/telemetry | Clock, timestamped events |
SystemClock, FakeClock in tests |
No aggregation or distributed tracing |
| Scheduler | Deferred | None in this milestone | Chapter 42 |
| Independent cache manager | Deferred | Each backend owns its own cache | Chapter 42 |
The baseline value types are frozen dataclasses with validation: requests need an ID and a prompt, temperature must be nonnegative, top_p must lie above zero and at most one, and the new-token limit must be positive. Freezing these values prevents ordinary reassignment, not mutation of arbitrary arrays held by adapters. Five structural Protocols describe the tokenizer, backend, random stream, sampler and clock. ContractViolation and its four baseline specialisations—InvalidToken, ContextOverflow, UnknownSequence, EmptyInput—identify deliberate contract refusals. Other exceptions can be implementation faults, but the engine may convert them to an error outcome. Structural typing alone does not enforce these postconditions.
The model/backend interface is small enough to inspect. This excerpt illustrates method shapes; the behavioural invariants reside in their documentation and executable checks rather than in the Protocol keyword:
class ModelBackend(Protocol):
identity: BackendIdentity
def new_sequence(self) -> int: ...
def prefill(self, seq: int, token_ids: Sequence[int]) -> np.ndarray: ... # logits of the last token, (vocab,)
def decode(self, seqs: Sequence[int], token_ids: Sequence[int]) -> np.ndarray: ... # (B, vocab)
def length(self, seq: int) -> int: ...
def release(self, seq: int) -> None: ...
def memory_in_use(self) -> int: ...
Logits cross as NumPy arrays so a float64 CPU reference and a CUDA model can satisfy the same shape and state contracts. That convenience forces expensive transfers in the current adapter, measured later. BackendIdentity specifies vocabulary, context, dtype, device and declared numerical promises. atol is a tolerance checked on defined paths, not a guarantee of maximum error for every possible input. deterministic means fixed conditions produced the same result in the tested repetitions; batch_invariant asks separately whether changing neighbours and computation shapes changes a request’s logits. The baseline HFBackend meets the latter promise by processing each sequence independently; it does not prove invariance of a multirow kernel.
The dependency table is enforced by scanning static Python imports. The Mermaid diagram below records the original Chapter 41 package graph generated from those imports, with ubiquitous edges to contracts suppressed for readability. It should be regenerated when later chapters add a scheduler, cache implementation or new adapters. Passing the scanner establishes agreement between the stated policy and visible imports, not the absence of dynamic loading or all other forms of coupling.
flowchart BT
subgraph L0["layer 0"]
contracts[contracts]
end
subgraph L1["layer 1"]
backends_hf[backends.hf]
backends_tiny[backends.tiny]
contract_tests[contract_tests]
engine[engine]
sampling[sampling]
tokenizers[tokenizers]
end
subgraph L2["layer 2"]
mutants[mutants]
runtime[runtime]
end
mutants --> backends_tiny
mutants --> engine
mutants --> sampling
mutants --> tokenizers
runtime --> backends_hf
runtime --> backends_tiny
runtime --> engine
runtime --> sampling
runtime --> tokenizers
Layer 1 components depend on contracts rather than importing one another’s concrete implementations. SerialEngine receives its backend, sampler, random-stream factory and clock from outside, while the composition root (runtime.py) wires the actual classes. An AST-based checker enforces allowed edges, rejects unapproved third-party imports and cycles, and checks that heavyweight frameworks are imported lazily in permitted modules. This makes accidental dependency drift visible. It does not test whether a collaborator passed through a constructor behaves correctly or whether a dynamic import occurs at runtime.
The decisions
Each of nine ADR files in examples/inference_lab/adr/ records a status, context, decision, consequences, evidence and Enforced by: names. The ADR check rejects missing sections and references to nonexistent tests, and the reverse mapping rejects checks that no decision names. The count of 47 named checks consists of 42 behavioural contract checks, four dependency checks and one ADR-consistency check. Bidirectional naming is a useful maintenance property, not an independent proof that every listed test enforces its decision. The mutation campaign tests some of those claimed connections empirically.
| ADR | Chapter 41 decision | Evidence or limitation |
|---|---|---|
| 001 | NumPy CPU reference, delayed heavy-framework imports | Portable tests without a GPU |
| 002 | Frozen values, structural Protocols plus behavioural checks | Corrects the starter’s toy-only assertion |
| 003 | Per-request random streams and fixed draw count per sampler/token | Chapter 39; same seed does not imply same output across algorithms |
| 004 | Untrusted text must not produce reserved control IDs | Chapter 34; not a complete prompt-injection defence |
| 005 | One terminal outcome and sequence release | Chapter 30; cleanup failures and abandoned generators require qualification |
| 006 | Injected monotonic nanosecond clock | Chapter 36; cannot preempt a blocking model operation |
| 007 | Explicit numerical promises checked against reference paths | Chapter 39; atol supported by finite calibration data |
| 008 | Imports must match one declared dependency policy | Static source analysis and dependency mutants |
| 009 | Deferred work and non-goals are named | Chapters 42–44, as planned |
The lifecycle and random-stream decisions deserve closer attention because both have tempting statements that are stronger than their actual tests.
ADR-005 — request lifecycle. SerialEngine.stream() opens a backend sequence, prefills the prompt, checks cancellation and deadlines between model operations, samples tokens and normally yields a final FinishEvent with one of five reasons: stop, length, cancelled, timeout or error. Its finally block releases the sequence for tested completions, cancellations, backend failures and explicitly closed generators. The absolute claim that a finish event is delivered “whatever happened” is too strong: a consumer that closes an abandoned generator receives no terminal event, an unclosed generator may retain resources, and an exception raised by backend.release() in finally can suppress the finish event and mask an earlier failure. Deadlines are cooperative and do not interrupt a blocked prefill or decode. These are specified gaps and priority mutants for the next revision, not fixes already applied.
ADR-003 — stream ownership. Each request’s random generator is seeded from that request alone. Within one sampler, consuming a fixed number of random draws for every chosen token prevents filtering branches from unpredictably advancing the same request’s stream. The reference Gumbel-max sampler consumes a vocabulary-sized vector; inverse-CDF sampling uses one uniform. Both satisfy the eight sampler checks and approximated the intended probability distribution in the recorded finite-draw test, but they do not promise identical tokens for the same seed. A reproducibility manifest must therefore record seed, sampler identity/version, token sequence and numerical execution regime. Stream isolation also does not remove shape-dependent logit differences when a future backend batches requests.
The checks
A check is a named function that takes an adapter and returns passed, diagnostic text and sometimes a number. It requires observable behaviour rather than inheritance from a reference class. Adapter exceptions are captured as failed checks so that one broken method does not abort all diagnostics. That robustness should not be confused with the engine’s own failure handling. The test harness must also own or copy its fixtures: the first mutant campaign found that a sampler mutating an input array in place could corrupt an expected value before the check used it.
The recorded Chapter 41 suite defines 42 behavioural checks: 14 backend checks, eight sampler checks, five tokenizer checks and 15 engine checks. The backend checks are identity_complete, prefill_shape, decode_shape, append_equals_whole, prefix_consistency, batch_independence, neighbours_untouched, repeatable, release_frees_memory, invalid_token, empty_input, context_limit, unknown_sequence and arguments_unmodified. The name of a check denotes an obligation under its scripted test conditions, not a guarantee for all possible prompts, failures, devices or sequence lengths.
Prefix consistency compares incremental cached logits with fresh full-prefix logits and accepts differences only inside the backend’s declared atol. It can reveal corrupt caches or wrong positions within the tested sequences. Neighbours untouched interleaves a second sequence and checks bitwise equality for a backend that claims invariance; the original Hugging Face adapter makes separate one-row calls, avoiding true cross-row batching. Release frees memory compares the backend’s memory_in_use() before and after release, as well as the validity of the released handle. It cannot discover a hidden allocation that the backend has stopped counting. That requires an oracle independent of the adapter, as the leak experiment demonstrates.
The 15 engine checks cover terminal event order and reasons, context boundaries, backend failures during prefill and after decode steps, cancellation, timeout decisions, explicit stream closure, seeded output, interleaving, manual-loop parity, tracing and self-reported memory returning to baseline. FakeClock advances by 0.1 seconds per read, allowing deterministic deadline tests without sleeping. It does not measure actual elapsed GPU time or prove a deadline is honoured while a device call blocks. A deliberate release()-raises mutant and tests for a consumer that neither drains nor explicitly closes the generator remain missing from this milestone.
Running them on a real model
The same suite was run against the reference NumPy backend and, through HFBackend, against Qwen3-0.6B in three configurations. For the saved experiment, every Hugging Face sequence owned its own DynamicCache and was evaluated alone, which explains why the adapter could state batch_invariant=True without exercising a genuinely multirow kernel. The adapter used a 512-token context limit to keep the boundary tests affordable. The saved table is a functional compatibility check, not a latency or serving-capacity benchmark and not a measurement of the later batched-backend work.
| Qwen3-0.6B | Named checks: backend / engine / tokenizer | Passed | Backend / engine suite seconds | Maximum absolute logit difference: append / prefix | Declared atol |
|---|---|---|---|---|---|
| GPU fp16 | 14 / 15 / 5 | 34/34 | 3.3 / 8.1 | 0.0322 / 0.0273 | 0.25 |
| GPU fp32 | 14 / 15 / 5 | 34/34 | 3.0 / 7.0 | 2.0e-5 / 1.8e-5 | 2e-3 |
| CPU fp32 | 14 / 15 / 5 | 34/34 | 17.6 / 29.9 | 2.6e-5 / 1.8e-5 | 2e-3 |
The differences are maxima over these particular tests; they are not bounds for every possible input. Suite seconds are not client-facing inference latencies.
The tested neighbour and batch-independence cases gave equal logits in all three environments, consistent with one-sequence-at-a-time execution. The HFTokenizer escaped 318 constructed strings containing fragments or occurrences of reserved markers without producing any of the 26 reserved control IDs. Its identity reported 151,669 tokenizer entries, while the backend returned 151,936 logits: tokenizer cardinality and model output dimension must be handled as separate facts. Greedy token sequences matched model.generate() for 20/20 prompts in each GPU dtype over 32 output tokens. A subtle limitation in the saved results is that the suite identities record eos_ids=[]; real Qwen end-token handling is therefore not independently validated by those particular model runs, even though other stop cases were tested.
The conclusion is deliberately narrow: on the tested machine, model revision, dtypes and short-context cases, the adapter fulfilled the sampled contractual obligations. This is not a proof that the obligations are complete, that every prompt is handled safely, or that actual device memory is released when the adapter says it is. The next tests must include observations the adapter cannot control.
Where the tolerance comes from
BackendIdentity.atol began as an engineering threshold: 0.25 for fp16, informed by Chapter 39’s shape experiments, and 2e-3 for fp32. The repository tested these choices first on a calibration corpus and then on held-out prompts generated with another seed. Prompts were order summaries of 63–93 tokens; for each one, 16 greedy continuation steps compared cached incremental logits with full-prefix forward passes and split-prefill with whole-prefill. There were 24 calibration and 24 held-out prompts per GPU setting and eight of each on CPU. This is a finite, version-specific tolerance qualification, not an exhaustive upper bound on future discrepancies.
| Setting and calibration + held-out prompts | Calibration max: incremental / append | Held-out max: incremental / append | Default atol |
Held-out maximum / default | Held-out maximum / calibration maximum |
|---|---|---|---|---|---|
| GPU fp16, 24 + 24 | 0.113 / 0.078 | 0.206 / 0.109 | 0.25 | 0.82 | 1.82 |
| GPU fp32, 24 + 24 | 1.9e-4 / 1.0e-4 | 1.3e-4 / 1.0e-4 | 2e-3 | 0.06 | 0.66 |
| CPU fp32, 8 + 8 | 8.5e-5 / 5.1e-5 | 1.9e-4 / 4.2e-5 | 2e-3 | 0.10 | 2.2 |
A maximum over 16 continuation steps and a few dozen prompts should not be interpreted as a universal numerical guarantee.
Every tested prefix agreed on its top-1 token despite nonzero logit differences. That is decision agreement on these samples, not proof that the logit error is too small to flip any greedy choice: the relevant quantity is the top-two margin, not merely the scale of the largest logit (about 36). The existing atol passed all checked cases. A proposed rule of twice the largest calibration error, rounded up, produced candidates of 0.3, 4e-4 and 2e-4; the last was almost exhausted by the CPU held-out result of 1.9e-4. Indeed the CPU held-out maximum was 2.2 times its calibration maximum and the fp16 maximum 1.82 times. The practical requirement is to record calibration scope and investigate a future violation, not to raise the tolerance silently until new results pass.
Testing the tests
A passing implementation is only evidence that a suite can accept something; it does not show what errors it can detect. The experiment therefore creates faulty adapters with specific violated obligations, records which checks each is expected to fail, runs the full suites and compares expected with observed failures. These are manually authored faults rather than an exhaustive program-wide mutation process. The purpose is to examine whether the tests themselves are falsifiable, especially when the adapter and checker share mutable input or self-reported measurements.
class LeakyRelease(TinyBackend):
"""Release forgets the sequence but not the bytes."""
...
Mutant("leaky_release", "backend", "release forgets the sequence but not its bytes",
("backend.release_frees_memory",), _b(LeakyRelease))
The saved fault catalogue has 39 mutants: 16 backends, eight samplers, six tokenizers and nine engines. Faults include cache mixing between sequences, release that leaves handles usable, silently accepted invalid IDs, truncated contexts, wrong tensor shapes, mutated caller inputs, imperfect top-p support, shared random streams, unescaped control markers, skipped deadlines and backend errors that escape the request lifecycle. Some deliberately violate strict numerical promises, others violate state or safety boundaries. The result evaluates this selected catalogue—not every possible defect a production inference engine might encounter.
| Fault family | Hand-built mutants | Rejected by at least one check | Failed every declared check |
|---|---|---|---|
| Backend | 16 | 16 | 16 |
| Sampler | 8 | 8 | 8 |
| Tokenizer | 6 | 6 | 6 |
| Engine | 9 | 9 | 9 |
| Total | 39 | 39 | 39 |
The counts establish the mutation suite’s response to these 39 constructions. They do not measure the probability of detecting an unseen defect.
Ten mutants also failed checks beyond those anticipated, producing 63 failed mutant–check pairs in the matrix. This is diagnostic information rather than 63 independent fault detections. A mutant that sorted the caller’s list in place contaminated fixtures reused by multiple checks; a decoder returning a vector instead of a batch matrix caused several downstream checks to fail after the shape contract had already broken. Distinguish the first violated obligation from failures cascading through malformed state or test fixtures.
The test suite changed in response to its own failures. Its first 29 mutants yielded 28 kills: a sampler altered an input logits array in place, and a checker compared against the same array after the modification. Supplying independent copies exposed the fault. Eight of 42 checks initially had no mutant that triggered them, so ten more mutants were added and three checks strengthened. Top-k/top-p checks had admitted some incorrectly narrowed supports; decode_shape had neglected a batch-of-one case. At the end every check had failed at least one mutant. This is an instructive example of iterative test design, but the updated score comes from a suite improved with knowledge of the mutants. A blind held-out catalogue is still needed to estimate generalisation.
The number 39/39 is not “100% safe”. Mutation-testing research supports using artificial faults to expose weak tests, while also warning that fault choice, redundancy, coverage and realism matter. The chapter’s result supports only the statement that these named checks detected the named faulty adapters. The hidden GPU-cache leak below is a concrete surviving fault outside the original behavioural oracle.
A fault the checks cannot see
Three deliberately faulty Hugging Face adapters clarify the failure boundary. A release that still reported memory failed backend.release_frees_memory. A decoder that ignored its existing cache failed prefix_consistency and several dependent shape/context checks. But HFHiddenLeak deleted its cache from the active-handle registry while retaining the actual object elsewhere, and then reported zero bytes in use. It passed all 14 backend checks because those checks relied on the adapter’s own account. The problem is not an absent Protocol annotation; it is the lack of an independently measured resource invariant.
An external GPU allocator observation made the third defect visible. Qwen3-0.6B at fp16 uses 28 layers × 2 (keys and values) × 8 KV heads × 128 elements × 2 bytes = 114,688 cache bytes per stored token. The honest adapter’s reported logical cache matched the arithmetic for 64, 256 and 511 tokens: 7,340,032, 29,360,128 and 58,605,568 bytes. After 20 requests, the honest adapter left PyTorch’s live CUDA allocation at baseline; the faulty one reported zero while its CUDA allocation remained 272,957,440 bytes higher. That equals 20 retained 119-token caches. The missing 120th token per request is the final generated token that was never decoded back into cache. This result establishes the leak in that controlled construction; PyTorch allocated bytes are not a complete measure of all process or device memory.
Independent measurements also exposed allocator effects not explained by logical KV arithmetic. The first 64-token cache increased live allocated bytes by 15,859,712, of which 8,519,680 remained after release, even though the analytic cache was 7,340,032 bytes; later tested sequences returned to their baselines. Peak allocation during prefill was about 1.78–2.77 times the live KV size. The experiment did not identify the one-time extra allocations or all temporary tensors. Chapter 42 should maintain separate accounts for logical cache, framework allocation and peak device pressure, and use independent tests after success, cancellation, timeout and backend error. A cache manager that relies on memory_in_use() alone could make a memory-admission decision on incomplete evidence.
The dependency rules
ADR-008 gives the layering a mechanical check. In the Chapter 41 source snapshot layers.DECLARED lists the allowed module edges and layers.EXTERNAL the approved third-party imports. Heavy torch and transformers imports are permitted only inside Hugging Face adapter functions, so loading reference contracts need not import a GPU framework. The AST scanner checks relative and absolute static imports, import cycles, missing or stale declarations, disallowed packages and eager heavy imports. Passing this checker means the source agrees with its static dependency policy; it does not guarantee the absence of dynamic imports, runtime reflection, or misuse of an injected dependency. Recheck and regenerate the graph when later chapters add scheduler and cache modules.
The checker accepts source text, so nine deliberately faulty dependency variants can be examined without changing tracked files. As with behavioural mutation testing, the result measures exactly the violations the author constructed. It is a controlled architectural regression test, not a complete dynamic-dependency monitor.
| Deliberate dependency violation | Required failure |
|---|---|
| Engine imports Hugging Face adapter directly | matches_declaration |
contracts imports engine |
matches_declaration, no_cycles |
| Backend imports tokeniser implementation | matches_declaration |
Bottom layer imports torch |
third_party_allowlist, heavy_imports_lazy |
Hugging Face adapter imports torch at module import time |
heavy_imports_lazy |
Engine imports undeclared requests |
third_party_allowlist |
| New module lacks a declaration | matches_declaration |
| Two siblings import one another despite their allowed edges | no_cycles |
| Declaration allows an import the code no longer makes | matches_declaration |
These are violations of stated source architecture, not simulated runtime security exploits.
All nine deliberately invalid source variants were rejected by the checks designated for them, and the Chapter 41 package initially passed the policy. The exactness rule has a maintenance cost: deleting the final use of an import means updating its allowed-edge entry too. The benefit is a table that describes the current code rather than the design the author once intended. Nonetheless, a syntactically clean graph could faithfully encode the wrong architecture; the decisions themselves still require review.
The cost of the boundary
The portable numerical boundary has a measurable price. The GPU adapter copies logits to float32 NumPy; the CPU sampler can convert a 151,936-entry vector to float64 and produce random draws. The experiment measured ten 63–93-token prompts, five repetitions and 32 output tokens each, randomising variant order inside each prompt/repetition. Time is whole-request wall time divided by output tokens and therefore includes prefill and the measurement environment; it is not isolated steady-state decode latency, a production serving benchmark or an independent statistical sample of ten GPUs.
| Variant | Median ms/output token over prompts | Paired extra over raw: median (range), ms | Median ratio to raw (range) |
|---|---|---|---|
| Library loop, argmax on GPU | 34.85 | 0 | 1 |
| Backend adapter: logits to NumPy, argmax in NumPy | 36.29 | +1.04 (−0.22 to +2.87) | 1.030 (0.995–1.085) |
| Serial engine, greedy | 35.78 | +0.94 (−0.64 to +3.49) | 1.027 (0.984–1.103) |
| Serial engine, reference sampler, T = 0.8 | 41.01 | +6.45 (+0.95 to +7.09) | 1.184 (1.023–1.211) |
| Serial engine, inverse-CDF sampler, T = 0.8 | 38.01 | +2.88 (+0.60 to +4.70) | 1.082 (1.015–1.135) |
The median of per-prompt differences is not generally the difference of the two separately reported medians.
An earlier run of the same benchmark, before inverse-CDF sampling was added, measured +0.97, +0.56 and +5.06 ms/token for the adapter loop, greedy engine and reference-sampled engine. The later run recorded +1.04, +0.94 and +6.45. Thus the two observed median overheads for the greedy engine were roughly 0.6–0.9 ms/token. Individual prompt-level differences even went negative, reflecting noise at this scale, rather than a faster algorithm proved by negative overhead. The sample is too small to treat the third decimal or the ranking of similar greedy variants as stable. The larger sampled overhead is more visible, but it partly reflects a different sampler, not merely an interface dispatch cost.
The component microbenchmarks provide context, but they should not simply be summed to reconstruct the end-to-end timings: allocation, transfer, synchronisation and measurement paths differ. These are median times from 300 repetitions at vocabulary size 151,936.
| Microbenchmarked operation | Median microseconds |
|---|---|
Device argmax and .item() |
36 |
| Copy full logits vector to float32 NumPy | 152 |
| Convert to float64 and argmax in NumPy | 296 |
| Engine loop with constant-logit backend, greedy | 335 per token |
| Gumbel-max reference sampler, T = 0.8 | 3,917 |
| Same sampler, top-k 50 | 4,530 |
| Same sampler, top-p 0.9 | 17,020 |
| Generate 151,936 uniforms | 693 |
| Inverse-CDF sampler, T = 0.8 | 2,087 |
| Same sampler, top-k 50 | 12,885 |
| Same sampler, top-p 0.9 | 13,528 |
At the tested scale, the greedy NumPy boundary costs around one millisecond per output token in the later end-to-end comparison. Sampling dominates more of the overhead: Gumbel-max consumes one uniform per vocabulary entry and the inverse-CDF algorithm consumes one, but its filtered paths may sort the whole vocabulary. The unfiltered inverse-CDF result was faster locally; its top-k path was slower (12.9 ms against 4.5 ms). Both samplers passed the eight behavioural checks, and their empirical distributions were close in the recorded 40,000-draw comparisons; this is finite-sample evidence, not a mathematical proof of exact distributional identity. The runtime contract intentionally does not choose a fastest sampler. A production choice needs matched correctness, numerical, seeded-output and loaded-throughput qualifications using Chapter 40’s benchmark discipline.
What is not here
Scope is recorded as data, not only as caveat prose. contracts.DEFERRED and contracts.NON_GOALS are reconciled with ADR-009 by tests. These lists describe what the Chapter 41 milestone promised; later capstone development should update their status and evidence rather than leave a historical “deferred” claim in place indefinitely.
Deferred at this milestone: a scheduler with admission, cross-request batching, fairness and preemption and an independent cache manager with block allocation, prefix reuse and eviction (Chapter 42); genuinely batched and additional-family backends (Chapter 43); and comparisons against established engines using the frozen Chapter 40 suite (Chapter 44). Outside the capstone’s declared scope: network serving, training, distributed inference, custom kernels, speculative decoding, multimodal and mixture-of-experts execution, and the tool-use and structured-output orchestration of Chapters 34–35. These distinctions prevent a serial research harness from being presented as a production-ready service.
A useful non-goal prevents an accidental inference. Matching 20 short greedy outputs does not prove safety of network clients, batching, distribution, or tools. Passing memory-release checks does not guarantee the physical GPU memory is free. The serial milestone establishes only a first qualifying set of boundaries: request ownership, sequence-state transitions, sampler-stream separation, event semantics and empirical numerical tolerances.
What the numbers do not show
- Mutation coverage is limited by the catalogue. The 39 faults were chosen after the suite existed. They show that the revised checks detect those faults, not that unknown defects cannot escape. A blinded mutant set would test generalisation.
- The memory oracle was initially self-reported. A hidden CUDA cache survived release while the backend reported zero. PyTorch live allocated bytes caught that construction but may not capture every allocation category, retention mechanism or CPU equivalent.
- Terminal-event and cleanup claims need qualification. Explicit generator closure releases state but cannot deliver a finish event; a consumer that neither drains nor closes may retain resources; a
release()exception can interrupt finalisation; and a timeout check cannot stop a blocked kernel. - Control-token tests are not prompt-injection resistance. Escaping 318 marker-bearing strings prevented reserved control IDs in these cases, but inserted zero-width characters alter the text, and untrusted content can still influence instructions.
- Numerical tolerances are empirical. The fp16 held-out maximum was 1.82 times the calibration maximum, on short prompts from one generator, one machine and one model.
- Baseline batch invariance did not exercise batching. Each Hugging Face sequence was executed separately. Cross-row and shape-invariant execution require new tests.
- Overhead is locally measured. Ten prompts on one shared GPU do not establish concurrent throughput, p99 TTFT or power. Small negative paired differences are measurement noise.
- Import-policy checks are syntactic. AST scanning cannot prove that runtime reflection or dynamically imported modules obey the intended architecture.
- External serving systems were not executed. The vLLM, SGLang and DeepInfer information is documentation context rather than capstone measurements.
Inference Lab increment
This milestone adds the reusable examples/inference_lab/ package and the experiment artifacts that qualify its initial serial implementation. Later chapters are expected to extend this package, but any modification must be accompanied by a review of the original contracts and recorded test assumptions. The result of Chapter 41 is an executable architectural baseline, not a completed, load-tested inference server.
contracts.py contains the baseline SamplingParams, Request, FinishReason, TokenEvent, FinishEvent, BackendIdentity, TokenizerIdentity, the Tokenizer, ModelBackend, RandomStream, Sampler and Clock Protocols, contract errors, and scope declarations. sampling.py provides PerRequestStream, ReferenceSampler and InverseCdfSampler; tokenizers.py provides ByteTokenizer; backends/tiny.py and backends/hf.py supply the NumPy and tested Qwen3 adapters; engine.py provides SerialEngine and SystemClock; runtime.py assembles the components. The repository may add types in later capstone milestones, so this list is tied to the recorded Chapter 41 baseline.
contract_tests.py defines four reusable suites and the 42 named behavioural checks. mutants.py and matrix.py contain the fault catalogue and expected-versus-observed failure matrix. layers.py contains the dependency policy, scanner and graph emitter, while adr.py checks the nine ADR records. examples/ch41/runtime_lab.py measures static checks, real-model adapter compliance, calibration, token parity, sampling overhead and independent CUDA memory. Preserve the saved raw measurements when repeating this work; a regenerated report without its original environment should not silently replace the earlier evidence.
From the repository root, the following commands run the focused tests, reproduce CPU-only static artifacts and rebuild the saved report. The commands shown are not a complete rerun of the GPU experiments:
python -m pytest tests/test_ch41_inference_lab.py -q
python examples/ch41/runtime_lab.py static --out research/ch41/measurements/static.json
python research/ch41/build_results.py
The GPU experiment commands suite, calibrate, parity, overhead and memory accept explicit --dtype and --device and require the Qwen model cached locally. For a new run, record model/tokenizer commit, CPU/GPU, driver, torch/transformers versions, prompt generator seeds and the choice of sampler. A new environment should produce a new evidence record rather than overwrite the provenance of the original measurements.
The engineering rule is: make every architecture promise falsifiable, test the test with an intentionally faulty adapter, and require independent evidence when the adapter reports on itself. Map ADRs to checks in both directions; isolate test fixtures; measure real device allocation beside logical KV bytes; state the limits of numerical tolerance and exactly-once event claims; and rerun the baseline qualification when scheduling, caching and multirow backends enter the system.
What you should now be able to do
- Distinguish a Python
Protocolsignature from an executable behavioural contract and a test that can falsify it. - Trace ADRs to named checks and detect a decision without a check or a check without a reason.
- Build intentionally wrong adapters with declared expected failures and report both survivors and cascading failures.
- Explain why the first mutation campaign missed an in-place sampler mutation and how independent fixtures fixed it.
- Derive KV bytes per token and independently diagnose a leak hidden from
memory_in_use(). - Calibrate an
atolagainst a held-out set and explain why the largest observed discrepancy is not a universal bound. - Identify the limitations of serial-generator finalisation, deadline checks, token-marker escaping and single-row batch-invariance claims.
- Compare the local cost of copying logits and sampling on CPU without confusing a microbenchmark with loaded-serving capacity.
Key terms
- Contract: an interface plus observable preconditions, postconditions and state invariants; a type signature is only part of it.
- Contract check: a stable named test that accepts any implementation and returns an observable result.
- Architecture decision record (ADR): a decision with context, status, consequences, evidence and intended enforcing checks.
- Bidirectional traceability: ADRs name checks and checks belong to ADRs; traceability alone does not establish adequacy.
- Mutant / survivor: a deliberately faulty implementation, or one that the suite does not reject.
- Mutation score: detected faults divided by faults in a specified catalogue, not a population-wide detection probability.
- Independent oracle: an observation not controlled by the component being checked, such as CUDA allocator readings beside a backend’s self-reported memory.
- Dependency policy: the allowed static import graph, enforced by scanning the source.
- Composition root: the module that supplies concrete implementations to abstract collaborators.
- Per-request stream: independent random-generator state, whose seed does not fully specify output without the algorithm and numerical regime.
- Numerical qualification: a declared dtype/device/computation path and tolerances tested on a stated corpus.
- Lifecycle finalisation: rules for emitting a terminal outcome and freeing state, including exceptions when the generator is closed or cleanup raises.
Reader exercises
- Implement a third sampler using a partition-based top-k path. Compare the eight contract checks, distributions and timing to both existing samplers.
- Add a leak mutant that retains a cache only when decoding fails; report whether self-reported and independent allocator checks detect it.
- Build a backend whose
release()raises. Determine whetherSerialEngine.stream()can still emit the prescribedFinishEvent; define and test a cleanup-failure policy. - Ask another engineer or agent to write ten faulty adapters without reading the checks. Report blind survivors separately from the original 39/39 score.
- Recalibrate numerical tolerance on long-context and non-order prompts, preserving the existing threshold while diagnosing any violation.
- Exercise reserved-token escaping under another tokenizer and Unicode normalisation; separate control-token integrity from instruction-following safety.
- Introduce a forbidden dynamic import and establish what the AST checker can and cannot detect.
- Compare logical KV bytes, PyTorch live-allocated bytes, reserved bytes and peak memory through successful, cancelled and failed requests.
- Test a consumer that stops iterating without explicitly closing the generator. Define the caller’s responsibility for deterministic cleanup.
- Repeat Chapter 40’s quality-gated benchmark on the later batched backend before comparing throughput figures.
References
- Efficient Memory Management for Large Language Model Serving with PagedAttention — Kwon et al., SOSP 2023. Research context for independent KV-cache management; its serving gains were not reproduced here.
- SGLang: Efficient Execution of Structured Language Model Programs — Zheng et al.; architecture and cache-reuse context, not a local experiment.
- DeepInfer at commit
774ce244— first-party runtime documentation; no execution or independent verification of claimed performance. - vLLM Architecture Overview — official, version-sensitive documentation; provides architectural comparison, not tests of this capstone.
- Applying ‘Design by Contract’ — Bertrand Meyer, IEEE Computer, 1992. Conceptual foundation for behavioural invariants beyond signature compatibility.
- Are Mutants a Valid Substitute for Real Faults in Software Testing? — Just et al., FSE 2014. Empirical relationship, with important qualifications, between mutation testing and real-fault detection.
- QuickCheck: A Lightweight Tool for Random Testing of Haskell Programs — Claessen and Hughes, ICFP 2000. Property-based generation as a complementary technique for challenging contracts; QuickCheck was not used in this chapter.
- Qwen3-0.6B — Apache-2.0; model revision
c1899de289a04d12100db370d81485cdf75e47caused in the tests.
Evidence in this chapter
| Claim | Evidence category and precise scope |
|---|---|
| The Chapter 41 milestone records 42 behavioural checks, four dependency checks and one ADR check, traced to nine ADRs | Recorded local tests and ADR validator, not 47 proofs |
| 39/39 author-designed faulty adapters were rejected; all declared failures occurred; every behavioural check was exercised by a mutant | Local mutation matrix, catalogue selected and suite revised by the author |
| The initial matrix rejected 28/29 and left eight checks untouched | Local development history, evidence of a discovered testing gap |
| Qwen3-0.6B fp16 GPU, fp32 GPU and fp32 CPU adapters passed 34 backend/engine/tokenizer checks | Local tests, one machine, short contexts; saved suite identities had eos_ids=[] |
| Greedy engine output matched library generation on 20/20 tested prompts in each GPU precision | Local parity test, 32 generated tokens per prompt |
| Tolerance passed the recorded calibration and held-out prompt sets | Local empirical qualification; held-out maxima 1.82, 0.66 and 2.2 times calibration maxima |
| A concealed KV cache passed 14/14 self-reported backend checks but left 272,957,440 more live CUDA-allocated bytes after 20 requests | Independent allocator observation for this constructed leak |
| KV cache uses 114,688 logical bytes per stored token for this model in fp16 | Model architecture arithmetic plus tensor-byte checks |
| Greedy boundary overhead was around 0.6–0.9 ms/token by two run medians; CPU sampling was costlier than greed | Local 10-prompt timing experiment, no loaded serving |
| Different sampling implementations can pass common checks and consume different seeded streams | Behavioural tests and sampling theory, not token identity across algorithms |
| vLLM, SGLang, DeepInfer architecture and PagedAttention design | External documentation/research, not executed locally |
| Contract, mutation and property-based testing theory | Published methodological research, added for context |
| Independent cache manager, scheduler, concurrent batches, cleanup-failure semantics, external-engine benchmarks and production admission | NOT_RUN or not established by Chapter 41 evidence |
Implementation status
- Manuscript:
content/books/inference/41-chapter.md(Chapter 41 historical milestone, not an assertion about the current state of later capstone revisions). - Baseline starter:
examples/ch41/contracts.pyandtests/test_ch41_contracts.py(original examples, unchanged in this work). - Capstone package:
examples/inference_lab/(contract types, samplers, tokenizers, NumPy and Hugging Face backends, serial engine, composition root, ADRs, checker and mutant matrix). - Experiment driver:
examples/ch41/runtime_lab.py(CPU static checks and optional local model suite, calibration, parity, timing and allocator measurements). - Saved milestone tests:
tests/test_ch41_inference_lab.py(42 Python tests at the recorded milestone). This count is distinct from the 42 named behavioural contract checks exercised within the suite. - Evidence:
research/ch41/sources.md,research/ch41/results.json,research/ch41/measurements/,research/ch41/build_results.py, andresearch/evidence-register.md. - Focused verification:
python -m pytest tests/test_ch41_inference_lab.py -q. Rebuild report:python research/ch41/build_results.py. Whole-repository tests:python -m unittest discover -s tests -v.
Publication caveat: the saved Chapter 41 runs did not establish an independent memory oracle inside the generic backend suite; they did not cover cleanup operations that raise, universally safe token handling, a genuinely batched Hugging Face backend or scheduler performance. The draft = false frontmatter setting makes the page publishable, not scientifically final.