Diy-LLM — How Large Language Models Are Forged

From tokenizers, data, and training to systems optimization, inference, alignment, evaluation, and multimodal models: the full pipeline of building an LLM, connected into one knowledge system.
Training large models is often jokingly called "alchemy": data is the raw material, compute is the furnace, and hyperparameters all come down to feel. CS336 explains the process well, but the entry barrier is high; we spell out every "ingredient" and every step so that the folklore turns back into reproducible principles and code.
✍️ Why This Project
In Spring 2025, Stanford CS336: Language Modeling from Scratch launched. The course is demanding, and learners in our community kept telling us the same thing: they wanted to study it, but the English lecture notes, the assumed prerequisites, and the assignment environment were real barriers. What they needed was a Chinese version they could actually understand and work through.
So we brought together a group of contributors and spent over half a year on writing → closed beta → public beta → chapter-by-chapter revision. This is not a translation of the original. We reorganized the material around how Chinese-speaking learners study: added background explanations, wrote out assignment implementations, checked and expanded the reference sources, and brought in examples from models developed in China. AI was used to assist with translation and material organization, but every chapter was written and finalized by human contributors, cross-reviewed, and revised repeatedly based on closed-beta and public-beta feedback. It is neither machine-translated nor AI-generated in bulk. Each major chapter has a named author, and the whole text went through a full content review. We call it a course "with a human touch" — that is also where most of the time went.
The course currently contains 16 chapters and 6 assignments, coordinated by 3 project leads with contributions from many community members, and is continuously open to corrections (see "Contributors" below).
What We Changed from the Original
| Dimension | Original CS336 | Diy-LLM (Chinese edition) |
|---|---|---|
| Knowledge structure | Follows lecture order and assumes math, PyTorch, and systems background | Reordered around the engineering pipeline of building an LLM; math, PyTorch, and GPU prerequisites are explained up front for a smoother learning curve |
| Explanation | Lectures and notes in English | Written chapter by chapter in Chinese, with derivations, terminology, and common confusions unpacked, while keeping the original technical depth |
| Assignments | Assignment handouts and tests | Six runnable implementations plus the reasoning behind the code; CPU debugging and MacBook MPS support added |
| Reference sources | Lecture notes and paper pointers | More detailed references so readers can trace back to primary sources |
| Models and examples | Mostly models from the English-speaking ecosystem | Qwen, DeepSeek, Qwen-VL, DeepSeekMoE, R1 / GRPO, and other cases from China's open-source ecosystem |
| Evaluation | MMLU, HumanEval, and other international benchmarks | Chinese benchmarks such as C-EVAL added and integrated into Assignment 6 |
| Runtime environment | Assumes the compute and environment provided by the course | Cloud GPU options, CPU / Mac debugging advice, and an offline PDF edition for readers in China |
| How it was written | — | Human-written and finalized (AI-assisted translation and organization) + cross-review + beta feedback; not AI-generated in bulk |
Because the Chinese edition is reordered around the engineering pipeline, chapter numbers do not map one-to-one to the original lectures. We recommend following the chapter order used here.
Version Alignment
- Originally based on: Stanford CS336 Spring 2025 (the archived site for that offering); the main storyline and Assignments 1–5 correspond to the original assignments 1–5.
- 2026 update: Synchronized with the new Stanford CS336 Spring 2026 material; topics such as RLVR and multimodality in the new schedule correspond to Chapters 14 and 15 here. Assignment 6 (model evaluation) is new to this edition.
- This is a community-run study project with no official affiliation with Stanford. Original lecture and assignment materials: stanford-cs336/lectures.
Prerequisites
- Python: Proficient in Python and software engineering skills
- Deep Learning: Familiar with PyTorch and neural network fundamentals
- Mathematics: Linear algebra, probability & statistics, calculus
- Machine Learning: Solid grasp of ML and DL basics
- GPU Programming (optional): CUDA basics help but aren't required
🎯 What You'll Be Able to Build
This course does not stop at "understanding the concepts": for each stage, you either build it yourself or can explain the design trade-offs.
- A language model implemented from scratch, and its architectural variants: hand-write a BPE tokenizer, implement RoPE, RMSNorm, SwiGLU, AdamW, and the training loop; swap the FFN for a Top-K-routed MoE and explain load balancing and the trade-offs behind DeepSeekMoE (Chapters 2, 4, 5).
- Make it trainable, fast, and cheap to serve: estimate FLOPs and memory, implement FlashAttention-2 in Triton, set up data/model parallelism; on the inference side, work with KV cache, speculative decoding, quantization, and continuous batching (Chapters 3, 6–8, 10).
- A complete data, training, and alignment pipeline: turn raw Common Crawl into a corpus through filtering, deduplication, and PII removal; run SFT and DPO / RLHF; then train mathematical reasoning with RLVR (GRPO) and understand the training path behind R1-style approaches (Chapters 11, 13, 14).
- Evaluate it, size it, and extend it to multimodality: run multidimensional evaluation with lm-evaluation-harness, EvalScope, and C-EVAL; fit scaling laws to predict model scale; and read the multimodal path from CLIP / SigLIP to LLaVA and Qwen-VL (Chapters 9, 12, 15).
Table of Contents
| Chapter | Key Content | Assignment | Status |
|---|---|---|---|
| Foreword | Project background, learning roadmap, prerequisites | - | ✅ |
| Ch1 Tooling | W&B experiment tracking, hyperparameter search | - | ✅ |
| Ch2 Tokenizer | BPE algorithm, Unicode normalization, tokenizer training | HW1 | ✅ |
| Ch3 PyTorch & Resource Accounting | Mixed precision, gradient accumulation, FLOPs/memory estimation | - | ✅ |
| Ch4 Architecture & Training Details | RoPE, RMSNorm, SwiGLU, AdamW, learning rate schedules | HW1 | ✅ |
| Ch5 Mixture of Experts | Top-K routing, load balancing, expert parallelism, DeepSeekMoE | - | ✅ |
| Ch6 GPU & Optimization | Memory bandwidth, Flash Attention, kernel fusion, BF16 | HW2 | ✅ |
| Ch7 GPU High-Perf Programming | CUDA, Tensor Cores, shared memory, Triton | HW2 | ✅ |
| Ch8 Distributed Training | Data/Model/Pipeline parallelism, ZeRO, FSDP, All-Reduce | HW2 | ✅ |
| Ch9 Scaling Laws | Chinchilla optimal, compute-efficient training | HW3 | ✅ |
| Ch10 Inference | KV cache, speculative decoding, quantization, PagedAttention | HW6 | ✅ |
| Ch11 Data Engineering | Data filtering, MinHash dedup, PII removal, data recipes | HW4 | ✅ |
| Ch12 Evaluation & Benchmarks | MMLU, HumanEval, HELM, Chatbot Arena, safety benchmarks | HW6 | ✅ |
| Ch13 Training Pipeline | Pre-training, SFT, DPO, RLHF PPO pipeline, alignment | HW5 | ✅ |
| Ch14 RLVR | GRPO, rule-based verifiers, process reward, DeepSeek-R1 | HW5 | ✅ |
| Ch15 Multimodal Models | CLIP, SigLIP, LLaVA, Qwen-VL, Chameleon, Omni Model | - | ✅ |
| Ch16 Extended Content | 1. What is LLM Reasoning? 2. LLM Future — LeCun's Roadmap | - | 🔄 |
Status: ✅ Complete 🔄 In Progress 📝 Draft 🚧 Planned ⏸️ Paused
Assignments
| HW | Core Tasks | Status |
|---|---|---|
| HW1: Build an LLM | Implement tokenizer, model architecture, optimizer; train a minimal LM | ✅ |
| HW2: Systems | Benchmarking, FlashAttention-2 in Triton, distributed training code | ✅ |
| HW3: Scaling Laws | Fit scaling laws, predict model scaling behavior | ✅ |
| HW4: Data Processing | Convert Common Crawl raw data to pre-training dataset | ✅ |
| HW5: Alignment | Apply SFT and RL (e.g., GRPO) to train on math problems | ✅ |
| HW6: Evaluation | Multi-dimension evaluation using lm-evaluation-harness and evalscope | ✅ |
Quick Start
git clone https://github.com/datawhalechina/diy-llm.git
cd diy-llmLearning Path
1️⃣ Theory → Read docs/en/ chapters in order
2️⃣ Practice → Complete the 6 assignments in coursework/
3️⃣ Deep Dive → Read code implementations, understand design decisions
Project Structure
diy-llm/
├── docs/
│ ├── zh/ # Chinese docs (default)
│ ├── en/ # English docs
│ └── .vitepress/ # VitePress config
├── coursework/ # Assignments
│ ├── assignment1-basics/
│ └── ...
└── README.mdLinks
- Repository: https://github.com/datawhalechina/diy-llm
- Read online: https://datawhalechina.github.io/diy-llm/en/ (简体中文)
- Course notes PDF: https://github.com/datawhalechina/diy-llm/releases/latest/
- Original course website (current · Spring 2026): https://cs336.stanford.edu/
- Original course website (archive · Spring 2025, the edition this project was first based on): https://cs336.stanford.edu/spring2025/
- Original course repository: https://github.com/stanford-cs336/lectures/tree/main
FAQ
Q: Can I learn without a GPU?
Theory can be studied normally. Some assignments can be debugged on CPU, but full training requires GPU. Cloud services are recommended.Q: How does this differ from the original CS336?
We retain the original technical depth while adding Chinese explanations, detailed reference sources, domestic model examples (Qwen, DeepSeek), and complete assignment implementations. See "What We Changed from the Original" for a point-by-point comparison and "Version Alignment" for how the two CS336 offerings map to this project.Reader Community
Join the Diy-LLM reader community to discuss the course, ask questions, and learn together:
![]() Group 1 | ![]() Group 2 |
If group 1 is full, join group 2. If both QR codes have expired or are full, add any maintainer below on WeChat (note: diy-llm) and we'll add you to the group:
| Maintainer | WeChat ID |
|---|---|
| Hu Xu (徐虎) | xuhu96736 |
| Li Youzhen (黎又榛) | zydsx111 |
| Li Shengkang (李盛康) | muzichengminguangli |
Contributors
![]() Hu Xu (徐虎) Project Lead · Datawhale · SJTU | ![]() Li Shengkang (李盛康) Project Lead · Datawhale · XUPT | ![]() Li Youzhen (黎又榛) Project Lead · Datawhale |
- Thanks to @aimetrics for adding MPS support for MacBooks in HW1
- Thanks to @FuTseYi (Datawhale) for website migration, deployment, and refactoring
- Thanks to @jiangyinhe for contributing to Ch16 "LLM Future — LeCun"; and for translating the first chapter and preface into English based on the Chinese version.
How to Contribute
Corrections, assignment implementations, new content, translations, and shared experience are all welcome. Before you start, please read CONTRIBUTING.md for the full submission workflow, content and code conventions, and the PR self-check list.
Three things that matter most: small fixes can go straight to an Issue or a PR, while new chapters and major changes should be discussed in an Issue first; PRs should state what changed, the evidence, and what you verified; AI assistance is allowed, but you must have read, understood, and verified the submission yourself — bulk AI-generated or densely submitted PRs will be asked to consolidate or will be closed, and repeated bulk submissions will no longer be accepted.
🗓️ Versions & Milestones
Overall progress: ████████████████░░░░ Writing → closed beta → public beta → second public beta complete; now in continuous maintenance
| ✅ Writing & Revision 2025.11 — 2026.02 | ✅ Closed Beta 2026.03.05 | ✅ Public Beta 2026.04 | ✅ 2nd Public Beta 2026.09 | 🔄 Maintenance 2026.10 — present |
Dates come from the commit history and version tags (757 commits, V0.1 / V0.2), with beta dates taken from project test records:
| Date | Milestone | Evidence |
|---|---|---|
| 2025-11-24 | Repository created; writing started with the tokenizer chapter | Initial commit |
| 2025-12 — 2026-01 | Peak writing period (186 commits in December); assignment implementations completed | Commits "完成作业一", "完成作业" |
| 2026-03-05 | Closed beta | Closed-beta feedback revisions |
| 2026-04 | Public beta | Public-beta feedback revisions |
| 2026-06-10 | V0.1: PDF notes released | tag V0.1, add pdf download |
| 2026-07-26 | Content from CS336 2026 added | Commit "修改第七章,新增2026内容" |
| 2026-08-17 | V0.2: PDF notes v2, reader groups | tag V0.2, pdf v2 + reader communication |
| 2026-09 | Second public beta | Second-beta feedback revisions |
| 2026-10 — present | Ongoing corrections: formula rendering, figures, wording | 28 commits in the last two months |
See GitHub Releases for the current version and PDF notes, "Why This Project" above for the writing and review process, and "Table of Contents" for per-chapter status.
License
This work is licensed under CC BY-NC-SA 4.0.
Acknowledgments
- Stanford CS336 course team for the excellent original course
- @Sm1les for support and guidance
- All contributors and the open-source community
Star History
Empowering everyone to systematically learn large language model construction
Made with ❤️ by Datawhale





