Assemble a request, a backend and a sampler into an engine
Run the first Inference Lab engine on a toy model and see which decisions belong to the request, the backend and the decoding loop.
An inference engine is not a model. It is the code that turns a validated request into calls on a model-specific backend, chooses tokens from the returned logits, and packages a result with a stop reason and timings. The model can be swapped without changing the request contract; the sampler can be swapped without changing the backend.
This example runs the first engine of the book’s Inference Lab. The backend is a
tiny causal transformer, not GPT-2, and the vocabulary is characters. The point
is the boundary: Request carries the decoding policy, ToyBackend hides the
model, and InferenceEngine owns the loop. The output is deterministic for the
given seed, so a change in one layer can be attributed rather than guessed.
Run it
From the canonical repository at commit
f958967d70992d7b09d9c75000bd8c543f1644d4:
python examples/ch06/engine.py --prompt abc --max-new-tokens 6 --seed 7 --jsonPython 3.11 or later with PyTorch. The default backend is the toy transformer: CPU-only, seeded, no model download, network, GPU or credentials. It finishes in under a second.
Implementation
The loop encodes the prompt once, then calls the backend with the growing id
sequence, samples one token, and records the per-token time. The stop reason is
max_tokens unless an EOS id was supplied and chosen. The backend protocol is
three methods: encode, forward and decode.
class InferenceEngine:
def __init__(self, backend: ModelBackend) -> None:
self.backend = backend
self.sampler = Sampler()
def generate(self, request: Request) -> Result:
if request.max_new_tokens < 1:
raise ValueError("max_new_tokens must be positive")
ids = self.backend.encode(request.prompt)
generated: List[int] = []
per_token: List[float] = []
stop_reason = "max_tokens"
start_total = time.perf_counter()
for step in range(request.max_new_tokens):
step_start = time.perf_counter()
logits = self.backend.forward(ids + generated)
next_id = self.sampler.sample(logits, request, step)
generated.append(next_id)
per_token.append(time.perf_counter() - step_start)
if request.eos_token_id is not None and next_id == request.eos_token_id:
stop_reason = "eos"
break
total_seconds = time.perf_counter() - start_total
all_ids = ids + generated
tokens = [self.backend.decode([i]) for i in generated]
text = self.backend.decode(all_ids)
return Result(
prompt=request.prompt,
generated_tokens=tokens,
generated_ids=generated,
text=text,
total_seconds=total_seconds,
per_token_seconds=per_token,
stop_reason=stop_reason,
metadata={
"backend": type(self.backend).__name__,
"temperature": request.temperature,
"top_k": request.top_k,
"top_p": request.top_p,
"seed": request.seed,
},
)Expected outcome
Observed with the command above (exit 0). Selected stable fields:
"prompt": "abc",
"generated_tokens": [
"i",
"g",
"m",
"r",
"m",
"p"
],
"text": "abcigmrmp",
"stop_reason": "max_tokens",The prompt is three characters and the engine generated six more. The backend
metadata names ToyBackend; temperature 1.0, no top-k or top-p, seed 7. The
per-token timings are omitted because they vary, and they include the whole
forward call plus sampling, not a separated model time.
Mechanism and limitations
Documented: Request validates the decoding policy fields and rejects a
non-positive token limit. ToyBackend builds a one-layer TinyTransformer with
d_model=16, two heads and a 32-character vocabulary, and calls it under
torch.no_grad(). Sampler.sample applies temperature, optional top-k and
top-p, then samples from the resulting distribution. The tests cover a smoke
run, a three-token request, invalid token counts, the benchmark loop and JSON
serialisation.
Observed: the command exited 0 with the six tokens and max_tokens above.
The targeted tests.test_ch06_engine is part of the canonical suite; the run was
not repeated separately in this session, so no independent test count is claimed
here.
Not shown: a real model, a KV cache, batched requests, concurrent access,
streaming, cancellation, or a production sampler. The toy backend re-runs the
whole sequence on every step, so its per-token time is not a decode benchmark.
The engine’s Request is an in-process object, not an HTTP contract; Chapter 25
adds that boundary.
Challenge this result
Run the same command with --temperature 0.01 and then --top-k 1. Predict
whether the generated text changes and whether the stop reason can change. Then
set --seed 8; the backend weights change, so the output should change even
though the request shape is identical. Explain which of those changes is a
decoding-policy change and which is a model change, and why the result’s
metadata must record both.
Source and verification
Canonical source:
examples/ch06/engine.py
at commit f958967d70992d7b09d9c75000bd8c543f1644d4. Tests:
tests/test_ch06_engine.py
.
Chapter: Building Our First Inference Engine
.
The run above is a fresh local execution on Windows 11 with Python 3.13.15 and
PyTorch 2.6.0+cu124; it uses the toy backend.
Understand this example
Copy this prompt into your AI tool. No code runs here.
Apply this example
Copy this prompt into your AI tool. No code runs here.