← Inference From First Principles

Model Architecture Versus Runtime Architecture

Changing one thing at a time on a real model to find where the model ends and the runtime begins, what the software stack does when asked for something it cannot do, and an admission function that refuses before any work is done.

Seven serving-side changes were compared with Llama-3.2-1B on twelve prompts, generating 48 greedy tokens per prompt: two prefill chunk sizes, two attention implementations, a static cache, left-padded batching, and a float32 load. Across these seven rows, 79 of 84 prompt-level outputs matched their own baseline token for token. The five disagreements all began where the reference logits were separated by at most 0.015625 (three margins were zero in the recorded precision). They occurred in the attention implementations and padded batches, not in the chunked-prefill, static-cache, or float32 rows. The largest recorded change in end-of-prompt logits was 0.02734375. These are output-preservation observations for this particular model, inputs, and software build—not proof that the runtime transformations are universally bitwise equivalent.

The contrasting tests changed numerical weights or the attention rule: decoder linear weights were rounded to simulated 8-bit or 4-bit grids; 1,200-token prompts were given a 512-token sliding window, with or without four retained initial tokens; and the shipped RoPE scaling was removed for three 12,000-token prompts. Only 8 of these 51 prompt-level runs matched their corresponding baseline, all under the int8 transformation. The maximum end-of-prompt logit differences ranged from 0.4106 for int8 to 13.5469 for the imposed window. Unlike the preceding rows, these interventions alter the effective model computation or its positional interpretation. The prompt lengths and, for RoPE, generation length also differ across groups, so the measurements show direction and scale rather than a controlled effect-size comparison across every row.

The distinction matters because a deployment has two obligations: preserve the specified computation when it changes how that computation is executed, and disclose and validate a new computation when it changes weights, routing, masks, positions, or the request itself. Chapters 10–18 predominantly study execution mechanisms; Chapters 19–23 also introduce model-sensitive choices such as expert capacity, KV-head layout, sliding windows, and RoPE scaling. The boundary is not established by the name of a configuration flag or even by whether a few greedy tokens coincide. This chapter tests it on one checkpoint, audits thirteen software-stack probes, and then implements a small admission policy. Six probes raised errors, three warned and continued, and four ran without a warning. Two of the silent cases were normal successful operations; one changed how a system message was represented, and one incurred an unannounced performance cost. That classification is more informative than calling every quiet operation a substitution.

Where this sits

Chapter 2 introduced the manifest as the identity and provenance record of an inference run. Chapter 6 introduced the backend contract—encode, decode, next_logits, and its manifest. Subsequent chapters ask what it takes to implement that contract: cache layout (10), paging (14), batching (15), prefix reuse (16), speculative decoding (17), execution graphs (18), expert dispatch and capacity (19–20), KV-head architectures (21), sliding windows (22), and position handling (23). Chapter 24 joins those pieces into two explicit questions: which choices alter the computation requested? and which combinations can this particular backend and device execute? Chapter 25 begins the service layer, where both questions must be answered before scheduling a request.

The Inference Lab adds three tools here: a configuration fingerprint to describe a subset of architectural requirements; a preservation harness that compares generated tokens and selected logits under controlled changes; and an admission function that reports rule-based rejections and warnings. These tools are deliberately incomplete. The fingerprint is not a weight or tokenizer digest, preservation is checked on finitely many prompts, and admission does not yet inspect memory headroom, all backend dependencies, or actual chat-template conformance. For the Pi series, this chapter turns Chapter 2’s manifest into a stronger requirement: record the model artefact, input formatting, numerical/dispatch choices, and the evidence that each requested capability is supported.

What the model decides

Model architecture vs runtime architecture

A checkpoint’s configuration contains important architectural parameters, but not every field is necessarily a training-time architectural decision. Some describe generation defaults, packaging, or implementation preferences. The laboratory therefore extracts a specified subset—layer and head dimensions, positional settings, window flags, softcapping, and expert counts—from ten locally cached config.json files. The following is configuration evidence, not an exhaustive fingerprint of the complete model artefacts:

Model Attention Nominal KV bytes/token (fp16) Configured max positions Positional extension stated Window stated
GPT-2 MHA, 12 heads 36,864 1,024 learned absolute positions none
Pythia-160m MHA, 12 36,864 2,048 none stated none
TinyLlama-1.1B GQA, 32 query / 4 KV 22,528 2,048 none stated none
Phi-3-mini-4k MHA, 32 393,216 4,096 none stated 2,047 in config; enforcement not established
Gemma-2-2B GQA, 8 / 4 106,496 8,192 none stated 4,096; attention-logit softcapping
Qwen3-1.7B GQA, 16 / 8 114,688 40,960 none stated disabled in config
Mistral-7B-Instruct-v0.3 GQA, 32 / 8 131,072 32,768 none stated none in this revision’s config
Llama-3.2-1B GQA, 32 / 8 32,768 131,072 llama3, factor 32, original max 8,192 none
Llama-3.2-3B GQA, 24 / 8 114,688 131,072 llama3, factor 32, original max 8,192 none
Llama-3.1-8B GQA, 32 / 8 131,072 131,072 llama3, factor 8, original max 8,192 none

All ten cached configurations report zero local experts. The KV column is the nominal tensor payload calculated as 2 × layers × KV heads × head width × 2 bytes; it is not allocated or reserved memory, and hybrid local/global windows can reduce live storage. The maximum-position field is a configured limit, not independent proof of how far the checkpoint was trained or where its accuracy remains good. fingerprint reads layer_types when available—Gemma-2’s local-layer count is represented in the actual ModelSpec—but the table deliberately shows only the window setting. Phi-3’s window entry is not evidence that a particular serving backend enforces it. A production fingerprint must additionally bind the weight hashes and quantization metadata, model/tokenizer revisions, template and special-token conventions, RoPE constants, layer-by-layer behaviour, and any softcapping values. Even a correct configuration parser does not replace a test against the implementation that will execute it.

What the runtime decides, and what it must not

A runtime chooses execution mechanisms: kernels, prefill chunking, cache allocation and layout, batching, scheduling, and graph replay. For a fixed checkpoint and input, these choices are intended to implement the same model-level operation, but that is a semantic obligation, not a guarantee of identical floating-point bits. Reduction order, precision, backend selection, and batch shapes may change numerical results and even an argmax at a near-tie. Earlier chapters measured individual cases: Chapter 14’s paged decoder returned matching tokens with logits within 1.1e-3; Chapter 15’s small-model scheduler agreed with standalone results; Chapter 16’s prefix reuse matched a fresh prefill to 7.6e-5; Chapter 18’s graph and eager paths agreed in its tested decode trace; Chapter 17’s greedy speculative decoding agreed for draft lengths 1 and 2 and produced near-tie divergences for some longer drafts. Those are bounded local tests with their own methods, not a cross-backend theorem of preservation. PyTorch’s numerical-accuracy guidance also cautions that mathematically equivalent floating-point computations need not be bitwise identical.

The new harness makes the comparison more systematic. For each treatment it records greedy-token agreement, first-divergence position, the baseline top-two logit margin at that position, and—where collected—the maximum absolute difference in next-token logits at the end of the prompt. The main baseline is Llama-3.2-1B, loaded in fp16 with default attention and a dynamic cache, on twelve 300-token excerpts with 48 generated tokens each. The left-padded batch is compared with solo runs of twelve shorter, unequal-length prompts, not those 300-token baselines. The window tests use twelve 1,200-token prompts; the RoPE test uses three 12,000-token prompts and 32 generated tokens. The table keeps these populations separate rather than implying one common prompt set for every row.

Change Classification in harness Identical outputs Baseline margin(s) at first divergence Maximum end-of-prompt logit difference
Chunked prefill, 64 tokens execution 12 / 12 none 0.0273
Chunked prefill, 512 tokens (300-token prompt fits one chunk) execution control 12 / 12 none 0
Alternate SDPA attention override execution 11 / 12 0.0156 0.0234
Eager attention implementation execution 11 / 12 0.0156 0.0269
Static cache, generate with compilation disabled execution 12 / 12 none not measured
Left-padded batch of 4, unequal-length prompts execution and batching 9 / 12 0, 0, 0 not measured
Float32 checkpoint load and arithmetic precision intervention 12 / 12 none 0.0216
Window 2,048, imposed on 1,200-token prompts mask-path control 12 / 12 none 0.0273
Decoder weights rounded to int8 grid, per output channel changed effective weights 8 / 12 0.0156, 0.0156, 0.1016, 0.125 0.4106
Decoder weights rounded to int4 grid, groups of 128 changed effective weights 0 / 12 0.0469–1.6875 5.7969
Window 512 imposed, no sinks; 1,200-token prompts changed attention mask 0 / 12 0.125–1.4219 13.5469
Window 512 plus 4 sinks; 1,200-token prompts changed attention mask 0 / 12 0.0469–0.5781 5.3711
Shipped RoPE scaling removed; three 12,000-token prompts changed positional scheme 0 / 3 0.8281, 1.1406, 1.6719 12.4219

The 8-bit and 4-bit rows simulate quantization by rounding decoder linear weights to symmetric grids, restoring the original weights after each treatment, and continuing to compute in fp16. They do not benchmark integer storage formats or integer kernels; embeddings and the output weight remain unrounded. The float32 row reloads a higher-precision representation of the checkpoint, so its effective numerical weights need not be bitwise identical to fp16, even though the nominal checkpoint is the same. “Maximum logit difference” refers only to the first step after prefill and is not a maximum over all generated steps. The padded-batch and static-cache rows have no such logit comparison. A baseline margin of zero refers to the values recorded in the tested precision; it does not establish a mathematical equality of ideal logits.

Three things stand out.

Execution changes preserved most, but not all, greedy traces. Across the seven execution/precision rows there were five first divergences in 84 prompt-level comparisons: one each for the alternate SDPA path and eager attention, and three for left-padded batching. All five baseline margins were 0 or 0.015625 in the recorded float representation. Chunked prefill and static-cache generation returned the same tokens in these trials. The 512-token chunk setting is effectively a no-split control for a 300-token prompt. The fact that two kernel formulations flip a near-tie is consistent with floating-point operation-order differences, but the harness does not trace which kernel or reduction caused each flip. The three zero-margin padded-batch divergences may also reflect tie-breaking or different execution shapes; that mechanism was not isolated. Float32 loading retained all twelve greedy traces, despite a recorded 0.0216 end-of-prompt logit difference. Token agreement alone cannot establish equality of the logits or sampling distributions.

Changing the represented model or attention rule was more disruptive in these tests. The int4, 512-window, 512-window-with-sinks, and removed-RoPE treatments produced no identical traces across their respective groups (twelve, twelve, twelve, and three runs). Their first divergences occurred on average after roughly 6.4%, 1.4%, 8.9%, and 4.2% of the generated trace, respectively. Some baseline margins exceeded one logit unit, unlike the five near-tie disagreements in the execution rows. Their end-of-prompt logit changes were also much larger in this experiment. These are not perfectly matched comparisons: the window and RoPE treatments use longer prompts, and the RoPE treatment has fewer output tokens. The type of intervention—altering weights, available attention positions, or rotary phases—is the reason to treat it as semantically different; the observed divergence rate is supporting evidence, not a universal threshold for classifying other interventions.

Int8 is the instructive borderline. Per-channel rounding left eight of twelve traces unchanged; its four first divergences occurred at baseline margins of 0.015625, 0.015625, 0.1015625, and 0.125. Those margins overlap the near-tie regime, while the maximum end-of-prompt perturbation of 0.4106 exceeds every execution-row value. A small observed output change does not make rounded weights a function-preserving kernel swap. The deployed model is the checkpoint plus its effective weight representation; a quantized release therefore needs its own recorded parameters, error evaluation, and identity. Conversely, a change in floating-point arithmetic may produce a different bit pattern while still implementing the same intended mathematical operation. The manifest needs to distinguish those two cases rather than judging identity from one numerical threshold.

The larger-window control is valuable precisely because the 2,048-position mask never excludes a key in these 1,200-token prompts, including their generated continuation. All twelve greedy traces matched the long-prompt baseline, despite an end-of-prompt numerical difference of 0.0273 when execution followed the masked-attention path. It isolates the effect of excluding positions from at least some of the numerical effects of using a mask. It does not show that masking and unmasked execution are bitwise equal, or that a 2,048-token window would be harmless on a longer prompt.

A runtime parameter can be a model parameter

The operational boundary is what a request means, not which software component exposes a setting. A top-\(k\) expert router with finite capacity may drop assignments based on its batch companions (Chapter 19); imposing a new attention window or removing an expected RoPE extension changes the function (Chapters 22–23); truncation changes the actual input; and quantization changes represented weights. Each must be an explicit, versioned choice with a stated quality or behaviour contract. Padding conventions and chat templates are also part of input semantics: an incorrect template or position alignment can change the request the model receives even when its weights are untouched. By contrast, paging, graph replay, or chunking can be implemented as execution alternatives that target the same specified operation. Their numerical agreement still needs tested tolerances. A manifest should record artefact identity, input identity, effective model choices, execution settings, and the preservation evidence separately, instead of collapsing all differences into “runtime configuration.”

What the stack does when asked for something it cannot do

A useful capability contract separates three outcomes: reject when the requested semantics cannot be provided; accept with an explicit, actionable warning or negotiated change when the caller can make an informed choice; and accept as requested when the implementation satisfies the contract. Silence is not inherently bad—ordinary successful calls are silent—but unannounced changes in semantics or performance guarantees are. The thirteen probes below record the actual behaviour of this local Transformers/PyTorch build; they are neither a complete survey of unsupported requests nor an independent measure of production serving systems.

Probe Observed behaviour Interpretation
GPT-2 given 1,200 tokens against 1,024 positions, CPU IndexError: index out of range in self rejected; opaque error, without a context-length explanation
num_return_sequences=3 with greedy decoding ValueError naming the constraint rejected with a useful reason
attn_implementation='flash_attention_2' ImportError: dependency not installed rejected with a useful reason
GPT-2 chat-template request ValueError: no template rejected with a useful reason
Gemma-2 template given a system role TemplateError: system role unsupported rejected explicitly
Static cache on Llama-3.2-1B, default generate BackendCompilerFailed: its default compilation path failed rejected because of an additional execution dependency
Tokenizing text to 5,002 tokens for TinyLlama (configured 2,048) tokenizer warning; all 5,002 token IDs returned warned; tokenization succeeded, no oversized forward pass was tested
temperature=0.7 with do_sample=False warning that flag may be ignored; result matched ordinary greedy warned and ignored a conflicting argument
Right-padded decoder-only batch of two warning; first row differed from solo/left-padded output warned; the request completed with incorrect padding semantics
Mistral-7B-v0.3 template given a system role text folded into first user turn, with no warning silent role flattening; independent system role not preserved
bfloat16 model load and 2,000-token prefill on SM 7.5 ran without warning, about 2.21× slower than fp16 silent performance cost, not evidence of dtype substitution
Llama-3.2 template given a system role native system header silent success, as requested
Static cache with compilation disabled matching tokens silent success, as requested

The thirteen probes comprise six errors, three warnings followed by execution or tokenization, and four cases without warnings. Among the latter four, native Llama system-role formatting and explicitly disabled static-cache compilation did what was requested; Mistral’s template flattened the system role into a user turn; and bfloat16 used the requested datatype but incurred a measured performance penalty. Calling all four “silent substitutions” would be false. The errors also vary in quality: the GPT-2 position failure supplies only an index exception, while the static-cache error reveals a compilation prerequisite that was not part of the user’s visible cache choice. TinyLlama’s tokenizer warning is not a measurement that its forward pass would fail; it says only that tokenizer output can exceed a configured model limit. The right-padding warning names a real hazard, but the observed first-row output still differed. A serving API should turn such warnings and exceptions into explicit contract decisions before enqueuing inference work.

Two silent cases deserve different remedies. Mistral’s template transformation retains the words of the supplied system instruction but not the independent role boundary the caller requested; a test that merely searches the rendered prompt for those words would miss the change. Such a template needs either an explicit compatibility contract or a rejected system-role request. The bfloat16 case is not a semantic substitution: the library did run with bfloat16 weights. On this RTX 2060 (compute capability 7.5) its best measured 2,000-token prefill time was 1.360 seconds versus 0.614 for fp16, approximately 2.21× slower. If a service promises a latency budget, that slowdown belongs in admission or cost estimation; without a promise, it is a performance caveat, not grounds to claim that the runtime ran a different dtype. Output equivalence between bf16 and fp16 was not assessed.

Admitting a request before any work is done

Admission: before any work is done

The original chapter argued for refusing unsupported combinations before work starts. The Lab turns that principle into a pure, rule-based preflight, not yet a real service gate. ModelSpec holds the extracted configuration facts; Request records prompt and maximum completion tokens, sampling flags, role requirements, batching/padding, dtype and an attention option; and RuntimeFacts supplies caller-provided knowledge of the available FlashAttention dependency, GPU compute capability, and chat-template behaviour. admit returns Decision(admitted, reasons, warnings) and accumulates all triggered reasons rather than failing at the first. In this laboratory, the rules inspect the supplied counts and booleans without loading a model; actual source-of-truth checks are a later obligation. An illustrative multi-rule rejection is:

decision = admit(spec, Request(prompt_tokens=1200, max_new_tokens=8, temperature=0.5), facts)
# Decision(admitted=False, reasons=[
#   "context: 1208 tokens exceed the 1024 positions of gpt2",
#   "sampling: temperature is set but do_sample is false, so the library would ignore it"])

The harness invokes admit on twelve requests based on the earlier probes; these are fixed examples, not independently held-out validation cases. The returned decisions are:

Request Laboratory decision
GPT-2, 1,200 prompt tokens plus 8 new reject: 1,208 exceeds 1,024 configured positions
TinyLlama, 4,000 prompt tokens plus 96 new reject: 4,096 exceeds 2,048 configured positions
Temperature set with greedy decoding reject: temperature would be ignored
Three return sequences with greedy decoding reject: needs sampling or beams
FlashAttention requested but dependency flagged unavailable reject
System prompt with GPT-2 and no chat template reject
System prompt with Gemma-2 and rejecting template reject
Right-padded batch of two reject: contract requires left padding
System prompt with Mistral-7B-v0.3 admit with warning: flattened into first user turn
bfloat16 on compute capability 7.5 admit with warning: may lack a fast path
Llama-3.2-1B, 40,000 prompt plus 100 new admit with warning: beyond 8,192 original RoPE reference positions; within configured 131,072
Plain Llama-3.2-1B request admit

The table yields eight rejects, three warning-admits, and one unqualified admit. The rules cover many of the observed tokenizer, sampling, template, padding, and dependency hazards, but they do not cover the static-cache compiler failure. They also do not prove that a 40,100-token request will fit in memory, meet a latency target, or produce a reliable answer: Chapter 23 found those to be separate questions. In this policy, exceeding a configured maximum is rejected; exceeding the original_max_position_embeddings field while staying within a shipped RoPE extension triggers a warning. That field is a reference parameter of the extension, not by itself a proof of the precise training window or a reason to distrust every extended position. A production system would need an explicit policy about warnings—whether they require caller acknowledgement—and would calculate true tokenized length including role delimiters and any reserved generation tokens.

Two limitations determine the next implementation step. First, RuntimeFacts is manually supplied, not discovered or verified. The flash_attention field is a boolean, not proof a compatible kernel works for this model’s shape and device; system_role is a declared value, not a rendered-template comparison; and a hardware generation alone is insufficient to predict the best dtype latency. A conformance suite should derive those facts from pinned software, attempt representative operations, and record evidence for each capability. Second, admission is narrower than the actual execution contract. It does not check available VRAM, concurrent reservations, context-dependent allocation peaks, scheduler limits, tokenizer/template versions, model-supported sampling modes, requested determinism, the static-cache compilation route, or semantic equality of the rendered prompt. The twelve examples were written around already observed failures, so good agreement with those examples is not an unbiased estimate of coverage. More complete admission must be driven by new negative tests and fail closed where capability or resource evidence is absent.

Reading a release as a matrix

Reading a release as a matrix

A compatibility matrix is more useful than a single “supported” flag. Useful dimensions include checkpoint revision, tokenizer and request format, hardware and precision, attention and cache strategy, sampling semantics, batching invariance, prefill/decode paths, supported operations, performance envelope, and missing service components. Two first-party open releases demonstrate why those dimensions must be explicit. Their README statements below are vendor declarations, not capabilities reproduced in this Lab.

The pinned DeepInfer README lists DeepSeek-V4.1-Flash as the supported model and NVIDIA SM100 GPUs and Huawei Ascend 950 NPUs as accelerator targets. Its documented features include optimized kernels, MoE/expert-parallel mechanisms, asynchronous scheduling, bounded sliding-window replay, and structured output. It limits its stated batch-invariant inference and deterministic sampling options to NVIDIA. The same README describes an offline inference release, not a complete online serving system, and lists a KV-cache system, prefill/decode disaggregation, and data-parallel replica load balancing among the required service components not included. “Supports the checkpoint” and “operates a production API with all serving functions” are therefore different matrix rows. This text describes only what the cited revision’s maintainers state; no DeepInfer run or capability probe was performed on the RTX 2060 used for this book.

OpenAI’s gpt-oss README states that the models were trained with the Harmony conversation format and warns that using another format will not work correctly. With Transformers, its chat template supplies Harmony; direct calls to generate need the caller to apply that format or use an appropriate Harmony library. The repository also distinguishes its educational/reference PyTorch, Triton, and Metal implementations from production-oriented serving integrations. Thus model support includes more than loading tensors: role and channel markers, tool-call framing, tokenizer/template compatibility, and an appropriate backend are part of the inference contract. The Lab did not load gpt-oss or test template failures; these are the authors’ claims. A practical service could verify round-trip formatting against a known Harmony fixture before admitting chat requests, instead of merely checking that a template exists.

PagedAttention, introduced by Kwon and colleagues at SOSP 2023, illustrates a primarily runtime-level innovation: organizing KV-cache memory into blocks for efficient allocation and sharing. The paper reports near-zero KV-cache waste and 2–4× throughput gains relative to its named serving baselines at comparable latency. Those are the authors’ system-level results, not measurements reproduced in this chapter. Chapter 14 checked a smaller, local preservation obligation for its own paged implementation (matching generated tokens and small logit differences). A production compatibility matrix needs both kinds of evidence: semantic conformance when an implementation changes cache layout, and separately benchmarked efficiency under declared load and hardware conditions.

What the numbers do not show

  • Small preservation corpus. Twelve book-derived 300-token prompts for the principal rows, twelve 1,200-token prompts for imposed windows, and three 12,000-token prompts for RoPE; 48 greedy tokens per prompt except 32 for the RoPE experiment. The groups are not fully matched and the resulting rates do not estimate broad reliability.
  • Token equality is weaker than equivalence. The logit comparison samples the prompt boundary only; sampling distributions, per-step logits, numerical tolerances across devices, and reproducible tie-breaking were not systematically tested.
  • Precision and quantization differ. The float32 checkpoint is loaded at higher precision than the fp16 baseline. Simulated int8/int4 rounds decoder linear weights but keeps fp16 execution; real quantized kernels, storage formats, scale choices and accumulated error remain untested.
  • The fallback sample mixes failures and successes. Six exceptions, three warnings and four unannounced outcomes were observed. Two silent outcomes fulfilled the request, one flattened a role, and one had a performance penalty; this is not thirteen genuine failures.
  • One software stack and one GPU. The results describe PyTorch 2.6.0, Transformers 5.17.0, and an RTX 2060 in the tested configuration. No cross-version, vLLM, SGLang, llama.cpp, or larger-model comparison was run.
  • No complete admission policy. admit does not actually interrogate runtime capabilities, does not reserve resources, and has no static-cache/compiler rule. The example decisions are not held-out validation.
  • Model identity is broader than ModelSpec. Weight digest, tokenizer revision, chat template, quantization format, special tokens, full positional parameters and per-layer configuration are not all captured or pinned; neither deployment nor checkpoint provenance is complete.

Inference Lab increment

The Lab now has:

  • fingerprint and ModelSpec: the extracted configuration subset—attention shape, nominal fp16 cache payload, configured positions, positional-extension type, window flag and local-layer count, softcapping presence and expert count. This is a partial architecture fingerprint, not a complete artefact identity.
  • Request, RuntimeFacts, admit, and Decision: a pure admission policy that reports all triggered reasons and warnings, based on supplied—not independently discovered—capability facts.
  • greedy, summarise_knob, first_divergence, and near_tie_share: a token-and-logit preservation harness; margins are measured at the first differing token.
  • fake_quantise_linears: simulated weight rounding in fp16, intentionally separate from genuine low-bit storage and kernels.
  • fingerprints, preservation, fallbacks, and admission: runnable experiments, plus tests of the pure rules and helpers.

The contract added by this chapter is: declare which computation a request requires, test whether an execution path implements it within stated numerical tolerances, and disclose any alternative that changes its meaning. A different numerical trace does not alone prove a changed mathematical function; matching a few greedy traces does not prove one was preserved. Capacity-based dropping, imposed windows, changed positional schemes, truncation, chat-template flattening, and new effective weights are examples that require explicit semantic treatment. Admission should name every failed capability and relevant resource limit before scheduling work; the current admit is the small, testable beginning of that gate, not a claim that such a complete service gate already exists.

What you should now be able to do

  • Read a config into a partial architecture fingerprint and identify which facts still require checkpoint, tokenizer and backend verification.
  • Design a preservation experiment that compares like-for-like prompts, token traces, baseline margins and logit tolerances; state the limits of greedy agreement.
  • Explain how a floating-point execution change can flip an argmax near a tie without necessarily changing the intended mathematical model.
  • Identify changes that alter effective weights, attention visibility, positional semantics, tokenized input or message roles—and therefore require explicit model/request policy.
  • Distinguish a rejected operation, a warning, a silent successful request, an undisclosed format transformation and a silent latency penalty.
  • Apply a pure rule-based admission function and name its missing facts, compiler/backend prerequisites, resource limits and conformance checks.
  • Read a vendor release as a matrix of declared support and omissions rather than as an unconditional production-serving guarantee.

Key terms

  • Architecture fingerprint: selected model-configuration requirements (heads, layers, positions, windows, RoPE, softcapping); a full identity additionally requires checkpoint and tokenizer/template provenance.
  • Execution conformance: evidence that a runtime implementation matches the specified model operation within stated numerical and behavioural tolerances.
  • Margin: the baseline top logit minus runner-up logit at a generated step.
  • Near-tie: a small measured margin where finite-precision changes can change greedy argmax; not an exact mathematical property inferred from a rounded zero.
  • Admission: checking a request against a model, backend and resource contract before scheduling execution.
  • Warning-admit: accepting a request while explicitly describing a risk or negotiated behaviour; it must not silently rewrite required semantics.
  • Silent substitution: an undisclosed change to requested meaning, such as flattening a separate system role into a user turn.
  • Capability matrix: a versioned table of supported model, hardware, format, operation and performance combinations with evidence.
  • Conformance test: an executable test that checks a claimed contract with specified preconditions and observable results.

Reader exercises

  1. Repeat the preservation table on Llama-3.2-3B with the same frozen prompt set, recording generated-token and per-step logit differences. Does a near-tie still explain every first divergence?
  2. Add speculative decoding and CUDA graphs (Chapters 17–18) to the same harness. Verify draft acceptance and cache-state equality, not only token traces.
  3. Add and test an admit rule for the static-cache/compiler dependency. Make it reject when compilation is required but unavailable, and admit when a tested noncompiling path is selected.
  4. Replace manually typed RuntimeFacts with versioned probes of the device, importability, actual attention kernels and rendered chat templates; deliberately inject stale facts and check that admission fails closed.
  5. Extend admission with reserved VRAM, peak-prefill estimates, number of concurrent requests and output-token budgets; compare decisions with later execution under changing load.
  6. Repeat the thirteen fallback probes on a second framework and version, explicitly separating successful requests from altered semantics and performance regressions.
  7. Add an MoE capacity limit, a system-role flattening template and an exact prefix truncation to the preservation harness. Which differences arise from model, input, or execution changes?
  8. Write a release manifest for int8 rounding, a 512-token imposed window and a changed RoPE variant, recording checkpoint and tokenizer hashes, configuration revision, treatment, input contract and evaluation evidence.

References

  • OpenAI gpt-oss repository — first-party README: Harmony response-format requirement, model/tool framing, and distinction between reference implementations and serving integrations; consulted 22–26 October 2026. The Lab did not run gpt-oss.
  • OpenAI Harmony format — first-party specification and renderer documenting message roles, channels and tool-related structure; used here to clarify why format compatibility is part of the model/input contract.
  • DeepInfer at pinned revision 774ce244 — first-party feature and hardware matrix for its documented release, including missing service components; not independently reproduced.
  • Efficient Memory Management for Large Language Model Serving with PagedAttention — Kwon et al., SOSP 2023; runtime memory management and the authors’ reported throughput comparison, not reproduced here.
  • PyTorch numerical accuracy guidance — documentation on finite-precision operation order and possible non-bitwise-identical results across algorithms, devices and builds.

Evidence in this chapter

Claim Evidence classification and qualification
Seven serving/precision rows matched 79 / 84 prompt-level traces; five first divergences had baseline margins of 0 or 0.015625 Local book measurement: Llama-3.2-1B, 12 prompts per row; not a general equivalence guarantee
Simulated int8 changed 4 / 12 traces, while int4 and both imposed 512-token windows changed 12 / 12 each and removing shipped RoPE changed 3 / 3 Local measurements with different prompt populations and treatments; only decoder linears were rounded
Maximum recorded end-of-prompt logit difference is 0.0273 across measured execution/precision rows, versus 0.4106–13.5469 for semantically changing rows Book result for one-step logits; static cache and padded batch have no logits comparison
Imposing a window longer than the prompt preserved 12 / 12 traces Local control: 1,200-token prompts under a 2,048-token window; not bitwise equality
Thirteen local probes produced six errors, three warnings and four no-warning cases Book result for this PyTorch/Transformers stack; includes two silent successful operations
Mistral’s rendered system text lost a separate role boundary; bfloat16 prefill ran approximately 2.21× slower than fp16 Local probe results; bf16 was not replaced by fp16, and no output-quality comparison was made
Right padding warned but produced a different first row from solo/left-padded generation Local result in one two-prompt example; mechanism not further isolated
Pure admit rejected 8 / 12 examples, warned on 3 and admitted 1 Book result; rules built from observed hazards and RuntimeFacts manually supplied; compiler failure not covered
DeepInfer’s supported model/hardware/options; gpt-oss requires Harmony Vendor README claims; not independently validated on this Lab’s hardware
PagedAttention reports near-zero cache waste and 2–4× throughput improvement Authors’ SOSP 2023 system evaluation, not repeated here
General cross-platform determinism, real low-bit kernels, full service admission, other serving stacks Not established by these experiments

Implementation status

  • Manuscript: content/books/inference/24-chapter.md
  • Runnable examples: examples/ch24/adapters.py (original adapters and strict unsupported-streaming example) and examples/ch24/contract_lab.py (configuration fingerprint, rule-based admission, preservation experiments and fallback probes)
  • Tests: tests/test_ch24_adapters.py, tests/test_ch24_contract_lab.py (configuration parsing, individual admission rules and combined reasons, divergence and margin summaries, quantization-grid properties; CPU-focused)
  • Recorded evidence: research/ch24/sources.md, research/ch24/results.json, research/evidence-register.md
  • Recorded experiment commands: python examples/ch24/contract_lab.py fingerprints, preservation, fallbacks, and admission
  • Repository verification command: python -m unittest discover -s tests -v; not rerun as part of this editorial pass

This chapter remains marked draft = false in its front matter but should not be described as fully qualified for production use. It establishes the semantics of the architecture/runtime boundary with one measured 1B checkpoint, local software-stack probes, and a tested pure admission function. It does not test other inference frameworks, robust batch-invariant kernels, production memory reservations, gpt-oss or DeepInfer execution, or long-context admission under concurrent serving load. Chapter 25 begins Part 5 by bringing these contracts into the inference loop and HTTP service, where a request must be validated, scheduled, executed, and accounted for separately.