← Inference From First Principles

Adding Multiple Model Backends

A batched-decode capability, a second level of backend for engines that own sampling, and a conformance matrix that says pass, fail or skip-with-a-reason: what the same scheduler does with a backend that decodes sixteen sequences in one call, and what a backend that cannot run looks like.

Sixteen requests arrived together on Qwen3-0.6B. With Implementing Scheduling and Caching’s scheduler advancing each sequence by a separate decode call, the measured median throughput across three trials was 22.5 output tokens/s; with the same scheduler and an adapter executing a whole decode batch in one model forward pass, it was 131.7 tokens/s. The median of the three within-trial throughput ratios was 5.42 (observed range 5.40–6.26). At sixteen concurrent sequences, median request completion fell from 22.78 to 3.88 seconds. These are measurements of a 16-request burst with 32 output tokens per request, not steady-state server throughput under arrivals. The change also increased median peak incremental CUDA allocation from 204 to 458 MB. Batched float16 output disagreed with the serial reference for 4 of 144 requests across the 4-, 8- and 16-running configurations; in float32, all 144 agreed. The result is a speed–memory–numerical-agreement trade-off, not a free acceleration.

The other result is a conformance matrix that records PASS, FAIL and SKIP with the reason. In the measured Windows environment, vllm 0.30.0 was installed but import vllm failed because vllm._C_stable_libtorch was missing; SGLang was not installed; OpenAI and Anthropic providers were deliberately not contacted. None of those outcomes measures the performance or correctness of those systems. The request-level test deliberately applied to the unadapted-library wrapper, RawHFGenerate, failed stop-token and invalid-request behaviour: this is a mismatch with our event contract, not a finding that Hugging Face’s documented generation API is defective. The adapted wrapper passed all nine applicable checks on the tested CPU configuration.

Both findings follow from one design rule: the word backend must not hide ownership. A logits-level adapter exposes individual forward passes and cache state; a generation-level system owns sampling, its execution loop and often scheduling. They need different contracts, explicit capability declarations and a matrix that distinguishes what was tested from what was never attempted. Performance, token agreement and contract compatibility must be reported independently.

The question

Designing the Inference Runtime specified a logits-and-cache interface and a serial engine; Implementing Scheduling and Caching added scheduling without true cross-sequence GPU batching. Now the capstone has to answer four linked questions. What must one batched decode call guarantee about ordering, state and failure atomicity? How can that call be inserted into the scheduler without changing the per-request lifecycle? How do we compare systems that expose only whole-request generation, not logits? And how do we record an unavailable capability without treating a skip as a pass? The experiment also asks what batching buys on the recorded workload and what it costs in GPU allocation and output identity.

The chapter’s acceptance gate is cross-backend conformance with explicit skip reasons. The measured throughput gain demonstrates why a batched backend matters; the tests and their deliberately faulty implementations show what that gain is allowed to change. A performance result alone does not certify that a new backend preserves the runtime’s contracts.

Where this sits

Correctness, Determinism and Reproducibility showed that changes in batch shape can change floating-point results and occasionally generated tokens. Designing the Inference Runtime therefore gave backends explicit numerical claims (atol, batch_invariant, deterministic), and Implementing Scheduling and Caching made independent requests share a scheduler. Here those decisions meet. A batched adapter must not claim bitwise batch invariance merely because its results are close to single-row decoding; its numerical promises have to be checked at the shapes it actually uses. Likewise, the 5% scenario-parity allowance is not an exact-equivalence promise.

Benchmarking Against Established Engines is intended to use Designing Meaningful Inference Benchmarks’s benchmark discipline to compare the capstone with other engines. For that comparison, the interface must be at the right level: the capstone’s own scheduler can expose forward-pass logits, but independent serving engines ordinarily manage their own cache and sampling. This chapter introduces their common request-to-events boundary and records, rather than conceals, the fact that no external serving engine was qualified on this machine.

Where the starter was wrong

The starter’s PyTorchToyBackend does not use PyTorch: it echoes a prompt followed by repeated x characters. Its conformance routine asks only whether generate("hi", 2) returns "hixx". That checks allegiance to one toy implementation, not interchangeability. The vLLM and SGLang entries are stubs, with availability supplied by the caller; counting those names as three tested backends would mistake placeholders for executions. The old starter and its tests remain untouched as historical evidence of what the new lab needed to improve.

The replacement needs three independent mechanisms: behavioural checks capable of failing a plausible implementation; capability and availability probes that preserve not supported, not runnable and failed as different statuses; and conformance results recorded alongside the exact model, precision, software environment and numerical tolerance. It also needs a second interface for systems that will not delegate their sampler and cache to us.

Two levels of backend

ModelBackend in the capstone is a logits-level contract: the engine opens a sequence, supplies tokens, owns its sampling decision and expects logits and sequence-state operations in return. This is useful when we control the forward pass. A production-style serving engine or hosted provider generally owns its scheduling, cache management and token selection; wrapping it as though it exposed per-step logits would be an invented capability. Hugging Face’s generate also owns a decoding loop and sampling. Accordingly, the runtime compares such implementations through a separate generation-level contract rather than pretending the two levels are identical.

ADR-014 records the boundary between the two contracts. The following diagram is an architectural map, not evidence that any external serving engine was executed.

    flowchart TB
    subgraph REQ["request level: GenerationBackend.generate(request) returns events"]
        EG["EngineGeneration: the capstone's own engines"]
        HG["HFGenerate: the library's generate, adapted"]
        RG["RawHFGenerate: the library as it is"]
        EXT["vLLM, SGLang, providers: found unavailable, skipped"]
    end
    subgraph LOG["logits level: ModelBackend, BatchedBackend"]
        TB["TinyBackend and BatchedTinyBackend: numpy"]
        HB["HFBackend and BatchedHFBackend: Qwen3, Llama, GPT-2"]
    end
    EG --> ENG["SerialEngine, BatchEngine: sampling, schedule, cache books"]
    ENG --> TB
    ENG --> HB
  

Backend contract: logits-level versus generation-level responsibilities

At the request level, GenerationBackend.generate(request, cancelled) yields a sequence of TokenEvent values followed by one FinishEvent; its GenerationCapabilities state whether the implementation declares logits, seeded sampling, cancellation and concurrent requests. EngineGeneration adapts the capstone’s serial or batch engine into that form. HFGenerate adapts library generation to the event semantics; RawHFGenerate deliberately exposes the mismatch. UnavailableGeneration explains why it cannot run by raising BackendUnavailable. A missing capability is not emulated and is not awarded a pass. In this milestone generate produces the event list for a request; the contract does not yet prove a streamed, multi-client network interface or prompt cancellation with low latency.

Capabilities: what a backend declares it can do

The request-level suite contains nine checks: well-formed events (indices, request and trace ids, timestamps, one finish); length limits at 1, 2 and 5 tokens; stop-token omission with reason STOP; repeated greedy output; agreement with a designated reference; repeatability when seeded sampling is declared; sampled first-token frequencies against reference logits; cancellation when declared; and invalid requests represented as ERROR events. The sampling check uses 300 independent seeds, temperature 1 and top-k 5, then compares empirical frequencies with the reference top-five softmax. Its acceptance threshold is total-variation distance 0.12, much coarser than a token-by-token equivalence check. It is a distributional smoke test for this model and prompt, not proof of arbitrary sampling fidelity, random-number independence or deterministic equivalence between different sampling algorithms. Capability-dependent checks are shown as SKIP, not silently subtracted from the matrix.

Batched decode

A logits-level backend declaring batched_decode=True must preserve more than shape. The BatchedBackend contract requires: (1) prevalidation and atomic rejection of a batch with invalid inputs, leaving all sequences unchanged; (2) logits returned in caller-supplied sequence order; (3) numerical agreement with single-sequence decode inside the backend’s declared atol; (4) cache-state agreement after rows of different lengths enter and leave the batch, tested against fresh-prefix computation; and (5) malformed or duplicate sequence ids rejected without side effects. Five checks—decode_is_atomic, matches_single_decode, order_and_subsets, state_matches_prefill, rejects_malformed—exercise those cases. In this chapter, atomicity means no visible state changes for the tested invalid/refused calls. It does not establish rollback after every possible GPU failure, allocator error or partial update.

BatchedTinyBackend supplies a CPU reference path. It groups projections and feed-forward work into matrix operations across rows while evaluating attention against each sequence’s separate cache. It satisfies the batched checks within the declared float64 tolerance, but the batched arithmetic can differ in its least significant bits from an otherwise equivalent single-row call. That is enough to forbid an unqualified bitwise batch invariance claim, even when token choices happen to agree.

BatchedHFBackend supplies the Qwen3 path measured here. Each sequence still owns an independent DynamicCache. For a decode step the adapter left-pads and concatenates those caches, constructs attention masks and per-row position ids, executes a single model forward pass and copies the newly produced key/value slice back into each sequence’s cache. The model call is combined; the cache storage is not paged or shared. The implementation copies historical cache tensors into a padded temporary batch on every step, making both transient memory and copy traffic dependent on sequence length and batch composition. Validating inputs before that work protects the tested rejection cases, while a true all-failures transaction guarantee would require a stronger commit/rollback design. The 458 MB peak reported later is for this specific stack-and-split implementation.

BatchEngine.step retains the Implementing Scheduling and Caching lifecycle: expire, admit, sample, check terminal conditions and advance each active request. With batched decode enabled, requests that still require a next-model step are collected and sent to one backend.decode call; those no longer active are filtered out. Without the feature, each such request is decoded separately. A batched exception triggers a per-row retry so that the scenario tests can isolate the faulty request. This recovery assumes the failed batch call left state unchanged, the very contract the batch suite tests for selected errors. It is not a general remedy for a backend that partly committed, wedged the GPU or failed for an unrelated global reason. The fallback can also incur additional work and must be metered in failure-heavy workloads.

Testing the batched path

Eight deliberately faulty variants probe the new boundaries: five batched backends introduce incorrect shared positions, partial state commitment, reversed rows, acceptance of duplicate handles or padded tokens leaking into shorter caches; three scheduler mutants decode an already-preempted request, assign returned rows to the wrong requests or terminate every request after one batched failure. Each mutant names its expected failing checks before the matrix is evaluated. These faults are specific to batched state and identity: an output with the correct overall shape can still belong to the wrong request.

In the saved mutation matrix 8 of 8 faulty variants were detected and all eight failed the checks declared for them; every one of the five new backend batch checks was failed by at least one backend mutant. This is evidence of sensitivity to the constructed faults, not a completeness proof. The 24 scheduler/cache mutants from Implementing Scheduling and Caching were also rerun after the engine changed, and all were detected again. The two early surprises below matter more than a bare 100% mutation score.

One scheduler mutant removed the filter for preempted requests already queued for a batched decode. Under the default newest-request victim policy the change was observationally equivalent: the newest request was advanced last and had not yet entered that decode batch. Coupling the mutant to the alternative oldest-request victim policy made the missing filter observable and the scenario check killed it. The oldest-victim policy itself was a conforming variant and passed. This is a useful design property: a contract should reject stale-row execution without needlessly fixing which request a scheduler must preempt.

The more consequential surprise was the parity threshold. The initial rule allowed at most 5% of requests to differ from serial generation inside each scenario. The float16 batched Qwen3 adapter failed: four requests differed among 116 across 24 scenarios, but one difference in a scenario of only three to seven requests exceeded its individual allowance. After observing that failure, the rule was changed to apply the unchanged 5% threshold to the aggregate of all scenario requests. The same four mismatches then amounted to 3.4% and passed. Aggregation is easier to interpret as a population-rate screen and still detects the reversed-row mutant in these cases, but the acceptance rule was selected with knowledge of the failing data. That makes this a post-observation qualification, not a clean confirmatory pass. A genuine promotion gate should freeze a per-request and per-scenario policy in advance, assess uncertainty in the mismatch rate, and then use a fresh held-out suite. The 4/116 scenario result is distinct from the 4/144 throughput-workload result below.

One infrastructure failure is also preserved in the evidence. A preliminary failure-injection check counted decode calls with an unbounded control run; a leaking-block mutant made the engine wait indefinitely, so the matrix hung for roughly forty minutes. Bounding that control at 500 iterations made the mutant observable and the run terminate. A production conformance harness needs execution timeouts, step limits, memory caps and per-case provenance; otherwise a broken backend can make the validator fail to finish rather than produce a FAIL. No general resource-isolation sandbox is claimed by the tests in this chapter.

What batching bought

The throughput experiment submitted sixteen chat-templated order requests together, around 90 prompt tokens and 32 requested output tokens apiece, on one Qwen3-0.6B instance. Three trials used newly drawn requests, with the same requests across configurations within each trial and configurations run in a random order. The reported tokens/s divides all generated output tokens (512 per trial) by the makespan to the last finish; it is burst-completion throughput, not throughput at a sustained open-loop arrival rate. The controlled comparison keeps the scheduler and the HF backend family fixed and changes whether decoding is done with one call per live sequence or one call for its whole batch. For 16 live requests and a 32-token target, the first token comes from prefill, leaving 16 × 31 = 496 decode rows. The count of decode calls then falls from 496 to 31 at batch 16; the work inside a call is different, so calls alone do not quantify compute savings.

float16, burst of 16 requests Per-sequence output tokens/s (median) Batched output tokens/s (median; observed range) Median paired batched/per-sequence ratio (range) Decode calls for 496 rows: per-sequence / batched
1 running 24.5 23.1 (22.6–24.5) 0.98 (0.94–1.10) 496 / 496
4 running 22.2 51.5 (49.4–67.4) 2.32 (2.26–2.90) 496 / 124
8 running 23.8 100.0 (86.2–102.1) 4.27 (3.62–4.83) 496 / 62
16 running 22.5 131.7 (121.4–135.0) 5.42 (5.40–6.26) 496 / 31

Values are medians or minima and maxima over three trials, not confidence intervals. Median of paired ratios is computed within trials; it need not equal the quotient of the separately rounded median throughput values.

The serial Designing the Inference Runtime engine produced a median 23.8 output tokens/s on these requests. At sixteen running, the batched adapter’s median paired speedup over serial was 5.51 (range 5.27–5.68), while per-sequence decoding under the scheduler stayed near serial throughput. Float32 showed the same qualitative pattern: serial 26.5, per-sequence 27.4–28.5 and batched 28.9, 74.1, 110.6 and 129.3 tokens/s as concurrency rose from 1 to 16; the paired batched/per-sequence ratio at 16 was 4.68 (4.56–5.17). These are descriptive comparisons over three bursts. Designing Meaningful Inference Benchmarks’s repeated-trial uncertainty and quality requirements have not been satisfied for a claim about production capacity.

Speed has three companion measures. At sixteen running in float16, median request TTFT was 0.75 seconds with a batched forward pass versus 1.05 seconds per-sequence; median request completion was 3.88 versus 22.78 seconds. The serial engine’s medians were 10.46 and 11.68 seconds respectively, illustrating how iteration scheduling changes which requests receive service. Memory went the other way: peak incremental CUDA allocation above the measured starting point was about 18 MB for serial, 204 MB for sixteen per-sequence requests and 458 MB for the batched adapter; float32 gave approximately 32, 404 and 901 MB. Stacking padded copies of the existing caches at every step is the leading implementation-level explanation of the extra peak, but a byte-by-byte attribution to temporary caches, activations and allocator behaviour was not separately measured. A persistent paged or packed cache is a plausible next experiment, not a measured counterfactual.

Token identity is a separate acceptance dimension. In float16, every one of the 48 requests at each tested concurrency matched serial under per-sequence decode. Under batched decode, 48/48 matched at one running; 46/48, 47/48 and 47/48 matched at 4, 8 and 16, respectively—140/144 across the genuinely batched configurations. Float32 matched for 144/144 in those same configurations. The observed 2.8% float16 mismatch rate is neither zero nor a precisely estimated deployment error rate. Different floating-point reduction shapes, potentially including a near tie between top logits, are a plausible mechanism informed by Correctness, Determinism and Reproducibility; no per-mismatch margin trace here isolates the cause. For a consumer that requires exact repeatability, passing a tolerance-based logits contract is insufficient. The deployment must choose a reference execution policy and explicitly decide whether any generated-token disagreement is acceptable.

The numerical promise of the batched adapter

BackendIdentity.atol defines an absolute-logit tolerance for operations that ought to compute the same state by different paths. The batched adapter initially reused the single-sequence defaults—0.25 in float16 and 2e-3 in float32—before its calibration. Following Designing the Inference Runtime’s procedure, one prompt set was used for calibration and another seed supplied a held-out set: 24 prompts each, 63–93 input tokens, eight sequences batched, sixteen greedy decode steps. At each step, logits were compared with a single-row decode forced to consume the same tokens; the final state was also compared with a fresh prefill of the full history. This is teacher-forced numerical agreement, not the free-running output test and not calibration over all batch shapes or context lengths.

Precision, GPU Calibration max: batched vs single / fresh prefill Held-out max: batched vs single / fresh prefill Default atol Largest held-out difference / default
float16 0.070 / 0.064 0.125 / 0.063 0.25 0.50
float32 1.3e-4 / 7e-5 1.2e-4 / 9e-5 2e-3 0.07

Each maximum is from the recorded 24-prompt set for that column. Values summarise the actual checked prompts, not hard bounds for unseen requests.

In the calibration experiment the batched and single-row paths chose the same top-1 token at every recorded teacher-forced step, and the predeclared atol was respected on both 24-prompt sets in both precisions. That does not contradict the four free-running float16 differences: the experiments use different prompts and execution histories, and one changed choice can alter every later token in a generated completion. In half precision the largest held-out single-decode difference (0.125) was about 1.78 times the calibration maximum (0.070), even though it was still half the default tolerance. A maximum observed on 24 prompts provides evidence for this workload only; it cannot certify an upper bound for long contexts, batch 32, mixed sequence lengths or changed kernels. Promotion should include a new-seed sweep over those axes and report both logit error and token-level disagreement.

One suite, several backends

Conformance: which backends pass, fail or skip each suite

The logits-level conformance matrix applies five suites: backend (14 checks), fork (5), batched decode (5), serial engine (15) and scheduler scenarios (12). Each backend runs only suites whose required capability and test factories are supplied. In the saved environment the matrix has ten locally available logits-level rows—numpy per-sequence and batched, three random-weight transformer architectures in both modes, and pretrained Qwen3-0.6B in both modes. The vLLM and SGLang rows are unavailable and skipped. A blank or skipped cell is never a pass, and a successful cell is conditional on the tested model, precision, prompt lengths, scenarios and declared numerical identity.

Logits-level backend Backend (14) Fork (5) Batch (5) Engine (15) Scenario (12)
NumPy float64, per-sequence 14/14 5/5 SKIP: no batched_decode 15/15 12/12
NumPy float64, batched 14/14 5/5 5/5 15/15 12/12
Random-weight Qwen3, Llama and GPT-2, float32 CPU, per-sequence 14/14 each 5/5 each SKIP each: no batched_decode 15/15 each 12/12 each
The same three architectures, batched 14/14 each 5/5 each 5/5 each 15/15 each 12/12 each
Qwen3-0.6B float16 GPU, per-sequence 14/14 5/5 SKIP: no batched_decode 15/15 12/12
Qwen3-0.6B float16 GPU, batched 14/14 5/5 5/5 15/15 12/12 (4/116 aggregate token mismatches)
vLLM, SGLang SKIP: not runnable here SKIP SKIP SKIP SKIP

The three random-weight model families occupy six distinct backend rows; they are combined only to keep the printed table readable. No model-quality or pretrained-weight claim follows from their passes.

All applicable checks passed for the ten locally runnable logits-level rows. The CPU architecture probes are especially useful as structural tests: random Qwen3, Llama and GPT-2 models have different positional mechanisms and cache layouts, so an adapter that hard-codes one cache form could fail even before pretrained weights are involved. But each random model has a 1,000-token vocabulary and says nothing about meaningful language generation. Only Qwen3-0.6B used pretrained weights. In its float16 adapter, the recorded basic append and prefix checks had maxima around 0.032 and 0.027; the batched-versus-single maximum from the suite was around 0.082 against atol=0.25. None of those values by itself explains the observed free-running token mismatch. The passing matrix is therefore interface evidence, not a certificate of semantic quality, memory efficiency or numerical invariance across hardware.

A good conformance table is informative even when its runnable rows are all green, provided failures and omissions remain visible. Designing the Inference Runtime tested the checks with mutants; this chapter adds eight batched faults and shows two suite-design corrections prompted by failures. Yet twelve named checks have no dedicated mutant campaign: the nine generation checks and three conformance-runner checks. Two generation checks failed on the deliberately raw library wrapper, and two broken-runner cases exercise important skip logic, but that is not equivalent to independent fault coverage for every rule. The next qualification milestone should add targeted mutants for the request-level event contract and the skip accounting.

The library’s own generate

The request-level comparison uses pretrained Qwen3-0.6B in float32 on the CPU, with six prompts of 48 tokens and, for the distribution check, 300 sampled first-token outputs per backend. The CPU configuration avoids a known class of potentially context-poisoning CUDA failures from invalid embedding indices; the suspected GPU behaviour was not deliberately induced here. The test therefore establishes only the request-event behaviour measured on this CPU setup. It does not benchmark streamed token arrival time, concurrent clients, or long-running cancellations.

Generation-level wrapper Result on the six CPU prompts Key observations
Capstone serial engine (reference) PASS 9/9 Sampled first-token total-variation distance 0.053
Capstone batch engine, batched decode PASS 9/9 Greedy output agrees on 6/6; sampling distance 0.053
transformers.generate through HFGenerate PASS 9/9 Sampling distance 0.064; adapter supplies required event semantics
transformers.generate through RawHFGenerate FAIL 2, PASS 5, SKIP 2 Stop token emitted and invalid request raised; sampling distance 0.040; seeded repetition and cancellation not declared
vLLM, SGLang, Anthropic API, OpenAI API SKIP with individual reason No external serving or provider inference executed

PASS 5/7 for the raw wrapper means five of seven executed checks passed; the other two of the nine were explicitly skipped, not passed.

RawHFGenerate intentionally calls the library without changing its return convention. For the tested stop id, the raw wrapper exposes the four generated tokens including the terminal token and labels the request as LENGTH; the capstone contract instead requires three emitted tokens and a STOP finish event. For an out-of-vocabulary id, the raw path raises an IndexError whereas our contract wants an ERROR finish event. Those are adapter-contract mismatches, not violations of Hugging Face’s API specification. HFGenerate adapts the result by removing a trailing stop id, translating exceptions to ERROR, polling a cancellation callback through a stopping criterion, and resetting PyTorch’s random seed. Two qualifications follow from its actual code: _events stamps TokenEvents after model.generate returns rather than at each token’s production, and torch.manual_seed changes process-global RNG state rather than supplying isolated per-request generation state. Consequently the nine checked behaviours do not certify real-time streaming timestamps, thread-safe concurrent seeding or immediate interruption of a GPU kernel. These need separate implementations and tests before an external-server comparison.

The capstone serial and batched generation wrappers produced the same sampling-distance estimate on this small first-token test, but that is a limit of the measurement’s resolution and of the logits actually supplied, not evidence that batched and serial distributions are identical under all prompts. The suite also verifies repeated greedy output and agreement with its designated reference; it does not evaluate factual accuracy, prompt adherence, refusal behaviour or end-to-end provider quality. A future cross-engine benchmark needs both contract conformance and application-level answer-quality evaluation.

What could not run

The availability gate runs an import probe in a fresh, isolated Python interpreter and captures its outcome. This is stronger than checking whether a distribution is installed, but an import is still only a preflight. A fully runnable server needs validated model loading, hardware support, request execution, cleanup and a completed reference-quality test before its benchmark row can be marked qualified.

  • vLLM: The observed environment had distribution version 0.30.0 installed, but import vllm failed with ModuleNotFoundError: No module named 'vllm._C_stable_libtorch'. This establishes an import-time failure on that Windows installation; it does not establish why the extension is absent or whether vLLM works on another supported deployment. The matrix records SKIP: import failure, not FAIL for model generation.
  • SGLang: The package was not installed, so no import or generation conformance was attempted. Its row reads SKIP: not installed.
  • OpenAI and Anthropic: Client packages were present, but the probes deliberately did not import clients or make network calls. They checked only whether credential variable names were set, without reporting values; neither was set in the recorded environment. Both rows read SKIP: NOT_RUN by policy—no network or cost. They would remain untested even if credentials were present. There are no measured provider results in this chapter.

These statuses must never be conflated. A backend that cannot be constructed is unavailable; a constructed backend may lack a declared capability; an applicable check may pass or fail. In conformance.py, skipped suites retain reasons and skipped checks do not inflate the pass count. Three runner self-checks verify those invariants, and targeted broken-runner cases caught counting skips as passes and invoking unavailable backends. They do not, however, constitute a full mutation matrix for the runner. The measured result is that the matrix maintained the distinctions for its tested cases; the engineering requirement for Benchmarking Against Established Engines is to make the distinctions fail-closed gates on whether a row may enter a performance comparison.

The OpenAI guide to verifying gpt-oss implementations offers a useful contrast. Its API-behaviour and evaluation-oriented checks ask whether an implementation completes tasks with acceptable results; this chapter’s adapter checks ask whether events, token handling and cache state obey a particular local contract. Neither substitutes for the other. A provider could satisfy the generation-level API while producing weak answers; a logits-level backend could match one token trace while having incompatible error or cancellation semantics. The book did not run the gpt-oss guide’s evaluations or reproduce any results from it. Its role here is to motivate an eventual two-level acceptance gate: behavioural conformance, then workload and output-quality qualification.

What the numbers do not show

  • One short-burst performance point. The 5.42× median paired ratio belongs to Qwen3-0.6B, three bursts of 16 requests, 32 generated tokens each, and contexts around 125 tokens. It is not a steady-arrival throughput result, a capacity estimate, or a claim about vLLM or SGLang. The copy-based batched adapter moves growing historical cache tensors each step; its behaviour at longer contexts or batches beyond 16 is not measured.
  • Performance includes a memory price. At 16 active requests the median incremental peak allocation is 458 MB versus 204 MB per-sequence (float32: 901 versus 404 MB). The experiment did not isolate cache-copy bytes from other transient allocations, nor implement paged storage. A persistent cache is a proposed next design, not an observed saving.
  • Three paired trials do not establish an operating SLO. The reported minima and maxima are the extrema of three runs, not confidence intervals. Designing Meaningful Inference Benchmarks’s benchmark, drift controls and separate trial-level uncertainty remain to be applied before serving-capacity decisions.
  • Numerical agreement is not exact. Of 144 genuinely batched float16 requests in the throughput experiment, four differ from serial. The aggregate 5% scenario parity rule was applied only after an initial per-scenario failure (4/116). Neither an atol test nor a post-observation parity pass replaces a predeclared quality gate on fresh data.
  • Only one pretrained model. Random-weight Qwen3, Llama and GPT-2 configurations exercise cache and position adapters, not language quality. The Qwen3-0.6B experiments do not qualify another checkpoint, precision, attention kernel or GPU family.
  • The generation suite is narrow. Its six CPU prompts and 300 first-token samples test the recorded event and distribution rules. The HFGenerate wrapper currently constructs events retrospectively and uses process-global seeding; genuine token streaming, isolated concurrent requests, prompt cancellation latency and GPU error recovery are NOT_RUN.
  • Not every new check has mutant evidence. The nine generation checks and three runner checks lack a dedicated full mutant matrix, notwithstanding the raw-library failures and selected broken-runner tests.
  • Unavailable remains untested. vLLM’s failed import, missing SGLang and the no-network provider policy produce skip reasons only. They give no comparative runtime, token-quality, safety or price evidence for those systems.

Inference Lab increment

The Inference Lab package now exposes BatchedBackend and GenerationBackend with declared capabilities in contracts.py; BatchedTinyBackend in backends/tiny.py; BatchedHFBackend in backends/hf.py; and the adapted and raw Hugging Face generation wrappers in backends/hf_generate.py. generation.py supplies EngineGeneration, UnavailableGeneration and availability probes. conformance.py records available, failed and skipped suite results; contract_tests.py adds batch and generation suites; and scheduler.py optionally collects live rows for a single batched decode call, falling back to per-sequence retry on a rejected batch. The batch mutants and the runner checks, together with ADRs 013–015, extend the traceability introduced in Designing the Inference Runtime. examples/ch43/backend_lab.py contains the experimental commands. This is a completed Chapter 43 milestone in the recorded repository state, not a claim that subsequent code revisions have been qualified by these measurements.

The qualification backlog is concrete: strengthen failed-batch rollback and deadline behaviour, implement genuinely streamed event timestamps, isolate request RNG state, add mutant coverage for request-level checks, freeze a predeclared token-agreement gate and qualify any external engine before granting it a benchmark row.

To run the repository’s tests and rebuild the Chapter 43 report from saved measurement files, use the following commands from the repository root. Rebuilding the report is not a new GPU experiment; the measured run environment and software revisions are recorded in research/ch43/results.json.

python -m pytest tests/test_ch43_backend_lab.py tests/test_ch43_backends.py -q
python research/ch43/build_results.py

The engineering rule is: place each adapter at the lowest truthful interface; declare capabilities explicitly; validate batch state, row identity and failure atomicity; keep PASS, FAIL and SKIP separate with reasons; and never promote a speedup without presenting its workload, GPU-memory cost, numerical disagreement and trial uncertainty. A compatibility shim may make an existing library conform to our event conventions without proving that the underlying library was wrong. A tolerance or quality threshold chosen after seeing a failure is exploratory until it passes a new, predeclared test. These disciplines are the input to Benchmarking Against Established Engines, not optional annotations on its leaderboard.

What you should now be able to do

  • Derive the five obligations of a batched-decode backend and construct an invalid-input test that proves the tested batch call leaves earlier rows untouched.
  • Explain how padding, position ids and separate KV caches allow unequal-length sequences to share one forward pass, and estimate why copying the cache every token increases memory traffic with context length.
  • Distinguish strict batch invariance, tolerance-based logit equivalence, distributional sampling checks and exact generated-token agreement.
  • Explain how an observed 5.42× paired throughput ratio can coexist with roughly doubled peak memory and 4/144 changed float16 outputs.
  • Choose between logits-level and request-level adapter contracts according to which component owns the decoding loop, random state and cache.
  • Build a matrix that reports missing capability, non-runnable environment, real failure and pass as distinct outcomes; identify why skip counts cannot enter a pass denominator.
  • Identify the statistical problem when a 5% parity rule changes aggregation after the first failure, and specify a held-out confirmation test.
  • State what must be added before the generation adapter’s event timestamps and seeded sampling can be used in a concurrent production benchmark.

Key terms

  • Logits-level backend: a model adapter exposing per-step logits and per-sequence cache operations to an external sampler and scheduler.
  • Generation-level backend: a request-to-events adapter around a component that owns its generation loop and usually its sampling.
  • Capability declaration: an explicit statement of supported operations, used to decide which suites are applicable.
  • Batched decode: one model forward pass consuming a next token from several active sequences while maintaining their separate logical histories.
  • Batch invariance: exact independence of a sequence’s computation from its batch partners and batch shape; distinct from merely staying inside an atol bound.
  • Atomic rejection: a failed or invalid batch operation leaves its participants’ state unchanged; the tests here establish this for selected rejected inputs.
  • Row-order integrity: logits returned in the same order as the sequence handles supplied to the decode call.
  • Request-level conformance: agreement with event, termination, failure and declared sampling/cancellation behaviours, not necessarily token-for-token equality between arbitrary samplers.
  • PASS / FAIL / SKIP: a successful applicable check, a failed applicable check, or a check not executed, the last always with its reason.
  • Probe: an availability preflight; successful import does not alone qualify model loading or request execution.
  • Equivalent mutant: a deliberately altered implementation that behaves identically for the scenario or policy being tested.
  • Conforming variant: a legitimate policy change that should pass unchanged contract checks.
  • Post-observation threshold: an acceptance rule or aggregation choice revised after seeing an evaluation outcome; requiring separate held-out confirmation.

Reader exercises

  1. Replace the repeated cache stack-and-split in BatchedHFBackend with a persistent or paged cache. Hold the model, request set and output-token target fixed; report both peak allocated bytes and measured copy traffic, not throughput alone.
  2. Repeat the 16-request experiment at contexts of roughly 125, 500 and 1,000 tokens, if memory permits. Explain whether padding and copying produce different throughput and memory trends as histories lengthen.
  3. Add two generation-level mutants to HFGenerate: emit the stop token and propagate invalid-request exceptions. Verify that the expected named checks fail, then add a mutant that fabricates token timestamps after completion and design a streaming-timestamp check capable of detecting it.
  4. Replace the process-global torch.manual_seed use with a request-owned generator where the framework supports it. Interleave sampled requests and verify that one request does not alter another’s random stream.
  5. Freeze a quality gate before executing new Qwen3 float16 tests: define whether the threshold is zero mismatches or a justified statistical upper bound, choose its unit of analysis and test on fresh scenario seeds rather than reusing 4/116.
  6. Construct a backend whose batch call modifies the first sequence before raising on the second. Check whether rollback or per-row fallback exposes corruption, and distinguish contract failure from failure of the recovery path.
  7. Investigate the missing vllm._C_stable_libtorch extension without changing the current matrix entry. Only promote the vLLM row after an isolated import, model load, smoke request and full request-level suite pass on a supported environment.
  8. Add a fail-closed Benchmarking Against Established Engines admission rule: no performance comparison may accept a backend without the same workload, a runnable probe, mandatory event checks, a frozen quality policy, and enough independent trials to support the verdict.

References

Three primary papers provide the systems context for the chapter’s actual design; their reported gains are not results of this book:

Implementation and comparison references:

Evidence in this chapter

Claim Evidence category and scope
At 16 running in the short 16-request burst, float16 batching yielded 131.7 versus 22.5 output tokens/s, median paired ratio 5.42 (5.40–6.26). BOOK RESULT: Qwen3-0.6B, three paired trials, one GPU; not an open-loop capacity estimate.
decode calls for 496 rows decreased from 496 per-sequence to 31 batched at 16 running. BOOK RESULT: counters from this workload; reduced call count alone is not a measure of arithmetic work.
Incremental peak CUDA allocation was about 458 versus 204 MB at 16 running (float32 about 901 versus 404 MB). BOOK RESULT: allocator measurements; cache-copy attribution not separately isolated.
Batched free-running tokens differed from serial for 4/144 float16 requests at batch 4/8/16, and 0/144 float32 requests. BOOK RESULT: small tested corpus, not a universal mismatch rate or a bitwise invariant.
Batched adapter held the declared atol for 24 calibration and 24 held-out prompts in each precision. BOOK RESULT: batch eight, 16 teacher-forced steps; not a worst-case bound on all inputs.
Ten locally runnable logits-level rows passed applicable suites; three random-weight architectures tested adapter structure. BOOK RESULT: structural conformance only for random models; no language quality inferred.
The original per-scenario 5% parity check failed on 4/116 differing requests; after switching to an aggregate 5% rule, the same result passed. BOOK RESULT, POST-OBSERVATION RULE CHANGE: a separate, predeclared held-out quality gate is NOT_RUN.
The raw HF generation wrapper failed stop handling and error-event requirements; the adapted wrapper passed 9/9 on six CPU prompts. BOOK RESULT: comparison against this book’s event contract, not a claim of a framework API defect.
Eight batched mutants were detected; 24 prior scheduling mutants were detected again; 12 request-level/runner checks lack dedicated mutation coverage. BOOK RESULT: author-constructed faults and checked scenarios; not exhaustive.
vLLM 0.30.0 failed to import; SGLang was absent; providers were not contacted. BOOK PROBE / NOT_RUN: no evidence about external-engine runtime quality or performance.
Orca, PagedAttention and FlashInfer discuss complementary scheduling, cache and attention designs. PUBLISHED RESEARCH: authors’ findings, not experiments reproduced here.
True event streaming, request-isolated HF RNG, full failure rollback, large contexts, other pretrained models and sustained-arrival cross-engine benchmarks. NOT_RUN / NOT_IMPLEMENTED IN THIS MILESTONE.

Implementation status

  • Manuscript: content/books/inference/43-chapter.md; full-text edits apply to this Inference path, not the Embeddings book.
  • Starter preserved: examples/ch43/backends.py and tests/test_ch43_backends.py.
  • Runtime increment: examples/ch43/backend_lab.py; examples/inference_lab/ with batched CPU/HF backends, HF generate adapters, generation-level capabilities, conformance runner, the batched scheduler path, updated scenario tests, new mutants and ADRs 013–015.
  • Tests: tests/test_ch43_backend_lab.py and tests/test_ch43_backends.py, with the recorded suite on CPU reference backends and locally runnable Qwen3 configurations.
  • Evidence: research/ch43/results.json, research/ch43/measurements/, research/ch43/build_results.py and research/ch43/sources.md; the saved results retain the initial parity failure and the subsequent rule revision.
  • Verification from the repository root: python -m pytest tests/test_ch43_backend_lab.py tests/test_ch43_backends.py -q and python research/ch43/build_results.py. The latter rebuilds the report from saved measurements; it does not rerun GPU generation.

Status: the local batched backend and the generation-level conformance framework have measured evidence. Benchmarking Against Established Engines must not treat the existing skip rows as qualified competitors or the post-observation 5% rule as a prospective acceptance gate. External engines, provider requests, real streaming timestamps and production arrival workloads remain unqualified.