Chapter 64
End-to-End Learning Lab and Capstone
On this page
Verification must cross implementation boundaries. A tokenization choice changes targets; a target changes training; a checkpoint changes serving; a tool changes what counts as success. These experiments test independent views of the same computation before the capstone combines them.
Execute the advanced invariants¶
Run python -m examples.decoder_lab in the optional PyTorch environment. The two-block decoder trains actual attention, compares full-prefix and cached logits, exposes stale-cache reuse after a prefix edit, executes valid-prefix repair, verifies assistant-only loss gradients and unequal microbatch gradients/updates, and checks AdamW continuation through serialization. A tiny LoRA projection confirms initial function equality and subsequent adapter-only change. The restored-edition run records its exact environment and numerical errors in docs/experiments/decoder-restored.json.
Run python -m examples.distributed_lab for two CPU processes using Gloo. Each rank contributes a different number of targets. The reduced gradient is compared with the unpartitioned objective. Rank-local weight files become discoverable only after publication of a complete manifest; an orphan staging file cannot change the committed snapshot. This is a local-filesystem publication exercise, not validation of FSDP, object-store consistency, optimizer sharding, or elastic restart.
| Boundary | Executable evidence | Claim it cannot establish |
|---|---|---|
| Decoder and optimizer | examples/decoder_lab.py |
Real-world model quality or GPU speed |
| Analytic continuous flow | examples/flow_matching.py |
Learned velocity accuracy or image generation quality |
| Learned two-dimensional flow | examples/learned_flow.py |
Image generation quality, DiT training or population performance from three seeds |
| Distributed reduction | examples/distributed_lab.py |
NCCL performance or FSDP memory savings |
| Interrupted publication | examples/checkpoint_publication.py |
Power-loss durability, remote object-store consistency or optimizer resharding |
| Output/revocation ordering | examples/output_authority.py |
A deployed cross-service authority transaction or network delivery guarantee |
| Admission and ownership simulation | examples/serving_trace.py |
Milliseconds or GPU batching efficiency |
| Measured loopback stream timing | examples/benchmarks/streaming_http.py |
Model-server throughput or a device kernel timeline |
| Data lineage and mixture | examples/data_release.py |
Quality of a real training corpus |
| Retrieval and external model | examples/model_application.py |
Hosted quality without an executed endpoint experiment |
| Constrained evidence selection | examples/model_followup.py |
Competing-source selection from its singleton candidate sets |
| Competing-passage/null diagnostic | examples/model_selection_diagnostic.py |
Population quality, free-form synthesis or learned-agent reliability |
| Fenced telemetry output recovery | examples/telemetry_sink.py |
Source correctness, watermark validity or multi-source replay |
| Compiled Metal RMSNorm | examples/accelerators/metal_rmsnorm.py |
CUDA correctness, backward registration or device occupancy |
| Accelerator operator | examples/accelerators/ |
Hardware acceptance from CPU reference tests |
The learned-flow lab trains an MLP on an eight-component Gaussian mixture and saves checkpoints, held-out errors, generated samples and three prespecified seeds. Compare the sample plots with the analytic conditional-mean field: a lower regression loss need not imply well-separated generated modes. Chapter 57 reports the recorded CPU run and its remaining modeling error.
The experiment index distinguishes executed results from experiment plans. The standard-library suite remains available without tensor dependencies. The earlier bigram exercise is retained in examples/tiny_lm.py as an optional elementary reference; it is no longer the central model demonstration.
When a hardware target is unavailable, leave its timing and profiler fields unmeasured. Do not substitute peak-specification arithmetic for a completed experiment. The accelerator acceptance template preserves that boundary.
Two target-only runners are prepared in examples/accelerators/: cuda_excerpt_validation.py assembles the printed GEMM, reduction and scan excerpts for compilation and Compute Sanitizer checks; nccl_validation.py checks two-GPU DDP accumulation and measures two all-reduce payloads. Neither has executed on NVIDIA hardware for this edition. Their README specifies the commands and evidence required to change that status.
Design the complete documentation service¶
Use the running 7B documentation assistant as a capstone. Start with the hypothetical workload and budgets in the RAG chapter, not a preferred framework. Deliver the following artifacts in order; each should be understandable by someone who has not watched the experiments.
- Contract and data manifest: define supported tasks, document owners, permissions, revisions, language slices, freshness, quality, latency, and failure outcomes. Separate development and held-out evaluation before tuning.
- Unadapted baseline: serve an existing compatible checkpoint with a bounded retrieval workflow. Record tokenizer/template, precision, context budget, and generation policy. Measure retrieval and generation separately.
- Adaptation decision: use SFT/LoRA only for demonstrated behavior gaps; use retrieval for changing facts. Require an independent verifier and enough interaction data before adding RL. Compare against the unadapted baseline at the same workload boundary.
- Capacity ledger: calculate weights, layer-specific state, workspaces, reserved memory, phase compute, and transfer budgets. A hybrid model requires a new state ledger; copying the dense transformer's KV formula is not a migration plan.
- Engine and performance experiment: establish one compatible engine baseline, then compare a second using the controlled/deployment distinction in Serving Engines and Cache Backends in Practice. Identify the measured bottleneck before adding batching, quantization, speculation, remote cache, or phase sharding. Keep correctness, quality, and SLO gates fixed. If accelerator portability is required, repeat the full acceptance path on one alternative stack; translated code alone is not the result.
- Bounded agent extension: permit only the tools the task requires. Define action identity, timeout/reconciliation, memory provenance, stopping conditions, and final-state verification. Compare completed authorized tasks per budget with the fixed workflow.
- Operational release: bind model/data/index/harness versions, canary, inject failures, rehearse rollback, and assign ownership. Preserve both positive and negative results.
Two alternative capstones¶
For offline structured extraction, replace the corpus/index with a versioned document batch, a schema plus independent field verifiers, and an immutable result manifest. Preserve source-to-record lineage, model/template identity, error queues, and a restart cursor. Compare useful records per deadline and budget; do not award credit to well-formed but incorrect JSON.
For a code-change agent, replace answer citations with a repository snapshot, a constrained patch surface, test outcomes, and a durable action ledger. Separate syntax, test execution, task completion, and unauthorized changes. A replay must not duplicate an external effect, and passing a narrow test must not be reported as proof of all intended behavior. Use held-out repositories/tasks and fixed tool budgets for a learned-policy comparison.
These alternatives are proposed implementation exercises, not additional completed applications. Give each a first executable milestone before scaling it:
| Alternative | Small fixture and interruption | Completion evidence |
|---|---|---|
| Extraction | Five source records with adjudicated date/time fields, including one ambiguous record; stop after staging three outputs | Restart publishes one complete immutable manifest containing four verified records and one explicit exception, with source revisions; no duplicated output and no ambiguous field silently guessed |
| Code change | A frozen tiny repository, one requested behavior change, protected tests and a permitted patch list; lose the reply after saving a draft patch | Resume reconciles the same operation key; one draft exists, protected tests remain unchanged, required behavior passes and edits stay within the permitted list |
Use examples/data_release.py for manifest identity/completeness and examples/durable_effects.py or examples/task_recovery.py for receipt/restart mechanics. They supply mechanisms, not field correctness or code-task success. Write those independent verifiers against the fixture before adding model calls. Record the failing run and recovered final state; then enlarge the held-out task set without tuning on its labels.
What a good capstone answer contains¶
Keep the checkpoint/engine revisions, rejected alternatives, workload trace, resource ledger, quality uncertainty, and latency decomposition together. Distinguish calculations, CPU tests, reported results, and your own measurements. Attach cache ownership through lookup, reservation, transfer, cancellation, and eviction; for a port, include the model/precision/sharding combination and cold-start/recovery results.
If target hardware was unavailable, submit semantic tests and the proposed experiment with performance explicitly unmeasured. Peak specifications cannot fill those cells.
A strong answer explains the bottleneck, calculates a tradeoff, and supplies a rejection test. It need not use every technique: a small model and fixed workflow may solve the task without MoE, distributed RL, or multiple agents.
As a self-check, change one assumption at a time: double input length; revoke a document permission mid-request; replace attention layers with recurrent layers; lose the reply after a successful tool write; or make rollout production faster than the learner. Trace which state, budget, and acceptance rule changes. The relevant derivations and failure protocols are developed in the preceding parts; the reference sheets below help locate them.
Optional companions¶
The canonical detailed telemetry track is printed in Part VI, beginning with Exact Streaming Queries and Time Windows, followed by online statistics, sketches and the complete telemetry service. It is optional within the main book; the streaming companion route links back to those chapters rather than maintaining another copy.
Separate companions contain the classical ML refresher, professional-development exercises, dated model catalogue, and platform-specific notes. The local reader renders these resources separately. Repository-relative links identify the matching local companion, without depending on a private remote branch.