Example

Follow one request through every inference stage

Run a deterministic toy request and separate what the pipeline measures from the model computation it only simulates.

A request is not one operation. It is parsed, tokenised, encoded, run through a model many times, decoded and formatted, and each stage has a different owner and a different failure mode. This example makes those boundaries visible with a generator small enough to read in one sitting. Its “forward pass” is a seeded table lookup, not a neural network, so the timings measure the surrounding pipeline rather than a model.

The useful outcome is not a tokens-per-second figure. It is the stage list and the deterministic token sequence, plus an explicit statement of which stages are simulated. That distinction is the first discipline the rest of the book relies on: a pipeline that reports a time has not thereby shown that a model ran.

Run it

From a clone of the canonical repository at commit f958967d70992d7b09d9c75000bd8c543f1644d4:

python examples/ch01/inference_stages.py "Hello" --max-new-tokens 8 --json

Python 3.11 or later is sufficient; this path uses the standard library only. It needs no network, GPU, model download or credentials, and finishes in well under a second. Omit --json for the same stages as labelled lines.

Implementation

The whole mechanism is one loop. Parsing, tokenisation and encoding happen once; forward_pass and sample happen once per generated token. The three names in simulated_stages are a promise about what did not happen.

    def generate(self, prompt: str, max_new_tokens: int) -> GenerationResult:
        if max_new_tokens < 1:
            raise ValueError("max_new_tokens must be positive")
        timings: List[StageTiming] = []
        simulated = ["forward_pass", "sampling_distribution", "kv_cache"]

        start = _now()
        # Stage 1: request parsing / validation.
        cleaned_prompt = prompt
        timings.append(StageTiming("request_parse", _now() - start))

        start = _now()
        prompt_tokens = self.tokenizer.tokenize(cleaned_prompt)
        timings.append(StageTiming("tokenize", _now() - start))

        start = _now()
        prompt_ids = self.tokenizer.encode(cleaned_prompt)
        timings.append(StageTiming("encode", _now() - start))

        generated_ids: List[int] = list(prompt_ids)
        for _ in range(max_new_tokens):
            start = _now()
            # Simulated forward pass: table lookup plus a softmax over a tiny
            # vocabulary.  This is O(vocab) and has no learned parameters.
            previous_id = generated_ids[-1] if generated_ids else 0
            logits = self._logits(previous_id)
            # Numerically stable softmax.
            maximum = max(logits)
            exps = [math.exp(value - maximum) for value in logits]
            total = sum(exps)
            probs = [value / total for value in exps]
            timings.append(StageTiming("forward_pass", _now() - start))

            start = _now()
            # Greedy selection with a deterministic tie-break by smallest token id.
            next_id = min(range(len(probs)), key=lambda i: (-probs[i], i))
            generated_ids.append(next_id)
            timings.append(StageTiming("sample", _now() - start))

Expected outcome

Observed on this machine with the command above (exit 0). The token sequence and the simulated-stage list are stable; the timing values are not, and are omitted here rather than presented as portable numbers.

  "text": "HelloRWPFdyxf",
  "simulated_stages": [
    "forward_pass",
    "sampling_distribution",
    "kv_cache"
  ],

The generated ids were 43, 48, 41, 31, 3, 24, 23, 5. The prompt was tokenised one character at a time by the toy vocabulary, so the eight generated characters are appended to the five prompt characters. The stage order in the JSON was request_parse, tokenize, encode, eight pairs of forward_pass and sample, then decode and response_format. The whole request took tens of microseconds on this machine; that figure belongs to this trace, not to a model.

Mechanism and limitations

Documented: the module defines a TokenGenerator protocol with a generate method, and the toy generator is deterministic for a fixed prompt, seed and token count. The README says the forward pass, sampling distribution and KV cache are simulated. The automated test file checks determinism, stage presence and non-negative durations, correct rejection of max_new_tokens=0, JSON serialisation, and the even-count median rule.

Observed: the command exited 0; the JSON contained the stable text HelloRWPFdyxf and the three simulated stage names above. The targeted test command python -m unittest tests.test_ch01_inference -v ran 13 tests and reported OK. No model weights were loaded.

Not shown: anything about a learned model’s latency, memory, quality or throughput; any benefit from a KV cache; any multi-request behaviour; any GPU effect. The toy forward_pass is a table lookup, so its share of request time cannot be transferred to a transformer. The timings include Python and process overhead, and a different interpreter or machine will produce different numbers.

Challenge this result

Run the same command with --seed 8 and then with the prompt é. Before running, predict which change alters the generated characters, which alters the stage list, and which raises an error. The second prompt is outside the toy vocabulary, so a successful run would contradict the tokeniser contract. Then replace the greedy choice with a fixed token id and explain why the pipeline is still described as inference even though no probability was consulted.

Source and verification

Canonical source: examples/ch01/inference_stages.py at commit f958967d70992d7b09d9c75000bd8c543f1644d4. Tests: tests/test_ch01_inference.py . Chapter: What Is Inference? . The run above is a fresh local execution on Windows 11 with Python 3.13.15; it is not the chapter’s recorded real-model measurement.

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.