Highlights

Contents

Part X
10

End-to-End Real LLM Inference

Every stage contributes to a correct chat reply. A fast model can still fail at serialization or stopping. Assemble the validated pipeline and measure its actual behavior before claiming it is ready.

YOU ARE HEREmessageschat templatetokenizertoken IDsconfig.jsonmodel.safetensorsint8 / int4 weightsOUR DECODER, REBUILT FROM THE CONFIGprefilldecodeattention kernelKV cacheparity checkvs referenceLM head → logitssamplingdetokenizereply textnext token

#Section 56Loading a Real Model From Scratch

The Qwen3-0.6B release is a folder of files, and each one feeds one stage of the pipeline.

File Size Feeds
config.json 726 bytes the architecture (Part V)
model.safetensors 1,503,300,328 bytes the weights (Part VI)
tokenizer.json 11,422,654 bytes normalizer, pre-tokenizer, vocabulary, merges (Part VIII)
tokenizer_config.json special tokens and the chat template (Parts VIII, IX)
generation_config.json stop tokens and default sampling settings

Loading from scratch is six steps, each covered earlier. Read config into a dataclass, taking head_dim literally. Construct architecture from it on the meta device. Load safetensors tensor by tensor and map parameters by name, tying the LM head. Load tokenizer from tokenizer.json and its template from tokenizer_config.json. Load generation settings from generation_config.json, which for Qwen3-0.6B says: stop on 151645 or 151643, pad with 151643, and sample with temperature 0.6, top-k 20 and top-p 0.95.

QWEN/QWEN3-0.6B: FIVE FILES, FIVE JOBSQwen3-0.6B/config.json726 BarchitecturePart Vmodel.safetensors1.50 GBweightsPart VItokenizer.json11.4 MBtext → IDsPart VIIItokenizer_config.jsonspecials + chat templateParts VIII, IXgeneration_config.jsonstop tokens, samplingPart X
Figure 4.69The checkpoint folder and what each file becomes. Two files make the model, two make the text processing around it, one sets how it generates.

The generation settings are easy to forget and matter more than they look. They are the model authors’ tested defaults, and for Qwen3 the model card adds a different set for non-thinking mode (temperature 0.7, top-p 0.8). How temperature, top-k and top-p work is the subject of the training chapter’s decoding part (Unit III).

#Section 57Preparing a Prompt

Render messages with the checkpoint’s generation prompt, tokenize once, and construct the attention mask and positions. With padding, positions must count real tokens rather than raw columns.

#Section 58Running Prefill

The 26 IDs go into the model in one forward pass.

Embeddings pass through the configured decoder blocks while each layer builds its cache. Final normalization and the head score the last position. The decoding policy selects the first reply token, which becomes the next input.

Short prompts and small models can be dominated by kernel-launch overhead. CUDA graphs record and replay a stable execution sequence to reduce that overhead.

PREFILL OF THE RUNNING PROMPT IN QWEN3-0.6B26 token IDsembed_tokens → (1, 26, 1024)28 layersRMSNorm → GQA + QK-norm + RoPE→ + → RMSNorm → SwiGLU → +positions 0 … 25, causal maskKV cache56 tensors of (1, 8, 26, 128)2,981,888 byteslast row onlyfinal norm → lm_head → (1, 151936)<think> 151667first sampled token2.33 × 10¹⁰ operations
Figure 4.70The prefill of the running prompt, with every shape. Twenty-six IDs become a (1, 26, 1,024) block that climbs 28 layers, filling the cache on the way; one row comes out the top as 151,936 logits.

#Section 59Running Decode

From the first generated token on, every step is the same. New token: its ID is looked up in the embedding table, (1,1,1,024)(1, 1, 1{,}024). Position update: the first new token is at position 26, the next at 27, and so on, always equal to the cache length before appending. Cached attention: in each layer the token's query attends over the 26, then 27, then 28 cached rows (Section 7). Append new K/V: each layer's cache grows by one row per step, 114,688 bytes per token in total. Generate next logits: one row of 151,936. Repeat until a stop condition.

Decode depends on weight and cache reads as well as execution overhead. Quantization helps when a compatible kernel reduces the actual transferred bytes.

Stopping

Generation stops on the first of four conditions: the model emits <|im_end|> (151645), the end of its turn; it emits <|endoftext|> (151643); the reply reaches a maximum length you set; or a stop string you configured appears in the decoded text. The stop token itself is not shown to the user. Without a length limit, a model that never emits its end-of-turn token (the result of most template bugs in Section 55) generates until the context window is full.

python
ids = tok.encode(prompt_text)                         # 26 IDs
cache = model.new_cache(max_len=4096)
logits = model(torch.tensor([ids]), cache=cache, pos=0)[:, -1]     # prefill
out = []
for step in range(max_new_tokens):
    nxt = sample(logits, temperature=0.6, top_k=20, top_p=0.95)    # one ID
    if nxt in (151645, 151643):
        break
    out.append(nxt)
    pos = len(ids) + len(out) - 1                     # 26 on the first step
    logits = model(torch.tensor([[nxt]]), cache=cache, pos=pos)[:, -1]
text = stream_decode(out)                             # buffered UTF-8
think, answer = split_on_last(out, 151668)            # </think>

#Section 60The Complete Inference Pipeline

Here is the whole path from messages to text, as one diagram, with the running example's numbers at every stage.

ONE CHAT TURN THROUGH QWEN3-0.6B, EVERY STAGE WITH ITS NUMBERSmessagesIX2 messages: system, userchat templateIX138 characters, generation prompt addedtokenizerVIII26 IDs, (1, 26)prefillIone pass, 28 layers, 2.33 × 10¹⁰ operationsKV cacheII56 tensors (1, 8, S, 128), 114,688 bytes per tokenfirst-token logitsI(1, 151936), last position onlysamplingXtemperature 0.6, top-k 20, top-p 0.95new tokenIIposition 26, then 27, 28, …decode with cacheI-III1.19 GB read per step: ≥ 0.36 ms on an H100EOS / stop conditionIX151645 or 151643, or max lengthdecoded textVIIIbuffered UTF-8, reasoning split at 151668once pertokencircles: the part of this chapter that covers each stage
Figure 4.71The complete inference pipeline for one chat turn of Qwen3-0.6B. Each box is a part of this chapter; the loop on the right runs once per generated token until an end-of-turn token or a length limit stops it.

The same chain in text form, as an outline you could implement top to bottom:

text
messages                    2 messages (system, user)
  v  chat template          138 characters, generation prompt added
  v  tokenizer              26 token IDs, (1, 26)
  v  prefill                one pass, 28 layers
  v  KV cache               56 tensors, (1, 8, 26, 128), 2,981,888 bytes
  v  first-token logits     (1, 151936)
  v  sampling               temperature 0.6, top-k 20, top-p 0.95
  v  new token              position 26
  v  decode with cache      one row per step, cache +114,688 bytes
  v  sampling               ... repeat ...
  v  EOS / stop condition   151645 or 151643, or max length
  v  decoded text           buffered UTF-8, reasoning split at 151668

Each arrow is a place where Parts I to IX found a bug class: template and tokenizer mismatches above the model, shape and mapping errors inside it, cache and position errors in the loop, and stop and decoding errors below it.

#Section 61Measuring Real LLM Inference

A measurement is only useful if it names what was measured, under what conditions. These are the standard numbers, and how to get each one.

Metric Definition How to measure
Time to first token request received to first token out wall clock around template, tokenize, prefill, sample
Inter-token latency time between consecutive tokens median and 99th percentile over the reply
Tokens per second generated tokens / decode time, per stream exclude prefill; report batch size
Prefill throughput prompt tokens / prefill time fixed prompt length, after warm-up
Decode throughput all generated tokens / time, across the batch at a stated batch size and context
Peak memory highest memory allocated during the run torch.cuda.max_memory_allocated()
KV-cache memory 2LHkvdhSbB2 L H_{kv} d_h S b B compute it, then confirm against peak memory
Model-loading time process start to ready cold and warm file cache, separately

Three habits make the numbers mean something. Warm up first: the first run includes kernel compilation, memory allocation and file caching, and can be many times slower. Synchronize before reading the clock: GPU work is asynchronous, so time.perf_counter() without torch.cuda.synchronize() measures how fast Python queued the work, not how fast it ran. And report the conditions: model, dtype, batch size, prompt length, generated length, context, hardware and software versions.

python
torch.cuda.synchronize(); t0 = time.perf_counter()
logits = model(prompt_ids, cache=cache, pos=0)[:, -1]
torch.cuda.synchronize(); t1 = time.perf_counter()            # prefill done
for _ in range(n_new):
    logits = model(next_ids(logits), cache=cache, pos=cache.len)[:, -1]
torch.cuda.synchronize(); t2 = time.perf_counter()
print("TTFT ms", (t1 - t0) * 1e3, "decode tok/s", n_new / (t2 - t1))
print("peak GB", torch.cuda.max_memory_allocated() / 1e9)

Compare measurements with a stated resource model to locate bottlenecks. A lower bound omits overhead and cannot establish achievable latency on its own.

THE METRICS ON ONE TIMELINE (NOT TO SCALE)load modeltemplate,tokenizeprefillmodel-loading timeTTFTITLtokens/s = tokens ÷ decode timeprefill throughput =prompt tokens ÷ prefill timememoryweightsKV cache growspeak memory
Figure 4.72Where each metric lives on the timeline of one request, from model load through prefill and decode to the last token, with memory drawn underneath.

#Section 62Final Engineering Checklist

Each line is a claim, and each claim has a test from this chapter that proves it.

Claim Proved by Section
Architecture matches config parameter count equals the card and the checkpoint: 596,049,920 26
Tensor shapes match checkpoint every header shape equals its parameter's shape 30, 33
Weight mapping is correct every parameter loaded exactly once; lm_head tied and checked 32, 33
Logit parity passes max abs logit difference below tolerance, fp32 and bf16 37, 40
Tokenizer matches checkpoint IDs equal the reference tokenizer's on a multilingual corpus; round trips exact 42, 46
Chat template matches training format rendered prompts equal the reference template's, token for token 50, 55
Cached and uncached outputs agree token and logit parity over 100 decode steps 8, 41
Quantized model is re-evaluated size, memory, speed, KL and task scores against bf16 23
Generation terminates correctly stops on 151645 and 151643, respects max length, stop token hidden 59
THE FINAL CHECKLIST: NINE CLAIMS, NINE TESTSarchitecture = configparams = 596,049,9201shapes = checkpointevery header shape2mapping correcteach param loaded once3logit parityfp32 and bf16 tolerances4tokenizer = checkpointIDs and round trips5template = trainingprompts equal, token for token6cached = uncached100 greedy steps7quantized re-measuredsize, speed, KL, tasks8terminates correctlystops on 151645, 1516439
Figure 4.73The nine claims as a card to pin above the desk. Each one is a test, not a feeling.

The order matters. Shapes before parity, because a shape error makes parity meaningless. Logit parity before generation parity, because a single-pass bug hides inside generation noise. Tokenizer and template before any quality evaluation, because a wrong prompt makes a correct model look bad. Quantization last, because it is a deliberate change that must be measured against a baseline already proved correct.

What this chapter did not cover

Everything here served one request at a time on one device. Production serving adds a layer above it: continuous batching, which adds and removes requests from the running batch at every decode step instead of waiting for a whole batch to finish; speculative decoding, which lets a small model guess several tokens that the large model verifies in a single pass; tensor and pipeline parallelism, which split a model too large for one GPU across several; and the scheduling, admission and memory management that frameworks like vLLM, SGLang and TensorRT-LLM implement. Each of them is built from the pieces in this chapter, the cache, the kernels, the memory arithmetic and the parity tests, and each is a natural next chapter.