Skip to content

A straightforward method for training your LLM, from downloading data to generating text.

Add post-training suite tooling: JSON configs, Streamlit UI, MkDocs site

FareedKhan-devff00dae9e684
diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml
new file mode 100644
index 0000000..126e0a8
--- /dev/null
+++ b/.github/workflows/docs.yml
@@ -0,0 +1,35 @@
+name: docs
+
+# Build the MkDocs Material site and publish it to GitHub Pages (the gh-pages branch).
+# One-time setup after the first run: repo Settings -> Pages -> Source = "Deploy from a
+# branch" -> branch "gh-pages" / root.
+
+on:
+ push:
+ branches: [main]
+ paths:
+ - "docs/**"
+ - "mkdocs.yml"
+ - "POST_TRAINING.md"
+ - ".github/workflows/docs.yml"
+ workflow_dispatch: {}
+
+permissions:
+ contents: write # mkdocs gh-deploy pushes to the gh-pages branch
+
+jobs:
+ deploy:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.11"
+ - name: Install docs dependencies
+ run: pip install mkdocs mkdocs-material pymdown-extensions
+ - name: Build (strict) and deploy to gh-pages
+ run: |
+ mkdocs build --strict # fail fast on broken links / nav
+ mkdocs gh-deploy --force # build + push to the gh-pages branch
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..315fb91
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,21 @@
+__pycache__/
+*.pyc
+*.pyo
+.ipynb_checkpoints/
+
+# build / packaging artifacts (generated by `pip install -e .`)
+*.egg-info/
+build/
+dist/
+
+# generated docs site
+site/
+
+# data / model artifacts (kept on the /ephemeral disk, not committed)
+data/
+models/
+*.h5
+*.pt
+*.jsonl
+wandb/
+/ephemeral/
diff --git a/.streamlit/config.toml b/.streamlit/config.toml
new file mode 100644
index 0000000..3055b11
--- /dev/null
+++ b/.streamlit/config.toml
@@ -0,0 +1,13 @@
+[theme]
+primaryColor = "#16a085"
+backgroundColor = "#ffffff"
+secondaryBackgroundColor = "#f3faf8"
+textColor = "#0a3d33"
+font = "sans serif"
+
+[server]
+headless = true
+runOnSave = true
+
+[browser]
+gatherUsageStats = false
diff --git a/POST_TRAINING.md b/POST_TRAINING.md
new file mode 100644
index 0000000..5f2c10e
--- /dev/null
+++ b/POST_TRAINING.md
@@ -0,0 +1,196 @@
+# Post-Training from Scratch: SFT · Reward Model · PPO · DPO · GRPO
+
+This adds a complete, **from-scratch** (pure PyTorch — no `trl`/`peft`/`transformers`)
+post-training suite on top of the repo's own `Transformer`, covering the full modern
+pipeline used to turn a base LM into an aligned, reasoning model:
+
+```
+Base (pretrained) ──► SFT ──► Reward Model ──► PPO ┐
+ │ ├─► GRPO / RLVR (GSM8K)
+ └────────► DPO / ORPO / KTO ─┘
+```
+
+Everything is self-contained on the repo's custom model and trained/evaluated on **real
+public datasets** (Alpaca, Dolly, Anthropic HH-RLHF, UltraFeedback, GSM8K). The headline
+metric is **greedy GSM8K accuracy across stages**.
+
+> **Expectation:** a ~400M model pretrained from scratch on 2×H100 is coherent and
+> instruction-followable and shows real before/after gains at each stage, but its
+> *absolute* GSM8K score stays modest — frontier numbers need far more pretraining
+> compute. The value here is the authentic end-to-end pipeline on real data with real eval.
+
+---
+
+## 0. Environment
+
+H100s need CUDA-12 wheels (the original `requirements.txt` pins cu118 for the legacy
+pretraining path and is left untouched). Use a separate venv + `requirements-post.txt`,
+and keep all large artifacts on the big `/ephemeral` disk.
+
+```bash
+python3 -m venv /ephemeral/venv && source /ephemeral/venv/bin/activate
+pip install -r requirements-post.txt # torch cu121 + datasets/wandb/tiktoken/h5py
+export HF_HOME=/ephemeral/hf_cache
+```
+
+Run everything from the repo root with `PYTHONPATH=.`. Single GPU: `python scripts/X.py`.
+Both GPUs: `torchrun --standalone --nproc_per_node=2 scripts/X.py` (DDP + bf16, one code path).
+
+Config lives in [config/post_training_config.py](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/config/post_training_config.py) as
+per-stage dataclasses; **any field is a CLI override**, e.g. `--lr 2e-5 --batch_size 16`.
+The default base model is ~400M (`n_embed=1024, n_head=16, n_blocks=24, context_length=1024`).
+
+---
+
+## 1. Pretrain the base (the long pole)
+
+```bash
+# one-time data prep (Pile -> flat-token HDF5 on /ephemeral)
+PYTHONPATH=. python scripts/prepare_pretrain_data.py --split val --out /ephemeral/data/pile_dev.h5
+PYTHONPATH=. python scripts/prepare_pretrain_data.py --split train --num_shards 1 --out /ephemeral/data/pile_train.h5
+
+# pretrain (multi-day for full quality; checkpoints continuously to /ephemeral/ckpts/base_pretrained.pt)
+PYTHONPATH=. torchrun --standalone --nproc_per_node=2 scripts/pretrain_base.py
+```
+
+[scripts/pretrain_base.py](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/scripts/pretrain_base.py) upgrades the original
+`train_transformer.py` recipe with DDP, bf16 autocast, gradient accumulation, a cosine LR
+schedule with warmup, and periodic checkpointing — everything needed to train a mid-size
+model on 2×H100. The original training script is untouched.
+
+---
+
+## 2. SFT (instruction tuning)
+
+```bash
+PYTHONPATH=. python scripts/prepare_sft_data.py --context_length 1024 # Alpaca+Dolly+GSM8K -> packed HDF5
+PYTHONPATH=. torchrun --standalone --nproc_per_node=2 scripts/train_sft.py # -> /ephemeral/ckpts/sft.pt
+```
+
+- **From-scratch loss:** prompt-masked next-token CE in
+ [src/post_training/sft.py](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/sft.py) (`sft_loss`). Only assistant tokens
+ are trained (mask from the chat template); sequence **packing** fills each row to the
+ context length.
+- **Chat format:** [src/post_training/chat_template.py](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/chat_template.py).
+ The r50k_base tokenizer has only `<|endoftext|>` as a special token, so role markers
+ (`<|user|>`, `<|assistant|>`, `<think>`, `<answer>`) are ordinary tokens the model learns.
+ GSM8K is reformatted into `<think>…</think><answer>N</answer>` so the model learns the
+ exact output structure the RL verifier rewards.
+- **Eval:** masked dev perplexity + greedy GSM8K dev accuracy.
+
+## 3. Reward Model
+
+```bash
+PYTHONPATH=. python scripts/prepare_preference_data.py --source both # HH-RLHF + UltraFeedback -> JSONL
+PYTHONPATH=. torchrun --standalone --nproc_per_node=2 scripts/train_reward.py # -> reward.pt
+```
+
+- **From-scratch:** a scalar reward head on the SFT backbone
+ ([src/post_training/reward_model.py](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/reward_model.py)), trained with the
+ **Bradley-Terry** pairwise loss in
+ [src/post_training/reward_train.py](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/reward_train.py). The reward is read
+ off the last real token (causal attention makes right-padding safe — no attention mask
+ needed). **Eval:** held-out preference accuracy (expect ~0.65–0.75 on noisy real data).
+
+## 4. DPO / ORPO / KTO
+
+```bash
+PYTHONPATH=. torchrun --standalone --nproc_per_node=2 scripts/train_dpo.py --loss_type dpo --beta 0.1
+# --loss_type orpo (reference-free, folds SFT+alignment into one stage)
+# --loss_type kto (unpaired, reference-KL baseline)
+```
+
+- **From-scratch:** all three objectives in [src/post_training/dpo.py](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/dpo.py).
+ Policy initialized from SFT; a frozen deep copy is the reference (ORPO needs none).
+ Operates on summed response log-probs from
+ [src/post_training/rollout.py](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/rollout.py) (`sequence_logprobs`).
+ **Eval:** implicit-reward accuracy/margins + GSM8K dev.
+
+## 5. PPO (classic RLHF)
+
+```bash
+PYTHONPATH=. python scripts/prepare_rl_prompts.py # GSM8K + arithmetic warm-up -> JSONL
+PYTHONPATH=. torchrun --standalone --nproc_per_node=2 scripts/train_ppo.py --reward_source verifier
+# --reward_source rm to use the trained reward model instead of the GSM8K checker
+```
+
+- **From-scratch:** GAE, clipped policy/value losses in
+ [src/post_training/ppo.py](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/ppo.py); the actor-critic shares the backbone
+ via [src/post_training/value_head.py](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/value_head.py). Each iteration:
+ roll out → score (verifier or RM) → add per-token **KL-to-reference** penalty → GAE →
+ several clipped-surrogate epochs. **Eval:** reward / KL / clip-fraction / value-loss curves
+ and greedy GSM8K test accuracy.
+
+## 6. GRPO / RLVR (the 2025 frontier; DeepSeek-R1 style)
+
+```bash
+PYTHONPATH=. torchrun --standalone --nproc_per_node=2 scripts/train_grpo.py --group_size 8
+```
+
+- **From-scratch:** group-relative advantages + token-level clipped surrogate with a k3 KL
+ penalty in [src/post_training/grpo.py](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/grpo.py). **No critic** — the
+ baseline is each prompt's own group of G samples. An **arithmetic curriculum** runs for
+ the first `curriculum_iters` iterations so the policy has non-zero reward variance before
+ full GSM8K. **Eval:** mean group reward, informative-group fraction, KL, GSM8K test accuracy.
+
+---
+
+## 7. Inference / chat (any stage checkpoint)
+
+[scripts/chat.py](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/scripts/chat.py) loads **any** checkpoint (base/sft/dpo/ppo/grpo) —
+reading the model dims from the checkpoint itself — and generates with the chat template
+(instruction models) or as raw continuation (the base model):
+
+```bash
+# instruction-tuned models (chat template applied automatically)
+PYTHONPATH=. python scripts/chat.py --ckpt /ephemeral/ckpts/sft.pt --prompt "What is 13 + 29?"
+PYTHONPATH=. python scripts/chat.py --ckpt /ephemeral/ckpts/grpo.pt --prompt "..." --greedy
+# base model continuation
+PYTHONPATH=. python scripts/chat.py --ckpt /ephemeral/ckpts/base_pretrained.pt --raw --prompt "Once upon a time"
+# interactive REPL (omit --prompt); sampling via --temperature/--top_p/--top_k or --greedy
+PYTHONPATH=. python scripts/chat.py --ckpt /ephemeral/ckpts/sft.pt
+```
+
+Generation reuses the same tested core as training/eval
+([src/post_training/rollout.py](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/rollout.py),
+[src/post_training/inference.py](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/inference.py)).
+
+## 8. The across-stages results table
+
+```bash
+for s in base_pretrained sft dpo ppo grpo; do
+ PYTHONPATH=. python scripts/eval_post_training.py --ckpt /ephemeral/ckpts/$s.pt \
+ --label $s --limit 200 --append /ephemeral/logs/stage_table.jsonl
+done
+PYTHONPATH=. python scripts/eval_post_training.py --table /ephemeral/logs/stage_table.jsonl
+```
+
+Every trainer also writes a JSONL metrics file under `/ephemeral/logs/` (plottable without
+any external service); pass `--use_wandb true` to also mirror to Weights & Biases.
+
+---
+
+## Design notes (why it's built this way)
+
+- **Wrap, don't rewrite.** The educational `Transformer`/`Block`/`Head`/`MLP` are unchanged
+ except one additive method, `forward_hidden` (returns post-final-LN hidden states the
+ heads consume). Value head, reward head, and all RL log-prob math compose around it.
+- **Causal attention ⇒ right-padding is safe.** The last real token never attends to
+ padding after it, so RM (last-token reward) and DPO (masked response) need no attention
+ mask; the response mask zeros padded positions in the loss.
+- **fp32 log-probs.** PPO/GRPO/DPO subtract log-probs, so they're always computed in fp32
+ even under bf16 autocast.
+- **Context cap.** Learned absolute positions cap any sequence at `context_length`; rollouts
+ enforce `prompt + generation ≤ context_length`.
+- **Reward hacking / KL control.** Verifier rewards are correctness-dominant with a small,
+ bounded format bonus; a KL-to-reference penalty anchors RL to the SFT policy.
+
+## Tests
+
+```bash
+PYTHONPATH=. python tests/test_post_training_smoke.py # core math: log-probs, heads, parsing, masking
+```
+
+Each trainer also runs end-to-end on a tiny model in seconds (see the smoke commands used
+during development), and the PPO/GRPO math has standalone unit checks (GAE, clipped losses,
+group advantages, k3 KL).
diff --git a/README.md b/README.md
index 3db40c2..ef35e6f 100644
--- a/README.md
+++ b/README.md
@@ -13,6 +13,13 @@
I implemented a transformer model from scratch using PyTorch, based on the paper [Attention is All You Need](https://arxiv.org/abs/1706.03762). You can use my scripts to train your own **billion** or **million** parameter LLM using a single GPU.
+> **New: from-scratch post-training suite (SFT · Reward Model · PPO · DPO · GRPO/RLVR).**
+> The repo now goes beyond pretraining all the way to a modern aligned reasoning model —
+> `Base → SFT → Reward Model → {PPO, DPO} → GRPO` — every algorithm hand-written in pure
+> PyTorch (no `trl`/`peft`/`transformers`) on this repo's own `Transformer`, trained on real
+> public datasets (Alpaca, Dolly, Anthropic HH-RLHF, UltraFeedback, GSM8K) and built for
+> multi-GPU (DDP + bf16). See **[POST_TRAINING.md](POST_TRAINING.md)** for the full guide.
+
Below is the output of the trained 13 million parameter LLM:
```
@@ -44,6 +51,7 @@ Odambinais is uncertain and fortune established in rural areas.
- [Saving the Trained Model](#saving-the-trained-model)
- [Training Loss](#training-loss)
- [Generating Text](#generating-text)
+- [Post-Training & Alignment (SFT · RM · PPO · DPO · GRPO)](#post-training--alignment-sft--rm--ppo--dpo--grpo)
- [What’s Next](#whats-next)
## Training Data Info
@@ -152,10 +160,21 @@ train-llm-from-scratch/
│ ├── train/ # Contains training data
│ └── val/ # Contains validation data
├── models/ # Directory where trained models are saved
+│
+│ # ── Post-training & tooling (added on top of the base; see POST_TRAINING.md / docs/) ──
+├── src/post_training/ # from-scratch SFT · reward model · PPO · DPO · GRPO + rollout/eval/inference
+├── configs/ # editable JSON configs: base.json + one per stage (+ smoke/)
+├── config/loader.py # loads configs/*.json into the stage dataclasses (defaults < base < stage < CLI)
+├── ui/ # Streamlit control panel: train · evaluate · chat (with theory) — `streamlit run ui/app.py`
+├── docs/ # Material for MkDocs site (theory + hand-drawn diagrams)
+├── mkdocs.yml # docs-site config
+└── pyproject.toml # `pip install -e .` (no more PYTHONPATH=.)
```
`scripts/` directory contains scripts for downloading the dataset, preprocessing the data, training the model, and generating text using the trained model. `src/models/` directory contains the implementation of the transformer model, multi-layer perceptron (MLP), attention mechanisms, and transformer blocks.`config/` directory contains the configuration file with default parameters. `data_loader/` directory contains functions for creating data loaders/iterators.
+> **Beyond the base model:** `src/post_training/` adds the full alignment suite (SFT → reward model → PPO/DPO → GRPO), configured by editable JSON in `configs/`, with a beautiful Streamlit control panel (`ui/`) and a Material for MkDocs site (`docs/`). The original teaching files above are unchanged. See **[POST_TRAINING.md](POST_TRAINING.md)** and the [`docs/`](docs/README.md) site.
+
## Usage
Clone the repository and navigate to the directory:
@@ -1250,6 +1269,63 @@ print(m_output) # Output from the Million model
Our million parameter model gives us the motivation that we can have a very narrow, goal-oriented LLM under 1B in size, while our 1B trained model shows us that the architecture needs to be coded in great depth with proper consideration. Otherwise, it won’t improve training or performance compared to the million-parameter model. It will just overfit the data unless you have a deep architecture for the billion-sized model.
+## Post-Training & Alignment (SFT · RM · PPO · DPO · GRPO)
+
+Pretraining gives us a model that can *continue* text. But a base model can't follow instructions or
+reason — that takes **post-training**. So I extended the repo all the way to a modern aligned/reasoning
+model, with every algorithm written from scratch in plain PyTorch (no `trl`, `peft`, or `transformers`),
+trained on **real public datasets** (Alpaca, Dolly, Anthropic HH-RLHF, UltraFeedback, GSM8K), and built
+to run on a single GPU or scale across multiple GPUs with DDP + bf16.
+
+The full journey, `Base → SFT → Reward Model → {PPO, DPO} → GRPO → eval/chat`:
+
+![Post-training pipeline: Base to SFT to RM/DPO to PPO/GRPO](docs/diagrams/README.png)
+
+<details>
+<summary>Mermaid source (live, editable)</summary>
+
+```mermaid
+flowchart TD
+ PILE([The Pile<br/>9.8B tokens]):::data --> PRE{{Pretrain<br/>~400M base}}:::model
+ PRE --> BASE[(base_pretrained.pt)]:::ckpt
+ BASE --> SFT{{SFT<br/>Alpaca · Dolly · GSM8K}}:::model
+ SFT --> SFTCK[(sft.pt)]:::ckpt
+ SFTCK --> RM{{Reward Model<br/>Bradley-Terry}}:::rl
+ SFTCK --> DPO{{DPO / ORPO / KTO}}:::rl
+ RM --> RMCK[(reward.pt)]:::ckpt
+ RMCK -->|reward signal| PPO{{PPO<br/>GAE + clip + KL}}:::rl
+ SFTCK --> PPO
+ SFTCK --> GRPO{{GRPO / RLVR<br/>group-relative}}:::rl
+ PPO --> EVAL([GSM8K eval<br/>+ chat]):::eval
+ DPO --> EVAL
+ GRPO --> EVAL
+ classDef data fill:#d6ffd9,stroke:#27ae60,stroke-width:2px,color:#143d1a;
+ classDef model fill:#ffe8a3,stroke:#d48806,stroke-width:2px,color:#5a3d00;
+ classDef rl fill:#ffd9b3,stroke:#e67e22,stroke-width:2px,color:#6b3500;
+ classDef ckpt fill:#eeeeee,stroke:#555555,stroke-width:2px,color:#222;
+ classDef eval fill:#e8d6ff,stroke:#8e44ad,stroke-width:2px,color:#3d1a5a;
+```
+
+</details>
+
+Each stage has its own deep-dive doc — concept, the hand-drawn diagram, the real code, run commands, and
+what every metric means — under [`docs/`](docs/README.md):
+
+| Stage | What it teaches | Doc |
+|---|---|---|
+| Data handling | how every dataset is downloaded & preprocessed | [docs/01_data_pipeline.md](docs/01_data_pipeline.md) |
+| Pretraining | language (next-token on the Pile), DDP + bf16 | [docs/02_pretraining.md](docs/02_pretraining.md) |
+| SFT | instruction following + `<think>/<answer>` format | [docs/03_sft.md](docs/03_sft.md) |
+| Reward Model | scoring which answer humans prefer (Bradley-Terry) | [docs/04_reward_model.md](docs/04_reward_model.md) |
+| DPO / ORPO / KTO | preference alignment without an RL loop | [docs/05_dpo.md](docs/05_dpo.md) |
+| PPO | classic RLHF: rollout → reward → GAE → clip | [docs/06_ppo.md](docs/06_ppo.md) |
+| GRPO / RLVR | reasoning via verifiable rewards (DeepSeek-R1 style) | [docs/07_grpo.md](docs/07_grpo.md) |
+| Evaluation | GSM8K accuracy across all stages | [docs/08_evaluation.md](docs/08_evaluation.md) |
+| Inference / chat | talk to any checkpoint | [docs/09_inference.md](docs/09_inference.md) |
+
+Start at the [**Post-Training Overview**](docs/README.md), or see [POST_TRAINING.md](POST_TRAINING.md)
+for the condensed command reference. The whole chain runs with `bash scripts/run_posttraining.sh`.
+
# What’s Next
I recommend that you create the 13+ million-parameter model and then start scaling it by adding the next 100 parameters, improving its ability to handle shorter contexts. It’s up to you how many more parameters you want to train for specific tasks. Then, for the remaining parameters under 1B, try fine-tuning the model on domain-specific data, such as writing emails or essays, and see how it generates the text.
diff --git a/config/__init__.py b/config/__init__.py
new file mode 100644
index 0000000..77a0021
--- /dev/null
+++ b/config/__init__.py
@@ -0,0 +1,2 @@
+"""Configuration package: legacy ``config.config`` (pretraining), the post-training
+dataclasses (``config.post_training_config``), and the JSON ``config.loader``."""
diff --git a/config/loader.py b/config/loader.py
new file mode 100644
index 0000000..4c1c347
--- /dev/null
+++ b/config/loader.py
@@ -0,0 +1,85 @@
+"""
+JSON config loader for the post-training stages.
+
+Industry-standard, learning-friendly: each stage's knobs live in a small editable JSON file
+under ``configs/`` (typed by the dataclasses in :mod:`config.post_training_config`). This
+loader resolves a final dataclass instance by merging four layers, lowest precedence first:
+
+ 1. dataclass field defaults (config.post_training_config.<Stage>Config)
+ 2. configs/base.json (shared model + runtime fields)
+ 3. the stage JSON (configs/sft.json, ...) (that stage's hyperparameters)
+ 4. CLI --field overrides (highest precedence)
+
+JSON ``null`` maps to Python ``None`` cleanly -- the right way to set ``str | None`` fields
+like ``amp_dtype``. Unknown keys are warned about, not fatal.
+
+When ``json_path`` lives in a sub-dir with its own ``base.json`` (e.g. ``configs/smoke/sft.json``),
+that sibling ``base.json`` is used automatically -- so the smoke configs shrink the model too.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from dataclasses import fields
+from typing import Any
+
+
+def _deep_merge(dst: dict, src: dict) -> dict:
+ """Recursively merge ``src`` into ``dst`` (nested-dict aware; future-proof)."""
+ for k, v in src.items():
+ if isinstance(v, dict) and isinstance(dst.get(k), dict):
+ _deep_merge(dst[k], v)
+ else:
+ dst[k] = v
+ return dst
+
+
+def _resolve_base(json_path: str | None, base_path: str | None) -> str:
+ if base_path is not None:
+ return base_path
+ if json_path:
+ sibling = os.path.join(os.path.dirname(json_path), "base.json")
+ if os.path.exists(sibling):
+ return sibling
+ return "configs/base.json"
+
+
+def load_config(
+ cfg_cls,
+ json_path: str | None = None,
+ overrides: dict[str, Any] | None = None,
+ *,
+ base_path: str | None = None,
+):
+ """
+ Resolve ``cfg_cls`` from ``base.json`` + the stage JSON + CLI overrides.
+
+ Args:
+ cfg_cls: the stage dataclass (e.g. ``SFTConfig``).
+ json_path: path to the stage JSON (e.g. ``configs/sft.json``); None = base + defaults.
+ overrides: parsed CLI ``--field`` values (None values are ignored).
+ base_path: shared base JSON; if None, uses the sibling ``base.json`` of ``json_path``
+ (so ``configs/smoke/sft.json`` picks up ``configs/smoke/base.json``), else
+ ``configs/base.json``.
+
+ Returns:
+ an instance of ``cfg_cls`` with the resolved values.
+ """
+ base = _resolve_base(json_path, base_path)
+ merged: dict[str, Any] = {}
+ for path in (base, json_path):
+ if path and os.path.exists(path):
+ with open(path) as fh:
+ _deep_merge(merged, json.load(fh))
+
+ field_names = {f.name for f in fields(cfg_cls)}
+ for key in list(merged):
+ if key not in field_names:
+ print(f"[config] ignoring unknown key '{key}' for {cfg_cls.__name__}")
+ merged.pop(key)
+
+ if overrides:
+ merged.update({k: v for k, v in overrides.items() if k in field_names and v is not None})
+
+ return cfg_cls(**merged)
diff --git a/config/post_training_config.py b/config/post_training_config.py
new file mode 100644
index 0000000..a0f83f0
--- /dev/null
+++ b/config/post_training_config.py
@@ -0,0 +1,178 @@
+"""
+Configuration for the from-scratch post-training suite.
+
+Kept entirely separate from ``config/config.py`` (which import-executes for the original
+pretraining path and must stay untouched). Each stage is a frozen-ish dataclass that
+inherits the shared :class:`BaseModelConfig` model/runtime fields and adds its own
+hyperparameters. Construct with overrides, e.g. ``SFTConfig(lr=2e-5, batch_size=16)``.
+
+The default base model is ~400M parameters (n_embed=1024, n_head=16, n_blocks=24,
+context_length=1024) -- the "mid" size chosen so real datasets (Alpaca, HH-RLHF, GSM8K)
+give meaningful results while still fitting comfortably on one H100 and training in a
+reasonable time on 2x H100. A tiny ``SMOKE`` variant is provided for fast CPU/1-GPU tests.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field, replace
+
+
+# Shared paths (all heavy artifacts live on the 1.5TB /ephemeral disk).
+EPHEMERAL = "/ephemeral"
+CKPT_DIR = f"{EPHEMERAL}/ckpts"
+DATA_DIR = f"{EPHEMERAL}/data"
+LOG_DIR = f"{EPHEMERAL}/logs"
+
+
+@dataclass
+class BaseModelConfig:
+ # --- model architecture (must match across all stages + the pretrained ckpt) ---
+ vocab_size: int = 50304
+ context_length: int = 1024
+ n_embed: int = 1024
+ n_head: int = 16
+ n_blocks: int = 24
+
+ # --- runtime ---
+ device: str = "cuda"
+ amp_dtype: str | None = "bf16" # None | "bf16"; bf16 needs no GradScaler on H100
+ seed: int = 1337
+ compile: bool = False # torch.compile the model (big speedup, slow 1st step)
+ ckpt_dir: str = CKPT_DIR
+ log_dir: str = LOG_DIR
+ use_wandb: bool = False
+ wandb_project: str = "train-llm-from-scratch-posttrain"
+
+
+@dataclass
+class PretrainConfig(BaseModelConfig):
+ """Pretrain the mid base model from scratch on the Pile HDF5 (mix in task text late)."""
+ train_path: str = "data/train/pile_train.h5"
+ dev_path: str = "data/val/pile_dev.h5"
+ batch_size: int = 24 # per-GPU micro-batch
+ grad_accum: int = 8 # effective batch = batch_size * grad_accum * world
+ train_steps: int = 200_000
+ eval_steps: int = 1_000
+ eval_iters: int = 100
+ warmup_steps: int = 2_000
+ lr: float = 3e-4
+ min_lr: float = 3e-5
+ weight_decay: float = 0.1
+ grad_clip: float = 1.0
+ out_ckpt: str = f"{CKPT_DIR}/base_pretrained.pt"
+ save_every: int = 2_000
+
+
+@dataclass
+class SFTConfig(BaseModelConfig):
+ pretrained_ckpt: str = f"{CKPT_DIR}/base_pretrained.pt"
+ data_path: str = f"{DATA_DIR}/sft_packed.h5"
+ out_ckpt: str = f"{CKPT_DIR}/sft.pt"
+ batch_size: int = 16
+ grad_accum: int = 2
+ epochs: int = 3
+ max_steps: int = -1 # -1 = run full epochs
+ eval_steps: int = 200
+ warmup_steps: int = 100
+ lr: float = 1e-5
+ min_lr: float = 1e-6
+ weight_decay: float = 0.0
+ grad_clip: float = 1.0
+ save_every: int = 500
+
+
+@dataclass
+class RewardConfig(BaseModelConfig):
+ sft_ckpt: str = f"{CKPT_DIR}/sft.pt"
+ pref_path: str = f"{DATA_DIR}/preferences.jsonl"
+ out_ckpt: str = f"{CKPT_DIR}/reward.pt"
+ batch_size: int = 8 # pairs per step (2x sequences through the model)
+ epochs: int = 1
+ eval_steps: int = 200
+ warmup_steps: int = 50
+ lr: float = 1e-5
+ weight_decay: float = 0.0
+ grad_clip: float = 1.0
+ max_len: int = 768
+ save_every: int = 500
+
+
+@dataclass
+class DPOConfig(BaseModelConfig):
+ sft_ckpt: str = f"{CKPT_DIR}/sft.pt" # init policy + frozen reference
+ pref_path: str = f"{DATA_DIR}/preferences.jsonl"
+ out_ckpt: str = f"{CKPT_DIR}/dpo.pt"
+ loss_type: str = "dpo" # "dpo" | "orpo" | "kto"
+ beta: float = 0.1
+ orpo_lambda: float = 1.0 # ORPO odds-ratio weight (loss_type="orpo")
+ batch_size: int = 8
+ epochs: int = 1
+ eval_steps: int = 200
+ warmup_steps: int = 50
+ lr: float = 5e-7
+ weight_decay: float = 0.0
+ grad_clip: float = 1.0
+ max_len: int = 768
+ save_every: int = 500
+
+
+@dataclass
+class PPOConfig(BaseModelConfig):
+ sft_ckpt: str = f"{CKPT_DIR}/sft.pt"
+ reward_ckpt: str = f"{CKPT_DIR}/reward.pt" # used when reward_source="rm"
+ prompt_path: str = f"{DATA_DIR}/rl_prompts_train.jsonl"
+ eval_prompt_path: str = f"{DATA_DIR}/rl_prompts_test.jsonl"
+ out_ckpt: str = f"{CKPT_DIR}/ppo.pt"
+ reward_source: str = "verifier" # "verifier" (GSM8K checker) | "rm" (reward model)
+ iterations: int = 1_000
+ prompts_per_iter: int = 32 # prompts sampled per PPO iteration (per rank)
+ rollout_len: int = 300
+ temperature: float = 1.0
+ top_p: float = 1.0
+ ppo_epochs: int = 4
+ minibatch_size: int = 16
+ clip: float = 0.2
+ vf_clip: float = 0.2
+ vf_coef: float = 0.5
+ ent_coef: float = 0.0
+ gamma: float = 1.0
+ gae_lambda: float = 0.95
+ kl_coef: float = 0.05 # penalty on KL(policy || ref) added to reward
+ lr: float = 1e-6
+ grad_clip: float = 1.0
+ eval_every: int = 50
+ save_every: int = 100
+
+
+@dataclass
+class GRPOConfig(BaseModelConfig):
+ sft_ckpt: str = f"{CKPT_DIR}/sft.pt"
+ prompt_path: str = f"{DATA_DIR}/rl_prompts_train.jsonl"
+ eval_prompt_path: str = f"{DATA_DIR}/rl_prompts_test.jsonl"
+ curriculum_path: str = f"{DATA_DIR}/arithmetic_prompts.jsonl" # warm-up before GSM8K
+ curriculum_iters: int = 100 # iterations on the arithmetic warm-up before GSM8K
+ out_ckpt: str = f"{CKPT_DIR}/grpo.pt"
+ iterations: int = 1_000
+ prompts_per_iter: int = 8 # distinct prompts per iter (per rank)
+ group_size: int = 8 # samples per prompt (group)
+ rollout_len: int = 300
+ temperature: float = 1.0
+ top_p: float = 1.0
+ grpo_epochs: int = 1
+ clip: float = 0.2
+ kl_coef: float = 0.04 # KL(policy || ref) penalty term in the loss
+ lr: float = 1e-6
+ grad_clip: float = 1.0
+ eval_every: int = 50
+ save_every: int = 100
+
+
+# Tiny config for fast smoke tests (CPU or a single GPU, seconds not hours).
+SMOKE = dict(
+ vocab_size=256, context_length=64, n_embed=64, n_head=4, n_blocks=2, device="cpu", amp_dtype=None
+)
+
+
+def smoke(cfg_cls):
+ """Return an instance of ``cfg_cls`` shrunk to the tiny SMOKE model dims."""
+ return replace(cfg_cls(), **SMOKE)
diff --git a/configs/base.json b/configs/base.json
new file mode 100644
index 0000000..b9730b9
--- /dev/null
+++ b/configs/base.json
@@ -0,0 +1,15 @@
+{
+ "vocab_size": 50304,
+ "context_length": 1024,
+ "n_embed": 1024,
+ "n_head": 16,
+ "n_blocks": 24,
+ "device": "cuda",
+ "amp_dtype": "bf16",
+ "seed": 1337,
+ "compile": false,
+ "ckpt_dir": "/ephemeral/ckpts",
+ "log_dir": "/ephemeral/logs",
+ "use_wandb": false,
+ "wandb_project": "train-llm-from-scratch-posttrain"
+}
diff --git a/configs/dpo.json b/configs/dpo.json
new file mode 100644
index 0000000..3b31b16
--- /dev/null
+++ b/configs/dpo.json
@@ -0,0 +1,17 @@
+{
+ "sft_ckpt": "/ephemeral/ckpts/sft.pt",
+ "pref_path": "/ephemeral/data/preferences.jsonl",
+ "out_ckpt": "/ephemeral/ckpts/dpo.pt",
+ "loss_type": "dpo",
+ "beta": 0.1,
+ "orpo_lambda": 1.0,
+ "batch_size": 8,
+ "epochs": 1,
+ "eval_steps": 200,
+ "warmup_steps": 50,
+ "lr": 5e-07,
+ "weight_decay": 0.0,
+ "grad_clip": 1.0,
+ "max_len": 768,
+ "save_every": 500
+}
diff --git a/configs/grpo.json b/configs/grpo.json
new file mode 100644
index 0000000..6da1a66
--- /dev/null
+++ b/configs/grpo.json
@@ -0,0 +1,21 @@
+{
+ "sft_ckpt": "/ephemeral/ckpts/sft.pt",
+ "prompt_path": "/ephemeral/data/rl_prompts_train.jsonl",
+ "eval_prompt_path": "/ephemeral/data/rl_prompts_test.jsonl",
+ "curriculum_path": "/ephemeral/data/arithmetic_prompts.jsonl",
+ "curriculum_iters": 100,
+ "out_ckpt": "/ephemeral/ckpts/grpo.pt",
+ "iterations": 1000,
+ "prompts_per_iter": 8,
+ "group_size": 8,
+ "rollout_len": 300,
+ "temperature": 1.0,
+ "top_p": 1.0,
+ "grpo_epochs": 1,
+ "clip": 0.2,
+ "kl_coef": 0.04,
+ "lr": 1e-06,
+ "grad_clip": 1.0,
+ "eval_every": 50,
+ "save_every": 100
+}
diff --git a/configs/ppo.json b/configs/ppo.json
new file mode 100644
index 0000000..5c45b4f
--- /dev/null
+++ b/configs/ppo.json
@@ -0,0 +1,26 @@
+{
+ "sft_ckpt": "/ephemeral/ckpts/sft.pt",
+ "reward_ckpt": "/ephemeral/ckpts/reward.pt",
+ "prompt_path": "/ephemeral/data/rl_prompts_train.jsonl",
+ "eval_prompt_path": "/ephemeral/data/rl_prompts_test.jsonl",
+ "out_ckpt": "/ephemeral/ckpts/ppo.pt",
+ "reward_source": "verifier",
+ "iterations": 1000,
+ "prompts_per_iter": 32,
+ "rollout_len": 300,
+ "temperature": 1.0,
+ "top_p": 1.0,
+ "ppo_epochs": 4,
+ "minibatch_size": 16,
+ "clip": 0.2,
+ "vf_clip": 0.2,
+ "vf_coef": 0.5,
+ "ent_coef": 0.0,
+ "gamma": 1.0,
+ "gae_lambda": 0.95,
+ "kl_coef": 0.05,
+ "lr": 1e-06,
+ "grad_clip": 1.0,
+ "eval_every": 50,
+ "save_every": 100
+}
diff --git a/configs/pretrain.json b/configs/pretrain.json
new file mode 100644
index 0000000..6b7f077
--- /dev/null
+++ b/configs/pretrain.json
@@ -0,0 +1,16 @@
+{
+ "train_path": "/ephemeral/data/pile_train.h5",
+ "dev_path": "/ephemeral/data/pile_dev.h5",
+ "batch_size": 8,
+ "grad_accum": 12,
+ "train_steps": 50000,
+ "eval_steps": 1000,
+ "eval_iters": 100,
+ "warmup_steps": 2000,
+ "lr": 0.0003,
+ "min_lr": 3e-05,
+ "weight_decay": 0.1,
+ "grad_clip": 1.0,
+ "out_ckpt": "/ephemeral/ckpts/base_pretrained.pt",
+ "save_every": 1000
+}
diff --git a/configs/reward.json b/configs/reward.json
new file mode 100644
index 0000000..4037732
--- /dev/null
+++ b/configs/reward.json
@@ -0,0 +1,14 @@
+{
+ "sft_ckpt": "/ephemeral/ckpts/sft.pt",
+ "pref_path": "/ephemeral/data/preferences.jsonl",
+ "out_ckpt": "/ephemeral/ckpts/reward.pt",
+ "batch_size": 8,
+ "epochs": 1,
+ "eval_steps": 200,
+ "warmup_steps": 50,
+ "lr": 1e-05,
+ "weight_decay": 0.0,
+ "grad_clip": 1.0,
+ "max_len": 768,
+ "save_every": 500
+}
diff --git a/configs/sft.json b/configs/sft.json
new file mode 100644
index 0000000..b59a839
--- /dev/null
+++ b/configs/sft.json
@@ -0,0 +1,16 @@
+{
+ "pretrained_ckpt": "/ephemeral/ckpts/base_pretrained.pt",
+ "data_path": "/ephemeral/data/sft_packed.h5",
+ "out_ckpt": "/ephemeral/ckpts/sft.pt",
+ "batch_size": 16,
+ "grad_accum": 2,
+ "epochs": 3,
+ "max_steps": -1,
+ "eval_steps": 200,
+ "warmup_steps": 100,
+ "lr": 1e-05,
+ "min_lr": 1e-06,
+ "weight_decay": 0.0,
+ "grad_clip": 1.0,
+ "save_every": 500
+}
diff --git a/configs/smoke/base.json b/configs/smoke/base.json
new file mode 100644
index 0000000..19f90c8
--- /dev/null
+++ b/configs/smoke/base.json
@@ -0,0 +1,9 @@
+{
+ "vocab_size": 50304,
+ "context_length": 256,
+ "n_embed": 128,
+ "n_head": 4,
+ "n_blocks": 2,
+ "device": "cpu",
+ "amp_dtype": null
+}
diff --git a/configs/smoke/dpo.json b/configs/smoke/dpo.json
new file mode 100644
index 0000000..02a571c
--- /dev/null
+++ b/configs/smoke/dpo.json
@@ -0,0 +1,8 @@
+{
+ "batch_size": 4,
+ "epochs": 1,
+ "eval_steps": 10000,
+ "warmup_steps": 2,
+ "max_len": 256,
+ "save_every": 10000
+}
diff --git a/configs/smoke/grpo.json b/configs/smoke/grpo.json
new file mode 100644
index 0000000..8cce3d6
--- /dev/null
+++ b/configs/smoke/grpo.json
@@ -0,0 +1,10 @@
+{
+ "iterations": 2,
+ "prompts_per_iter": 2,
+ "group_size": 4,
+ "rollout_len": 32,
+ "curriculum_iters": 1,
+ "grpo_epochs": 1,
+ "eval_every": 10000,
+ "save_every": 10000
+}
diff --git a/configs/smoke/ppo.json b/configs/smoke/ppo.json
new file mode 100644
index 0000000..5d07eb8
--- /dev/null
+++ b/configs/smoke/ppo.json
@@ -0,0 +1,9 @@
+{
+ "iterations": 2,
+ "prompts_per_iter": 4,
+ "rollout_len": 32,
+ "ppo_epochs": 2,
+ "minibatch_size": 2,
+ "eval_every": 10000,
+ "save_every": 10000
+}
diff --git a/configs/smoke/pretrain.json b/configs/smoke/pretrain.json
new file mode 100644
index 0000000..ad122b0
--- /dev/null
+++ b/configs/smoke/pretrain.json
@@ -0,0 +1,10 @@
+{
+ "batch_size": 4,
+ "grad_accum": 1,
+ "train_steps": 20,
+ "eval_steps": 10000,
+ "warmup_steps": 2,
+ "save_every": 10000,
+ "train_path": "/ephemeral/data/pile_train.h5",
+ "dev_path": "/ephemeral/data/pile_dev.h5"
+}
diff --git a/configs/smoke/reward.json b/configs/smoke/reward.json
new file mode 100644
index 0000000..02a571c
--- /dev/null
+++ b/configs/smoke/reward.json
@@ -0,0 +1,8 @@
+{
+ "batch_size": 4,
+ "epochs": 1,
+ "eval_steps": 10000,
+ "warmup_steps": 2,
+ "max_len": 256,
+ "save_every": 10000
+}
diff --git a/configs/smoke/sft.json b/configs/smoke/sft.json
new file mode 100644
index 0000000..832fc5d
--- /dev/null
+++ b/configs/smoke/sft.json
@@ -0,0 +1,7 @@
+{
+ "max_steps": 10,
+ "batch_size": 4,
+ "eval_steps": 10000,
+ "warmup_steps": 2,
+ "save_every": 10000
+}
diff --git a/data_loader/__init__.py b/data_loader/__init__.py
new file mode 100644
index 0000000..d766b6f
--- /dev/null
+++ b/data_loader/__init__.py
@@ -0,0 +1 @@
+"""Data loaders: pretraining HDF5 iterator + SFT / preference / RL-prompt iterators."""
diff --git a/data_loader/preference_dataset.py b/data_loader/preference_dataset.py
new file mode 100644
index 0000000..50b939a
--- /dev/null
+++ b/data_loader/preference_dataset.py
@@ -0,0 +1,79 @@
+"""
+Batch iterator over preference pairs for reward-model and DPO training.
+
+Reads a JSONL file of ``{"prompt", "chosen", "rejected"}`` (produced by
+``scripts/prepare_preference_data.py``). Each side is rendered through the chat template
+so we get, for the chosen and rejected responses to the same prompt:
+ - token ids of ``prompt + response + EOT``
+ - a response mask (1 over the completion, used by DPO)
+ - the true sequence length (used by the reward model to read the last-token reward)
+
+Right-padding is safe here because the model's attention is causal: the last real token
+never attends to padding that comes after it, and the response mask zeros padded
+positions in the loss.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Iterator
+
+import numpy as np
+import torch
+
+from src.post_training.chat_template import EOT_ID, encode_chat
+
+
+def _encode_side(prompt: str, response: str, max_len: int) -> tuple[list[int], list[int]]:
+ ids, mask = encode_chat([{"role": "user", "content": prompt},
+ {"role": "assistant", "content": response}])
+ return ids[:max_len], mask[:max_len]
+
+
+def _collate(rows: list[dict], max_len: int, device: str) -> dict:
+ enc = [( _encode_side(r["prompt"], r["chosen"], max_len),
+ _encode_side(r["prompt"], r["rejected"], max_len)) for r in rows]
+ # Pad chosen and rejected to a single common length so they can share one forward.
+ L = max(max(len(c[0]), len(j[0])) for c, j in enc)
+
+ def pad(seq, fill):
+ return seq + [fill] * (L - len(seq))
+
+ ch_ids, ch_mask, ch_len, rj_ids, rj_mask, rj_len = [], [], [], [], [], []
+ for (cids, cmask), (jids, jmask) in enc:
+ ch_len.append(len(cids)); rj_len.append(len(jids))
+ ch_ids.append(pad(cids, EOT_ID)); ch_mask.append(pad(cmask, 0))
+ rj_ids.append(pad(jids, EOT_ID)); rj_mask.append(pad(jmask, 0))
+
+ t = lambda a, dt: torch.tensor(a, dtype=dt, device=device)
+ return {
+ "chosen_ids": t(ch_ids, torch.long), "chosen_mask": t(ch_mask, torch.long), "chosen_len": t(ch_len, torch.long),
+ "rejected_ids": t(rj_ids, torch.long), "rejected_mask": t(rj_mask, torch.long), "rejected_len": t(rj_len, torch.long),
+ }
+
+
+def get_preference_iterator(
+ path: str,
+ batch_size: int,
+ max_len: int,
+ device: str = "cpu",
+ *,
+ rank: int = 0,
+ world_size: int = 1,
+ shuffle: bool = True,
+ infinite: bool = True,
+) -> Iterator[dict]:
+ """Yield collated preference batches (dict of tensors). Rows are sharded across ranks."""
+ with open(path) as f:
+ rows = [json.loads(line) for line in f if line.strip()]
+ rows = rows[rank::world_size]
+ rng = np.random.default_rng(7 + rank)
+ while True:
+ order = np.arange(len(rows))
+ if shuffle:
+ rng.shuffle(order)
+ for s in range(0, len(order) - batch_size + 1, batch_size):
+ batch = [rows[i] for i in order[s:s + batch_size]]
+ yield _collate(batch, max_len, device)
+ if not infinite:
+ return
diff --git a/data_loader/prompt_dataset.py b/data_loader/prompt_dataset.py
new file mode 100644
index 0000000..426d62a
--- /dev/null
+++ b/data_loader/prompt_dataset.py
@@ -0,0 +1,36 @@
+"""
+Prompt iterator for RL (PPO / GRPO). Reads a JSONL of ``{"prompt", "gold"}`` (gold is the
+verifiable numeric answer, or null) and yields lists of sampled rows. Rows are sharded
+across ranks so each GPU optimizes on its own prompts.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Iterator
+
+import numpy as np
+
+
+def load_prompt_rows(path: str) -> list[dict]:
+ with open(path) as f:
+ return [json.loads(line) for line in f if line.strip()]
+
+
+def get_prompt_iterator(
+ path: str,
+ prompts_per_iter: int,
+ *,
+ rank: int = 0,
+ world_size: int = 1,
+ seed: int = 0,
+ shuffle: bool = True,
+) -> Iterator[list[dict]]:
+ """Infinitely yield lists of ``prompts_per_iter`` rows (this rank's shard)."""
+ rows = load_prompt_rows(path)[rank::world_size]
+ rng = np.random.default_rng(seed + rank)
+ n = len(rows)
+ while True:
+ idx = rng.permutation(n) if shuffle else np.arange(n)
+ for s in range(0, n - prompts_per_iter + 1, prompts_per_iter):
+ yield [rows[i] for i in idx[s:s + prompts_per_iter]]
diff --git a/data_loader/sft_dataset.py b/data_loader/sft_dataset.py
new file mode 100644
index 0000000..dabdd25
--- /dev/null
+++ b/data_loader/sft_dataset.py
@@ -0,0 +1,52 @@
+"""
+Batch iterator for packed SFT data (mirrors ``data_loader.data_loader.get_batch_iterator``
+but carries the per-token loss mask alongside the tokens).
+
+The HDF5 file has two aligned datasets, ``tokens`` and ``loss_mask``, both shape
+(N, context_length), produced by ``scripts/prepare_sft_data.py``.
+"""
+
+from __future__ import annotations
+
+from typing import Iterator
+
+import h5py
+import numpy as np
+import torch
+
+
+def get_sft_batch_iterator(
+ data_path: str,
+ batch_size: int,
+ device: str = "cpu",
+ *,
+ rank: int = 0,
+ world_size: int = 1,
+ shuffle: bool = True,
+ infinite: bool = True,
+) -> Iterator[tuple[torch.Tensor, torch.Tensor, int]]:
+ """
+ Yield ``(tokens, loss_mask, epoch)`` batches from a packed SFT HDF5 file.
+
+ Rows are sharded across ranks (each rank sees a disjoint stride) so DDP data-parallel
+ training covers the dataset once per epoch. Set ``infinite=False`` to stop after one
+ pass (used for evaluation).
+ """
+ with h5py.File(data_path, "r") as f:
+ tokens = f["tokens"]
+ masks = f["loss_mask"]
+ n = tokens.shape[0]
+ idxs = np.arange(rank, n, world_size)
+ epoch = 0
+ rng = np.random.default_rng(1234 + rank)
+ while True:
+ if shuffle:
+ rng.shuffle(idxs)
+ for start in range(0, len(idxs) - batch_size + 1, batch_size):
+ batch = np.sort(idxs[start: start + batch_size]) # sorted for h5py fancy-index
+ tk = torch.tensor(np.asarray(tokens[batch]), dtype=torch.long, device=device)
+ mk = torch.tensor(np.asarray(masks[batch]), dtype=torch.long, device=device)
+ yield tk, mk, epoch
+ epoch += 1
+ if not infinite:
+ return
diff --git a/docs/01_data_pipeline.md b/docs/01_data_pipeline.md
new file mode 100644
index 0000000..5582585
--- /dev/null
+++ b/docs/01_data_pipeline.md
@@ -0,0 +1,155 @@
+<!-- omit in toc -->
+# Data Handling & Preprocessing
+
+Every stage needs data in a different shape, and getting these shapes right is honestly half the
+battle — a misaligned loss mask or a mis-parsed gold answer will silently wreck training. So before
+any model code, here is exactly how I download and preprocess each dataset, and the format each
+trainer expects.
+
+There are **four** data pipelines, all feeding off real public datasets:
+
+![Data preprocessing pipelines](diagrams/01_data_pipeline.png)
+
+<details>
+<summary>Mermaid source (live, editable)</summary>
+
+```mermaid
+flowchart TD
+ subgraph PT[" 1 · Pretraining "]
+ P1([Pile .jsonl.zst]):::data --> P2[stream-decompress<br/>+ tiktoken r50k_base]:::proc --> P3[(pile_train.h5<br/>flat tokens)]:::store
+ end
+ subgraph SF[" 2 · SFT "]
+ S1([Alpaca · Dolly · GSM8K]):::data --> S2[render chat template<br/>mask prompt tokens]:::proc --> S3[pack to 1024]:::proc --> S4[(sft_packed.h5<br/>tokens + loss_mask)]:::store
+ end
+ subgraph PF[" 3 · Preferences "]
+ F1([HH-RLHF · UltraFeedback]):::data --> F2[split prompt /<br/>chosen / rejected]:::proc --> F3[(preferences.jsonl)]:::store
+ end
+ subgraph RL[" 4 · RL prompts "]
+ R1([GSM8K · arithmetic]):::data --> R2[extract numeric<br/>gold answer]:::proc --> R3[(rl_prompts.jsonl<br/>prompt + gold)]:::store
+ end
+ P3 --> M1{{pretrain_base.py}}:::model
+ S4 --> M2{{train_sft.py}}:::model
+ F3 --> M3{{train_reward.py · train_dpo.py}}:::rl
+ R3 --> M4{{train_ppo.py · train_grpo.py}}:::rl
+ classDef data fill:#d6ffd9,stroke:#27ae60,stroke-width:2px,color:#143d1a;
+ classDef proc fill:#d6e8ff,stroke:#2c6fbb,stroke-width:2px,color:#0d2c52;
+ classDef store fill:#cdece8,stroke:#16a085,stroke-width:2px,color:#0a3d33;
+ classDef model fill:#ffe8a3,stroke:#d48806,stroke-width:2px,color:#5a3d00;
+ classDef rl fill:#ffd9b3,stroke:#e67e22,stroke-width:2px,color:#6b3500;
+```
+
+</details>
+
+Everything lands on the big `/ephemeral` disk and uses the OpenAI **`r50k_base`** tokenizer
+(`vocab_size = 50304`, the only special token is `<|endoftext|>` = id `50256`).
+
+## 1 · Pretraining data (Pile → flat-token HDF5)
+
+[`scripts/prepare_pretrain_data.py`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/scripts/prepare_pretrain_data.py) streams the compressed
+Pile shards, batch-tokenizes with tiktoken, and writes one flat `int32` token array to HDF5 (far
+faster than the original per-document resize). Each document is terminated with `<|endoftext|>`:
+
+```python
+for ids in enc.encode_ordinary_batch(docs):
+ buf.extend(ids)
+ buf.append(EOT_ID) # 50256 separates documents
+ if len(buf) >= WRITE_CHUNK:
+ flush() # append ~8M tokens to the HDF5 dataset at once
+```
+
+```bash
+PYTHONPATH=. python scripts/prepare_pretrain_data.py --split val --out /ephemeral/data/pile_dev.h5
+PYTHONPATH=. python scripts/prepare_pretrain_data.py --split train --num_shards 1 --out /ephemeral/data/pile_train.h5
+```
+
+The base [`get_batch_iterator`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/data_loader/data_loader.py) then slices random
+`context_length + 1` windows out of this flat array for next-token training.
+
+## 2 · SFT data (instructions → packed tokens **+ loss mask**)
+
+This is the subtle one. We only want to train the model to produce the **assistant** tokens, not to
+parrot the prompt. The chat format ([`chat_template.py`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/chat_template.py)) uses
+plain-text role markers (since `r50k_base` has no spare special tokens) and `<|endoftext|>` as the
+turn terminator:
+
+```
+<|user|>
+{question}<|endoftext|><|assistant|>
+{answer}<|endoftext|>
+```
+
+[`encode_chat`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/chat_template.py#L95) builds the token ids **and** an aligned
+`loss_mask` that is `1` only over the assistant completion (and its terminating EOT):
+
+```python
+content_ids = _encode_ordinary(m["content"])
+is_completion = role == "assistant"
+ids.extend(content_ids)
+mask.extend([1 if is_completion else 0] * len(content_ids)) # train ONLY assistant tokens
+ids.append(EOT_ID)
+mask.append(1 if is_completion else 0) # ...and teach it to stop
+```
+
+[`prepare_sft_data.py`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/scripts/prepare_sft_data.py) renders Alpaca + Dolly + GSM8K through this,
+reformatting GSM8K into the `<think>…</think><answer>N</answer>` structure (so the model learns the
+exact shape the RL verifier later rewards), then [`pack_examples`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/sft.py#L41)
+concatenates everything and slices it into fixed `1024`-token rows, writing two aligned HDF5 datasets,
+`tokens` and `loss_mask`.
+
+```bash
+PYTHONPATH=. python scripts/prepare_sft_data.py --context_length 1024 --out_dir /ephemeral/data
+```
+
+I verified on the real file that the mask covers exactly `<answer>4</answer>` and excludes the user
+question — that alignment is what makes SFT work.
+
+## 3 · Preference data (→ `{prompt, chosen, rejected}` JSONL)
+
+[`prepare_preference_data.py`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/scripts/prepare_preference_data.py) pulls **Anthropic/hh-rlhf** and
+**HuggingFaceH4/ultrafeedback_binarized** and normalizes both to one schema. For HH-RLHF I split each
+dialogue at the last `Assistant:` turn so the chosen/rejected share a prompt and differ only in the
+final response:
+
+```python
+def _split_hh(text):
+ idx = text.rfind("\n\nAssistant:")
+ return text[:idx].strip(), text[idx + len("\n\nAssistant:"):].strip()
+```
+
+Output is `preferences.jsonl` (train) + `preferences_test.jsonl` (held-out, for measuring reward-model
+accuracy). [`preference_dataset.py`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/data_loader/preference_dataset.py) tokenizes each side through
+the same chat template and right-pads a batch — which is safe because the model's attention is
+**causal**, so the last real token never attends to padding after it (no attention mask needed).
+
+```bash
+PYTHONPATH=. python scripts/prepare_preference_data.py --source both --max_per_source 40000
+```
+
+## 4 · RL prompt data (→ `{prompt, gold}` JSONL)
+
+[`prepare_rl_prompts.py`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/scripts/prepare_rl_prompts.py) turns GSM8K into prompts with a **verifiable
+numeric gold answer** (parsed from the dataset's `#### N`), plus a programmatic **arithmetic curriculum**
+that even a weak policy can partly solve — so RL has non-zero reward signal to bootstrap from:
+
+```python
+gold = gsm8k_gold_answer(ex["answer"]) # the number after '####'
+rows.append({"prompt": ex["question"].strip(), "gold": gold})
+```
+
+```bash
+PYTHONPATH=. python scripts/prepare_rl_prompts.py --out_dir /ephemeral/data
+```
+
+I cross-checked the emitted gold answers 50/50 against the live GSM8K dataset — they match exactly,
+which matters because the verifier reward ([08_evaluation.md](08_evaluation.md)) is only as trustworthy
+as the gold it compares against.
+
+## What you end up with
+
+| File | Shape | Used by |
+|---|---|---|
+| `pile_train.h5` / `pile_dev.h5` | flat `int32` tokens | pretraining |
+| `sft_packed.h5` | `tokens` + `loss_mask`, `(N, 1024)` | SFT |
+| `preferences.jsonl` (+ `_test`) | `{prompt, chosen, rejected}` | Reward Model, DPO |
+| `rl_prompts_train.jsonl` / `_test` | `{prompt, gold}` | PPO, GRPO |
+| `arithmetic_prompts.jsonl` | `{prompt, gold}` | GRPO curriculum warm-up |
diff --git a/docs/02_pretraining.md b/docs/02_pretraining.md
new file mode 100644
index 0000000..f34d8ac
--- /dev/null
+++ b/docs/02_pretraining.md
@@ -0,0 +1,96 @@
+<!-- omit in toc -->
+# Stage 1 — Pretraining the base model
+
+Everything downstream is only as good as the base model, so the first thing I do is pretrain a
+**~400M-parameter** version of this repo's own `Transformer` from scratch on the Pile. The original
+[`train_transformer.py`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/scripts/train_transformer.py) is a clean single-GPU loop; for a mid-size
+model on 2×H100 I wrote [`pretrain_base.py`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/scripts/pretrain_base.py), which adds the few things
+that actually matter at this scale — DistributedDataParallel, bf16 autocast, gradient accumulation, a
+cosine LR schedule with warmup, and periodic checkpointing — without touching the model itself.
+
+![Pretraining loop](diagrams/02_pretraining.png)
+
+<details>
+<summary>Mermaid source (live, editable)</summary>
+
+```mermaid
+flowchart LR
+ H[(pile_train.h5)]:::store --> IT[get_batch_iterator<br/>random windows]:::proc
+ IT --> FWD{{forward<br/>bf16 autocast}}:::model
+ FWD --> L[cross-entropy loss]:::loss
+ L --> BWD[backward<br/>x grad_accum]:::model
+ BWD --> CL[clip grad norm 1.0]:::proc
+ CL --> ST[AdamW step<br/>cosine LR + warmup]:::model
+ ST -->|every 1000 steps| CK[(base_pretrained.pt)]:::ckpt
+ ST -->|next step| IT
+ classDef store fill:#cdece8,stroke:#16a085,stroke-width:2px,color:#0a3d33;
+ classDef proc fill:#d6e8ff,stroke:#2c6fbb,stroke-width:2px,color:#0d2c52;
+ classDef model fill:#ffe8a3,stroke:#d48806,stroke-width:2px,color:#5a3d00;
+ classDef loss fill:#ffd6d6,stroke:#c0392b,stroke-width:2px,color:#5c1212;
+ classDef ckpt fill:#eeeeee,stroke:#555,stroke-width:2px,color:#222;
+```
+
+</details>
+
+## The model
+
+The base config lives in [`config/post_training_config.py`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/config/post_training_config.py)
+(`BaseModelConfig`): `n_embed=1024, n_head=16, n_blocks=24, context_length=1024` → ~406M params. The
+context length is bumped to 1024 (vs the original 512) so GSM8K reasoning chains fit later.
+
+## The training step
+
+The heart of [`pretrain_base.py`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/scripts/pretrain_base.py) is a gradient-accumulation loop under
+bf16 autocast, syncing gradients across GPUs only on the last micro-step:
+
+```python
+for micro in range(cfg.grad_accum):
+ xb, yb = next(batch_iter)
+ sync = (micro == cfg.grad_accum - 1) or not ctx.enabled
+ cm = model.no_sync() if (ctx.enabled and not sync) else _nullcm()
+ with cm, amp_autocast(cfg.amp_dtype, ctx.device): # bf16 on H100, no GradScaler needed
+ _, loss = model(xb, yb)
+ loss = loss / cfg.grad_accum
+ loss.backward()
+
+torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.grad_clip) # stability
+optimizer.step()
+```
+
+A few choices worth calling out:
+- **bf16 autocast** ([`amp_autocast`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/utils.py)) needs no `GradScaler` (unlike
+ fp16), which keeps the loop clean. Master weights stay fp32.
+- **AdamW with a weight-decay split** ([`configure_optimizer`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/optim.py)) — decay
+ the 2-D weight matrices, never the biases / norms / embeddings (the standard GPT recipe).
+- **Cosine LR with warmup** ([`cosine_lr`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/optim.py)) — linear ramp for
+ `warmup_steps`, then cosine decay to `min_lr`.
+- **DDP** ([`distributed.py`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/distributed.py)) — each rank seeds its data shuffle
+ differently so the two GPUs see different windows; only rank 0 logs and checkpoints.
+
+## Run it
+
+```bash
+# single GPU
+PYTHONPATH=. python scripts/pretrain_base.py
+# both H100s (effective batch = batch_size * grad_accum * num_gpus)
+PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True PYTHONPATH=. \
+ torchrun --standalone --nproc_per_node=2 scripts/pretrain_base.py \
+ --batch_size 8 --grad_accum 12 --train_steps 50000
+```
+
+> **Why `batch_size 8`?** The repo's educational attention materializes a `(B, n_head, T, T)` tensor
+> per block, so memory is dominated by the sequence-length term. At context 1024, batch 8 fits an 80GB
+> H100 comfortably under DDP; we recover the effective batch with `grad_accum`.
+
+## What the numbers mean
+
+- **train_loss** — running cross-entropy; starts near `ln(vocab) ≈ 10.8` and should fall steadily
+ (mine went `11.06 → 8.6 → 6.0 → …`). This is the single best health signal.
+- **tok/s** — throughput (~32k/s combined on 2×H100 here).
+- **eval train/dev** — averaged loss on held-out windows, printed every `eval_steps`; watch the dev
+ loss to spot overfitting.
+
+Checkpoints are written to `/ephemeral/ckpts/base_pretrained.pt` every `save_every` steps and carry the
+config, so every later stage can rebuild the exact model with [`load_backbone_from_ckpt`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/utils.py).
+
+➡️ Next: [Stage 2 — SFT](03_sft.md).
diff --git a/docs/03_sft.md b/docs/03_sft.md
new file mode 100644
index 0000000..9161ebd
--- /dev/null
+++ b/docs/03_sft.md
@@ -0,0 +1,91 @@
+<!-- omit in toc -->
+# Stage 2 — Supervised Fine-Tuning (SFT)
+
+The base model can continue text but it doesn't know it's supposed to *answer* you. SFT fixes that by
+showing it thousands of `(instruction, response)` pairs and training it to produce the **response**.
+The only real difference from pretraining is a per-token **loss mask**: we compute the loss on the
+assistant tokens and ignore the prompt.
+
+![SFT masked-loss flow](diagrams/03_sft.png)
+
+<details>
+<summary>Mermaid source (live, editable)</summary>
+
+```mermaid
+flowchart LR
+ H[(sft_packed.h5<br/>tokens + loss_mask)]:::store --> B[batch:<br/>tokens, mask]:::proc
+ B --> M{{Transformer<br/>logits}}:::model
+ M --> SH[shift: predict t+1]:::proc
+ SH --> CE[token cross-entropy]:::loss
+ MASK([loss_mask = 1 on<br/>assistant tokens]):::data --> CE
+ CE --> AVG[average over<br/>masked tokens only]:::loss --> UPD[AdamW step]:::model
+ classDef store fill:#cdece8,stroke:#16a085,stroke-width:2px,color:#0a3d33;
+ classDef proc fill:#d6e8ff,stroke:#2c6fbb,stroke-width:2px,color:#0d2c52;
+ classDef data fill:#d6ffd9,stroke:#27ae60,stroke-width:2px,color:#143d1a;
+ classDef model fill:#ffe8a3,stroke:#d48806,stroke-width:2px,color:#5a3d00;
+ classDef loss fill:#ffd6d6,stroke:#c0392b,stroke-width:2px,color:#5c1212;
+```
+
+</details>
+
+## The masked loss
+
+The whole stage hinges on [`sft_loss`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/sft.py#L18). It's ordinary next-token
+cross-entropy, except every target position is weighted by the mask so only completion tokens count:
+
+```python
+def sft_loss(logits, tokens, loss_mask):
+ logits = logits[:, :-1, :] # predict token t+1 from position t (same shift as pretraining)
+ targets = tokens[:, 1:]
+ mask = loss_mask[:, 1:].to(logits.dtype)
+ V = logits.size(-1)
+ ce = F.cross_entropy(logits.reshape(-1, V).float(), targets.reshape(-1).long(), reduction="none")
+ ce = ce.view(targets.shape) * mask
+ return ce.sum() / mask.sum().clamp(min=1.0) # mean over ASSISTANT tokens only
+```
+
+The mask itself was produced at data-prep time by
+[`encode_chat`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/chat_template.py#L95) (see
+[01_data_pipeline.md](01_data_pipeline.md)) and packed alongside the tokens. The `.float()` on the
+logits keeps the cross-entropy numerically clean under bf16.
+
+## The trainer
+
+[`train_sft.py`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/scripts/train_sft.py) loads the pretrained base with
+[`load_backbone_from_ckpt`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/utils.py), then runs a compact loop — autocast forward,
+masked loss, clip, step, cosine LR — with periodic dev evaluation:
+
+```python
+tokens, mask, epoch = next(train_it)
+with amp_autocast(cfg.amp_dtype, ctx.device):
+ logits, _ = model(tokens)
+ loss = sft_loss(logits, tokens, mask)
+loss.backward()
+torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.grad_clip)
+optimizer.step()
+```
+
+Batches come from [`get_sft_batch_iterator`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/data_loader/sft_dataset.py), which shards the packed
+rows across DDP ranks and yields `(tokens, loss_mask, epoch)`.
+
+## Run it
+
+```bash
+PYTHONPATH=. python scripts/train_sft.py # single GPU
+PYTHONPATH=. torchrun --standalone --nproc_per_node=2 scripts/train_sft.py # both GPUs
+# tune: --lr 1e-5 --epochs 3 --batch_size 16
+```
+
+## What the numbers mean
+
+- **train_loss / ppl** — masked cross-entropy (and its perplexity) over assistant tokens; should drop
+ well below the base model's loss. To sanity-check the mechanics I ran an *overfit* test on 8 rows and
+ watched the loss collapse `11.0 → 4.7`, confirming the gradient path learns.
+- **dev_loss** — the same masked loss on a held-out split (`sft_dev_packed.h5`); the honest signal.
+- **GSM8K dev accuracy** — after SFT the model both follows instructions *and* emits the
+ `<answer>…</answer>` format, so this should rise above the base model (see [08_evaluation.md](08_evaluation.md)).
+
+The result is saved to `/ephemeral/ckpts/sft.pt` and becomes the starting point for the reward model,
+DPO, PPO and GRPO.
+
+➡️ Next: [Stage 3 — Reward Model](04_reward_model.md) or jump to [DPO](05_dpo.md).
diff --git a/docs/04_reward_model.md b/docs/04_reward_model.md
new file mode 100644
index 0000000..29370ce
--- /dev/null
+++ b/docs/04_reward_model.md
@@ -0,0 +1,101 @@
+<!-- omit in toc -->
+# Stage 3 — Reward Model
+
+To do classic RLHF (PPO) we need something that scores a response with a single number: higher = more
+preferred. That's the reward model. I build it by putting a tiny scalar head on top of the SFT
+backbone and training it on human preference pairs with the **Bradley-Terry** loss — the same recipe
+as InstructGPT.
+
+![Reward model (Bradley-Terry)](diagrams/04_reward_model.png)
+
+<details>
+<summary>Mermaid source (live, editable)</summary>
+
+```mermaid
+flowchart LR
+ P([preference pair<br/>prompt + chosen / rejected]):::data --> BB{{SFT backbone<br/>forward_hidden}}:::model
+ BB --> LT[take last real token]:::proc
+ LT --> RH[reward head<br/>Linear→1]:::model
+ RH --> RC([r_chosen]):::rl
+ RH --> RR([r_rejected]):::rl
+ RC --> BT[Bradley-Terry<br/>-log σ r_chosen - r_rejected]:::loss
+ RR --> BT
+ BT --> UPD[AdamW step]:::model
+ classDef data fill:#d6ffd9,stroke:#27ae60,stroke-width:2px,color:#143d1a;
+ classDef proc fill:#d6e8ff,stroke:#2c6fbb,stroke-width:2px,color:#0d2c52;
+ classDef model fill:#ffe8a3,stroke:#d48806,stroke-width:2px,color:#5a3d00;
+ classDef rl fill:#ffd9b3,stroke:#e67e22,stroke-width:2px,color:#6b3500;
+ classDef loss fill:#ffd6d6,stroke:#c0392b,stroke-width:2px,color:#5c1212;
+```
+
+</details>
+
+## The model: a scalar head on the backbone
+
+[`RewardModel`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/reward_model.py#L37) wraps a `Transformer`, drops the `lm_head`,
+and reads the reward off the **last real token's** hidden state (the InstructGPT convention). Because
+attention is causal, that last token has seen the whole sequence and never attends to the right-padding
+after it — so we need no attention mask:
+
+```python
+class RewardModel(nn.Module):
+ def __init__(self, transformer):
+ self.transformer = transformer
+ self.reward_head = nn.Linear(transformer.lm_head.in_features, 1, bias=False)
+
+ def forward(self, idx, seq_lengths=None):
+ rewards = self.reward_head(self.transformer.forward_hidden(idx)).squeeze(-1) # (B, T)
+ return gather_last(rewards, seq_lengths) # reward at the last real token -> (B,)
+```
+
+[`gather_last`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/utils.py) just indexes `rewards[i, seq_lengths[i]-1]`.
+
+## The objective: Bradley-Terry
+
+[`bradley_terry_loss`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/reward_train.py#L18) pushes the chosen reward above the
+rejected one. That's the entire training signal:
+
+```python
+def bradley_terry_loss(chosen_rewards, rejected_rewards):
+ return -F.logsigmoid(chosen_rewards - rejected_rewards).mean()
+```
+
+[`preference_accuracy`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/reward_train.py#L23) — the fraction of pairs where
+`r_chosen > r_rejected` — is the metric I actually watch.
+
+## The trainer
+
+[`train_reward.py`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/scripts/train_reward.py) initializes the backbone from `sft.pt`, then for each
+batch runs the **chosen and rejected sequences through the model in a single forward** (concatenated to
+`2B`), splits the rewards, and applies the loss:
+
+```python
+ids = torch.cat([batch["chosen_ids"], batch["rejected_ids"]], dim=0)
+lens = torch.cat([batch["chosen_len"], batch["rejected_len"]], dim=0)
+rewards = rm(ids, seq_lengths=lens).float()
+chosen_r, rejected_r = rewards[:B], rewards[B:]
+loss = bradley_terry_loss(chosen_r, rejected_r)
+```
+
+Pairs come from [`get_preference_iterator`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/data_loader/preference_dataset.py), which right-pads each
+batch (safe under causal attention) and tracks the true length of each side.
+
+## Run it
+
+```bash
+PYTHONPATH=. python scripts/train_reward.py
+PYTHONPATH=. torchrun --standalone --nproc_per_node=2 scripts/train_reward.py
+# tune: --lr 1e-5 --max_len 768
+```
+
+## What the numbers mean
+
+- **loss** — Bradley-Terry; starts at `-log σ(0) = 0.693` (chance) and drops as the gap widens.
+- **train_acc / test_acc** — preference accuracy. On clean fixtures it goes to `1.0`; on **real, noisy**
+ HH-RLHF / UltraFeedback expect roughly **0.65–0.75** — that's normal, human preferences are noisy.
+- **margin** — mean `r_chosen − r_rejected`; a useful "is it still separating them" signal.
+
+Saved to `/ephemeral/ckpts/reward.pt`; PPO loads it with
+[`load_reward_model`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/reward_model.py) when `--reward_source rm`.
+
+➡️ Next: [Stage 5 — PPO](06_ppo.md) (which consumes this), or the RM-free path: [DPO](05_dpo.md).
diff --git a/docs/05_dpo.md b/docs/05_dpo.md
new file mode 100644
index 0000000..f485bad
--- /dev/null
+++ b/docs/05_dpo.md
@@ -0,0 +1,104 @@
+<!-- omit in toc -->
+# Stage 4 — DPO (and ORPO / KTO)
+
+Direct Preference Optimization is the shortcut around RLHF: instead of training a reward model and then
+running an RL loop, DPO optimizes the policy *directly* on preference pairs, using a frozen copy of the
+SFT model as a reference anchor. No reward model, no rollouts, no value function — just one clean loss.
+I also implemented two popular variants behind a `--loss_type` flag: **ORPO** (reference-free) and
+**KTO** (works from a desirable/undesirable signal).
+
+![DPO / ORPO / KTO](diagrams/05_dpo.png)
+
+<details>
+<summary>Mermaid source (live, editable)</summary>
+
+```mermaid
+flowchart LR
+ P([chosen / rejected]):::data --> POL{{policy<br/>trainable}}:::model
+ P --> REF{{reference<br/>frozen SFT copy}}:::ckpt
+ POL --> LPP[seq log-probs<br/>π_chosen, π_rejected]:::proc
+ REF --> LPR[seq log-probs<br/>ref_chosen, ref_rejected]:::proc
+ LPP --> D[DPO loss<br/>-log σ β·Δlogratios]:::loss
+ LPR --> D
+ D --> UPD[AdamW step]:::model
+ classDef data fill:#d6ffd9,stroke:#27ae60,stroke-width:2px,color:#143d1a;
+ classDef proc fill:#d6e8ff,stroke:#2c6fbb,stroke-width:2px,color:#0d2c52;
+ classDef model fill:#ffe8a3,stroke:#d48806,stroke-width:2px,color:#5a3d00;
+ classDef ckpt fill:#eeeeee,stroke:#555,stroke-width:2px,color:#222;
+ classDef loss fill:#ffd6d6,stroke:#c0392b,stroke-width:2px,color:#5c1212;
+```
+
+</details>
+
+## Sequence log-probs (the shared ingredient)
+
+DPO compares how much *more* likely the policy makes the chosen response vs the rejected one, relative
+to the reference. So I need the **summed log-prob of each response** under both models.
+[`sequence_logprobs`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/rollout.py#L268) does exactly that (and is reused by PPO/GRPO):
+
+```python
+def sequence_logprobs(model, sequences, response_mask, *, temperature=1.0, requires_grad=True):
+ lp, mask = compute_logprobs(model, sequences, response_mask, temperature=temperature, requires_grad=requires_grad)
+ m = mask.to(lp.dtype)
+ return (lp * m).sum(dim=-1), m.sum(dim=-1) # (summed logprob, #tokens) per sequence
+```
+
+## The DPO loss
+
+[`dpo_loss`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/dpo.py#L21) is the canonical objective. The β temperature controls how
+hard it pushes away from the reference:
+
+```python
+def dpo_loss(policy_chosen_logps, policy_rejected_logps, ref_chosen_logps, ref_rejected_logps, beta=0.1):
+ pi_logratios = policy_chosen_logps - policy_rejected_logps
+ ref_logratios = ref_chosen_logps - ref_rejected_logps
+ logits = pi_logratios - ref_logratios
+ loss = -F.logsigmoid(beta * logits).mean()
+ chosen_reward = beta * (policy_chosen_logps - ref_chosen_logps).detach()
+ rejected_reward = beta * (policy_rejected_logps - ref_rejected_logps).detach()
+ return loss, chosen_reward, rejected_reward
+```
+
+The two **variants** ([`orpo_loss`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/dpo.py#L48),
+[`kto_loss`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/dpo.py#L71)) live in the same file:
+- **ORPO** — reference-free: combines the SFT negative-log-likelihood on the chosen response with an
+ odds-ratio preference term, folding SFT + alignment into one stage (no frozen reference needed).
+- **KTO** — treats chosen as *desirable* and rejected as *undesirable* against a reference-KL baseline
+ estimated from the batch; useful when you only have thumbs-up/down rather than pairs.
+
+## The trainer
+
+[`train_dpo.py`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/scripts/train_dpo.py) loads the policy from `sft.pt`, makes a frozen reference with
+[`make_frozen_copy`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/utils.py) (skipped for ORPO), and computes policy + reference
+log-probs each step:
+
+```python
+policy = load_backbone_from_ckpt(cfg, cfg.sft_ckpt, ctx.device)
+ref = make_frozen_copy(policy, device=ctx.device) if cfg.loss_type != "orpo" else None
+...
+loss, cr, rr = _compute_losses(policy, ref, batch, cfg, ctx) # picks dpo/orpo/kto by cfg.loss_type
+loss.backward()
+```
+
+## Run it
+
+```bash
+PYTHONPATH=. python scripts/train_dpo.py --loss_type dpo --beta 0.1
+PYTHONPATH=. python scripts/train_dpo.py --loss_type orpo --orpo_lambda 1.0
+PYTHONPATH=. torchrun --standalone --nproc_per_node=2 scripts/train_dpo.py
+```
+
+> DPO uses a **small** learning rate (`5e-7` by default) — it's easy to over-push away from the
+> reference and degrade the model, so go gentle.
+
+## What the numbers mean
+
+- **loss** — DPO/KTO start near `0.693`; ORPO starts higher (it includes the NLL term).
+- **acc** — implicit-reward accuracy: fraction of pairs where the policy's implicit reward prefers the
+ chosen response. Should climb above 0.5.
+- **r_chosen / r_rejected** — the implicit rewards `β·(logπ − logref)`; the gap (margin) should widen.
+- **GSM8K dev accuracy** — the real downstream check.
+
+Saved to `/ephemeral/ckpts/dpo.pt`.
+
+➡️ Next: the RL path — [PPO](06_ppo.md) and [GRPO](07_grpo.md).
diff --git a/docs/06_ppo.md b/docs/06_ppo.md
new file mode 100644
index 0000000..18eee77
--- /dev/null
+++ b/docs/06_ppo.md
@@ -0,0 +1,112 @@
+<!-- omit in toc -->
+# Stage 5 — PPO (classic RLHF)
+
+This is the original ChatGPT recipe: let the model generate, score the generations with a reward, and
+nudge the policy toward higher-reward behaviour using Proximal Policy Optimization — with a value
+network (critic) for variance reduction and a KL penalty to keep it from drifting too far from the SFT
+model. I wrote the whole loop from scratch: rollout → reward → GAE advantages → clipped update.
+
+![PPO loop](diagrams/06_ppo.png)
+
+<details>
+<summary>Mermaid source (live, editable)</summary>
+
+```mermaid
+flowchart LR
+ PR([GSM8K prompts]):::data --> RO[rollout<br/>generate_with_logprobs]:::proc
+ RO --> SC{score: verifier<br/>or reward model}:::rl
+ SC --> KL[+ per-token<br/>KL-to-ref penalty]:::rl
+ KL --> GAE[compute_gae<br/>advantages + returns]:::proc
+ GAE --> UP{{clipped update<br/>policy + value, K epochs}}:::model
+ UP -->|sync old policy| RO
+ REF{{frozen ref}}:::ckpt
+ REF -. KL .-> KL
+ VH{{value head}}:::model
+ VH -. value .-> GAE
+ classDef data fill:#d6ffd9,stroke:#27ae60,stroke-width:2px,color:#143d1a;
+ classDef proc fill:#d6e8ff,stroke:#2c6fbb,stroke-width:2px,color:#0d2c52;
+ classDef rl fill:#ffd9b3,stroke:#e67e22,stroke-width:2px,color:#6b3500;
+ classDef model fill:#ffe8a3,stroke:#d48806,stroke-width:2px,color:#5a3d00;
+ classDef ckpt fill:#eeeeee,stroke:#555,stroke-width:2px,color:#222;
+```
+
+</details>
+
+## The actor-critic
+
+PPO needs a per-token value estimate `V(s_t)` next to the policy logits. I get both from one backbone
+with [`TransformerWithValueHead`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/value_head.py#L19) — it reuses
+`forward_hidden` + `lm_head` for the policy and adds a small scalar value head (initialized to ~0 so the
+critic doesn't destabilize early training):
+
+```python
+def forward(self, idx):
+ hidden = self.transformer.forward_hidden(idx)
+ logits = self.transformer.lm_head(hidden) # policy
+ values = self.value_head(hidden).squeeze(-1) # critic, (B, T)
+ return logits, values
+```
+
+## Rollout + log-probs
+
+[`rollout_prompts`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/rollout.py#L180) length-buckets the prompts and samples a
+completion for each, and [`generate_with_logprobs`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/rollout.py#L94) records the
+sampling log-probs. Log-probs are always taken in **fp32** ([`compute_logprobs`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/rollout.py#L233))
+because PPO subtracts them and bf16 rounding there is harmful.
+
+## GAE — Generalized Advantage Estimation
+
+[`compute_gae`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/ppo.py#L24) works in the "action frame" (index `t` = producing
+token `t+1`), bootstrapping only while the next action is still a response token:
+
+```python
+for t in reversed(range(L)):
+ nonterminal = m[:, t + 1] if t + 1 < L else 0.0 # episode ends after the last response token
+ delta = rewards[:, t] + gamma * values_next[:, t] * nonterminal - values[:, t]
+ lastgae = delta + gamma * lam * nonterminal * lastgae
+ adv[:, t] = lastgae
+returns = adv + values
+```
+
+The per-token reward is the **KL-to-reference penalty** at every response token, plus the scalar task
+reward added at the **last** response token. Advantages are then normalized with
+[`whiten`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/ppo.py#L60).
+
+## The clipped objective
+
+[`ppo_policy_loss`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/ppo.py#L68) is the standard clipped surrogate;
+[`ppo_value_loss`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/ppo.py#L84) clips the value update too:
+
+```python
+ratio = torch.exp(new_logp - old_logp)
+surr1 = ratio * advantages
+surr2 = torch.clamp(ratio, 1.0 - clip, 1.0 + clip) * advantages
+loss = -masked_mean(torch.min(surr1, surr2), mask)
+```
+
+[`train_ppo.py`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/scripts/train_ppo.py) ties it together: rollout once, compute old log-probs / ref
+log-probs / values, build rewards, GAE, then run `ppo_epochs` of minibatched clipped updates.
+
+## Run it
+
+```bash
+PYTHONPATH=. python scripts/train_ppo.py --reward_source verifier # GSM8K checker as reward
+PYTHONPATH=. python scripts/train_ppo.py --reward_source rm # use the trained reward.pt
+PYTHONPATH=. torchrun --standalone --nproc_per_node=2 scripts/train_ppo.py
+```
+
+## What the numbers mean
+
+- **reward** — mean task reward per iteration; the headline curve, should trend up.
+- **KL_ref** — mean KL of the policy from the SFT reference; must stay **bounded**. If it blows up the
+ model is degenerating — lower the LR or raise `--kl_coef`.
+- **clipfrac** — fraction of tokens hitting the PPO clip; a health/▒step-size signal.
+- **value_loss** — critic regression error.
+- **GSM8K test accuracy** — the real outcome, evaluated every `--eval_every`.
+
+> PPO is the touchy one: small LR (`1e-6`), `clip 0.2`, grad-clip 1.0, and watch KL. I verified the loop
+> truly *optimizes* by giving it a learnable synthetic reward — reward climbed `0.10 → 1.00`.
+
+Saved to `/ephemeral/ckpts/ppo.pt`.
+
+➡️ Next: [Stage 6 — GRPO](07_grpo.md), which drops the critic entirely.
diff --git a/docs/07_grpo.md b/docs/07_grpo.md
new file mode 100644
index 0000000..bfdc688
--- /dev/null
+++ b/docs/07_grpo.md
@@ -0,0 +1,99 @@
+<!-- omit in toc -->
+# Stage 6 — GRPO / RLVR (the reasoning frontier)
+
+GRPO (Group Relative Policy Optimization) is the algorithm behind DeepSeek-R1, and it's beautifully
+simple: **throw away PPO's value network**. For each prompt, sample a whole *group* of answers, score
+them with a verifiable reward, and use the group's own mean/std as the baseline. The advantage is just
+"how much better than your groupmates was this answer?" — no critic to train, no value loss.
+
+![GRPO loop](diagrams/07_grpo.png)
+
+<details>
+<summary>Mermaid source (live, editable)</summary>
+
+```mermaid
+flowchart LR
+ PR([prompt]):::data --> G[sample a GROUP<br/>of G answers]:::proc
+ G --> V{verifier reward<br/>per answer}:::rl
+ V --> A[group advantage<br/>r - mean / std]:::proc
+ A --> L[clipped surrogate<br/>+ k3 KL to ref]:::loss
+ L --> UPD{{policy update}}:::model
+ UPD -->|next prompt| PR
+ REF{{frozen ref}}:::ckpt
+ REF -. KL .-> L
+ classDef data fill:#d6ffd9,stroke:#27ae60,stroke-width:2px,color:#143d1a;
+ classDef proc fill:#d6e8ff,stroke:#2c6fbb,stroke-width:2px,color:#0d2c52;
+ classDef rl fill:#ffd9b3,stroke:#e67e22,stroke-width:2px,color:#6b3500;
+ classDef loss fill:#ffd6d6,stroke:#c0392b,stroke-width:2px,color:#5c1212;
+ classDef model fill:#ffe8a3,stroke:#d48806,stroke-width:2px,color:#5a3d00;
+ classDef ckpt fill:#eeeeee,stroke:#555,stroke-width:2px,color:#222;
+```
+
+</details>
+
+## Group-relative advantage
+
+[`group_advantages`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/grpo.py#L17) is the whole idea — standardize rewards *within
+each group*, so a good answer is one that beats its siblings on the same prompt:
+
+```python
+def group_advantages(rewards, group_size, eps=1e-4):
+ r = rewards.view(-1, group_size) # rewards laid out group-contiguously
+ adv = (r - r.mean(1, keepdim=True)) / (r.std(1, keepdim=True) + eps)
+ return adv.reshape(-1)
+```
+
+A nice property: if every answer in a group gets the same reward (all right or all wrong), the std-based
+advantage is ~0 and that group simply contributes no gradient — so I log the fraction of *informative*
+groups as a health metric.
+
+## The loss: clipped surrogate + KL
+
+[`grpo_loss`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/grpo.py#L37) applies the same PPO-style token-level clipped surrogate
+(advantage broadcast across a completion's tokens) plus a per-token KL penalty to the reference, using
+Schulman's non-negative **k3** estimator ([`k3_kl`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/grpo.py#L31)):
+
+```python
+ratio = torch.exp(new_logp - old_logp)
+surrogate = torch.min(ratio * adv, torch.clamp(ratio, 1 - clip, 1 + clip) * adv)
+kl = k3_kl(new_logp, ref_logp) # exp(Δ) - Δ - 1, always ≥ 0
+loss = -masked_mean(surrogate - kl_coef * kl, resp_mask)
+```
+
+## The trainer + curriculum
+
+[`train_grpo.py`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/scripts/train_grpo.py) loads the policy from `sft.pt`, replicates each prompt `G`
+times (group-contiguously), rolls them out, scores with the GSM8K verifier, and updates. It runs an
+**arithmetic curriculum** for the first `--curriculum_iters` iterations so the policy earns some reward
+*before* facing full GSM8K (otherwise every group is all-wrong and there's no signal):
+
+```python
+rows = next(warm_it if it < cfg.curriculum_iters else main_it)
+prompts = [p for p in base_prompts for _ in range(G)] # group-contiguous
+rewards = torch.tensor([reward_gsm8k(responses[i], golds[i]) for i in range(len(prompts))])
+adv = group_advantages(rewards, G)
+```
+
+## Run it
+
+```bash
+PYTHONPATH=. python scripts/train_grpo.py --group_size 8
+PYTHONPATH=. torchrun --standalone --nproc_per_node=2 scripts/train_grpo.py
+# tune: --curriculum_iters 100 --kl_coef 0.04 --temperature 1.0
+```
+
+## What the numbers mean
+
+- **reward** — mean verifier reward across the group samples; the curve you want climbing.
+- **informative** — fraction of groups with non-zero reward spread (groups that actually teach
+ something). If this collapses to 0, raise temperature / group size or stay longer on the curriculum.
+- **KL** — KL to the reference; keep it bounded.
+- **GSM8K test accuracy** — the headline reasoning metric, evaluated every `--eval_every`.
+
+> I verified the GRPO path genuinely optimizes: with a learnable reward the mean reward climbed
+> **0.10 → 0.69 → 1.00** in ~15 iterations and saturated. PPO and GRPO share the same rollout/log-prob
+> core, so this also exercises the common machinery.
+
+Saved to `/ephemeral/ckpts/grpo.pt`.
+
+➡️ Next: [measure all stages on GSM8K](08_evaluation.md) and [chat with the result](09_inference.md).
diff --git a/docs/08_evaluation.md b/docs/08_evaluation.md
new file mode 100644
index 0000000..a5c2941
--- /dev/null
+++ b/docs/08_evaluation.md
@@ -0,0 +1,99 @@
+<!-- omit in toc -->
+# Evaluation
+
+A pipeline is only believable if you can measure it, so I evaluate every stage on the **same** held-out
+GSM8K test set with greedy decoding. The headline deliverable is a single table: GSM8K accuracy as it
+moves Base → SFT → DPO → PPO → GRPO. The reward is *verifiable* — I parse the model's final number and
+compare it to the gold answer — so the score is objective, not a judgment call.
+
+![Evaluation flow](diagrams/08_evaluation.png)
+
+<details>
+<summary>Mermaid source (live, editable)</summary>
+
+```mermaid
+flowchart LR
+ CK[(stage checkpoint)]:::ckpt --> GEN[batched_generate<br/>greedy, length-bucketed]:::proc
+ Q([GSM8K question]):::data --> GEN
+ GEN --> EX[extract_answer<br/>answer / #### / last number]:::proc
+ EX --> CMP{== gold?}:::eval
+ GOLD([gold number]):::data --> CMP
+ CMP --> ACC[accuracy across<br/>Base→SFT→DPO→PPO→GRPO]:::eval
+ classDef ckpt fill:#eeeeee,stroke:#555,stroke-width:2px,color:#222;
+ classDef proc fill:#d6e8ff,stroke:#2c6fbb,stroke-width:2px,color:#0d2c52;
+ classDef data fill:#d6ffd9,stroke:#27ae60,stroke-width:2px,color:#143d1a;
+ classDef eval fill:#e8d6ff,stroke:#8e44ad,stroke-width:2px,color:#3d1a5a;
+```
+
+</details>
+
+## Generation: length-bucketed, greedy
+
+The educational model has no padding-aware attention mask, so
+[`batched_generate`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/evaluation.py#L24) groups prompts of equal length and decodes
+each bucket together; `greedy=True` forces argmax (`top_k=1`) for comparable, deterministic numbers.
+
+## Scoring: a verifiable reward
+
+[`gsm8k_accuracy`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/evaluation.py#L77) generates an answer per question and checks
+it with the verifier:
+
+```python
+prompts = [encode_prompt([{"role": "user", "content": q}]) for q, _ in qa_pairs]
+responses = batched_generate(model, prompts, max_new_tokens, device=device, greedy=greedy)
+correct = sum(is_correct(resp, gsm8k_gold_answer(ans)) for (q, ans), resp in zip(qa_pairs, responses))
+```
+
+The reward/checker lives in [`rewards/`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/rewards/). `extract_answer` is tolerant —
+it prefers an `<answer>…</answer>` tag, then a GSM8K-style `#### N`, then falls back to the last number
+in the text — and [`reward_gsm8k`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/rewards/verifiers.py#L35) is
+**correctness-dominant** with only a small, bounded format bonus, to discourage reward hacking:
+
+```python
+r = 0.0
+if _answers_match(extract_answer(text), gold): r += 1.0 # the reward that matters
+if has_well_formed_answer(text): r += 0.2 # small format nudge
+return min(r, 1.2) # clipped
+```
+
+I sanity-checked this scorer independently of any model: feeding it correct answers scores **100/100**
+and wrong answers **0/100** false positives, with gold cross-verified against the live GSM8K dataset.
+
+## The across-stages table
+
+[`eval_post_training.py`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/scripts/eval_post_training.py) loads any checkpoint (reading its dims from
+the stored `cfg`), scores it, and appends a row to a JSONL you can render as a table:
+
+```bash
+for s in base_pretrained sft dpo ppo grpo; do
+ PYTHONPATH=. python scripts/eval_post_training.py --ckpt /ephemeral/ckpts/$s.pt \
+ --label $s --limit 200 --append /ephemeral/logs/stage_table.jsonl
+done
+PYTHONPATH=. python scripts/eval_post_training.py --table /ephemeral/logs/stage_table.jsonl
+```
+
+```
+stage GSM8K acc n
+------------------------------------
+base_pretrained ... 200
+sft ... 200
+dpo ... 200
+ppo ... 200
+grpo ... 200
+```
+
+## In-training metrics
+
+Each trainer also writes a metrics JSONL under `/ephemeral/logs/` (via
+[`MetricsLogger`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/logging_utils.py)) — train/dev loss for SFT, preference accuracy
+for the reward model, implicit-reward accuracy for DPO, and reward/KL/clip-fraction + GSM8K accuracy for
+PPO/GRPO. Pass `--use_wandb true` to also mirror to Weights & Biases; the JSONL is always written so you
+can plot offline.
+
+## What "good" looks like at this scale
+
+A ~400M from-scratch model won't top the GSM8K leaderboard — the point is the **relative** climb across
+stages and bounded KL during RL. Expect modest absolute numbers but a clear, real before/after gain at
+each step.
+
+➡️ Next: [talk to any checkpoint](09_inference.md).
diff --git a/docs/09_inference.md b/docs/09_inference.md
new file mode 100644
index 0000000..2701dae
--- /dev/null
+++ b/docs/09_inference.md
@@ -0,0 +1,89 @@
+<!-- omit in toc -->
+# Inference & Chat
+
+Training is only satisfying if you can actually *talk* to the result. The original
+[`generate_text.py`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/scripts/generate_text.py) does raw continuation for the base model, but it's
+hard-wired to the legacy config and has no chat template — so I added a small inference layer that loads
+**any** stage checkpoint (base / SFT / DPO / PPO / GRPO) and talks to it correctly.
+
+![Inference / chat flow](diagrams/09_inference.png)
+
+<details>
+<summary>Mermaid source (live, editable)</summary>
+
+```mermaid
+flowchart LR
+ CK[(any checkpoint)]:::ckpt --> LD[load_model_from_ckpt<br/>dims from stored cfg]:::proc
+ LD --> MODE{chat or raw?}:::proc
+ MODE -->|instruction model| CT[wrap in chat template]:::proc
+ MODE -->|base model| RAW[raw prefix]:::proc
+ CT --> GEN{{generate<br/>temperature / top-p / greedy}}:::model
+ RAW --> GEN
+ GEN --> DEC([decode → reply]):::eval
+ classDef ckpt fill:#eeeeee,stroke:#555,stroke-width:2px,color:#222;
+ classDef proc fill:#d6e8ff,stroke:#2c6fbb,stroke-width:2px,color:#0d2c52;
+ classDef model fill:#ffe8a3,stroke:#d48806,stroke-width:2px,color:#5a3d00;
+ classDef eval fill:#e8d6ff,stroke:#8e44ad,stroke-width:2px,color:#3d1a5a;
+```
+
+</details>
+
+## Load any checkpoint by its stored config
+
+[`load_model_from_ckpt`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/inference.py) reads the model dimensions from the
+checkpoint's saved `cfg`, so you never re-specify `n_embed`/`n_blocks`, and it tolerates DDP /
+reward-head key prefixes:
+
+```python
+ck = torch.load(ckpt_path, map_location="cpu", weights_only=False)
+cfg = {**(ck.get("cfg") or {}), **(overrides or {})}
+model = Transformer(n_head=cfg["n_head"], n_embed=cfg["n_embed"], ...)
+state = {k.removeprefix("module.").removeprefix("transformer."): v for k, v in state.items()}
+```
+
+## Chat vs raw
+
+[`generate_reply`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/inference.py#L37) has two modes, reusing the same tested
+generation core as training/eval ([`batched_generate`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/evaluation.py#L24)):
+
+- **chat** (default) — wraps your text in the chat template (optionally with a `system` message) and
+ returns the decoded assistant turn. Use this for SFT/DPO/PPO/GRPO checkpoints.
+- **raw** (`--raw`) — treats your text as a prefix and returns the base model's continuation (no
+ template). Use this for `base_pretrained.pt`.
+
+```python
+if raw:
+ ids = get_tokenizer().encode_ordinary(user_text)
+else:
+ ids = encode_prompt([{"role": "user", "content": user_text}]) # ...ends at <|assistant|>
+out = batched_generate(model, [ids], max_new_tokens, device=device,
+ temperature=temperature, top_k=top_k, top_p=top_p, greedy=greedy)
+```
+
+Decoding is defensive — [`decode`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/post_training/chat_template.py) drops the EOT terminator and
+any padding-vocab ids (the model's vocab is padded to 50304 but r50k_base only decodes 0–50255).
+
+## The CLI
+
+[`scripts/chat.py`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/scripts/chat.py) is one-shot or an interactive REPL:
+
+```bash
+# instruction-tuned models (chat template applied automatically)
+PYTHONPATH=. python scripts/chat.py --ckpt /ephemeral/ckpts/sft.pt --prompt "What is 13 + 29?"
+PYTHONPATH=. python scripts/chat.py --ckpt /ephemeral/ckpts/grpo.pt --prompt "..." --greedy
+# base-model continuation
+PYTHONPATH=. python scripts/chat.py --ckpt /ephemeral/ckpts/base_pretrained.pt --raw --prompt "Once upon a time"
+# interactive REPL (omit --prompt)
+PYTHONPATH=. python scripts/chat.py --ckpt /ephemeral/ckpts/sft.pt
+```
+
+Sampling controls: `--temperature`, `--top_p`, `--top_k`, or `--greedy` for deterministic argmax. Runs
+on `--device cuda` or `cpu` (both verified).
+
+## Sampling knobs, briefly
+
+- **greedy** — reproducible, best for eval / math (`--greedy`).
+- **temperature** — higher = more random; ~`0.7–1.0` for open-ended chat.
+- **top_p / top_k** — nucleus / top-k truncation to cut the long tail of unlikely tokens.
+
+That's the full loop: pretrain → align → reason → measure → chat. Back to the [overview](README.md).
diff --git a/docs/README.md b/docs/README.md
new file mode 100644
index 0000000..88e32a5
--- /dev/null
+++ b/docs/README.md
@@ -0,0 +1,82 @@
+<!-- omit in toc -->
+# Post-Training & Alignment — Overview
+
+When I first trained this transformer from scratch, it could *continue* text but it couldn't
+*follow instructions* or *reason*. That's what post-training fixes. This `docs/` folder walks
+through the whole journey I built on top of the base model — every stage written from scratch
+in plain PyTorch (no `trl`, no `peft`, no `transformers`), trained on real public datasets, and
+runnable on a single GPU or scaled across multiple GPUs with DDP.
+
+The pipeline mirrors how modern aligned/reasoning models are actually built:
+
+![Post-training pipeline](diagrams/00_overview.png)
+
+<details>
+<summary>Mermaid source (live, editable)</summary>
+
+```mermaid
+flowchart TD
+ PILE([The Pile<br/>9.8B tokens]):::data --> PRE{{Pretrain<br/>~400M base}}:::model
+ PRE --> BASE[(base_pretrained.pt)]:::ckpt
+ BASE --> SFT{{SFT<br/>Alpaca · Dolly · GSM8K}}:::model
+ SFT --> SFTCK[(sft.pt)]:::ckpt
+ SFTCK --> RM{{Reward Model<br/>Bradley-Terry}}:::rl
+ SFTCK --> DPO{{DPO / ORPO / KTO<br/>preference}}:::rl
+ RM --> RMCK[(reward.pt)]:::ckpt
+ RMCK -->|reward signal| PPO{{PPO<br/>GAE + clip + KL}}:::rl
+ SFTCK --> PPO
+ SFTCK --> GRPO{{GRPO / RLVR<br/>group-relative}}:::rl
+ PPO --> EVAL([GSM8K eval<br/>+ chat / inference]):::eval
+ DPO --> EVAL
+ GRPO --> EVAL
+ classDef data fill:#d6ffd9,stroke:#27ae60,stroke-width:2px,color:#143d1a;
+ classDef model fill:#ffe8a3,stroke:#d48806,stroke-width:2px,color:#5a3d00;
+ classDef rl fill:#ffd9b3,stroke:#e67e22,stroke-width:2px,color:#6b3500;
+ classDef ckpt fill:#eeeeee,stroke:#555555,stroke-width:2px,color:#222;
+ classDef eval fill:#e8d6ff,stroke:#8e44ad,stroke-width:2px,color:#3d1a5a;
+```
+
+</details>
+
+## The stages, in order
+
+| # | Stage | What it teaches the model | Doc |
+|---|---|---|---|
+| 1 | **Pretraining** | language itself (next-token prediction on the Pile) | [02_pretraining.md](02_pretraining.md) |
+| 2 | **SFT** | to follow instructions & produce the `<think>/<answer>` format | [03_sft.md](03_sft.md) |
+| 3 | **Reward Model** | to score which answer humans prefer | [04_reward_model.md](04_reward_model.md) |
+| 4 | **DPO / ORPO / KTO** | to prefer better answers *without* an RL loop | [05_dpo.md](05_dpo.md) |
+| 5 | **PPO** | to maximize a reward (RM or verifier) with the classic RLHF loop | [06_ppo.md](06_ppo.md) |
+| 6 | **GRPO / RLVR** | to reason, using verifiable rewards (DeepSeek-R1 style) | [07_grpo.md](07_grpo.md) |
+| — | **Data pipeline** | how every dataset above is downloaded & preprocessed | [01_data_pipeline.md](01_data_pipeline.md) |
+| — | **Evaluation** | how I measure GSM8K accuracy across all stages | [08_evaluation.md](08_evaluation.md) |
+| — | **Inference / chat** | how to actually talk to any checkpoint | [09_inference.md](09_inference.md) |
+
+## The one design rule: *wrap, don't rewrite*
+
+Everything here sits on top of the original [`Transformer`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/models/transformer.py). I changed the
+educational model in exactly **one** place — I added a [`forward_hidden`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/src/models/transformer.py#L56)
+method that returns the final hidden states the `lm_head` consumes. Every post-training head (a value
+head for PPO, a scalar reward head for the reward model) and every RL log-prob computation composes
+*around* that one method, so the from-scratch model you already understand stays intact.
+
+## Colour legend (used in every diagram in these docs)
+
+🟩 data / corpus · 🟦 preprocessing · 🟦‍⬛ storage (HDF5 / JSONL) · 🟨 model / training loop
+· 🟧 RL / reward · 🟥 loss / objective · 🟪 evaluation · ⬜ checkpoint
+
+> Each diagram is a hand-drawn, colour-coded Mermaid sketch, **pre-rendered to a PNG and embedded as
+> an image** (GitHub's live Mermaid doesn't reliably do `look: handDrawn`, and some viewers — e.g. the
+> VS Code preview — block SVGs, so an embedded PNG shows everywhere). The editable Mermaid source sits
+> in a collapsible *"Mermaid source"* block under each image. To regenerate the images after editing,
+> see [diagrams/README.md](diagrams/README.md).
+
+## Run the whole thing
+
+Once the base model has pretrained ([02_pretraining.md](02_pretraining.md)), the entire chain is one script:
+
+```bash
+bash scripts/run_posttraining.sh # SFT -> RM -> DPO -> PPO -> GRPO -> eval table
+```
+
+See [POST_TRAINING.md](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/POST_TRAINING.md) for the condensed command reference.
diff --git a/docs/diagrams/00_overview.png b/docs/diagrams/00_overview.png
new file mode 100644
index 0000000..289b15a
Binary files /dev/null and b/docs/diagrams/00_overview.png differ
diff --git a/docs/diagrams/01_data_pipeline.png b/docs/diagrams/01_data_pipeline.png
new file mode 100644
index 0000000..8c0cca4
Binary files /dev/null and b/docs/diagrams/01_data_pipeline.png differ
diff --git a/docs/diagrams/02_pretraining.png b/docs/diagrams/02_pretraining.png
new file mode 100644
index 0000000..53b5f1b
Binary files /dev/null and b/docs/diagrams/02_pretraining.png differ
diff --git a/docs/diagrams/03_sft.png b/docs/diagrams/03_sft.png
new file mode 100644
index 0000000..7bd2cfc
Binary files /dev/null and b/docs/diagrams/03_sft.png differ
diff --git a/docs/diagrams/04_reward_model.png b/docs/diagrams/04_reward_model.png
new file mode 100644
index 0000000..df92740
Binary files /dev/null and b/docs/diagrams/04_reward_model.png differ
diff --git a/docs/diagrams/05_dpo.png b/docs/diagrams/05_dpo.png
new file mode 100644
index 0000000..f6ad7e5
Binary files /dev/null and b/docs/diagrams/05_dpo.png differ
diff --git a/docs/diagrams/06_ppo.png b/docs/diagrams/06_ppo.png
new file mode 100644
index 0000000..8fa51f4
Binary files /dev/null and b/docs/diagrams/06_ppo.png differ
diff --git a/docs/diagrams/07_grpo.png b/docs/diagrams/07_grpo.png
new file mode 100644
index 0000000..2703ab4
Binary files /dev/null and b/docs/diagrams/07_grpo.png differ
diff --git a/docs/diagrams/08_evaluation.png b/docs/diagrams/08_evaluation.png
new file mode 100644
index 0000000..74bb66f
Binary files /dev/null and b/docs/diagrams/08_evaluation.png differ
diff --git a/docs/diagrams/09_inference.png b/docs/diagrams/09_inference.png
new file mode 100644
index 0000000..6b91092
Binary files /dev/null and b/docs/diagrams/09_inference.png differ
diff --git a/docs/diagrams/README.md b/docs/diagrams/README.md
new file mode 100644
index 0000000..f449e11
--- /dev/null
+++ b/docs/diagrams/README.md
@@ -0,0 +1,30 @@
+# Diagrams
+
+The documentation diagrams are **hand-drawn, colour-coded Mermaid sketches**, pre-rendered to PNG and
+embedded as images in the docs. We pre-render (rather than rely on live ```` ```mermaid ```` blocks)
+because GitHub's live Mermaid renderer does not reliably support the `look: handDrawn` style, and some
+markdown viewers (e.g. the VS Code preview) block SVGs — an embedded **PNG** shows the hand-drawn look
+everywhere. Each doc also keeps the editable Mermaid source in a collapsible *"Mermaid source"* block
+under its image.
+
+## Files
+
+- `src/*.mmd` — the canonical hand-drawn Mermaid sources (with `look: handDrawn` + the colour palette).
+- `*.png` — the rendered images embedded by the docs (and `README.png` for the top-level README).
+
+## Regenerate after editing
+
+Edit the relevant `src/<name>.mmd`, then from the repo root:
+
+```bash
+bash scripts/render_diagrams.sh
+```
+
+That re-renders every `src/*.mmd` to `docs/diagrams/<name>.png`. Requires the Mermaid CLI
+(`npm i -g @mermaid-js/mermaid-cli`) and a Chrome/Chromium for headless rendering
+(set `CHROME=/path/to/chrome` if it isn't at `/usr/bin/google-chrome-stable`).
+
+## Colour legend
+
+🟩 data / corpus · 🟦 preprocessing · teal storage (HDF5 / JSONL) · 🟨 model / training loop ·
+🟧 RL / reward · 🟥 loss / objective · 🟪 evaluation · ⬜ checkpoint
diff --git a/docs/diagrams/README.png b/docs/diagrams/README.png
new file mode 100644
index 0000000..6fd7449
Binary files /dev/null and b/docs/diagrams/README.png differ
diff --git a/docs/diagrams/src/00_overview.mmd b/docs/diagrams/src/00_overview.mmd
new file mode 100644
index 0000000..b13b547
--- /dev/null
+++ b/docs/diagrams/src/00_overview.mmd
@@ -0,0 +1,20 @@
+%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'fontFamily':'Comic Sans MS, cursive'}}}%%
+flowchart TD
+ PILE([The Pile<br/>9.8B tokens]):::data --> PRE{{Pretrain<br/>~400M base}}:::model
+ PRE --> BASE[(base_pretrained.pt)]:::ckpt
+ BASE --> SFT{{SFT<br/>Alpaca · Dolly · GSM8K}}:::model
+ SFT --> SFTCK[(sft.pt)]:::ckpt
+ SFTCK --> RM{{Reward Model<br/>Bradley-Terry}}:::rl
+ SFTCK --> DPO{{DPO / ORPO / KTO<br/>preference}}:::rl
+ RM --> RMCK[(reward.pt)]:::ckpt
+ RMCK -->|reward signal| PPO{{PPO<br/>GAE + clip + KL}}:::rl
+ SFTCK --> PPO
+ SFTCK --> GRPO{{GRPO / RLVR<br/>group-relative}}:::rl
+ PPO --> EVAL([GSM8K eval<br/>+ chat / inference]):::eval
+ DPO --> EVAL
+ GRPO --> EVAL
+ classDef data fill:#d6ffd9,stroke:#27ae60,stroke-width:2px,color:#143d1a;
+ classDef model fill:#ffe8a3,stroke:#d48806,stroke-width:2px,color:#5a3d00;
+ classDef rl fill:#ffd9b3,stroke:#e67e22,stroke-width:2px,color:#6b3500;
+ classDef ckpt fill:#eeeeee,stroke:#555555,stroke-width:2px,color:#222;
+ classDef eval fill:#e8d6ff,stroke:#8e44ad,stroke-width:2px,color:#3d1a5a;
diff --git a/docs/diagrams/src/01_data_pipeline.mmd b/docs/diagrams/src/01_data_pipeline.mmd
new file mode 100644
index 0000000..6f7d254
--- /dev/null
+++ b/docs/diagrams/src/01_data_pipeline.mmd
@@ -0,0 +1,23 @@
+%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'fontFamily':'Comic Sans MS, cursive'}}}%%
+flowchart TD
+ subgraph PT[" 1 · Pretraining "]
+ P1([Pile .jsonl.zst]):::data --> P2[stream-decompress<br/>+ tiktoken r50k_base]:::proc --> P3[(pile_train.h5<br/>flat tokens)]:::store
+ end
+ subgraph SF[" 2 · SFT "]
+ S1([Alpaca · Dolly · GSM8K]):::data --> S2[render chat template<br/>mask prompt tokens]:::proc --> S3[pack to 1024]:::proc --> S4[(sft_packed.h5<br/>tokens + loss_mask)]:::store
+ end
+ subgraph PF[" 3 · Preferences "]
+ F1([HH-RLHF · UltraFeedback]):::data --> F2[split prompt /<br/>chosen / rejected]:::proc --> F3[(preferences.jsonl)]:::store
+ end
+ subgraph RL[" 4 · RL prompts "]
+ R1([GSM8K · arithmetic]):::data --> R2[extract numeric<br/>gold answer]:::proc --> R3[(rl_prompts.jsonl<br/>prompt + gold)]:::store
+ end
+ P3 --> M1{{pretrain_base.py}}:::model
+ S4 --> M2{{train_sft.py}}:::model
+ F3 --> M3{{train_reward.py · train_dpo.py}}:::rl
+ R3 --> M4{{train_ppo.py · train_grpo.py}}:::rl
+ classDef data fill:#d6ffd9,stroke:#27ae60,stroke-width:2px,color:#143d1a;
+ classDef proc fill:#d6e8ff,stroke:#2c6fbb,stroke-width:2px,color:#0d2c52;
+ classDef store fill:#cdece8,stroke:#16a085,stroke-width:2px,color:#0a3d33;
+ classDef model fill:#ffe8a3,stroke:#d48806,stroke-width:2px,color:#5a3d00;
+ classDef rl fill:#ffd9b3,stroke:#e67e22,stroke-width:2px,color:#6b3500;
diff --git a/docs/diagrams/src/02_pretraining.mmd b/docs/diagrams/src/02_pretraining.mmd
new file mode 100644
index 0000000..6b05c1b
--- /dev/null
+++ b/docs/diagrams/src/02_pretraining.mmd
@@ -0,0 +1,15 @@
+%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'fontFamily':'Comic Sans MS, cursive'}}}%%
+flowchart LR
+ H[(pile_train.h5)]:::store --> IT[get_batch_iterator<br/>random windows]:::proc
+ IT --> FWD{{forward<br/>bf16 autocast}}:::model
+ FWD --> L[cross-entropy loss]:::loss
+ L --> BWD[backward<br/>x grad_accum]:::model
+ BWD --> CL[clip grad norm 1.0]:::proc
+ CL --> ST[AdamW step<br/>cosine LR + warmup]:::model
+ ST -->|every 1000 steps| CK[(base_pretrained.pt)]:::ckpt
+ ST -->|next step| IT
+ classDef store fill:#cdece8,stroke:#16a085,stroke-width:2px,color:#0a3d33;
+ classDef proc fill:#d6e8ff,stroke:#2c6fbb,stroke-width:2px,color:#0d2c52;
+ classDef model fill:#ffe8a3,stroke:#d48806,stroke-width:2px,color:#5a3d00;
+ classDef loss fill:#ffd6d6,stroke:#c0392b,stroke-width:2px,color:#5c1212;
+ classDef ckpt fill:#eeeeee,stroke:#555,stroke-width:2px,color:#222;
diff --git a/docs/diagrams/src/03_sft.mmd b/docs/diagrams/src/03_sft.mmd
new file mode 100644
index 0000000..3d47086
--- /dev/null
+++ b/docs/diagrams/src/03_sft.mmd
@@ -0,0 +1,13 @@
+%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'fontFamily':'Comic Sans MS, cursive'}}}%%
+flowchart LR
+ H[(sft_packed.h5<br/>tokens + loss_mask)]:::store --> B[batch:<br/>tokens, mask]:::proc
+ B --> M{{Transformer<br/>logits}}:::model
+ M --> SH[shift: predict t+1]:::proc
+ SH --> CE[token cross-entropy]:::loss
+ MASK([loss_mask = 1 on<br/>assistant tokens]):::data --> CE
+ CE --> AVG[average over<br/>masked tokens only]:::loss --> UPD[AdamW step]:::model
+ classDef store fill:#cdece8,stroke:#16a085,stroke-width:2px,color:#0a3d33;
+ classDef proc fill:#d6e8ff,stroke:#2c6fbb,stroke-width:2px,color:#0d2c52;
+ classDef data fill:#d6ffd9,stroke:#27ae60,stroke-width:2px,color:#143d1a;
+ classDef model fill:#ffe8a3,stroke:#d48806,stroke-width:2px,color:#5a3d00;
+ classDef loss fill:#ffd6d6,stroke:#c0392b,stroke-width:2px,color:#5c1212;
diff --git a/docs/diagrams/src/04_reward_model.mmd b/docs/diagrams/src/04_reward_model.mmd
new file mode 100644
index 0000000..844c141
--- /dev/null
+++ b/docs/diagrams/src/04_reward_model.mmd
@@ -0,0 +1,15 @@
+%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'fontFamily':'Comic Sans MS, cursive'}}}%%
+flowchart LR
+ P([preference pair<br/>prompt + chosen / rejected]):::data --> BB{{SFT backbone<br/>forward_hidden}}:::model
+ BB --> LT[take last real token]:::proc
+ LT --> RH[reward head<br/>Linear→1]:::model
+ RH --> RC([r_chosen]):::rl
+ RH --> RR([r_rejected]):::rl
+ RC --> BT[Bradley-Terry<br/>-log σ r_chosen - r_rejected]:::loss
+ RR --> BT
+ BT --> UPD[AdamW step]:::model
+ classDef data fill:#d6ffd9,stroke:#27ae60,stroke-width:2px,color:#143d1a;
+ classDef proc fill:#d6e8ff,stroke:#2c6fbb,stroke-width:2px,color:#0d2c52;
+ classDef model fill:#ffe8a3,stroke:#d48806,stroke-width:2px,color:#5a3d00;
+ classDef rl fill:#ffd9b3,stroke:#e67e22,stroke-width:2px,color:#6b3500;
+ classDef loss fill:#ffd6d6,stroke:#c0392b,stroke-width:2px,color:#5c1212;
diff --git a/docs/diagrams/src/05_dpo.mmd b/docs/diagrams/src/05_dpo.mmd
new file mode 100644
index 0000000..3ca5f59
--- /dev/null
+++ b/docs/diagrams/src/05_dpo.mmd
@@ -0,0 +1,14 @@
+%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'fontFamily':'Comic Sans MS, cursive'}}}%%
+flowchart LR
+ P([chosen / rejected]):::data --> POL{{policy<br/>trainable}}:::model
+ P --> REF{{reference<br/>frozen SFT copy}}:::ckpt
+ POL --> LPP[seq log-probs<br/>π_chosen, π_rejected]:::proc
+ REF --> LPR[seq log-probs<br/>ref_chosen, ref_rejected]:::proc
+ LPP --> D[DPO loss<br/>-log σ β·Δlogratios]:::loss
+ LPR --> D
+ D --> UPD[AdamW step]:::model
+ classDef data fill:#d6ffd9,stroke:#27ae60,stroke-width:2px,color:#143d1a;
+ classDef proc fill:#d6e8ff,stroke:#2c6fbb,stroke-width:2px,color:#0d2c52;
+ classDef model fill:#ffe8a3,stroke:#d48806,stroke-width:2px,color:#5a3d00;
+ classDef ckpt fill:#eeeeee,stroke:#555,stroke-width:2px,color:#222;
+ classDef loss fill:#ffd6d6,stroke:#c0392b,stroke-width:2px,color:#5c1212;
diff --git a/docs/diagrams/src/06_ppo.mmd b/docs/diagrams/src/06_ppo.mmd
new file mode 100644
index 0000000..1b8aa79
--- /dev/null
+++ b/docs/diagrams/src/06_ppo.mmd
@@ -0,0 +1,17 @@
+%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'fontFamily':'Comic Sans MS, cursive'}}}%%
+flowchart LR
+ PR([GSM8K prompts]):::data --> RO[rollout<br/>generate_with_logprobs]:::proc
+ RO --> SC{score: verifier<br/>or reward model}:::rl
+ SC --> KL[+ per-token<br/>KL-to-ref penalty]:::rl
+ KL --> GAE[compute_gae<br/>advantages + returns]:::proc
+ GAE --> UP{{clipped update<br/>policy + value, K epochs}}:::model
+ UP -->|sync old policy| RO
+ REF{{frozen ref}}:::ckpt
+ REF -. KL .-> KL
+ VH{{value head}}:::model
+ VH -. value .-> GAE
+ classDef data fill:#d6ffd9,stroke:#27ae60,stroke-width:2px,color:#143d1a;
+ classDef proc fill:#d6e8ff,stroke:#2c6fbb,stroke-width:2px,color:#0d2c52;
+ classDef rl fill:#ffd9b3,stroke:#e67e22,stroke-width:2px,color:#6b3500;
+ classDef model fill:#ffe8a3,stroke:#d48806,stroke-width:2px,color:#5a3d00;
+ classDef ckpt fill:#eeeeee,stroke:#555,stroke-width:2px,color:#222;
diff --git a/docs/diagrams/src/07_grpo.mmd b/docs/diagrams/src/07_grpo.mmd
new file mode 100644
index 0000000..080f872
--- /dev/null
+++ b/docs/diagrams/src/07_grpo.mmd
@@ -0,0 +1,16 @@
+%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'fontFamily':'Comic Sans MS, cursive'}}}%%
+flowchart LR
+ PR([prompt]):::data --> G[sample a GROUP<br/>of G answers]:::proc
+ G --> V{verifier reward<br/>per answer}:::rl
+ V --> A[group advantage<br/>r - mean / std]:::proc
+ A --> L[clipped surrogate<br/>+ k3 KL to ref]:::loss
+ L --> UPD{{policy update}}:::model
+ UPD -->|next prompt| PR
+ REF{{frozen ref}}:::ckpt
+ REF -. KL .-> L
+ classDef data fill:#d6ffd9,stroke:#27ae60,stroke-width:2px,color:#143d1a;
+ classDef proc fill:#d6e8ff,stroke:#2c6fbb,stroke-width:2px,color:#0d2c52;
+ classDef rl fill:#ffd9b3,stroke:#e67e22,stroke-width:2px,color:#6b3500;
+ classDef loss fill:#ffd6d6,stroke:#c0392b,stroke-width:2px,color:#5c1212;
+ classDef model fill:#ffe8a3,stroke:#d48806,stroke-width:2px,color:#5a3d00;
+ classDef ckpt fill:#eeeeee,stroke:#555,stroke-width:2px,color:#222;
diff --git a/docs/diagrams/src/08_evaluation.mmd b/docs/diagrams/src/08_evaluation.mmd
new file mode 100644
index 0000000..1862d30
--- /dev/null
+++ b/docs/diagrams/src/08_evaluation.mmd
@@ -0,0 +1,12 @@
+%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'fontFamily':'Comic Sans MS, cursive'}}}%%
+flowchart LR
+ CK[(stage checkpoint)]:::ckpt --> GEN[batched_generate<br/>greedy, length-bucketed]:::proc
+ Q([GSM8K question]):::data --> GEN
+ GEN --> EX[extract_answer<br/>answer / #### / last number]:::proc
+ EX --> CMP{== gold?}:::eval
+ GOLD([gold number]):::data --> CMP
+ CMP --> ACC[accuracy across<br/>Base→SFT→DPO→PPO→GRPO]:::eval
+ classDef ckpt fill:#eeeeee,stroke:#555,stroke-width:2px,color:#222;
+ classDef proc fill:#d6e8ff,stroke:#2c6fbb,stroke-width:2px,color:#0d2c52;
+ classDef data fill:#d6ffd9,stroke:#27ae60,stroke-width:2px,color:#143d1a;
+ classDef eval fill:#e8d6ff,stroke:#8e44ad,stroke-width:2px,color:#3d1a5a;
diff --git a/docs/diagrams/src/09_inference.mmd b/docs/diagrams/src/09_inference.mmd
new file mode 100644
index 0000000..d16651e
--- /dev/null
+++ b/docs/diagrams/src/09_inference.mmd
@@ -0,0 +1,13 @@
+%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'fontFamily':'Comic Sans MS, cursive'}}}%%
+flowchart LR
+ CK[(any checkpoint)]:::ckpt --> LD[load_model_from_ckpt<br/>dims from stored cfg]:::proc
+ LD --> MODE{chat or raw?}:::proc
+ MODE -->|instruction model| CT[wrap in chat template]:::proc
+ MODE -->|base model| RAW[raw prefix]:::proc
+ CT --> GEN{{generate<br/>temperature / top-p / greedy}}:::model
+ RAW --> GEN
+ GEN --> DEC([decode → reply]):::eval
+ classDef ckpt fill:#eeeeee,stroke:#555,stroke-width:2px,color:#222;
+ classDef proc fill:#d6e8ff,stroke:#2c6fbb,stroke-width:2px,color:#0d2c52;
+ classDef model fill:#ffe8a3,stroke:#d48806,stroke-width:2px,color:#5a3d00;
+ classDef eval fill:#e8d6ff,stroke:#8e44ad,stroke-width:2px,color:#3d1a5a;
diff --git a/docs/diagrams/src/README.mmd b/docs/diagrams/src/README.mmd
new file mode 100644
index 0000000..442e337
--- /dev/null
+++ b/docs/diagrams/src/README.mmd
@@ -0,0 +1,20 @@
+%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'fontFamily':'Comic Sans MS, cursive'}}}%%
+flowchart TD
+ PILE([The Pile<br/>9.8B tokens]):::data --> PRE{{Pretrain<br/>~400M base}}:::model
+ PRE --> BASE[(base_pretrained.pt)]:::ckpt
+ BASE --> SFT{{SFT<br/>Alpaca · Dolly · GSM8K}}:::model
+ SFT --> SFTCK[(sft.pt)]:::ckpt
+ SFTCK --> RM{{Reward Model<br/>Bradley-Terry}}:::rl
+ SFTCK --> DPO{{DPO / ORPO / KTO}}:::rl
+ RM --> RMCK[(reward.pt)]:::ckpt
+ RMCK -->|reward signal| PPO{{PPO<br/>GAE + clip + KL}}:::rl
+ SFTCK --> PPO
+ SFTCK --> GRPO{{GRPO / RLVR<br/>group-relative}}:::rl
+ PPO --> EVAL([GSM8K eval<br/>+ chat]):::eval
+ DPO --> EVAL
+ GRPO --> EVAL
+ classDef data fill:#d6ffd9,stroke:#27ae60,stroke-width:2px,color:#143d1a;
+ classDef model fill:#ffe8a3,stroke:#d48806,stroke-width:2px,color:#5a3d00;
+ classDef rl fill:#ffd9b3,stroke:#e67e22,stroke-width:2px,color:#6b3500;
+ classDef ckpt fill:#eeeeee,stroke:#555555,stroke-width:2px,color:#222;
+ classDef eval fill:#e8d6ff,stroke:#8e44ad,stroke-width:2px,color:#3d1a5a;
diff --git a/docs/howto/commands.md b/docs/howto/commands.md
new file mode 100644
index 0000000..a04684f
--- /dev/null
+++ b/docs/howto/commands.md
@@ -0,0 +1,6 @@
+# Command cheatsheet
+
+The condensed command reference for the whole pipeline (included verbatim from
+[`POST_TRAINING.md`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/POST_TRAINING.md)).
+
+--8<-- "POST_TRAINING.md"
diff --git a/docs/howto/configs.md b/docs/howto/configs.md
new file mode 100644
index 0000000..97746f8
--- /dev/null
+++ b/docs/howto/configs.md
@@ -0,0 +1,65 @@
+# Configure with JSON
+
+Every training stage is configured by a small, human-editable JSON file under
+[`configs/`](https://github.com/FareedKhan-dev/train-llm-from-scratch/tree/main/configs). You edit one
+file and see only that stage's knobs — the model architecture and runtime live in the shared
+`configs/base.json`.
+
+```
+configs/
+ base.json # shared model + runtime (vocab, n_embed, device, amp_dtype, ...)
+ pretrain.json # one file per stage — only that stage's hyperparameters
+ sft.json reward.json dpo.json ppo.json grpo.json
+ smoke/ # tiny CPU variant (small model + few steps) for quick tests
+ base.json pretrain.json sft.json ...
+```
+
+## How a config is resolved
+
+[`config/loader.py`](https://github.com/FareedKhan-dev/train-llm-from-scratch/blob/main/config/loader.py)
+merges four layers, **lowest precedence first**:
+
+```
+dataclass defaults < configs/base.json < configs/<stage>.json < CLI --field overrides
+```
+
+The dataclasses in `config/post_training_config.py` are the typed schema; the JSON is the editable
+source; the CLI wins for quick one-offs. JSON `null` maps to Python `None` (the clean way to set a
+`str | None` field such as `amp_dtype`).
+
+!!! tip "Smoke configs auto-shrink the model"
+ A stage JSON in a sub-folder uses that folder's `base.json`. So `configs/smoke/sft.json` picks up
+ `configs/smoke/base.json` (tiny model, CPU) automatically — handy for a fast end-to-end test.
+
+## Editing & inspecting
+
+=== "Edit the JSON"
+
+ ```jsonc
+ // configs/sft.json
+ {
+ "pretrained_ckpt": "/ephemeral/ckpts/base_pretrained.pt",
+ "data_path": "/ephemeral/data/sft_packed.h5",
+ "lr": 1e-5,
+ "epochs": 3,
+ "batch_size": 16
+ }
+ ```
+
+=== "Override on the CLI"
+
+ ```bash
+ # --field beats the JSON
+ python scripts/train_sft.py --config configs/sft.json --lr 2e-5 --batch_size 8
+ ```
+
+=== "Print the resolved config"
+
+ ```bash
+ python scripts/train_sft.py --config configs/sft.json --print-config
+ # dumps the fully merged config as JSON, then exits
+ ```
+
+Every trainer accepts `--config <path>` (defaulting to its stage file), all `--field` overrides, and
+`--print-config`. The legacy pretraining path (`scripts/train_transformer.py` + `config/config.py`) is
+untouched and still works as the README teaches.
diff --git a/docs/howto/train.md b/docs/howto/train.md
new file mode 100644
index 0000000..dc43a06
--- /dev/null
+++ b/docs/howto/train.md
@@ -0,0 +1,67 @@
+# Train (UI & CLI)
+
+You can run every stage two ways: from the **command line** (full control, best for long jobs) or from
+the **Streamlit control panel** (forms, one-click launch, live logs, charts — see [The UI](ui.md)).
+
+## Install
+
+```bash
+pip install -e ".[train]" # editable install — no more PYTHONPATH=.
+export HF_HOME=/ephemeral/hf_cache
+```
+
+## The pipeline, end to end (CLI)
+
+Each command reads its stage JSON from `configs/` (override anything with `--field`, or point at another
+file with `--config`). Use `python` for one GPU and `torchrun` for many.
+
+=== "1. Data"
+
+ ```bash
+ python scripts/prepare_pretrain_data.py --split val --out /ephemeral/data/pile_dev.h5
+ python scripts/prepare_pretrain_data.py --split train --num_shards 1 --out /ephemeral/data/pile_train.h5
+ python scripts/prepare_sft_data.py
+ python scripts/prepare_preference_data.py --source both
+ python scripts/prepare_rl_prompts.py
+ ```
+
+=== "2. Pretrain"
+
+ ```bash
+ # single GPU
+ python scripts/pretrain_base.py --config configs/pretrain.json
+ # both GPUs (effective batch = batch_size * grad_accum * num_gpus)
+ torchrun --standalone --nproc_per_node=2 scripts/pretrain_base.py --config configs/pretrain.json
+ ```
+
+=== "3. Align"
+
+ ```bash
+ torchrun --standalone --nproc_per_node=2 scripts/train_sft.py
+ torchrun --standalone --nproc_per_node=2 scripts/train_reward.py
+ torchrun --standalone --nproc_per_node=2 scripts/train_dpo.py --loss_type dpo
+ torchrun --standalone --nproc_per_node=2 scripts/train_ppo.py --reward_source verifier
+ torchrun --standalone --nproc_per_node=2 scripts/train_grpo.py
+ ```
+
+The whole alignment chain in one shot:
+
+```bash
+bash scripts/run_posttraining.sh # SFT → RM → DPO → PPO → GRPO → eval table
+```
+
+## Multi-GPU notes
+
+- `torchrun --standalone --nproc_per_node=N` launches N data-parallel ranks (DDP + bf16). Only rank 0
+ logs and checkpoints.
+- On the dev box (2× H100, no NVLink) the educational attention materializes a `(B, n_head, T, T)` tensor
+ per block, so memory scales with sequence length — at context 1024 use `--batch_size 8 --grad_accum 12`
+ and recover the effective batch via accumulation. Set `PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True`.
+
+## Where outputs go
+
+- Checkpoints → `/ephemeral/ckpts/<stage>.pt` (each carries its own resolved `cfg`).
+- Metrics → `/ephemeral/logs/<stage>_<timestamp>.jsonl` (one JSON per logged step). The UI plots these
+ live; you can also `--use_wandb true` to mirror to Weights & Biases.
+
+Then [evaluate](../08_evaluation.md) on GSM8K and [chat](../09_inference.md) with any checkpoint.
diff --git a/docs/howto/ui.md b/docs/howto/ui.md
new file mode 100644
index 0000000..679705e
--- /dev/null
+++ b/docs/howto/ui.md
@@ -0,0 +1,36 @@
+# The control-panel UI
+
+A polished **Streamlit** app that wraps the whole pipeline — theory, one-click training, live logs,
+metric charts, evaluation, and chat — so you can drive everything without memorizing commands.
+
+```bash
+pip install -e ".[ui]"
+streamlit run ui/app.py
+```
+
+## What's inside
+
+- **Home** — the pipeline diagram, live job status, and GPU status at a glance.
+- **Data** — launch the `prepare_*` scripts and watch the files appear under `/ephemeral/data`.
+- **A page per stage** (Pretrain, SFT, Reward, DPO, PPO, GRPO). Each page gives you:
+ 1. the **theory + hand-drawn diagram** for that stage (pulled straight from these docs),
+ 2. a **config form** that writes the stage's `configs/*.json`,
+ 3. a **Launch** button that runs the real training script as a background job, and
+ 4. a **live log tail** + **metric charts** (loss / reward / KL / accuracy) read from the JSONL.
+- **Evaluate** — run GSM8K accuracy on any checkpoint and inspect sample generations.
+- **Chat** — talk to any checkpoint in-process, with temperature / top-p / top-k controls.
+
+## How launching works
+
+The app builds the same command you'd type (`torchrun … scripts/train_sft.py --config …`), runs it as a
+detached background process, and streams its log file into the page — so jobs keep running even if you
+navigate away or refresh. A **Stop** button cleanly terminates the job (and all `torchrun` workers).
+
+!!! warning "One GPU job at a time"
+ Two multi-GPU `torchrun` jobs would fight over the same cards and OOM. The UI's **GPU-busy guard**
+ disables *Launch* for a GPU stage while another GPU job is running (e.g. while pretraining occupies
+ both H100s). CPU/smoke runs and the in-process **Chat** page always stay available.
+
+!!! tip "Smoke mode"
+ Each stage page has a *smoke* toggle that uses the tiny `configs/smoke/*.json` (small model, few
+ steps, CPU) so you can validate the whole flow in seconds before committing to a real run.
diff --git a/mkdocs.yml b/mkdocs.yml
new file mode 100644
index 0000000..c46685c
--- /dev/null
+++ b/mkdocs.yml
@@ -0,0 +1,83 @@
+site_name: Train LLM From Scratch
+site_description: From pretraining to RLHF/GRPO — every algorithm hand-written in pure PyTorch.
+site_url: https://FareedKhan-dev.github.io/train-llm-from-scratch/
+repo_url: https://github.com/FareedKhan-dev/train-llm-from-scratch
+repo_name: FareedKhan-dev/train-llm-from-scratch
+docs_dir: docs
+# Files present under docs/ but intentionally not page nodes in the nav.
+not_in_nav: |
+ /diagrams/README.md
+# Keep the raw mermaid sources out of the built site.
+exclude_docs: |
+ /diagrams/src/
+
+theme:
+ name: material
+ icon:
+ repo: fontawesome/brands/github
+ palette:
+ - media: "(prefers-color-scheme: light)"
+ scheme: default
+ primary: teal
+ accent: teal
+ toggle: {icon: material/weather-night, name: Switch to dark mode}
+ - media: "(prefers-color-scheme: dark)"
+ scheme: slate
+ primary: teal
+ accent: teal
+ toggle: {icon: material/weather-sunny, name: Switch to light mode}
+ features:
+ - navigation.tabs
+ - navigation.sections
+ - navigation.top
+ - navigation.indexes
+ - toc.follow
+ - search.suggest
+ - search.highlight
+ - content.code.copy
+ - content.code.annotate
+
+plugins:
+ - search
+
+markdown_extensions:
+ - admonition
+ - attr_list
+ - md_in_html
+ - footnotes
+ - toc:
+ permalink: true
+ - pymdownx.highlight:
+ anchor_linenums: true
+ - pymdownx.inlinehilite
+ - pymdownx.snippets:
+ base_path: ["."] # so howto/commands.md can include the root POST_TRAINING.md
+ - pymdownx.superfences:
+ custom_fences:
+ - name: mermaid
+ class: mermaid
+ format: !!python/name:pymdownx.superfences.fence_code_format
+ - pymdownx.tabbed:
+ alternate_style: true
+
+extra_javascript:
+ - https://unpkg.com/mermaid@11/dist/mermaid.min.js # live hand-drawn mermaid in <details>
+
+nav:
+ - Home: README.md
+ - Theory & Pipeline:
+ - Data handling: 01_data_pipeline.md
+ - Pretraining: 02_pretraining.md
+ - SFT: 03_sft.md
+ - Reward Model: 04_reward_model.md
+ - DPO / ORPO / KTO: 05_dpo.md
+ - PPO: 06_ppo.md
+ - GRPO / RLVR: 07_grpo.md
+ - How-to:
+ - Configure (JSON): howto/configs.md
+ - Train (UI & CLI): howto/train.md
+ - The control-panel UI: howto/ui.md
+ - Evaluate: 08_evaluation.md
+ - Inference / Chat: 09_inference.md
+ - Reference:
+ - Command cheatsheet: howto/commands.md
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 0000000..2643daf
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,42 @@
+[build-system]
+requires = ["setuptools>=68"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "train-llm-from-scratch"
+version = "0.1.0"
+description = "Train an LLM from scratch in pure PyTorch — pretraining through SFT, Reward Modeling, PPO, DPO and GRPO/RLVR."
+readme = "README.md"
+requires-python = ">=3.9"
+license = { text = "MIT" }
+# Core deps for the model + data path. (The teaching pretraining path also has
+# requirements.txt with cu118 wheels; this project install does not pin a CUDA build —
+# install the right torch wheel for your machine first if needed.)
+dependencies = [
+ "torch",
+ "numpy",
+ "h5py",
+ "tqdm",
+ "tiktoken",
+ "zstandard",
+ "requests",
+]
+
+[project.optional-dependencies]
+# Post-training extras (datasets + optional experiment logging).
+train = ["datasets", "wandb"]
+# The Streamlit control-panel UI.
+ui = ["streamlit", "pandas", "altair"]
+# The MkDocs Material documentation site.
+docs = ["mkdocs", "mkdocs-material", "pymdown-extensions"]
+# Everything, for development.
+all = ["datasets", "wandb", "streamlit", "pandas", "altair", "mkdocs", "mkdocs-material", "pymdown-extensions"]
+
+# Make the existing import roots installable so `pip install -e .` removes the need for
+# `PYTHONPATH=.`. These packages already exist in the repo (additive __init__.py only).
+[tool.setuptools]
+packages = ["config", "data_loader", "src", "src.models", "src.post_training", "src.post_training.rewards", "ui"]
+
+[tool.setuptools.package-data]
+# ship the JSON configs alongside the package
+"*" = ["*.json"]
diff --git a/requirements-post.txt b/requirements-post.txt
new file mode 100644
index 0000000..b149d7d
--- /dev/null
+++ b/requirements-post.txt
@@ -0,0 +1,19 @@
+# Post-training stack for the from-scratch SFT / RM / PPO / DPO / GRPO suite.
+# Targets H100 + CUDA 12.x (the base requirements.txt pins cu118 for the original
+# pretraining path; this file does NOT overwrite it). Install into a fresh venv:
+#
+# python3 -m venv /ephemeral/venv && source /ephemeral/venv/bin/activate
+# pip install -r requirements-post.txt
+#
+# torchrun (multi-GPU) ships with torch.
+
+--extra-index-url https://download.pytorch.org/whl/cu121
+
+torch
+numpy
+h5py
+tqdm
+tiktoken
+zstandard
+datasets # HuggingFace dataset downloads (Alpaca, HH-RLHF, GSM8K, ...)
+wandb # optional experiment logging (every script also writes JSONL)
diff --git a/scripts/chat.py b/scripts/chat.py
new file mode 100644
index 0000000..d9618fb
--- /dev/null
+++ b/scripts/chat.py
@@ -0,0 +1,65 @@
+"""
+Chat / inference CLI for any stage checkpoint (base, SFT, DPO, PPO, GRPO).
+
+Model dimensions are read from the checkpoint, so you only pass the path. Use the chat
+template for instruction-tuned models, or --raw for base-model continuation.
+
+One-shot:
+ PYTHONPATH=. python scripts/chat.py --ckpt /ephemeral/ckpts/sft.pt --prompt "What is 13 + 29?"
+ PYTHONPATH=. python scripts/chat.py --ckpt /ephemeral/ckpts/grpo.pt --prompt "..." --greedy
+ PYTHONPATH=. python scripts/chat.py --ckpt /ephemeral/ckpts/base_pretrained.pt --raw --prompt "Once upon a time"
+Interactive REPL (no --prompt):
+ PYTHONPATH=. python scripts/chat.py --ckpt /ephemeral/ckpts/sft.pt
+"""
+
+from __future__ import annotations
+
+import argparse
+
+import torch
+
+from src.post_training.inference import generate_reply, load_model_from_ckpt
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("--ckpt", required=True)
+ p.add_argument("--prompt", default=None, help="one-shot prompt; omit for interactive REPL")
+ p.add_argument("--system", default=None, help="optional system message (chat mode)")
+ p.add_argument("--raw", action="store_true", help="base-model continuation (no chat template)")
+ p.add_argument("--max_new_tokens", type=int, default=256)
+ p.add_argument("--temperature", type=float, default=0.8)
+ p.add_argument("--top_p", type=float, default=0.95)
+ p.add_argument("--top_k", type=int, default=None)
+ p.add_argument("--greedy", action="store_true", help="deterministic argmax decoding")
+ p.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
+ args = p.parse_args()
+
+ model = load_model_from_ckpt(args.ckpt, args.device)
+ n = sum(p.numel() for p in model.parameters())
+ print(f"loaded {args.ckpt} ({n/1e6:.0f}M params) on {args.device} | "
+ f"mode={'raw' if args.raw else 'chat'} {'greedy' if args.greedy else f'T={args.temperature} top_p={args.top_p}'}")
+
+ def reply(text):
+ return generate_reply(model, text, device=args.device, system=args.system, raw=args.raw,
+ max_new_tokens=args.max_new_tokens, temperature=args.temperature,
+ top_p=args.top_p if args.top_p < 1 else None, top_k=args.top_k, greedy=args.greedy)
+
+ if args.prompt is not None:
+ print(reply(args.prompt))
+ return
+
+ print("Interactive chat (Ctrl-D / 'exit' to quit).")
+ while True:
+ try:
+ text = input("\nyou> ").strip()
+ except EOFError:
+ break
+ if text in ("exit", "quit"):
+ break
+ if text:
+ print("bot>", reply(text))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/eval_post_training.py b/scripts/eval_post_training.py
new file mode 100644
index 0000000..c906562
--- /dev/null
+++ b/scripts/eval_post_training.py
@@ -0,0 +1,87 @@
+"""
+Evaluate any stage checkpoint on GSM8K (greedy) and optionally dump sample generations.
+Use it to build the headline "GSM8K accuracy across stages" table:
+
+ for s in base_pretrained sft dpo ppo grpo; do
+ PYTHONPATH=. python scripts/eval_post_training.py --ckpt /ephemeral/ckpts/$s.pt \
+ --label $s --limit 200 --append /ephemeral/logs/stage_table.jsonl
+ done
+ PYTHONPATH=. python scripts/eval_post_training.py --table /ephemeral/logs/stage_table.jsonl
+
+Model dimensions are read from the checkpoint's stored ``cfg`` so you don't have to repeat
+them. Reward checkpoints (which have a reward head, not an LM head only) still load because
+we keep just the backbone keys for generation.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+
+import torch
+
+from src.models.transformer import Transformer
+from src.post_training.evaluation import gsm8k_accuracy, load_gsm8k_eval
+
+
+def model_from_ckpt(ckpt_path: str, device: str, overrides: dict | None = None) -> Transformer:
+ ck = torch.load(ckpt_path, map_location="cpu", weights_only=False)
+ cfg = ck.get("cfg", {}) or {}
+ cfg = {**cfg, **(overrides or {})}
+ model = Transformer(
+ n_head=cfg.get("n_head", 16), n_embed=cfg.get("n_embed", 1024),
+ context_length=cfg.get("context_length", 1024), vocab_size=cfg.get("vocab_size", 50304),
+ N_BLOCKS=cfg.get("n_blocks", 24),
+ )
+ state = ck["model_state_dict"] if "model_state_dict" in ck else ck
+ state = {k.removeprefix("module.").removeprefix("transformer."): v for k, v in state.items()}
+ backbone_keys = set(model.state_dict().keys())
+ filtered = {k: v for k, v in state.items() if k in backbone_keys}
+ model.load_state_dict(filtered, strict=False)
+ return model.to(device).eval()
+
+
+def print_table(path: str):
+ rows = [json.loads(l) for l in open(path) if l.strip()]
+ print(f"\n{'stage':<18}{'GSM8K acc':>10}{'n':>8}")
+ print("-" * 36)
+ for r in rows:
+ print(f"{r['label']:<18}{r['accuracy']*100:>9.1f}%{r['n']:>8}")
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("--ckpt")
+ p.add_argument("--label", default="model")
+ p.add_argument("--limit", type=int, default=200)
+ p.add_argument("--split", default="test")
+ p.add_argument("--max_new_tokens", type=int, default=300)
+ p.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
+ p.add_argument("--samples", type=int, default=3)
+ p.add_argument("--append", default=None, help="append the result row to this JSONL")
+ p.add_argument("--table", default=None, help="just print a stage table from this JSONL and exit")
+ args = p.parse_args()
+
+ if args.table:
+ print_table(args.table)
+ return
+
+ model = model_from_ckpt(args.ckpt, args.device)
+ qa = load_gsm8k_eval(args.split, limit=args.limit)
+ res = gsm8k_accuracy(model, qa, device=args.device, max_new_tokens=args.max_new_tokens,
+ greedy=True, return_samples=args.samples)
+ print(f"[{args.label}] GSM8K {args.split} accuracy: {res['accuracy']*100:.1f}% ({res['correct']}/{res['n']})")
+ for s in res["samples"]:
+ print(f"\n Q: {s['q'][:120]}\n gold={s['gold']} correct={s['correct']}\n A: {s['response'][:300]}")
+
+ if args.append:
+ os.makedirs(os.path.dirname(args.append) or ".", exist_ok=True)
+ with open(args.append, "a") as f:
+ f.write(json.dumps({"label": args.label, "accuracy": res["accuracy"],
+ "correct": res["correct"], "n": res["n"]}) + "\n")
+ print(f"\nappended -> {args.append}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/prepare_preference_data.py b/scripts/prepare_preference_data.py
new file mode 100644
index 0000000..3b0877b
--- /dev/null
+++ b/scripts/prepare_preference_data.py
@@ -0,0 +1,112 @@
+"""
+Build preference data for the reward model and DPO from real public datasets:
+ - Anthropic/hh-rlhf (helpful/harmless human preferences)
+ - HuggingFaceH4/ultrafeedback_binarized (LLM-judged preference pairs)
+
+Emits JSONL of ``{"prompt", "chosen", "rejected"}`` (train + held-out test). The held-out
+test split is what reward-model preference accuracy is measured on.
+
+Example:
+ PYTHONPATH=. HF_HOME=/ephemeral/hf_cache python scripts/prepare_preference_data.py \
+ --source both --max_per_source 40000 --out_dir /ephemeral/data
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+
+os.environ.setdefault("HF_HOME", "/ephemeral/hf_cache")
+
+_ASSISTANT_MARKER = "\n\nAssistant:"
+
+
+def _split_hh(text: str) -> tuple[str, str] | None:
+ """Split an HH-RLHF conversation string into (prompt_context, final_response)."""
+ idx = text.rfind(_ASSISTANT_MARKER)
+ if idx == -1:
+ return None
+ prompt = text[:idx].strip()
+ response = text[idx + len(_ASSISTANT_MARKER):].strip()
+ if not prompt or not response:
+ return None
+ return prompt, response
+
+
+def from_hh(max_n: int, split: str) -> list[dict]:
+ from datasets import load_dataset
+
+ ds = load_dataset("Anthropic/hh-rlhf", split=split)
+ if max_n:
+ ds = ds.select(range(min(max_n, len(ds))))
+ out = []
+ for ex in ds:
+ c = _split_hh(ex["chosen"]); r = _split_hh(ex["rejected"])
+ if not c or not r:
+ continue
+ prompt, chosen = c
+ _, rejected = r
+ if chosen == rejected:
+ continue
+ out.append({"prompt": prompt, "chosen": chosen, "rejected": rejected})
+ return out
+
+
+def from_ultrafeedback(max_n: int, split: str) -> list[dict]:
+ from datasets import load_dataset
+
+ hf_split = "train_prefs" if split == "train" else "test_prefs"
+ ds = load_dataset("HuggingFaceH4/ultrafeedback_binarized", split=hf_split)
+ if max_n:
+ ds = ds.select(range(min(max_n, len(ds))))
+ out = []
+ for ex in ds:
+ prompt = ex["prompt"].strip()
+ chosen = ex["chosen"][-1]["content"].strip()
+ rejected = ex["rejected"][-1]["content"].strip()
+ if not prompt or not chosen or not rejected or chosen == rejected:
+ continue
+ out.append({"prompt": prompt, "chosen": chosen, "rejected": rejected})
+ return out
+
+
+def collect(source: str, max_n: int, split: str) -> list[dict]:
+ rows: list[dict] = []
+ if source in ("hh", "both"):
+ print(f"Loading Anthropic/hh-rlhf [{split}] ...")
+ rows += from_hh(max_n, split)
+ if source in ("ultrafeedback", "both"):
+ print(f"Loading ultrafeedback_binarized [{split}] ...")
+ try:
+ rows += from_ultrafeedback(max_n, split)
+ except Exception as e: # noqa: BLE001
+ print(f" (skipping ultrafeedback: {e})")
+ return rows
+
+
+def write_jsonl(rows: list[dict], path: str) -> None:
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
+ with open(path, "w") as f:
+ for r in rows:
+ f.write(json.dumps(r) + "\n")
+ print(f" wrote {len(rows)} pairs -> {path}")
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("--source", choices=["hh", "ultrafeedback", "both"], default="both")
+ p.add_argument("--max_per_source", type=int, default=40000)
+ p.add_argument("--out_dir", default="/ephemeral/data")
+ args = p.parse_args()
+
+ train = collect(args.source, args.max_per_source, "train")
+ test = collect(args.source, max(2000, args.max_per_source // 20), "test")
+ import random
+ random.Random(0).shuffle(train)
+ write_jsonl(train, os.path.join(args.out_dir, "preferences.jsonl"))
+ write_jsonl(test, os.path.join(args.out_dir, "preferences_test.jsonl"))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/prepare_pretrain_data.py b/scripts/prepare_pretrain_data.py
new file mode 100644
index 0000000..7b71ee3
--- /dev/null
+++ b/scripts/prepare_pretrain_data.py
@@ -0,0 +1,139 @@
+"""
+Download + tokenize Pile-uncopyrighted shards into a single flat-token HDF5 for
+pretraining. Faster than the original ``data_preprocess.py`` (which resizes the HDF5 per
+document): here we stream-decompress, batch-tokenize with tiktoken, and write tokens to
+the HDF5 in large chunks.
+
+Writes to /ephemeral by default (the 1.5TB disk).
+
+Examples:
+ # dev split from the Pile validation file
+ PYTHONPATH=. python scripts/prepare_pretrain_data.py --split val \
+ --out /ephemeral/data/pile_dev.h5
+ # one training shard
+ PYTHONPATH=. python scripts/prepare_pretrain_data.py --split train --num_shards 1 \
+ --out /ephemeral/data/pile_train.h5
+"""
+
+from __future__ import annotations
+
+import argparse
+import io
+import json
+import os
+
+import h5py
+import numpy as np
+import requests
+import tiktoken
+import zstandard as zstd
+from tqdm import tqdm
+
+BASE_URL = "https://huggingface.co/datasets/monology/pile-uncopyrighted/resolve/main"
+EOT_ID = 50256
+WRITE_CHUNK = 8_000_000 # flush tokens to HDF5 in ~8M-token chunks
+ENC_BATCH = 1024 # documents per tiktoken batch-encode
+
+
+def shard_urls(split: str, num_shards: int) -> list[str]:
+ if split == "val":
+ return [f"{BASE_URL}/val.jsonl.zst"]
+ return [f"{BASE_URL}/train/{i:02d}.jsonl.zst" for i in range(num_shards)]
+
+
+def download(url: str, dest: str) -> str:
+ if os.path.exists(dest):
+ print(f" cached: {dest}")
+ return dest
+ os.makedirs(os.path.dirname(dest), exist_ok=True)
+ print(f" downloading {url}")
+ with requests.get(url, stream=True) as r:
+ r.raise_for_status()
+ total = int(r.headers.get("content-length", 0))
+ with open(dest + ".part", "wb") as f:
+ for chunk in tqdm(r.iter_content(1 << 20), total=total >> 20, unit="MB", desc="dl"):
+ f.write(chunk)
+ os.replace(dest + ".part", dest)
+ return dest
+
+
+def iter_texts(zst_path: str):
+ dctx = zstd.ZstdDecompressor()
+ with open(zst_path, "rb") as fh:
+ reader = dctx.stream_reader(fh)
+ for line in io.TextIOWrapper(reader, encoding="utf-8"):
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ txt = json.loads(line).get("text")
+ except json.JSONDecodeError:
+ continue
+ if txt:
+ yield txt
+
+
+def tokenize_to_h5(zst_paths: list[str], out_path: str, max_tokens: int | None) -> int:
+ enc = tiktoken.get_encoding("r50k_base")
+ os.makedirs(os.path.dirname(out_path) or ".", exist_ok=True)
+ total = 0
+ buf: list[int] = []
+ with h5py.File(out_path, "w") as f:
+ dset = f.create_dataset("tokens", (0,), maxshape=(None,), dtype="i4", chunks=(WRITE_CHUNK,))
+
+ def flush():
+ nonlocal total, buf
+ if not buf:
+ return
+ arr = np.asarray(buf, dtype=np.int32)
+ dset.resize(total + arr.size, axis=0)
+ dset[total: total + arr.size] = arr
+ total += arr.size
+ buf = []
+
+ for zp in zst_paths:
+ print(f" tokenizing {zp}")
+ docs: list[str] = []
+ pbar = tqdm(iter_texts(zp), unit="doc", desc="tok")
+ for txt in pbar:
+ docs.append(txt)
+ if len(docs) >= ENC_BATCH:
+ for ids in enc.encode_ordinary_batch(docs):
+ buf.extend(ids)
+ buf.append(EOT_ID)
+ docs = []
+ if len(buf) >= WRITE_CHUNK:
+ flush()
+ pbar.set_postfix(tokens=f"{total/1e6:.1f}M")
+ if max_tokens and total >= max_tokens:
+ break
+ if docs:
+ for ids in enc.encode_ordinary_batch(docs):
+ buf.extend(ids)
+ buf.append(EOT_ID)
+ flush()
+ if max_tokens and total >= max_tokens:
+ break
+ print(f" wrote {total:,} tokens -> {out_path}")
+ return total
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("--split", choices=["train", "val"], required=True)
+ p.add_argument("--num_shards", type=int, default=1, help="train shards to use")
+ p.add_argument("--raw_dir", default="/ephemeral/data/pile_raw")
+ p.add_argument("--out", required=True)
+ p.add_argument("--max_tokens", type=int, default=None, help="stop after this many tokens")
+ args = p.parse_args()
+
+ urls = shard_urls(args.split, args.num_shards)
+ local = []
+ for u in urls:
+ name = "val.jsonl.zst" if args.split == "val" else os.path.basename(u)
+ local.append(download(u, os.path.join(args.raw_dir, name)))
+ tokenize_to_h5(local, args.out, args.max_tokens)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/prepare_rl_prompts.py b/scripts/prepare_rl_prompts.py
new file mode 100644
index 0000000..e716772
--- /dev/null
+++ b/scripts/prepare_rl_prompts.py
@@ -0,0 +1,76 @@
+"""
+Build RL prompt sets ({"prompt", "gold"}) for PPO/GRPO:
+ - GSM8K train -> rl_prompts_train.jsonl (the RL training prompts)
+ - GSM8K test -> rl_prompts_test.jsonl (held-out benchmark for eval)
+ - a programmatic arithmetic set -> arithmetic_prompts.jsonl (RL curriculum warm-up,
+ where even a weak model gets some non-zero reward so RL has signal to start from)
+
+Example:
+ PYTHONPATH=. HF_HOME=/ephemeral/hf_cache python scripts/prepare_rl_prompts.py --out_dir /ephemeral/data
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import random
+
+os.environ.setdefault("HF_HOME", "/ephemeral/hf_cache")
+
+from src.post_training.rewards import gsm8k_gold_answer
+
+
+def write_jsonl(rows, path):
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
+ with open(path, "w") as f:
+ for r in rows:
+ f.write(json.dumps(r) + "\n")
+ print(f" wrote {len(rows)} prompts -> {path}")
+
+
+def gsm8k_prompts(split: str, limit: int | None):
+ from datasets import load_dataset
+
+ ds = load_dataset("openai/gsm8k", "main", split=split)
+ if limit:
+ ds = ds.select(range(min(limit, len(ds))))
+ rows = []
+ for ex in ds:
+ gold = gsm8k_gold_answer(ex["answer"])
+ if gold is not None:
+ rows.append({"prompt": ex["question"].strip(), "gold": gold})
+ return rows
+
+
+def arithmetic_prompts(n: int, max_val: int, seed: int):
+ rng = random.Random(seed)
+ ops = [("+", lambda a, b: a + b), ("-", lambda a, b: a - b), ("*", lambda a, b: a * b)]
+ rows = []
+ for _ in range(n):
+ a, b = rng.randint(0, max_val), rng.randint(0, max_val)
+ sym, fn = rng.choice(ops)
+ rows.append({"prompt": f"What is {a} {sym} {b}?", "gold": float(fn(a, b))})
+ return rows
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("--out_dir", default="/ephemeral/data")
+ p.add_argument("--train_limit", type=int, default=None)
+ p.add_argument("--test_limit", type=int, default=500)
+ p.add_argument("--arith_n", type=int, default=5000)
+ p.add_argument("--arith_max", type=int, default=20)
+ args = p.parse_args()
+
+ print("Loading GSM8K train ...")
+ write_jsonl(gsm8k_prompts("train", args.train_limit), os.path.join(args.out_dir, "rl_prompts_train.jsonl"))
+ print("Loading GSM8K test ...")
+ write_jsonl(gsm8k_prompts("test", args.test_limit), os.path.join(args.out_dir, "rl_prompts_test.jsonl"))
+ print("Generating arithmetic curriculum ...")
+ write_jsonl(arithmetic_prompts(args.arith_n, args.arith_max, seed=0),
+ os.path.join(args.out_dir, "arithmetic_prompts.jsonl"))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/prepare_sft_data.py b/scripts/prepare_sft_data.py
new file mode 100644
index 0000000..d289602
--- /dev/null
+++ b/scripts/prepare_sft_data.py
@@ -0,0 +1,127 @@
+"""
+Build the SFT dataset from real public instruction data + GSM8K, render it through the
+chat template (masking prompt tokens), pack to fixed-length rows, and write a packed
+HDF5 (``tokens`` + ``loss_mask``) plus a held-out dev file.
+
+Datasets (downloaded via HuggingFace ``datasets`` to /ephemeral/hf_cache):
+ - tatsu-lab/alpaca (general instruction following)
+ - databricks/databricks-dolly-15k (general instruction following)
+ - openai/gsm8k (main, train) (math, reformatted into <think>/<answer> so the model
+ learns the reasoning format the RL verifier rewards)
+
+Example:
+ PYTHONPATH=. HF_HOME=/ephemeral/hf_cache python scripts/prepare_sft_data.py \
+ --context_length 1024 --out_dir /ephemeral/data
+"""
+
+from __future__ import annotations
+
+import argparse
+import os
+import re
+
+import h5py
+import numpy as np
+
+from src.post_training.chat_template import encode_chat, ANSWER_OPEN, ANSWER_CLOSE, THINK_OPEN, THINK_CLOSE
+from src.post_training.sft import pack_examples
+
+os.environ.setdefault("HF_HOME", "/ephemeral/hf_cache")
+_CALC_RE = re.compile(r"<<[^>]*>>") # GSM8K calculator annotations
+_HASH_RE = re.compile(r"####\s*(.+)\s*$")
+
+
+def gsm8k_to_messages(question: str, answer: str) -> list[dict]:
+ """Reformat a GSM8K (question, answer) into chat messages whose assistant turn uses
+ the <think>...</think><answer>N</answer> structure."""
+ answer = _CALC_RE.sub("", answer).strip()
+ m = _HASH_RE.search(answer)
+ final = m.group(1).strip() if m else answer
+ reasoning = _HASH_RE.sub("", answer).strip()
+ completion = f"{THINK_OPEN}{reasoning}{THINK_CLOSE}{ANSWER_OPEN}{final}{ANSWER_CLOSE}"
+ return [{"role": "user", "content": question.strip()},
+ {"role": "assistant", "content": completion}]
+
+
+def alpaca_to_messages(ex: dict) -> list[dict]:
+ instr = ex["instruction"].strip()
+ inp = (ex.get("input") or "").strip()
+ user = f"{instr}\n\n{inp}" if inp else instr
+ return [{"role": "user", "content": user}, {"role": "assistant", "content": ex["output"].strip()}]
+
+
+def dolly_to_messages(ex: dict) -> list[dict]:
+ instr = ex["instruction"].strip()
+ ctx = (ex.get("context") or "").strip()
+ user = f"{instr}\n\n{ctx}" if ctx else instr
+ return [{"role": "user", "content": user}, {"role": "assistant", "content": ex["response"].strip()}]
+
+
+def collect_examples(context_length: int, limit_per_set: int | None) -> list[tuple[list[int], list[int]]]:
+ from datasets import load_dataset
+
+ examples: list[tuple[list[int], list[int]]] = []
+ n_kept = n_skipped = 0
+
+ def add(messages):
+ nonlocal n_kept, n_skipped
+ ids, mask = encode_chat(messages)
+ if len(ids) <= context_length and sum(mask) > 0:
+ examples.append((ids, mask))
+ n_kept += 1
+ else:
+ n_skipped += 1
+
+ print("Loading tatsu-lab/alpaca ...")
+ alpaca = load_dataset("tatsu-lab/alpaca", split="train")
+ for ex in (alpaca.select(range(min(limit_per_set, len(alpaca)))) if limit_per_set else alpaca):
+ add(alpaca_to_messages(ex))
+
+ print("Loading databricks/databricks-dolly-15k ...")
+ try:
+ dolly = load_dataset("databricks/databricks-dolly-15k", split="train")
+ for ex in (dolly.select(range(min(limit_per_set, len(dolly)))) if limit_per_set else dolly):
+ add(dolly_to_messages(ex))
+ except Exception as e: # noqa: BLE001
+ print(f" (skipping dolly: {e})")
+
+ print("Loading openai/gsm8k (main/train) ...")
+ gsm = load_dataset("openai/gsm8k", "main", split="train")
+ for ex in (gsm.select(range(min(limit_per_set, len(gsm)))) if limit_per_set else gsm):
+ add(gsm8k_to_messages(ex["question"], ex["answer"]))
+
+ print(f"Collected {n_kept} examples (skipped {n_skipped} that exceeded context_length).")
+ return examples
+
+
+def write_packed(examples, context_length: int, out_path: str) -> int:
+ tokens, masks = pack_examples(examples, context_length)
+ os.makedirs(os.path.dirname(out_path) or ".", exist_ok=True)
+ with h5py.File(out_path, "w") as f:
+ f.create_dataset("tokens", data=tokens)
+ f.create_dataset("loss_mask", data=masks)
+ print(f" wrote {tokens.shape[0]} packed rows x {context_length} -> {out_path}")
+ return tokens.shape[0]
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("--context_length", type=int, default=1024)
+ p.add_argument("--out_dir", default="/ephemeral/data")
+ p.add_argument("--dev_frac", type=float, default=0.02)
+ p.add_argument("--limit_per_set", type=int, default=None, help="cap examples per dataset (debug)")
+ p.add_argument("--seed", type=int, default=42)
+ args = p.parse_args()
+
+ examples = collect_examples(args.context_length, args.limit_per_set)
+ rng = np.random.default_rng(args.seed)
+ rng.shuffle(examples)
+ n_dev = max(1, int(len(examples) * args.dev_frac))
+ dev, train = examples[:n_dev], examples[n_dev:]
+
+ write_packed(train, args.context_length, os.path.join(args.out_dir, "sft_packed.h5"))
+ write_packed(dev, args.context_length, os.path.join(args.out_dir, "sft_dev_packed.h5"))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/pretrain_base.py b/scripts/pretrain_base.py
new file mode 100644
index 0000000..d132694
--- /dev/null
+++ b/scripts/pretrain_base.py
@@ -0,0 +1,158 @@
+"""
+Pretrain the mid-size (~400M) base model from scratch on the Pile HDF5 corpus.
+
+This is the shared starting checkpoint for every post-training stage. It upgrades the
+original ``train_transformer.py`` recipe with the things needed to actually train a
+mid-size model on 2x H100: DistributedDataParallel, bf16 autocast, gradient accumulation,
+a cosine LR schedule with warmup, weight-decay param groups, and periodic checkpointing.
+The original ``train_transformer.py`` is left untouched.
+
+Single GPU:
+ PYTHONPATH=. python scripts/pretrain_base.py
+Both GPUs:
+ PYTHONPATH=. torchrun --standalone --nproc_per_node=2 scripts/pretrain_base.py
+
+Override any config field from the CLI, e.g. ``--batch_size 16 --train_steps 50000``.
+"""
+
+from __future__ import annotations
+
+import os
+import time
+
+import numpy as np
+import torch
+
+from config.post_training_config import PretrainConfig
+from data_loader.data_loader import get_batch_iterator
+from src.post_training.cli import parse_config_with_json
+from src.post_training.distributed import ddp_setup, ddp_wrap, cleanup, reduce_scalar
+from src.post_training.logging_utils import MetricsLogger
+from src.post_training.optim import configure_optimizer, cosine_lr
+from src.post_training.utils import (
+ amp_autocast, build_model_from_config, save_stage_ckpt, set_seed, unwrap,
+)
+
+
+def estimate_loss(model, cfg, ctx, iters: int) -> dict[str, float]:
+ model.eval()
+ out = {}
+ for split, path in [("train", cfg.train_path), ("dev", cfg.dev_path)]:
+ if not os.path.exists(path):
+ continue
+ it = get_batch_iterator(path, cfg.batch_size, cfg.context_length, device=ctx.device)
+ losses = torch.zeros(iters)
+ for k in range(iters):
+ xb, yb = next(it)
+ with amp_autocast(cfg.amp_dtype, ctx.device):
+ _, loss = model(xb, yb)
+ losses[k] = loss.item()
+ out[split] = losses.mean().item()
+ model.train()
+ return out
+
+
+def main():
+ cfg, extras = parse_config_with_json(
+ PretrainConfig, "configs/pretrain.json",
+ extra={"--resume": dict(type=str, default=None, help="checkpoint to resume from")})
+ resume = extras.resume
+ ctx = ddp_setup(cfg.device)
+ # Different data shuffle per rank (the loader shuffles via numpy global RNG).
+ set_seed(cfg.seed + ctx.rank)
+
+ model = build_model_from_config(cfg).to(ctx.device)
+ start_step = 0
+ if resume and os.path.exists(resume):
+ ck = torch.load(resume, map_location="cpu", weights_only=False)
+ unwrap(model).load_state_dict(ck["model_state_dict"])
+ start_step = ck.get("step", 0)
+ if ctx.is_main:
+ print(f"Resumed from {resume} at step {start_step}")
+
+ if cfg.compile:
+ model = torch.compile(model)
+ model = ddp_wrap(model, ctx)
+
+ optimizer = configure_optimizer(unwrap(model), cfg.lr, cfg.weight_decay)
+ if resume and os.path.exists(resume):
+ ck = torch.load(resume, map_location="cpu", weights_only=False)
+ if ck.get("optimizer_state_dict"):
+ optimizer.load_state_dict(ck["optimizer_state_dict"])
+
+ logger = None
+ if ctx.is_main:
+ n_params = sum(p.numel() for p in unwrap(model).parameters())
+ print(f"Model parameters: {n_params:,} (~{n_params/1e6:.0f}M) | world_size={ctx.world_size}")
+ print(f"Effective batch = {cfg.batch_size}*{cfg.grad_accum}*{ctx.world_size} "
+ f"= {cfg.batch_size*cfg.grad_accum*ctx.world_size} seqs/step")
+ logger = MetricsLogger("pretrain", cfg.log_dir, use_wandb=cfg.use_wandb,
+ wandb_project=cfg.wandb_project, config=vars(cfg).copy() if hasattr(cfg, "__dict__") else None)
+
+ batch_iter = get_batch_iterator(cfg.train_path, cfg.batch_size, cfg.context_length, device=ctx.device)
+ tokens_per_step = cfg.batch_size * cfg.context_length * cfg.grad_accum * ctx.world_size
+
+ model.train()
+ t0 = time.perf_counter()
+ for step in range(start_step, cfg.train_steps):
+ lr = cosine_lr(step, warmup_steps=cfg.warmup_steps, max_steps=cfg.train_steps,
+ lr=cfg.lr, min_lr=cfg.min_lr)
+ for g in optimizer.param_groups:
+ g["lr"] = lr
+
+ optimizer.zero_grad(set_to_none=True)
+ accum_loss = 0.0
+ for micro in range(cfg.grad_accum):
+ xb, yb = next(batch_iter)
+ # Only sync grads on the last micro-step (DDP optimization).
+ sync = (micro == cfg.grad_accum - 1) or not ctx.enabled
+ cm = model.no_sync() if (ctx.enabled and not sync) else _nullcm()
+ with cm, amp_autocast(cfg.amp_dtype, ctx.device):
+ _, loss = model(xb, yb)
+ loss = loss / cfg.grad_accum
+ loss.backward()
+ accum_loss += loss.item()
+
+ torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.grad_clip)
+ optimizer.step()
+
+ if ctx.is_main and step % 20 == 0:
+ dt = time.perf_counter() - t0
+ tok_s = tokens_per_step * 20 / dt if step > start_step else 0.0
+ t0 = time.perf_counter()
+ print(f"step {step} | loss {accum_loss:.4f} | lr {lr:.2e} | {tok_s:,.0f} tok/s")
+ if logger:
+ logger.log(step, {"train_loss": accum_loss, "lr": lr, "tok_per_s": tok_s})
+
+ if step > start_step and step % cfg.eval_steps == 0:
+ ev = estimate_loss(model, cfg, ctx, cfg.eval_iters)
+ ev = {k: reduce_scalar(v, ctx) for k, v in ev.items()}
+ if ctx.is_main:
+ print(f" [eval] step {step} | " + " | ".join(f"{k} {v:.4f}" for k, v in ev.items()))
+ if logger:
+ logger.log(step, {f"eval_{k}": v for k, v in ev.items()})
+
+ if ctx.is_main and step > start_step and step % cfg.save_every == 0:
+ save_stage_ckpt(cfg.out_ckpt, model, optimizer, stage="pretrain",
+ cfg=cfg, step=step, metrics={"train_loss": accum_loss})
+ print(f" saved checkpoint -> {cfg.out_ckpt} (step {step})")
+
+ if ctx.is_main:
+ save_stage_ckpt(cfg.out_ckpt, model, optimizer, stage="pretrain", cfg=cfg,
+ step=cfg.train_steps, metrics={"train_loss": accum_loss})
+ print(f"Done. Final checkpoint -> {cfg.out_ckpt}")
+ if logger:
+ logger.close()
+ cleanup(ctx)
+
+
+import contextlib
+
+
+def _nullcm():
+ return contextlib.nullcontext()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/render_diagrams.sh b/scripts/render_diagrams.sh
new file mode 100755
index 0000000..deee540
--- /dev/null
+++ b/scripts/render_diagrams.sh
@@ -0,0 +1,29 @@
+#!/usr/bin/env bash
+# Render the hand-drawn, colour-coded diagram sources (docs/diagrams/src/*.mmd) to SVGs
+# (docs/diagrams/*.svg) that are embedded as images in the docs. We pre-render because
+# GitHub's live Mermaid does not reliably support `look: handDrawn`; embedding the SVG makes
+# the hand-drawn look show everywhere.
+#
+# One-time setup:
+# sudo apt-get install -y nodejs # Node >= 18
+# sudo npm install -g @mermaid-js/mermaid-cli # provides `mmdc`
+# # a Chrome/Chromium for headless rendering (e.g. google-chrome-stable)
+#
+# Usage (from repo root):
+# bash scripts/render_diagrams.sh
+set -euo pipefail
+cd "$(dirname "$0")/.."
+
+SRC=docs/diagrams/src
+OUT=docs/diagrams
+CHROME="${CHROME:-/usr/bin/google-chrome-stable}"
+PP=$(mktemp)
+echo "{\"executablePath\":\"$CHROME\",\"args\":[\"--no-sandbox\",\"--disable-gpu\",\"--disable-dev-shm-usage\"]}" > "$PP"
+
+for m in "$SRC"/*.mmd; do
+ base=$(basename "$m" .mmd)
+ mmdc -p "$PP" -i "$m" -o "$OUT/$base.png" -b white -s 2 # PNG @2x: renders in every viewer (GitHub, VS Code preview)
+ echo "rendered $OUT/$base.png"
+done
+rm -f "$PP"
+echo "Done. Edit a .mmd in $SRC, re-run this script, and the embedded image updates."
diff --git a/scripts/run_posttraining.sh b/scripts/run_posttraining.sh
new file mode 100755
index 0000000..dc32ea9
--- /dev/null
+++ b/scripts/run_posttraining.sh
@@ -0,0 +1,49 @@
+#!/usr/bin/env bash
+# Turnkey post-training pipeline: SFT -> Reward Model -> {DPO, PPO} -> GRPO -> eval table.
+# Assumes the base model is already pretrained (scripts/pretrain_base.py ->
+# /ephemeral/ckpts/base_pretrained.pt) and the datasets are prepared (scripts/prepare_*).
+#
+# Usage (from repo root):
+# bash scripts/run_posttraining.sh # use both GPUs (torchrun)
+# NPROC=1 bash scripts/run_posttraining.sh # single GPU
+#
+# Each stage writes a checkpoint to /ephemeral/ckpts and metrics JSONL to /ephemeral/logs.
+set -euo pipefail
+
+cd "$(dirname "$0")/.."
+export PYTHONPATH=. HF_HOME=/ephemeral/hf_cache PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+PY=/ephemeral/venv/bin/python
+NPROC=${NPROC:-2}
+
+run() { # run a training script single- or multi-GPU
+ if [ "$NPROC" -gt 1 ]; then
+ /ephemeral/venv/bin/torchrun --standalone --nproc_per_node="$NPROC" "$@"
+ else
+ $PY "$@"
+ fi
+}
+
+echo "############ 1/5 SFT ############"
+run scripts/train_sft.py
+
+echo "############ 2/5 Reward Model ############"
+run scripts/train_reward.py
+
+echo "############ 3/5 DPO ############"
+run scripts/train_dpo.py --loss_type dpo
+
+echo "############ 4/5 PPO (GSM8K, verifier reward) ############"
+run scripts/train_ppo.py --reward_source verifier
+
+echo "############ 5/5 GRPO (arithmetic curriculum -> GSM8K) ############"
+run scripts/train_grpo.py
+
+echo "############ Eval: GSM8K accuracy across stages ############"
+TABLE=/ephemeral/logs/stage_table.jsonl
+rm -f "$TABLE"
+for s in base_pretrained sft dpo ppo grpo; do
+ [ -f "/ephemeral/ckpts/$s.pt" ] && \
+ $PY scripts/eval_post_training.py --ckpt "/ephemeral/ckpts/$s.pt" --label "$s" --limit 200 --append "$TABLE"
+done
+$PY scripts/eval_post_training.py --table "$TABLE"
+echo "Done. Metrics in /ephemeral/logs, checkpoints in /ephemeral/ckpts."
diff --git a/scripts/train_dpo.py b/scripts/train_dpo.py
new file mode 100644
index 0000000..c53c0ed
--- /dev/null
+++ b/scripts/train_dpo.py
@@ -0,0 +1,142 @@
+"""
+Direct Preference Optimization (and ORPO / KTO variants) on preference pairs.
+
+The policy is initialized from the SFT checkpoint; a frozen deep copy of it serves as the
+DPO/KTO reference (ORPO is reference-free). Reports implicit-reward accuracy on held-out
+preferences and GSM8K dev accuracy.
+
+ PYTHONPATH=. python scripts/train_dpo.py --loss_type dpo --beta 0.1
+ PYTHONPATH=. torchrun --standalone --nproc_per_node=2 scripts/train_dpo.py
+"""
+
+from __future__ import annotations
+
+import time
+
+import torch
+
+from config.post_training_config import DPOConfig
+from data_loader.preference_dataset import get_preference_iterator
+from src.post_training.cli import parse_config_with_json
+from src.post_training.distributed import ddp_setup, ddp_wrap, cleanup, reduce_scalar
+from src.post_training.dpo import dpo_loss, orpo_loss, kto_loss, implicit_accuracy
+from src.post_training.logging_utils import MetricsLogger
+from src.post_training.optim import configure_optimizer, cosine_lr
+from src.post_training.rollout import sequence_logprobs
+from src.post_training.utils import (
+ amp_autocast, load_backbone_from_ckpt, make_frozen_copy, save_stage_ckpt, set_seed, unwrap,
+)
+
+TEST_PATH = "/ephemeral/data/preferences_test.jsonl"
+
+
+def _logps(model, ids, mask, requires_grad):
+ return sequence_logprobs(model, ids, mask, requires_grad=requires_grad)
+
+
+def _compute_losses(policy, ref, batch, cfg, ctx):
+ B = batch["chosen_ids"].size(0)
+ ids = torch.cat([batch["chosen_ids"], batch["rejected_ids"]], dim=0)
+ mask = torch.cat([batch["chosen_mask"], batch["rejected_mask"]], dim=0)
+
+ with amp_autocast(cfg.amp_dtype, ctx.device):
+ psum, pn = _logps(policy, ids, mask, requires_grad=True)
+ pc, pr, ncn, nrn = psum[:B], psum[B:], pn[:B], pn[B:]
+
+ if cfg.loss_type == "orpo":
+ return orpo_loss(pc, pr, ncn, nrn, orpo_lambda=cfg.orpo_lambda)
+
+ with torch.no_grad(), amp_autocast(cfg.amp_dtype, ctx.device):
+ rsum, _ = _logps(ref, ids, mask, requires_grad=False)
+ rc, rr = rsum[:B], rsum[B:]
+ if cfg.loss_type == "kto":
+ return kto_loss(pc, pr, rc, rr, beta=cfg.beta)
+ return dpo_loss(pc, pr, rc, rr, beta=cfg.beta)
+
+
+def eval_implicit_acc(policy, ref, cfg, ctx, max_batches: int = 100) -> tuple[float, float]:
+ policy.eval()
+ it = get_preference_iterator(TEST_PATH, cfg.batch_size, cfg.max_len, device=ctx.device,
+ rank=ctx.rank, world_size=ctx.world_size, shuffle=False, infinite=False)
+ acc, marg, n = 0.0, 0.0, 0
+ for batch in it:
+ loss, cr, rr = _compute_losses(policy, ref, batch, cfg, ctx)
+ acc += implicit_accuracy(cr, rr).item()
+ marg += (cr - rr).mean().item()
+ n += 1
+ if n >= max_batches:
+ break
+ policy.train()
+ return acc / max(1, n), marg / max(1, n)
+
+
+def main():
+ cfg, _ = parse_config_with_json(DPOConfig, "configs/dpo.json")
+ ctx = ddp_setup(cfg.device)
+ set_seed(cfg.seed + ctx.rank)
+
+ policy = load_backbone_from_ckpt(cfg, cfg.sft_ckpt, ctx.device)
+ ref = make_frozen_copy(policy, device=ctx.device) if cfg.loss_type != "orpo" else None
+ policy = ddp_wrap(policy, ctx)
+ optimizer = configure_optimizer(unwrap(policy), cfg.lr, cfg.weight_decay)
+
+ with open(cfg.pref_path) as f:
+ n_rows = sum(1 for line in f if line.strip())
+ total_steps = max(1, (n_rows // (cfg.batch_size * ctx.world_size)) * cfg.epochs)
+
+ logger = None
+ if ctx.is_main:
+ print(f"DPO[{cfg.loss_type}] from {cfg.sft_ckpt} | {n_rows} pairs | total_steps={total_steps} | beta={cfg.beta}")
+ logger = MetricsLogger(f"dpo_{cfg.loss_type}", cfg.log_dir, use_wandb=cfg.use_wandb, wandb_project=cfg.wandb_project)
+
+ train_it = get_preference_iterator(cfg.pref_path, cfg.batch_size, cfg.max_len, device=ctx.device,
+ rank=ctx.rank, world_size=ctx.world_size, shuffle=True, infinite=True)
+
+ policy.train()
+ t0 = time.perf_counter()
+ for step in range(total_steps):
+ lr = cosine_lr(step, warmup_steps=cfg.warmup_steps, max_steps=total_steps, lr=cfg.lr, min_lr=cfg.lr * 0.1)
+ for g in optimizer.param_groups:
+ g["lr"] = lr
+
+ batch = next(train_it)
+ loss, cr, rr = _compute_losses(policy, ref, batch, cfg, ctx)
+ optimizer.zero_grad(set_to_none=True)
+ loss.backward()
+ torch.nn.utils.clip_grad_norm_(policy.parameters(), cfg.grad_clip)
+ optimizer.step()
+
+ if ctx.is_main and step % 20 == 0:
+ acc = implicit_accuracy(cr, rr).item()
+ dt = time.perf_counter() - t0; t0 = time.perf_counter()
+ print(f"step {step}/{total_steps} | loss {loss.item():.4f} | acc {acc:.3f} | "
+ f"r_chosen {cr.mean().item():.3f} r_rejected {rr.mean().item():.3f} | {dt:.1f}s/20")
+ if logger:
+ logger.log(step, {"train_loss": loss.item(), "train_acc": acc,
+ "r_chosen": cr.mean().item(), "r_rejected": rr.mean().item(), "lr": lr})
+
+ if step > 0 and step % cfg.eval_steps == 0:
+ acc, marg = eval_implicit_acc(policy, ref, cfg, ctx)
+ acc, marg = reduce_scalar(acc, ctx), reduce_scalar(marg, ctx)
+ if ctx.is_main:
+ print(f" [eval] step {step} | test_acc {acc:.3f} | margin {marg:.3f}")
+ if logger:
+ logger.log(step, {"test_acc": acc, "test_margin": marg})
+
+ if ctx.is_main and step > 0 and step % cfg.save_every == 0:
+ save_stage_ckpt(cfg.out_ckpt, policy, optimizer, stage=f"dpo_{cfg.loss_type}", cfg=cfg, step=step,
+ metrics={"train_loss": loss.item()})
+
+ if ctx.is_main:
+ acc, marg = eval_implicit_acc(policy, ref, cfg, ctx)
+ save_stage_ckpt(cfg.out_ckpt, policy, optimizer, stage=f"dpo_{cfg.loss_type}", cfg=cfg, step=total_steps,
+ metrics={"test_acc": acc, "test_margin": marg})
+ print(f"Done DPO[{cfg.loss_type}]. test_acc {acc:.3f} margin {marg:.3f} -> {cfg.out_ckpt}")
+ if logger:
+ logger.close()
+ cleanup(ctx)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/train_grpo.py b/scripts/train_grpo.py
new file mode 100644
index 0000000..3b7e798
--- /dev/null
+++ b/scripts/train_grpo.py
@@ -0,0 +1,139 @@
+"""
+GRPO / RLVR on GSM8K (DeepSeek-R1 style), from scratch -- no critic, group-relative
+advantages, verifiable reward.
+
+Per iteration: for each prompt sample a group of G completions, score each with the GSM8K
+verifier, compute group-relative advantages, and update with a token-level clipped
+surrogate + KL-to-reference penalty. An arithmetic warm-up curriculum runs first so the
+policy gets non-zero reward variance before facing full GSM8K.
+
+ PYTHONPATH=. python scripts/train_grpo.py
+ PYTHONPATH=. torchrun --standalone --nproc_per_node=2 scripts/train_grpo.py
+"""
+
+from __future__ import annotations
+
+import time
+
+import torch
+
+from config.post_training_config import GRPOConfig
+from data_loader.prompt_dataset import get_prompt_iterator
+from src.post_training.cli import parse_config_with_json
+from src.post_training.chat_template import decode, encode_prompt
+from src.post_training.distributed import ddp_setup, ddp_wrap, cleanup, reduce_scalar
+from src.post_training.evaluation import gsm8k_accuracy, load_gsm8k_eval
+from src.post_training.grpo import group_advantages, grpo_loss
+from src.post_training.logging_utils import MetricsLogger
+from src.post_training.optim import configure_optimizer
+from src.post_training.rewards import reward_gsm8k
+from src.post_training.rollout import compute_logprobs, rollout_prompts
+from src.post_training.utils import (
+ amp_autocast, load_backbone_from_ckpt, make_frozen_copy, save_stage_ckpt, set_seed, unwrap,
+)
+
+
+def seq_lengths_from_mask(response_mask, prompt_lens):
+ N, T = response_mask.shape
+ pos = torch.arange(T, device=response_mask.device)
+ last = torch.where(response_mask, pos[None, :], torch.full_like(response_mask, -1, dtype=torch.long)).max(dim=1).values
+ return torch.where(last >= 0, last + 1, prompt_lens)
+
+
+def main():
+ cfg, _ = parse_config_with_json(GRPOConfig, "configs/grpo.json")
+ ctx = ddp_setup(cfg.device)
+ set_seed(cfg.seed + ctx.rank)
+
+ policy = load_backbone_from_ckpt(cfg, cfg.sft_ckpt, ctx.device)
+ ref = make_frozen_copy(policy, device=ctx.device)
+ policy_ddp = ddp_wrap(policy, ctx)
+ optimizer = configure_optimizer(unwrap(policy_ddp), cfg.lr, weight_decay=0.0)
+
+ eval_set = None
+ logger = MetricsLogger("grpo", cfg.log_dir, use_wandb=cfg.use_wandb, wandb_project=cfg.wandb_project) if ctx.is_main else None
+ if ctx.is_main:
+ print(f"GRPO from {cfg.sft_ckpt} | group_size={cfg.group_size} | world={ctx.world_size}")
+
+ warm_it = get_prompt_iterator(cfg.curriculum_path, cfg.prompts_per_iter, rank=ctx.rank,
+ world_size=ctx.world_size, seed=cfg.seed)
+ main_it = get_prompt_iterator(cfg.prompt_path, cfg.prompts_per_iter, rank=ctx.rank,
+ world_size=ctx.world_size, seed=cfg.seed)
+
+ G = cfg.group_size
+ for it in range(cfg.iterations):
+ rows = next(warm_it if it < cfg.curriculum_iters else main_it)
+ # Replicate each prompt G times, group-contiguously.
+ base_prompts = [encode_prompt([{"role": "user", "content": r["prompt"]}]) for r in rows]
+ prompts = [p for p in base_prompts for _ in range(G)]
+ golds = [r.get("gold") for r in rows for _ in range(G)]
+
+ policy.eval()
+ with amp_autocast(cfg.amp_dtype, ctx.device):
+ seqs, rmask, plens = rollout_prompts(policy, prompts, cfg.rollout_len, device=ctx.device,
+ temperature=cfg.temperature, top_p=cfg.top_p if cfg.top_p < 1 else None)
+ resp = rmask[:, 1:]
+
+ seq_lens = seq_lengths_from_mask(rmask, plens)
+ responses = [decode(seqs[i, plens[i]:seq_lens[i]].tolist()) for i in range(len(prompts))]
+ rewards = torch.tensor([reward_gsm8k(responses[i], golds[i]) for i in range(len(prompts))],
+ device=ctx.device, dtype=torch.float32)
+ adv = group_advantages(rewards, G)
+
+ with torch.no_grad(), amp_autocast(cfg.amp_dtype, ctx.device):
+ old_logp, _ = compute_logprobs(policy, seqs, rmask, temperature=cfg.temperature, requires_grad=False)
+ ref_logp, _ = compute_logprobs(ref, seqs, rmask, temperature=cfg.temperature, requires_grad=False)
+ old_logp, ref_logp = old_logp.float(), ref_logp.float()
+
+ policy.train()
+ N = seqs.size(0)
+ agg = {"loss": 0.0, "kl": 0.0, "clipfrac": 0.0, "n": 0}
+ for _ in range(cfg.grpo_epochs):
+ perm = torch.randperm(N, device=ctx.device)
+ for s in range(0, N, max(1, G)): # minibatch ~ one group's worth
+ mb = perm[s:s + max(1, G)]
+ with amp_autocast(cfg.amp_dtype, ctx.device):
+ new_logp, _ = compute_logprobs(policy_ddp, seqs[mb], rmask[mb], temperature=cfg.temperature, requires_grad=True)
+ loss, st = grpo_loss(new_logp.float(), old_logp[mb], ref_logp[mb], adv[mb], resp[mb],
+ clip=cfg.clip, kl_coef=cfg.kl_coef)
+ optimizer.zero_grad(set_to_none=True)
+ loss.backward()
+ torch.nn.utils.clip_grad_norm_(policy_ddp.parameters(), cfg.grad_clip)
+ optimizer.step()
+ agg["loss"] += loss.item(); agg["kl"] += st["kl"]; agg["clipfrac"] += st["clipfrac"]; agg["n"] += 1
+
+ mean_reward = reduce_scalar(rewards.mean().item(), ctx)
+ # Fraction of groups with non-zero reward spread (informative groups).
+ grp_std = rewards.view(-1, G).std(dim=1)
+ informative = reduce_scalar((grp_std > 1e-6).float().mean().item(), ctx)
+ resp_len = reduce_scalar(resp.float().sum(1).mean().item(), ctx)
+ n = max(1, agg["n"])
+ if ctx.is_main and it % 5 == 0:
+ phase = "warmup" if it < cfg.curriculum_iters else "gsm8k"
+ print(f"iter {it}[{phase}] | reward {mean_reward:.3f} | informative {informative:.2f} | "
+ f"loss {agg['loss']/n:.4f} | KL {agg['kl']/n:.4f} | clipfrac {agg['clipfrac']/n:.3f} | resp_len {resp_len:.0f}")
+ if logger:
+ logger.log(it, {"reward": mean_reward, "informative_groups": informative,
+ "loss": agg["loss"]/n, "kl": agg["kl"]/n, "resp_len": resp_len})
+
+ if ctx.is_main and it > 0 and it % cfg.eval_every == 0:
+ if eval_set is None:
+ eval_set = load_gsm8k_eval("test", limit=200)
+ res = gsm8k_accuracy(unwrap(policy_ddp), eval_set, device=ctx.device, max_new_tokens=cfg.rollout_len)
+ print(f" [eval] iter {it} | GSM8K test acc {res['accuracy']:.3f} ({res['correct']}/{res['n']})")
+ if logger:
+ logger.log(it, {"gsm8k_acc": res["accuracy"]})
+ if ctx.is_main and it > 0 and it % cfg.save_every == 0:
+ save_stage_ckpt(cfg.out_ckpt, unwrap(policy_ddp), optimizer, stage="grpo", cfg=cfg, step=it,
+ metrics={"reward": mean_reward})
+
+ if ctx.is_main:
+ save_stage_ckpt(cfg.out_ckpt, unwrap(policy_ddp), optimizer, stage="grpo", cfg=cfg, step=cfg.iterations, metrics={})
+ print(f"Done GRPO -> {cfg.out_ckpt}")
+ if logger:
+ logger.close()
+ cleanup(ctx)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/train_ppo.py b/scripts/train_ppo.py
new file mode 100644
index 0000000..c415c4e
--- /dev/null
+++ b/scripts/train_ppo.py
@@ -0,0 +1,167 @@
+"""
+PPO RLHF on GSM8K (the classic InstructGPT recipe), from scratch.
+
+Per iteration: roll out completions with the current policy, score them (verifiable GSM8K
+reward, or a trained reward model), add a per-token KL-to-reference penalty, compute GAE
+advantages with the shared value head, then run several clipped-surrogate update epochs.
+Reports mean reward, KL, value loss, clip fraction, and held-out GSM8K accuracy.
+
+ PYTHONPATH=. python scripts/train_ppo.py --reward_source verifier
+ PYTHONPATH=. torchrun --standalone --nproc_per_node=2 scripts/train_ppo.py
+"""
+
+from __future__ import annotations
+
+import time
+
+import torch
+import torch.nn.functional as F
+
+from config.post_training_config import PPOConfig
+from data_loader.prompt_dataset import get_prompt_iterator
+from src.post_training.cli import parse_config_with_json
+from src.post_training.chat_template import EOT_ID, decode, encode_prompt
+from src.post_training.distributed import ddp_setup, ddp_wrap, cleanup, reduce_scalar
+from src.post_training.evaluation import gsm8k_accuracy, load_gsm8k_eval
+from src.post_training.logging_utils import MetricsLogger
+from src.post_training.optim import configure_optimizer
+from src.post_training.ppo import compute_gae, whiten, ppo_policy_loss, ppo_value_loss, approx_kl
+from src.post_training.reward_model import load_reward_model
+from src.post_training.rewards import reward_gsm8k
+from src.post_training.rollout import compute_logprobs, rollout_prompts
+from src.post_training.utils import (
+ amp_autocast, load_backbone_from_ckpt, make_frozen_copy, masked_mean, save_stage_ckpt, set_seed, unwrap,
+)
+from src.post_training.value_head import TransformerWithValueHead
+
+
+def actor_logp_values(actor, seqs, temperature):
+ """One forward through the actor-critic -> (logp, values) in the action frame (B,T-1)."""
+ logits, values = actor(seqs)
+ logits = logits[:, :-1, :]
+ logp_all = F.log_softmax(logits.float() / max(temperature, 1e-6), dim=-1)
+ logp = logp_all.gather(-1, seqs[:, 1:, None]).squeeze(-1)
+ return logp, values[:, :-1]
+
+
+def seq_lengths_from_mask(response_mask, prompt_lens):
+ """Real token count per row = last response position + 1 (or prompt_len if no response)."""
+ N, T = response_mask.shape
+ pos = torch.arange(T, device=response_mask.device)
+ last = torch.where(response_mask, pos[None, :], torch.full_like(response_mask, -1, dtype=torch.long)).max(dim=1).values
+ return torch.where(last >= 0, last + 1, prompt_lens)
+
+
+def main():
+ cfg, _ = parse_config_with_json(PPOConfig, "configs/ppo.json")
+ ctx = ddp_setup(cfg.device)
+ set_seed(cfg.seed + ctx.rank)
+
+ backbone = load_backbone_from_ckpt(cfg, cfg.sft_ckpt, ctx.device)
+ ref = make_frozen_copy(backbone, device=ctx.device)
+ actor = TransformerWithValueHead(backbone).to(ctx.device)
+ actor_ddp = ddp_wrap(actor, ctx)
+ optimizer = configure_optimizer(unwrap(actor_ddp), cfg.lr, weight_decay=0.0)
+
+ rm = load_reward_model(cfg, cfg.reward_ckpt, ctx.device) if cfg.reward_source == "rm" else None
+
+ eval_set = None # loaded lazily on first eval to keep startup/smoke runs offline
+ logger = MetricsLogger("ppo", cfg.log_dir, use_wandb=cfg.use_wandb, wandb_project=cfg.wandb_project) if ctx.is_main else None
+ if ctx.is_main:
+ print(f"PPO from {cfg.sft_ckpt} | reward={cfg.reward_source} | world={ctx.world_size}")
+
+ prompt_it = get_prompt_iterator(cfg.prompt_path, cfg.prompts_per_iter, rank=ctx.rank,
+ world_size=ctx.world_size, seed=cfg.seed)
+
+ for it in range(cfg.iterations):
+ rows = next(prompt_it)
+ prompts = [encode_prompt([{"role": "user", "content": r["prompt"]}]) for r in rows]
+ golds = [r.get("gold") for r in rows]
+
+ # --- rollout ---
+ actor.eval()
+ with amp_autocast(cfg.amp_dtype, ctx.device):
+ seqs, rmask, plens = rollout_prompts(actor, prompts, cfg.rollout_len, device=ctx.device,
+ temperature=cfg.temperature, top_p=cfg.top_p if cfg.top_p < 1 else None)
+ resp = rmask[:, 1:] # action-frame response mask (N, T-1)
+
+ # --- score ---
+ seq_lens = seq_lengths_from_mask(rmask, plens)
+ responses = [decode(seqs[i, plens[i]:seq_lens[i]].tolist()) for i in range(len(rows))]
+ if cfg.reward_source == "rm":
+ with torch.no_grad(), amp_autocast(cfg.amp_dtype, ctx.device):
+ task_r = rm(seqs, seq_lengths=seq_lens).float().tolist()
+ else:
+ task_r = [reward_gsm8k(responses[i], golds[i]) for i in range(len(rows))]
+
+ # --- per-token rewards: KL penalty everywhere + task reward at last response token ---
+ with torch.no_grad(), amp_autocast(cfg.amp_dtype, ctx.device):
+ old_logp, old_values = actor_logp_values(actor, seqs, cfg.temperature)
+ ref_logp, _ = compute_logprobs(ref, seqs, rmask, temperature=cfg.temperature, requires_grad=False)
+ old_logp, old_values, ref_logp = old_logp.float(), old_values.float(), ref_logp.float()
+
+ rewards = -cfg.kl_coef * (old_logp - ref_logp) * resp.float()
+ last_idx = seq_lens - 2 # action index of the last response token
+ last_idx = last_idx.clamp(min=0)
+ task_t = torch.tensor(task_r, device=ctx.device, dtype=torch.float32)
+ rewards[torch.arange(len(rows), device=ctx.device), last_idx] += task_t
+
+ values_next = torch.cat([old_values[:, 1:], torch.zeros_like(old_values[:, :1])], dim=1)
+ adv, returns = compute_gae(rewards, old_values, values_next, resp, gamma=cfg.gamma, lam=cfg.gae_lambda)
+ adv = whiten(adv, resp)
+
+ # --- clipped PPO update epochs over minibatches of rollout rows ---
+ actor.train()
+ N = seqs.size(0)
+ stats = {"policy_loss": 0.0, "value_loss": 0.0, "clipfrac": 0.0, "kl": 0.0, "n": 0}
+ for _ in range(cfg.ppo_epochs):
+ perm = torch.randperm(N, device=ctx.device)
+ for s in range(0, N, cfg.minibatch_size):
+ mb = perm[s:s + cfg.minibatch_size]
+ with amp_autocast(cfg.amp_dtype, ctx.device):
+ new_logp, new_values = actor_logp_values(actor_ddp, seqs[mb], cfg.temperature)
+ m = resp[mb]
+ p_loss, clipf = ppo_policy_loss(new_logp.float(), old_logp[mb], adv[mb], m, clip=cfg.clip)
+ v_loss = ppo_value_loss(new_values.float(), old_values[mb], returns[mb], m, vf_clip=cfg.vf_clip)
+ loss = p_loss + cfg.vf_coef * v_loss
+ optimizer.zero_grad(set_to_none=True)
+ loss.backward()
+ torch.nn.utils.clip_grad_norm_(actor_ddp.parameters(), cfg.grad_clip)
+ optimizer.step()
+ stats["policy_loss"] += p_loss.item(); stats["value_loss"] += v_loss.item()
+ stats["clipfrac"] += clipf.item()
+ stats["kl"] += approx_kl(new_logp.float(), old_logp[mb], m).item(); stats["n"] += 1
+
+ mean_reward = reduce_scalar(float(sum(task_r) / max(1, len(task_r))), ctx)
+ kl_ref = reduce_scalar(masked_mean(old_logp - ref_logp, resp).item(), ctx)
+ resp_len = reduce_scalar(resp.float().sum(1).mean().item(), ctx)
+ n = max(1, stats["n"])
+ if ctx.is_main and it % 5 == 0:
+ print(f"iter {it} | reward {mean_reward:.3f} | KL_ref {kl_ref:.3f} | "
+ f"ploss {stats['policy_loss']/n:.4f} | vloss {stats['value_loss']/n:.4f} | "
+ f"clipfrac {stats['clipfrac']/n:.3f} | resp_len {resp_len:.0f}")
+ if logger:
+ logger.log(it, {"reward": mean_reward, "kl_ref": kl_ref, "policy_loss": stats["policy_loss"]/n,
+ "value_loss": stats["value_loss"]/n, "clipfrac": stats["clipfrac"]/n, "resp_len": resp_len})
+
+ if ctx.is_main and it > 0 and it % cfg.eval_every == 0:
+ if eval_set is None:
+ eval_set = load_gsm8k_eval("test", limit=200)
+ res = gsm8k_accuracy(unwrap(actor_ddp), eval_set, device=ctx.device, max_new_tokens=cfg.rollout_len)
+ print(f" [eval] iter {it} | GSM8K test acc {res['accuracy']:.3f} ({res['correct']}/{res['n']})")
+ if logger:
+ logger.log(it, {"gsm8k_acc": res["accuracy"]})
+ if ctx.is_main and it > 0 and it % cfg.save_every == 0:
+ save_stage_ckpt(cfg.out_ckpt, unwrap(actor_ddp).transformer, optimizer, stage="ppo", cfg=cfg, step=it,
+ metrics={"reward": mean_reward})
+
+ if ctx.is_main:
+ save_stage_ckpt(cfg.out_ckpt, unwrap(actor_ddp).transformer, optimizer, stage="ppo", cfg=cfg, step=cfg.iterations, metrics={})
+ print(f"Done PPO -> {cfg.out_ckpt}")
+ if logger:
+ logger.close()
+ cleanup(ctx)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/train_reward.py b/scripts/train_reward.py
new file mode 100644
index 0000000..ff025bf
--- /dev/null
+++ b/scripts/train_reward.py
@@ -0,0 +1,127 @@
+"""
+Train the reward model on preference pairs with the Bradley-Terry loss.
+
+Initializes the reward backbone from the SFT checkpoint, adds a scalar reward head, and
+trains so chosen responses score above rejected ones. Reports held-out preference accuracy.
+
+Single GPU:
+ PYTHONPATH=. python scripts/train_reward.py
+Both GPUs:
+ PYTHONPATH=. torchrun --standalone --nproc_per_node=2 scripts/train_reward.py
+"""
+
+from __future__ import annotations
+
+import time
+
+import torch
+
+from config.post_training_config import RewardConfig
+from data_loader.preference_dataset import get_preference_iterator
+from src.post_training.cli import parse_config_with_json
+from src.post_training.distributed import ddp_setup, ddp_wrap, cleanup, reduce_scalar
+from src.post_training.logging_utils import MetricsLogger
+from src.post_training.optim import configure_optimizer, cosine_lr
+from src.post_training.reward_model import RewardModel
+from src.post_training.reward_train import bradley_terry_loss, preference_accuracy, reward_margin
+from src.post_training.utils import amp_autocast, load_backbone_from_ckpt, save_stage_ckpt, set_seed, unwrap
+
+TEST_PATH = "/ephemeral/data/preferences_test.jsonl"
+
+
+def _pair_rewards(rm, batch, cfg, ctx):
+ """Forward chosen+rejected in one pass; return (chosen_rewards, rejected_rewards)."""
+ B = batch["chosen_ids"].size(0)
+ ids = torch.cat([batch["chosen_ids"], batch["rejected_ids"]], dim=0)
+ lens = torch.cat([batch["chosen_len"], batch["rejected_len"]], dim=0)
+ with amp_autocast(cfg.amp_dtype, ctx.device):
+ rewards = rm(ids, seq_lengths=lens).float()
+ return rewards[:B], rewards[B:]
+
+
+def eval_accuracy(rm, cfg, ctx, max_batches: int = 100) -> tuple[float, float]:
+ rm.eval()
+ it = get_preference_iterator(TEST_PATH, cfg.batch_size, cfg.max_len, device=ctx.device,
+ rank=ctx.rank, world_size=ctx.world_size, shuffle=False, infinite=False)
+ acc, marg, n = 0.0, 0.0, 0
+ for batch in it:
+ cr, rr = _pair_rewards(rm, batch, cfg, ctx)
+ acc += preference_accuracy(cr, rr).item()
+ marg += reward_margin(cr, rr).item()
+ n += 1
+ if n >= max_batches:
+ break
+ rm.train()
+ return acc / max(1, n), marg / max(1, n)
+
+
+def main():
+ cfg, _ = parse_config_with_json(RewardConfig, "configs/reward.json")
+ ctx = ddp_setup(cfg.device)
+ set_seed(cfg.seed + ctx.rank)
+
+ backbone = load_backbone_from_ckpt(cfg, cfg.sft_ckpt, ctx.device)
+ rm = RewardModel(backbone).to(ctx.device)
+ rm = ddp_wrap(rm, ctx)
+ optimizer = configure_optimizer(unwrap(rm), cfg.lr, cfg.weight_decay)
+
+ import json
+ with open(cfg.pref_path) as f:
+ n_rows = sum(1 for line in f if line.strip())
+ total_steps = max(1, (n_rows // (cfg.batch_size * ctx.world_size)) * cfg.epochs)
+
+ logger = None
+ if ctx.is_main:
+ print(f"Reward model from {cfg.sft_ckpt} | {n_rows} pairs | total_steps={total_steps}")
+ logger = MetricsLogger("reward", cfg.log_dir, use_wandb=cfg.use_wandb, wandb_project=cfg.wandb_project)
+
+ train_it = get_preference_iterator(cfg.pref_path, cfg.batch_size, cfg.max_len, device=ctx.device,
+ rank=ctx.rank, world_size=ctx.world_size, shuffle=True, infinite=True)
+
+ rm.train()
+ t0 = time.perf_counter()
+ for step in range(total_steps):
+ lr = cosine_lr(step, warmup_steps=cfg.warmup_steps, max_steps=total_steps, lr=cfg.lr, min_lr=cfg.lr * 0.1)
+ for g in optimizer.param_groups:
+ g["lr"] = lr
+
+ batch = next(train_it)
+ cr, rr = _pair_rewards(rm, batch, cfg, ctx)
+ loss = bradley_terry_loss(cr, rr)
+ optimizer.zero_grad(set_to_none=True)
+ loss.backward()
+ torch.nn.utils.clip_grad_norm_(rm.parameters(), cfg.grad_clip)
+ optimizer.step()
+
+ if ctx.is_main and step % 20 == 0:
+ acc = preference_accuracy(cr, rr).item()
+ dt = time.perf_counter() - t0; t0 = time.perf_counter()
+ print(f"step {step}/{total_steps} | loss {loss.item():.4f} | train_acc {acc:.3f} | lr {lr:.2e} | {dt:.1f}s/20")
+ if logger:
+ logger.log(step, {"train_loss": loss.item(), "train_acc": acc, "lr": lr})
+
+ if step > 0 and step % cfg.eval_steps == 0:
+ acc, marg = eval_accuracy(rm, cfg, ctx)
+ acc, marg = reduce_scalar(acc, ctx), reduce_scalar(marg, ctx)
+ if ctx.is_main:
+ print(f" [eval] step {step} | test_acc {acc:.3f} | margin {marg:.3f}")
+ if logger:
+ logger.log(step, {"test_acc": acc, "test_margin": marg})
+
+ if ctx.is_main and step > 0 and step % cfg.save_every == 0:
+ save_stage_ckpt(cfg.out_ckpt, rm, optimizer, stage="reward", cfg=cfg, step=step,
+ metrics={"train_loss": loss.item()})
+
+ if ctx.is_main:
+ acc, marg = eval_accuracy(rm, cfg, ctx)
+ save_stage_ckpt(cfg.out_ckpt, rm, optimizer, stage="reward", cfg=cfg, step=total_steps,
+ metrics={"test_acc": acc, "test_margin": marg})
+ print(f"Done RM. test_acc {acc:.3f} margin {marg:.3f} -> {cfg.out_ckpt}")
+ if logger:
+ logger.close()
+ cleanup(ctx)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/train_sft.py b/scripts/train_sft.py
new file mode 100644
index 0000000..a878b59
--- /dev/null
+++ b/scripts/train_sft.py
@@ -0,0 +1,124 @@
+"""
+Supervised Fine-Tuning of the pretrained base on packed instruction data.
+
+Loads the base checkpoint, trains with the prompt-masked SFT loss, periodically reports
+masked dev loss, and saves an SFT checkpoint. DDP + bf16, single code path for 1 or N GPUs.
+
+Single GPU:
+ PYTHONPATH=. python scripts/train_sft.py
+Both GPUs:
+ PYTHONPATH=. torchrun --standalone --nproc_per_node=2 scripts/train_sft.py
+"""
+
+from __future__ import annotations
+
+import contextlib
+import math
+import time
+
+import torch
+
+from config.post_training_config import SFTConfig
+from data_loader.sft_dataset import get_sft_batch_iterator
+from src.post_training.cli import parse_config_with_json
+from src.post_training.distributed import ddp_setup, ddp_wrap, cleanup, reduce_scalar
+from src.post_training.logging_utils import MetricsLogger
+from src.post_training.optim import configure_optimizer, cosine_lr
+from src.post_training.sft import sft_loss
+from src.post_training.utils import amp_autocast, load_backbone_from_ckpt, save_stage_ckpt, set_seed, unwrap
+
+DEV_PATH = "/ephemeral/data/sft_dev_packed.h5"
+
+
+def eval_dev(model, cfg, ctx, dev_path: str, max_batches: int = 50) -> float:
+ model.eval()
+ it = get_sft_batch_iterator(dev_path, cfg.batch_size, device=ctx.device,
+ rank=ctx.rank, world_size=ctx.world_size, shuffle=False, infinite=False)
+ total, n = 0.0, 0
+ for tokens, mask, _ in it:
+ with amp_autocast(cfg.amp_dtype, ctx.device):
+ logits, _ = model(tokens)
+ loss = sft_loss(logits, tokens, mask)
+ total += loss.item(); n += 1
+ if n >= max_batches:
+ break
+ model.train()
+ return total / max(1, n)
+
+
+def main():
+ cfg, _ = parse_config_with_json(SFTConfig, "configs/sft.json")
+ ctx = ddp_setup(cfg.device)
+ set_seed(cfg.seed + ctx.rank)
+
+ model = load_backbone_from_ckpt(cfg, cfg.pretrained_ckpt, ctx.device)
+ if cfg.compile:
+ model = torch.compile(model)
+ model = ddp_wrap(model, ctx)
+ optimizer = configure_optimizer(unwrap(model), cfg.lr, cfg.weight_decay)
+
+ logger = None
+ if ctx.is_main:
+ print(f"SFT from {cfg.pretrained_ckpt} | world_size={ctx.world_size}")
+ logger = MetricsLogger("sft", cfg.log_dir, use_wandb=cfg.use_wandb, wandb_project=cfg.wandb_project)
+
+ train_it = get_sft_batch_iterator(cfg.data_path, cfg.batch_size, device=ctx.device,
+ rank=ctx.rank, world_size=ctx.world_size, shuffle=True, infinite=True)
+
+ # Estimate total steps for the cosine schedule from dataset size.
+ import h5py
+ with h5py.File(cfg.data_path, "r") as f:
+ n_rows = f["tokens"].shape[0]
+ steps_per_epoch = max(1, n_rows // (cfg.batch_size * ctx.world_size))
+ total_steps = cfg.max_steps if cfg.max_steps > 0 else steps_per_epoch * cfg.epochs
+ if ctx.is_main:
+ print(f"{n_rows} packed rows | ~{steps_per_epoch} steps/epoch | total_steps={total_steps}")
+
+ model.train()
+ t0 = time.perf_counter()
+ for step in range(total_steps):
+ lr = cosine_lr(step, warmup_steps=cfg.warmup_steps, max_steps=total_steps, lr=cfg.lr, min_lr=cfg.min_lr)
+ for g in optimizer.param_groups:
+ g["lr"] = lr
+
+ tokens, mask, epoch = next(train_it)
+ if epoch >= cfg.epochs and cfg.max_steps <= 0:
+ break
+ optimizer.zero_grad(set_to_none=True)
+ with amp_autocast(cfg.amp_dtype, ctx.device):
+ logits, _ = model(tokens)
+ loss = sft_loss(logits, tokens, mask)
+ loss.backward()
+ torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.grad_clip)
+ optimizer.step()
+
+ if ctx.is_main and step % 20 == 0:
+ dt = time.perf_counter() - t0; t0 = time.perf_counter()
+ print(f"step {step}/{total_steps} | loss {loss.item():.4f} | ppl {math.exp(min(20, loss.item())):.2f} | lr {lr:.2e} | {dt:.1f}s/20")
+ if logger:
+ logger.log(step, {"train_loss": loss.item(), "lr": lr})
+
+ if step > 0 and step % cfg.eval_steps == 0:
+ dev = reduce_scalar(eval_dev(model, cfg, ctx, DEV_PATH), ctx)
+ if ctx.is_main:
+ print(f" [eval] step {step} | dev_loss {dev:.4f} | dev_ppl {math.exp(min(20, dev)):.2f}")
+ if logger:
+ logger.log(step, {"dev_loss": dev})
+
+ if ctx.is_main and step > 0 and step % cfg.save_every == 0:
+ save_stage_ckpt(cfg.out_ckpt, model, optimizer, stage="sft", cfg=cfg, step=step,
+ metrics={"train_loss": loss.item()})
+
+ if ctx.is_main:
+ dev = eval_dev(model, cfg, ctx, DEV_PATH)
+ save_stage_ckpt(cfg.out_ckpt, model, optimizer, stage="sft", cfg=cfg, step=total_steps,
+ metrics={"dev_loss": dev})
+ print(f"Done SFT. dev_loss {dev:.4f} -> {cfg.out_ckpt}")
+ if logger:
+ logger.close()
+ cleanup(ctx)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/models/transformer.py b/src/models/transformer.py
index 4650753..b8b8877 100644
--- a/src/models/transformer.py
+++ b/src/models/transformer.py
@@ -53,6 +53,27 @@ class Transformer(nn.Module):
pos_embedding = self.position_embed(self.pos_idxs[:T])
return tok_embedding + pos_embedding
+ def forward_hidden(self, idx: torch.Tensor) -> torch.Tensor:
+ """
+ Run the backbone and return the final hidden states AFTER the final layer norm.
+
+ This is exactly the tensor that ``lm_head`` consumes, so it is the right
+ representation for auxiliary heads added during post-training (a scalar value
+ head for PPO, a scalar reward head for the reward model). Keeping it as a
+ separate method lets those heads reuse the backbone without duplicating the
+ forward logic or rewriting ``forward``.
+
+ Args:
+ idx (torch.Tensor): Input token indices, shape (B, T).
+
+ Returns:
+ torch.Tensor: Final hidden states, shape (B, T, n_embed).
+ """
+ x = self._pre_attn_pass(idx)
+ for block in self.attn_blocks:
+ x = block(x)
+ return self.layer_norm(x)
+
def forward(self, idx: torch.Tensor, targets: torch.Tensor = None) -> tuple[torch.Tensor, torch.Tensor | None]:
"""
Forward pass through the Transformer.
@@ -64,10 +85,7 @@ class Transformer(nn.Module):
Returns:
tuple: Logits and loss (if targets are provided).
"""
- x = self._pre_attn_pass(idx)
- for block in self.attn_blocks:
- x = block(x)
- x = self.layer_norm(x)
+ x = self.forward_hidden(idx)
logits = self.lm_head(x)
loss = None
if targets is not None:
diff --git a/src/post_training/__init__.py b/src/post_training/__init__.py
new file mode 100644
index 0000000..1fd1f61
--- /dev/null
+++ b/src/post_training/__init__.py
@@ -0,0 +1,19 @@
+"""
+From-scratch post-training suite for ``train-llm-from-scratch``.
+
+This package adds Supervised Fine-Tuning (SFT), reward modeling, PPO, DPO and
+GRPO/RLVR on top of the repo's own custom :class:`~src.models.transformer.Transformer`.
+Everything here is written in plain PyTorch in the same teaching style as the rest
+of the repo -- no ``trl`` / ``peft`` / ``transformers`` for the algorithms.
+
+Module map
+----------
+- ``chat_template`` : tiktoken r50k_base chat formatting + loss masking
+- ``rollout`` : sampling + per-token log-prob utilities (the RL core)
+- ``value_head`` : actor-critic wrapper for PPO
+- ``reward_model`` : scalar reward head wrapper
+- ``utils`` : frozen copies, checkpoint I/O, masked reductions, seeding
+- ``distributed`` : optional pure-``torch.distributed`` DDP helpers
+- ``sft`` / ``reward_train`` / ``dpo`` / ``ppo`` / ``grpo`` : the algorithms
+- ``rewards`` : verifiable reward functions (GSM8K, arithmetic, format)
+"""
diff --git a/src/post_training/chat_template.py b/src/post_training/chat_template.py
new file mode 100644
index 0000000..1acc414
--- /dev/null
+++ b/src/post_training/chat_template.py
@@ -0,0 +1,154 @@
+"""
+Chat formatting + loss masking for post-training.
+
+The repo's tokenizer is tiktoken ``r50k_base``, whose ONLY special token is
+``<|endoftext|>`` (id 50256). We therefore cannot register new special tokens for
+chat roles. Instead we use plain-text role markers that simply tokenize as ordinary
+multi-token strings -- the model learns them during SFT just like any other text.
+``<|endoftext|>`` (EOT) is reused as the turn/sequence terminator and the single
+generation stop token.
+
+Conversation format (one user turn -> one assistant turn)::
+
+ <|user|>
+ {user content}<|endoftext|><|assistant|>
+ {assistant content}<|endoftext|>
+
+For reasoning / RLVR tasks the assistant content carries the structure itself::
+
+ <think>step by step ...</think><answer>42</answer>
+
+which needs no special handling here -- it is just the assistant message body.
+
+Two outputs matter for training:
+- ``ids`` : the full token id sequence.
+- ``loss_mask`` : 1 on tokens the model should be trained to PRODUCE (the assistant
+ content plus its terminating EOT), 0 on prompt / role-marker tokens.
+ This is exactly the SFT prompt-masking mechanism and the RL
+ ``response_mask`` for generated positions.
+"""
+
+from __future__ import annotations
+
+from functools import lru_cache
+from typing import Iterable
+
+import tiktoken
+
+# tiktoken r50k_base end-of-text id; the only true special token and our stop token.
+EOT_ID = 50256
+
+# Plain-text role markers (ordinary tokens, NOT registered specials).
+USER_HEADER = "<|user|>\n"
+ASSISTANT_HEADER = "<|assistant|>\n"
+SYSTEM_HEADER = "<|system|>\n"
+
+# Reasoning structure markers (also ordinary tokens). Exposed so reward parsing and
+# data generation share a single source of truth.
+THINK_OPEN, THINK_CLOSE = "<think>", "</think>"
+ANSWER_OPEN, ANSWER_CLOSE = "<answer>", "</answer>"
+
+
+@lru_cache(maxsize=1)
+def get_tokenizer() -> "tiktoken.Encoding":
+ """Return the shared r50k_base encoder (cached so we build it once)."""
+ return tiktoken.get_encoding("r50k_base")
+
+
+def _encode_ordinary(text: str) -> list[int]:
+ """Encode text as ordinary tokens (no special-token handling)."""
+ return get_tokenizer().encode_ordinary(text)
+
+
+def _header_for(role: str) -> str:
+ if role == "user":
+ return USER_HEADER
+ if role == "assistant":
+ return ASSISTANT_HEADER
+ if role == "system":
+ return SYSTEM_HEADER
+ raise ValueError(f"Unknown chat role: {role!r}")
+
+
+def render_chat(messages: Iterable[dict], add_generation_prompt: bool = False) -> str:
+ """
+ Render a list of ``{"role", "content"}`` messages to the plain-text chat format.
+
+ This is purely for display/debugging; tokenization goes through :func:`encode_chat`
+ so that loss masks stay exactly aligned with token boundaries.
+
+ Args:
+ messages: iterable of ``{"role": "user"|"assistant"|"system", "content": str}``.
+ add_generation_prompt: if True, append a trailing ``<|assistant|>\\n`` so the
+ model is cued to generate (used at inference / rollout time).
+ """
+ parts: list[str] = []
+ for m in messages:
+ parts.append(_header_for(m["role"]))
+ parts.append(m["content"])
+ parts.append("<|endoftext|>")
+ if add_generation_prompt:
+ parts.append(ASSISTANT_HEADER)
+ return "".join(parts)
+
+
+def encode_chat(
+ messages: Iterable[dict],
+ add_generation_prompt: bool = False,
+) -> tuple[list[int], list[int]]:
+ """
+ Tokenize a conversation and build an aligned per-token loss mask.
+
+ The mask is 1 over assistant content (and its terminating EOT) and 0 everywhere
+ else (role markers, user/system content). When ``add_generation_prompt`` is True
+ the conversation ends with an ``<|assistant|>\\n`` header and no completion, so the
+ returned mask is all zeros -- this is the prompt form used for rollouts.
+
+ Returns:
+ (ids, loss_mask) as equal-length python lists of ints.
+ """
+ ids: list[int] = []
+ mask: list[int] = []
+
+ for m in messages:
+ role = m["role"]
+ # Role header: always masked out (the model should not be trained to emit it,
+ # and at rollout time it is part of the fixed prompt).
+ header_ids = _encode_ordinary(_header_for(role))
+ ids.extend(header_ids)
+ mask.extend([0] * len(header_ids))
+
+ content_ids = _encode_ordinary(m["content"])
+ is_completion = role == "assistant"
+ ids.extend(content_ids)
+ mask.extend([1 if is_completion else 0] * len(content_ids))
+
+ # Turn terminator. Trained on (mask=1) only when it closes an assistant turn,
+ # so the model learns to stop.
+ ids.append(EOT_ID)
+ mask.append(1 if is_completion else 0)
+
+ if add_generation_prompt:
+ header_ids = _encode_ordinary(ASSISTANT_HEADER)
+ ids.extend(header_ids)
+ mask.extend([0] * len(header_ids))
+
+ return ids, mask
+
+
+def encode_prompt(messages: Iterable[dict]) -> list[int]:
+ """Token ids for the prompt form (ends in the assistant header, ready to generate)."""
+ ids, _ = encode_chat(messages, add_generation_prompt=True)
+ return ids
+
+
+def decode(ids: Iterable[int]) -> str:
+ """
+ Decode token ids back to text (for eval / verifier parsing / sample dumps).
+
+ Defensive: drops the EOT terminator and any id >= EOT (50256), since the model's vocab
+ is padded to 50304 but r50k_base can only decode ordinary tokens 0..50255. An
+ under-trained model can emit those padding ids, which would otherwise crash decoding.
+ """
+ clean = [t for t in ids if 0 <= t < EOT_ID]
+ return get_tokenizer().decode(clean)
diff --git a/src/post_training/cli.py b/src/post_training/cli.py
new file mode 100644
index 0000000..ba4f498
--- /dev/null
+++ b/src/post_training/cli.py
@@ -0,0 +1,81 @@
+"""
+Shared CLI helper: turn any stage config dataclass into ``--field value`` arguments so
+every training script can override hyperparameters without bespoke argparse blocks.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+from dataclasses import asdict, fields
+from types import SimpleNamespace
+
+from config.loader import load_config
+
+
+def _add_typed(p: argparse.ArgumentParser, name: str, type_str) -> None:
+ t = str(type_str)
+ if "int" in t and "|" not in t:
+ p.add_argument(f"--{name}", type=int)
+ elif "float" in t:
+ p.add_argument(f"--{name}", type=float)
+ elif t == "bool" or t == "<class 'bool'>":
+ p.add_argument(f"--{name}", type=lambda s: s.lower() in ("1", "true", "yes"))
+ else:
+ # str, optionals, unions -> accept as string (dataclass keeps None defaults otherwise)
+ p.add_argument(f"--{name}", type=str)
+
+
+def parse_config(cfg_cls, extra: dict | None = None):
+ """
+ Parse CLI overrides for a config dataclass.
+
+ Returns ``(cfg, extras)`` where ``cfg`` is an instance of ``cfg_cls`` with any provided
+ ``--field`` overrides applied, and ``extras`` is a namespace of any non-config args
+ declared via ``extra`` (mapping ``"--flag" -> dict(argparse kwargs)``).
+ """
+ p = argparse.ArgumentParser()
+ field_names = {f.name for f in fields(cfg_cls)}
+ for f in fields(cfg_cls):
+ _add_typed(p, f.name, f.type)
+ for flag, kwargs in (extra or {}).items():
+ p.add_argument(flag, **kwargs)
+ args = vars(p.parse_args())
+
+ overrides = {k: v for k, v in args.items() if k in field_names and v is not None}
+ extras = {k: v for k, v in args.items() if k not in field_names}
+ return cfg_cls(**overrides), SimpleNamespace(**extras)
+
+
+def parse_config_with_json(cfg_cls, default_json: str, extra: dict | None = None):
+ """
+ Like :func:`parse_config`, but resolves the config from a JSON file too.
+
+ Adds two flags on top of the per-field ``--field`` overrides:
+ - ``--config PATH`` : the stage JSON to load (default ``default_json``).
+ - ``--print-config`` : print the fully resolved config as JSON and exit.
+
+ Resolution order (low -> high): dataclass defaults < ``configs/base.json`` < the stage
+ JSON < CLI ``--field`` overrides (see :func:`config.loader.load_config`).
+
+ Returns ``(cfg, extras)`` exactly like :func:`parse_config`.
+ """
+ p = argparse.ArgumentParser()
+ field_names = {f.name for f in fields(cfg_cls)}
+ for f in fields(cfg_cls):
+ _add_typed(p, f.name, f.type)
+ p.add_argument("--config", default=default_json, help="stage JSON config to load")
+ p.add_argument("--print-config", action="store_true", help="print resolved config and exit")
+ for flag, kwargs in (extra or {}).items():
+ p.add_argument(flag, **kwargs)
+ args = vars(p.parse_args())
+
+ reserved = {"config", "print_config"}
+ overrides = {k: v for k, v in args.items() if k in field_names and v is not None}
+ extras = {k: v for k, v in args.items() if k not in field_names and k not in reserved}
+
+ cfg = load_config(cfg_cls, args["config"], overrides)
+ if args["print_config"]:
+ print(json.dumps(asdict(cfg), indent=2))
+ raise SystemExit(0)
+ return cfg, SimpleNamespace(**extras)
diff --git a/src/post_training/distributed.py b/src/post_training/distributed.py
new file mode 100644
index 0000000..4d46975
--- /dev/null
+++ b/src/post_training/distributed.py
@@ -0,0 +1,102 @@
+"""
+Optional, from-scratch multi-GPU helpers (pure ``torch.distributed`` -- no accelerate).
+
+Every training script works on a single GPU with plain ``python scripts/train_*.py`` and
+on N GPUs with ``torchrun --standalone --nproc_per_node=N scripts/train_*.py``. When not
+launched under torchrun, :func:`ddp_setup` returns a world_size=1 context and all the
+helpers degrade to no-ops, so the scripts have a single code path.
+"""
+
+from __future__ import annotations
+
+import os
+from dataclasses import dataclass
+
+import torch
+import torch.distributed as dist
+from torch.nn.parallel import DistributedDataParallel as DDP
+
+
+@dataclass
+class DDPContext:
+ rank: int
+ local_rank: int
+ world_size: int
+ device: str
+
+ @property
+ def is_main(self) -> bool:
+ return self.rank == 0
+
+ @property
+ def enabled(self) -> bool:
+ return self.world_size > 1
+
+
+def ddp_setup(device: str = "cuda") -> DDPContext:
+ """Initialize the process group if launched under torchrun; otherwise single-process.
+
+ Reads ``RANK`` / ``LOCAL_RANK`` / ``WORLD_SIZE`` from the environment (set by
+ torchrun). Uses the NCCL backend on CUDA, gloo on CPU.
+ """
+ world_size = int(os.environ.get("WORLD_SIZE", "1"))
+ if world_size == 1:
+ dev = device if (device == "cuda" and torch.cuda.is_available()) else "cpu"
+ if dev == "cuda":
+ torch.cuda.set_device(0)
+ return DDPContext(rank=0, local_rank=0, world_size=1, device=dev)
+
+ rank = int(os.environ["RANK"])
+ local_rank = int(os.environ["LOCAL_RANK"])
+ backend = "nccl" if (device == "cuda" and torch.cuda.is_available()) else "gloo"
+ dist.init_process_group(backend=backend, rank=rank, world_size=world_size)
+ if device == "cuda":
+ torch.cuda.set_device(local_rank)
+ dev = f"cuda:{local_rank}"
+ else:
+ dev = "cpu"
+ return DDPContext(rank=rank, local_rank=local_rank, world_size=world_size, device=dev)
+
+
+def ddp_wrap(model: torch.nn.Module, ctx: DDPContext) -> torch.nn.Module:
+ """Wrap a model in DDP when running multi-GPU; return it unchanged otherwise.
+
+ Only the *trainable* model should be wrapped. Reference / old-policy / reward models
+ carry no gradients and must NOT be wrapped (they are replicated identically per rank).
+ """
+ if not ctx.enabled:
+ return model
+ device_ids = [ctx.local_rank] if ctx.device.startswith("cuda") else None
+ return DDP(model, device_ids=device_ids, find_unused_parameters=False)
+
+
+def is_main_process(ctx: DDPContext) -> bool:
+ return ctx.is_main
+
+
+def reduce_scalar(value: float, ctx: DDPContext, average: bool = True) -> float:
+ """All-reduce a python scalar across ranks (sum or mean). No-op when single-process."""
+ if not ctx.enabled:
+ return value
+ t = torch.tensor([value], device=ctx.device, dtype=torch.float32)
+ dist.all_reduce(t, op=dist.ReduceOp.SUM)
+ if average:
+ t /= ctx.world_size
+ return t.item()
+
+
+def barrier(ctx: DDPContext) -> None:
+ if ctx.enabled:
+ dist.barrier()
+
+
+def cleanup(ctx: DDPContext) -> None:
+ if ctx.enabled and dist.is_initialized():
+ dist.destroy_process_group()
+
+
+def shard_indices(num_items: int, ctx: DDPContext) -> range:
+ """Return this rank's strided slice of ``range(num_items)`` for data sharding."""
+ if not ctx.enabled:
+ return range(num_items)
+ return range(ctx.rank, num_items, ctx.world_size)
diff --git a/src/post_training/dpo.py b/src/post_training/dpo.py
new file mode 100644
index 0000000..751f4c8
--- /dev/null
+++ b/src/post_training/dpo.py
@@ -0,0 +1,95 @@
+"""
+Direct Preference Optimization and two reference-free / unpaired variants.
+
+All operate on sequence-level log-probabilities of the chosen/rejected responses (summed
+over response tokens via :func:`src.post_training.rollout.sequence_logprobs`).
+
+- ``dpo_loss`` : the standard DPO objective; aligns the policy to preferences using a
+ frozen reference model and temperature ``beta``.
+- ``orpo_loss`` : ORPO -- reference-FREE; combines the SFT NLL on the chosen response with
+ an odds-ratio preference term (folds SFT + alignment into one stage).
+- ``kto_loss`` : KTO -- works from a per-example desirable/undesirable signal (here read
+ off the chosen/rejected pair) with a reference KL baseline.
+"""
+
+from __future__ import annotations
+
+import torch
+import torch.nn.functional as F
+
+
+def dpo_loss(
+ policy_chosen_logps: torch.Tensor,
+ policy_rejected_logps: torch.Tensor,
+ ref_chosen_logps: torch.Tensor,
+ ref_rejected_logps: torch.Tensor,
+ beta: float = 0.1,
+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """
+ Standard DPO loss. Inputs are summed response log-probs (B,).
+
+ Returns ``(loss, chosen_reward, rejected_reward)`` where the implicit rewards
+ ``beta * (policy_logp - ref_logp)`` are detached diagnostics.
+ """
+ pi_logratios = policy_chosen_logps - policy_rejected_logps
+ ref_logratios = ref_chosen_logps - ref_rejected_logps
+ logits = pi_logratios - ref_logratios
+ loss = -F.logsigmoid(beta * logits).mean()
+ chosen_reward = beta * (policy_chosen_logps - ref_chosen_logps).detach()
+ rejected_reward = beta * (policy_rejected_logps - ref_rejected_logps).detach()
+ return loss, chosen_reward, rejected_reward
+
+
+def _log1mexp(x: torch.Tensor) -> torch.Tensor:
+ """Numerically stable log(1 - exp(x)) for x < 0."""
+ return torch.where(x > -0.6931, torch.log(-torch.expm1(x)), torch.log1p(-torch.exp(x)))
+
+
+def orpo_loss(
+ policy_chosen_logps: torch.Tensor,
+ policy_rejected_logps: torch.Tensor,
+ chosen_n_tokens: torch.Tensor,
+ rejected_n_tokens: torch.Tensor,
+ orpo_lambda: float = 1.0,
+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """
+ ORPO (reference-free). Uses per-token MEAN log-probs.
+
+ ``L = NLL(chosen) + lambda * -log sigmoid(log_odds_chosen - log_odds_rejected)``
+ where ``log_odds = mean_logp - log(1 - exp(mean_logp))``.
+ """
+ chosen_mean = policy_chosen_logps / chosen_n_tokens.clamp(min=1)
+ rejected_mean = policy_rejected_logps / rejected_n_tokens.clamp(min=1)
+ log_odds = (chosen_mean - _log1mexp(chosen_mean)) - (rejected_mean - _log1mexp(rejected_mean))
+ or_loss = -F.logsigmoid(log_odds).mean()
+ nll = -chosen_mean.mean()
+ loss = nll + orpo_lambda * or_loss
+ # Implicit rewards for logging: the mean log-probs themselves.
+ return loss, chosen_mean.detach(), rejected_mean.detach()
+
+
+def kto_loss(
+ policy_chosen_logps: torch.Tensor,
+ policy_rejected_logps: torch.Tensor,
+ ref_chosen_logps: torch.Tensor,
+ ref_rejected_logps: torch.Tensor,
+ beta: float = 0.1,
+ desirable_weight: float = 1.0,
+ undesirable_weight: float = 1.0,
+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """
+ KTO from paired data: chosen = desirable, rejected = undesirable, with a reference-KL
+ baseline estimated (detached) from the batch's mean log-ratio.
+ """
+ chosen_logratio = policy_chosen_logps - ref_chosen_logps
+ rejected_logratio = policy_rejected_logps - ref_rejected_logps
+ kl = torch.cat([chosen_logratio, rejected_logratio]).mean().clamp(min=0).detach()
+ chosen_losses = 1.0 - torch.sigmoid(beta * (chosen_logratio - kl))
+ rejected_losses = 1.0 - torch.sigmoid(beta * (kl - rejected_logratio))
+ loss = (desirable_weight * chosen_losses).mean() + (undesirable_weight * rejected_losses).mean()
+ return loss, (beta * chosen_logratio).detach(), (beta * rejected_logratio).detach()
+
+
+def implicit_accuracy(chosen_reward: torch.Tensor, rejected_reward: torch.Tensor) -> torch.Tensor:
+ """Fraction of pairs where the implicit (DPO/KTO/ORPO) reward prefers chosen."""
+ return (chosen_reward > rejected_reward).float().mean()
diff --git a/src/post_training/evaluation.py b/src/post_training/evaluation.py
new file mode 100644
index 0000000..c0527d1
--- /dev/null
+++ b/src/post_training/evaluation.py
@@ -0,0 +1,116 @@
+"""
+Shared evaluation utilities for post-training stages.
+
+The headline metric across the whole pipeline is GSM8K accuracy (greedy decoding) on a
+fixed held-out set, so Base -> SFT -> DPO -> PPO -> GRPO can be compared on one axis.
+``batched_generate`` length-buckets prompts so the mask-free model can decode many at once.
+"""
+
+from __future__ import annotations
+
+import torch
+
+from src.post_training.chat_template import EOT_ID, decode, encode_prompt
+from src.post_training.rollout import generate_with_logprobs
+from src.post_training.rewards import gsm8k_gold_answer, is_correct
+
+
+def _model_context_length(model) -> int:
+ inner = getattr(model, "transformer", model)
+ return getattr(inner, "context_length", 1024)
+
+
+def batched_generate(
+ model,
+ prompts: list[list[int]],
+ max_new_tokens: int,
+ *,
+ device: str,
+ temperature: float = 1.0,
+ top_k: int | None = None,
+ top_p: float | None = None,
+ greedy: bool = False,
+ micro_batch: int = 32,
+) -> list[str]:
+ """
+ Generate a response string for each tokenized prompt, returned in input order.
+
+ Prompts are grouped by identical length (the model has no padding-aware attention
+ mask) and decoded in micro-batches. ``greedy=True`` forces argmax decoding (top_k=1),
+ which is what we use for comparable eval numbers.
+ """
+ if greedy:
+ temperature, top_k, top_p = 1.0, 1, None
+
+ cap = _model_context_length(model)
+ order = sorted(range(len(prompts)), key=lambda i: len(prompts[i]))
+ results: list[str | None] = [None] * len(prompts)
+
+ i = 0
+ while i < len(order):
+ j = i
+ L = len(prompts[order[i]])
+ # Gather a run of same-length prompts, up to micro_batch.
+ while j < len(order) and len(prompts[order[j]]) == L and (j - i) < micro_batch:
+ j += 1
+ idxs = order[i:j]
+ i = j
+ budget = min(max_new_tokens, cap - L)
+ if budget <= 0: # prompt already fills the context; nothing to generate
+ for k in idxs:
+ results[k] = ""
+ continue
+ batch = torch.tensor([prompts[k] for k in idxs], dtype=torch.long, device=device)
+ rb = generate_with_logprobs(model, batch, budget, temperature=temperature,
+ top_k=top_k, top_p=top_p, stop_tokens=(EOT_ID,), pad_id=EOT_ID)
+ gen = rb.sequences[:, L:]
+ for row, k in enumerate(idxs):
+ toks = gen[row].tolist()
+ if EOT_ID in toks:
+ toks = toks[: toks.index(EOT_ID)]
+ results[k] = decode(toks)
+ return [r or "" for r in results]
+
+
+def gsm8k_accuracy(
+ model,
+ qa_pairs: list[tuple[str, str]],
+ *,
+ device: str,
+ max_new_tokens: int = 300,
+ greedy: bool = True,
+ return_samples: int = 0,
+) -> dict:
+ """
+ Compute greedy GSM8K accuracy over ``(question, answer_field)`` pairs.
+
+ Returns ``{"accuracy", "n", "correct", "samples"}`` where ``samples`` holds a few
+ (question, response, gold, correct) tuples for qualitative inspection.
+ """
+ prompts = [encode_prompt([{"role": "user", "content": q}]) for q, _ in qa_pairs]
+ responses = batched_generate(model, prompts, max_new_tokens, device=device, greedy=greedy)
+
+ correct = 0
+ samples = []
+ for (q, ans), resp in zip(qa_pairs, responses):
+ gold = gsm8k_gold_answer(ans)
+ ok = is_correct(resp, gold)
+ correct += int(ok)
+ if len(samples) < return_samples:
+ samples.append({"q": q, "response": resp, "gold": gold, "correct": ok})
+ n = len(qa_pairs)
+ return {"accuracy": correct / max(1, n), "n": n, "correct": correct, "samples": samples}
+
+
+def load_gsm8k_eval(split: str = "test", limit: int | None = 200) -> list[tuple[str, str]]:
+ """Load ``(question, answer_field)`` pairs from GSM8K for evaluation."""
+ import os
+ os.environ.setdefault("HF_HOME", "/ephemeral/hf_cache")
+ from datasets import load_dataset
+
+ ds = load_dataset("openai/gsm8k", "main", split=split)
+ if limit:
+ ds = ds.select(range(min(limit, len(ds))))
+ return [(ex["question"], ex["answer"]) for ex in ds]
diff --git a/src/post_training/grpo.py b/src/post_training/grpo.py
new file mode 100644
index 0000000..6c9ba64
--- /dev/null
+++ b/src/post_training/grpo.py
@@ -0,0 +1,70 @@
+"""
+GRPO (Group Relative Policy Optimization) core -- the DeepSeek-R1 RL algorithm.
+
+GRPO drops PPO's value network. For each prompt it samples a GROUP of G completions,
+scores them with a verifiable reward, and uses the group's own mean/std to compute a
+relative advantage -- so the baseline is the group, not a learned critic. The update is a
+token-level clipped surrogate plus a per-token KL penalty to the reference policy.
+"""
+
+from __future__ import annotations
+
+import torch
+
+from src.post_training.utils import masked_mean
+
+
+def group_advantages(rewards: torch.Tensor, group_size: int, eps: float = 1e-4) -> torch.Tensor:
+ """
+ Group-relative advantage: ``(r - group_mean) / (group_std + eps)``.
+
+ ``rewards`` is (num_prompts * group_size,) laid out group-contiguously (all G samples
+ of prompt 0, then prompt 1, ...). Returns advantages of the same shape.
+ """
+ r = rewards.view(-1, group_size)
+ mean = r.mean(dim=1, keepdim=True)
+ std = r.std(dim=1, keepdim=True)
+ adv = (r - mean) / (std + eps)
+ return adv.reshape(-1)
+
+
+def k3_kl(new_logp: torch.Tensor, ref_logp: torch.Tensor) -> torch.Tensor:
+ """Per-token unbiased, non-negative KL estimator (Schulman's k3) for KL(policy||ref)."""
+ diff = ref_logp - new_logp
+ return torch.exp(diff) - diff - 1.0
+
+
+def grpo_loss(
+ new_logp: torch.Tensor,
+ old_logp: torch.Tensor,
+ ref_logp: torch.Tensor,
+ advantages: torch.Tensor,
+ resp_mask: torch.Tensor,
+ clip: float = 0.2,
+ kl_coef: float = 0.04,
+) -> tuple[torch.Tensor, dict]:
+ """
+ Token-level clipped surrogate + KL penalty.
+
+ Args:
+ new_logp/old_logp/ref_logp: (B, L) per-token log-probs (policy / sampling / ref).
+ advantages: (B,) one scalar per completion, broadcast over its tokens.
+ resp_mask: (B, L) bool over response tokens.
+
+ Returns:
+ (loss, stats) with mean KL and clip fraction for logging.
+ """
+ adv = advantages[:, None]
+ ratio = torch.exp(new_logp - old_logp)
+ surr1 = ratio * adv
+ surr2 = torch.clamp(ratio, 1.0 - clip, 1.0 + clip) * adv
+ surrogate = torch.min(surr1, surr2)
+ kl = k3_kl(new_logp, ref_logp)
+
+ per_token = surrogate - kl_coef * kl
+ loss = -masked_mean(per_token, resp_mask)
+ stats = {
+ "kl": masked_mean(kl, resp_mask).item(),
+ "clipfrac": masked_mean(((ratio - 1.0).abs() > clip).float(), resp_mask).item(),
+ }
+ return loss, stats
diff --git a/src/post_training/inference.py b/src/post_training/inference.py
new file mode 100644
index 0000000..dd33876
--- /dev/null
+++ b/src/post_training/inference.py
@@ -0,0 +1,71 @@
+"""
+Inference helpers shared by the chat CLI and the eval scripts.
+
+Loads any stage checkpoint (base / sft / dpo / ppo / grpo) by reading the model
+dimensions from the checkpoint's stored ``cfg`` (so you never have to repeat them), and
+generates a reply either in chat-template form (for instruction-tuned models) or as raw
+continuation (for the base model).
+"""
+
+from __future__ import annotations
+
+import torch
+
+from src.models.transformer import Transformer
+from src.post_training.chat_template import EOT_ID, decode, encode_prompt, get_tokenizer
+from src.post_training.evaluation import batched_generate
+
+
+def load_model_from_ckpt(ckpt_path: str, device: str, overrides: dict | None = None) -> Transformer:
+ """Build a :class:`Transformer` from a checkpoint's stored cfg and load its backbone
+ weights (tolerates ``module.``/``transformer.`` prefixes and reward-head extras)."""
+ ck = torch.load(ckpt_path, map_location="cpu", weights_only=False)
+ cfg = {**(ck.get("cfg") or {}), **(overrides or {})}
+ model = Transformer(
+ n_head=cfg.get("n_head", 16), n_embed=cfg.get("n_embed", 1024),
+ context_length=cfg.get("context_length", 1024), vocab_size=cfg.get("vocab_size", 50304),
+ N_BLOCKS=cfg.get("n_blocks", 24),
+ )
+ state = ck["model_state_dict"] if "model_state_dict" in ck else ck
+ state = {k.removeprefix("module.").removeprefix("transformer."): v for k, v in state.items()}
+ keys = set(model.state_dict().keys())
+ model.load_state_dict({k: v for k, v in state.items() if k in keys}, strict=False)
+ return model.to(device).eval()
+
+
+def generate_reply(
+ model,
+ user_text: str,
+ *,
+ device: str,
+ system: str | None = None,
+ raw: bool = False,
+ max_new_tokens: int = 256,
+ temperature: float = 0.8,
+ top_k: int | None = None,
+ top_p: float | None = 0.95,
+ greedy: bool = False,
+) -> str:
+ """
+ Generate a response to ``user_text``.
+
+ - chat mode (default): wraps the prompt in the chat template (optionally with a
+ ``system`` message) and returns the decoded assistant turn.
+ - raw mode (``raw=True``): treats ``user_text`` as a prefix and returns the base
+ model's continuation (no chat template) -- the right mode for the pretrained base.
+ """
+ if raw:
+ ids = get_tokenizer().encode_ordinary(user_text)
+ out = batched_generate(model, [ids], max_new_tokens, device=device, temperature=temperature,
+ top_k=top_k, top_p=top_p, greedy=greedy)
+ return out[0]
+
+ messages = []
+ if system:
+ messages.append({"role": "system", "content": system})
+ messages.append({"role": "user", "content": user_text})
+ prompt_ids = encode_prompt(messages)
+ out = batched_generate(model, [prompt_ids], max_new_tokens, device=device, temperature=temperature,
+ top_k=top_k, top_p=top_p, greedy=greedy)
+ return out[0]
diff --git a/src/post_training/logging_utils.py b/src/post_training/logging_utils.py
new file mode 100644
index 0000000..e77993d
--- /dev/null
+++ b/src/post_training/logging_utils.py
@@ -0,0 +1,58 @@
+"""
+Lightweight metrics logging shared by every training stage.
+
+Always writes one JSON object per logged step to a JSONL file under the log dir (so runs
+are reproducible and plottable without any external service). Optionally mirrors to
+Weights & Biases when ``use_wandb=True`` and the package is importable. Only the main
+process should construct/use a logger (the trainers guard this).
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import time
+from typing import Any
+
+
+class MetricsLogger:
+ def __init__(
+ self,
+ stage: str,
+ log_dir: str,
+ *,
+ use_wandb: bool = False,
+ wandb_project: str = "train-llm-from-scratch-posttrain",
+ config: dict | None = None,
+ run_name: str | None = None,
+ ) -> None:
+ os.makedirs(log_dir, exist_ok=True)
+ self.stage = stage
+ # No Date.now in scripts here; use time.time() (allowed) for unique filenames.
+ stamp = int(time.time())
+ self.path = os.path.join(log_dir, f"{stage}_{stamp}.jsonl")
+ self._fh = open(self.path, "a")
+ self._wandb = None
+ if use_wandb:
+ try:
+ import wandb
+
+ wandb.init(project=wandb_project, name=run_name or f"{stage}-{stamp}", config=config or {})
+ self._wandb = wandb
+ except Exception as e: # noqa: BLE001 - logging must never crash training
+ print(f"[logger] wandb disabled ({e}); JSONL logging only -> {self.path}")
+ print(f"[logger] stage={stage} -> {self.path}")
+
+ def log(self, step: int, metrics: dict[str, Any]) -> None:
+ record = {"step": step, "wall": time.time(), **metrics}
+ self._fh.write(json.dumps(record) + "\n")
+ self._fh.flush()
+ if self._wandb is not None:
+ self._wandb.log(metrics, step=step)
+
+ def close(self) -> None:
+ try:
+ self._fh.close()
+ finally:
+ if self._wandb is not None:
+ self._wandb.finish()
diff --git a/src/post_training/optim.py b/src/post_training/optim.py
new file mode 100644
index 0000000..567f512
--- /dev/null
+++ b/src/post_training/optim.py
@@ -0,0 +1,49 @@
+"""
+Optimizer and learning-rate-schedule helpers shared across stages.
+
+- ``configure_optimizer`` builds AdamW with the standard weight-decay split (decay the 2D
+ weight matrices, don't decay biases / LayerNorm / embeddings).
+- ``cosine_lr`` is a linear-warmup + cosine-decay schedule returning the LR for a step.
+"""
+
+from __future__ import annotations
+
+import math
+
+import torch
+import torch.nn as nn
+
+
+def configure_optimizer(
+ model: nn.Module,
+ lr: float,
+ weight_decay: float,
+ betas: tuple[float, float] = (0.9, 0.95),
+) -> torch.optim.AdamW:
+ """AdamW with weight decay applied only to >=2D parameters (matrices), not to
+ biases / norms / 1D params. Standard GPT recipe."""
+ decay, no_decay = [], []
+ for name, p in model.named_parameters():
+ if not p.requires_grad:
+ continue
+ if p.dim() >= 2:
+ decay.append(p)
+ else:
+ no_decay.append(p)
+ groups = [
+ {"params": decay, "weight_decay": weight_decay},
+ {"params": no_decay, "weight_decay": 0.0},
+ ]
+ return torch.optim.AdamW(groups, lr=lr, betas=betas)
+
+
+def cosine_lr(step: int, *, warmup_steps: int, max_steps: int, lr: float, min_lr: float) -> float:
+ """Linear warmup to ``lr`` over ``warmup_steps``, then cosine decay to ``min_lr`` by
+ ``max_steps`` (constant ``min_lr`` afterwards)."""
+ if step < warmup_steps:
+ return lr * (step + 1) / max(1, warmup_steps)
+ if step >= max_steps:
+ return min_lr
+ progress = (step - warmup_steps) / max(1, max_steps - warmup_steps)
+ coeff = 0.5 * (1.0 + math.cos(math.pi * progress))
+ return min_lr + coeff * (lr - min_lr)
diff --git a/src/post_training/ppo.py b/src/post_training/ppo.py
new file mode 100644
index 0000000..cb60a92
--- /dev/null
+++ b/src/post_training/ppo.py
@@ -0,0 +1,100 @@
+"""
+PPO core (the classic InstructGPT RLHF update), written from scratch.
+
+The orchestration (rollout -> score -> GAE -> clipped epochs) lives in
+``scripts/train_ppo.py``; this module holds the reusable, testable pieces:
+
+- ``compute_gae`` : Generalized Advantage Estimation over response tokens.
+- ``whiten`` : advantage normalization (masked).
+- ``ppo_policy_loss`` : clipped surrogate objective.
+- ``ppo_value_loss`` : clipped value-function loss.
+
+All tensors are in the "action frame" of length ``L = T-1``: index ``t`` corresponds to
+producing token ``t+1``, with state-value ``V(s_t)``, log-prob of the produced token, and
+the reward received for that action. ``resp_mask`` marks which actions are response tokens.
+"""
+
+from __future__ import annotations
+
+import torch
+
+from src.post_training.utils import masked_mean
+
+
+def compute_gae(
+ rewards: torch.Tensor,
+ values: torch.Tensor,
+ values_next: torch.Tensor,
+ resp_mask: torch.Tensor,
+ gamma: float = 1.0,
+ lam: float = 0.95,
+) -> tuple[torch.Tensor, torch.Tensor]:
+ """
+ Generalized Advantage Estimation over the response.
+
+ Args (all (B, L) in the action frame; ``resp_mask`` bool):
+ rewards: per-action reward (KL penalty per token + task reward at the last
+ response token).
+ values: V(s_t).
+ values_next: V(s_{t+1}).
+ resp_mask: True where action t is a response token. The episode is terminal
+ after the last response token (no bootstrap past it).
+
+ Returns:
+ (advantages, returns) each (B, L), zeroed outside the response.
+ """
+ B, L = rewards.shape
+ adv = torch.zeros_like(rewards)
+ lastgae = torch.zeros(B, device=rewards.device)
+ m = resp_mask.float()
+ for t in reversed(range(L)):
+ # Bootstrap only if the NEXT action is still a response action.
+ nonterminal = m[:, t + 1] if t + 1 < L else torch.zeros(B, device=rewards.device)
+ delta = rewards[:, t] + gamma * values_next[:, t] * nonterminal - values[:, t]
+ lastgae = delta + gamma * lam * nonterminal * lastgae
+ adv[:, t] = lastgae
+ returns = adv + values
+ return adv * m, returns * m
+
+
+def whiten(advantages: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
+ """Normalize advantages to zero mean / unit std over masked (response) positions."""
+ m = mask.float()
+ mean = masked_mean(advantages, m)
+ var = masked_mean((advantages - mean) ** 2, m)
+ return ((advantages - mean) / (var.sqrt() + 1e-8)) * m
+
+
+def ppo_policy_loss(
+ new_logp: torch.Tensor,
+ old_logp: torch.Tensor,
+ advantages: torch.Tensor,
+ mask: torch.Tensor,
+ clip: float = 0.2,
+) -> tuple[torch.Tensor, torch.Tensor]:
+ """Clipped surrogate policy loss. Returns (loss, clip_fraction)."""
+ ratio = torch.exp(new_logp - old_logp)
+ surr1 = ratio * advantages
+ surr2 = torch.clamp(ratio, 1.0 - clip, 1.0 + clip) * advantages
+ loss = -masked_mean(torch.min(surr1, surr2), mask)
+ clipped = ((ratio - 1.0).abs() > clip).float()
+ return loss, masked_mean(clipped, mask)
+
+
+def ppo_value_loss(
+ new_values: torch.Tensor,
+ old_values: torch.Tensor,
+ returns: torch.Tensor,
+ mask: torch.Tensor,
+ vf_clip: float = 0.2,
+) -> torch.Tensor:
+ """Clipped value-function loss (0.5 * max of clipped/unclipped squared error)."""
+ v_clipped = old_values + torch.clamp(new_values - old_values, -vf_clip, vf_clip)
+ loss_unclipped = (new_values - returns) ** 2
+ loss_clipped = (v_clipped - returns) ** 2
+ return 0.5 * masked_mean(torch.max(loss_unclipped, loss_clipped), mask)
+
+
+def approx_kl(new_logp: torch.Tensor, old_logp: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
+ """Mean approximate KL(old || new) over response tokens (a PPO health metric)."""
+ return masked_mean(old_logp - new_logp, mask)
diff --git a/src/post_training/reward_model.py b/src/post_training/reward_model.py
new file mode 100644
index 0000000..af7e171
--- /dev/null
+++ b/src/post_training/reward_model.py
@@ -0,0 +1,68 @@
+"""
+Reward model: a scalar reward head on top of a :class:`Transformer` backbone.
+
+Following InstructGPT, the reward of a full sequence is read off the hidden state of its
+**last real token**. We train it with the Bradley-Terry pairwise loss (see
+``reward_train.py``) on (chosen, rejected) preference pairs. The trained RM then provides
+the scalar reward signal for PPO.
+"""
+
+from __future__ import annotations
+
+import torch
+import torch.nn as nn
+
+import torch as _torch
+
+from src.models.transformer import Transformer
+from src.post_training.utils import build_model_from_config, gather_last, unwrap
+
+
+def load_reward_model(cfg, ckpt_path: str, device: str) -> "RewardModel":
+ """Reconstruct a trained :class:`RewardModel` (backbone + reward head) from a reward
+ checkpoint saved by ``scripts/train_reward.py``."""
+ backbone = build_model_from_config(cfg)
+ rm = RewardModel(backbone)
+ ck = _torch.load(ckpt_path, map_location="cpu", weights_only=False)
+ state = ck["model_state_dict"] if "model_state_dict" in ck else ck
+ if any(k.startswith("module.") for k in state):
+ state = {k.removeprefix("module."): v for k, v in state.items()}
+ rm.load_state_dict(state, strict=True)
+ rm.to(device).eval()
+ for p in rm.parameters():
+ p.requires_grad_(False)
+ return rm
+
+
+class RewardModel(nn.Module):
+ """Wrap a :class:`Transformer` and add a scalar reward head (no ``lm_head`` used)."""
+
+ def __init__(self, transformer: Transformer) -> None:
+ super().__init__()
+ self.transformer = transformer
+ n_embed = transformer.lm_head.in_features
+ self.reward_head = nn.Linear(n_embed, 1, bias=False)
+ nn.init.zeros_(self.reward_head.weight) # start near-zero rewards
+
+ @property
+ def context_length(self) -> int:
+ return self.transformer.context_length
+
+ def token_rewards(self, idx: torch.Tensor) -> torch.Tensor:
+ """Per-token scalar reward (B, T) -- useful for diagnostics / dense shaping."""
+ hidden = self.transformer.forward_hidden(idx)
+ return self.reward_head(hidden).squeeze(-1)
+
+ def forward(self, idx: torch.Tensor, seq_lengths: torch.Tensor | None = None) -> torch.Tensor:
+ """
+ Scalar reward per sequence (B,).
+
+ Args:
+ idx: (B, T) token ids.
+ seq_lengths: (B,) number of real (non-pad) tokens per row. If None, uses the
+ full length T (assumes no padding).
+ """
+ rewards = self.token_rewards(idx) # (B, T)
+ if seq_lengths is None:
+ return rewards[:, -1]
+ return gather_last(rewards, seq_lengths)
diff --git a/src/post_training/reward_train.py b/src/post_training/reward_train.py
new file mode 100644
index 0000000..0bdb349
--- /dev/null
+++ b/src/post_training/reward_train.py
@@ -0,0 +1,30 @@
+"""
+Reward-model training objective: the Bradley-Terry pairwise loss used by InstructGPT.
+
+Given scalar rewards for a preferred (``chosen``) and dispreferred (``rejected``) response
+to the same prompt, the model is trained so the chosen reward exceeds the rejected one:
+
+ L = -log sigmoid(r_chosen - r_rejected)
+
+Preference accuracy (fraction with r_chosen > r_rejected) is the headline eval metric.
+"""
+
+from __future__ import annotations
+
+import torch
+import torch.nn.functional as F
+
+
+def bradley_terry_loss(chosen_rewards: torch.Tensor, rejected_rewards: torch.Tensor) -> torch.Tensor:
+ """Mean ``-log sigmoid(chosen - rejected)`` over a batch of preference pairs."""
+ return -F.logsigmoid(chosen_rewards - rejected_rewards).mean()
+
+
+def preference_accuracy(chosen_rewards: torch.Tensor, rejected_rewards: torch.Tensor) -> torch.Tensor:
+ """Fraction of pairs where the model scores the chosen response higher."""
+ return (chosen_rewards > rejected_rewards).float().mean()
+
+
+def reward_margin(chosen_rewards: torch.Tensor, rejected_rewards: torch.Tensor) -> torch.Tensor:
+ """Mean reward gap (chosen - rejected); a useful training diagnostic."""
+ return (chosen_rewards - rejected_rewards).mean()
diff --git a/src/post_training/rewards/__init__.py b/src/post_training/rewards/__init__.py
new file mode 100644
index 0000000..21e0ff8
--- /dev/null
+++ b/src/post_training/rewards/__init__.py
@@ -0,0 +1,25 @@
+"""Verifiable (programmatic) reward functions for RLVR -- GSM8K math + arithmetic warm-up."""
+
+from src.post_training.rewards.parsing import (
+ extract_answer,
+ extract_think,
+ parse_number,
+ gsm8k_gold_answer,
+)
+from src.post_training.rewards.verifiers import (
+ reward_gsm8k,
+ reward_arithmetic,
+ reward_format,
+ is_correct,
+)
+
+__all__ = [
+ "extract_answer",
+ "extract_think",
+ "parse_number",
+ "gsm8k_gold_answer",
+ "reward_gsm8k",
+ "reward_arithmetic",
+ "reward_format",
+ "is_correct",
+]
diff --git a/src/post_training/rewards/parsing.py b/src/post_training/rewards/parsing.py
new file mode 100644
index 0000000..1c14cda
--- /dev/null
+++ b/src/post_training/rewards/parsing.py
@@ -0,0 +1,80 @@
+"""
+Tolerant parsing of model outputs and gold answers for verifiable rewards.
+
+The model is trained (via SFT) to answer in the form::
+
+ <think> step by step reasoning ... </think><answer>42</answer>
+
+but a small model is inconsistent, so parsing falls back gracefully: prefer an
+``<answer>`` tag, then a GSM8K-style ``#### N``, then the last number in the text.
+"""
+
+from __future__ import annotations
+
+import re
+
+from src.post_training.chat_template import (
+ ANSWER_OPEN, ANSWER_CLOSE, THINK_OPEN, THINK_CLOSE,
+)
+
+# A number: optional sign, digits with optional thousands commas, optional decimal.
+_NUMBER_RE = re.compile(r"-?\$?\d[\d,]*(?:\.\d+)?")
+_ANSWER_RE = re.compile(re.escape(ANSWER_OPEN) + r"(.*?)" + re.escape(ANSWER_CLOSE), re.DOTALL)
+_THINK_RE = re.compile(re.escape(THINK_OPEN) + r"(.*?)" + re.escape(THINK_CLOSE), re.DOTALL)
+_HASH_RE = re.compile(r"####\s*(-?\$?\d[\d,]*(?:\.\d+)?)")
+
+
+def parse_number(s: str | None) -> float | None:
+ """Parse the first number out of a string, tolerating ``$`` and thousands commas."""
+ if s is None:
+ return None
+ m = _NUMBER_RE.search(s)
+ if not m:
+ return None
+ raw = m.group(0).replace(",", "").replace("$", "")
+ try:
+ return float(raw)
+ except ValueError:
+ return None
+
+
+def extract_think(text: str) -> str | None:
+ """Return the content of the first ``<think>...</think>`` block, if any."""
+ m = _THINK_RE.search(text)
+ return m.group(1).strip() if m else None
+
+
+def extract_answer(text: str) -> float | None:
+ """
+ Extract the model's final numeric answer with graceful fallback:
+ 1) inside an ``<answer>...</answer>`` tag, else
+ 2) after a GSM8K-style ``#### N``, else
+ 3) the last number appearing anywhere in the text.
+ """
+ m = _ANSWER_RE.search(text)
+ if m:
+ n = parse_number(m.group(1))
+ if n is not None:
+ return n
+ m = _HASH_RE.search(text)
+ if m:
+ n = parse_number(m.group(1))
+ if n is not None:
+ return n
+ nums = _NUMBER_RE.findall(text)
+ if nums:
+ return parse_number(nums[-1])
+ return None
+
+
+def gsm8k_gold_answer(answer_field: str) -> float | None:
+ """Extract the numeric gold answer from a GSM8K ``answer`` field (ends in ``#### N``)."""
+ m = _HASH_RE.search(answer_field)
+ if m:
+ return parse_number(m.group(1))
+ return parse_number(answer_field)
+
+
+def has_well_formed_answer(text: str) -> bool:
+ """True iff there is exactly one well-formed ``<answer>...</answer>`` block."""
+ return len(_ANSWER_RE.findall(text)) == 1
diff --git a/src/post_training/rewards/verifiers.py b/src/post_training/rewards/verifiers.py
new file mode 100644
index 0000000..c78b474
--- /dev/null
+++ b/src/post_training/rewards/verifiers.py
@@ -0,0 +1,51 @@
+"""
+Verifiable reward functions (RLVR). Each maps a decoded model response (+ a gold answer)
+to a scalar reward. The design is deliberately **correctness-dominant** with only a small,
+bounded format bonus, to limit reward hacking (a tiny model will happily emit empty
+``<answer></answer>`` tags or repeat tokens if the format bonus is too large).
+
+Reward decomposition (clipped to [0, 1.2]):
+ +1.0 if the parsed final answer matches the gold answer (exact, with float tolerance)
+ +0.2 if there is exactly one well-formed <answer>...</answer> block (format shaping)
+"""
+
+from __future__ import annotations
+
+import math
+
+from src.post_training.rewards.parsing import extract_answer, has_well_formed_answer
+
+CORRECT_BONUS = 1.0
+FORMAT_BONUS = 0.2
+REWARD_CLIP = 1.2
+FLOAT_TOL = 1e-4
+
+
+def _answers_match(pred: float | None, gold: float | None) -> bool:
+ if pred is None or gold is None:
+ return False
+ return math.isclose(pred, gold, rel_tol=0.0, abs_tol=FLOAT_TOL)
+
+
+def is_correct(text: str, gold: float | None) -> bool:
+ """Whether the model's parsed answer matches the gold answer (used for accuracy eval)."""
+ return _answers_match(extract_answer(text), gold)
+
+
+def reward_gsm8k(text: str, gold: float | None) -> float:
+ """Reward for a GSM8K response: correctness (dominant) + small format bonus, clipped."""
+ r = 0.0
+ if _answers_match(extract_answer(text), gold):
+ r += CORRECT_BONUS
+ if has_well_formed_answer(text):
+ r += FORMAT_BONUS
+ return min(r, REWARD_CLIP)
+
+
+# Arithmetic warm-up uses the same logic (gold is a single number).
+reward_arithmetic = reward_gsm8k
+
+
+def reward_format(text: str) -> float:
+ """Pure format reward (no gold): 1.0 if exactly one well-formed answer block else 0."""
+ return 1.0 if has_well_formed_answer(text) else 0.0
diff --git a/src/post_training/rollout.py b/src/post_training/rollout.py
new file mode 100644
index 0000000..2dbbc65
--- /dev/null
+++ b/src/post_training/rollout.py
@@ -0,0 +1,293 @@
+"""
+Generation + per-token log-probability utilities -- the shared core of every RL
+algorithm here (PPO and GRPO).
+
+These are FREE FUNCTIONS rather than methods on ``Transformer`` on purpose: the exact
+same log-prob math has to be run against four different parameter sets during PPO/GRPO
+(the trainable policy, the frozen reference, the old-policy snapshot, and -- for the
+value head -- the actor-critic wrapper), so ``f(model, ...)`` composes far better than a
+bound method and keeps the educational model file untouched.
+
+Two key constraints from the repo's model:
+- Learned absolute positions cap any sequence at ``context_length``; we enforce
+ ``prompt_len + max_new_tokens <= context_length``.
+- There is no padding-aware attention mask, so callers pass **equal-length** prompts
+ (length-bucketed). Padding only ever appears AFTER a row hits its stop token, and the
+ ``response_mask`` makes the loss ignore it.
+
+Numerical note: log-probs are always taken in fp32 (``logits.float()``) even under bf16
+autocast, because PPO/GRPO/DPO subtract log-probs and bf16 rounding there is harmful.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+import torch
+import torch.nn.functional as F
+
+from src.post_training.chat_template import EOT_ID
+
+
+@dataclass
+class RolloutBatch:
+ """Result of :func:`generate_with_logprobs`.
+
+ Attributes:
+ sequences: (B, P+G) prompt tokens followed by generated tokens.
+ response_mask: (B, P+G) bool. True only on generated positions that are real
+ (not post-stop padding); always False over the prompt.
+ gen_logprobs: (B, G) log-prob of each generated token under the sampling policy
+ (full-distribution log-prob at the sampling temperature). 0 on
+ padded/finished positions.
+ prompt_len: int P, the (shared) prompt length.
+ """
+
+ sequences: torch.Tensor
+ response_mask: torch.Tensor
+ gen_logprobs: torch.Tensor
+ prompt_len: int
+
+
+def _logits_from(model, idx: torch.Tensor) -> torch.Tensor:
+ """Get logits whether ``model`` returns ``(logits, loss)`` (Transformer) or
+ ``(logits, values)`` (value-head wrapper) or a bare logits tensor."""
+ out = model(idx)
+ return out[0] if isinstance(out, tuple) else out
+
+
+def filter_logits(
+ logits: torch.Tensor,
+ temperature: float = 1.0,
+ top_k: int | None = None,
+ top_p: float | None = None,
+) -> torch.Tensor:
+ """
+ Apply temperature, then optional top-k and nucleus (top-p) filtering to a batch of
+ next-token logits ``(B, vocab)``. Returns logits with filtered entries set to -inf,
+ ready to softmax-and-sample. Used ONLY to build the sampling distribution; the
+ log-prob we record for the ratio is the full-distribution log-prob (see
+ :func:`generate_with_logprobs`).
+ """
+ if temperature != 1.0:
+ logits = logits / max(temperature, 1e-6)
+
+ if top_k is not None and top_k > 0:
+ k = min(top_k, logits.size(-1))
+ kth = torch.topk(logits, k, dim=-1).values[..., -1, None]
+ logits = logits.masked_fill(logits < kth, float("-inf"))
+
+ if top_p is not None and 0.0 < top_p < 1.0:
+ sorted_logits, sorted_idx = torch.sort(logits, descending=True, dim=-1)
+ cumprobs = sorted_logits.softmax(dim=-1).cumsum(dim=-1)
+ remove = cumprobs > top_p
+ # Keep at least the top token; shift so the token that crosses top_p stays.
+ remove[..., 1:] = remove[..., :-1].clone()
+ remove[..., 0] = False
+ remove = remove.scatter(-1, sorted_idx, remove)
+ logits = logits.masked_fill(remove, float("-inf"))
+
+ return logits
+
+
+def generate_with_logprobs(
+ model,
+ prompt_ids: torch.Tensor,
+ max_new_tokens: int,
+ *,
+ temperature: float = 1.0,
+ top_k: int | None = None,
+ top_p: float | None = None,
+ stop_tokens: tuple[int, ...] = (EOT_ID,),
+ pad_id: int = EOT_ID,
+ context_length: int | None = None,
+) -> RolloutBatch:
+ """
+ Autoregressively sample a completion for each prompt and record per-token log-probs.
+
+ ``prompt_ids`` must be (B, P) with a shared length P (length-bucket your prompts).
+ Rows stop individually once they emit any ``stop_tokens``; subsequent positions are
+ filled with ``pad_id`` and excluded from ``response_mask``.
+
+ No KV cache (kept for clarity): each step re-runs the prefix, which is fine for the
+ short sequences here on an H100.
+ """
+ model.eval()
+ device = prompt_ids.device
+ B, P = prompt_ids.shape
+
+ cap = context_length if context_length is not None else getattr(model, "context_length", P + max_new_tokens)
+ cap = getattr(getattr(model, "transformer", model), "context_length", cap)
+ max_new_tokens = min(max_new_tokens, cap - P)
+ if max_new_tokens <= 0:
+ raise ValueError(f"Prompt length {P} leaves no room under context_length {cap}.")
+
+ stop_set = torch.tensor(stop_tokens, device=device)
+ sequences = prompt_ids.clone()
+ gen_logprobs = torch.zeros(B, max_new_tokens, device=device)
+ gen_mask = torch.zeros(B, max_new_tokens, dtype=torch.bool, device=device)
+ finished = torch.zeros(B, dtype=torch.bool, device=device)
+
+ for t in range(max_new_tokens):
+ idx_cond = sequences[:, -cap:]
+ logits = _logits_from(model, idx_cond)[:, -1, :] # (B, vocab)
+
+ # Full-distribution log-prob at the sampling temperature (matches recompute).
+ full_logprobs = F.log_softmax(logits.float() / max(temperature, 1e-6), dim=-1)
+ # Separate truncated distribution to actually sample from.
+ probs = F.softmax(filter_logits(logits, temperature, top_k, top_p), dim=-1)
+ next_tok = torch.multinomial(probs, num_samples=1).squeeze(-1) # (B,)
+
+ active = ~finished
+ token_lp = full_logprobs.gather(-1, next_tok[:, None]).squeeze(-1)
+ # Finished rows emit padding and contribute nothing.
+ next_tok = torch.where(active, next_tok, torch.full_like(next_tok, pad_id))
+ gen_logprobs[:, t] = torch.where(active, token_lp, torch.zeros_like(token_lp))
+ gen_mask[:, t] = active
+
+ sequences = torch.cat([sequences, next_tok[:, None]], dim=1)
+ # A row is finished AFTER (and including) the step where it emits a stop token.
+ hit_stop = (next_tok[:, None] == stop_set).any(dim=-1)
+ finished = finished | (active & hit_stop)
+
+ if bool(finished.all()):
+ # Pad remaining columns so shapes stay (B, max_new_tokens).
+ if t + 1 < max_new_tokens:
+ rem = max_new_tokens - (t + 1)
+ sequences = torch.cat(
+ [sequences, torch.full((B, rem), pad_id, dtype=sequences.dtype, device=device)], dim=1
+ )
+ break
+
+ response_mask = torch.cat(
+ [torch.zeros(B, P, dtype=torch.bool, device=device), gen_mask], dim=1
+ )
+ return RolloutBatch(
+ sequences=sequences,
+ response_mask=response_mask,
+ gen_logprobs=gen_logprobs,
+ prompt_len=P,
+ )
+
+
+def _cap_of(model) -> int:
+ inner = getattr(model, "transformer", model)
+ return getattr(inner, "context_length", 1024)
+
+
+def rollout_prompts(
+ model,
+ prompts: list[list[int]],
+ max_new_tokens: int,
+ *,
+ device: str,
+ temperature: float = 1.0,
+ top_k: int | None = None,
+ top_p: float | None = None,
+ pad_id: int = EOT_ID,
+ micro_batch: int = 64,
+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """
+ Generate one completion per (possibly variable-length) tokenized prompt and merge the
+ results into padded tensors. Length-buckets prompts (the model has no padding-aware
+ attention mask) and pads all rollouts to a common width.
+
+ Returns ``(sequences, response_mask, prompt_lens)``:
+ sequences: (N, Tmax) prompt+response, right-padded with ``pad_id``.
+ response_mask: (N, Tmax) bool, True on real generated tokens.
+ prompt_lens: (N,) prompt length of each row.
+ """
+ cap = _cap_of(model)
+ order = sorted(range(len(prompts)), key=lambda i: len(prompts[i]))
+ pieces = [] # (orig_idxs, sequences, response_mask, prompt_len)
+ i = 0
+ while i < len(order):
+ L = len(prompts[order[i]])
+ j = i
+ while j < len(order) and len(prompts[order[j]]) == L and (j - i) < micro_batch:
+ j += 1
+ idxs = order[i:j]
+ i = j
+ budget = max(1, min(max_new_tokens, cap - L))
+ batch = torch.tensor([prompts[k] for k in idxs], dtype=torch.long, device=device)
+ rb = generate_with_logprobs(model, batch, budget, temperature=temperature,
+ top_k=top_k, top_p=top_p, stop_tokens=(EOT_ID,), pad_id=pad_id)
+ pieces.append((idxs, rb.sequences, rb.response_mask, L))
+
+ N = len(prompts)
+ Tmax = max(seq.size(1) for _, seq, _, _ in pieces)
+ sequences = torch.full((N, Tmax), pad_id, dtype=torch.long, device=device)
+ response_mask = torch.zeros((N, Tmax), dtype=torch.bool, device=device)
+ prompt_lens = torch.zeros(N, dtype=torch.long, device=device)
+ for idxs, seq, rmask, L in pieces:
+ t = seq.size(1)
+ for row, k in enumerate(idxs):
+ sequences[k, :t] = seq[row]
+ response_mask[k, :t] = rmask[row]
+ prompt_lens[k] = L
+ return sequences, response_mask, prompt_lens
+
+
+def compute_logprobs(
+ model,
+ sequences: torch.Tensor,
+ response_mask: torch.Tensor,
+ *,
+ temperature: float = 1.0,
+ requires_grad: bool = True,
+) -> tuple[torch.Tensor, torch.Tensor]:
+ """
+ Teacher-forced recomputation of per-token log-probs of ``sequences`` under ``model``.
+
+ Mirrors the model's training shift: ``logits[:, t]`` predicts ``sequences[:, t+1]``,
+ so the returned tensors have length ``T-1`` and are aligned to target positions
+ ``1..T-1``.
+
+ Args:
+ sequences: (B, T) token ids (prompt + response).
+ response_mask: (B, T) bool over response positions (as from :class:`RolloutBatch`).
+ temperature: divide logits by this before log-softmax, matching sampling.
+ requires_grad: if False, runs under ``no_grad`` (use for ref / old-policy).
+
+ Returns:
+ (logprobs, mask) each (B, T-1). ``logprobs`` is the log-prob of the realized
+ next token; ``mask`` is the response mask shifted to align with those targets.
+ """
+ ctx = torch.enable_grad() if requires_grad else torch.no_grad()
+ with ctx:
+ logits = _logits_from(model, sequences)[:, :-1, :] # predict tokens 1..T-1
+ logprobs_all = F.log_softmax(logits.float() / max(temperature, 1e-6), dim=-1)
+ targets = sequences[:, 1:].unsqueeze(-1)
+ logprobs = logprobs_all.gather(-1, targets).squeeze(-1) # (B, T-1)
+ mask = response_mask[:, 1:].to(torch.bool)
+ return logprobs, mask
+
+
+def sequence_logprobs(
+ model,
+ sequences: torch.Tensor,
+ response_mask: torch.Tensor,
+ *,
+ temperature: float = 1.0,
+ requires_grad: bool = True,
+) -> tuple[torch.Tensor, torch.Tensor]:
+ """
+ Sequence-level summed log-prob over response tokens (used by DPO/KTO/ORPO).
+
+ Returns ``(sum_logprob, n_tokens)`` each shape (B,). The per-token mean is
+ ``sum_logprob / n_tokens.clamp(min=1)``.
+ """
+ lp, mask = compute_logprobs(model, sequences, response_mask, temperature=temperature, requires_grad=requires_grad)
+ m = mask.to(lp.dtype)
+ return (lp * m).sum(dim=-1), m.sum(dim=-1)
+
+
+def sequence_entropy(model, sequences: torch.Tensor, temperature: float = 1.0) -> torch.Tensor:
+ """Per-token predictive entropy ``(B, T-1)`` of ``model`` on ``sequences`` (for an
+ optional PPO entropy bonus / diagnostics)."""
+ with torch.no_grad():
+ logits = _logits_from(model, sequences)[:, :-1, :]
+ logp = F.log_softmax(logits.float() / max(temperature, 1e-6), dim=-1)
+ return -(logp.exp() * logp).sum(dim=-1)
diff --git a/src/post_training/sft.py b/src/post_training/sft.py
new file mode 100644
index 0000000..c7ee5b7
--- /dev/null
+++ b/src/post_training/sft.py
@@ -0,0 +1,63 @@
+"""
+Supervised Fine-Tuning (SFT) core: a prompt-masked language-modeling loss and a
+sequence-packing utility.
+
+The only difference from ordinary next-token pretraining is the per-token ``loss_mask``:
+we train the model to produce the *assistant* tokens (mask=1) but not to reproduce the
+prompt / role markers (mask=0). The mask comes from
+:func:`src.post_training.chat_template.encode_chat`.
+"""
+
+from __future__ import annotations
+
+import numpy as np
+import torch
+import torch.nn.functional as F
+
+
+def sft_loss(logits: torch.Tensor, tokens: torch.Tensor, loss_mask: torch.Tensor) -> torch.Tensor:
+ """
+ Masked next-token cross-entropy.
+
+ Args:
+ logits: (B, T, V) model logits for ``tokens``.
+ tokens: (B, T) packed token ids.
+ loss_mask: (B, T) 1 on tokens that should be predicted (assistant completions).
+
+ Returns:
+ Scalar loss averaged over masked target positions.
+ """
+ # Predict token t+1 from position t (same shift the base model uses).
+ logits = logits[:, :-1, :]
+ targets = tokens[:, 1:]
+ mask = loss_mask[:, 1:].to(logits.dtype)
+
+ V = logits.size(-1)
+ ce = F.cross_entropy(logits.reshape(-1, V).float(), targets.reshape(-1).long(), reduction="none")
+ ce = ce.view(targets.shape) * mask
+ return ce.sum() / mask.sum().clamp(min=1.0)
+
+
+def pack_examples(
+ examples: list[tuple[list[int], list[int]]],
+ context_length: int,
+) -> tuple[np.ndarray, np.ndarray]:
+ """
+ Pack a list of ``(ids, loss_mask)`` examples into fixed-length ``context_length``
+ rows by concatenating them and slicing. Examples are already EOT-terminated by the
+ chat template, so the EOT acts as the separator between packed examples. Trailing
+ tokens that don't fill a full row are dropped.
+
+ Returns:
+ (tokens, masks) int arrays of shape (N, context_length).
+ """
+ flat_ids: list[int] = []
+ flat_mask: list[int] = []
+ for ids, mask in examples:
+ flat_ids.extend(ids)
+ flat_mask.extend(mask)
+
+ n_rows = len(flat_ids) // context_length
+ ids_arr = np.asarray(flat_ids[: n_rows * context_length], dtype=np.int32).reshape(n_rows, context_length)
+ mask_arr = np.asarray(flat_mask[: n_rows * context_length], dtype=np.int8).reshape(n_rows, context_length)
+ return ids_arr, mask_arr
diff --git a/src/post_training/utils.py b/src/post_training/utils.py
new file mode 100644
index 0000000..9c24dfe
--- /dev/null
+++ b/src/post_training/utils.py
@@ -0,0 +1,178 @@
+"""
+Shared helpers for the post-training stack: model construction from configs,
+frozen reference/old-policy copies, checkpoint I/O (keeping the repo's existing
+checkpoint shape), masked reductions, and seeding.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import copy
+import os
+import random
+from dataclasses import asdict, is_dataclass
+from typing import Any
+
+import numpy as np
+import torch
+import torch.nn as nn
+
+from src.models.transformer import Transformer
+
+
+def amp_autocast(amp_dtype: str | None, device: str):
+ """Return a bf16 autocast context on CUDA when requested, else a no-op context.
+
+ bf16 needs no GradScaler (unlike fp16), which keeps the training loops clean.
+ """
+ if amp_dtype == "bf16" and str(device).startswith("cuda") and torch.cuda.is_available():
+ return torch.autocast(device_type="cuda", dtype=torch.bfloat16)
+ return contextlib.nullcontext()
+
+
+# --- Reproducibility ---------------------------------------------------------
+
+def set_seed(seed: int) -> None:
+ """Seed python / numpy / torch (incl. CUDA) for reproducible runs."""
+ random.seed(seed)
+ np.random.seed(seed)
+ torch.manual_seed(seed)
+ torch.cuda.manual_seed_all(seed)
+
+
+# --- Model construction ------------------------------------------------------
+
+def _cfg_get(cfg: Any, key: str) -> Any:
+ """Read a field from either a dataclass/object (attr) or a dict."""
+ if isinstance(cfg, dict):
+ return cfg[key]
+ return getattr(cfg, key)
+
+
+def build_model_from_config(cfg: Any) -> Transformer:
+ """
+ Construct a fresh :class:`Transformer` from a config carrying the standard keys
+ ``n_head, n_embed, context_length, vocab_size, n_blocks``. Works with the new
+ post-training dataclasses and with the legacy ``default_config`` dict.
+ """
+ return Transformer(
+ n_head=_cfg_get(cfg, "n_head"),
+ n_embed=_cfg_get(cfg, "n_embed"),
+ context_length=_cfg_get(cfg, "context_length"),
+ vocab_size=_cfg_get(cfg, "vocab_size"),
+ N_BLOCKS=_cfg_get(cfg, "n_blocks"),
+ )
+
+
+def _strip_ddp_prefix(state_dict: dict) -> dict:
+ """Remove a leading ``module.`` from keys saved by DistributedDataParallel."""
+ if any(k.startswith("module.") for k in state_dict):
+ return {k.removeprefix("module."): v for k, v in state_dict.items()}
+ return state_dict
+
+
+def load_backbone_from_ckpt(cfg: Any, ckpt_path: str, device: str) -> Transformer:
+ """
+ Build a Transformer from ``cfg`` and load backbone weights from a checkpoint saved
+ by the pretraining script or any post-training stage (``model_state_dict`` key).
+ DDP ``module.`` prefixes are stripped. Auxiliary head weights (value/reward), if
+ present, are ignored here -- wrappers add their own fresh heads.
+ """
+ model = build_model_from_config(cfg)
+ ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False)
+ state = ckpt["model_state_dict"] if "model_state_dict" in ckpt else ckpt
+ state = _strip_ddp_prefix(state)
+ # Keep only keys that belong to the bare Transformer backbone.
+ backbone_keys = set(model.state_dict().keys())
+ filtered = {k: v for k, v in state.items() if k in backbone_keys}
+ missing, unexpected = model.load_state_dict(filtered, strict=False)
+ if missing:
+ print(f"[load_backbone] {len(missing)} missing keys (e.g. {missing[:3]})")
+ return model.to(device)
+
+
+def unwrap(model: nn.Module) -> nn.Module:
+ """Return the underlying module behind a DDP wrapper (or the model itself)."""
+ return model.module if hasattr(model, "module") else model
+
+
+def make_frozen_copy(model: nn.Module, device: str | None = None) -> nn.Module:
+ """
+ Deep-copy a model, put it in eval mode, and disable all gradients. Used for the
+ DPO/PPO/GRPO reference model and the PPO old-policy snapshot. At the ~300M-1B
+ scale this is cheap on an 80GB H100 and is the clearest possible implementation.
+ """
+ ref = copy.deepcopy(unwrap(model))
+ if device is not None:
+ ref = ref.to(device)
+ ref.eval()
+ for p in ref.parameters():
+ p.requires_grad_(False)
+ return ref
+
+
+# --- Masked reductions -------------------------------------------------------
+
+def masked_mean(values: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
+ """Mean of ``values`` over positions where ``mask`` is truthy (safe if mask empty)."""
+ mask = mask.to(values.dtype)
+ total = (values * mask).sum()
+ count = mask.sum().clamp(min=1.0)
+ return total / count
+
+
+def masked_mean_per_row(values: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
+ """Per-row (B,) mean of ``values`` (B,T) over masked positions."""
+ mask = mask.to(values.dtype)
+ total = (values * mask).sum(dim=-1)
+ count = mask.sum(dim=-1).clamp(min=1.0)
+ return total / count
+
+
+def gather_last(values: torch.Tensor, seq_lengths: torch.Tensor) -> torch.Tensor:
+ """
+ Given per-token ``values`` (B, T) and ``seq_lengths`` (B,), return the value at the
+ last real token of each row, i.e. ``values[i, seq_lengths[i]-1]``. This is the
+ InstructGPT convention for reading a scalar reward off a sequence model.
+ """
+ idx = (seq_lengths - 1).clamp(min=0).long()
+ return values[torch.arange(values.size(0), device=values.device), idx]
+
+
+# --- Checkpoint I/O ----------------------------------------------------------
+
+def _cfg_to_dict(cfg: Any) -> Any:
+ return asdict(cfg) if is_dataclass(cfg) else cfg
+
+
+def save_stage_ckpt(
+ path: str,
+ model: nn.Module,
+ optimizer: torch.optim.Optimizer | None,
+ *,
+ stage: str,
+ cfg: Any,
+ step: int,
+ metrics: dict | None = None,
+ extra: dict | None = None,
+) -> None:
+ """
+ Save a checkpoint in the repo's existing shape (``model_state_dict`` /
+ ``optimizer_state_dict``) plus post-training metadata (``stage``, ``cfg``, ``step``,
+ ``metrics``). DDP wrappers are unwrapped first so checkpoints load cleanly on a
+ single GPU.
+ """
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
+ payload = {
+ "model_state_dict": unwrap(model).state_dict(),
+ "optimizer_state_dict": optimizer.state_dict() if optimizer is not None else None,
+ "stage": stage,
+ "cfg": _cfg_to_dict(cfg),
+ "step": step,
+ "metrics": metrics or {},
+ "pytorch_version": torch.__version__,
+ "cuda_version": torch.version.cuda,
+ }
+ if extra:
+ payload.update(extra)
+ torch.save(payload, path)
diff --git a/src/post_training/value_head.py b/src/post_training/value_head.py
new file mode 100644
index 0000000..2f94809
--- /dev/null
+++ b/src/post_training/value_head.py
@@ -0,0 +1,56 @@
+"""
+Actor-critic wrapper for PPO.
+
+PPO needs a per-token *value* estimate V(s_t) alongside the policy logits. We get both
+from a single backbone: the wrapper reuses the :class:`Transformer`'s ``forward_hidden``
+and ``lm_head`` for the policy, and adds a small scalar value head on top of the same
+hidden states. Sharing the backbone is the standard, memory-cheap choice; the value head
+is initialized to output ~0 so early training is stable.
+"""
+
+from __future__ import annotations
+
+import torch
+import torch.nn as nn
+
+from src.models.transformer import Transformer
+
+
+class TransformerWithValueHead(nn.Module):
+ """Wrap a :class:`Transformer` and add a scalar value head for PPO.
+
+ ``forward(idx)`` returns ``(logits, values)`` where ``logits`` are the policy logits
+ (B, T, vocab) and ``values`` are per-token value estimates (B, T).
+ """
+
+ def __init__(self, transformer: Transformer) -> None:
+ super().__init__()
+ self.transformer = transformer
+ n_embed = transformer.lm_head.in_features
+ self.value_head = nn.Sequential(
+ nn.Linear(n_embed, n_embed),
+ nn.ReLU(),
+ nn.Linear(n_embed, 1),
+ )
+ # Start with values ~0 so the critic does not destabilize the policy early on.
+ last = self.value_head[-1]
+ nn.init.zeros_(last.weight)
+ nn.init.zeros_(last.bias)
+
+ # Expose the backbone's context length so rollout's cap detection works.
+ @property
+ def context_length(self) -> int:
+ return self.transformer.context_length
+
+ def forward(self, idx: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
+ hidden = self.transformer.forward_hidden(idx) # (B, T, n_embed)
+ logits = self.transformer.lm_head(hidden) # (B, T, vocab)
+ values = self.value_head(hidden).squeeze(-1) # (B, T)
+ return logits, values
+
+ @torch.no_grad()
+ def value_only(self, idx: torch.Tensor) -> torch.Tensor:
+ """Per-token values without computing the (large) vocab logits -- used when
+ scoring rollouts where only V(s_t) is needed."""
+ hidden = self.transformer.forward_hidden(idx)
+ return self.value_head(hidden).squeeze(-1)
diff --git a/tests/gpu_verify.sh b/tests/gpu_verify.sh
new file mode 100644
index 0000000..1969fe0
--- /dev/null
+++ b/tests/gpu_verify.sh
@@ -0,0 +1,51 @@
+#!/usr/bin/env bash
+# End-to-end GPU verification: run EVERY post-training script for a few steps on the GPU,
+# on the REAL prepared datasets, with a tiny model (fits in the spare VRAM next to the
+# running pretraining). Proves the full pipeline works on GPU + real data, not just CPU.
+set -uo pipefail
+cd "$(dirname "$0")/.."
+export PYTHONPATH=. HF_HOME=/ephemeral/hf_cache PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+export CUDA_VISIBLE_DEVICES=${CUDA_VISIBLE_DEVICES:-0}
+PY=/ephemeral/venv/bin/python
+DIM="--vocab_size 50304 --context_length 1024 --n_embed 128 --n_head 4 --n_blocks 2 --device cuda --amp_dtype bf16"
+CK=/ephemeral/ckpts/tiny_base.pt
+ok() { echo " [PASS] $1"; }; bad() { echo " [FAIL] $1"; }
+
+echo "== 1/6 SFT on real sft_packed.h5 (GPU) =="
+$PY scripts/train_sft.py $DIM --pretrained_ckpt $CK --data_path /ephemeral/data/sft_packed.h5 \
+ --out_ckpt /ephemeral/ckpts/gpuverify_sft.pt --batch_size 8 --epochs 1 --max_steps 12 \
+ --eval_steps 1000 --warmup_steps 2 --save_every 1000 2>&1 | grep -E "step [0-9]+/|Done SFT" | tail -2 \
+ && [ -f /ephemeral/ckpts/gpuverify_sft.pt ] && ok "SFT ran on GPU + saved" || bad "SFT"
+
+echo "== 2/6 Reward Model on real preferences.jsonl (GPU) =="
+$PY scripts/train_reward.py $DIM --sft_ckpt $CK --pref_path /ephemeral/data/prefs_small.jsonl \
+ --out_ckpt /ephemeral/ckpts/gpuverify_reward.pt --batch_size 8 --epochs 1 --eval_steps 1000 \
+ --warmup_steps 2 --max_len 512 --save_every 1000 2>&1 | grep -E "step [0-9]+/|Done RM" | tail -2 \
+ && [ -f /ephemeral/ckpts/gpuverify_reward.pt ] && ok "Reward ran on GPU + saved" || bad "Reward"
+# truncate to a few steps by capping rows via a tiny pref file
+echo "== 3/6 DPO on real preferences.jsonl (GPU) =="
+$PY scripts/train_dpo.py $DIM --sft_ckpt $CK --pref_path /ephemeral/data/prefs_small.jsonl \
+ --out_ckpt /ephemeral/ckpts/gpuverify_dpo.pt --loss_type dpo --beta 0.1 --batch_size 8 --epochs 1 \
+ --eval_steps 1000 --warmup_steps 2 --max_len 512 --save_every 1000 2>&1 | grep -E "step [0-9]+/|Done DPO" | tail -2 \
+ && [ -f /ephemeral/ckpts/gpuverify_dpo.pt ] && ok "DPO ran on GPU + saved" || bad "DPO"
+
+echo "== 4/6 PPO on real GSM8K prompts, verifier reward (GPU) =="
+$PY scripts/train_ppo.py $DIM --sft_ckpt $CK --prompt_path /ephemeral/data/rl_prompts_train.jsonl \
+ --reward_source verifier --iterations 2 --prompts_per_iter 4 --rollout_len 48 --ppo_epochs 2 \
+ --minibatch_size 2 --eval_every 1000 --save_every 1000 --out_ckpt /ephemeral/ckpts/gpuverify_ppo.pt \
+ 2>&1 | grep -E "iter [0-9]+|Done PPO" | tail -2 \
+ && [ -f /ephemeral/ckpts/gpuverify_ppo.pt ] && ok "PPO ran on GPU + saved" || bad "PPO"
+
+echo "== 5/6 GRPO on real arithmetic+GSM8K prompts (GPU) =="
+$PY scripts/train_grpo.py $DIM --sft_ckpt $CK --curriculum_path /ephemeral/data/arithmetic_prompts.jsonl \
+ --prompt_path /ephemeral/data/rl_prompts_train.jsonl --curriculum_iters 1 --iterations 2 \
+ --prompts_per_iter 2 --group_size 4 --rollout_len 48 --grpo_epochs 1 --eval_every 1000 --save_every 1000 \
+ --out_ckpt /ephemeral/ckpts/gpuverify_grpo.pt 2>&1 | grep -E "iter [0-9]+|Done GRPO" | tail -2 \
+ && [ -f /ephemeral/ckpts/gpuverify_grpo.pt ] && ok "GRPO ran on GPU + saved" || bad "GRPO"
+
+echo "== 6/6 GSM8K eval benchmark on GPU =="
+$PY scripts/eval_post_training.py --ckpt $CK --label tiny_base --limit 20 --max_new_tokens 48 --device cuda --samples 0 \
+ 2>&1 | grep -E "GSM8K test accuracy" | tail -1 \
+ && ok "GSM8K eval ran on GPU" || bad "eval"
+
+echo "== cleanup =="; rm -f /ephemeral/ckpts/gpuverify_*.pt; echo "done"
diff --git a/tests/grpo_live.py b/tests/grpo_live.py
new file mode 100644
index 0000000..9ea8c06
--- /dev/null
+++ b/tests/grpo_live.py
@@ -0,0 +1,31 @@
+"""Live-progress GRPO-ascends-reward proof (prints every few iters). See verify_rl_optimizes.py."""
+import torch
+from src.models.transformer import Transformer
+from src.post_training.grpo import group_advantages, grpo_loss
+from src.post_training.rollout import generate_with_logprobs, compute_logprobs
+from src.post_training.utils import make_frozen_copy, set_seed
+
+VOCAB, TARGET, PL, GEN, G = 64, 7, 4, 8, 8
+set_seed(0)
+dev = "cuda" if torch.cuda.is_available() else "cpu"
+policy = Transformer(n_head=4, n_embed=64, context_length=PL + GEN + 2, vocab_size=VOCAB, N_BLOCKS=2).to(dev)
+ref = make_frozen_copy(policy, device=dev)
+opt = torch.optim.Adam(policy.parameters(), lr=1e-2)
+prompt = torch.zeros(G, PL, dtype=torch.long, device=dev)
+hist = []
+for it in range(40):
+ rb = generate_with_logprobs(policy, prompt, GEN, temperature=1.0)
+ seqs, rmask = rb.sequences, rb.response_mask
+ rew = torch.tensor([(seqs[i, PL:] == TARGET).float().mean().item() for i in range(G)], device=dev)
+ adv = group_advantages(rew, G)
+ old, _ = compute_logprobs(policy, seqs, rmask, requires_grad=False)
+ rf, _ = compute_logprobs(ref, seqs, rmask, requires_grad=False)
+ new, _ = compute_logprobs(policy, seqs, rmask, requires_grad=True)
+ loss, _ = grpo_loss(new, old, rf, adv, rmask[:, 1:], clip=0.2, kl_coef=0.0)
+ opt.zero_grad(); loss.backward(); opt.step()
+ hist.append(rew.mean().item())
+ if it % 5 == 0 or it == 39:
+ print(f"iter {it:2d} | mean reward (P[target token]) = {rew.mean().item():.3f}", flush=True)
+start, end = sum(hist[:5]) / 5, sum(hist[-5:]) / 5
+verdict = "PASS (RL ascends reward)" if end > start + 0.2 else "NO IMPROVEMENT"
+print(f"\nRESULT: reward {start:.3f} -> {end:.3f} => {verdict}", flush=True)
diff --git a/tests/test_post_training_smoke.py b/tests/test_post_training_smoke.py
new file mode 100644
index 0000000..64725f2
--- /dev/null
+++ b/tests/test_post_training_smoke.py
@@ -0,0 +1,147 @@
+"""
+Fast smoke tests for the post-training core (no training, no datasets, runs on CPU in
+seconds). Verifies the load-bearing math so bugs surface before the long runs.
+
+Run from the repo root:
+ PYTHONPATH=. python tests/test_post_training_smoke.py
+"""
+
+import torch
+import torch.nn.functional as F
+
+from src.models.transformer import Transformer
+from src.post_training import chat_template as ct
+from src.post_training.rollout import (
+ generate_with_logprobs, compute_logprobs, filter_logits,
+)
+from src.post_training.value_head import TransformerWithValueHead
+from src.post_training.reward_model import RewardModel
+from src.post_training.utils import make_frozen_copy, gather_last, masked_mean, build_model_from_config
+from src.post_training.rewards import extract_answer, gsm8k_gold_answer, reward_gsm8k, is_correct
+
+
+def _tiny_model(vocab=64, ctx=32):
+ torch.manual_seed(0)
+ return Transformer(n_head=4, n_embed=32, context_length=ctx, vocab_size=vocab, N_BLOCKS=2)
+
+
+def test_forward_hidden_matches_forward():
+ m = _tiny_model().eval()
+ idx = torch.randint(0, 64, (2, 10))
+ with torch.no_grad():
+ logits_a, _ = m(idx)
+ logits_b = m.lm_head(m.forward_hidden(idx))
+ assert torch.allclose(logits_a, logits_b, atol=1e-5), "forward_hidden must reproduce forward logits"
+ print("ok forward_hidden matches forward")
+
+
+def test_compute_logprobs_matches_manual():
+ m = _tiny_model().eval()
+ seq = torch.randint(0, 64, (3, 12))
+ mask = torch.ones_like(seq, dtype=torch.bool)
+ lp, shifted = compute_logprobs(m, seq, mask, temperature=1.0, requires_grad=False)
+ with torch.no_grad():
+ logits = m(seq)[0][:, :-1, :]
+ manual = F.log_softmax(logits.float(), dim=-1).gather(-1, seq[:, 1:, None]).squeeze(-1)
+ assert torch.allclose(lp, manual, atol=1e-5), "compute_logprobs disagrees with manual log_softmax/gather"
+ assert shifted.shape == (3, 11)
+ print("ok compute_logprobs matches manual computation")
+
+
+def test_rollout_logprobs_consistent():
+ # Recorded sampling log-probs must equal a teacher-forced recompute under the same model+temp.
+ m = _tiny_model().eval()
+ prompt = torch.randint(0, 64, (4, 5))
+ rb = generate_with_logprobs(m, prompt, max_new_tokens=10, temperature=1.0, top_k=None, top_p=None)
+ assert rb.sequences.shape[1] == 5 + 10
+ assert rb.response_mask[:, :5].sum() == 0, "prompt positions must not be in response_mask"
+ lp, shifted = compute_logprobs(m, rb.sequences, rb.response_mask, temperature=1.0, requires_grad=False)
+ # Align recorded gen_logprobs (B,G) to shifted recompute on generated positions.
+ recorded = rb.gen_logprobs[rb.response_mask[:, 5:]]
+ recomputed = lp[shifted]
+ assert torch.allclose(recorded, recomputed, atol=1e-4), "sampling vs recompute log-probs diverge"
+ print(f"ok rollout/recompute log-probs consistent ({recorded.numel()} response tokens)")
+
+
+def test_context_cap_enforced():
+ m = _tiny_model(ctx=16).eval()
+ prompt = torch.randint(0, 64, (1, 10))
+ rb = generate_with_logprobs(m, prompt, max_new_tokens=100) # asks for too many
+ assert rb.sequences.shape[1] <= 16, "must clamp prompt+gen to context_length"
+ print("ok context_length cap enforced")
+
+
+def test_value_and_reward_heads():
+ m = _tiny_model()
+ actor = TransformerWithValueHead(m)
+ idx = torch.randint(0, 64, (2, 8))
+ logits, values = actor(idx)
+ assert logits.shape == (2, 8, 64) and values.shape == (2, 8)
+ values.sum().backward() # critic path differentiable
+ assert actor.value_head[0].weight.grad is not None
+
+ rm = RewardModel(_tiny_model())
+ lengths = torch.tensor([8, 5])
+ r = rm(idx, seq_lengths=lengths)
+ assert r.shape == (2,)
+ r.sum().backward()
+ assert rm.reward_head.weight.grad is not None
+ print("ok value head + reward head shapes and backprop")
+
+
+def test_frozen_copy_and_reductions():
+ m = _tiny_model()
+ ref = make_frozen_copy(m, device="cpu")
+ assert all(not p.requires_grad for p in ref.parameters())
+ vals = torch.tensor([[1.0, 2.0, 3.0]])
+ mask = torch.tensor([[1, 1, 0]])
+ assert abs(masked_mean(vals, mask).item() - 1.5) < 1e-6
+ last = gather_last(torch.tensor([[10.0, 20.0, 30.0]]), torch.tensor([2]))
+ assert last.item() == 20.0
+ print("ok frozen copy + masked_mean + gather_last")
+
+
+def test_chat_template_masking():
+ msgs = [{"role": "user", "content": "What is 2+2?"},
+ {"role": "assistant", "content": "<answer>4</answer>"}]
+ ids, mask = ct.encode_chat(msgs)
+ assert len(ids) == len(mask)
+ assert ids[-1] == ct.EOT_ID and mask[-1] == 1, "assistant turn must end in a trained EOT"
+ # The assistant content tokens should be the only masked-in region (plus its EOT).
+ assert sum(mask) > 0 and sum(mask) < len(mask)
+ prompt_ids = ct.encode_prompt(msgs[:1])
+ assert ct.decode(prompt_ids).endswith(ct.ASSISTANT_HEADER)
+ print(f"ok chat template ids/mask aligned ({sum(mask)}/{len(mask)} trained tokens)")
+
+
+def test_reward_parsing():
+ assert gsm8k_gold_answer("She has 18 apples.\n#### 18") == 18.0
+ assert extract_answer("blah <answer>42</answer> done") == 42.0
+ assert extract_answer("the total is 1,234 dollars") == 1234.0
+ assert is_correct("<answer>42</answer>", 42.0)
+ assert reward_gsm8k("<answer>42</answer>", 42.0) > 1.0 # correct + format
+ assert reward_gsm8k("<answer>7</answer>", 42.0) == 0.2 # wrong but formatted
+ assert reward_gsm8k("the answer is 42", 42.0) == 1.0 # correct, no format bonus
+ print("ok reward parsing + verifier scoring")
+
+
+def test_build_from_config():
+ from config.post_training_config import smoke, SFTConfig
+ cfg = smoke(SFTConfig)
+ m = build_model_from_config(cfg)
+ assert m.context_length == 64 and m.lm_head.out_features == 256
+ print("ok build_model_from_config from dataclass")
+
+
+if __name__ == "__main__":
+ torch.manual_seed(0)
+ test_forward_hidden_matches_forward()
+ test_compute_logprobs_matches_manual()
+ test_rollout_logprobs_consistent()
+ test_context_cap_enforced()
+ test_value_and_reward_heads()
+ test_frozen_copy_and_reductions()
+ test_chat_template_masking()
+ test_reward_parsing()
+ test_build_from_config()
+ print("\nALL SMOKE TESTS PASSED")
diff --git a/tests/test_rl_math.py b/tests/test_rl_math.py
new file mode 100644
index 0000000..8c500d5
--- /dev/null
+++ b/tests/test_rl_math.py
@@ -0,0 +1,87 @@
+"""
+Unit tests for the from-scratch RL math (PPO + GRPO). Pure-CPU, runs in milliseconds.
+
+ PYTHONPATH=. python tests/test_rl_math.py
+"""
+
+import torch
+
+from src.post_training.ppo import compute_gae, whiten, ppo_policy_loss, ppo_value_loss, approx_kl
+from src.post_training.grpo import group_advantages, grpo_loss, k3_kl
+
+
+def test_gae_reward_to_go():
+ # lambda=1, zero values -> advantage is plain reward-to-go (=1 everywhere here).
+ r = torch.tensor([[0.0, 0.0, 1.0]])
+ v = torch.zeros(1, 3)
+ m = torch.ones(1, 3, dtype=torch.bool)
+ adv, ret = compute_gae(r, v, v, m, gamma=1.0, lam=1.0)
+ assert torch.allclose(adv, torch.ones(1, 3)), adv
+ assert torch.allclose(ret, torch.ones(1, 3)), ret
+ # lambda<1 discounts earlier advantages.
+ adv2, _ = compute_gae(r, v, v, m, gamma=1.0, lam=0.95)
+ assert adv2[0, 0] < adv2[0, 1] < adv2[0, 2]
+ print("ok GAE reward-to-go + lambda discounting")
+
+
+def test_gae_masks_outside_response():
+ r = torch.tensor([[0.0, 1.0, 0.0]])
+ v = torch.zeros(1, 3)
+ m = torch.tensor([[0, 1, 0]], dtype=torch.bool) # only middle token is a response token
+ adv, ret = compute_gae(r, v, v, m, gamma=1.0, lam=1.0)
+ assert adv[0, 0] == 0 and adv[0, 2] == 0
+ print("ok GAE zeros advantages outside the response")
+
+
+def test_whiten():
+ a = torch.tensor([[1.0, 2.0, 3.0, 0.0]])
+ m = torch.tensor([[1, 1, 1, 0]], dtype=torch.bool)
+ w = whiten(a, m)
+ assert abs(w[0, :3].mean().item()) < 1e-5
+ assert w[0, 3] == 0
+ print("ok whiten: zero-mean over mask, zero outside")
+
+
+def test_ppo_losses():
+ m = torch.ones(1, 3, dtype=torch.bool)
+ # ratio == 1 -> policy loss = -mean(advantage)
+ loss, clipf = ppo_policy_loss(torch.zeros(1, 3), torch.zeros(1, 3), torch.ones(1, 3), m, clip=0.2)
+ assert abs(loss.item() + 1.0) < 1e-5 and clipf.item() == 0.0
+ # value loss = 0.5 * MSE
+ vl = ppo_value_loss(torch.zeros(1, 3), torch.zeros(1, 3), torch.ones(1, 3), m, vf_clip=0.2)
+ assert abs(vl.item() - 0.5) < 1e-5
+ # clipping engages for a large ratio
+ _, cf = ppo_policy_loss(torch.full((1, 3), 1.0), torch.zeros(1, 3), torch.ones(1, 3), m, clip=0.2)
+ assert cf.item() == 1.0
+ print("ok ppo policy/value loss + clip fraction")
+
+
+def test_group_advantages():
+ r = torch.tensor([1.0, 0.0, 0.0, 0.0, 2.0, 2.0, 2.0, 2.0])
+ adv = group_advantages(r, 4)
+ assert abs(adv[:4].mean().item()) < 1e-5
+ assert adv[4:].abs().max().item() < 1e-3 # zero-variance group -> ~zero advantage
+ assert adv[0] > 0 and adv[1] < 0
+ print("ok group_advantages: group-relative, zero-variance group ~0")
+
+
+def test_grpo_loss_and_kl():
+ B, L = 2, 3
+ z = torch.zeros(B, L)
+ m = torch.ones(B, L, dtype=torch.bool)
+ loss, st = grpo_loss(z, z, z, torch.ones(B), m, clip=0.2, kl_coef=0.04)
+ assert abs(loss.item() + 1.0) < 1e-5 # ratio=1, adv=1, kl=0 -> -1
+ assert abs(st["kl"]) < 1e-6
+ kl = k3_kl(torch.tensor([-1.0, 0.5, 0.0]), torch.zeros(3))
+ assert (kl >= 0).all() # k3 KL is non-negative
+ print("ok grpo_loss + non-negative k3 KL")
+
+
+if __name__ == "__main__":
+ test_gae_reward_to_go()
+ test_gae_masks_outside_response()
+ test_whiten()
+ test_ppo_losses()
+ test_group_advantages()
+ test_grpo_loss_and_kl()
+ print("\nALL RL MATH TESTS PASSED")
diff --git a/tests/verify_data_and_eval.py b/tests/verify_data_and_eval.py
new file mode 100644
index 0000000..4a8ca5a
--- /dev/null
+++ b/tests/verify_data_and_eval.py
@@ -0,0 +1,137 @@
+"""
+Deep correctness checks on the REAL prepared data and the evaluation benchmark.
+No training, no GPU -- inspects the actual files on disk and the scoring logic.
+
+ PYTHONPATH=. python tests/verify_data_and_eval.py
+"""
+
+import json
+
+import h5py
+import numpy as np
+
+from src.post_training.chat_template import EOT_ID, decode, encode_chat, ASSISTANT_HEADER
+from src.post_training.rewards import gsm8k_gold_answer, extract_answer, is_correct, reward_gsm8k
+
+DATA = "/ephemeral/data"
+PASS, FAIL = "PASS", "FAIL"
+
+
+def check(name, cond, detail=""):
+ print(f" [{PASS if cond else FAIL}] {name}" + (f" -- {detail}" if detail else ""))
+ assert cond, f"FAILED: {name} {detail}"
+
+
+def verify_pile():
+ print("\n== Pile pretraining HDF5 ==")
+ for split, path in [("train", f"{DATA}/pile_train.h5"), ("dev", f"{DATA}/pile_dev.h5")]:
+ with h5py.File(path, "r") as f:
+ d = f["tokens"]
+ n = d.shape[0]
+ head = np.asarray(d[:100000])
+ check(f"{split}: nonempty", n > 1_000_000, f"{n:,} tokens")
+ check(f"{split}: token ids in [0,50256]", head.min() >= 0 and head.max() <= 50256,
+ f"min {head.min()} max {head.max()}")
+ check(f"{split}: contains EOT separators", (head == EOT_ID).sum() > 0,
+ f"{int((head==EOT_ID).sum())} EOT in first 100k")
+
+
+def verify_sft_mask_alignment():
+ """The critical SFT check: the loss_mask must be 1 EXACTLY on assistant-completion
+ tokens and 0 on the prompt / role markers. We decode masked vs unmasked spans of a
+ real packed row and confirm they read like completion vs prompt."""
+ print("\n== SFT packed data: loss-mask alignment (real data) ==")
+ with h5py.File(f"{DATA}/sft_packed.h5", "r") as f:
+ tokens, masks = f["tokens"], f["loss_mask"]
+ check("packed: nonempty", tokens.shape[0] > 100, f"{tokens.shape[0]} rows x {tokens.shape[1]}")
+ check("packed: tokens/masks aligned shape", tokens.shape == masks.shape)
+ row_t = np.asarray(tokens[0]); row_m = np.asarray(masks[0])
+ check("packed: token ids valid", row_t.min() >= 0 and row_t.max() <= 50303)
+ check("packed: mask is binary", set(np.unique(row_m)).issubset({0, 1}))
+ frac = row_m.mean()
+ check("packed: mask trains a sensible fraction", 0.02 < frac < 0.95, f"{frac:.2f} of tokens trained")
+
+ # Re-derive a single example from the chat template and confirm the mask matches exactly.
+ ids, mask = encode_chat([{"role": "user", "content": "What is 2+2?"},
+ {"role": "assistant", "content": "<answer>4</answer>"}])
+ masked_text = decode([t for t, m in zip(ids, mask) if m == 1])
+ unmasked_text = decode([t for t, m in zip(ids, mask) if m == 0])
+ check("mask covers the assistant answer", "answer>4" in masked_text or "4" in masked_text,
+ f"masked={masked_text!r}")
+ check("mask excludes the user question", "2+2" in unmasked_text and "2+2" not in masked_text,
+ f"unmasked={unmasked_text!r}")
+ check("prompt form ends at assistant header", decode(encode_chat(
+ [{"role": "user", "content": "Hi"}], add_generation_prompt=True)[0]).endswith(ASSISTANT_HEADER))
+
+
+def verify_preferences():
+ print("\n== Preference data (HH-RLHF + UltraFeedback) ==")
+ for path in [f"{DATA}/preferences.jsonl", f"{DATA}/preferences_test.jsonl"]:
+ rows = [json.loads(l) for l in open(path)]
+ check(f"{path.split('/')[-1]}: nonempty", len(rows) > 100, f"{len(rows)} pairs")
+ bad = [r for r in rows[:5000] if not (r.get("prompt") and r.get("chosen") and r.get("rejected"))]
+ check("all pairs have prompt/chosen/rejected", len(bad) == 0)
+ diff = [r for r in rows[:5000] if r["chosen"] == r["rejected"]]
+ check("chosen != rejected", len(diff) == 0, f"{len(diff)} degenerate")
+ # decode-roundtrip a real pair through the chat encoder
+ r = json.loads(open(f"{DATA}/preferences.jsonl").readline())
+ ids, _ = encode_chat([{"role": "user", "content": r["prompt"]}, {"role": "assistant", "content": r["chosen"]}])
+ check("real pair encodes to tokens", len(ids) > 0, f"{len(ids)} tokens")
+
+
+def verify_rl_prompts_and_gold():
+ """Gold answers in the RL prompt files must match the GSM8K dataset's #### answer."""
+ print("\n== RL prompts + gold answers ==")
+ rows = [json.loads(l) for l in open(f"{DATA}/rl_prompts_test.jsonl")]
+ check("gsm8k test prompts present", len(rows) > 100, f"{len(rows)} prompts")
+ check("all have numeric gold", all(isinstance(r["gold"], (int, float)) for r in rows))
+ # Cross-check gold against the live GSM8K dataset for a few rows.
+ import os
+ os.environ.setdefault("HF_HOME", "/ephemeral/hf_cache")
+ from datasets import load_dataset
+ ds = load_dataset("openai/gsm8k", "main", split="test")
+ by_q = {ex["question"].strip(): ex["answer"] for ex in ds}
+ checked = 0
+ for r in rows[:50]:
+ if r["prompt"] in by_q:
+ assert gsm8k_gold_answer(by_q[r["prompt"]]) == r["gold"], (r["prompt"][:40], r["gold"])
+ checked += 1
+ check("gold matches GSM8K #### answer", checked >= 40, f"verified {checked}/50 against source")
+ # arithmetic curriculum gold correctness
+ ar = [json.loads(l) for l in open(f"{DATA}/arithmetic_prompts.jsonl")]
+ check("arithmetic prompts present", len(ar) > 1000, f"{len(ar)} prompts")
+
+
+def verify_eval_benchmark():
+ """Prove the GSM8K scoring is correct independent of any model: a response containing
+ the gold scores correct; a wrong number scores incorrect."""
+ print("\n== Evaluation benchmark scoring (GSM8K verifier) ==")
+ import os
+ os.environ.setdefault("HF_HOME", "/ephemeral/hf_cache")
+ from datasets import load_dataset
+ ds = load_dataset("openai/gsm8k", "main", split="test").select(range(100))
+
+ correct_when_right = correct_when_wrong = 0
+ for ex in ds:
+ gold = gsm8k_gold_answer(ex["answer"])
+ good = f"<think>...</think><answer>{int(gold) if gold==int(gold) else gold}</answer>"
+ bad = f"<answer>{gold + 7}</answer>"
+ correct_when_right += int(is_correct(good, gold))
+ correct_when_wrong += int(is_correct(bad, gold))
+ check("perfect answers score correct", correct_when_right >= 98, f"{correct_when_right}/100")
+ check("wrong answers score incorrect", correct_when_wrong == 0, f"{correct_when_wrong}/100 false positives")
+ # reward shaping: correct+formatted > correct-only > wrong
+ check("reward: correct+format > wrong", reward_gsm8k("<answer>5</answer>", 5.0) > reward_gsm8k("<answer>9</answer>", 5.0))
+ check("reward: bounded", reward_gsm8k("<answer>5</answer>", 5.0) <= 1.2)
+ # tolerant parsing variants
+ check("parse: $ and commas", extract_answer("the total is $1,234") == 1234.0)
+ check("parse: #### form", extract_answer("reasoning #### 18") == 18.0)
+
+
+if __name__ == "__main__":
+ verify_pile()
+ verify_sft_mask_alignment()
+ verify_preferences()
+ verify_rl_prompts_and_gold()
+ verify_eval_benchmark()
+ print("\nALL DATA + EVAL CORRECTNESS CHECKS PASSED")
diff --git a/tests/verify_rl_optimizes.py b/tests/verify_rl_optimizes.py
new file mode 100644
index 0000000..a5240d9
--- /dev/null
+++ b/tests/verify_rl_optimizes.py
@@ -0,0 +1,105 @@
+"""
+Prove the RL machinery actually OPTIMIZES its reward (not just runs without error).
+
+Uses the real GRPO and PPO code paths (rollout -> reward -> advantage -> clipped update)
+on a tiny model with a learnable synthetic reward: "emit the target token". If the loops
+are correct, the policy raises the probability of the target token and the mean reward
+climbs. Runs on CPU in well under a minute (tiny vocab).
+
+ PYTHONPATH=. python tests/verify_rl_optimizes.py
+"""
+
+import torch
+
+from src.models.transformer import Transformer
+from src.post_training.grpo import group_advantages, grpo_loss
+from src.post_training.ppo import compute_gae, whiten, ppo_policy_loss, ppo_value_loss
+from src.post_training.rollout import generate_with_logprobs, compute_logprobs
+from src.post_training.utils import make_frozen_copy, set_seed
+from src.post_training.value_head import TransformerWithValueHead
+
+VOCAB, TARGET = 64, 7
+PROMPT_LEN, GEN = 4, 8
+
+
+def dense_reward(seq, prompt_len, target=TARGET):
+ """Fraction of generated tokens equal to the target token (dense, easy to learn)."""
+ gen = seq[prompt_len:]
+ return (gen == target).float().mean().item()
+
+
+def tiny_model():
+ set_seed(0)
+ return Transformer(n_head=4, n_embed=64, context_length=PROMPT_LEN + GEN + 2, vocab_size=VOCAB, N_BLOCKS=2)
+
+
+def verify_grpo_optimizes():
+ print("\n== GRPO optimizes reward (real grpo_loss path) ==")
+ policy = tiny_model()
+ ref = make_frozen_copy(policy)
+ opt = torch.optim.Adam(policy.parameters(), lr=1e-2)
+ G = 8
+ prompt = torch.zeros(1, PROMPT_LEN, dtype=torch.long)
+ history = []
+ for it in range(60):
+ batch = prompt.repeat(G, 1)
+ rb = generate_with_logprobs(policy, batch, GEN, temperature=1.0)
+ seqs, rmask = rb.sequences, rb.response_mask
+ rewards = torch.tensor([dense_reward(seqs[i], PROMPT_LEN) for i in range(G)])
+ adv = group_advantages(rewards, G)
+ old_lp, _ = compute_logprobs(policy, seqs, rmask, requires_grad=False)
+ ref_lp, _ = compute_logprobs(ref, seqs, rmask, requires_grad=False)
+ new_lp, _ = compute_logprobs(policy, seqs, rmask, requires_grad=True)
+ loss, _ = grpo_loss(new_lp, old_lp, ref_lp, adv, rmask[:, 1:], clip=0.2, kl_coef=0.0)
+ opt.zero_grad(); loss.backward(); opt.step()
+ history.append(rewards.mean().item())
+ start, end = sum(history[:5]) / 5, sum(history[-5:]) / 5
+ print(f" mean reward: start {start:.3f} -> end {end:.3f}")
+ assert end > start + 0.2, f"GRPO did not improve reward ({start:.3f} -> {end:.3f})"
+ print(f" [PASS] GRPO raised P(target token); reward climbed {start:.2f} -> {end:.2f}")
+
+
+def verify_ppo_optimizes():
+ print("\n== PPO optimizes reward (real GAE + clipped losses path) ==")
+ backbone = tiny_model()
+ ref = make_frozen_copy(backbone)
+ actor = TransformerWithValueHead(backbone)
+ opt = torch.optim.Adam(actor.parameters(), lr=1e-2)
+ B = 8
+ prompt = torch.zeros(B, PROMPT_LEN, dtype=torch.long)
+ history = []
+ for it in range(60):
+ rb = generate_with_logprobs(actor, prompt, GEN, temperature=1.0)
+ seqs, rmask = rb.sequences, rb.response_mask
+ resp = rmask[:, 1:]
+ task_r = torch.tensor([dense_reward(seqs[i], PROMPT_LEN) for i in range(B)])
+
+ with torch.no_grad():
+ logits, values = actor(seqs)
+ old_lp, _ = compute_logprobs(actor, seqs, rmask, requires_grad=False)
+ old_v = values[:, :-1]
+ # sparse terminal reward at last response token
+ rewards = torch.zeros_like(resp, dtype=torch.float32)
+ last = resp.float().cumsum(1).argmax(1)
+ rewards[torch.arange(B), last] = task_r
+ vnext = torch.cat([old_v[:, 1:], torch.zeros_like(old_v[:, :1])], 1)
+ adv, ret = compute_gae(rewards, old_v, vnext, resp, gamma=1.0, lam=0.95)
+ adv = whiten(adv, resp)
+ for _ in range(4):
+ logits, values = actor(seqs)
+ new_lp, _ = compute_logprobs(actor, seqs, rmask, requires_grad=True)
+ pl, _ = ppo_policy_loss(new_lp, old_lp, adv, resp, clip=0.2)
+ vl = ppo_value_loss(values[:, :-1], old_v, ret, resp, vf_clip=0.2)
+ loss = pl + 0.5 * vl
+ opt.zero_grad(); loss.backward(); opt.step()
+ history.append(task_r.mean().item())
+ start, end = sum(history[:5]) / 5, sum(history[-5:]) / 5
+ print(f" mean reward: start {start:.3f} -> end {end:.3f}")
+ assert end > start + 0.15, f"PPO did not improve reward ({start:.3f} -> {end:.3f})"
+ print(f" [PASS] PPO raised reward {start:.2f} -> {end:.2f}")
+
+
+if __name__ == "__main__":
+ verify_grpo_optimizes()
+ verify_ppo_optimizes()
+ print("\nRL OPTIMIZATION VERIFIED: both PPO and GRPO increase their reward.")
diff --git a/ui/__init__.py b/ui/__init__.py
new file mode 100644
index 0000000..7261344
--- /dev/null
+++ b/ui/__init__.py
@@ -0,0 +1 @@
+"""Streamlit control-panel package for the training pipeline."""
diff --git a/ui/app.py b/ui/app.py
new file mode 100644
index 0000000..abffd8d
--- /dev/null
+++ b/ui/app.py
@@ -0,0 +1,66 @@
+"""
+Train LLM From Scratch — control panel (Home).
+
+Run with: streamlit run ui/app.py
+"""
+
+from __future__ import annotations
+
+import os
+
+import streamlit as st
+
+from ui import jobs, theme
+from ui.stages import ABS_DOC, STAGES
+
+theme.setup_page("Control Panel", "🧠")
+theme.hero("🧠 Train LLM From Scratch — Control Panel",
+ "Pretrain → SFT → Reward Model → DPO → PPO → GRPO · evaluate · chat — all from one place.")
+
+# Master pipeline diagram (the hand-drawn overview).
+overview = ABS_DOC("docs/diagrams/00_overview.png")
+if os.path.exists(overview):
+ st.image(overview, use_container_width=True)
+
+st.markdown(
+ "Use the **pages in the sidebar** to prepare data, configure and launch each training stage "
+ "(with live logs + metric charts), evaluate on GSM8K, and chat with any checkpoint."
+)
+
+# --- GPU status ---
+st.subheader("🖥️ GPUs")
+gpus = theme.gpu_status()
+if gpus:
+ cols = st.columns(len(gpus))
+ for col, (i, name, used, total, util) in zip(cols, gpus):
+ col.metric(f"GPU {i} · {name.split(' ')[-1]}", f"{used/1024:.0f}/{total/1024:.0f} GB", f"{util}% util")
+else:
+ st.info("No GPUs detected (nvidia-smi unavailable) — CPU / smoke mode only.")
+
+# --- Job status ---
+st.subheader("📋 Jobs")
+busy = jobs.gpu_busy()
+if busy:
+ st.warning(f"A GPU job is currently running: **{busy}**. Other GPU launches are guarded until it finishes.")
+active = jobs.active_jobs()
+if active:
+ for rec in active:
+ s = jobs.status(rec["job_id"])
+ st.markdown(
+ f'<div class="stage-card"><b>{rec["job_id"]}</b> &nbsp; {theme.status_badge(s)} '
+ f'&nbsp; <code>{" ".join(rec["cmd"][:3])} …</code></div>', unsafe_allow_html=True)
+else:
+ st.caption("No jobs launched yet.")
+
+# --- Pipeline map ---
+st.subheader("🗺️ Pipeline")
+for key, sgt in STAGES.items():
+ s = jobs.status(key)
+ st.markdown(
+ f'<div class="stage-card" style="--c:{theme.COLORS.get("model")}">'
+ f'{sgt.emoji} <b>{sgt.title}</b> &nbsp; {theme.status_badge(s)} '
+ f'&nbsp; <span style="opacity:.7">{sgt.script}</span></div>', unsafe_allow_html=True)
+
+st.divider()
+st.caption("Docs: see the MkDocs site (`mkdocs serve`) or the `docs/` folder. "
+ "CLI reference: `POST_TRAINING.md`.")
diff --git a/ui/config_forms.py b/ui/config_forms.py
new file mode 100644
index 0000000..06ada8a
--- /dev/null
+++ b/ui/config_forms.py
@@ -0,0 +1,81 @@
+"""
+Render an editable config form from a stage's dataclass fields and write it back to JSON.
+
+Base/runtime fields (shared) are saved to ``base.json``; the stage's own hyperparameters to
+``configs/<stage>.json`` — matching the loader's merge model. Shows the exact resolved
+launch command underneath.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from dataclasses import fields
+
+import streamlit as st
+
+from config.loader import load_config
+from config.post_training_config import BaseModelConfig
+from ui.jobs import build_argv
+from ui.stages import Stage
+
+_BASE_FIELDS = {f.name for f in fields(BaseModelConfig)}
+
+
+def _widget(f, value):
+ t = str(f.type)
+ label = f.name
+ if t == "bool" or "bool" in t and "|" not in t:
+ return st.checkbox(label, bool(value))
+ if "int" in t and "|" not in t:
+ return int(st.number_input(label, value=int(value), step=1, format="%d"))
+ if "float" in t:
+ return float(st.number_input(label, value=float(value), format="%g"))
+ # str / str|None / unknown -> text; empty string means "unset" (-> null) for optionals
+ return st.text_input(label, "" if value is None else str(value))
+
+
+def _coerce_blank(f, value):
+ """Map an empty text box back to None for optional (``| None``) string fields."""
+ if isinstance(value, str) and value == "" and "None" in str(f.type):
+ return None
+ return value
+
+
+def _write_json(path: str, obj: dict) -> None:
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
+ with open(path, "w") as f:
+ json.dump(obj, f, indent=2)
+ f.write("\n")
+
+
+def render_form(stage: Stage, smoke: bool = False, nproc: int = 1) -> None:
+ json_path = stage.smoke_json if smoke else stage.config_json
+ base_path = os.path.join(os.path.dirname(json_path), "base.json")
+ cur = load_config(stage.cfg_cls, json_path)
+
+ vals: dict = {}
+ with st.expander("🧱 Model & runtime · shared `base.json`", expanded=False):
+ cols = st.columns(2)
+ bf = [f for f in fields(stage.cfg_cls) if f.name in _BASE_FIELDS]
+ for i, f in enumerate(bf):
+ with cols[i % 2]:
+ vals[f.name] = _coerce_blank(f, _widget(f, getattr(cur, f.name)))
+
+ with st.expander(f"⚙️ {stage.title} hyperparameters · `{json_path}`", expanded=True):
+ cols = st.columns(2)
+ sf = [f for f in fields(stage.cfg_cls) if f.name not in _BASE_FIELDS]
+ for i, f in enumerate(sf):
+ with cols[i % 2]:
+ vals[f.name] = _coerce_blank(f, _widget(f, getattr(cur, f.name)))
+
+ if st.button("💾 Save config", key=f"save_{stage.key}_{smoke}"):
+ base_vals = {k: v for k, v in vals.items() if k in _BASE_FIELDS}
+ stage_vals = {k: v for k, v in vals.items() if k not in _BASE_FIELDS}
+ _write_json(base_path, base_vals)
+ _write_json(json_path, stage_vals)
+ st.success(f"Saved → `{base_path}` and `{json_path}`")
+
+ st.caption("Resolved launch command")
+ argv = build_argv(stage.script, json_path, nproc, stage.multi_gpu)
+ st.code(" ".join(argv), language="bash")
diff --git a/ui/docs_render.py b/ui/docs_render.py
new file mode 100644
index 0000000..a7ce3ce
--- /dev/null
+++ b/ui/docs_render.py
@@ -0,0 +1,40 @@
+"""
+Render a ``docs/*.md`` theory page inside Streamlit.
+
+Streamlit's ``st.markdown`` can't load local-disk images and won't render the ``<details>``
+mermaid blocks, so we: (1) show the stage diagram with ``st.image`` (absolute path), and
+(2) strip the markdown image line + the ``<details>…</details>`` mermaid block before
+rendering the prose. The ``docs/*.md`` files stay the single source of truth (the MkDocs
+site publishes the same files).
+"""
+
+from __future__ import annotations
+
+import os
+import re
+
+from ui.stages import ABS_DOC
+
+
+def _clean_markdown(text: str) -> str:
+ # drop the embedded PNG line (we render it via st.image instead)
+ text = re.sub(r"^!\[[^\]]*\]\([^)]*\)\s*$", "", text, flags=re.MULTILINE)
+ # drop the <details>…</details> live-mermaid block
+ text = re.sub(r"<details>.*?</details>", "", text, flags=re.DOTALL)
+ # drop the leading H1 (the page already has a header)
+ text = re.sub(r"^#\s+.*$", "", text, count=1, flags=re.MULTILINE)
+ return text.strip()
+
+
+def render_doc(st, doc_md: str, diagram_png: str | None = None) -> None:
+ """Render the diagram (if any) + the prose of a docs markdown file."""
+ if diagram_png:
+ abs_png = ABS_DOC(diagram_png)
+ if os.path.exists(abs_png):
+ st.image(abs_png, use_container_width=True)
+ abs_md = ABS_DOC(doc_md)
+ if os.path.exists(abs_md):
+ with open(abs_md) as f:
+ st.markdown(_clean_markdown(f.read()))
+ else:
+ st.info(f"Theory doc not found: {doc_md}")
diff --git a/ui/jobs.py b/ui/jobs.py
new file mode 100644
index 0000000..19d0b79
--- /dev/null
+++ b/ui/jobs.py
@@ -0,0 +1,161 @@
+"""
+Background job manager for the control panel.
+
+Launches the real training / data-prep scripts as detached subprocesses, captures their
+output to a logfile, and records a tiny JSON registry under /ephemeral/ui_jobs/ so jobs
+survive Streamlit reruns and page navigation. Includes a GPU-busy guard so we never start a
+second multi-GPU job on top of a running one (which would OOM the H100s).
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import signal
+import subprocess
+import sys
+import time
+
+from ui.stages import REPO_ROOT
+
+JOB_DIR = "/ephemeral/ui_jobs"
+_TORCHRUN = os.path.join(os.path.dirname(sys.executable), "torchrun")
+
+
+def _ensure_job_dir() -> None:
+ os.makedirs(JOB_DIR, exist_ok=True)
+
+
+def _reg(job_id: str) -> str:
+ return os.path.join(JOB_DIR, f"{job_id}.json")
+
+
+def _log(job_id: str) -> str:
+ return os.path.join(JOB_DIR, f"{job_id}.log")
+
+
+def _write_registry(job_id: str, data: dict) -> None:
+ with open(_reg(job_id), "w") as f:
+ json.dump(data, f)
+
+
+def read_registry(job_id: str) -> dict | None:
+ p = _reg(job_id)
+ if not os.path.exists(p):
+ return None
+ try:
+ with open(p) as f:
+ return json.load(f)
+ except json.JSONDecodeError:
+ return None
+
+
+def _alive(pid: int) -> bool:
+ try:
+ os.kill(pid, 0)
+ except OSError:
+ return False
+ # A finished detached child lingers as a zombie (parent = this process) and still
+ # passes kill(pid, 0). Treat zombies as dead and best-effort reap them.
+ try:
+ with open(f"/proc/{pid}/stat") as f:
+ state = f.read().rsplit(") ", 1)[1].split(" ", 1)[0]
+ if state == "Z":
+ try:
+ os.waitpid(pid, os.WNOHANG)
+ except OSError:
+ pass
+ return False
+ except (FileNotFoundError, IndexError):
+ return False
+ return True
+
+
+def build_argv(script: str, config_json: str, nproc: int, multi_gpu: bool, extra: list[str] | None = None) -> list[str]:
+ """Construct the exact command (torchrun for multi-GPU, else python)."""
+ base = [script, "--config", config_json] + (extra or [])
+ if multi_gpu and nproc > 1:
+ return [_TORCHRUN, "--standalone", f"--nproc_per_node={nproc}", *base]
+ return [sys.executable, *base]
+
+
+def launch(job_id: str, argv: list[str], *, kind: str = "cpu") -> dict:
+ """Start ``argv`` as a detached background job. ``kind`` is 'gpu' or 'cpu' (for the guard)."""
+ _ensure_job_dir()
+ log_path = _log(job_id)
+ env = {**os.environ, "PYTHONPATH": REPO_ROOT}
+ env.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
+ env.setdefault("HF_HOME", "/ephemeral/hf_cache")
+ logf = open(log_path, "wb")
+ proc = subprocess.Popen(
+ argv, cwd=REPO_ROOT, env=env, stdout=logf, stderr=subprocess.STDOUT,
+ start_new_session=True, # own process group -> killpg reaches all torchrun ranks
+ )
+ rec = dict(job_id=job_id, pid=proc.pid, cmd=argv, log=log_path, kind=kind,
+ started=time.time(), status="running")
+ _write_registry(job_id, rec)
+ return rec
+
+
+def status(job_id: str) -> str:
+ """Return 'running' | 'finished' | 'failed' | 'none'."""
+ rec = read_registry(job_id)
+ if not rec:
+ return "none"
+ if _alive(rec["pid"]):
+ return "running"
+ tail = tail_log(job_id, 4000).lower()
+ if "traceback" in tail or "error:" in tail or "aborted" in tail:
+ return "failed"
+ return "finished"
+
+
+def stop(job_id: str) -> bool:
+ """Terminate a running job and all its workers (process group)."""
+ rec = read_registry(job_id)
+ if not rec:
+ return False
+ try:
+ os.killpg(os.getpgid(rec["pid"]), signal.SIGTERM)
+ except OSError:
+ return False
+ rec["status"] = "stopped"
+ _write_registry(job_id, rec)
+ return True
+
+
+def tail_log(job_id: str, max_bytes: int = 16000) -> str:
+ p = _log(job_id)
+ if not os.path.exists(p):
+ return ""
+ with open(p, "rb") as f:
+ f.seek(0, os.SEEK_END)
+ size = f.tell()
+ f.seek(max(0, size - max_bytes))
+ return f.read().decode("utf-8", errors="replace")
+
+
+def gpu_busy() -> str | None:
+ """Return the job_id of a *running* GPU job, if any (for the launch guard)."""
+ if not os.path.isdir(JOB_DIR):
+ return None
+ for fn in os.listdir(JOB_DIR):
+ if not fn.endswith(".json"):
+ continue
+ rec = read_registry(fn[:-5])
+ if rec and rec.get("kind") == "gpu" and _alive(rec["pid"]):
+ return rec["job_id"]
+ return None
+
+
+def active_jobs() -> list[dict]:
+ out = []
+ if not os.path.isdir(JOB_DIR):
+ return out
+ for fn in sorted(os.listdir(JOB_DIR)):
+ if fn.endswith(".json"):
+ rec = read_registry(fn[:-5])
+ if rec:
+ rec["live"] = _alive(rec["pid"])
+ out.append(rec)
+ return out
diff --git a/ui/metrics.py b/ui/metrics.py
new file mode 100644
index 0000000..e36a545
--- /dev/null
+++ b/ui/metrics.py
@@ -0,0 +1,35 @@
+"""Read the newest ``/ephemeral/logs/<prefix>_*.jsonl`` metrics file into a DataFrame."""
+
+from __future__ import annotations
+
+import glob
+import json
+import os
+
+from ui.stages import LOG_DIR
+
+
+def latest_log(prefix: str) -> str | None:
+ files = glob.glob(os.path.join(LOG_DIR, f"{prefix}_*.jsonl"))
+ return max(files, key=os.path.getmtime) if files else None
+
+
+def load_metrics(path: str):
+ import pandas as pd
+
+ rows = []
+ with open(path) as f:
+ for line in f:
+ line = line.strip()
+ if line:
+ try:
+ rows.append(json.loads(line))
+ except json.JSONDecodeError:
+ pass
+ return pd.DataFrame(rows)
+
+
+def metric_columns(df) -> list[str]:
+ """Numeric columns worth plotting (drop bookkeeping)."""
+ skip = {"step", "wall"}
+ return [c for c in df.columns if c not in skip and df[c].dtype.kind in "fi"]
diff --git a/ui/pages/1_Data.py b/ui/pages/1_Data.py
new file mode 100644
index 0000000..dc93574
--- /dev/null
+++ b/ui/pages/1_Data.py
@@ -0,0 +1,57 @@
+"""Data preparation page: download + preprocess every dataset as background jobs."""
+
+from __future__ import annotations
+
+import os
+import re
+import sys
+import time
+
+import streamlit as st
+
+from ui import jobs, theme
+from ui.stages import DATA_DIR, DATA_SCRIPTS
+
+theme.setup_page("Data", "📦")
+theme.hero("📦 Data preparation",
+ "Download & preprocess the corpora — Pile (pretrain), Alpaca/Dolly/GSM8K (SFT), "
+ "HH-RLHF/UltraFeedback (preferences), GSM8K + arithmetic (RL).")
+
+st.caption("Each button launches the real `scripts/prepare_*.py` as a background job (sets "
+ "`HF_HOME=/ephemeral/hf_cache`). Large downloads take a while — watch the log below.")
+
+for name, args in DATA_SCRIPTS.items():
+ job_id = "data_" + re.sub(r"[^a-z0-9]+", "_", name.lower()).strip("_")
+ s = jobs.status(job_id)
+ c1, c2 = st.columns([3, 1])
+ c1.markdown(f'<div class="stage-card" style="--c:{theme.COLORS["data"]}">'
+ f'<b>{name}</b> &nbsp; {theme.status_badge(s)}<br>'
+ f'<code>{" ".join(args)}</code></div>', unsafe_allow_html=True)
+ if c2.button("Prepare", key=f"prep_{job_id}", disabled=(s == "running")):
+ env_argv = [sys.executable, *args]
+ rec = jobs.launch(job_id, env_argv, kind="cpu")
+ # data scripts need the HF cache env; relaunch path uses jobs env + HF_HOME
+ os.environ.setdefault("HF_HOME", "/ephemeral/hf_cache")
+ st.session_state["last_data_job"] = job_id
+ st.rerun()
+
+st.subheader("Live log")
+last = st.session_state.get("last_data_job")
+sel = st.selectbox("Job", [j["job_id"] for j in jobs.active_jobs() if j["job_id"].startswith("data_")] or ["—"],
+ index=0)
+job_to_show = sel if sel != "—" else last
+if job_to_show:
+ st.code(jobs.tail_log(job_to_show, 10000) or "(no log yet)", language="text")
+ if jobs.status(job_to_show) == "running" and st.toggle("Auto-refresh", value=True):
+ time.sleep(3); st.rerun()
+
+st.subheader("Files in /ephemeral/data")
+if os.path.isdir(DATA_DIR):
+ rows = []
+ for fn in sorted(os.listdir(DATA_DIR)):
+ p = os.path.join(DATA_DIR, fn)
+ if os.path.isfile(p):
+ rows.append({"file": fn, "size": f"{os.path.getsize(p)/1e6:.1f} MB"})
+ st.dataframe(rows, use_container_width=True, hide_index=True) if rows else st.caption("empty")
+else:
+ st.caption("/ephemeral/data does not exist yet.")
diff --git a/ui/pages/2_Pretrain.py b/ui/pages/2_Pretrain.py
new file mode 100644
index 0000000..c4597aa
--- /dev/null
+++ b/ui/pages/2_Pretrain.py
@@ -0,0 +1,3 @@
+"""2_Pretrain stage page."""
+from ui.stage_page import render_stage_page
+render_stage_page("pretrain")
diff --git a/ui/pages/3_SFT.py b/ui/pages/3_SFT.py
new file mode 100644
index 0000000..c3e05cf
--- /dev/null
+++ b/ui/pages/3_SFT.py
@@ -0,0 +1,3 @@
+"""3_SFT stage page."""
+from ui.stage_page import render_stage_page
+render_stage_page("sft")
diff --git a/ui/pages/4_Reward_Model.py b/ui/pages/4_Reward_Model.py
new file mode 100644
index 0000000..7fa5983
--- /dev/null
+++ b/ui/pages/4_Reward_Model.py
@@ -0,0 +1,3 @@
+"""4_Reward_Model stage page."""
+from ui.stage_page import render_stage_page
+render_stage_page("reward")
diff --git a/ui/pages/5_DPO.py b/ui/pages/5_DPO.py
new file mode 100644
index 0000000..9129a74
--- /dev/null
+++ b/ui/pages/5_DPO.py
@@ -0,0 +1,3 @@
+"""5_DPO stage page."""
+from ui.stage_page import render_stage_page
+render_stage_page("dpo")
diff --git a/ui/pages/6_PPO.py b/ui/pages/6_PPO.py
new file mode 100644
index 0000000..b4ed329
--- /dev/null
+++ b/ui/pages/6_PPO.py
@@ -0,0 +1,3 @@
+"""6_PPO stage page."""
+from ui.stage_page import render_stage_page
+render_stage_page("ppo")
diff --git a/ui/pages/7_GRPO.py b/ui/pages/7_GRPO.py
new file mode 100644
index 0000000..a1681a1
--- /dev/null
+++ b/ui/pages/7_GRPO.py
@@ -0,0 +1,3 @@
+"""7_GRPO stage page."""
+from ui.stage_page import render_stage_page
+render_stage_page("grpo")
diff --git a/ui/pages/8_Evaluate.py b/ui/pages/8_Evaluate.py
new file mode 100644
index 0000000..313d9de
--- /dev/null
+++ b/ui/pages/8_Evaluate.py
@@ -0,0 +1,38 @@
+"""Evaluate a checkpoint on GSM8K (greedy), in-process."""
+
+from __future__ import annotations
+
+import glob
+
+import streamlit as st
+
+from ui import theme
+
+theme.setup_page("Evaluate", "📊")
+theme.hero("📊 Evaluate on GSM8K", "Greedy GSM8K accuracy for any checkpoint, with sample generations.")
+
+ckpts = sorted(glob.glob("/ephemeral/ckpts/*.pt"))
+if not ckpts:
+ st.warning("No checkpoints found in /ephemeral/ckpts. Train a stage first.")
+ st.stop()
+
+ckpt = st.selectbox("Checkpoint", ckpts, index=len(ckpts) - 1)
+c1, c2, c3 = st.columns(3)
+limit = c1.slider("Num questions", 5, 200, 20, step=5)
+max_new = c2.slider("Max new tokens", 64, 400, 256, step=32)
+device = c3.selectbox("Device", ["cuda", "cpu"], index=0)
+
+if st.button("▶️ Run GSM8K eval", type="primary"):
+ with st.spinner(f"Generating + scoring {limit} GSM8K problems on {device} …"):
+ from src.post_training.evaluation import gsm8k_accuracy, load_gsm8k_eval
+ from src.post_training.inference import load_model_from_ckpt
+ model = load_model_from_ckpt(ckpt, device)
+ qa = load_gsm8k_eval("test", limit=limit)
+ res = gsm8k_accuracy(model, qa, device=device, max_new_tokens=max_new, greedy=True,
+ return_samples=min(5, limit))
+ st.metric("GSM8K accuracy", f"{res['accuracy']*100:.1f}%", f"{res['correct']}/{res['n']} correct")
+ st.subheader("Sample generations")
+ for s in res["samples"]:
+ with st.expander(("✅ " if s["correct"] else "❌ ") + s["q"][:90]):
+ st.markdown(f"**Gold:** `{s['gold']}` · **Correct:** {s['correct']}")
+ st.code(s["response"][:1200], language="text")
diff --git a/ui/pages/9_Chat.py b/ui/pages/9_Chat.py
new file mode 100644
index 0000000..ce8257f
--- /dev/null
+++ b/ui/pages/9_Chat.py
@@ -0,0 +1,57 @@
+"""Chat with any checkpoint, in-process (no subprocess)."""
+
+from __future__ import annotations
+
+import glob
+
+import streamlit as st
+
+from ui import theme
+
+theme.setup_page("Chat", "💬")
+theme.hero("💬 Chat", "Talk to any checkpoint — chat template for instruction models, raw mode for the base.")
+
+ckpts = sorted(glob.glob("/ephemeral/ckpts/*.pt"))
+if not ckpts:
+ st.warning("No checkpoints in /ephemeral/ckpts yet. Train a stage (or run a smoke job) first.")
+ st.stop()
+
+with st.sidebar:
+ st.header("Generation")
+ ckpt = st.selectbox("Checkpoint", ckpts, index=len(ckpts) - 1)
+ device = st.selectbox("Device", ["cuda", "cpu"], index=0)
+ raw = st.toggle("Raw mode (base continuation, no chat template)", value=False)
+ greedy = st.toggle("Greedy (deterministic)", value=False)
+ temperature = st.slider("Temperature", 0.1, 1.5, 0.8, 0.05, disabled=greedy)
+ top_p = st.slider("top-p", 0.1, 1.0, 0.95, 0.05, disabled=greedy)
+ max_new = st.slider("Max new tokens", 16, 512, 256, 16)
+ system = st.text_input("System prompt (chat mode)", "")
+ if st.button("🗑️ Clear history"):
+ st.session_state.pop("chat_msgs", None)
+
+
[email protected]_resource(show_spinner="Loading checkpoint …")
+def _load(path, dev):
+ from src.post_training.inference import load_model_from_ckpt
+ return load_model_from_ckpt(path, dev)
+
+
+model = _load(ckpt, device)
+st.caption(f"Loaded `{ckpt}` · {sum(p.numel() for p in model.parameters())/1e6:.0f}M params on {device} · "
+ f"mode={'raw' if raw else 'chat'}")
+
+st.session_state.setdefault("chat_msgs", [])
+for m in st.session_state["chat_msgs"]:
+ st.chat_message(m["role"]).markdown(m["content"])
+
+prompt = st.chat_input("Ask something (e.g. 'What is 13 + 29?')")
+if prompt:
+ st.session_state["chat_msgs"].append({"role": "user", "content": prompt})
+ st.chat_message("user").markdown(prompt)
+ with st.chat_message("assistant"), st.spinner("Generating …"):
+ from src.post_training.inference import generate_reply
+ reply = generate_reply(model, prompt, device=device, system=system or None, raw=raw,
+ max_new_tokens=max_new, temperature=temperature,
+ top_p=top_p if top_p < 1 else None, greedy=greedy)
+ st.markdown(reply if reply.strip() else "_(empty generation)_")
+ st.session_state["chat_msgs"].append({"role": "assistant", "content": reply})
diff --git a/ui/stage_page.py b/ui/stage_page.py
new file mode 100644
index 0000000..d6313dc
--- /dev/null
+++ b/ui/stage_page.py
@@ -0,0 +1,86 @@
+"""
+Reusable renderer for a training-stage page: theory + diagram → config form → launch /
+stop (with the GPU-busy guard) → live log → metric charts. Each stage page is a 3-liner
+that calls :func:`render_stage_page`.
+"""
+
+from __future__ import annotations
+
+import streamlit as st
+
+from ui import jobs, metrics, theme
+from ui.config_forms import render_form
+from ui.docs_render import render_doc
+from ui.stages import STAGES
+
+
+def render_stage_page(stage_key: str) -> None:
+ stage = STAGES[stage_key]
+ theme.setup_page(stage.title, stage.emoji)
+ theme.hero(f"{stage.emoji} {stage.title}", f"Configure, launch, and monitor the {stage.title} stage.")
+
+ job_status = jobs.status(stage.key)
+ st.markdown(f"**Job status:** {theme.status_badge(job_status)}", unsafe_allow_html=True)
+
+ tab_run, tab_theory = st.tabs(["🚀 Run", "📖 Theory"])
+
+ with tab_theory:
+ render_doc(st, stage.doc_md, stage.diagram_png)
+
+ with tab_run:
+ c1, c2 = st.columns([1, 1])
+ with c1:
+ smoke = st.toggle("Smoke mode (tiny model, few steps, CPU)", value=False, key=f"smoke_{stage.key}")
+ with c2:
+ ngpu = theme.gpu_status()
+ max_gpu = max(1, len(ngpu))
+ nproc = st.slider("GPUs (torchrun)", 1, max_gpu, min(2, max_gpu) if stage.multi_gpu and not smoke else 1,
+ disabled=smoke or not stage.multi_gpu, key=f"nproc_{stage.key}")
+ if smoke:
+ nproc = 1
+
+ st.subheader("Configuration")
+ render_form(stage, smoke=smoke, nproc=nproc)
+
+ st.subheader("Launch")
+ busy = jobs.gpu_busy()
+ guard = (not smoke) and busy is not None and busy != stage.key
+ if guard:
+ st.warning(f"🚧 GPUs are occupied by job **{busy}**. Stop it, or use Smoke mode (CPU), "
+ f"before launching {stage.title} on GPU.")
+ cols = st.columns(3)
+ with cols[0]:
+ if st.button("▶️ Launch", type="primary", disabled=(job_status == "running" or guard),
+ key=f"launch_{stage.key}"):
+ cfg_json = stage.smoke_json if smoke else stage.config_json
+ argv = jobs.build_argv(stage.script, cfg_json, nproc, stage.multi_gpu)
+ kind = "cpu" if smoke else ("gpu" if stage.multi_gpu else "cpu")
+ jobs.launch(stage.key, argv, kind=kind)
+ st.rerun()
+ with cols[1]:
+ if st.button("⏹️ Stop", disabled=(job_status != "running"), key=f"stop_{stage.key}"):
+ jobs.stop(stage.key)
+ st.rerun()
+ with cols[2]:
+ auto = st.toggle("Auto-refresh", value=(job_status == "running"), key=f"auto_{stage.key}")
+
+ st.subheader("Live log")
+ st.code(jobs.tail_log(stage.key, 12000) or "(no log yet — launch the stage)", language="text")
+
+ st.subheader("Metrics")
+ log = metrics.latest_log(stage.log_prefix)
+ if log:
+ df = metrics.load_metrics(log)
+ cols_to_plot = metrics.metric_columns(df) if not df.empty else []
+ if "step" in df.columns and cols_to_plot:
+ st.line_chart(df.set_index("step")[cols_to_plot])
+ st.caption(f"from `{log}` · {len(df)} logged points")
+ else:
+ st.info("No metrics logged yet.")
+ else:
+ st.info(f"No `{stage.log_prefix}_*.jsonl` metrics found yet.")
+
+ if auto:
+ import time
+ time.sleep(3)
+ st.rerun()
diff --git a/ui/stages.py b/ui/stages.py
new file mode 100644
index 0000000..a0680cd
--- /dev/null
+++ b/ui/stages.py
@@ -0,0 +1,75 @@
+"""
+Single source of truth for the control panel: maps each pipeline stage to its config
+dataclass, JSON file, training script, log prefix, theory doc, diagram, and whether it is a
+multi-GPU (torchrun) stage. Every page / form / job reads from here.
+"""
+
+from __future__ import annotations
+
+import os
+from dataclasses import dataclass
+
+from config.post_training_config import (
+ PretrainConfig, SFTConfig, RewardConfig, DPOConfig, PPOConfig, GRPOConfig,
+)
+
+REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+CKPT_DIR = "/ephemeral/ckpts"
+DATA_DIR = "/ephemeral/data"
+LOG_DIR = "/ephemeral/logs"
+
+
+@dataclass(frozen=True)
+class Stage:
+ key: str # short id ("sft")
+ title: str # display ("Supervised Fine-Tuning")
+ emoji: str
+ cfg_cls: type # the dataclass
+ config_json: str # configs/<stage>.json
+ smoke_json: str # configs/smoke/<stage>.json
+ script: str # scripts/<trainer>.py
+ log_prefix: str # JSONL files are <log_prefix>_<ts>.jsonl
+ doc_md: str # docs/<NN_stage>.md (theory)
+ diagram_png: str # docs/diagrams/<NN_stage>.png
+ multi_gpu: bool # True -> can use torchrun
+
+
+STAGES: dict[str, Stage] = {
+ "pretrain": Stage("pretrain", "Pretraining", "📚", PretrainConfig,
+ "configs/pretrain.json", "configs/smoke/pretrain.json",
+ "scripts/pretrain_base.py", "pretrain",
+ "docs/02_pretraining.md", "docs/diagrams/02_pretraining.png", True),
+ "sft": Stage("sft", "Supervised Fine-Tuning", "🎯", SFTConfig,
+ "configs/sft.json", "configs/smoke/sft.json",
+ "scripts/train_sft.py", "sft",
+ "docs/03_sft.md", "docs/diagrams/03_sft.png", True),
+ "reward": Stage("reward", "Reward Model", "🏅", RewardConfig,
+ "configs/reward.json", "configs/smoke/reward.json",
+ "scripts/train_reward.py", "reward",
+ "docs/04_reward_model.md", "docs/diagrams/04_reward_model.png", True),
+ "dpo": Stage("dpo", "DPO / ORPO / KTO", "⚖️", DPOConfig,
+ "configs/dpo.json", "configs/smoke/dpo.json",
+ "scripts/train_dpo.py", "dpo",
+ "docs/05_dpo.md", "docs/diagrams/05_dpo.png", True),
+ "ppo": Stage("ppo", "PPO (RLHF)", "🎮", PPOConfig,
+ "configs/ppo.json", "configs/smoke/ppo.json",
+ "scripts/train_ppo.py", "ppo",
+ "docs/06_ppo.md", "docs/diagrams/06_ppo.png", True),
+ "grpo": Stage("grpo", "GRPO / RLVR", "🧠", GRPOConfig,
+ "configs/grpo.json", "configs/smoke/grpo.json",
+ "scripts/train_grpo.py", "grpo",
+ "docs/07_grpo.md", "docs/diagrams/07_grpo.png", True),
+}
+
+# Data-prep scripts (plain python jobs, no config dataclass).
+DATA_SCRIPTS = {
+ "Pretrain corpus (Pile → HDF5)": ["scripts/prepare_pretrain_data.py", "--split", "train",
+ "--num_shards", "1", "--out", f"{DATA_DIR}/pile_train.h5"],
+ "Pretrain dev (Pile val)": ["scripts/prepare_pretrain_data.py", "--split", "val",
+ "--out", f"{DATA_DIR}/pile_dev.h5"],
+ "SFT (Alpaca · Dolly · GSM8K)": ["scripts/prepare_sft_data.py"],
+ "Preferences (HH-RLHF · UltraFeedback)": ["scripts/prepare_preference_data.py", "--source", "both"],
+ "RL prompts (GSM8K + arithmetic)": ["scripts/prepare_rl_prompts.py"],
+}
+
+ABS_DOC = lambda rel: os.path.join(REPO_ROOT, rel) # noqa: E731
diff --git a/ui/theme.py b/ui/theme.py
new file mode 100644
index 0000000..42d6ff4
--- /dev/null
+++ b/ui/theme.py
@@ -0,0 +1,65 @@
+"""Shared look-and-feel: page config, CSS injection, header, GPU status, job badges."""
+
+from __future__ import annotations
+
+import streamlit as st
+
+# Palette matching the hand-drawn diagrams.
+COLORS = {
+ "data": "#27ae60", "proc": "#2c6fbb", "store": "#16a085", "model": "#d48806",
+ "rl": "#e67e22", "loss": "#c0392b", "eval": "#8e44ad", "ckpt": "#888888",
+}
+
+_CSS = """
+<style>
+.block-container {padding-top: 2rem; max-width: 1100px;}
+h1, h2, h3 {letter-spacing: .2px;}
+.hero {background: linear-gradient(135deg,#16a085 0%, #2c6fbb 100%);
+ color: #fff; padding: 1.4rem 1.6rem; border-radius: 16px; margin-bottom: 1.2rem;}
+.hero h1 {color:#fff; margin:0 0 .3rem 0; font-size: 1.7rem;}
+.hero p {color:#eafaf5; margin:0; font-size: .98rem;}
+.stage-card {border-left: 6px solid var(--c,#16a085); background: rgba(127,127,127,.06);
+ padding: .8rem 1rem; border-radius: 10px; margin:.3rem 0;}
+.badge {display:inline-block; padding:.12rem .6rem; border-radius:999px; font-size:.78rem;
+ font-weight:600; color:#fff;}
+.b-run{background:#d48806;} .b-ok{background:#27ae60;} .b-fail{background:#c0392b;}
+.b-idle{background:#888;}
+div[data-testid="stMetricValue"] {font-size: 1.5rem;}
+</style>
+"""
+
+_BADGE = {"running": ("b-run", "running"), "finished": ("b-ok", "finished"),
+ "failed": ("b-fail", "failed"), "stopped": ("b-idle", "stopped"), "none": ("b-idle", "idle")}
+
+
+def setup_page(title: str, icon: str = "🧠") -> None:
+ st.set_page_config(page_title=f"{title} · Train LLM From Scratch", page_icon=icon, layout="wide")
+ st.markdown(_CSS, unsafe_allow_html=True)
+
+
+def hero(title: str, subtitle: str) -> None:
+ st.markdown(f'<div class="hero"><h1>{title}</h1><p>{subtitle}</p></div>', unsafe_allow_html=True)
+
+
+def status_badge(status: str) -> str:
+ cls, label = _BADGE.get(status, ("b-idle", status))
+ return f'<span class="badge {cls}">{label}</span>'
+
+
+def gpu_status():
+ """Return a list of (idx, name, used_mb, total_mb, util) via nvidia-smi, or []."""
+ import shutil
+ import subprocess
+ if not shutil.which("nvidia-smi"):
+ return []
+ try:
+ out = subprocess.check_output(
+ ["nvidia-smi", "--query-gpu=index,name,memory.used,memory.total,utilization.gpu",
+ "--format=csv,noheader,nounits"], text=True, timeout=5)
+ except Exception: # noqa: BLE001
+ return []
+ rows = []
+ for line in out.strip().splitlines():
+ i, name, used, total, util = [x.strip() for x in line.split(",")]
+ rows.append((int(i), name, int(used), int(total), int(util)))
+ return rows