← Inference From First Principles

Autoregressive Generation

A forward pass becomes a sequence: the cost of the loop, why checking is cheaper than producing, and how to stop and stream without corrupting the text.

Here is an experiment with a surprising result. GPT-2, on a CPU with no cache, generated 64 tokens greedily. That took 11.49 seconds. Then I took the 17-token prompt plus the 64 tokens it had just produced, and fed all 81 tokens to the same model in one forward pass. That took a median of 0.419 seconds over five timed calls, about 27 times faster. And at every one of the 64 positions, the model’s top choice in the single pass matched the token the slow loop had chosen.

So the model can check 64 tokens in a fraction of the time it took to produce them. Why?

There are three reasons, and the experiment does not separate them:

  • The slow loop had no cache. Every step reprocessed the whole sequence so far: 3,104 token positions in total, against 81 in the single checking pass, a factor of about 38. This is probably the largest part of the gap.
  • Producing is serial; checking is not. To choose token 50 the model needs token 49. But once all the tokens are known, a causal transformer can score every position at once, because each position only looks backwards.
  • Fixed per-call overhead is paid 64 times by the loop and once by the check.

So the 27× compares two deliberately different workloads; it is not a speed-up for any real engine. A cached generator would remove much of the gap; how much remains is a question for Key-Value Caching.

This chapter puts the forward pass from The Transformer as a Computation inside a generation loop. It measures what the naive loop costs, explains why checking is cheap, and then deals with two jobs that are easy to get wrong:

  • stopping in exactly the right place;
  • streaming text to the client without corrupting it.

A correct token choice is necessary but not sufficient for a correct response. How the engine handles the end-of-sequence token, hides partial stop strings, turns tokens back into text and delivers it can all change what the client actually receives.

Where this sits

What Is Inference? introduced the loop, Tokens, Embeddings and Probability defined how a token is chosen, and The Transformer as a Computation opened up the forward pass. Here they come together in one interface, generate. It takes:

  • prompt token ids;
  • a callback that returns next-token logits;
  • a decoding function;
  • a token limit;
  • optional end-of-sequence (EOS) id and stop strings;
  • an optional selection hook.

It records the chosen ids, timings per step, the emitted text and a stop reason: eos, stop_string or max_tokens. Timeouts, cancellation and a full sampling configuration are not implemented yet.

The Inference Lab gains this loop contract plus two helpers: StopStrings, which hides text that might be the start of a stop string, and IncrementalDecoder, which turns a growing list of token ids into readable text. Both are small reference mechanisms with known gaps, which the chapter names.

Why does this matter beyond model serving? An agent may use Observation: as a stop string to end its action text, and a user interface expects a steady stream of readable characters. If the engine leaks the start of a stop marker, drops buffered text at the end, or forgets to send the final piece to the client, the agent or user sees a protocol failure that looks like a model failure.

The loop

The rule. Let \(s_t\) be the token sequence after \(t\) steps, starting from the prompt \(s_0\). One step is:

\[ z_t = f_\theta(s_t)_{\text{last}}, \qquad x_{t+1} = \operatorname{select}(z_t), \qquad s_{t+1} = s_t \,\Vert\, x_{t+1} \]
In words: run the model \(f_\theta\) on the sequence so far, take the logits at the last position, choose a token with the decoding rule, and append it.

The input to the next step includes the token just chosen. That is the serial decision dependency. It does not stop hardware from doing useful work on guesses about what comes next: blockwise and speculative methods propose tokens early and then verify them. But the dependency still decides which tokens are finally accepted.

Generation is serial in choosing, parallel in scoring

What the loop has to remember. Mathematically, the state is just the accepted token sequence, plus the model and decoding rule. In practice an engine also keeps cached keys and values, position information, random-number state, how much text has been emitted, any held-back stop-string text, and resource limits. A KV cache avoids recomputing earlier keys and values; it should give the same results to within an agreed numerical tolerance, though exact equality is not automatic across kernels or precisions. And the sequence cannot grow for ever: GPT-2’s position limit has to be enforced at some point. This chapter studies the no-cache baseline; Key-Value Caching tests the cache.

What the naive loop costs

In examples/ch05/real_generation.py, every step sends the entire sequence so far to GPT-2 and keeps only the last row of logits. Nothing is reused.

Counting the work. Starting from \(P\) prompt tokens and generating \(n\) new ones, the loop processes \(P\) positions, then \(P+1\), then \(P+2\), and so on:

\[ \sum_{k=0}^{n-1} (P + k) = nP + \frac{n(n-1)}{2} \]
An ideal engine would process each position once: \(P\) for the prompt, then one new position per further step, \(P+n-1\) in total. The ratio of the two counts, which we call the **position-recomputation factor** (labelled *waste factor* in the table), shows how much the naive loop repeats itself.

The measurement. Same 17-token prompt, different generation lengths:

New tokens Median total time Positions processed If each token once Waste factor ms per position
8 0.97 s 164 24 6.8 5.9
16 1.98 s 392 32 12.2 5.0
32 4.25 s 1,040 48 21.7 4.1
64 11.16 s 3,104 80 38.8 3.6
128 28.54 s 10,304 144 71.6 2.8

Each time is the median of two runs; full timings are in research/ch05/results.json. The last column is simply total time divided by positions processed, a convenient summary rather than a claim that every position costs the same.

What the table shows.

  • Repetition grows fast. The waste factor rises from 6.8 at 8 new tokens to 71.6 at 128. The naive loop processes \(O(nP+n^2)\) positions. And that is only a count of positions: because each pass also recomputes full \(T\times T\) attention, the total arithmetic can grow faster still, up to cubic in \(n\).
  • Time grows more slowly than positions. From 8 to 128 tokens, positions processed grew about 63-fold but time grew only about 29-fold, so time per position fell from 5.9 to 2.8 ms. Two explanations fit: larger matrix operations may use the CPU more efficiently (consistent with, though not established by, the timings in The Transformer as a Computation), and a fixed per-call overhead is spread over more positions. This run did not measure CPU utilisation or memory traffic, so it does not decide between them.

What it does not show. Nothing here measures a cached loop. Dividing these times by the waste factor would not predict cached performance: cache maintenance, memory traffic, one-token matrix shapes and attention over the stored history all change the cost. The cached comparison is NOT_RUN in this chapter and is the starting point of Key-Value Caching. Memory Bandwidth and Compute Bottlenecks then turns counts into time and bandwidth estimates.

Naive loop cost: waste factor and drift

How each step’s latency changes

A separate 64-token run timed every decode step individually, after one discarded warm-up pass. (Three separate runs generated 64 tokens from this prompt: 11.16 s in the scaling table (median of two), 11.49 s in the verification run, and 14.54 s here, where every step was also timed individually. Treat them as different runs; their spread is a reminder that single runs on this machine vary by tens of per cent.)

Quantity Value
Time to first token (forward pass over 17 positions) 125 ms
Median inter-token time 187 ms
95th percentile inter-token time 413 ms
Maximum 460 ms
Median, first half of steps 147 ms
Median, second half of steps 284 ms
Fitted drift 4.3 ms per step
Overall rate 4.4 tokens/s

Steps got slower as the sequence grew: the median rose from 147 ms in the first half to 284 ms in the second, and a straight-line fit gives a slope of about 4.3 ms per step. That is what you would expect when every step reprocesses a longer sequence.

This changes how to read the percentiles. The 95th percentile, 413 ms, is a valid summary of the observed intervals, but it mixes two things: steady growth with sequence length, and ordinary run-to-run variation. A percentile alone cannot tell you why the slow steps were slow. So when comparing engines, report the step index or context length alongside p50 and p95, and keep the first token separate from later steps.

Two warnings for later chapters. First, a KV cache removes the repeated prefix work, but each step still attends over a growing history, so a flat latency profile is something to test, not assume. Second, the 125 ms “time to first token” here is only the first step’s computation. Real service time to first token also includes tokenisation, queueing, dispatch and delivery, none of which were measured.

Why checking is cheaper than producing

Now back to the experiment that opened the chapter.

The set-up. Generate 64 tokens greedily with no cache. Then feed the prompt plus all 64 generated tokens to the model in one forward pass, and compare its top choice at each of the 64 prediction positions with the token actually generated. (Only 80 positions are needed for those 64 comparisons; the measured pass included the final generated token too, making 81. The last row was computed but not used.)

Time
Generate 64 tokens serially (no cache) 11.49 s
One forward pass over the 81-token sequence (median of 5) 0.419 s
Ratio 27×
Positions where the argmax equals the generated token 64 of 64

Why it works. Causal masking means the prediction at each position depends only on earlier tokens. So when all the tokens are already known, every position can be scored at once, and the answers are the same predictions the serial loop made one at a time. All 64 top choices matched.

What it does and does not prove. The top token ids matched. The experiment did not check whether the full logit vectors were bit-for-bit identical between the two execution shapes, and it says nothing about cached or fused kernels. (The masked-prefix test in The Transformer as a Computation looked at exact equality on one fixed execution path.)

Why it matters: proposing versus verifying. If something cheap, such as a small draft model or a heuristic, can propose several tokens, the large model can verify them all in one pass:

  • With greedy decoding, the verifier keeps the longest run of proposed tokens that match its own top choices.
  • With sampling, comparing top choices is wrong. Exact speculative sampling uses a specific acceptance-and-correction rule that preserves the target model’s distribution.

Blockwise parallel decoding (Stern et al., 2018) and speculative decoding (Leviathan et al., 2023) formalise these ideas. Note the related distinction: prompt tokens are known in advance, so they are processed together during prefill; new tokens are produced one by one during decode.

The 27× compares an uncached serial loop with one warmed forward pass, on one CPU and one prompt. It is not the speed-up of speculative decoding, and not what a production server would see. What the experiment supports is narrower: the harness reproduced all 64 greedy choices, a causal forward pass scored known positions together, and the real question for later is whether proposing and checking blocks beats a properly cached baseline. That has not been measured here.

Stopping

Generation can end for four kinds of reason, decided by different parties:

Reason Who decides Nature
End-of-sequence token The model A token the model chooses to emit
Token limit The request A resource limit
Stop string The decoding policy A condition on the decoded text
Timeout or cancellation The service An external signal

The current generate implements the first three and checks them during normal generation. Timeout and cancellation are requirements, not yet working code; the function has no input for them and can only return eos, stop_string or max_tokens.

When cancellation is added, note one subtlety. In a synchronous loop like this one, a service can only check for cancellation between steps, and a forward pass that has already started may run to completion. So the delay before cancellation takes effect is up to the rest of the current step, plus scheduling and clean-up, not necessarily a whole step. Reliability, Cancellation and Recovery adds and tests these states.

How often does the model choose to end?

The question. Will GPT-2 choose its end-of-text token (id 50256) before hitting the limit?

The experiment. Six prompts, each run greedily for at most 64 steps. The prompts included a document ending and a chat-like transcript.

Prompt style Stop reason Maximum P(EOS) over the run Best rank of EOS
Document ending (“All rights reserved.”) max_tokens 0.117 2
Chat transcript max_tokens 0.007 2
Question and answer max_tokens 0.021 2
List max_tokens 0.012 3
Story opening max_tokens 0.002 40
Code max_tokens 0.004 3

In all 384 steps, <|endoftext|> was never the top choice. It came closest after “All rights reserved.”, reaching probability 0.117 and second place, but greedy decoding never picks second place. Every run ended at max_tokens.

This is about these six prompts and greedy decoding, not a general EOS rate. One plausible factor, not tested here, is that GPT-2 is a base language model: it was trained to predict text, including its end-of-text marker, not trained as a modern assistant to finish a chat turn when asked.

How EOS is handled. EOS is a token id, not a piece of text, and the loop checks for it before decoding. When it is chosen, generated_ids keeps the id but text leaves out its decoded form. One defect matters here: if text is being held back for a possible stop string when EOS is chosen, the current loop discards it (defect 1 in the Lab increment below).

Stop strings

The question. A stop string such as Observation: should end generation when it appears. Why not just watch for its token ids?

Because the same text can be made of different tokens. Here is what the GPT-2 tokeniser does with some common markers:

Surface text GPT-2 tokens
END END
\nEND \n · END
Observation: Obs · ervation · :
Observation: (leading space) Obs · ervation · :
</s> </ · s · >

Segmentation depends on context. Even a double newline can be token 628 or tokens 198 and 198, which look identical. A matcher looking for [628] misses the second form. So stop strings must be matched on decoded text. (The engine still has to decide on normalisation, special tokens, and whether the stop text appears in the stored ids or the returned output.)

The streaming problem. Suppose the stop string is END and the decoder produces E, then N, then D. If the engine sent E and N to the client as soon as they appeared, it could not take them back when D completes the marker. So the engine must hold back any text that might be the start of a stop string, and release it only once it cannot be.

Stop strings: hold-back across token boundaries

How StopStrings does it. It holds back the longest stretch at the end of the pending text that is a proper prefix of some stop string. Tracing two cases with stop string END:

Text arrives Pending Held back Emitted Why
E E E — E could start END
X EX — EX EX cannot start END
Text arrives Pending Held back Emitted Why
E E E — could start END
N EN EN — could start END
D END — — marker complete: stop, emit nothing

At most max(len(stop)) - 1 characters ever need to be held back, though how long that takes in time depends on how quickly tokens arrive. The unit tests cover split markers, false starts, earliest completed matches and flushing at the token limit.

A known gap: results can depend on how text is chunked. Ideally, the same decoded text with the same stop strings should give the same final output however the text was split into pieces. The current matcher does not guarantee that. With stop strings ["ABCDE", "BC"]:

  • Feeding ABCDE in one piece matches ABCDE at index 0 and emits nothing.
  • Feeding ABC then DE stops on BC early and emits A.

That is a real counterexample, not just an untested case. A precedence rule and buffering policy have to be specified and implemented before the reference can claim chunk-invariance. Overlapping patterns, Unicode normalisation and arbitrary chunkings are also not yet systematically tested. Exercise 2 turns this into a regression test.

Streaming

The question. Streaming should not change which tokens are chosen or what the final output is. It only changes when the client sees each piece. So what can go wrong?

Tokens are not characters. A GPT-2 token can hold part of a UTF-8 character. Decoding each token on its own can produce the replacement character �, even though the full sequence decodes perfectly.

The experiment. The test string 推論 café 😀 is nine GPT-2 tokens, and eight of them, decoded individually, contain a replacement character.

Method Recorded result and scope
Decode individual GPT-2 token ids and concatenate Eight of nine individual decodes contain �; concatenation differs from the source text
Use IncrementalDecoder on the same nine ids, then flush Concatenation equals 推論 café 😀 with no replacement characters; the recorded report counts six empty deltas across pushes plus the final flush

Token-by-token decoding corrupted the Japanese characters and the emoji ( café happened to decode cleanly). IncrementalDecoder instead re-decodes the whole growing sequence on each push, and holds back output whenever the result ends in �, waiting for the rest of the character. On this input, the streamed pieces join up to the exact original text.

Known gaps in the decoder. It works here, but it is not a general UTF-8 solution:

  • It treats any trailing � as “incomplete, wait”. That also delays a genuine U+FFFD in the text, or a replacement caused by malformed bytes, and it cannot tell these apart.
  • It re-decodes everything on every push, so total work grows quadratically with output length.

A production version should use an incremental byte-state decoder with an explicit policy for invalid bytes, and tests for malformed UTF-8, literal U+FFFD, a prompt ending mid-character, and the final flush (exercises 5 and 9).

Three things that are easy to conflate. A model token is not necessarily a stream event: the decoder may hold incomplete bytes, the stop matcher may hold tentative text, and the transport may merge callbacks. So model-side step times are not client-side character latency. Likewise, the three outputs of generate mean different things:

Output What it contains
generated_ids Every chosen id, including EOS if chosen
text The final visible text, without stop markers
on_text events What was streamed to the callback, which can currently lag or miss the final piece

A reliable request record should hold the tokeniser revision, selection rule, full generated ids, final visible text and, when streaming, the event trace.

The loop as code

The core of generate is short. Here it is as explanatory pseudocode, not the full function:

for step in range(max_new_tokens):
    logits = next_logits(ids)                      # the seam: any engine plugs in here
    best = argmax(logits)
    ids.append(best)
    steps.append({"step": step + 1, "token_id": best, "seconds": ..., "positions_processed": len(ids) - 1})
    if best == eos_token_id:
        reason = "eos"; break                      # EOS is checked before it can be emitted
    out, stopped = stopper.feed(decoder.push(best))
    emit(out)
    if stopped:
        reason = "stop_string"; break

next_logits(ids) is the seam where any engine plugs in: a toy, the no-cache model, or a wrapper with its own state. In this function it always receives the full id sequence. EOS is checked before any decoding. Each step records positions_processed, forward_seconds and select_seconds. The real function also accepts an optional select(logits, step) callback for non-greedy rules.

The real function has finalisation logic after this loop, and that is where two defects live (see the Lab increment below). The older generation_loop.py remains a simple toy with a different result shape. Neither yet demonstrates network streaming or correct finalisation in every case.

Inference Lab increment

The Chapter 5 increment is a deliberately narrow reference API:

  • generate(next_logits, decode, prompt_ids, max_new_tokens, eos_token_id=None, stop_strings=(), on_text=None, select=None): a no-cache loop returning stop_reason, generated_ids, text, per-step timings and total_seconds. The select hook is optional; SamplingConfig and its seed from Tokens, Embeddings and Probability are not wired in by default.
  • StopStrings: a text-level matcher that holds back possible stop-string prefixes.
  • IncrementalDecoder: a prefix-redecode reference that handles the measured Unicode example but relies on a replacement-character heuristic.
  • positions_naive and positions_cached: counts of processed positions, not time estimates for a real cached runtime.

Known defects to fix before Chapter 6 builds on this:

  1. EOS drops held-back text. If a possible stop-string prefix such as EN is pending when EOS is chosen, the loop breaks without flushing it, so the returned text is truncated (exercise 3).
  2. The final flush skips the callback. Text flushed at max_tokens is added to the returned string but never passed to on_text, so the streamed text and returned text differ (exercise 4).
  3. Chunk-invariance is not established for overlapping stop strings (exercise 2).
  4. Cancellation and prompt-boundary behaviour are unspecified.

With Chapters 1–4, the Lab can now describe a record that identifies the artefact, tokeniser, sampling rule, forward implementation, timings and stop outcome. Chapter 5’s return value does not yet assemble those fields or store a sampling seed. The performance baseline is useful as it stands; correctness at the API boundary is the next gate.

Limits of this chapter’s evidence

About the set-up

  • One small model, greedy decoding. The real-model measurements use one pinned GPT-2 small. They do not describe instruction-tuned models, production stop policies or stochastic acceptance.
  • One CPU thread, no serving. Absolute throughput, scheduling, batching and GPU behaviour were not measured.

About the measurements

  • No KV-cache benchmark. The waste factors and the 27× ratio describe a deliberately naive loop. Cached performance is NOT_RUN.
  • One prompt for scaling, latency and verification, in separate timing runs. The fitted drift and timings are not transferable.
  • Two runs per length in the scaling table. The medians describe this machine, not a robust distribution.
  • The latency run was a single run and did not separate trend from scheduler effects and noise.
  • Verification compared top tokens only, not full logit vectors.
  • The EOS result covers six prompts on a base model, and says nothing about instruction-tuned models.

About the implementation

  • Streaming was only partly verified. GPT-2 tokenisation and a synthetic byte-token model were exercised; network transport, arbitrary Unicode and invalid bytes were not.
  • End-of-run defects are unfixed and untested: EOS can discard held-back text, and on_text misses text flushed at the token limit.
  • Cancellation and timeout are not implemented. They are requirements for Reliability, Cancellation and Recovery, not findings.

What you should now be able to do

  • Write the serial next-token rule, and explain why a known or proposed continuation can be scored in parallel.
  • Derive the no-cache recomputation factor, and distinguish it from FLOPs, cached cost and wall-clock speed-up.
  • Explain the 64-of-64 verification result without claiming bit-identical logits or a 27× production speed-up.
  • Report the implemented stop reasons separately from the cancellation and timeout requirements.
  • Specify a precedence rule for stop strings, and test hold-back against arbitrary chunk splits and overlapping patterns.
  • Explain why decoding byte-level tokens one at a time corrupts Unicode, and where the prefix-redecode reference still falls short.
  • Explain why first-step compute time is not end-to-end time to first token, and how latency drift affects the reading of p95.
  • Distinguish generated ids, final returned text and on_text events when validating a stream.

We now have a working loop, a measured baseline and a list of defects. Building Our First Inference Engine turns these pieces into a single engine with explicit parts and contracts, and the defects above are the first things it has to fix.

Key terms

  • Autoregressive generation: choosing accepted tokens sequentially, conditioned on the accepted prefix.
  • Prefix: the supplied and accepted token ids that condition the next distribution, subject to the model’s context policy.
  • Stop reason: the recorded termination cause; this implementation supports eos, stop_string and max_tokens only.
  • EOS token: a model vocabulary id that can mark a sequence boundary; selecting it does not require emitting its decoded surface form.
  • Stop string: a text-level pattern used by the decoding policy to truncate output.
  • Hold-back: keeping a possible stop-string prefix private until it can be emitted or rejected.
  • Incremental decoder: a decoder that produces stable text deltas from a token stream; the present implementation approximates this with full-prefix decoding.
  • Position-recomputation factor: number of processed input positions in the no-cache loop divided by the once-per-position idealisation.
  • TTFT: request-to-first-visible-token latency under a specified service boundary; not equivalent to this chapter’s first-step computation time.
  • Inter-token latency drift: a systematic trend in step duration as the accepted prefix grows.
  • Parallel verification: scoring known draft tokens in one causal forward pass; acceptance semantics differ between greedy and stochastic decoding.

Reader exercises

  1. Add a timeout stop reason and a cancellation check between forward calls. Trigger cancellation midway through a slow forward step and separate request arrival, check time, and termination time. Which delay is unavoidable without interruptible kernels?
  2. Write a chunk-invariance property test for StopStrings. Include random splits, two overlapping stop patterns, and the case where an earlier partial match competes with a later full match. Define an explicit precedence rule before testing.
  3. Write an EOS regression test for generate that holds back EN for stop string END, then selects EOS. The final returned text should retain EN. Does the current implementation pass? Fix the finalisation path.
  4. Write a callback regression test where generation ends at max_tokens with held-back suffix EN. Compare ''.join(on_text_deltas) with result['text']. Repair the callback delivery so they match.
  5. Exercise IncrementalDecoder with literal U+FFFD, malformed UTF-8, an emoji split over byte tokens, and a prompt ending in a partial byte sequence. Define error handling rather than assuming every � means “wait”.
  6. Repeat the parallel-check experiment after sampling at temperature 1.0. Explain why argmax matching is not an acceptance test for samples, and derive the distribution-preserving acceptance rule from the speculative-decoding paper.
  7. Run the EOS experiment on a cached instruction-tuned model, if available. Record the tokenizer’s EOS id, prompt format, and decoding settings before comparing outcomes.
  8. Refit step time versus position and compare it with both the projection FLOPs and dense-attention FLOPs in The Transformer as a Computation. Does a linear fit explain the entire trace?
  9. Implement a linear-time byte-state incremental decoder and benchmark it against full-prefix decoding over longer multilingual outputs. Include a finish/flush test.

References

Primary research (three papers):

Technical specifications and implementation references:

  • Attention Is All You Need — causal masking and parallel self-attention in the original transformer architecture (not a description of the particular GPT-2 benchmark).
  • Hugging Face generation strategies — library-specific stopping and decoding options; version-dependent behaviour must be checked against the installed release.
  • Python incremental codecs — byte-state incremental decoding and explicit treatment of incomplete byte sequences.

Evidence in this chapter

Claim Evidence status / scope
A causal model can score known tokens in parallel, while normal accepted-token selection has a serial dependency Established mechanism; causal architecture and decoding literature
Blockwise and speculative methods can propose blocks and verify them without changing the target policy when their acceptance rules are correct Established research, not implemented or benchmarked here
Serial no-cache 64-token run: 11.49 s; warmed 81-token pass: median 0.419 s; 64/64 greedy argmax ids agree Book result: one CPU, one prompt, no KV cache; logits equality not checked
No-cache recomputation factor rises from 6.8 to 71.6 at output lengths 8 to 128 Book arithmetic over input-position counts; not a measured cached speedup
Total time per processed position fell from 5.9 to 2.8 ms in the scaling experiment Book result, two runs per length; explanation remains hypothesis
Separate 64-token latency run: first-step compute 125 ms, inter-token p95 413 ms, fitted drift 4.3 ms/step, total 14.54 s Book result, one run; not end-to-end TTFT or a decomposition of drift versus noise
EOS id 50256 was never chosen in 384 greedy steps across six prompts Book result on GPT-2 small; no claim about instruction-tuned models
Stop text can have multiple token-id segmentations Established mechanism plus book tokeniser examples
Eight of nine individual GPT-2 token decodes in the multilingual test contain replacement characters Book result; prefix-redecode succeeds on this one test case
IncrementalDecoder handles arbitrary Unicode and malformed bytes safely NOT_ESTABLISHED; replacement-character heuristic has identified limitations
Chunk-invariance for overlapping stop strings KNOWN IMPLEMENTATION GAP; different delta splits can select different stop markers
EOS finalisation preserves pending stop-string text; callbacks receive all final text KNOWN IMPLEMENTATION GAPS, requiring regression tests and code fixes
Real KV-cached generation, network streaming, timeout/cancellation and sampled verification NOT_RUN / not measured in this chapter