The complete training-to-generation pipeline
The pipeline connects text, learning, evaluation, and generation. Learned weights and training history have different roles. Trace each component’s contribution and use those responsibilities to diagnose failures.
#Section 33The complete training-to-generation pipeline
Take the illustrative token stream [17, 23, 5, 81, 9, 44, 2, 7, 3]. Eight IDs become one input window and the eight IDs after them become its labels. By the end of this chapter, there is no unexplained arrow between that stream and a checkpoint that can continue a prompt. There is also no claim that these invented IDs spell meaningful words: they make alignment and shape visible.
Corpus, tokenizer and batches
Start with raw documents and define cleaning, boundary handling and deduplication. Split documents or source groups into training, validation and test before constructing overlapping windows. Learn or select the tokenizer under the declared split policy, and persist its exact vocabulary and special-token configuration. The earlier tokenization part supplies the algorithm; Part III supplies the example-building contract.
Convert the training corpus to the matching token IDs. Sample two windows of eight inputs and their one-position-shifted labels per microbatch, with any packed-document attention mask and ignored-target policy made explicit. Four microbatches provide 64 supervised targets for the example optimizer update. A validation example comes from held-out material, not a different random start inside the same training document.
Transformer, loss, backpropagation and optimizer
Look up embeddings, apply eight independent blocks, normalize the final stream and project to vocabulary logits. The core shape trace is below. It lists the operations relevant to training without repeating the earlier attention derivations.
| Stage | Example shape | What changes |
|---|---|---|
| Input and target IDs | Each (2, 8) |
One-position target shift |
| Embedding | (2, 8, 512) |
IDs become learned vectors |
| Each block’s residual stream | (2, 8, 512) |
Context and features |
| Query heads | (2, 8, 8, 64) |
Eight query heads |
| Key/value heads | Each (2, 2, 8, 64) |
Two shared KV heads |
| SwiGLU gate/up/product | Each (2, 8, 1536) |
Expanded feature computation |
| Final RMSNorm | (2, 8, 512) |
Head input scale |
| Vocabulary projection | (2, 8, 32000) |
One score per candidate |
| Flattened loss inputs | (16, 32000) and (16,) |
Target alignment only |
| Summed microbatch NLL | Scalar | Cost of valid targets |
| One accumulated parameter gradient | Matches each parameter | Contributions from 64 targets |
Each microbatch’s summed NLL is divided by the combined valid-target count before backward. Reverse-mode differentiation adds contributions through residual branches, shared token projections and both uses of the tied embedding. Parameters do not change until all four backward calls finish. Then the loop unscales if the precision policy requires it, checks and clips the combined gradient, applies one AdamW update with the declared learning rate, and advances the correct counter.
Evaluation, checkpoint and prompt
At chosen boundaries, evaluate fixed held-out targets with module evaluation mode and gradient recording disabled. Sum NLL and valid-token counts, then derive loss, perplexity and BPB under the shared text contract. Compare controlled runs before crediting a small score change to an architecture. Save the training state at a completed update boundary, and separately identify the checkpoint selected for inference.
The inference artifact needs the architecture, learned state and matching tokenizer, plus the positional, numerical and generation conventions. It does not need Adam’s moments to produce logits. If the caller later resumes training, the weights-only inference artifact is insufficient unless the missing histories can be restored from another source. A “checkpoint” filename therefore does not establish whether the file is resumable.
Tokenize the prompt with that exact tokenizer, use evaluation mode, and process it with the fixed parameters. Read the last valid position’s logits. Apply the requested temperature and candidate filter, choose one token, append it, and repeat under the termination policy. Decode IDs to text with correct byte handling. The output depends on the trained predictor, the prompt and the decoder policy together.
#Section 34Learned weights and training state
A checkpoint stores learned parameters, but a resumable training run needs additional state. Keep those responsibilities separate when deciding what to save.
Which objects learn
Projections, embedding rows, and norm gains learn. Masks, rotary tables, and generation caches do not. A tied head reuses the embedding parameter rather than creating another learned object.
Training state is a different count
Training retains gradients and optimizer history beyond parameter values. Saved activations, workspaces, and allocation reserves add further memory; mixed-precision layouts differ by implementation.
An inference export needs weights and the model’s input contract. Dtype affects storage, while tied serialization must preserve or recreate parameter sharing.
A larger model has the same distinction between inference weights and training state. An inference-memory estimate is therefore insufficient for training planning.
#Section 35What each component contributes
Erase the formulas and draw the pipeline from memory. Can you name one job for each component and say what would fail if it were removed? That is a better test of understanding than recalling a library’s default values. The tables and drawings should now support that explanation rather than replace it.
| Component | Its job | A concrete failure when wrong |
|---|---|---|
| Corpus and splits | Supply the target distribution and held-out test | Leakage makes validation optimistic |
| Tokenizer | Map text to stable IDs and back | Wrong vocabulary changes every token meaning |
| Shifted labels | Define the next-token task | Double shift trains the wrong alignment |
| Causal mask | Hide future inputs from each prediction | The model can see its answer |
| Embedding | Supply learned input vectors | IDs are treated as false numeric magnitudes |
| Attention and positions | Use permitted context with position information | Context or position dependence is wrong |
| FFN | Transform contextual features at each position | Feature computation is changed or removed |
| Residuals and norms | Carry state and control the chosen branch scales | Depth and head input behave differently |
| LM head | Score vocabulary candidates | Hidden features never become token scores |
| Cross-entropy | Measure observed next-token likelihood | The optimized target differs from evaluation |
| Backpropagation | Compute derivatives of that objective | Parameters lack the required correction signal |
| Optimizer and schedule | Apply history-dependent parameter updates | The intended training trajectory changes |
| Precision and clipping | Keep declared arithmetic and gradients usable | Underflow, overflow or excessive updates |
| Validation and seed repeats | Measure generalization and uncertainty | A lucky run is mistaken for a method gain |
| Checkpoint | Restore the declared state | Resume loses history or the next data draw |
| Decoder and stopping | Choose and terminate a continuation | Output repeats, overruns, or uses bad markers |
A whiteboard diagnosis
If training loss drops immediately to almost zero, inspect target visibility and alignment before celebrating. If loss is nonfinite, inspect inputs, logits, reductions and gradients before clipping anything. If training improves but validation worsens, inspect split integrity, measurement policy and fitting behavior. If sampled text is bad despite plausible held-out likelihood, compare greedy outputs, verify tokenizer and positions, and inspect the decoder settings.
If a resumed run diverges from the uninterrupted run immediately, compare the next batch, applied learning rate and Adam state before blaming floating-point chaos. If an architecture variant wins one run, inspect seed spread and actual compute. If the model runs out of memory, identify which tensor category grows with batch or context; adding parameters, activations and an attention score grid under one vague “model size” label hides the remedy. These diagnoses follow the contracts developed in the chapter.
The boundary of this chapter
We have trained a causal predictor under an explicit small-model recipe and defined how to evaluate and sample it. We have not built a distributed training stack, a production data-curation service, supervised instruction tuning, preference optimization, retrieval or a complete model-serving engine. Those layers introduce further objectives, state and resource constraints. Inference Engineering follows the fixed checkpoint into caching, kernels, weight loading and real checkpoint parity.