# Companion code: run the course's algorithms yourself

> The DMXSF companion repository provides 61 Python labs for a laptop CPU, covering all 66 wiki articles with runnable material and checking their core formulas and mechanisms.

- URL: https://dmxsf.com/en/code/
- Updated: 2026-11-18

[dmxsf/dmxsf](https://github.com/dmxsf/dmxsf) offers 61 CPU labs, from tensor shapes and GPU rooflines to local inference, agents, training, evaluation, and safety. Every lab has Chinese and English instructions, a run command, and recorded output. The default runs need no GPU, model API, or external weights.

## Quick start

```bash
git clone https://github.com/dmxsf/dmxsf.git
cd dmxsf
uv sync                      # Python 3.10 or newer; pip install -e . works too
uv run dmxsf list            # every lab
uv run dmxsf run foundations/tensors-and-shapes
uv run dmxsf roadmap weekend # labs for the weekend crash course
```

Dependencies are managed with [uv](https://docs.astral.sh/uv/). Without uv, run `pip install -e .` and drop `uv run` from the commands.

## How the code relates to the course

- **All 66 articles with runnable material have a lab.** The directory `labs/<section>/<page>/` follows the path of the primary article. Closely related articles such as information theory and next-token prediction can share a lab. The "Companion code" card gives the full command, source location, and README in the selected language.
- **Labs check core formulas and mechanisms.** Parameter counts, memory and probabilities can be recomputed directly. Some performance and scaling experiments use smaller CPU examples. A failing check prints `[FAIL]` and exits with a nonzero status. Use `--seed N` to change the random seed.
- **The README states the scope of each experiment.** It identifies teaching examples, results that can be reproduced with `--hf` or `--bge`, and measurements that require the full experiment in the wiki article.
- **Library, labs and tests are separate.** `src/dmxsf/` is an importable library, `labs/` holds scripts written to be read like a tutorial, and `tests/` tests the library. CI runs all of the tests on every commit and runs each lab once with `--quick`.

## How to use it

1. Read a wiki page and note the formulas or tables you would like to verify.
2. Run its lab and read the source next to the output; the docstring at the top of each lab says which parts of the page it checks.
3. Change a parameter and run it again, then try the exercises in the lab's write-up.

## Environment and run time

- A CPU is enough. The first lab that needs a pretrained model trains a very small byte-level model on your machine (a few minutes) and caches it in `~/.cache/dmxsf`.
- The full run time of each lab is listed below; `--quick` is a smoke version for checking that your setup works.
- Timings in milliseconds or throughput depend on the machine: read the ratios in a lab, not the absolute numbers.

## All labs

Each lab covers one or two wiki pages and lives in the directory that mirrors the wiki path; its output checks the numbers on the page. (61 labs)

### Getting Started

#### [What is an LLM? The whole loop, small enough to read](https://github.com/dmxsf/dmxsf/tree/main/labs/start/what-is-an-llm)

Predict one byte, append it, repeat: the whole loop on an 842,496-parameter GPT you can open, from tokens and embeddings to the softmax, the training objective and the three numbers (parameters, tokens, context). It ends with the map from every page of the course to its lab.

- Course pages: [What Is a Large Language Model? From Next-Word Prediction to General Assistants](https://dmxsf.com/en/wiki/start/what-is-an-llm/), [LLM Learning Roadmap: A Map of the Wiki and Four Study Paths](https://dmxsf.com/en/wiki/start/learning-roadmap/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run start/what-is-an-llm`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/start/what-is-an-llm/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/start/what-is-an-llm/README.en.md)

#### [LLM formula sheet: parameters, memory and compute](https://github.com/dmxsf/dmxsf/tree/main/labs/start/cheat-sheet)

Cross-check released-model parameter counts, KV bytes, training FLOPs and pass@k.

- Course pages: [LLM Cheat Sheet: Estimating Parameters, Compute, Memory and Decoding Speed](https://dmxsf.com/en/wiki/start/cheat-sheet/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run start/cheat-sheet`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/start/cheat-sheet/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/start/cheat-sheet/README.en.md)

### Foundations

#### [Tensor shapes: a linear layer by hand](https://github.com/dmxsf/dmxsf/tree/main/labs/foundations/tensors-and-shapes)

Track position and feature axes through a projection, bias and ReLU.

- Course pages: [Python and tensor shapes: from a table to a linear layer](https://dmxsf.com/en/wiki/foundations/tensors-and-shapes/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run foundations/tensors-and-shapes`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/foundations/tensors-and-shapes/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/foundations/tensors-and-shapes/README.en.md)

#### [Next-token prediction and information theory](https://github.com/dmxsf/dmxsf/tree/main/labs/foundations/next-token-prediction)

Bigram counts on the page's toy corpus, entropy, cross-entropy and KL divergence checked against each other, character n-grams on Shakespeare until the counts run out, and a neural bigram that learns the count table by gradient descent.

- Course pages: [From Language Modeling to Next-Token Prediction](https://dmxsf.com/en/wiki/foundations/next-token-prediction/), [Information Theory Refresher: Entropy, Cross-Entropy and KL Divergence](https://dmxsf.com/en/wiki/foundations/information-theory/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run foundations/next-token-prediction`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/foundations/next-token-prediction/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/foundations/next-token-prediction/README.en.md)

#### [Neural networks: gradients and XOR](https://github.com/dmxsf/dmxsf/tree/main/labs/foundations/neural-network-basics)

Check manual backpropagation with finite differences, then fit XOR with and without a hidden layer.

- Course pages: [Neural Network Basics: From Linear Layers to Backpropagation](https://dmxsf.com/en/wiki/foundations/neural-network-basics/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run foundations/neural-network-basics`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/foundations/neural-network-basics/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/foundations/neural-network-basics/README.en.md)

#### [Tokenizers and embeddings](https://github.com/dmxsf/dmxsf/tree/main/labs/foundations/tokenizer-and-embeddings)

BPE by hand on the page's toy corpus, a byte-level BPE that never says <unk>, what the training text decides about a language's cost, an embedding table as a matrix multiply, and how much of a model the embedding table is.

- Course pages: [Tokenizers and Embeddings: BPE, Vocabulary Size and the Embedding Table](https://dmxsf.com/en/wiki/foundations/tokenizer-and-embeddings/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run foundations/tokenizer-and-embeddings`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/foundations/tokenizer-and-embeddings/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/foundations/tokenizer-and-embeddings/README.en.md)

#### [Optimizers, schedules, mixed precision and loss spikes](https://github.com/dmxsf/dmxsf/tree/main/labs/foundations/optimizers-and-training-stability)

SGD, Adam and AdamW written out and checked against PyTorch in float64; why Adam wins on an ill-conditioned quadratic; decoupled weight decay; learning-rate schedules; mixed precision and master weights; one corrupted batch and what clipping and beta2 do about it.

- Course pages: [Optimizers and Training Stability: AdamW, Warmup, Mixed Precision, Loss Spikes](https://dmxsf.com/en/wiki/foundations/optimizers-and-training-stability/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run foundations/optimizers-and-training-stability`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/foundations/optimizers-and-training-stability/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/foundations/optimizers-and-training-stability/README.en.md)

### Model Architecture

#### [From RNN to attention: gradients and retrieval paths](https://github.com/dmxsf/dmxsf/tree/main/labs/architecture/from-rnn-to-attention)

Compare the gradient through a recurrent chain and a gated memory path, then recover an earlier value with attention.

- Course pages: [From RNNs to Attention: Why the Transformer Appeared](https://dmxsf.com/en/wiki/architecture/from-rnn-to-attention/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run architecture/from-rnn-to-attention`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/architecture/from-rnn-to-attention/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/architecture/from-rnn-to-attention/README.en.md)

#### [Attention, by hand and in a model](https://github.com/dmxsf/dmxsf/tree/main/labs/architecture/attention-basics)

The page's three-position example by hand, why scores are divided by sqrt(d) (the dot product has variance d), masks, heads and positions, and a small model that has to use attention to copy what followed the last occurrence.

- Course pages: [Attention Basics: How a Transformer Reads Context](https://dmxsf.com/en/wiki/architecture/attention-basics/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run architecture/attention-basics`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/architecture/attention-basics/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/architecture/attention-basics/README.en.md)

#### [Position encodings and length extrapolation](https://github.com/dmxsf/dmxsf/tree/main/labs/architecture/positional-encoding)

Sinusoidal encodings as clocks, RoPE's score depending only on distance, the stretching recipes (position interpolation, NTK-aware, YaRN, the Llama 3.1 rule) computed side by side, and five position schemes trained on short text and tested on long text.

- Course pages: [Positional Encoding Explained: Absolute, Relative and RoPE](https://dmxsf.com/en/wiki/architecture/positional-encoding/), [Long Context: Position Extrapolation, Training Recipes and Cost](https://dmxsf.com/en/wiki/architecture/long-context/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run architecture/positional-encoding`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/architecture/positional-encoding/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/architecture/positional-encoding/README.en.md)

#### [The Transformer block and the modern recipe](https://github.com/dmxsf/dmxsf/tree/main/labs/architecture/transformer-block)

Count a GPT-2 small block (12d²+13d parameters), see where real models keep their parameters, measure signal and gradient by depth for pre-norm and post-norm, then walk from GPT-2 to Llama one change at a time.

- Course pages: [Transformer Block Explained: Attention, FFN, Residuals and LayerNorm](https://dmxsf.com/en/wiki/architecture/transformer-block/), [Modern LLM Architecture: From GPT-2 to Llama, Qwen and DeepSeek](https://dmxsf.com/en/wiki/architecture/modern-llm-architecture/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run architecture/transformer-block`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/architecture/transformer-block/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/architecture/transformer-block/README.en.md)

#### [Efficient attention](https://github.com/dmxsf/dmxsf/tree/main/labs/architecture/efficient-attention)

KV-cache formulas against the page's table and against real tensors, MLA caching a latent vector, FlashAttention's tiles and online softmax, sliding-window attention, and converting an MHA model to GQA by mean-pooling heads.

- Course pages: [Efficient Attention: MQA, GQA, MLA and FlashAttention](https://dmxsf.com/en/wiki/architecture/efficient-attention/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run architecture/efficient-attention`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/architecture/efficient-attention/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/architecture/efficient-attention/README.en.md)

#### [Mixture of experts: routing, load balance and the parameter accounts](https://github.com/dmxsf/dmxsf/tree/main/labs/architecture/mixture-of-experts)

A MoE layer that computes only the tokens an expert was chosen for, total against active parameters counted on real modules, a DeepSeek-V3-style toy model, expert capacity, the balance loss, how many experts a decoding batch touches, and a trained MoE against dense models of equal cost and equal size.

- Course pages: [Mixture of Experts (MoE): Routing, Load Balancing and Sparse Activation](https://dmxsf.com/en/wiki/architecture/mixture-of-experts/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run architecture/mixture-of-experts`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/architecture/mixture-of-experts/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/architecture/mixture-of-experts/README.en.md)

#### [State space and hybrids: equivalent scans and memory](https://github.com/dmxsf/dmxsf/tree/main/labs/architecture/state-space-and-hybrid)

Compare recurrent and explicit causal forms of the same selective update and account for hybrid state and cache.

- Course pages: [State Space Models and Hybrids: Trading the KV Cache for a Fixed-Size State](https://dmxsf.com/en/wiki/architecture/state-space-and-hybrid/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run architecture/state-space-and-hybrid`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/architecture/state-space-and-hybrid/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/architecture/state-space-and-hybrid/README.en.md)

### Compute and Systems

#### [Hardware basics: storage and copy time](https://github.com/dmxsf/dmxsf/tree/main/labs/systems/hardware-basics)

Compute tensor sizes and a copy-time lower bound with explicit units.

- Course pages: [LLM hardware basics: CPUs, GPUs, memory, and moving data](https://dmxsf.com/en/wiki/systems/hardware-basics/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run systems/hardware-basics`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/systems/hardware-basics/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/systems/hardware-basics/README.en.md)

#### [GPU roofline: bytes, FLOPs and tile reuse](https://github.com/dmxsf/dmxsf/tree/main/labs/systems/gpu-and-roofline)

Compute the A100 and H100 ridge points, model a linear layer, and count matrix-multiply tile traffic.

- Course pages: [GPUs and the Roofline Model: Why Big Models Are Bound by Memory Bandwidth](https://dmxsf.com/en/wiki/systems/gpu-and-roofline/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run systems/gpu-and-roofline`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/systems/gpu-and-roofline/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/systems/gpu-and-roofline/README.en.md)

#### [GPU kernels: tiled GEMM and memory traffic](https://github.com/dmxsf/dmxsf/tree/main/labs/systems/gpu-kernels)

Run tiled matrix multiplication on uneven shapes and verify logical memory traffic.

- Course pages: [GPU kernels: from tiled matrix multiplication to fusion](https://dmxsf.com/en/wiki/systems/gpu-kernels/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run systems/gpu-kernels`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/systems/gpu-kernels/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/systems/gpu-kernels/README.en.md)

#### [Numerical precision: rounding, overflow and loss scaling](https://github.com/dmxsf/dmxsf/tree/main/labs/systems/numerical-precision)

Reproduce low-precision stalled addition, stable softmax, and loss scaling with CPU tensors.

- Course pages: [Numerical Precision: Three Ways FP16, BF16 and FP8 Training Goes Wrong](https://dmxsf.com/en/wiki/systems/numerical-precision/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run systems/numerical-precision`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/systems/numerical-precision/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/systems/numerical-precision/README.en.md)

#### [Collective communication: simulate a ring all-reduce](https://github.com/dmxsf/dmxsf/tree/main/labs/systems/collective-communication)

Track each chunk through reduce-scatter and all-gather, then compare the observed per-rank bytes with the alpha-beta model.

- Course pages: [Collective Communication: Why All-Reduce Has So Many Algorithms](https://dmxsf.com/en/wiki/systems/collective-communication/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run systems/collective-communication`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/systems/collective-communication/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/systems/collective-communication/README.en.md)

### Pre-training

#### [The pretraining pipeline on a laptop: monitoring, data mix, resuming, leakage](https://github.com/dmxsf/dmxsf/tree/main/labs/pretraining/training-pipeline)

Two free checks before spending compute, a baseline run and how to read its log, then three experiments on a laptop: the data mix, four ways to resume from a checkpoint (only one is exact), and validation text leaking into the training data.

- Course pages: [The LLM Training Pipeline: From Data to Deployment](https://dmxsf.com/en/wiki/pretraining/training-pipeline/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run pretraining/training-pipeline`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/pretraining/training-pipeline/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/pretraining/training-pipeline/README.en.md)

#### [Data engineering: build and audit a dedup filter](https://github.com/dmxsf/dmxsf/tree/main/labs/pretraining/data-engineering)

Compare exact duplicates and shingle similarity, then read the banding curve before choosing a deduplication threshold.

- Course pages: [Pretraining Data Engineering: Filtering, Deduplication and Mixing](https://dmxsf.com/en/wiki/pretraining/data-engineering/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run pretraining/data-engineering`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/pretraining/data-engineering/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/pretraining/data-engineering/README.en.md)

#### [Scaling laws: the formulas, the serving cost, and a tiny study of our own](https://github.com/dmxsf/dmxsf/tree/main/labs/pretraining/scaling-laws)

The page's power laws and compute-optimal split recomputed, what serving cost does to the best model, a real tiny scaling study (tune the learning rate per size, train a grid, fit L(N, D), predict an unseen run), and what a 12-point fit can and cannot identify.

- Course pages: [Scaling Laws: How to Split Compute Between Parameters and Data](https://dmxsf.com/en/wiki/pretraining/scaling-laws/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run pretraining/scaling-laws`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/pretraining/scaling-laws/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/pretraining/scaling-laws/README.en.md)

#### [Training compute and memory: 6ND, MFU, model state and activations](https://github.com/dmxsf/dmxsf/tree/main/labs/pretraining/compute-and-memory)

Every formula on the page checked against a measurement: PyTorch's FLOP counter, the tensors autograd saves for the backward pass, and the optimizer's state; then MFU, GPU hours and a full Llama 2 7B account on 8 x 80 GiB.

- Course pages: [The Compute and Memory Ledger of Training: FLOPs, MFU and Memory Budgets](https://dmxsf.com/en/wiki/pretraining/compute-and-memory/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run pretraining/compute-and-memory`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/pretraining/compute-and-memory/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/pretraining/compute-and-memory/README.en.md)

#### [Distributed training: gradients, ZeRO, tensor and pipeline parallelism](https://github.com/dmxsf/dmxsf/tree/main/labs/pretraining/distributed-training)

Built and measured in a few processes on one machine: data-parallel gradient averaging, the ring all-reduce, data parallelism, ZeRO-1 and ZeRO-3 trained side by side (same weights, measured memory and communication), Megatron-style tensor parallelism, and pipeline schedules.

- Course pages: [Distributed Training: Data, Tensor and Pipeline Parallelism](https://dmxsf.com/en/wiki/pretraining/distributed-training/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run pretraining/distributed-training`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/pretraining/distributed-training/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/pretraining/distributed-training/README.en.md)

### Post-training and Alignment

#### [SFT data: the loss mask, a data health check, and what data size, noise, masking and replay do](https://github.com/dmxsf/dmxsf/tree/main/labs/post-training/sft-data)

What the SFT loss averages over (the -100 mask, packing and padding), data health checks against planted ground truth, and four controlled experiments: run-to-run noise, examples per intent, wrong labels, loss on the prompt and replaying general text.

- Course pages: [SFT Data: Construction and Quality Control](https://dmxsf.com/en/wiki/post-training/sft-data/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run post-training/sft-data`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/post-training/sft-data/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/post-training/sft-data/README.en.md)

#### [LoRA: the parameter bill, the mechanics, LoRA against full fine-tuning, merging, NF4](https://github.com/dmxsf/dmxsf/tree/main/labs/post-training/lora-finetuning)

LoRA written from scratch and compared with full fine-tuning: the exact parameter bill, learning-rate windows, rank and alpha, which matrices to adapt, how low-rank the learned update is, merging into the weights and into 4-bit (NF4) weights, memory and speed.

- Course pages: [LoRA Fine-Tuning in Practice](https://dmxsf.com/en/wiki/post-training/lora-finetuning/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run post-training/lora-finetuning`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/post-training/lora-finetuning/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/post-training/lora-finetuning/README.en.md)

#### [Reward models: pairwise scores and label noise](https://github.com/dmxsf/dmxsf/tree/main/labs/post-training/reward-models)

Fit Bradley–Terry scores on a connected comparison graph and reproduce the agreement ceiling under independent label flips.

- Course pages: [Reward Models: Turning Human Preferences into a Score to Optimize](https://dmxsf.com/en/wiki/post-training/reward-models/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run post-training/reward-models`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/post-training/reward-models/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/post-training/reward-models/README.en.md)

#### [Policy gradients: exact checks, baselines and GAE](https://github.com/dmxsf/dmxsf/tree/main/labs/post-training/rl-fundamentals)

Enumerate a tiny policy, compare gradients against finite differences, and vary lambda in a finite GAE trajectory.

- Course pages: [Reinforcement Learning Basics: Policy Gradients, Advantages and PPO](https://dmxsf.com/en/wiki/post-training/rl-fundamentals/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run post-training/rl-fundamentals`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/post-training/rl-fundamentals/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/post-training/rl-fundamentals/README.en.md)

#### [Preference optimization: the DPO loss, its closed form, and a real DPO run](https://github.com/dmxsf/dmxsf/tree/main/labs/post-training/preference-optimization)

The DPO loss by hand, its closed-form optimum checked against random competitors and fitted comparisons, a real DPO run on a small byte-level model (learning rate, beta, chosen log-probabilities that fall, the LoRA-off reference), and reward hacking as the KL budget grows.

- Course pages: [Preference Optimization: From RLHF to DPO](https://dmxsf.com/en/wiki/post-training/preference-optimization/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run post-training/preference-optimization`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/post-training/preference-optimization/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/post-training/preference-optimization/README.en.md)

#### [Reasoning RL: verifiers, GRPO advantages and loss, and a real RLVR run](https://github.com/dmxsf/dmxsf/tree/main/labs/post-training/reasoning-rl)

The verifier, group advantages, the GRPO loss, clipping and the k3 KL estimator checked exactly; then a real RLVR run in which a tiny model is updated from nothing but exact-match 0/1 rewards.

- Course pages: [Reinforcement Learning for Reasoning: RLVR and GRPO](https://dmxsf.com/en/wiki/post-training/reasoning-rl/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run post-training/reasoning-rl`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/post-training/reasoning-rl/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/post-training/reasoning-rl/README.en.md)

#### [Reasoning RL systems: rollout and learner scheduling](https://github.com/dmxsf/dmxsf/tree/main/labs/post-training/rollout-and-training)

Replay serial and overlapping jobs, and verify policy lag and dropped batches.

- Course pages: [Reasoning RL systems: asynchronous rollouts and policy lag](https://dmxsf.com/en/wiki/post-training/rollout-and-training/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run post-training/rollout-and-training`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/post-training/rollout-and-training/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/post-training/rollout-and-training/README.en.md)

### Inference and Serving

#### [First inference service: a local HTTP endpoint](https://github.com/dmxsf/dmxsf/tree/main/labs/inference/first-inference-service)

Send real local HTTP requests to a toy decoder and check success and errors.

- Course pages: [Your first inference service: put a model function behind HTTP](https://dmxsf.com/en/wiki/inference/first-inference-service/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run inference/first-inference-service`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/inference/first-inference-service/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/inference/first-inference-service/README.en.md)

#### [Decoding and sampling: temperature, top-k, top-p, min-p, beam search, penalties](https://github.com/dmxsf/dmxsf/tree/main/labs/inference/decoding-and-sampling)

The page's four-token example reproduced exactly (temperature, top-k, top-p, min-p, and why the order matters), whether samples follow the processed distribution, what each knob does to real text, beam search, repetition penalties, and whether batch shape changes greedy output.

- Course pages: [Decoding and Sampling: Temperature, Top-k, Top-p and Beam Search](https://dmxsf.com/en/wiki/inference/decoding-and-sampling/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run inference/decoding-and-sampling`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/inference/decoding-and-sampling/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/inference/decoding-and-sampling/README.en.md)

#### [KV cache: the memory formula, exactness, the saving, prefill against decode](https://github.com/dmxsf/dmxsf/tree/main/labs/inference/kv-cache)

The memory formula against real cache tensors, cached and uncached decoding agreeing exactly, and the saving counted two ways: token positions processed (exact) and time on a CPU (read the ratios), plus the prefill and decode split.

- Course pages: [KV Cache and Inference Performance](https://dmxsf.com/en/wiki/inference/kv-cache/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run inference/kv-cache`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/inference/kv-cache/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/inference/kv-cache/README.en.md)

#### [Prefix caching: cache reuse versus queues](https://github.com/dmxsf/dmxsf/tree/main/labs/inference/prefix-caching)

Replay bursty and spaced arrivals with two cache routing policies.

- Course pages: [Prefix Caching and PD Disaggregation: Pay for Repeated Compute Once](https://dmxsf.com/en/wiki/inference/prefix-caching/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run inference/prefix-caching`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/inference/prefix-caching/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/inference/prefix-caching/README.en.md)

#### [Quantization: the ledger, the grid, weights, activations, calibration, the KV cache](https://github.com/dmxsf/dmxsf/tree/main/labs/inference/quantization)

The 80 GB ledger for Llama 3 8B, the rounding grid, and experiments on a small model: round-to-nearest, SmoothQuant, an AWQ-style scale search, GPTQ and a quantized KV cache, with outliers dialled in and labelled as constructed.

- Course pages: [Model Quantization: INT8, INT4, GPTQ and AWQ Explained and Measured](https://dmxsf.com/en/wiki/inference/quantization/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run inference/quantization`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/inference/quantization/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/inference/quantization/README.en.md)

#### [Serving: continuous batching, paged KV memory, prefix cache, TTFT, capacity](https://github.com/dmxsf/dmxsf/tree/main/labs/inference/continuous-batching)

Roofline and exact batched decoding, static against continuous scheduling on paper and on a real model, a paged KV pool with copy-on-write, a hash-based prefix cache, and what a request costs (TTFT, TPOT, capacity). Read the ratios, not the milliseconds.

- Course pages: [Continuous Batching and PagedAttention: How a Server Handles Many Requests at Once](https://dmxsf.com/en/wiki/inference/continuous-batching/), [LLM Inference Serving: Latency Metrics, Measuring, and Choosing an Engine](https://dmxsf.com/en/wiki/inference/serving/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run inference/continuous-batching`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/inference/continuous-batching/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/inference/continuous-batching/README.en.md)

#### [Speculative decoding: the rule, the formulas, a real draft and target](https://github.com/dmxsf/dmxsf/tree/main/labs/inference/speculative-decoding)

The accept/reject rule that keeps the target's exact distribution, checked on the page's toy distribution, by exact algebra and on real models; the formulas of Leviathan et al.; a draft and target byte-level pair run with KV caches; and when it does not pay.

- Course pages: [Speculative Decoding: Draft with a Small Model, Verify with a Large One](https://dmxsf.com/en/wiki/inference/speculative-decoding/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run inference/speculative-decoding`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/inference/speculative-decoding/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/inference/speculative-decoding/README.en.md)

### Applications

#### [First agent: a bounded tool loop](https://github.com/dmxsf/dmxsf/tree/main/labs/applications/first-agent)

Run a read-only lookup loop and check success, absence, and the step budget.

- Course pages: [Your first agent: a read-only tool and a bounded loop](https://dmxsf.com/en/wiki/applications/first-agent/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run applications/first-agent`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/applications/first-agent/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/applications/first-agent/README.en.md)

#### [Prompting, measured](https://github.com/dmxsf/dmxsf/tree/main/labs/applications/prompt-engineering)

The chat template rendered by hand, what a prefix cache can reuse, scorers that separate format failures from wrong judgments, the twelve word problems re-solved in code, and how far a 12-ticket eval set can be trusted. With --hf the page's experiments are rerun on Qwen2.5-1.5B-Instruct.

- Course pages: [Prompt Engineering: A Systematic Guide to Specs, Layers, Examples and Evaluation](https://dmxsf.com/en/wiki/applications/prompt-engineering/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run applications/prompt-engineering`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/applications/prompt-engineering/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/applications/prompt-engineering/README.en.md)
- Optional: add --hf or --bge to run the real models; needs uv sync --extra hf

#### [Structured output: constrained decoding, its cost, and the function-calling loop](https://github.com/dmxsf/dmxsf/tree/main/labs/applications/structured-output-and-function-calling)

Constrained decoding from the automaton up: the page's demo token for token, why the stepwise mask is not the model's distribution over legal outputs, the mask on a byte-level GPT that has and has not seen the format, schemas, validation and retries.

- Course pages: [Structured Outputs and Function Calling: From JSON Mode to Constrained Decoding](https://dmxsf.com/en/wiki/applications/structured-output-and-function-calling/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run applications/structured-output-and-function-calling`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/applications/structured-output-and-function-calling/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/applications/structured-output-and-function-calling/README.en.md)

#### [RAG, piece by piece](https://github.com/dmxsf/dmxsf/tree/main/labs/applications/rag)

Chunking, similarity and index size, BM25 from the formula, rank fusion (RRF), retrieval metrics and context assembly, reproducing the page's numbers offline; with --bge the dense retriever and the reranker run too.

- Course pages: [RAG in Practice: Chunking, Hybrid Retrieval, Reranking and Evaluation](https://dmxsf.com/en/wiki/applications/rag/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run applications/rag`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/applications/rag/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/applications/rag/README.en.md)
- Optional: add --hf or --bge to run the real models; needs uv sync --extra hf

#### [Agents and tool calling: the loop, its guards, and the trace scorer](https://github.com/dmxsf/dmxsf/tree/main/labs/applications/agents-and-tool-calling)

The tool-calling loop with its guards (format, business rules, repeats, confirmation, step limit) and the scorer, with the model swapped for a scripted stand-in that replays the page's decisions; then pass^k against pass@k. No language model runs.

- Course pages: [Agents and Tool Calling in Practice: From Function Calling to ReAct Workflows](https://dmxsf.com/en/wiki/applications/agents-and-tool-calling/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run applications/agents-and-tool-calling`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/applications/agents-and-tool-calling/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/applications/agents-and-tool-calling/README.en.md)

#### [Agent context and memory: budget and precedence](https://github.com/dmxsf/dmxsf/tree/main/labs/applications/context-and-memory)

Keep tool groups whole and verify overrides and deletion on versioned records.

- Course pages: [Agent context and memory: budgets, versions, and state](https://dmxsf.com/en/wiki/applications/context-and-memory/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run applications/context-and-memory`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/applications/context-and-memory/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/applications/context-and-memory/README.en.md)

#### [Agent evaluation: repeatability and terminal state](https://github.com/dmxsf/dmxsf/tree/main/labs/applications/agent-evaluation)

Compare equal one-run scores and validate four calendar traces.

- Course pages: [Agent Evaluation: You Are Grading the System, Not the Model](https://dmxsf.com/en/wiki/applications/agent-evaluation/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run applications/agent-evaluation`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/applications/agent-evaluation/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/applications/agent-evaluation/README.en.md)

#### [MCP tools: inspect discovery, calls and schema size](https://github.com/dmxsf/dmxsf/tree/main/labs/applications/mcp-and-tool-ecosystem)

Inspect offline JSON-RPC tools/list and tools/call messages and measure what narrowing the catalog sends to a client.

- Course pages: [MCP and the Tool Ecosystem: How It Works and What to Do When Tools Pile Up](https://dmxsf.com/en/wiki/applications/mcp-and-tool-ecosystem/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run applications/mcp-and-tool-ecosystem`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/applications/mcp-and-tool-ecosystem/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/applications/mcp-and-tool-ecosystem/README.en.md)

### Multimodal

#### [Multimodal LLMs: images as tokens](https://github.com/dmxsf/dmxsf/tree/main/labs/multimodal/multimodal-llms)

Patches to visual tokens, what the tokens cost in KV cache and FLOPs, LLaVA's projector and two training stages, CLIP's contrastive loss and a small CLIP trained from scratch on rendered shapes. With --hf, CLIP ViT-B/32 on CIFAR-10.

- Course pages: [Multimodal LLMs: How an Image Becomes Tokens](https://dmxsf.com/en/wiki/multimodal/multimodal-llms/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run multimodal/multimodal-llms`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/multimodal/multimodal-llms/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/multimodal/multimodal-llms/README.en.md)
- Optional: add --hf or --bge to run the real models; needs uv sync --extra hf

#### [Diffusion and flow matching: verify a Gaussian path](https://github.com/dmxsf/dmxsf/tree/main/labs/multimodal/diffusion-and-flow-matching)

Measure the forward diffusion variance and integrate a simple analytic flow, checking how Euler error changes with step count.

- Course pages: [Diffusion Models and Flow Matching: Generating Images, Actions and Text from Noise](https://dmxsf.com/en/wiki/multimodal/diffusion-and-flow-matching/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run multimodal/diffusion-and-flow-matching`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/multimodal/diffusion-and-flow-matching/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/multimodal/diffusion-and-flow-matching/README.en.md)

#### [World models: plan, observe, and replan](https://github.com/dmxsf/dmxsf/tree/main/labs/multimodal/world-models)

Compare fixed execution with feedback on a grid with a hidden wall.

- Course pages: [World models and planning: from prediction to closed-loop control](https://dmxsf.com/en/wiki/multimodal/world-models/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run multimodal/world-models`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/multimodal/world-models/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/multimodal/world-models/README.en.md)

### Evaluation

#### [Benchmark contamination: an n-gram detector, and a leak you can measure](https://github.com/dmxsf/dmxsf/tree/main/labs/evaluation/llm-evaluation)

The page's n-gram contamination detector on its own example; a benchmark whose answers can only be memorised; a model trained with a third of it leaked verbatim, a third paraphrased and a third absent; what the detector flags and what the clean-subset check concludes.

- Course pages: [LLM Evaluation Methodology: Benchmarks, Contamination and a Workflow](https://dmxsf.com/en/wiki/evaluation/llm-evaluation/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run evaluation/llm-evaluation`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/evaluation/llm-evaluation/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/evaluation/llm-evaluation/README.en.md)

#### [Evaluation statistics: pass@k, the error of a score, paired tests, sample sizes](https://github.com/dmxsf/dmxsf/tree/main/labs/evaluation/eval-statistics)

pass@k against brute-force enumeration, the 95% interval against how often it actually covers, paired comparisons and the sample-size table against the power of a real test, then two real models compared on held-out text.

- Course pages: [The Statistics of Evaluation: pass@k, Confidence Intervals and Sample Size](https://dmxsf.com/en/wiki/evaluation/eval-statistics/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run evaluation/eval-statistics`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/evaluation/eval-statistics/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/evaluation/eval-statistics/README.en.md)

#### [LLM-as-a-judge: bias, agreement, and Bradley-Terry leaderboards](https://github.com/dmxsf/dmxsf/tree/main/labs/evaluation/llm-as-judge)

A judge stand-in with chosen biases, so every number has an exact answer: swapping the order cancels position bias but not length bias, Cohen's kappa exposes a judge that always guesses the majority class, and a Bradley-Terry leaderboard is corrected for length.

- Course pages: [LLM-as-a-Judge: Using a Model as the Grader, Its Biases and Calibration](https://dmxsf.com/en/wiki/evaluation/llm-as-judge/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run evaluation/llm-as-judge`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/evaluation/llm-as-judge/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/evaluation/llm-as-judge/README.en.md)

#### [Evaluation sets: noisy labels, agreement and item information](https://github.com/dmxsf/dmxsf/tree/main/labs/evaluation/building-eval-sets)

Check a four-option label-noise formula by simulation, compute Cohen's kappa, and locate a 2PL item's most informative difficulty.

- Course pages: [Building Evaluation Sets: Question Sources, Label Quality and Item Information](https://dmxsf.com/en/wiki/evaluation/building-eval-sets/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run evaluation/building-eval-sets`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/evaluation/building-eval-sets/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/evaluation/building-eval-sets/README.en.md)

#### [Benchmark contamination: detect wording overlap and audit slices](https://github.com/dmxsf/dmxsf/tree/main/labs/evaluation/benchmark-contamination)

Build real overlap flags on synthetic benchmark questions and audit how averaging hides contaminated and clean slices.

- Course pages: [Benchmark Contamination: How It Happens, How to Detect It, How to Avoid It](https://dmxsf.com/en/wiki/evaluation/benchmark-contamination/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run evaluation/benchmark-contamination`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/evaluation/benchmark-contamination/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/evaluation/benchmark-contamination/README.en.md)

#### [Production evaluation: replay and release gates](https://github.com/dmxsf/dmxsf/tree/main/labs/evaluation/production-evaluation)

Replay paired outcomes and detect regressions and missing coverage in critical slices.

- Course pages: [Production evaluation for LLMs: replay, canaries, and rollback](https://dmxsf.com/en/wiki/evaluation/production-evaluation/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run evaluation/production-evaluation`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/evaluation/production-evaluation/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/evaluation/production-evaluation/README.en.md)

### Safety and Alignment Risks

#### [Tool authorization: separate data, proposals and permissions](https://github.com/dmxsf/dmxsf/tree/main/labs/safety/prompt-injection-and-jailbreaks)

Replay a benign read and policy-boundary cases in a mocked runtime, verifying that content cannot grant new privileges.

- Course pages: [Prompt Injection and Jailbreaks: The Security Boundaries of LLM Applications](https://dmxsf.com/en/wiki/safety/prompt-injection-and-jailbreaks/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run safety/prompt-injection-and-jailbreaks`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/safety/prompt-injection-and-jailbreaks/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/safety/prompt-injection-and-jailbreaks/README.en.md)

#### [Calibration: withheld answers, confidence and accuracy](https://github.com/dmxsf/dmxsf/tree/main/labs/safety/hallucination-and-calibration)

Fit temperature on held-out calibration examples and plot the trade-off between coverage and error using synthetic scores.

- Course pages: [Hallucination and Calibration: Why Models Sound Sure and Are Wrong](https://dmxsf.com/en/wiki/safety/hallucination-and-calibration/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run safety/hallucination-and-calibration`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/safety/hallucination-and-calibration/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/safety/hallucination-and-calibration/README.en.md)

#### [Privacy audit: exposure for synthetic canaries](https://github.com/dmxsf/dmxsf/tree/main/labs/safety/memorization-and-privacy)

Compare rank exposure and top-one generation using an artificial candidate distribution, then measure uniform-rank exposure.

- Course pages: [Memorization and Privacy: What Models Remember, How to Measure and Reduce It](https://dmxsf.com/en/wiki/safety/memorization-and-privacy/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run safety/memorization-and-privacy`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/safety/memorization-and-privacy/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/safety/memorization-and-privacy/README.en.md)

### Frontier

#### [Test-time compute: independent draws, reranking and majority voting](https://github.com/dmxsf/dmxsf/tree/main/labs/frontier/test-time-compute)

Compare independent and perfectly correlated draws and compute how a noisy selector changes best-of-N.

- Course pages: [Test-Time Compute: Spending Compute on Inference](https://dmxsf.com/en/wiki/frontier/test-time-compute/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run frontier/test-time-compute`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/frontier/test-time-compute/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/frontier/test-time-compute/README.en.md)

#### [Synthetic data: rare-event loss and verified selection](https://github.com/dmxsf/dmxsf/tree/main/labs/frontier/synthetic-data-and-self-improvement)

Measure support lost when each generation replaces the previous one, then see how an independent verifier filters synthetic labels.

- Course pages: [Synthetic Data and Self-Improvement: When Models Make Data, and When It Collapses](https://dmxsf.com/en/wiki/frontier/synthetic-data-and-self-improvement/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run frontier/synthetic-data-and-self-improvement`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/frontier/synthetic-data-and-self-improvement/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/frontier/synthetic-data-and-self-improvement/README.en.md)

#### [Interpretability: superposed features and causal patching](https://github.com/dmxsf/dmxsf/tree/main/labs/frontier/interpretability)

Measure interference between nonorthogonal features and patch one controlled activation to explain a toy prediction change.

- Course pages: [Mechanistic Interpretability: Superposition, Sparse Autoencoders and Circuits](https://dmxsf.com/en/wiki/frontier/interpretability/)
- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run frontier/interpretability`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/frontier/interpretability/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/frontier/interpretability/README.en.md)

## Follow a study route

These are the roadmap's own routes: the labs behind the pages you read in a week or step are the ones to run in it.

### Route 0: Weekend crash course (about 10 hours)

- Step 1: [What is an LLM? The whole loop, small enough to read](https://github.com/dmxsf/dmxsf/tree/main/labs/start/what-is-an-llm)
- Step 2: [Next-token prediction and information theory](https://github.com/dmxsf/dmxsf/tree/main/labs/foundations/next-token-prediction)
- Step 3: [Attention, by hand and in a model](https://github.com/dmxsf/dmxsf/tree/main/labs/architecture/attention-basics)
- Step 4: [The Transformer block and the modern recipe](https://github.com/dmxsf/dmxsf/tree/main/labs/architecture/transformer-block)
- Step 5: [The pretraining pipeline on a laptop: monitoring, data mix, resuming, leakage](https://github.com/dmxsf/dmxsf/tree/main/labs/pretraining/training-pipeline)
- Step 6: [KV cache: the memory formula, exactness, the saving, prefill against decode](https://github.com/dmxsf/dmxsf/tree/main/labs/inference/kv-cache)
- Step 7: [Benchmark contamination: an n-gram detector, and a leak you can measure](https://github.com/dmxsf/dmxsf/tree/main/labs/evaluation/llm-evaluation)

### Route 1: AI application developer (8 weeks)

- Week 1: [What is an LLM? The whole loop, small enough to read](https://github.com/dmxsf/dmxsf/tree/main/labs/start/what-is-an-llm), [Next-token prediction and information theory](https://github.com/dmxsf/dmxsf/tree/main/labs/foundations/next-token-prediction), [Decoding and sampling: temperature, top-k, top-p, min-p, beam search, penalties](https://github.com/dmxsf/dmxsf/tree/main/labs/inference/decoding-and-sampling)
- Week 2: [Prompting, measured](https://github.com/dmxsf/dmxsf/tree/main/labs/applications/prompt-engineering), [Structured output: constrained decoding, its cost, and the function-calling loop](https://github.com/dmxsf/dmxsf/tree/main/labs/applications/structured-output-and-function-calling)
- Week 3: [Benchmark contamination: an n-gram detector, and a leak you can measure](https://github.com/dmxsf/dmxsf/tree/main/labs/evaluation/llm-evaluation), [Evaluation statistics: pass@k, the error of a score, paired tests, sample sizes](https://github.com/dmxsf/dmxsf/tree/main/labs/evaluation/eval-statistics)
- Week 4: [First inference service: a local HTTP endpoint](https://github.com/dmxsf/dmxsf/tree/main/labs/inference/first-inference-service), [RAG, piece by piece](https://github.com/dmxsf/dmxsf/tree/main/labs/applications/rag)
- Week 5: [First agent: a bounded tool loop](https://github.com/dmxsf/dmxsf/tree/main/labs/applications/first-agent), [Agents and tool calling: the loop, its guards, and the trace scorer](https://github.com/dmxsf/dmxsf/tree/main/labs/applications/agents-and-tool-calling), [Agent evaluation: repeatability and terminal state](https://github.com/dmxsf/dmxsf/tree/main/labs/applications/agent-evaluation), [MCP tools: inspect discovery, calls and schema size](https://github.com/dmxsf/dmxsf/tree/main/labs/applications/mcp-and-tool-ecosystem), [Agent context and memory: budget and precedence](https://github.com/dmxsf/dmxsf/tree/main/labs/applications/context-and-memory)
- Week 6: [Tool authorization: separate data, proposals and permissions](https://github.com/dmxsf/dmxsf/tree/main/labs/safety/prompt-injection-and-jailbreaks), [Calibration: withheld answers, confidence and accuracy](https://github.com/dmxsf/dmxsf/tree/main/labs/safety/hallucination-and-calibration), [Privacy audit: exposure for synthetic canaries](https://github.com/dmxsf/dmxsf/tree/main/labs/safety/memorization-and-privacy)
- Week 7: [Serving: continuous batching, paged KV memory, prefix cache, TTFT, capacity](https://github.com/dmxsf/dmxsf/tree/main/labs/inference/continuous-batching), [KV cache: the memory formula, exactness, the saving, prefill against decode](https://github.com/dmxsf/dmxsf/tree/main/labs/inference/kv-cache), [Quantization: the ledger, the grid, weights, activations, calibration, the KV cache](https://github.com/dmxsf/dmxsf/tree/main/labs/inference/quantization)
- Week 8: [Evaluation sets: noisy labels, agreement and item information](https://github.com/dmxsf/dmxsf/tree/main/labs/evaluation/building-eval-sets), [LLM-as-a-judge: bias, agreement, and Bradley-Terry leaderboards](https://github.com/dmxsf/dmxsf/tree/main/labs/evaluation/llm-as-judge), [Production evaluation: replay and release gates](https://github.com/dmxsf/dmxsf/tree/main/labs/evaluation/production-evaluation)

### Route 2: LLM engineer (14 weeks)

- Week 1: [Tensor shapes: a linear layer by hand](https://github.com/dmxsf/dmxsf/tree/main/labs/foundations/tensors-and-shapes), [Neural networks: gradients and XOR](https://github.com/dmxsf/dmxsf/tree/main/labs/foundations/neural-network-basics), [Next-token prediction and information theory](https://github.com/dmxsf/dmxsf/tree/main/labs/foundations/next-token-prediction)
- Week 2: [Tokenizers and embeddings](https://github.com/dmxsf/dmxsf/tree/main/labs/foundations/tokenizer-and-embeddings), [From RNN to attention: gradients and retrieval paths](https://github.com/dmxsf/dmxsf/tree/main/labs/architecture/from-rnn-to-attention), [Attention, by hand and in a model](https://github.com/dmxsf/dmxsf/tree/main/labs/architecture/attention-basics)
- Week 3: [Position encodings and length extrapolation](https://github.com/dmxsf/dmxsf/tree/main/labs/architecture/positional-encoding), [The Transformer block and the modern recipe](https://github.com/dmxsf/dmxsf/tree/main/labs/architecture/transformer-block)
- Week 4: [The Transformer block and the modern recipe](https://github.com/dmxsf/dmxsf/tree/main/labs/architecture/transformer-block), [Efficient attention](https://github.com/dmxsf/dmxsf/tree/main/labs/architecture/efficient-attention)
- Week 5: [The pretraining pipeline on a laptop: monitoring, data mix, resuming, leakage](https://github.com/dmxsf/dmxsf/tree/main/labs/pretraining/training-pipeline), [Optimizers, schedules, mixed precision and loss spikes](https://github.com/dmxsf/dmxsf/tree/main/labs/foundations/optimizers-and-training-stability), [Data engineering: build and audit a dedup filter](https://github.com/dmxsf/dmxsf/tree/main/labs/pretraining/data-engineering)
- Week 6: [Scaling laws: the formulas, the serving cost, and a tiny study of our own](https://github.com/dmxsf/dmxsf/tree/main/labs/pretraining/scaling-laws), [Training compute and memory: 6ND, MFU, model state and activations](https://github.com/dmxsf/dmxsf/tree/main/labs/pretraining/compute-and-memory)
- Week 7: [Hardware basics: storage and copy time](https://github.com/dmxsf/dmxsf/tree/main/labs/systems/hardware-basics), [GPU roofline: bytes, FLOPs and tile reuse](https://github.com/dmxsf/dmxsf/tree/main/labs/systems/gpu-and-roofline), [Numerical precision: rounding, overflow and loss scaling](https://github.com/dmxsf/dmxsf/tree/main/labs/systems/numerical-precision), [GPU kernels: tiled GEMM and memory traffic](https://github.com/dmxsf/dmxsf/tree/main/labs/systems/gpu-kernels)
- Week 8: [Distributed training: gradients, ZeRO, tensor and pipeline parallelism](https://github.com/dmxsf/dmxsf/tree/main/labs/pretraining/distributed-training), [Collective communication: simulate a ring all-reduce](https://github.com/dmxsf/dmxsf/tree/main/labs/systems/collective-communication)
- Week 9: [SFT data: the loss mask, a data health check, and what data size, noise, masking and replay do](https://github.com/dmxsf/dmxsf/tree/main/labs/post-training/sft-data), [LoRA: the parameter bill, the mechanics, LoRA against full fine-tuning, merging, NF4](https://github.com/dmxsf/dmxsf/tree/main/labs/post-training/lora-finetuning), [Privacy audit: exposure for synthetic canaries](https://github.com/dmxsf/dmxsf/tree/main/labs/safety/memorization-and-privacy)
- Week 10: [Reward models: pairwise scores and label noise](https://github.com/dmxsf/dmxsf/tree/main/labs/post-training/reward-models), [Policy gradients: exact checks, baselines and GAE](https://github.com/dmxsf/dmxsf/tree/main/labs/post-training/rl-fundamentals), [Preference optimization: the DPO loss, its closed form, and a real DPO run](https://github.com/dmxsf/dmxsf/tree/main/labs/post-training/preference-optimization)
- Week 11: [KV cache: the memory formula, exactness, the saving, prefill against decode](https://github.com/dmxsf/dmxsf/tree/main/labs/inference/kv-cache), [Quantization: the ledger, the grid, weights, activations, calibration, the KV cache](https://github.com/dmxsf/dmxsf/tree/main/labs/inference/quantization)
- Week 12: [Serving: continuous batching, paged KV memory, prefix cache, TTFT, capacity](https://github.com/dmxsf/dmxsf/tree/main/labs/inference/continuous-batching), [Speculative decoding: the rule, the formulas, a real draft and target](https://github.com/dmxsf/dmxsf/tree/main/labs/inference/speculative-decoding), [Prefix caching: cache reuse versus queues](https://github.com/dmxsf/dmxsf/tree/main/labs/inference/prefix-caching)
- Week 13: [Benchmark contamination: an n-gram detector, and a leak you can measure](https://github.com/dmxsf/dmxsf/tree/main/labs/evaluation/llm-evaluation), [Evaluation statistics: pass@k, the error of a score, paired tests, sample sizes](https://github.com/dmxsf/dmxsf/tree/main/labs/evaluation/eval-statistics), [Evaluation sets: noisy labels, agreement and item information](https://github.com/dmxsf/dmxsf/tree/main/labs/evaluation/building-eval-sets)
- Week 14: [Multimodal LLMs: images as tokens](https://github.com/dmxsf/dmxsf/tree/main/labs/multimodal/multimodal-llms), [Test-time compute: independent draws, reranking and majority voting](https://github.com/dmxsf/dmxsf/tree/main/labs/frontier/test-time-compute)

### Route 3: LLM researcher (16 weeks)

- Week 1: [From RNN to attention: gradients and retrieval paths](https://github.com/dmxsf/dmxsf/tree/main/labs/architecture/from-rnn-to-attention)
- Week 2: Reading or writing for this step
- Week 3: [The Transformer block and the modern recipe](https://github.com/dmxsf/dmxsf/tree/main/labs/architecture/transformer-block)
- Week 4: [Scaling laws: the formulas, the serving cost, and a tiny study of our own](https://github.com/dmxsf/dmxsf/tree/main/labs/pretraining/scaling-laws)
- Week 5: [Mixture of experts: routing, load balance and the parameter accounts](https://github.com/dmxsf/dmxsf/tree/main/labs/architecture/mixture-of-experts)
- Week 6: [Efficient attention](https://github.com/dmxsf/dmxsf/tree/main/labs/architecture/efficient-attention)
- Week 7: [GPU roofline: bytes, FLOPs and tile reuse](https://github.com/dmxsf/dmxsf/tree/main/labs/systems/gpu-and-roofline)
- Week 8: [Position encodings and length extrapolation](https://github.com/dmxsf/dmxsf/tree/main/labs/architecture/positional-encoding)
- Week 9: [Reward models: pairwise scores and label noise](https://github.com/dmxsf/dmxsf/tree/main/labs/post-training/reward-models)
- Week 10: [Policy gradients: exact checks, baselines and GAE](https://github.com/dmxsf/dmxsf/tree/main/labs/post-training/rl-fundamentals), [Preference optimization: the DPO loss, its closed form, and a real DPO run](https://github.com/dmxsf/dmxsf/tree/main/labs/post-training/preference-optimization)
- Week 11: [Reasoning RL: verifiers, GRPO advantages and loss, and a real RLVR run](https://github.com/dmxsf/dmxsf/tree/main/labs/post-training/reasoning-rl), [Reasoning RL systems: rollout and learner scheduling](https://github.com/dmxsf/dmxsf/tree/main/labs/post-training/rollout-and-training)
- Week 12: [Test-time compute: independent draws, reranking and majority voting](https://github.com/dmxsf/dmxsf/tree/main/labs/frontier/test-time-compute), [World models: plan, observe, and replan](https://github.com/dmxsf/dmxsf/tree/main/labs/multimodal/world-models)
- Week 13: [Benchmark contamination: an n-gram detector, and a leak you can measure](https://github.com/dmxsf/dmxsf/tree/main/labs/evaluation/llm-evaluation), [Evaluation statistics: pass@k, the error of a score, paired tests, sample sizes](https://github.com/dmxsf/dmxsf/tree/main/labs/evaluation/eval-statistics), [Evaluation sets: noisy labels, agreement and item information](https://github.com/dmxsf/dmxsf/tree/main/labs/evaluation/building-eval-sets), [Benchmark contamination: detect wording overlap and audit slices](https://github.com/dmxsf/dmxsf/tree/main/labs/evaluation/benchmark-contamination)
- Week 14: [Calibration: withheld answers, confidence and accuracy](https://github.com/dmxsf/dmxsf/tree/main/labs/safety/hallucination-and-calibration), [Tool authorization: separate data, proposals and permissions](https://github.com/dmxsf/dmxsf/tree/main/labs/safety/prompt-injection-and-jailbreaks), [Privacy audit: exposure for synthetic canaries](https://github.com/dmxsf/dmxsf/tree/main/labs/safety/memorization-and-privacy)
- Week 15: Reading or writing for this step
- Week 16: Reading or writing for this step

