Building Our First Inference Engine
Assemble tokeniser, backend, sampler, loop and record into one engine with a stable interface, check each replaceable part against a reference, and measure the baseline.
The first engine in this chapter had a bug that no single-request test could find.
To make sampling reproducible, it seeded a fresh random-number generator at every step with the request’s seed \(s\) plus the step number \(k\): seed \(s+k\). That looks harmless. But request seed 2 at step 0 and request seed 1 at step 1 both use the number 2. So do many other pairs:
| Request seed | Step 0 | Step 1 | Step 2 | Step 3 |
|---|---|---|---|---|
| 1 | 1 | 2 | 3 | 4 |
| 2 | 2 | 3 | 4 | 5 |
| 3 | 3 | 4 | 5 | 6 |
(Bold values occur more than once in this small table.)
Across 100 consecutive request seeds and 32 steps each, 3,200 request-step pairs collapsed to just 131 distinct seed values. On a fixed set of identical logits, the tokens sampled for seed 2 were an exact copy of seed 1’s, shifted by one step, at all 31 overlapping steps.
Nothing crashed. Each request was reproducible, the output looked plausible, and a test that ran the same request twice passed. The bug only showed up when you compared different requests with each other, which is exactly what matters for a service that hands out consecutive seeds. (What this experiment shows is deterministic seed aliasing. It does not measure real user traffic, statistical independence or output quality.)
That bug motivates this chapter’s design: an engine built from parts with explicit contracts, so that each part can be tested on its own and in combination, and so that every result carries evidence of what produced it. Those are goals, not guarantees. A reproducible wrong answer is still wrong, and two implementations agreeing on a small set of inputs is still limited evidence.
Where this sits
Chapters 1 to 5 built a request record, artefact identity, token selection, a hand-written GPT-2 forward pass, and a generation loop with stopping and decoding. This chapter connects them into Inference Lab engine version 0 and closes Part I.
Version 0 is a testable baseline, not a production server. It recomputes the full prefix every step and has no KV cache, batching or concurrent scheduling. The benchmarks use one CPU thread. (The real-model backend accepts a device argument, but nothing here qualifies it on a GPU.) Every later improvement will be compared against this baseline on the same workloads, with explicit acceptance criteria and honest timing uncertainty.
For the wider Pi series, what matters is the request/result contract. An agent does not need to know how logits are computed, but it does need to know which model and decoding policy ran, why generation stopped, and what was actually returned. Version 0 exposes that boundary locally. It does not yet offer a network API, full replay, cancellation or streaming transport.
Parts and contracts
The engine in examples/ch06/lab_engine.py is assembled from five parts:
| Part | Implemented contract | Responsibility |
|---|---|---|
| Request | Request(prompt, max_new_tokens, sampling, stop_strings, use_eos) |
Holds inputs and checks selected invariants at construction |
| Backend | encode(text), decode(ids), next_logits(ids), eos_token_id, manifest() |
Tokenisation, model execution and reported identity |
| Sampler | select(logits, config, step) -> int |
Greedy or seeded token selection, separate from the forward pass |
| Loop | Autoregressive Generation’s generate(...) |
Repeated scoring, token choice, EOS/stop-string handling and step measurements |
| Result | text, generated_ids, stop_reason, usage, timing, steps, provenance |
Captures the output and the subset of execution context currently recorded |
The examples provide two samplers (ListSampler, TorchSampler) and three backends (TableBackend, LibraryBackend, OracleBackend), so each boundary really can be swapped.
Boundaries reduce how much has to change together, but they do not remove shared obligations. A new backend can change token ids, EOS meaning, numerical precision or the context limit. A sampler depends on the shape and finiteness of the logits it receives. The loop decides which text becomes visible. A successful swap must keep those contracts, or renegotiate them openly, not just implement the right method names.
The request: checked when it is built
Request is a frozen dataclass with a __post_init__ check. Here is what it does and does not catch:
| Rejected at construction | Not yet checked |
|---|---|
max_new_tokens ≤ 0 |
Types (Python annotations are not enforced; True passes as an integer) |
| Temperature ≤ 0 for non-greedy sampling | Non-finite numbers such as NaN |
top_k < 1 |
top_k larger than the backend’s vocabulary |
top_p outside \((0,1]\) |
Sampling parameters when greedy=True |
| Empty stop strings | Contradictory or irrelevant field combinations |
Catching errors when the request is built, rather than halfway through generation, is a real improvement. But “an invalid request cannot exist” would overstate it; exercise 2 builds requests that slip through.
The selection policy is the SamplingConfig from Tokens, Embeddings and Probability: greedy, temperature, top_k, top_p, seed. With greedy=True the engine skips stochastic selection entirely, so a zero temperature is never divided by. Greedy is best thought of as its own named policy, not as \(T=0\) in the temperature formula.
The backend: everything model-specific, behind one door
The backend’s job is small: turn text into ids, ids into text, and a prefix into last-position logits. Three implementations:
| Backend | What it computes with | Use |
|---|---|---|
TableBackend |
The seeded transition table from What Is Inference?; no learned weights | Fast, controlled tests |
LibraryBackend |
A Hugging Face causal LM’s own implementation (here, pinned GPT-2 on CPU) | The real model |
OracleBackend |
The same GPT-2 parameters, through the hand-written forward pass from The Transformer as a Computation | An independent composition of operations to compare against |
(The oracle uses the same architecture, the same weights and PyTorch tensor operations. It is an independent route through the arithmetic, not an independent proof or an independently sourced model.)
What each backend reports about itself. Each backend returns a manifest():
- The toy reports only its backend name, seed, vocabulary size and simulated status.
- The library backend reports its implementation and version, model identifier, resolved snapshot directory, dtype, parameter device, SHA-256 values for five selected files, and a digest of the parameter tensors.
- The oracle reports the same, with its own backend and implementation labels.
manifest_sha256 is the SHA-256 of a canonical JSON serialisation of the manifest: a compact key for comparing runs. It is not complete. It does not cover every artefact file, the implementation source, runtime settings or other dependencies, and the code writes dtype as float32 rather than reading it. A self-computed hash is not proof of origin, and matching parameter digests do not establish tokeniser compatibility or buffer identity.
Two different questions. Comparing the library and oracle backends answers two separate questions:
| Question | Recorded answer |
|---|---|
| Do they choose the same tokens? | Yes on all four prompts tested: 32 identical greedy tokens each |
| Do their records claim the same execution path? | No: parameter digests match, manifest hashes differ, because the backend and implementation fields differ |
That second answer is the intended result: same weights, different route. But notice that a hash difference is only meaningful because we know which fields went into the hash. Two implementations can hash differently and produce identical output; two can hash identically after an implementation change the manifest does not record. So the manifest should eventually include a versioned implementation identity and a complete enough model and tokeniser record to tell materially different executions apart.
Agreement on four greedy 32-token trajectories is evidence, not proof of equivalence for all logits, prompts, hardware or decoding settings. Chapter 4’s logit comparison complements it. Neither replaces tests for near-ties, longer contexts, stochastic selection and future runtime variants.
Two samplers, one of them trusted
The Python-list sampler from Tokens, Embeddings and Probability is easy to read, which makes it a good behavioural reference. But sorting and renormalising 50,257 entries in Python is slow. So version 0 adds TorchSampler, which does the same work with vectorised PyTorch operations.
A faster replacement is only worth having if it chooses the same tokens. The experiment gives both samplers the same logits, configuration, seed and step, and compares the chosen ids across five policies (greedy; unfiltered sampling; temperature with top-k; temperature with top-p; temperature with both) and ten seeds per row:
| Logits | Rows | Configurations | Seeds | Comparisons | Mismatches |
|---|---|---|---|---|---|
| Random, vocabulary 5,000 | 40 | 5 | 10 | 2,000 | 0 |
| Real GPT-2, vocabulary 50,257 | 24 | 5 | 10 | 1,200 | 0 |
All 3,200 choices matched. Getting there required the same tie ordering, float64 arithmetic in the tensor sampler, identical derived seeds and the same cumulative-probability draw rule.
What the agreement does not cover. Every comparison used step 0, so the per-step seed derivation was not swept across a full trajectory. Both samplers come from the same code family, so they could share a mistake. And this is agreement on chosen ids, not a proof that the two produce the same distributions. Near-equal logits, ties after filtering, non-finite inputs, empty candidate sets and cumulative sums landing right on the random threshold all need dedicated edge-case tests (exercise 4). This matters because one differently sampled token changes everything that follows, and later benchmarks must report such divergences rather than mistaking them for model changes.
The seed defect, in detail
The fix. The code replaces seed + step with derive_seed(seed, step): the SHA-256 of the text form of the pair, truncated to 64 bits, used to seed Python’s generator for that step.
The test. Logits are held fixed at [2.0, 1.0, 0.5, 0.1], so any shifted pattern in the choices can only come from the seeding scheme:
| Scheme | Distinct derived seed values among 3,200 tested pairs | Shifted-choice matches, 31 comparisons |
|---|---|---|
Additive seed + step |
131 | 31 / 31 |
| SHA-256-derived 64-bit seed | 3,200 | 16 / 31 |
Reading the second row. With the hash, all 3,200 tested pairs got distinct seeds, and the shifted comparison matched at 16 of 31 positions (about 52%). How many matches would chance give? Two independent draws from these logits agree with probability \(\sum_i p_i^2 \approx 0.399\), so 16 of 31 is not obviously out of line. But 31 comparisons are few, and match frequency is a weak test of a random-number generator. The defensible claim is narrow: the hash scheme breaks the exact shifted-copy defect, with no collisions among these 3,200 seeds.
What hashing does not give you:
- Guaranteed distinct seeds. A 64-bit digest can collide; we only observed no collisions in a finite set.
- Statistically independent streams. That was not tested.
- Different streams for requests that use the same seed. Two requests given the same base seed still get identical streams (exercise 1).
The lesson. Both schemes pass the test “identical inputs give identical outputs”. The new regression tests also check that selected pairs do not alias and that the old shifted copy is gone. But the real lesson is not “hash your seeds”. It is that tests must look for unwanted relationships between executions, not just reproducibility within one. A perfectly reproducible engine can still have a perfectly reproducible cross-request bug.
For a serving runtime, the bigger design job is request-level ownership of random state: what happens when callers reuse a seed, how unique per-request streams are derived, whether concurrent scheduling changes the draws, and whether to keep one generator per request or create one per step. This chapter tests only a small part of that.
What the engine returns
Every call returns a Result. This is its current schema:
Result(
text, generated_ids, stop_reason,
usage = {prompt_tokens, completion_tokens, positions_processed},
timing = {total_seconds, forward_seconds, select_seconds, other_seconds},
steps = [...per-step records...],
provenance = {backend, manifest_sha256, manifest, sampler, sampling, loop},
)
Three parts deserve a closer look.
Usage separates output from work. completion_tokens counts generated ids; positions_processed adds up the full prefix length sent to the backend at every step. For a 17-token prompt and 32 steps, those are 32 and 1,040. One convention is not yet spelled out in the record: an EOS token can be counted in generated_ids but withheld from the text, and a stop string’s tokens can be generated and then removed from the text. A request record should state its token and text accounting explicitly.
Timing covers part of the request, and adds up by construction. The clock starts after the prompt is encoded:
Included in total_seconds |
Excluded |
|---|---|
forward_seconds (backend calls) |
Prompt tokenisation |
select_seconds (sampler calls) |
Building the Result and provenance record |
other_seconds = total − forward − select |
other_seconds is a remainder, so the three always sum to the total (a test checks this). But it is not purely “engine logic”: it includes decoding, stop matching, loop bookkeeping and call overhead. These boundaries need stating before anyone compares this number with end-to-end service latency.
Provenance is partial. It records the manifest and its hash, backend and sampler names, the sampling configuration and a description of the no-cache loop. It does not record the original prompt or its ids, stop_strings, use_eos, a hash of the code, all tokeniser and config files, or the full execution environment. All of those can change the result. So a Result on its own cannot yet be replayed exactly, and the manifest hash is a comparison aid, not proof of identity. Recording the canonical request alongside the result is the obvious next step (exercise 3).
Where a step’s time goes
What Is Inference? found token selection negligible next to the forward pass. That was with greedy selection. What about real sampling with filters?
The probe. 32-token GPT-2 generations, each sampler, two policies: greedy, and temperature 0.8 with top-k 40 and top-p 0.9. Each cell is one generation. The median columns are medians across steps; the share column is computed from sums across steps, so you cannot recompute it from the medians.
| Sampler | Rule | Median forward | Median selection | Selection share of step |
|---|---|---|---|---|
| List | greedy | 100.9 ms | 3.4 ms | 3.4% |
| List | T=0.8, k=40, p=0.9 | 107.4 ms | 47.7 ms | 32.5% |
| Torch | greedy | 103.5 ms | 3.5 ms | 3.2% |
| Torch | T=0.8, k=40, p=0.9 | 99.5 ms | 5.2 ms | 5.1% |
With filtering on, the Python-list sampler took 32.5% of forward-plus-selection time. The tensor sampler took 5.1%. Greedy was cheap in both.
So Chapter 1’s impression needs revising: selection cost depends on the configuration. Filtering and sampling across 50,257 logits is expensive in the reference implementation. And as model execution gets faster, selection’s relative share will tend to grow, by an amount that depends on the model, vocabulary, device and how logits are transferred.
The list sampler stays as the transparent reference. The tensor sampler is a candidate optimisation, with agreement evidence from the differential corpus and indicative timing from one run per cell. (The matched policies produced agreeing text prefixes, but this report does not itself prove the full sequences equal.) A proper benchmark would randomise run order, repeat each configuration and report distributions.
The baseline
The set-up. GPT-2 small; the 17-token prompt from Autoregressive Generation; 32 greedy output tokens; the tensor sampler; one warm-up request discarded, then three timed requests per backend. Time is the engine’s internal generation interval described above, so it excludes model loading and prompt tokenisation.
| Backend | Runs (s) | Median | Tokens/s | ms per token |
|---|---|---|---|---|
| Library | 3.94, 4.12, 4.64 | 4.12 s | 7.8 | 129 |
| Oracle | 4.98, 7.07, 7.36 | 7.07 s | 4.5 | 221 |
What it shows. Each 32-step run processed 1,040 token positions, against 48 distinct positions by the final step: a 21.7× recomputation ratio (1,040 / 48). That is a work count, not a measured cache speed-up. Both backends produced identical ids across their repeated runs (which says nothing about the quality of those ids).
What it does not show. Three runs per backend cannot rank them. The library median was 4.12 s and the oracle’s 7.07 s, but the oracle ranged from 4.98 to 7.36 s, and in earlier equivalence runs it was sometimes close to the library. Environmental noise, memory allocation and implementation differences could all contribute, and none was isolated. What this baseline supports is a scale: several seconds for 32 uncached tokens on this CPU. Keep the raw samples, and rerun under controlled conditions before claiming a winner (exercise 8).
Numbers from Part I that do not agree
Several figures in Chapters 1–6 describe similar things and differ, sometimes by large factors. They come from different code paths, prompts, processes and sessions, and none of the differences has been investigated, so do not combine them:
| Quantity | One measurement | Another measurement | Likely differences (not verified) |
|---|---|---|---|
| 16 uncached GPT-2 tokens, CPU | About 2.7 s per request (What Is Inference?) | 1.98 s median (Autoregressive Generation) | Different harness and session |
| First-forward penalty | About 270 ms (403 vs 132 ms, Chapter 1) | About 51 ms (154 vs 103 ms, From Training to Execution) | Different prompt length and timing boundary |
| Greedy selection per token | 0.40 ms median (Chapter 1 sample stage) |
3.4 ms median (ListSampler, this chapter) |
Different implementation: Python-list sampler over 50,257 values |
Reconciling these is part of the whole-book review; until then, quote each number with its chapter and harness.
Inference Lab increment
Version 0 exposes a small local Python interface (a demonstration, not a stable network API):
engine = Engine(backend, sampler)
result = engine.generate(Request(prompt, max_new_tokens=32, sampling=SamplingConfig(...)))
It assembles Part I: timing and stage separation from What Is Inference?, partial artefact identity from From Training to Execution, deterministic selection from Tokens, Embeddings and Probability, the GPT-2 reference from The Transformer as a Computation, and stopping and decoding from Autoregressive Generation. Assembly is not completion; Chapter 5’s edge-case defects still apply.
The acceptance ladder. From now on, any replacement part has to climb these rungs in order:
- It passes the interface and request-validation tests.
- It matches the reference on relevant deterministic and numerical cases, within stated tolerances.
- It passes the streaming, stop, EOS and provenance regressions.
- Only then is its performance measured against a reproducible baseline.
Some optimisations, such as quantisation, legitimately change logits or even tokens. They need their own accuracy and behaviour criteria, rather than being treated automatically as “a different model”.
What version 0 does not do. This list is both the scope boundary and the backlog for later chapters:
- No KV cache. The prefix is recomputed every step (Key-Value Caching).
- No batching or concurrent scheduling. One generation per call (Continuous Batching, Request Scheduling and Admission Control, Concurrent Requests and Streaming).
- No GPU qualification. Accepting a
deviceargument is not validation (Matrix Multiplication and GPU Execution onwards). - No streaming from
Engine.generate. The underlying loop has anon_texthook, but the engine does not forward it, and there is no network stream (Concurrent Requests and Streaming). - No cancellation, timeouts or back-pressure (Reliability, Cancellation and Recovery).
- No per-request memory measurement. Usage counts tokens and positions, not memory.
- No complete replay record. Prompt ids, EOS and stop-string policy and some execution details are missing from
Result. - No full artefact compatibility check. Selected file hashes and a parameter digest are reported, but tokeniser–weight pairing and implementation identity are not enforced.
- No comprehensive input validation. Freezing the dataclass prevents changes after construction; it does not prevent bad values going in.
Limits of this chapter’s evidence
About the set-up
- One GPT-2 snapshot, one CPU environment. Other models and hardware may change both speed and numerical behaviour.
- One main prompt and few repetitions. Three requests per backend for the baseline, one trajectory per overhead cell. No ranking is justified.
About the comparisons
- The sampler corpus is finite. 3,200 matching choices, all at step 0; sequence-level and edge-case equivalence not established.
- The backend comparison is narrow. Four greedy prompts of 32 tokens do not establish identical distributions or kernels.
- Seed uniqueness was observed, not guaranteed. No collisions among 3,200 hashed values; independence, collision-freedom and distinct streams for repeated caller seeds are not established.
About the record
- The timing boundary excludes encoding and reporting, so
total_secondsis not arrival-to-response latency. - Manifest and request records are incomplete. File hashes do not establish provenance, and a
Resultcannot replay every input. - No quality or robustness evaluation. Two implementations agreeing can reproduce the same errors, and some numerical approximation may be acceptable under explicit tolerances.
What you should now be able to do
- Sketch the five engine boundaries and the assumptions passed between tokeniser, backend, sampler and loop.
- Say which
Requestfields are actually validated, and build a malformed request the current code accepts. - Explain why reproducibility within one request is different from distinct seeds across requests, and both are different from statistical independence.
- Compare a reference and a candidate sampler on matched logits, and say what 3,200 matching choices cannot establish.
- Distinguish parameter identity, manifest identity, implementation identity and agreement of outputs.
- Reconcile generated-token counts with visible text when EOS or a stop string ends a request.
- Describe exactly what
Engine.generatetimes and what it leaves out. - State an honest CPU baseline, with its sample count, warm-up procedure, uncertainty and what was not measured.
Part I is complete: we have a working, inspectable engine and an honest baseline for it. Its most striking number is the recomputation ratio: of the 1,040 token positions processed per request, only 48 were new. Before fixing that, Part II looks at the hardware doing the work. Matrix Multiplication and GPU Execution starts with matrix multiplication, the operation behind most of the forward pass’s arithmetic, and with how to time a GPU without fooling yourself.
Key terms
- Engine: the component that coordinates request validation, backend execution, selection and result construction.
- Backend: the model/tokenizer adapter exposing ids-to-logits execution and a partial manifest.
- Manifest: a canonical, hashable record of selected artefact and implementation fields; not an attestation of source.
- Provenance: recorded context about an execution, useful only to the extent that relevant inputs and software are captured.
- Differential test: evaluating candidate and reference on matched inputs and comparing observable behaviour.
- Oracle: a slower, inspectable reference whose own correctness and coverage must also be assessed.
- Seed aliasing: distinct logical random draws being initialised from the same derived seed.
- Derived seed: a deterministic transformation of a base seed and step, which may reduce collisions without guaranteeing independence.
- Baseline: a measured implementation/workload pair with a documented environment and measurement boundary.
- Positions processed: total token positions presented to a backend across generation steps; not itself a latency measurement.
- Replay record: enough canonical request, artefact, policy and environment data to attempt to reproduce a prior execution.
Reader exercises
- Reintroduce
seed + stepand reproduce the 31-for-31 shifted-copy result. Then check what happens if two requests deliberately use the same base seed under the hash-derived scheme. Specify the request-identity policy needed for unique streams. - Add negative tests for
max_new_tokens=True,temperature=float("nan"), wrongstop_stringstypes andtop_klarger than the vocabulary. Decide which layer should reject each case and at what point. - Add canonical prompt text or prompt ids,
stop_stringsanduse_eosto the result’s replay metadata. Prove that modifying one of these fields changes the replay identifier while preserving separate implementation and artefact identities. - Run the samplers on exact ties, near-ties, repeated
stepvalues, non-finite scores and top-p thresholds at cumulative-mass boundaries. Which failures should be rejected versus compared within tolerance? - Configure two backends with different numerical dtypes. Compare logits as well as greedy ids on several prompts, and explicitly report the first divergence instead of assuming different logits mean a different artefact.
- Check EOS and a stop string that begins before an EOS event. Verify that
text,generated_ids,completion_tokensand any streaming callback have coherent termination semantics. - Time encoding, generation, provenance construction and JSON serialisation separately, then compare their sum with an end-to-end wall-clock timer around the whole call.
- Run the baseline at least ten times in randomised backend order, once on a quiet machine and once under load. Report raw timings, median, spread, processor thread count and warm-up policy.
- Implement a backend that supports several requests in one batch. Describe which parts of the current
next_logits(ids)contract andpositions_processedaccounting need revision before the results are comparable.
References
- Yu et al., Orca: A Distributed Serving System for Transformer-Based Generative Models (OSDI 2022) — shows why autoregressive requests need iteration-level scheduling and why scheduling is distinct from the per-token model computation. Version 0 implements neither scheduling nor selective batching.
- Kwon et al., Efficient Memory Management for Large Language Model Serving with PagedAttention (SOSP 2023) — explains why KV-cache memory management determines batch capacity and serving throughput, a capability deliberately absent here.
- Zheng et al., SGLang: Efficient Execution of Structured Language Model Programs (NeurIPS 2024) — motivates the separation between application-level generation programs and a runtime with reusable state and structured output mechanisms.
- deepseek-ai/DeepInfer, repository at pinned commit
774ce244— implementation context, not a peer-reviewed research paper. Its supported models and hardware must be established from the pinned version before claiming comparability.
These references motivate the architecture and later improvement programme; they do not validate this chapter’s seed experiment, sampler comparison or CPU timings, which come from the repository’s own recorded runs.
Evidence in this chapter
| Claim | Evidence classification |
|---|---|
| Separating model execution, request scheduling and memory management is useful in serving systems | Established background; Orca, PagedAttention and SGLang |
Additive seed + step produced 131 distinct seed integers among 3,200 pairs and 31/31 shifted choices |
Book result; arithmetic and controlled sampling |
Hashed (seed, step) produced 3,200 distinct 64-bit values in this tested set and 16/31 shifted matches |
Book result; finite observation, not independence proof |
ListSampler and TorchSampler chose the same token in 3,200 recorded comparisons |
Book result; matched logits, five policies, ten seeds, step 0 |
| Library and oracle generated the same 32 greedy ids on four prompts | Book result; agreement on sampled trajectories, not complete equivalence |
| Library and oracle have equal parameter digests but different manifest hashes | Book result; manifest fields are intentionally different |
| List selection was 32.5% and tensor selection 5.1% of step forward-plus-selection time under the filtered policy | Book result; one generation per table cell |
| Library median baseline 4.12 s for 32 uncached tokens | Book result; three noisy CPU runs, internal generation-time boundary |
| Engine timings cover the full request including tokenisation and provenance | Not implemented; the timer begins after encoding |
| Result contains every input needed for complete replay | Not implemented; request and environment fields are missing |
| Seed derivation guarantees independent random streams for different requests | Not established, and repeated base seeds reproduce the same stream |
| A particular backend is faster, a particular sampler improves output quality, or GPU/production behaviour transfers | Not established or not measured |
| Stop-string/EOS streaming semantics are correct for all chunkings and terminations | Not established; additional regression coverage required |