A straightforward method for training your LLM, from downloading data to generating text.
docs: add hand-drawn diagrams and a reproducible generator
FareedKhan-dev040f478c5169
diff --git a/images/00_pipeline.mmd b/images/00_pipeline.mmdnew file mode 100644index 0000000..34613d5--- /dev/null+++ b/images/00_pipeline.mmd@@ -0,0 +1,21 @@+flowchart LR+ PILE([The Pile<br/>raw text]):::data --> PRE{{Pretrain<br/>base ~400M}}:::model+ PRE --> SFT{{SFT<br/>instruct}}:::model+ SFT --> RM{{Reward Model<br/>Bradley-Terry}}:::rl+ SFT --> DPO{{DPO / ORPO / KTO}}:::rl+ SFT --> GRPO{{GRPO / RLVR}}:::rl+ RM -->|reward signal| PPO{{PPO}}:::rl+ PPO --> EVAL([GSM8K eval<br/>+ chat]):::eval+ DPO --> EVAL+ GRPO --> EVAL++ classDef data fill:#cdeccd,stroke:#2e7d32,stroke-width:2px,color:#143d1a;+ classDef store fill:#cfeee9,stroke:#1f9e8f,stroke-width:2px,color:#0c3a34;+ classDef proc fill:#cfe3fb,stroke:#1565c0,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:#ffd4d4,stroke:#c0392b,stroke-width:2px,color:#5c1212;+ classDef ckpt fill:#ececec,stroke:#666666,stroke-width:2px,color:#222222;+ classDef eval fill:#e7d6fb,stroke:#8e44ad,stroke-width:2px,color:#3d1a5a;+ classDef out fill:#e7d6fb,stroke:#7b3fbf,stroke-width:2px,color:#3d1a5a;+ classDef op fill:#ffffff,stroke:#888888,stroke-width:2px,color:#333333;diff --git a/images/00_pipeline.png b/images/00_pipeline.pngnew file mode 100644index 0000000..b0f705cBinary files /dev/null and b/images/00_pipeline.png differdiff --git a/images/01_data.mmd b/images/01_data.mmdnew file mode 100644index 0000000..473525a--- /dev/null+++ b/images/01_data.mmd@@ -0,0 +1,16 @@+flowchart LR+ A1([Pretrain: The Pile]):::data --> A2[tiktoken r50k_base<br/>stream + encode]:::proc --> A3[(pile_train.h5<br/>flat int32 tokens)]:::store+ B1([SFT: Alpaca · Dolly · GSM8K]):::data --> B2[chat template<br/>+ mask the prompt]:::proc --> B3[(sft_packed.h5<br/>tokens + loss_mask)]:::store+ C1([Prefs: HH-RLHF · UltraFeedback]):::data --> C2[split prompt /<br/>chosen / rejected]:::proc --> C3[(preferences.jsonl)]:::store+ D1([RL: GSM8K · arithmetic]):::data --> D2[keep the gold answer]:::proc --> D3[(rl_prompts.jsonl)]:::store++ classDef data fill:#cdeccd,stroke:#2e7d32,stroke-width:2px,color:#143d1a;+ classDef store fill:#cfeee9,stroke:#1f9e8f,stroke-width:2px,color:#0c3a34;+ classDef proc fill:#cfe3fb,stroke:#1565c0,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:#ffd4d4,stroke:#c0392b,stroke-width:2px,color:#5c1212;+ classDef ckpt fill:#ececec,stroke:#666666,stroke-width:2px,color:#222222;+ classDef eval fill:#e7d6fb,stroke:#8e44ad,stroke-width:2px,color:#3d1a5a;+ classDef out fill:#e7d6fb,stroke:#7b3fbf,stroke-width:2px,color:#3d1a5a;+ classDef op fill:#ffffff,stroke:#888888,stroke-width:2px,color:#333333;diff --git a/images/01_data.png b/images/01_data.pngnew file mode 100644index 0000000..2cedba7Binary files /dev/null and b/images/01_data.png differdiff --git a/images/02_tokenization.mmd b/images/02_tokenization.mmdnew file mode 100644index 0000000..ae9c6b1--- /dev/null+++ b/images/02_tokenization.mmd@@ -0,0 +1,17 @@+flowchart LR+ T1["raw text<br/>'Once upon a time'"]:::data --> T2["tiktoken<br/>r50k_base"]:::proc+ T2 --> T3["token ids<br/>[7454, 2402, 257, 640]"]:::store+ T3 --> T4["append <|endoftext|><br/>(id 50256)"]:::proc+ T4 --> T5["fixed windows of<br/>context_length + 1"]:::store+ T5 --> T6["x = window[:-1]<br/>y = window[1:]"]:::out++ classDef data fill:#cdeccd,stroke:#2e7d32,stroke-width:2px,color:#143d1a;+ classDef store fill:#cfeee9,stroke:#1f9e8f,stroke-width:2px,color:#0c3a34;+ classDef proc fill:#cfe3fb,stroke:#1565c0,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:#ffd4d4,stroke:#c0392b,stroke-width:2px,color:#5c1212;+ classDef ckpt fill:#ececec,stroke:#666666,stroke-width:2px,color:#222222;+ classDef eval fill:#e7d6fb,stroke:#8e44ad,stroke-width:2px,color:#3d1a5a;+ classDef out fill:#e7d6fb,stroke:#7b3fbf,stroke-width:2px,color:#3d1a5a;+ classDef op fill:#ffffff,stroke:#888888,stroke-width:2px,color:#333333;diff --git a/images/02_tokenization.png b/images/02_tokenization.pngnew file mode 100644index 0000000..f22c469Binary files /dev/null and b/images/02_tokenization.png differdiff --git a/images/03_mlp.mmd b/images/03_mlp.mmdnew file mode 100644index 0000000..0b02941--- /dev/null+++ b/images/03_mlp.mmd@@ -0,0 +1,16 @@+flowchart LR+ M1["x (B, T, n_embed)"]:::data --> M2["Linear<br/>n_embed -> 4 · n_embed"]:::proc+ M2 --> M3["ReLU"]:::proc+ M3 --> M4["Linear<br/>4 · n_embed -> n_embed"]:::proc+ M4 --> M5["out (B, T, n_embed)"]:::out++ classDef data fill:#cdeccd,stroke:#2e7d32,stroke-width:2px,color:#143d1a;+ classDef store fill:#cfeee9,stroke:#1f9e8f,stroke-width:2px,color:#0c3a34;+ classDef proc fill:#cfe3fb,stroke:#1565c0,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:#ffd4d4,stroke:#c0392b,stroke-width:2px,color:#5c1212;+ classDef ckpt fill:#ececec,stroke:#666666,stroke-width:2px,color:#222222;+ classDef eval fill:#e7d6fb,stroke:#8e44ad,stroke-width:2px,color:#3d1a5a;+ classDef out fill:#e7d6fb,stroke:#7b3fbf,stroke-width:2px,color:#3d1a5a;+ classDef op fill:#ffffff,stroke:#888888,stroke-width:2px,color:#333333;diff --git a/images/03_mlp.png b/images/03_mlp.pngnew file mode 100644index 0000000..b9a88baBinary files /dev/null and b/images/03_mlp.png differdiff --git a/images/04_attention_head.mmd b/images/04_attention_head.mmdnew file mode 100644index 0000000..2bfb5d9--- /dev/null+++ b/images/04_attention_head.mmd@@ -0,0 +1,21 @@+flowchart LR+ X["x : token vectors<br/>(B, T, C)"]:::data --> Q["Q = x Wq"]:::proc+ X --> K["K = x Wk"]:::proc+ X --> V["V = x Wv"]:::proc+ Q --> S["scores = Q Kᵀ / √d"]:::rl+ K --> S+ S --> M["causal mask<br/>+ softmax"]:::rl+ M --> O["weights · V"]:::rl+ V --> O+ O --> H["head output<br/>(B, T, head_size)"]:::out++ classDef data fill:#cdeccd,stroke:#2e7d32,stroke-width:2px,color:#143d1a;+ classDef store fill:#cfeee9,stroke:#1f9e8f,stroke-width:2px,color:#0c3a34;+ classDef proc fill:#cfe3fb,stroke:#1565c0,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:#ffd4d4,stroke:#c0392b,stroke-width:2px,color:#5c1212;+ classDef ckpt fill:#ececec,stroke:#666666,stroke-width:2px,color:#222222;+ classDef eval fill:#e7d6fb,stroke:#8e44ad,stroke-width:2px,color:#3d1a5a;+ classDef out fill:#e7d6fb,stroke:#7b3fbf,stroke-width:2px,color:#3d1a5a;+ classDef op fill:#ffffff,stroke:#888888,stroke-width:2px,color:#333333;diff --git a/images/04_attention_head.png b/images/04_attention_head.pngnew file mode 100644index 0000000..f6cc2f0Binary files /dev/null and b/images/04_attention_head.png differdiff --git a/images/05_multi_head_attention.mmd b/images/05_multi_head_attention.mmdnew file mode 100644index 0000000..a0aa372--- /dev/null+++ b/images/05_multi_head_attention.mmd@@ -0,0 +1,20 @@+flowchart LR+ X["x (B, T, C)"]:::data --> H1["head 1"]:::proc+ X --> H2["head 2"]:::proc+ X --> H3["... (n_head heads)"]:::proc+ H1 --> CC["concat heads<br/>(B, T, C)"]:::rl+ H2 --> CC+ H3 --> CC+ CC --> PJ["output projection<br/>Linear C -> C"]:::proc+ PJ --> HO["multi-head output"]:::out++ classDef data fill:#cdeccd,stroke:#2e7d32,stroke-width:2px,color:#143d1a;+ classDef store fill:#cfeee9,stroke:#1f9e8f,stroke-width:2px,color:#0c3a34;+ classDef proc fill:#cfe3fb,stroke:#1565c0,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:#ffd4d4,stroke:#c0392b,stroke-width:2px,color:#5c1212;+ classDef ckpt fill:#ececec,stroke:#666666,stroke-width:2px,color:#222222;+ classDef eval fill:#e7d6fb,stroke:#8e44ad,stroke-width:2px,color:#3d1a5a;+ classDef out fill:#e7d6fb,stroke:#7b3fbf,stroke-width:2px,color:#3d1a5a;+ classDef op fill:#ffffff,stroke:#888888,stroke-width:2px,color:#333333;diff --git a/images/05_multi_head_attention.png b/images/05_multi_head_attention.pngnew file mode 100644index 0000000..ae4c6f5Binary files /dev/null and b/images/05_multi_head_attention.png differdiff --git a/images/06_transformer_block.mmd b/images/06_transformer_block.mmdnew file mode 100644index 0000000..2eba85b--- /dev/null+++ b/images/06_transformer_block.mmd@@ -0,0 +1,17 @@+flowchart LR+ X["x"]:::data --> LN1["LayerNorm"]:::proc --> AT["Multi-Head Attention"]:::rl --> A1(("+")):::op+ X --> A1+ A1 --> LN2["LayerNorm"]:::proc --> ML["MLP"]:::proc --> A2(("+")):::op+ A1 --> A2+ A2 --> BO["block output"]:::out++ classDef data fill:#cdeccd,stroke:#2e7d32,stroke-width:2px,color:#143d1a;+ classDef store fill:#cfeee9,stroke:#1f9e8f,stroke-width:2px,color:#0c3a34;+ classDef proc fill:#cfe3fb,stroke:#1565c0,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:#ffd4d4,stroke:#c0392b,stroke-width:2px,color:#5c1212;+ classDef ckpt fill:#ececec,stroke:#666666,stroke-width:2px,color:#222222;+ classDef eval fill:#e7d6fb,stroke:#8e44ad,stroke-width:2px,color:#3d1a5a;+ classDef out fill:#e7d6fb,stroke:#7b3fbf,stroke-width:2px,color:#3d1a5a;+ classDef op fill:#ffffff,stroke:#888888,stroke-width:2px,color:#333333;diff --git a/images/06_transformer_block.png b/images/06_transformer_block.pngnew file mode 100644index 0000000..7b1b4c2Binary files /dev/null and b/images/06_transformer_block.png differdiff --git a/images/07_transformer.mmd b/images/07_transformer.mmdnew file mode 100644index 0000000..188e16f--- /dev/null+++ b/images/07_transformer.mmd@@ -0,0 +1,21 @@+flowchart LR+ I["token ids (B, T)"]:::data --> TE["token embedding"]:::proc+ I --> PE["position embedding"]:::proc+ TE --> SUM(("+")):::op+ PE --> SUM+ SUM --> BLK["N_BLOCKS ×<br/>Transformer Block"]:::model+ BLK --> LNF["final LayerNorm"]:::proc+ LNF --> LMH["lm_head<br/>Linear -> vocab_size"]:::proc+ LMH --> LOG["logits (B, T, vocab)"]:::out+ LOG -. targets present .-> CE["cross-entropy loss"]:::loss++ classDef data fill:#cdeccd,stroke:#2e7d32,stroke-width:2px,color:#143d1a;+ classDef store fill:#cfeee9,stroke:#1f9e8f,stroke-width:2px,color:#0c3a34;+ classDef proc fill:#cfe3fb,stroke:#1565c0,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:#ffd4d4,stroke:#c0392b,stroke-width:2px,color:#5c1212;+ classDef ckpt fill:#ececec,stroke:#666666,stroke-width:2px,color:#222222;+ classDef eval fill:#e7d6fb,stroke:#8e44ad,stroke-width:2px,color:#3d1a5a;+ classDef out fill:#e7d6fb,stroke:#7b3fbf,stroke-width:2px,color:#3d1a5a;+ classDef op fill:#ffffff,stroke:#888888,stroke-width:2px,color:#333333;diff --git a/images/07_transformer.png b/images/07_transformer.pngnew file mode 100644index 0000000..9b9904fBinary files /dev/null and b/images/07_transformer.png differdiff --git a/images/08_training_loop.mmd b/images/08_training_loop.mmdnew file mode 100644index 0000000..18f32fb--- /dev/null+++ b/images/08_training_loop.mmd@@ -0,0 +1,14 @@+flowchart LR+ D[(pile_train.h5)]:::store --> IT["get_batch_iterator<br/>random windows"]:::proc --> FW["forward<br/>(bf16 autocast)"]:::model --> CE["cross-entropy"]:::loss --> BW["backward<br/>× grad_accum"]:::proc --> CL["clip grad norm 1.0"]:::proc --> ST["AdamW step<br/>cosine LR + warmup"]:::model --> CK[(checkpoint)]:::ckpt+ ST -. next step .-> IT++ classDef data fill:#cdeccd,stroke:#2e7d32,stroke-width:2px,color:#143d1a;+ classDef store fill:#cfeee9,stroke:#1f9e8f,stroke-width:2px,color:#0c3a34;+ classDef proc fill:#cfe3fb,stroke:#1565c0,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:#ffd4d4,stroke:#c0392b,stroke-width:2px,color:#5c1212;+ classDef ckpt fill:#ececec,stroke:#666666,stroke-width:2px,color:#222222;+ classDef eval fill:#e7d6fb,stroke:#8e44ad,stroke-width:2px,color:#3d1a5a;+ classDef out fill:#e7d6fb,stroke:#7b3fbf,stroke-width:2px,color:#3d1a5a;+ classDef op fill:#ffffff,stroke:#888888,stroke-width:2px,color:#333333;diff --git a/images/08_training_loop.png b/images/08_training_loop.pngnew file mode 100644index 0000000..a59ceceBinary files /dev/null and b/images/08_training_loop.png differdiff --git a/images/09_sft.mmd b/images/09_sft.mmdnew file mode 100644index 0000000..c22b636--- /dev/null+++ b/images/09_sft.mmd@@ -0,0 +1,15 @@+flowchart LR+ S0[(sft_packed.h5<br/>tokens + loss_mask)]:::store --> S1["Transformer forward"]:::model --> S2["shift: predict t+1"]:::proc --> S3["per-token cross-entropy"]:::loss+ S0 --> S4["loss_mask = 1 only on<br/>assistant tokens"]:::proc --> S5["mean over masked tokens"]:::loss+ S3 --> S5 --> S6["AdamW step"]:::model++ classDef data fill:#cdeccd,stroke:#2e7d32,stroke-width:2px,color:#143d1a;+ classDef store fill:#cfeee9,stroke:#1f9e8f,stroke-width:2px,color:#0c3a34;+ classDef proc fill:#cfe3fb,stroke:#1565c0,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:#ffd4d4,stroke:#c0392b,stroke-width:2px,color:#5c1212;+ classDef ckpt fill:#ececec,stroke:#666666,stroke-width:2px,color:#222222;+ classDef eval fill:#e7d6fb,stroke:#8e44ad,stroke-width:2px,color:#3d1a5a;+ classDef out fill:#e7d6fb,stroke:#7b3fbf,stroke-width:2px,color:#3d1a5a;+ classDef op fill:#ffffff,stroke:#888888,stroke-width:2px,color:#333333;diff --git a/images/09_sft.png b/images/09_sft.pngnew file mode 100644index 0000000..890d263Binary files /dev/null and b/images/09_sft.png differdiff --git a/images/10_reward_model.mmd b/images/10_reward_model.mmdnew file mode 100644index 0000000..a189c91--- /dev/null+++ b/images/10_reward_model.mmd@@ -0,0 +1,14 @@+flowchart LR+ R0["prompt + chosen / rejected"]:::data --> R1["SFT backbone<br/>forward_hidden"]:::model --> R2["take last real token"]:::proc --> R3["reward head<br/>Linear -> 1"]:::proc+ R3 --> R4["r_chosen , r_rejected"]:::rl --> R5["Bradley-Terry loss<br/>-log σ(r_chosen - r_rejected)"]:::loss --> R6["AdamW step"]:::model++ classDef data fill:#cdeccd,stroke:#2e7d32,stroke-width:2px,color:#143d1a;+ classDef store fill:#cfeee9,stroke:#1f9e8f,stroke-width:2px,color:#0c3a34;+ classDef proc fill:#cfe3fb,stroke:#1565c0,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:#ffd4d4,stroke:#c0392b,stroke-width:2px,color:#5c1212;+ classDef ckpt fill:#ececec,stroke:#666666,stroke-width:2px,color:#222222;+ classDef eval fill:#e7d6fb,stroke:#8e44ad,stroke-width:2px,color:#3d1a5a;+ classDef out fill:#e7d6fb,stroke:#7b3fbf,stroke-width:2px,color:#3d1a5a;+ classDef op fill:#ffffff,stroke:#888888,stroke-width:2px,color:#333333;diff --git a/images/10_reward_model.png b/images/10_reward_model.pngnew file mode 100644index 0000000..bf77f7dBinary files /dev/null and b/images/10_reward_model.png differdiff --git a/images/11_dpo.mmd b/images/11_dpo.mmdnew file mode 100644index 0000000..2bb75b4--- /dev/null+++ b/images/11_dpo.mmd@@ -0,0 +1,16 @@+flowchart LR+ P0["chosen / rejected pair"]:::data --> P1["policy (trainable)<br/>sequence log-probs"]:::model+ P0 --> P2["reference (frozen SFT)<br/>sequence log-probs"]:::ckpt+ P1 --> P3["DPO loss<br/>-log σ(β · Δ)"]:::loss+ P2 --> P3 --> P4["AdamW step"]:::model++ classDef data fill:#cdeccd,stroke:#2e7d32,stroke-width:2px,color:#143d1a;+ classDef store fill:#cfeee9,stroke:#1f9e8f,stroke-width:2px,color:#0c3a34;+ classDef proc fill:#cfe3fb,stroke:#1565c0,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:#ffd4d4,stroke:#c0392b,stroke-width:2px,color:#5c1212;+ classDef ckpt fill:#ececec,stroke:#666666,stroke-width:2px,color:#222222;+ classDef eval fill:#e7d6fb,stroke:#8e44ad,stroke-width:2px,color:#3d1a5a;+ classDef out fill:#e7d6fb,stroke:#7b3fbf,stroke-width:2px,color:#3d1a5a;+ classDef op fill:#ffffff,stroke:#888888,stroke-width:2px,color:#333333;diff --git a/images/11_dpo.png b/images/11_dpo.pngnew file mode 100644index 0000000..727b932Binary files /dev/null and b/images/11_dpo.png differdiff --git a/images/12_ppo.mmd b/images/12_ppo.mmdnew file mode 100644index 0000000..6d8644a--- /dev/null+++ b/images/12_ppo.mmd@@ -0,0 +1,14 @@+flowchart LR+ Q0([GSM8K prompts]):::data --> Q1["rollout<br/>generate + log-probs"]:::model --> Q2["score<br/>verifier or reward model"]:::rl --> Q3["+ per-token KL to ref"]:::rl --> Q4["GAE<br/>advantages + returns"]:::proc --> Q5["clipped policy + value<br/>(K epochs)"]:::model --> Q6[(ppo.pt)]:::ckpt+ Q5 -. sync old policy .-> Q1++ classDef data fill:#cdeccd,stroke:#2e7d32,stroke-width:2px,color:#143d1a;+ classDef store fill:#cfeee9,stroke:#1f9e8f,stroke-width:2px,color:#0c3a34;+ classDef proc fill:#cfe3fb,stroke:#1565c0,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:#ffd4d4,stroke:#c0392b,stroke-width:2px,color:#5c1212;+ classDef ckpt fill:#ececec,stroke:#666666,stroke-width:2px,color:#222222;+ classDef eval fill:#e7d6fb,stroke:#8e44ad,stroke-width:2px,color:#3d1a5a;+ classDef out fill:#e7d6fb,stroke:#7b3fbf,stroke-width:2px,color:#3d1a5a;+ classDef op fill:#ffffff,stroke:#888888,stroke-width:2px,color:#333333;diff --git a/images/12_ppo.png b/images/12_ppo.pngnew file mode 100644index 0000000..b342680Binary files /dev/null and b/images/12_ppo.png differdiff --git a/images/13_grpo.mmd b/images/13_grpo.mmdnew file mode 100644index 0000000..f5d5d62--- /dev/null+++ b/images/13_grpo.mmd@@ -0,0 +1,14 @@+flowchart LR+ G0([prompt]):::data --> G1["sample a GROUP<br/>of G answers"]:::model --> G2["verifier reward<br/>per answer"]:::rl --> G3["group advantage<br/>(r - mean) / std"]:::proc --> G4["clipped surrogate<br/>+ k3 KL to ref"]:::loss --> G5["policy update"]:::model+ G5 -. next prompt .-> G0++ classDef data fill:#cdeccd,stroke:#2e7d32,stroke-width:2px,color:#143d1a;+ classDef store fill:#cfeee9,stroke:#1f9e8f,stroke-width:2px,color:#0c3a34;+ classDef proc fill:#cfe3fb,stroke:#1565c0,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:#ffd4d4,stroke:#c0392b,stroke-width:2px,color:#5c1212;+ classDef ckpt fill:#ececec,stroke:#666666,stroke-width:2px,color:#222222;+ classDef eval fill:#e7d6fb,stroke:#8e44ad,stroke-width:2px,color:#3d1a5a;+ classDef out fill:#e7d6fb,stroke:#7b3fbf,stroke-width:2px,color:#3d1a5a;+ classDef op fill:#ffffff,stroke:#888888,stroke-width:2px,color:#333333;diff --git a/images/13_grpo.png b/images/13_grpo.pngnew file mode 100644index 0000000..a703af8Binary files /dev/null and b/images/13_grpo.png differdiff --git a/images/14_evaluation.mmd b/images/14_evaluation.mmdnew file mode 100644index 0000000..6cf3c90--- /dev/null+++ b/images/14_evaluation.mmd@@ -0,0 +1,13 @@+flowchart LR+ E0[(stage checkpoint)]:::ckpt --> E1["greedy generate"]:::model --> E2["extract_answer<br/><answer>N</answer>"]:::proc --> E3{"== gold?"}:::rl --> E4["GSM8K accuracy<br/>Base -> SFT -> ... -> GRPO"]:::eval++ classDef data fill:#cdeccd,stroke:#2e7d32,stroke-width:2px,color:#143d1a;+ classDef store fill:#cfeee9,stroke:#1f9e8f,stroke-width:2px,color:#0c3a34;+ classDef proc fill:#cfe3fb,stroke:#1565c0,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:#ffd4d4,stroke:#c0392b,stroke-width:2px,color:#5c1212;+ classDef ckpt fill:#ececec,stroke:#666666,stroke-width:2px,color:#222222;+ classDef eval fill:#e7d6fb,stroke:#8e44ad,stroke-width:2px,color:#3d1a5a;+ classDef out fill:#e7d6fb,stroke:#7b3fbf,stroke-width:2px,color:#3d1a5a;+ classDef op fill:#ffffff,stroke:#888888,stroke-width:2px,color:#333333;diff --git a/images/14_evaluation.png b/images/14_evaluation.pngnew file mode 100644index 0000000..0abbc22Binary files /dev/null and b/images/14_evaluation.png differdiff --git a/images/15_inference.mmd b/images/15_inference.mmdnew file mode 100644index 0000000..c31b26a--- /dev/null+++ b/images/15_inference.mmd@@ -0,0 +1,17 @@+flowchart LR+ C0[(any checkpoint)]:::ckpt --> C1["load dims from cfg"]:::proc --> C2{"chat or raw?"}:::rl+ C2 -->|instruct| C3["wrap in chat template"]:::proc+ C2 -->|base| C4["raw prefix"]:::proc+ C3 --> C5["generate<br/>temperature / top-p / greedy"]:::model+ C4 --> C5 --> C6["decode -> reply"]:::out++ classDef data fill:#cdeccd,stroke:#2e7d32,stroke-width:2px,color:#143d1a;+ classDef store fill:#cfeee9,stroke:#1f9e8f,stroke-width:2px,color:#0c3a34;+ classDef proc fill:#cfe3fb,stroke:#1565c0,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:#ffd4d4,stroke:#c0392b,stroke-width:2px,color:#5c1212;+ classDef ckpt fill:#ececec,stroke:#666666,stroke-width:2px,color:#222222;+ classDef eval fill:#e7d6fb,stroke:#8e44ad,stroke-width:2px,color:#3d1a5a;+ classDef out fill:#e7d6fb,stroke:#7b3fbf,stroke-width:2px,color:#3d1a5a;+ classDef op fill:#ffffff,stroke:#888888,stroke-width:2px,color:#333333;diff --git a/images/15_inference.png b/images/15_inference.pngnew file mode 100644index 0000000..d3f5983Binary files /dev/null and b/images/15_inference.png differdiff --git a/images/loss_curve.png b/images/loss_curve.pngnew file mode 100644index 0000000..c837de6Binary files /dev/null and b/images/loss_curve.png differdiff --git a/images/make_diagrams.py b/images/make_diagrams.pynew file mode 100644index 0000000..3a5e836--- /dev/null+++ b/images/make_diagrams.py@@ -0,0 +1,161 @@+"""+Generate every README diagram as a Mermaid .mmd file, then render to PNG with the hand-drawn+look. Reproducible: edit a graph below, re-run, re-render.++Render step (run from this folder, needs Node.js for npx):+ for f in *.mmd; do+ npx -y @mermaid-js/mermaid-cli -i "$f" -o "${f%.mmd}.png" -c mmdc.json -p puppeteer.json -b white -s 3+ done+"""+import os++OUT = os.path.dirname(os.path.abspath(__file__))++# Shared palette: soft fill + strong border per role (data, store, proc, model, rl, loss, ckpt, eval, out, op).+PALETTE = """+ classDef data fill:#cdeccd,stroke:#2e7d32,stroke-width:2px,color:#143d1a;+ classDef store fill:#cfeee9,stroke:#1f9e8f,stroke-width:2px,color:#0c3a34;+ classDef proc fill:#cfe3fb,stroke:#1565c0,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:#ffd4d4,stroke:#c0392b,stroke-width:2px,color:#5c1212;+ classDef ckpt fill:#ececec,stroke:#666666,stroke-width:2px,color:#222222;+ classDef eval fill:#e7d6fb,stroke:#8e44ad,stroke-width:2px,color:#3d1a5a;+ classDef out fill:#e7d6fb,stroke:#7b3fbf,stroke-width:2px,color:#3d1a5a;+ classDef op fill:#ffffff,stroke:#888888,stroke-width:2px,color:#333333;+"""++DIAGRAMS = {+"00_pipeline": """flowchart LR+ PILE([The Pile<br/>raw text]):::data --> PRE{{Pretrain<br/>base ~400M}}:::model+ PRE --> SFT{{SFT<br/>instruct}}:::model+ SFT --> RM{{Reward Model<br/>Bradley-Terry}}:::rl+ SFT --> DPO{{DPO / ORPO / KTO}}:::rl+ SFT --> GRPO{{GRPO / RLVR}}:::rl+ RM -->|reward signal| PPO{{PPO}}:::rl+ PPO --> EVAL([GSM8K eval<br/>+ chat]):::eval+ DPO --> EVAL+ GRPO --> EVAL+""",++"01_data": """flowchart LR+ A1([Pretrain: The Pile]):::data --> A2[tiktoken r50k_base<br/>stream + encode]:::proc --> A3[(pile_train.h5<br/>flat int32 tokens)]:::store+ B1([SFT: Alpaca · Dolly · GSM8K]):::data --> B2[chat template<br/>+ mask the prompt]:::proc --> B3[(sft_packed.h5<br/>tokens + loss_mask)]:::store+ C1([Prefs: HH-RLHF · UltraFeedback]):::data --> C2[split prompt /<br/>chosen / rejected]:::proc --> C3[(preferences.jsonl)]:::store+ D1([RL: GSM8K · arithmetic]):::data --> D2[keep the gold answer]:::proc --> D3[(rl_prompts.jsonl)]:::store+""",++"02_tokenization": """flowchart LR+ T1["raw text<br/>'Once upon a time'"]:::data --> T2["tiktoken<br/>r50k_base"]:::proc+ T2 --> T3["token ids<br/>[7454, 2402, 257, 640]"]:::store+ T3 --> T4["append <|endoftext|><br/>(id 50256)"]:::proc+ T4 --> T5["fixed windows of<br/>context_length + 1"]:::store+ T5 --> T6["x = window[:-1]<br/>y = window[1:]"]:::out+""",++"03_mlp": """flowchart LR+ M1["x (B, T, n_embed)"]:::data --> M2["Linear<br/>n_embed -> 4 · n_embed"]:::proc+ M2 --> M3["ReLU"]:::proc+ M3 --> M4["Linear<br/>4 · n_embed -> n_embed"]:::proc+ M4 --> M5["out (B, T, n_embed)"]:::out+""",++"04_attention_head": """flowchart LR+ X["x : token vectors<br/>(B, T, C)"]:::data --> Q["Q = x Wq"]:::proc+ X --> K["K = x Wk"]:::proc+ X --> V["V = x Wv"]:::proc+ Q --> S["scores = Q Kᵀ / √d"]:::rl+ K --> S+ S --> M["causal mask<br/>+ softmax"]:::rl+ M --> O["weights · V"]:::rl+ V --> O+ O --> H["head output<br/>(B, T, head_size)"]:::out+""",++"05_multi_head_attention": """flowchart LR+ X["x (B, T, C)"]:::data --> H1["head 1"]:::proc+ X --> H2["head 2"]:::proc+ X --> H3["... (n_head heads)"]:::proc+ H1 --> CC["concat heads<br/>(B, T, C)"]:::rl+ H2 --> CC+ H3 --> CC+ CC --> PJ["output projection<br/>Linear C -> C"]:::proc+ PJ --> HO["multi-head output"]:::out+""",++"06_transformer_block": """flowchart LR+ X["x"]:::data --> LN1["LayerNorm"]:::proc --> AT["Multi-Head Attention"]:::rl --> A1(("+")):::op+ X --> A1+ A1 --> LN2["LayerNorm"]:::proc --> ML["MLP"]:::proc --> A2(("+")):::op+ A1 --> A2+ A2 --> BO["block output"]:::out+""",++"07_transformer": """flowchart LR+ I["token ids (B, T)"]:::data --> TE["token embedding"]:::proc+ I --> PE["position embedding"]:::proc+ TE --> SUM(("+")):::op+ PE --> SUM+ SUM --> BLK["N_BLOCKS ×<br/>Transformer Block"]:::model+ BLK --> LNF["final LayerNorm"]:::proc+ LNF --> LMH["lm_head<br/>Linear -> vocab_size"]:::proc+ LMH --> LOG["logits (B, T, vocab)"]:::out+ LOG -. targets present .-> CE["cross-entropy loss"]:::loss+""",++"08_training_loop": """flowchart LR+ D[(pile_train.h5)]:::store --> IT["get_batch_iterator<br/>random windows"]:::proc --> FW["forward<br/>(bf16 autocast)"]:::model --> CE["cross-entropy"]:::loss --> BW["backward<br/>× grad_accum"]:::proc --> CL["clip grad norm 1.0"]:::proc --> ST["AdamW step<br/>cosine LR + warmup"]:::model --> CK[(checkpoint)]:::ckpt+ ST -. next step .-> IT+""",++"09_sft": """flowchart LR+ S0[(sft_packed.h5<br/>tokens + loss_mask)]:::store --> S1["Transformer forward"]:::model --> S2["shift: predict t+1"]:::proc --> S3["per-token cross-entropy"]:::loss+ S0 --> S4["loss_mask = 1 only on<br/>assistant tokens"]:::proc --> S5["mean over masked tokens"]:::loss+ S3 --> S5 --> S6["AdamW step"]:::model+""",++"10_reward_model": """flowchart LR+ R0["prompt + chosen / rejected"]:::data --> R1["SFT backbone<br/>forward_hidden"]:::model --> R2["take last real token"]:::proc --> R3["reward head<br/>Linear -> 1"]:::proc+ R3 --> R4["r_chosen , r_rejected"]:::rl --> R5["Bradley-Terry loss<br/>-log σ(r_chosen - r_rejected)"]:::loss --> R6["AdamW step"]:::model+""",++"11_dpo": """flowchart LR+ P0["chosen / rejected pair"]:::data --> P1["policy (trainable)<br/>sequence log-probs"]:::model+ P0 --> P2["reference (frozen SFT)<br/>sequence log-probs"]:::ckpt+ P1 --> P3["DPO loss<br/>-log σ(β · Δ)"]:::loss+ P2 --> P3 --> P4["AdamW step"]:::model+""",++"12_ppo": """flowchart LR+ Q0([GSM8K prompts]):::data --> Q1["rollout<br/>generate + log-probs"]:::model --> Q2["score<br/>verifier or reward model"]:::rl --> Q3["+ per-token KL to ref"]:::rl --> Q4["GAE<br/>advantages + returns"]:::proc --> Q5["clipped policy + value<br/>(K epochs)"]:::model --> Q6[(ppo.pt)]:::ckpt+ Q5 -. sync old policy .-> Q1+""",++"13_grpo": """flowchart LR+ G0([prompt]):::data --> G1["sample a GROUP<br/>of G answers"]:::model --> G2["verifier reward<br/>per answer"]:::rl --> G3["group advantage<br/>(r - mean) / std"]:::proc --> G4["clipped surrogate<br/>+ k3 KL to ref"]:::loss --> G5["policy update"]:::model+ G5 -. next prompt .-> G0+""",++"14_evaluation": """flowchart LR+ E0[(stage checkpoint)]:::ckpt --> E1["greedy generate"]:::model --> E2["extract_answer<br/><answer>N</answer>"]:::proc --> E3{"== gold?"}:::rl --> E4["GSM8K accuracy<br/>Base -> SFT -> ... -> GRPO"]:::eval+""",++"15_inference": """flowchart LR+ C0[(any checkpoint)]:::ckpt --> C1["load dims from cfg"]:::proc --> C2{"chat or raw?"}:::rl+ C2 -->|instruct| C3["wrap in chat template"]:::proc+ C2 -->|base| C4["raw prefix"]:::proc+ C3 --> C5["generate<br/>temperature / top-p / greedy"]:::model+ C4 --> C5 --> C6["decode -> reply"]:::out+""",+}++def main():+ for name, body in DIAGRAMS.items():+ path = os.path.join(OUT, name + ".mmd")+ with open(path, "w", encoding="utf-8") as f:+ f.write(body.rstrip() + "\n" + PALETTE)+ print("wrote", name + ".mmd")+ print("total:", len(DIAGRAMS), "diagrams")++if __name__ == "__main__":+ main()diff --git a/images/mmdc.json b/images/mmdc.jsonnew file mode 100644index 0000000..3d20f8f--- /dev/null+++ b/images/mmdc.json@@ -0,0 +1,15 @@+{+ "look": "handDrawn",+ "theme": "base",+ "themeVariables": {+ "fontFamily": "Comic Sans MS, Comic Sans, Chalkboard SE, cursive",+ "fontSize": "16px",+ "lineColor": "#3b3b3b",+ "primaryColor": "#ffe8a3",+ "primaryBorderColor": "#e8730c",+ "primaryTextColor": "#1a1a1a",+ "clusterBkg": "#ffffff",+ "clusterBorder": "#cccccc"+ },+ "flowchart": { "htmlLabels": true, "curve": "basis", "nodeSpacing": 22, "rankSpacing": 55 }+}diff --git a/images/plot_artifacts.py b/images/plot_artifacts.pynew file mode 100644index 0000000..107ee39--- /dev/null+++ b/images/plot_artifacts.py@@ -0,0 +1,66 @@+"""+Plot the real training artifacts produced by the GPU run into the README images:+ - images/loss_curve.png from the pretraining stdout (step / train loss / dev loss)+ - images/gsm8k_accuracy.png from the across-stages GSM8K table (stage_table.jsonl)++Usage:+ python images/plot_artifacts.py <artifacts_dir>+where <artifacts_dir> holds pretrain_stdout.txt and stage_table.jsonl.+"""+import json, os, re, sys+import matplotlib as mpl+mpl.use("Agg")+import matplotlib.pyplot as plt++OUT = os.path.dirname(os.path.abspath(__file__))+ART = sys.argv[1] if len(sys.argv) > 1 else OUT++mpl.rcParams["font.family"] = ["Comic Sans MS", "Ink Free", "DejaVu Sans"]+BLUE, ORANGE, PURPLE = "#1565c0", "#e8730c", "#7b3fbf"++def plot_loss():+ path = os.path.join(ART, "pretrain_stdout.txt")+ if not os.path.exists(path):+ print("no pretrain_stdout.txt, skipping loss curve"); return+ txt = open(path, encoding="utf-8", errors="ignore").read()+ train = [(int(s), float(l)) for s, l in re.findall(r"^step (\d+) \| loss ([\d.]+)", txt, re.M)]+ ev = re.findall(r"\[eval\] step (\d+) \| train ([\d.]+) \| dev ([\d.]+)", txt)+ ev = [(int(s), float(a), float(b)) for s, a, b in ev]+ if not train:+ print("no step lines found, skipping loss curve"); return+ fig, ax = plt.subplots(figsize=(9, 5.2))+ xs, ys = zip(*train)+ ax.plot(xs, ys, color=BLUE, lw=2.2, label="train loss")+ if ev:+ es, et, ed = zip(*ev)+ ax.plot(es, ed, color=ORANGE, lw=2.2, marker="o", ms=5, label="dev loss")+ ax.axhline(10.83, color="#999", ls="--", lw=1.2, label="uniform-guess loss ln(50304)")+ ax.set_xlabel("training step"); ax.set_ylabel("cross-entropy loss")+ ax.set_title("Pretraining a 77M base on The Pile (2x L40)", fontsize=15)+ ax.grid(True, alpha=0.25); ax.legend()+ fig.tight_layout(); fig.savefig(os.path.join(OUT, "loss_curve.png"), dpi=150, facecolor="white")+ print("wrote loss_curve.png (last train=%.3f%s)" % (ys[-1], (", dev=%.3f" % ed[-1]) if ev else ""))++def plot_gsm8k():+ path = os.path.join(ART, "stage_table.jsonl")+ if not os.path.exists(path):+ print("no stage_table.jsonl, skipping accuracy chart"); return+ rows = [json.loads(l) for l in open(path) if l.strip()]+ order = ["base_pretrained", "sft", "dpo", "ppo", "grpo"]+ rows.sort(key=lambda r: order.index(r["label"]) if r["label"] in order else 99)+ labels = [r["label"].replace("base_pretrained", "base") for r in rows]+ accs = [100.0 * r["accuracy"] for r in rows]+ fig, ax = plt.subplots(figsize=(8, 5))+ bars = ax.bar(labels, accs, color=[BLUE, "#d48806", "#e67e22", "#c0392b", PURPLE][:len(labels)],+ edgecolor="#333", linewidth=1.5)+ for b, a in zip(bars, accs):+ ax.text(b.get_x()+b.get_width()/2, a, f"{a:.1f}%", ha="center", va="bottom", fontsize=11)+ ax.set_ylabel("GSM8K accuracy (%)")+ ax.set_title("GSM8K accuracy across stages (77M, 2x L40)", fontsize=15)+ ax.grid(True, axis="y", alpha=0.25)+ fig.tight_layout(); fig.savefig(os.path.join(OUT, "gsm8k_accuracy.png"), dpi=150, facecolor="white")+ print("wrote gsm8k_accuracy.png ", dict(zip(labels, [round(a,1) for a in accs])))++if __name__ == "__main__":+ plot_loss()+ plot_gsm8k()diff --git a/images/puppeteer.json b/images/puppeteer.jsonnew file mode 100644index 0000000..24b062d--- /dev/null+++ b/images/puppeteer.json@@ -0,0 +1 @@+{ "args": ["--no-sandbox", "--disable-setuid-sandbox"] }