Skip to content

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

docs: add foundations tutorial

Abellegese6efc06256796
diff --git a/.gitignore b/.gitignore
index 315fb91..8420144 100644
--- a/.gitignore
+++ b/.gitignore
@@ -10,6 +10,7 @@ dist/
# generated docs site
site/
+.superpowers/
# data / model artifacts (kept on the /ephemeral disk, not committed)
data/
diff --git a/README.md b/README.md
index ef35e6f..2fff884 100644
--- a/README.md
+++ b/README.md
@@ -20,6 +20,12 @@ I implemented a transformer model from scratch using PyTorch, based on the paper
> 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.
+> **New: foundations-first tutorial documentation.**
+> If you want to understand the codebase before running the full training pipeline, start with the
+> **[LLM Foundations tutorial](docs/foundations/README.md)**. It explains tokenization, data shapes,
+> decoder-only Transformers, attention, losses, optimization, and generation with diagrams, formulas,
+> and links back to the source code. The full MkDocs site starts at **[docs/README.md](docs/README.md)**.
+
Below is the output of the trained 13 million parameter LLM:
```
@@ -34,6 +40,7 @@ Odambinais is uncertain and fortune established in rural areas.
## Table of Contents
- [Training Data Info](#training-data-info)
- [Prerequisites and Training Time](#prerequisites-and-training-time)
+- [Documentation Site](#documentation-site)
- [Code Structure](#code-structure)
- [Usage](#usage)
- [Step by Step Code Explanation](#step-by-step-code-explanation)
@@ -136,6 +143,20 @@ A community run on an NVIDIA GeForce RTX 5090 validated the following:
The training script now prints lightweight runtime diagnostics to make these reports easier to collect. Newer PyTorch versions may also require explicit checkpoint loading compatibility handling during generation.
+## Documentation Site
+
+The repository includes a Material for MkDocs documentation site under [`docs/`](docs/README.md).
+For a foundations-first learning path, start with [`docs/foundations/README.md`](docs/foundations/README.md),
+then continue through the data, pretraining, SFT, reward-model, DPO, PPO, GRPO, evaluation, and
+inference pages.
+
+Run the docs locally with:
+
+```bash
+pip install -e ".[docs]"
+mkdocs serve
+```
+
## Code Structure
The codebase is organized as follows:
diff --git a/docs/01_data_pipeline.md b/docs/01_data_pipeline.md
index 5582585..b14874c 100644
--- a/docs/01_data_pipeline.md
+++ b/docs/01_data_pipeline.md
@@ -6,6 +6,10 @@ battle — a misaligned loss mask or a mis-parsed gold answer will silently wrec
any model code, here is exactly how I download and preprocess each dataset, and the format each
trainer expects.
+For the first-principles background behind these shapes, read
+[Tokenization & Data Shapes](foundations/tokenization.md). That page explains why pretraining uses
+flat token streams, why SFT needs `loss_mask`, and why preference data must preserve a shared prompt.
+
There are **four** data pipelines, all feeding off real public datasets:
![Data preprocessing pipelines](diagrams/01_data_pipeline.png)
diff --git a/docs/02_pretraining.md b/docs/02_pretraining.md
index f34d8ac..b8cd08a 100644
--- a/docs/02_pretraining.md
+++ b/docs/02_pretraining.md
@@ -8,6 +8,12 @@ model on 2×H100 I wrote [`pretrain_base.py`](https://github.com/FareedKhan-dev/
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.
+If the architecture or training terms are unfamiliar, read the foundations chapters first:
+[Decoder-Only Transformer](foundations/transformer.md),
+[Attention, Masks & Heads](foundations/attention.md),
+[Objectives, Losses & Perplexity](foundations/objectives.md), and
+[Optimization & Training Systems](foundations/optimization.md).
+
![Pretraining loop](diagrams/02_pretraining.png)
<details>
diff --git a/docs/03_sft.md b/docs/03_sft.md
index 9161ebd..fb15a7a 100644
--- a/docs/03_sft.md
+++ b/docs/03_sft.md
@@ -6,6 +6,10 @@ showing it thousands of `(instruction, response)` pairs and training it to produ
The only real difference from pretraining is a per-token **loss mask**: we compute the loss on the
assistant tokens and ignore the prompt.
+The exact token/mask mechanics are explained in
+[Tokenization & Data Shapes](foundations/tokenization.md), and the masked objective is derived in
+[Objectives, Losses & Perplexity](foundations/objectives.md).
+
![SFT masked-loss flow](diagrams/03_sft.png)
<details>
diff --git a/docs/04_reward_model.md b/docs/04_reward_model.md
index 29370ce..892f2d5 100644
--- a/docs/04_reward_model.md
+++ b/docs/04_reward_model.md
@@ -6,6 +6,10 @@ preferred. That's the reward model. I build it by putting a tiny scalar head on
backbone and training it on human preference pairs with the **Bradley-Terry** loss — the same recipe
as InstructGPT.
+This page assumes you already know how the backbone produces hidden states. If not, start with
+[Decoder-Only Transformer](foundations/transformer.md). The preference-data shape is covered in
+[Tokenization & Data Shapes](foundations/tokenization.md).
+
![Reward model (Bradley-Terry)](diagrams/04_reward_model.png)
<details>
diff --git a/docs/05_dpo.md b/docs/05_dpo.md
index f485bad..52b9425 100644
--- a/docs/05_dpo.md
+++ b/docs/05_dpo.md
@@ -7,6 +7,9 @@ SFT model as a reference anchor. No reward model, no rollouts, no value function
I also implemented two popular variants behind a `--loss_type` flag: **ORPO** (reference-free) and
**KTO** (works from a desirable/undesirable signal).
+For the sequence log-probability notation used here, see
+[Objectives, Losses & Perplexity](foundations/objectives.md).
+
![DPO / ORPO / KTO](diagrams/05_dpo.png)
<details>
diff --git a/docs/06_ppo.md b/docs/06_ppo.md
index 18eee77..103c74c 100644
--- a/docs/06_ppo.md
+++ b/docs/06_ppo.md
@@ -6,6 +6,10 @@ nudge the policy toward higher-reward behaviour using Proximal Policy Optimizati
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.
+The clipped objective and policy-ratio notation are introduced in
+[Objectives, Losses & Perplexity](foundations/objectives.md). The optimizer and stability pieces are
+covered in [Optimization & Training Systems](foundations/optimization.md).
+
![PPO loop](diagrams/06_ppo.png)
<details>
diff --git a/docs/07_grpo.md b/docs/07_grpo.md
index bfdc688..796aa5a 100644
--- a/docs/07_grpo.md
+++ b/docs/07_grpo.md
@@ -6,6 +6,9 @@ simple: **throw away PPO's value network**. For each prompt, sample a whole *gro
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.
+For the group-relative advantage formula and how it relates to PPO-style policy ratios, see
+[Objectives, Losses & Perplexity](foundations/objectives.md).
+
![GRPO loop](diagrams/07_grpo.png)
<details>
diff --git a/docs/09_inference.md b/docs/09_inference.md
index 2701dae..8e9df26 100644
--- a/docs/09_inference.md
+++ b/docs/09_inference.md
@@ -6,6 +6,9 @@ Training is only satisfying if you can actually *talk* to the result. The origin
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.
+For the underlying decoding loop, context cropping, temperature, and stop-token behavior, read
+[Generation & Sampling](foundations/generation.md).
+
![Inference / chat flow](diagrams/09_inference.png)
<details>
diff --git a/docs/README.md b/docs/README.md
index 88e32a5..04db457 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -7,6 +7,32 @@ through the whole journey I built on top of the base model — every stage writt
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.
+If you are new to LLM training internals, start with the new
+**[LLM Foundations](foundations/README.md)** section before reading the stage pages. It explains the
+token shapes, decoder-only Transformer, attention masks, objectives, optimization loop, and generation
+mechanics that every later page relies on.
+
+## Recommended reading order
+
+1. **Foundations first**:
+ [Tokenization](foundations/tokenization.md) ->
+ [Transformer](foundations/transformer.md) ->
+ [Attention](foundations/attention.md) ->
+ [Objectives](foundations/objectives.md) ->
+ [Optimization](foundations/optimization.md) ->
+ [Generation](foundations/generation.md).
+2. **Then the full pipeline**:
+ [Data](01_data_pipeline.md) ->
+ [Pretraining](02_pretraining.md) ->
+ [SFT](03_sft.md) ->
+ [Reward Model](04_reward_model.md) ->
+ [DPO](05_dpo.md) ->
+ [PPO](06_ppo.md) ->
+ [GRPO](07_grpo.md).
+3. **Finally run and inspect**:
+ [Evaluation](08_evaluation.md), [Inference / Chat](09_inference.md), and the
+ [command cheatsheet](howto/commands.md).
+
The pipeline mirrors how modern aligned/reasoning models are actually built:
![Post-training pipeline](diagrams/00_overview.png)
diff --git a/docs/assets/foundations-tutorial-screenshot.png b/docs/assets/foundations-tutorial-screenshot.png
new file mode 100644
index 0000000..220c6eb
Binary files /dev/null and b/docs/assets/foundations-tutorial-screenshot.png differ
diff --git a/docs/foundations/README.md b/docs/foundations/README.md
new file mode 100644
index 0000000..e82d288
--- /dev/null
+++ b/docs/foundations/README.md
@@ -0,0 +1,108 @@
+# LLM Foundations
+
+This section explains the ideas that the training code assumes you know. It is not a PyTorch primer.
+It is a bridge between the source files in this repository and the core concepts behind modern
+decoder-only language models.
+
+The priority is:
+
+1. understand the base model and pretraining mechanics;
+2. connect those mechanics to every existing stage in the site;
+3. use the same language later for SFT, reward models, DPO, PPO, and GRPO.
+
+## The whole training story
+
+```mermaid
+flowchart LR
+ RAW[raw text] --> TOK[tokenizer]
+ TOK --> IDS[token ids]
+ IDS --> BASE[decoder-only Transformer]
+ BASE --> CE[next-token cross-entropy]
+ CE --> CKPT[base checkpoint]
+ CKPT --> SFT[SFT: instruction following]
+ SFT --> PREF[preference optimization]
+ PREF --> RL[RL / verifier optimization]
+ RL --> CHAT[inference and chat]
+
+ 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;
+ class RAW,TOK,IDS data;
+ class BASE,CKPT,SFT,PREF,RL,CHAT model;
+ class CE loss;
+```
+
+At the base level, an LLM is a conditional probability model:
+
+\[
+p_\theta(x_1, x_2, \ldots, x_T)
+= \prod_{t=1}^{T} p_\theta(x_t \mid x_{<t})
+\]
+
+The Transformer does not learn "truth" directly. It learns a distribution over the next token. A
+large amount of useful behavior appears because the next-token task forces the model to compress
+syntax, facts, formats, style, and reasoning traces into its weights.
+
+## Where each concept lives in this repo
+
+| Concept | Why it matters | Main code |
+|---|---|---|
+| Tokenization | Text must become integer ids before the model can train. | `scripts/prepare_pretrain_data.py`, `src/post_training/chat_template.py` |
+| Fixed context windows | Training examples are contiguous windows of tokens. | `data_loader/data_loader.py` |
+| Token and position embeddings | Integer ids become vectors and positions. | `src/models/transformer.py` |
+| Causal self-attention | Each token mixes information from previous tokens only. | `src/models/attention.py` |
+| Transformer block | Attention plus MLP, with pre-norm residual structure. | `src/models/transformer_block.py` |
+| Logits | Hidden states become unnormalized vocabulary scores. | `src/models/transformer.py` |
+| Cross-entropy | The base objective rewards probability on the true next token. | `src/models/transformer.py`, `src/post_training/sft.py` |
+| AdamW and LR schedule | Optimization details that decide whether training is stable. | `src/post_training/optim.py` |
+| Gradient accumulation | Simulates a larger batch under memory limits. | `scripts/pretrain_base.py`, `scripts/train_sft.py` |
+| Generation | The model feeds sampled tokens back into itself. | `src/models/transformer.py`, `src/post_training/inference.py` |
+
+## Learning path
+
+Read in this order:
+
+1. [Tokenization & Data Shapes](tokenization.md) - how text becomes batches.
+2. [Decoder-Only Transformer](transformer.md) - the model skeleton.
+3. [Attention, Masks & Heads](attention.md) - the core operation.
+4. [Objectives, Losses & Perplexity](objectives.md) - what the model is optimized to do.
+5. [Optimization & Training Systems](optimization.md) - how the loop stays stable.
+6. [Generation & Sampling](generation.md) - how logits become text.
+
+Then continue to the pipeline pages:
+
+- [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)
+
+## Mental model
+
+The base training loop is compact:
+
+\[
+\text{text} \to \text{token ids} \to \text{embeddings} \to \text{Transformer blocks}
+\to \text{logits} \to \text{cross-entropy} \to \nabla_\theta
+\]
+
+Post-training mostly changes the data and the loss:
+
+- SFT keeps next-token prediction, but masks the loss to assistant tokens.
+- Reward modeling changes the output from vocabulary logits to one scalar score.
+- DPO compares sequence log-probabilities for chosen and rejected responses.
+- PPO and GRPO sample completions, score them, and update the policy with a constrained RL objective.
+
+The same backbone is reused throughout. That is the most important design idea in this repo.
+
+## Primary references
+
+- [Attention Is All You Need](https://arxiv.org/abs/1706.03762) introduced the Transformer and scaled dot-product attention.
+- [The Pile](https://arxiv.org/abs/2101.00027) describes the 825 GiB text corpus used by the pretraining path.
+- [Neural Machine Translation of Rare Words with Subword Units](https://arxiv.org/abs/1508.07909) introduced the BPE subword idea that modern tokenizers build on.
+- [Decoupled Weight Decay Regularization](https://arxiv.org/abs/1711.05101) motivates AdamW.
+- [Training language models to follow instructions with human feedback](https://arxiv.org/abs/2203.02155) is the classic SFT -> reward model -> PPO RLHF recipe.
+- [Direct Preference Optimization](https://arxiv.org/abs/2305.18290) motivates the DPO page.
+- [DeepSeekMath](https://arxiv.org/abs/2402.03300) introduces GRPO in the mathematical reasoning setting.
diff --git a/docs/foundations/attention.md b/docs/foundations/attention.md
new file mode 100644
index 0000000..068f55c
--- /dev/null
+++ b/docs/foundations/attention.md
@@ -0,0 +1,168 @@
+# Attention, Masks & Heads
+
+Self-attention is the operation that lets each token decide which previous tokens matter.
+
+In a decoder-only language model, position \(t\) can use information from positions \(0..t\), but not
+from positions \(t+1..T-1\). That restriction is what makes next-token training honest.
+
+## The attention equation
+
+For an input tensor \(X \in \mathbb{R}^{B \times T \times C}\), one attention head learns three
+linear projections:
+
+\[
+Q = X W_Q,\quad K = X W_K,\quad V = X W_V
+\]
+
+where \(Q,K,V \in \mathbb{R}^{B \times T \times D}\).
+
+Scaled dot-product attention is:
+
+\[
+\text{Attention}(Q,K,V)
+= \text{softmax}\left(\frac{QK^T}{\sqrt{D}} + M\right)V
+\]
+
+The mask \(M\) is `0` for allowed positions and \(-\infty\) for future positions.
+
+## Query, key, value intuition
+
+For each token:
+
+- query: "what am I looking for?"
+- key: "what information do I contain?"
+- value: "what content should I pass forward if selected?"
+
+The dot product \(q_t \cdot k_s\) measures how much token \(t\) wants information from token \(s\).
+
+## Why divide by \(\sqrt{D}\)?
+
+If the components of queries and keys have roughly unit variance, their dot product has variance
+proportional to \(D\). Larger head sizes would create large logits, making softmax overly sharp and
+gradients weak. The scale factor keeps attention logits in a more stable range:
+
+\[
+\frac{q_t \cdot k_s}{\sqrt{D}}
+\]
+
+## Causal masking
+
+For \(T=5\), the allowed attention pattern is:
+
+\[
+\begin{bmatrix}
+1 & 0 & 0 & 0 & 0 \\
+1 & 1 & 0 & 0 & 0 \\
+1 & 1 & 1 & 0 & 0 \\
+1 & 1 & 1 & 1 & 0 \\
+1 & 1 & 1 & 1 & 1
+\end{bmatrix}
+\]
+
+The repo stores this as a lower-triangular buffer:
+
+```python
+self.register_buffer("tril", torch.tril(torch.ones(context_length, context_length)))
+```
+
+Then masks future locations before softmax:
+
+```python
+attn_weights = q @ k.transpose(-2, -1) * scale_factor
+attn_weights = attn_weights.masked_fill(self.tril[:T, :T] == 0, float("-inf"))
+attn_weights = F.softmax(attn_weights, dim=-1)
+out = attn_weights @ v
+```
+
+Because the future logits become \(-\infty\), their softmax probability becomes zero.
+
+```mermaid
+flowchart LR
+ X["x (B,T,C)"] --> Q["query projection"]
+ X --> K["key projection"]
+ X --> V["value projection"]
+ Q --> S["QK^T / sqrt(D)"]
+ K --> S
+ S --> M["causal mask"]
+ M --> P["softmax weights"]
+ V --> O["weights @ V"]
+ P --> O
+```
+
+## Multi-head attention
+
+One head has one attention pattern. Multiple heads let the model learn several patterns in parallel:
+
+- syntax dependencies;
+- repeated names or entities;
+- local phrase structure;
+- delimiter and format tracking;
+- arithmetic or code-like dependencies.
+
+The repo creates `n_head` independent `Head` modules:
+
+```python
+self.heads = nn.ModuleList([
+ Head(n_embed // n_head, n_embed, context_length)
+ for _ in range(n_head)
+])
+self.proj = nn.Linear(n_embed, n_embed)
+```
+
+Then concatenates head outputs:
+
+```python
+x = torch.cat([h(x) for h in self.heads], dim=-1)
+x = self.proj(x)
+```
+
+If \(H\) heads each emit width \(D=C/H\), concatenation returns width \(C\):
+
+\[
+\text{Concat}(\text{head}_1,\ldots,\text{head}_H) \in \mathbb{R}^{B \times T \times C}
+\]
+
+The final projection mixes information across heads.
+
+## Attention cost
+
+The attention score matrix has shape:
+
+\[
+B \times T \times T
+\]
+
+per head. With \(H\) heads, the core score storage is roughly:
+
+\[
+O(BHT^2)
+\]
+
+This is why context length is expensive. Doubling \(T\) roughly quadruples the attention matrix size.
+The repo's educational attention implementation is intentionally readable and materializes these
+matrices directly.
+
+## What attention can and cannot do
+
+Attention mixes information between positions. It does not by itself:
+
+- create a probability distribution over the vocabulary;
+- know token order without positional information;
+- perform nonlinear transformation beyond weighted averaging.
+
+Those jobs come from position embeddings, the MLP, layer norms, residual paths, and the final LM head.
+
+## Debugging attention mentally
+
+If training behaves oddly, ask these questions:
+
+1. Is the mask causal, or can tokens see the answer?
+2. Are `q`, `k`, and `v` projected from the same normalized input?
+3. Is `head_size = n_embed // n_head` an integer?
+4. Does concatenating all heads return exactly `n_embed` channels?
+5. Is sequence length `T` less than or equal to `context_length`?
+
+## Next
+
+Attention creates hidden states. The loss decides how hidden states become learning signal. Continue
+to [Objectives, Losses & Perplexity](objectives.md).
diff --git a/docs/foundations/generation.md b/docs/foundations/generation.md
new file mode 100644
index 0000000..0898e88
--- /dev/null
+++ b/docs/foundations/generation.md
@@ -0,0 +1,140 @@
+# Generation & Sampling
+
+Training predicts the next token for known text. Generation uses the model's own sampled token as the
+next input.
+
+That feedback loop is why small probability differences can produce very different completions.
+
+## Autoregressive loop
+
+```mermaid
+flowchart LR
+ P["prompt ids"] --> CROP["keep last context_length ids"]
+ CROP --> M["Transformer"]
+ M --> LOGITS["last-position logits"]
+ LOGITS --> PROBS["softmax / sampling"]
+ PROBS --> NEXT["next token id"]
+ NEXT --> APPEND["append to sequence"]
+ APPEND --> CROP
+```
+
+The simple implementation in `src/models/transformer.py`:
+
+```python
+for _ in range(max_new_tokens):
+ idx_cond = idx[:, -self.context_length:]
+ logits, _ = self(idx_cond)
+ logits = logits[:, -1, :]
+ probs = F.softmax(logits, dim=-1)
+ idx_next = torch.multinomial(probs, num_samples=1)
+ idx = torch.cat((idx, idx_next), dim=1)
+```
+
+Only the final position is used because that position has attended to the whole current context.
+
+## Greedy decoding vs sampling
+
+Greedy decoding chooses:
+
+\[
+\arg\max_i p_i
+\]
+
+Sampling draws:
+
+\[
+x \sim \text{Categorical}(p)
+\]
+
+Greedy decoding is deterministic and often repetitive. Sampling is stochastic and can produce more
+varied text.
+
+This repo's simple base `generate` method samples directly from the full softmax distribution.
+The post-training inference utilities add more controls.
+
+## Temperature
+
+Temperature rescales logits before softmax:
+
+\[
+p_i =
+\frac{\exp(z_i / \tau)}
+{\sum_j \exp(z_j / \tau)}
+\]
+
+Effects:
+
+- \(\tau < 1\): sharper distribution, safer but less diverse;
+- \(\tau = 1\): unchanged;
+- \(\tau > 1\): flatter distribution, more diverse but more error-prone.
+
+Temperature operates on logits, not probabilities.
+
+## Top-k and top-p
+
+Many generation systems restrict the candidate set before sampling.
+
+Top-k keeps only the \(k\) highest-probability tokens.
+
+Top-p, also called nucleus sampling, keeps the smallest set of tokens whose cumulative probability is
+at least \(p\).
+
+These controls are not part of the base model architecture. They are decoding policies layered on top
+of the model's logits.
+
+## Context cropping
+
+The model has a fixed maximum context length:
+
+```python
+idx_cond = idx[:, -self.context_length:]
+```
+
+If the conversation grows beyond that, the oldest tokens are dropped. The model cannot attend to text
+outside the retained context window.
+
+This is why context length is a product constraint, not just a training hyperparameter.
+
+## Stop tokens
+
+The tokenizer's EOT token is:
+
+```python
+EOT_ID = 50256
+```
+
+During training, EOT appears between documents and after assistant messages. During inference, a chat
+loop can stop when EOT appears or when a formatted answer is complete.
+
+If the model was never trained to emit a clear stop token or answer delimiter, decoding has to guess
+when to stop.
+
+## Why generated text can drift
+
+During teacher-forced training, every input prefix comes from the dataset. During generation, prefixes
+come from the model itself. If the model samples a poor token early, future predictions condition on
+that poor token.
+
+This distribution shift is one reason post-training matters:
+
+- SFT teaches the answer format;
+- reward/preference methods push the model toward preferred completions;
+- RLVR/GRPO can reward final answers that satisfy an external verifier.
+
+## Useful generation diagnostics
+
+| Symptom | Likely cause | Check |
+|---|---|---|
+| Repeats forever | distribution too sharp or no learned stop behavior | lower max tokens, check EOT handling, adjust sampling |
+| Ignores instruction | base model not SFT-trained enough | test an SFT checkpoint |
+| Wrong answer format | SFT data format mismatch | inspect chat template and masks |
+| Random-looking text | undertrained model or high temperature | compare train/dev loss and lower temperature |
+| Crashes on long prompts | prompt exceeds context or device memory | crop context and inspect `context_length` |
+
+## Next
+
+You now have the foundation for the full pipeline. Continue to:
+
+- [Data handling](../01_data_pipeline.md)
+- [Pretraining](../02_pretraining.md)
+- [SFT](../03_sft.md)
diff --git a/docs/foundations/objectives.md b/docs/foundations/objectives.md
new file mode 100644
index 0000000..8dae25c
--- /dev/null
+++ b/docs/foundations/objectives.md
@@ -0,0 +1,249 @@
+# Objectives, Losses & Perplexity
+
+The architecture defines what the model can compute. The objective defines what behavior training
+rewards.
+
+For a decoder-only language model, the base objective is next-token prediction.
+
+## From logits to probability
+
+At position \(t\), the model emits logits:
+
+\[
+z_t \in \mathbb{R}^{V}
+\]
+
+Softmax turns logits into a distribution:
+
+\[
+p_\theta(x_{t+1}=i \mid x_{\leq t})
+= \frac{\exp(z_{t,i})}{\sum_{j=1}^{V}\exp(z_{t,j})}
+\]
+
+The target is one integer token id \(y_t\). Cross-entropy for that position is:
+
+\[
+\ell_t = -\log p_\theta(y_t \mid x_{\leq t})
+\]
+
+The batch loss is the mean over positions:
+
+\[
+\mathcal{L}_{\text{LM}}
+= -\frac{1}{BT}\sum_{b=1}^{B}\sum_{t=1}^{T}
+\log p_\theta(y_{b,t} \mid x_{b,\leq t})
+\]
+
+## The shift
+
+The model receives:
+
+\[
+x = [t_0,t_1,\ldots,t_{T-1}]
+\]
+
+and predicts:
+
+\[
+y = [t_1,t_2,\ldots,t_T]
+\]
+
+In `src/models/transformer.py`, the simple `forward` path computes cross-entropy over all positions:
+
+```python
+logits, loss = model(idx, targets)
+flat_logits = logits.view(B * T, C)
+targets = targets.view(B * T).long()
+loss = F.cross_entropy(flat_logits, targets)
+```
+
+The post-training SFT path makes the shift explicit because it needs a mask:
+
+```python
+logits = logits[:, :-1, :]
+targets = tokens[:, 1:]
+mask = loss_mask[:, 1:].to(logits.dtype)
+```
+
+## Perplexity
+
+Perplexity is exponentiated cross-entropy:
+
+\[
+\text{PPL} = \exp(\mathcal{L})
+\]
+
+If the model assigns high probability to the true next tokens, loss falls and perplexity falls.
+
+Interpretation:
+
+- loss near \(\log(V)\) means the model is close to uniform random guessing;
+- lower loss means the model is concentrating probability on plausible next tokens;
+- validation loss matters more than training loss for generalization.
+
+With `V = 50304`:
+
+\[
+\log(V) \approx 10.83
+\]
+
+So an untrained model often starts near that value.
+
+## SFT masked loss
+
+SFT still uses next-token cross-entropy, but only assistant completion tokens count:
+
+\[
+\mathcal{L}_{\text{SFT}}
+=
+\frac{\sum_{b,t} m_{b,t}\,\ell_{b,t}}
+{\sum_{b,t} m_{b,t}}
+\]
+
+where \(m_{b,t}=1\) for assistant tokens and \(0\) for prompt tokens.
+
+Implementation in `src/post_training/sft.py`:
+
+```python
+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)
+```
+
+This distinction is crucial. The model should learn how to answer the prompt, not how to predict the
+prompt itself.
+
+## Sequence log-probabilities
+
+Preference optimization and RL need the log-probability of an entire response, not only one token.
+
+For response tokens \(a_1,\ldots,a_L\) after prompt \(p\):
+
+\[
+\log \pi_\theta(a \mid p)
+= \sum_{t=1}^{L}
+\log \pi_\theta(a_t \mid p, a_{<t})
+\]
+
+The repo computes this in `src/post_training/rollout.py` with `sequence_logprobs`. It applies a
+response mask and sums token log-probs over answer positions.
+
+That one primitive is reused by:
+
+- DPO, ORPO, and KTO;
+- PPO policy ratios;
+- GRPO policy ratios;
+- KL measurements against a frozen reference model.
+
+## DPO objective
+
+DPO uses preference pairs: chosen response \(y_w\) and rejected response \(y_l\). It compares the policy
+against a frozen reference model:
+
+\[
+\Delta_\pi =
+\log \pi_\theta(y_w \mid x) - \log \pi_\theta(y_l \mid x)
+\]
+
+\[
+\Delta_{\text{ref}} =
+\log \pi_{\text{ref}}(y_w \mid x) - \log \pi_{\text{ref}}(y_l \mid x)
+\]
+
+\[
+\mathcal{L}_{\text{DPO}}
+=
+-\log \sigma\left(\beta(\Delta_\pi - \Delta_{\text{ref}})\right)
+\]
+
+In `src/post_training/dpo.py`:
+
+```python
+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()
+```
+
+Intuition: make the chosen response more likely than the rejected response, but measure the change
+relative to the reference model so the policy does not drift without constraint.
+
+## PPO objective in one picture
+
+PPO samples responses, scores them, and updates the policy using the ratio between new and old action
+probabilities:
+
+\[
+r_t(\theta) =
+\frac{\pi_\theta(a_t \mid s_t)}
+{\pi_{\text{old}}(a_t \mid s_t)}
+= \exp(\log \pi_\theta - \log \pi_{\text{old}})
+\]
+
+The clipped policy objective is:
+
+\[
+\mathcal{L}_{\text{PPO}}
+=
+-\mathbb{E}_t
+\left[
+\min
+\left(
+r_t(\theta) A_t,
+\text{clip}(r_t(\theta),1-\epsilon,1+\epsilon) A_t
+\right)
+\right]
+\]
+
+The repo implements that in `src/post_training/ppo.py`:
+
+```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)
+```
+
+The clip prevents one update from moving too far from the sampled policy.
+
+## GRPO objective in one picture
+
+GRPO avoids a learned value function. For each prompt, it samples a group of responses and normalizes
+their rewards within the group:
+
+\[
+A_i = \frac{r_i - \text{mean}(r_1,\ldots,r_G)}
+{\text{std}(r_1,\ldots,r_G)+\epsilon}
+\]
+
+That advantage says: "Was this answer better or worse than its siblings for the same prompt?"
+
+In `src/post_training/grpo.py`:
+
+```python
+r = rewards.view(-1, group_size)
+adv = (r - r.mean(1, keepdim=True)) / (r.std(1, keepdim=True) + eps)
+```
+
+This is useful for verifiable-reward reasoning tasks because it removes PPO's value head and critic
+training loop.
+
+## Objective comparison
+
+| Stage | Data | Main signal | Learns |
+|---|---|---|---|
+| Pretraining | raw token stream | next-token CE | language modeling |
+| SFT | prompt/answer examples | masked next-token CE | instruction following format |
+| Reward model | chosen/rejected pairs | Bradley-Terry preference loss | scalar preference scoring |
+| DPO | chosen/rejected pairs | sequence log-prob preference loss | preference alignment without RL rollout |
+| PPO | sampled responses + reward | clipped policy gradient | reward-seeking behavior under KL control |
+| GRPO | grouped sampled responses + verifier | group-relative clipped policy gradient | verifier-driven reasoning without critic |
+
+## Next
+
+Loss gives direction. Optimization decides whether the model can follow it reliably. Continue to
+[Optimization & Training Systems](optimization.md).
diff --git a/docs/foundations/optimization.md b/docs/foundations/optimization.md
new file mode 100644
index 0000000..70805d7
--- /dev/null
+++ b/docs/foundations/optimization.md
@@ -0,0 +1,220 @@
+# Optimization & Training Systems
+
+Once the loss is defined, training is an engineering problem: move parameters in the right direction
+without numerical instability, memory blowups, or throughput collapse.
+
+The main ingredients in this repo are:
+
+- AdamW;
+- linear warmup plus cosine learning-rate decay;
+- gradient accumulation;
+- gradient clipping;
+- bf16 autocast;
+- DistributedDataParallel for multi-GPU training.
+
+## The training step
+
+```mermaid
+flowchart LR
+ B["batch"] --> F["forward under autocast"]
+ F --> L["loss / grad_accum"]
+ L --> BW["backward"]
+ BW --> GA{"more microsteps?"}
+ GA -- yes --> B
+ GA -- no --> CLIP["clip grad norm"]
+ CLIP --> LR["set scheduled LR"]
+ LR --> STEP["AdamW step"]
+ STEP --> ZERO["zero gradients"]
+```
+
+The pretraining loop in `scripts/pretrain_base.py` uses this pattern:
+
+```python
+for micro in range(cfg.grad_accum):
+ xb, yb = next(batch_iter)
+ with amp_autocast(cfg.amp_dtype, ctx.device):
+ _, loss = model(xb, yb)
+ loss = loss / cfg.grad_accum
+ loss.backward()
+
+torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.grad_clip)
+optimizer.step()
+optimizer.zero_grad(set_to_none=True)
+```
+
+Dividing the loss by `grad_accum` keeps the gradient scale the same as if the full effective batch had
+fit in memory.
+
+## AdamW
+
+Adam keeps exponential moving averages of gradients and squared gradients:
+
+\[
+m_t = \beta_1 m_{t-1} + (1-\beta_1)g_t
+\]
+
+\[
+v_t = \beta_2 v_{t-1} + (1-\beta_2)g_t^2
+\]
+
+After bias correction, parameters are updated approximately by:
+
+\[
+\theta_{t+1}
+= \theta_t - \eta \frac{\hat{m}_t}{\sqrt{\hat{v}_t}+\epsilon}
+\]
+
+AdamW decouples weight decay from the gradient update:
+
+\[
+\theta_{t+1}
+= \theta_t - \eta \left(
+\frac{\hat{m}_t}{\sqrt{\hat{v}_t}+\epsilon}
++ \lambda \theta_t
+\right)
+\]
+
+The repo applies weight decay only to matrix-like parameters:
+
+```python
+if p.dim() >= 2:
+ decay.append(p)
+else:
+ no_decay.append(p)
+```
+
+This is the standard GPT recipe: decay large weight matrices, but not biases, LayerNorm scales, or
+one-dimensional parameters.
+
+## Learning-rate warmup and cosine decay
+
+The learning rate is small at the start, ramps up, then decays:
+
+\[
+\eta(s) =
+\eta_{\max}\frac{s+1}{S_{\text{warmup}}}
+\quad \text{if } s < S_{\text{warmup}}
+\]
+
+After warmup:
+
+\[
+\eta(s) =
+\eta_{\min}
++ \frac{1}{2}(1+\cos(\pi p))(\eta_{\max}-\eta_{\min})
+\]
+
+where:
+
+\[
+p = \frac{s-S_{\text{warmup}}}{S_{\max}-S_{\text{warmup}}}
+\]
+
+Implementation in `src/post_training/optim.py`:
+
+```python
+if step < warmup_steps:
+ return lr * (step + 1) / max(1, warmup_steps)
+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)
+```
+
+Warmup prevents early unstable updates while weights are still poorly calibrated. Cosine decay reduces
+step size as training approaches the end of the budget.
+
+## Gradient accumulation
+
+If one batch is too large for GPU memory, split it into microbatches:
+
+\[
+B_{\text{effective}} = B_{\text{micro}} \times N_{\text{accum}} \times N_{\text{gpus}}
+\]
+
+Example:
+
+- microbatch size: 8;
+- accumulation steps: 12;
+- GPUs: 2.
+
+\[
+B_{\text{effective}} = 8 \times 12 \times 2 = 192
+\]
+
+The optimizer steps once after all microbatches have contributed gradients.
+
+## Gradient clipping
+
+Gradient clipping limits the global norm:
+
+\[
+g \leftarrow g \cdot \min\left(1, \frac{c}{\|g\|_2}\right)
+\]
+
+If the gradient norm is below the threshold \(c\), nothing changes. If it is too large, the whole
+gradient vector is scaled down. This is a stability guard, especially useful in RL and long-sequence
+training.
+
+## bf16 autocast
+
+`bf16` uses fewer bits than fp32, but keeps an 8-bit exponent like fp32. That makes it much more
+forgiving than fp16 for deep learning training.
+
+The repo uses autocast for forward computation:
+
+```python
+with amp_autocast(cfg.amp_dtype, ctx.device):
+ logits, _ = model(tokens)
+ loss = sft_loss(logits, tokens, mask)
+```
+
+Model parameters usually remain fp32. Many matrix multiplications run in bf16, improving memory and
+throughput on supported GPUs.
+
+## DistributedDataParallel
+
+DDP creates one process per GPU. Each process:
+
+1. owns a full copy of the model;
+2. receives a different shard or random stream of data;
+3. computes gradients locally;
+4. synchronizes gradients across processes before the optimizer step.
+
+With gradient accumulation, synchronization is needed only on the last microstep. The repo uses
+`model.no_sync()` for earlier microsteps to avoid unnecessary communication.
+
+```mermaid
+flowchart LR
+ R0["rank 0 GPU"] --> G["gradient all-reduce"]
+ R1["rank 1 GPU"] --> G
+ G --> U0["rank 0 optimizer step"]
+ G --> U1["rank 1 optimizer step"]
+```
+
+## What to watch during training
+
+| Metric | Healthy behavior | Problem signal |
+|---|---|---|
+| train loss | falls steadily | flat near random baseline |
+| dev loss | falls, then stabilizes | rises while train loss falls |
+| grad norm | finite, bounded after clipping | NaN or repeated huge spikes |
+| tokens/sec | stable for same config | sudden drop or dataloader stall |
+| KL in RL stages | bounded | runaway drift from reference |
+| reward in RL stages | rises with variance | zero signal for many iterations |
+
+## Memory levers
+
+If a config does not fit, reduce in this order:
+
+1. `batch_size`;
+2. `context_length`;
+3. `n_blocks`;
+4. `n_embed`;
+5. `n_head` only if it still divides `n_embed`.
+
+Context length is especially expensive because attention uses a \(T \times T\) score matrix.
+
+## Next
+
+After training, the model still only emits logits. Generation turns those logits into text. Continue
+to [Generation & Sampling](generation.md).
diff --git a/docs/foundations/tokenization.md b/docs/foundations/tokenization.md
new file mode 100644
index 0000000..9745aa9
--- /dev/null
+++ b/docs/foundations/tokenization.md
@@ -0,0 +1,159 @@
+# Tokenization & Data Shapes
+
+The Transformer never sees characters or words. It sees integer token ids. A tokenizer is the boundary
+between language and tensors.
+
+This repo uses OpenAI's `r50k_base` tokenizer through `tiktoken`, with:
+
+- vocabulary size `50304`;
+- end-of-text token `<|endoftext|>` with id `50256`;
+- plain text role markers for chat because the tokenizer has no custom chat tokens.
+
+## Why subword tokenization exists
+
+A word-level vocabulary cannot handle rare names, typos, code identifiers, URLs, and new terms without
+exploding in size. A character-level vocabulary handles everything but makes sequences long. Subword
+tokenization is the compromise: frequent words can be one token, rare words can be decomposed.
+
+```mermaid
+flowchart LR
+ T["The tokenizer sees text"] --> A["common words -> short token sequences"]
+ T --> B["rare words -> subword pieces"]
+ T --> C["punctuation/code -> reusable fragments"]
+ A --> IDS["integer ids"]
+ B --> IDS
+ C --> IDS
+```
+
+The original BPE idea is simple: start with small units, repeatedly merge frequent adjacent pairs, and
+end with a fixed vocabulary of reusable pieces. The repo does not train its own tokenizer; it reuses
+`r50k_base`.
+
+## Pretraining shape: one long token stream
+
+For pretraining, documents are converted into one flat array:
+
+\[
+[d_1, \text{EOT}, d_2, \text{EOT}, \ldots, d_N, \text{EOT}]
+\]
+
+`scripts/prepare_pretrain_data.py` streams Pile shards, tokenizes documents, appends EOT, and writes
+the result to HDF5:
+
+```python
+for ids in enc.encode_ordinary_batch(docs):
+ buf.extend(ids)
+ buf.append(EOT_ID)
+ if len(buf) >= WRITE_CHUNK:
+ flush()
+```
+
+The training loader slices random windows of length `context_length + 1`. The first `context_length`
+tokens are inputs. The next `context_length` tokens are targets shifted by one position:
+
+\[
+x = [t_0, t_1, \ldots, t_{T-1}]
+\]
+
+\[
+y = [t_1, t_2, \ldots, t_T]
+\]
+
+That shift is the entire next-token prediction task.
+
+```mermaid
+flowchart LR
+ H[(pile_train.h5 flat ids)] --> W["sample T+1-token window"]
+ W --> X["input: tokens 0..T-1"]
+ W --> Y["target: tokens 1..T"]
+ X --> M["Transformer"]
+ M --> L["cross-entropy against target"]
+ Y --> L
+```
+
+## SFT shape: tokens plus a loss mask
+
+SFT examples are conversations. We want the model to learn the assistant answer, not memorize the user
+prompt. So the data contains two aligned arrays:
+
+- `tokens`: token ids;
+- `loss_mask`: `1` for assistant completion tokens, `0` for prompt tokens.
+
+The chat template is plain text:
+
+```text
+<|user|>
+{question}<|endoftext|><|assistant|>
+{answer}<|endoftext|>
+```
+
+The key implementation is in `src/post_training/chat_template.py`:
+
+```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))
+ids.append(EOT_ID)
+mask.append(1 if is_completion else 0)
+```
+
+The mask aligns with the token ids:
+
+| Span | Example | Mask |
+|---|---|---|
+| user marker | `<|user|>` | 0 |
+| user question | `What is 2+2?` | 0 |
+| assistant marker | `<|assistant|>` | 0 |
+| assistant answer | `<answer>4</answer>` | 1 |
+| assistant EOT | `<|endoftext|>` | 1 |
+
+## Preference shape: prompt, chosen, rejected
+
+Preference learning uses pairs:
+
+```json
+{"prompt": "...", "chosen": "...", "rejected": "..."}
+```
+
+Both responses share the same prompt. That matters because DPO and reward modeling should compare
+answer quality, not prompt difficulty.
+
+For a batch, the loader creates two tokenized sequences:
+
+\[
+\text{chosen ids} = \text{chat}(prompt, chosen)
+\]
+
+\[
+\text{rejected ids} = \text{chat}(prompt, rejected)
+\]
+
+The chosen and rejected sides are padded to the same length for batching. The repo tracks true sequence
+lengths so the reward model can read the last real token instead of a padding token.
+
+## RL prompt shape: prompt plus verifiable gold answer
+
+PPO and GRPO need prompts that can be scored after generation:
+
+```json
+{"prompt": "Jan has 3 apples...", "gold": "12"}
+```
+
+The verifier extracts the model's final answer and compares it to `gold`. This is called verifiable
+reward because the training signal does not require a human labeler or a learned reward model.
+
+## Common shape bugs
+
+| Bug | Symptom | Prevention |
+|---|---|---|
+| Target not shifted | Model learns to copy the current token. | Always predict `tokens[:, 1:]` from `tokens[:, :-1]`. |
+| Prompt tokens included in SFT loss | Model wastes capacity predicting user input. | Use `loss_mask` and average over masked positions only. |
+| Missing EOT | Model does not learn when to stop. | Include EOT after documents and assistant messages. |
+| Preference prompt mismatch | Reward/DPO compares different tasks. | Normalize to shared prompt plus chosen/rejected responses. |
+| Padding used as reward position | Reward model trains on meaningless pad hidden states. | Track `seq_lengths` and gather the last real token. |
+
+## Next
+
+Once text is tokenized, the model needs to turn ids into vectors. Continue to
+[Decoder-Only Transformer](transformer.md).
diff --git a/docs/foundations/transformer.md b/docs/foundations/transformer.md
new file mode 100644
index 0000000..5b368d6
--- /dev/null
+++ b/docs/foundations/transformer.md
@@ -0,0 +1,234 @@
+# Decoder-Only Transformer
+
+This repo implements a GPT-style decoder-only Transformer. "Decoder-only" means:
+
+- the model reads a single token sequence;
+- each position can attend only to previous positions;
+- the output at every position is a distribution over the next token.
+
+It is the right architecture for autoregressive language modeling:
+
+\[
+p_\theta(x_t \mid x_{<t})
+\]
+
+## The forward pass
+
+```mermaid
+flowchart TD
+ IDS["token ids (B, T)"] --> TOK["token embedding (B, T, C)"]
+ IDS --> POS["position ids 0..T-1"]
+ POS --> PE["position embedding (T, C)"]
+ TOK --> SUM["token + position"]
+ PE --> SUM
+ SUM --> B1["Block 1"]
+ B1 --> B2["Block 2"]
+ B2 --> BN["... N blocks"]
+ BN --> LN["final LayerNorm"]
+ LN --> HEAD["lm_head Linear(C -> vocab)"]
+ HEAD --> LOGITS["logits (B, T, V)"]
+```
+
+The implementation is in `src/models/transformer.py`:
+
+```python
+self.token_embed = nn.Embedding(vocab_size, n_embed)
+self.position_embed = nn.Embedding(context_length, n_embed)
+self.attn_blocks = nn.ModuleList([
+ Block(n_head, n_embed, context_length) for _ in range(N_BLOCKS)
+])
+self.layer_norm = nn.LayerNorm(n_embed)
+self.lm_head = nn.Linear(n_embed, vocab_size)
+```
+
+Shape symbols used throughout the docs:
+
+| Symbol | Meaning |
+|---|---|
+| `B` | batch size |
+| `T` | sequence length / context length |
+| `C` | embedding width, `n_embed` |
+| `H` | number of attention heads |
+| `D` | head width, usually `C / H` |
+| `V` | vocabulary size |
+
+## Embeddings
+
+Token ids are categorical. The embedding table is a learned lookup:
+
+\[
+E_{\text{tok}} \in \mathbb{R}^{V \times C}
+\]
+
+For token id \(x_t\), the token vector is:
+
+\[
+e_t = E_{\text{tok}}[x_t]
+\]
+
+The model also learns absolute position embeddings:
+
+\[
+E_{\text{pos}} \in \mathbb{R}^{T_{\max} \times C}
+\]
+
+The input to the first block is:
+
+\[
+h_t^{(0)} = E_{\text{tok}}[x_t] + E_{\text{pos}}[t]
+\]
+
+In code:
+
+```python
+tok_embedding = self.token_embed(idx)
+pos_embedding = self.position_embed(self.pos_idxs[:T])
+return tok_embedding + pos_embedding
+```
+
+The position embedding is necessary because attention alone is permutation-equivariant: without
+position information, the model would not know whether a token occurred first, last, or in the middle.
+
+## Transformer block
+
+Each block in `src/models/transformer_block.py` uses pre-norm residual structure:
+
+```python
+x = x + self.attn(self.ln1(x))
+x = x + self.mlp(self.ln2(x))
+```
+
+Mathematically:
+
+\[
+u = x + \text{MHA}(\text{LN}(x))
+\]
+
+\[
+y = u + \text{MLP}(\text{LN}(u))
+\]
+
+This gives each block two jobs:
+
+- attention moves information across token positions;
+- the MLP transforms each position independently.
+
+## Why residual connections matter
+
+A residual block learns an update, not a full replacement:
+
+\[
+y = x + f(x)
+\]
+
+If a layer is not useful yet, it can learn a small update and let information pass through. This makes
+deep stacks trainable because gradients have a direct path backward through the addition.
+
+## Why LayerNorm appears before sublayers
+
+LayerNorm normalizes each token vector across its feature dimension:
+
+\[
+\text{LN}(x) = \gamma \odot \frac{x - \mu}{\sqrt{\sigma^2 + \epsilon}} + \beta
+\]
+
+For a token vector \(x \in \mathbb{R}^{C}\):
+
+\[
+\mu = \frac{1}{C} \sum_{i=1}^{C} x_i
+\]
+
+\[
+\sigma^2 = \frac{1}{C} \sum_{i=1}^{C} (x_i - \mu)^2
+\]
+
+This repo uses pre-norm (`LN -> sublayer -> residual`) instead of post-norm (`sublayer -> residual ->
+LN`). Pre-norm is common in GPT-like models because it tends to make deeper stacks easier to optimize.
+
+## MLP / feed-forward network
+
+The block MLP in `src/models/mlp.py` is:
+
+```python
+self.hidden = nn.Linear(n_embed, 4 * n_embed)
+self.relu = nn.ReLU()
+self.proj = nn.Linear(4 * n_embed, n_embed)
+```
+
+For each position independently:
+
+\[
+\text{MLP}(x) = W_2 \, \text{ReLU}(W_1 x + b_1) + b_2
+\]
+
+where:
+
+- \(W_1\) expands from \(C\) to \(4C\);
+- \(W_2\) projects from \(4C\) back to \(C\).
+
+Attention lets tokens communicate. The MLP gives each token vector nonlinear compute after that
+communication.
+
+## Logits and the language-model head
+
+After the final block and final norm:
+
+\[
+z_t = W_{\text{lm}} h_t + b_{\text{lm}}
+\]
+
+The result \(z_t \in \mathbb{R}^{V}\) is a vector of logits: one unnormalized score per token in the
+vocabulary.
+
+The probability distribution comes from softmax:
+
+\[
+p_\theta(x_{t+1}=i \mid x_{\leq t}) =
+\frac{\exp(z_{t,i})}{\sum_{j=1}^{V}\exp(z_{t,j})}
+\]
+
+## Parameter count intuition
+
+Ignoring biases and norms, a rough per-block parameter estimate is:
+
+\[
+\text{attention} \approx 4C^2
+\]
+
+because Q, K, V, and the output projection are each \(C \times C\).
+
+\[
+\text{MLP} \approx 8C^2
+\]
+
+because \(C \to 4C\) and \(4C \to C\).
+
+So each block is roughly:
+
+\[
+12C^2
+\]
+
+The embedding and LM head add:
+
+\[
+V C + C V
+\]
+
+This repo does not tie token embeddings and output embeddings, so the input embedding and `lm_head`
+are separate parameter matrices.
+
+## Repo-specific architecture notes
+
+| Choice | Repo implementation | Consequence |
+|---|---|---|
+| Absolute learned positions | `nn.Embedding(context_length, n_embed)` | Simple and readable; fixed max context. |
+| Causal attention mask | lower-triangular buffer in each head | Prevents future-token leakage. |
+| MLP activation | ReLU | Educationally simple; many production GPT models use GELU/SwiGLU variants. |
+| Dropout | not present in base modules | Less code noise; regularization comes mostly from data and optimizer choices. |
+| Weight tying | not used | Easier to read; more parameters than tied embeddings. |
+| Post-training heads | use `forward_hidden` | Reward/value heads reuse the same backbone. |
+
+## Next
+
+The most important sublayer is attention. Continue to [Attention, Masks & Heads](attention.md).
diff --git a/docs/javascripts/mathjax.js b/docs/javascripts/mathjax.js
new file mode 100644
index 0000000..80e81ba
--- /dev/null
+++ b/docs/javascripts/mathjax.js
@@ -0,0 +1,12 @@
+window.MathJax = {
+ tex: {
+ inlineMath: [["\\(", "\\)"]],
+ displayMath: [["\\[", "\\]"]],
+ processEscapes: true,
+ processEnvironments: true
+ },
+ options: {
+ ignoreHtmlClass: ".*|",
+ processHtmlClass: "arithmatex"
+ }
+};
diff --git a/mkdocs.yml b/mkdocs.yml
index c46685c..c11f5f2 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -50,6 +50,8 @@ markdown_extensions:
- pymdownx.highlight:
anchor_linenums: true
- pymdownx.inlinehilite
+ - pymdownx.arithmatex:
+ generic: true
- pymdownx.snippets:
base_path: ["."] # so howto/commands.md can include the root POST_TRAINING.md
- pymdownx.superfences:
@@ -62,9 +64,19 @@ markdown_extensions:
extra_javascript:
- https://unpkg.com/mermaid@11/dist/mermaid.min.js # live hand-drawn mermaid in <details>
+ - javascripts/mathjax.js
+ - https://unpkg.com/mathjax@3/es5/tex-mml-chtml.js
nav:
- Home: README.md
+ - Foundations:
+ - Overview: foundations/README.md
+ - Tokenization & Data Shapes: foundations/tokenization.md
+ - Decoder-Only Transformer: foundations/transformer.md
+ - Attention, Masks & Heads: foundations/attention.md
+ - Objectives, Losses & Perplexity: foundations/objectives.md
+ - Optimization & Training Systems: foundations/optimization.md
+ - Generation & Sampling: foundations/generation.md
- Theory & Pipeline:
- Data handling: 01_data_pipeline.md
- Pretraining: 02_pretraining.md