Skip to content

Diy-LLM — How Large Language Models Are Forged ​

diy-llm

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.

Read OnlinePDF NotesAssignment Code

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 ​

DimensionOriginal CS336Diy-LLM (Chinese edition)
Knowledge structureFollows lecture order and assumes math, PyTorch, and systems backgroundReordered around the engineering pipeline of building an LLM; math, PyTorch, and GPU prerequisites are explained up front for a smoother learning curve
ExplanationLectures and notes in EnglishWritten chapter by chapter in Chinese, with derivations, terminology, and common confusions unpacked, while keeping the original technical depth
AssignmentsAssignment handouts and testsSix runnable implementations plus the reasoning behind the code; CPU debugging and MacBook MPS support added
Reference sourcesLecture notes and paper pointersMore detailed references so readers can trace back to primary sources
Models and examplesMostly models from the English-speaking ecosystemQwen, DeepSeek, Qwen-VL, DeepSeekMoE, R1 / GRPO, and other cases from China's open-source ecosystem
EvaluationMMLU, HumanEval, and other international benchmarksChinese benchmarks such as C-EVAL added and integrated into Assignment 6
Runtime environmentAssumes the compute and environment provided by the courseCloud 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 ​

ChapterKey ContentAssignmentStatus
ForewordProject background, learning roadmap, prerequisites-✅
Ch1 ToolingW&B experiment tracking, hyperparameter search-✅
Ch2 TokenizerBPE algorithm, Unicode normalization, tokenizer trainingHW1✅
Ch3 PyTorch & Resource AccountingMixed precision, gradient accumulation, FLOPs/memory estimation-✅
Ch4 Architecture & Training DetailsRoPE, RMSNorm, SwiGLU, AdamW, learning rate schedulesHW1✅
Ch5 Mixture of ExpertsTop-K routing, load balancing, expert parallelism, DeepSeekMoE-✅
Ch6 GPU & OptimizationMemory bandwidth, Flash Attention, kernel fusion, BF16HW2✅
Ch7 GPU High-Perf ProgrammingCUDA, Tensor Cores, shared memory, TritonHW2✅
Ch8 Distributed TrainingData/Model/Pipeline parallelism, ZeRO, FSDP, All-ReduceHW2✅
Ch9 Scaling LawsChinchilla optimal, compute-efficient trainingHW3✅
Ch10 InferenceKV cache, speculative decoding, quantization, PagedAttentionHW6✅
Ch11 Data EngineeringData filtering, MinHash dedup, PII removal, data recipesHW4✅
Ch12 Evaluation & BenchmarksMMLU, HumanEval, HELM, Chatbot Arena, safety benchmarksHW6✅
Ch13 Training PipelinePre-training, SFT, DPO, RLHF PPO pipeline, alignmentHW5✅
Ch14 RLVRGRPO, rule-based verifiers, process reward, DeepSeek-R1HW5✅
Ch15 Multimodal ModelsCLIP, SigLIP, LLaVA, Qwen-VL, Chameleon, Omni Model-✅
Ch16 Extended Content1. What is LLM Reasoning?
2. LLM Future — LeCun's Roadmap
-🔄

Status: ✅ Complete  🔄 In Progress 📝 Draft 🚧 Planned ⏸️ Paused

Assignments ​

HWCore TasksStatus
HW1: Build an LLMImplement tokenizer, model architecture, optimizer; train a minimal LM✅
HW2: SystemsBenchmarking, FlashAttention-2 in Triton, distributed training code✅
HW3: Scaling LawsFit scaling laws, predict model scaling behavior✅
HW4: Data ProcessingConvert Common Crawl raw data to pre-training dataset✅
HW5: AlignmentApply SFT and RL (e.g., GRPO) to train on math problems✅
HW6: EvaluationMulti-dimension evaluation using lm-evaluation-harness and evalscope✅

Quick Start ​

bash
git clone https://github.com/datawhalechina/diy-llm.git
cd diy-llm

Learning 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.md

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:

Reader community group 1 QR code
Group 1
Reader community group 2 QR code
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:

MaintainerWeChat ID
Hu Xu (徐虎)xuhu96736
Li Youzhen (黎又榛)zydsx111
Li Shengkang (李盛康)muzichengminguangli

Contributors ​

pic
Hu Xu (徐虎)

Project Lead · Datawhale · SJTU
Chapters: 1, 3, 9, 12, 14, 15; HW5, 6; Content review

pic
Li Shengkang (李盛康)

Project Lead · Datawhale · XUPT
Chapters: 4, 6, 7, 8, 13; HW2, 4

pic
Li Youzhen (黎又榛)

Project Lead · Datawhale
Chapters: 2, 5, 10, 11, 13; HW1, 3

  • 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:

DateMilestoneEvidence
2025-11-24Repository created; writing started with the tokenizer chapterInitial commit
2025-12 — 2026-01Peak writing period (186 commits in December); assignment implementations completedCommits "完成作业一", "完成作业"
2026-03-05Closed betaClosed-beta feedback revisions
2026-04Public betaPublic-beta feedback revisions
2026-06-10V0.1: PDF notes releasedtag V0.1, add pdf download
2026-07-26Content from CS336 2026 addedCommit "修改第七章,新增2026内容"
2026-08-17V0.2: PDF notes v2, reader groupstag V0.2, pdf v2 + reader communication
2026-09Second public betaSecond-beta feedback revisions
2026-10 — presentOngoing corrections: formula rendering, figures, wording28 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 ​

CC BY-NC-SA 4.0

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 ​

Star History Chart

Empowering everyone to systematically learn large language model construction

Made with ❤️ by Datawhale