modern-llm-notebook

walkinglabs活跃维护

用 PyTorch 从零手写现代 LLM 架构、训练与推理的实战课程,配套可直接运行的 notebook,适合边跑边学大模型原理。

A hands-on course on modern LLM architectures, training, and inference, with step-by-step PyTorch implementations and runnable notebooks.

暂无版本280star60fork同步于 2026-11-07 07:30 UTC

怎么上手

由 README 提炼,执行前请确认
git clone https://github.com/walkinglabs/modern-llm-notebook.git
pip install -r requirements.txt
硬件要求按 README 说明

README 未给出显存门槛;训练脚本在 AMD MI300X 上有实验报告,并可通过 AMD Radeon Cloud 模板使用 GPU,也可在 Colab 或 ModelScope 在线运行 notebook。

纯 CPU 可运行支持 Apple Silicon支持 ROCm / AMD
下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

从零手写并训练现代 LLM 的 PyTorch 实战课程,含可运行 notebook 与复现脚本

用 PyTorch 从零手写现代 LLM 架构、训练与推理的实战课程,配套可直接运行的 notebook,适合边跑边学大模型原理。

核心能力

  • 手算 BPE 合并与注意力分数,逐层拆解中间值和张量形状
  • 用 Data-Juicer 清洗中文语料并完成分词、切分与打包
  • 从随机权重预训练 61.55M 参数 DotLM 稠密模型
  • 覆盖 RoPE、GQA、MLA、MoE、LoRA、量化与推理系统
  • 提供预训练到 SFT 的复现脚本与实验报告

容易踩的坑

环境需 Python 3.9+ 与 PyTorch 2.0+;数据管线要先下载 Ultra-FineWeb 等语料并清洗后才能训练;MoE 预训练、工具调用 SFT 等部分配方 README 标注为计划中,尚不可直接跑通。

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

0 个版本

暂无 release 数据(可能没有发版,或尚未同步)。

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    News

    • 2026-09: Added from-scratch training labs covering BPE tokenization, data cleaning, 64M-class DotLM pretraining, SFT, and evaluation, with reproduction scripts and experiment reports.
    • 2026-08: Reorganized the course into four parts, rebuilt the inference labs on decoding, acceleration, quantization, and deployment, and expanded post-training and diffusion LM topics.
    • 2026-06: Expanded MLA, distributed training, quantization, tool calling, and systems appendices, with runnable exercises and saved experiment outputs.
    • 2026-05: Launched bilingual notebooks and the online reader, covering the foundations from tokenization and Transformers to Mini-GPT.

    Quick Start

    Read Online

    The easiest way to explore the course is through the published reader:

    walkinglabs.github.io/modern-llm-notebook

    You can also open the first English notebook directly in Google Colab.

    Run Online through Partner Platforms

    Everyone is welcome to open this project at any time, run the notebooks, change the code, and test the experiments. The online reader provides partner launch buttons at the top of each chapter, so you can get started without setting up a local environment:

    • Open in ModelScope: open and run a notebook online. Use the chapter buttons for other notebooks.
    • Open in AMD: use the project template on AMD Radeon Cloud to run and test with a GPU.
    • Open in Colab: run notebooks in your browser and select a GPU when the platform provides one.

    Thank you to our partners for online execution and compute support. Sign-in requirements, GPU availability, and usage quotas follow each platform's current rules.

    [!NOTE] Modern LLM Notebook is under active development. The Chinese course is the source edition; the English mirror is being updated alongside it. Corrections, suggestions, and focused pull requests are welcome.

    What Makes This Course Different

    Start with a few words, follow a BPE merge by hand, trace an attention score, and observe the first gradient update. The notebooks break these steps into small examples, with intermediate values, tensor shapes, and experiments that explain the result.

    • Detailed from-scratch teaching. Build the core components in PyTorch through intuition, hand calculation, implementation, and observation. Basic Python and matrix operations are enough to begin.
    • Data engineering and real training. Learn where corpora come from, how Data-Juicer cleans them, and how synthetic data and data mixtures work. Follow DotLM's 64M-class Dense pretraining → supervised fine-tuning (SFT) scripts, with an existing AMD MI300X experiment report.
    • Modern LLM topics in one course. Extend the foundations to RoPE, GQA, MLA, MoE, LoRA, tool calling, preference alignment, distillation, quantization, and inference systems.

    This is an educational reference: notebooks explain each mechanism, while the training scripts and reports document larger experiments. The Chinese notebooks are the source edition, with an English mirror and a bilingual web reader.

    From Zero to a Trained Model

    Follow the main path from raw text to a trained model. The lower strip shows the topics to explore beyond the Dense baseline; the table distinguishes runnable training scripts from notebook implementations and planned training recipes.

    StageWhat is availableStart here
    Prepare real dataDownload, quality-filter, clean, count tokens, split, and pack a Chinese corpusData pipeline · Data engineering
    Train a tokenizerLearn BPE merge rules, train a vocabulary, and save a tokenizerBPE notebook
    Pretrain a Dense modelTrain from random weights with RoPE, GQA, SwiGLU, and QK-Norm; 64M class, 61.55M measured parameters in the reported runConfiguration · Pretraining script
    Continue with SFTLoad the pretrained checkpoint, format conversations, and compute loss on assistant answersSFT script · Training notebook
    Evaluate and diagnoseValidation perplexity, benchmark results, generated examples, and documented failuresExperiment report · Evaluation notebook
    Study small MoE modelsImplement routing and expert computation in a notebook; full MoE pretraining recipe is plannedMoE notebook
    Explore tool callingConstruct tool-use examples and study the execution loop; end-to-end tool-use SFT is plannedFunction calling
    Extend post-trainingLearn LoRA and adapter merging, preference objectives, and distillation; comparative small-model training and merging recipes are plannedLoRA · Alignment · OPD

    Models & Benchmarks

    DotLM · 64M-class Dense is the course's modern small-model training baseline: pretrain from random weights on cleaned Chinese text, then continue with assistant-only SFT. The tables present the recorded mini-tier seed 42 results. The chart also includes two small Base models' published scores as references.

    Model Summary

    SettingDotLM · 64M-class Dense
    Architecture / parametersDecoder-only Dense / about 61.55M (reported count)
    Layers / hidden size8 / 768
    AttentionGQA, 8 query heads / 4 KV heads, head dimension 96
    FFNSwiGLU, intermediate size 2304
    Position encoding / normalizationRoPE (θ = 10,000) / Pre-Norm RMSNorm + QK-Norm
    Vocabulary / weight sharing6,400 / tied token embedding and LM head
    Training sequence length / precision512 / BF16

    Model implementation · Configuration · Pretraining · SFT · Experiment report

    Training Results

    StageDataTraining budgetRecorded results
    PretrainingChinese Ultra-FineWeb, approximately 0.269B training-set tokens5,120 steps, batch 128; approximately 0.336B processed tokensLoss 8.93 → 2.74; validation PPL 18.30 / 18.03
    SFTBelleGroup train_1M_CN, 917,424 records2 epochs, 28,668 steps; batch 64Assistant-only loss about 2.3 → 1.65

    The experiment used one AMD MI300X GPU. PPL values use packed-sequence and document-independent evaluation respectively; processed tokens include repeated sampling. This run uses an existing MiniMind tokenizer with a 6,400-token vocabulary; the from-scratch BPE lab is a separate experiment. mini and full share the architecture; the full tier currently has a configuration but no completed report.

    Evaluation Results

    Evaluated with lm-evaluation-harness on the DotLM SFT checkpoint · 0-shot. Scores are percentages: acc is choice accuracy; acc_norm uses length-normalized answer scores.

    The chart shows DotLM in blue and published SmolLM Base references in gray (source). Evaluation protocols differ; these are reference scores, not a shared-protocol rerun.

    CategoryBenchmarkacc (%)acc_norm (%)
    KnowledgeCEval-valid25.78—
    KnowledgeMMLU24.21—
    Science QAARC Easy25.5126.77
    Science QAARC Challenge19.9721.76
    CommonsensePIQA53.9753.26
    Science QAOpenBookQA13.8026.20
    CommonsenseHellaSwag26.9527.73
    CommonsenseWinoGrande51.30—

    Source: mini-tier seed 42 report. — means the metric was not reported.

    The experiment records use the former name FirstLLM; the script and checkpoint paths below refer to the same model.

    ItemProtocol
    Checkpointfirstllm_64m_exp24_sft/mini_seed42_sft.pt, after SFT
    Entry pointrun_lm_eval.sh: export .pt to Hugging Face format, then evaluate through the hf backend
    Few-shot / backend--num_fewshot 0, --model hf, trust_remote_code=True
    Current script defaults--batch_size auto, --device cuda; MI300X runs through PyTorch ROCm
    PPL toolrun_ppl.py; PT checkpoint, with packed-validation and document-independent protocols

    The chart uses DotLM's acc_norm for HellaSwag / PIQA / OpenBookQA and acc for WinoGrande. SmolLM's published scores use lighteval; its task definitions use loglikelihood_acc_norm_nospace. Model stages, sizes, corpora, and metric implementations differ. Rows are ordered by published scores.

    CMMLU and Social IQa were not run; GSM8K did not complete. The report also documents incoherent and repetitive generations. It does not record an exact lm-eval version / commit; save the tool version and result JSON when reproducing it.

    Prepare the report's SFT checkpoint and matching tokenizer, and install compatible lm-evaluation-harness / Hugging Face dependencies. Run the eight completed tasks with:

    CKPT=llm_train/checkpoints/firstllm_64m_exp24_sft/mini_seed42_sft.pt \
    TOKENIZER=notebooks/part1-foundation/mini_tokenizer.json \
    TASKS=ceval-valid,mmlu,arc_easy,arc_challenge,piqa,openbookqa,hellaswag,winogrande \
    NUM_FEWSHOT=0 \
    bash llm_train/scripts/run_lm_eval.sh
    

    The script writes an HF export directory and lm-eval result JSON. Changes to evaluation versions, task definitions, or dataset versions may affect the scores.

    Model / experimentArchitecture and parametersRecorded resultsEntry point
    Character-level nanoGPT2 layers, hidden size 64, 2 heads; 108,352 total parametersTiny Shakespeare, 500 steps; train loss 2.2472, validation loss 2.2906Mini-GPT · Saved source outputs
    Compact Dense (historical short run)4 layers, hidden size 384, 6Q / 2KV, FFN 1152; about 9.34M150 steps each of PT / SFT; first-to-last 10-step mean loss: PT 7.4355 → 2.2707, SFT 2.5253 → 2.1588Historical report
    MoE teaching implementationTop-k routing and expert FFNsComponent experiments available; complete small-model pretraining recipe, parameter count, and results pendingMoE

    nanoGPT's total includes 4,096 position-embedding parameters; the notebook's default printed count of 104,256 excludes them. The 9.34M record comes from a historical notebook experiment and has no current standalone YAML recipe. These experiments use different data and measurement protocols, so their losses are not directly comparable. Data, intermediate artifacts, and checkpoints must be prepared locally; no public weight-download entry point is currently provided.

    Data Sources and Processing

    The course covers web, encyclopedic, book, code, paper, and mathematical corpora, with composable Data-Juicer operators for cleaning, filtering, privacy protection, and deduplication. The diagram shows example operator chains; DotLM's implemented recipe uses Ultra-FineWeb for pretraining and Belle for SFT, as described in Data Pipeline Details.

    Data engineering notebook · Processing script · Pipeline details

    Learning Roadmap

    Topics covered:

    • Model training: BPE tokenizers, Mini-GPT, data preparation, DotLM pretraining, SFT, and evaluation.
    • Data engineering: corpus collection, Data-Juicer cleaning, synthetic data, data mixtures, and packing.
    • Model architectures: RoPE, GQA, MLA, MoE, scaling laws, and parallel training.
    • Post-training and inference: LoRA, model merging, alignment, distillation, decoding, KV cache, quantization, and inference systems.

    Curriculum

    The main course is organized into four parts. Each notebook is intended to be self-contained: follow the sequence or look up a topic directly.

    Part 1: Foundation

    #NotebookMain questionImplementation focus
    01Text and TokenizersWhy does a model need a tokenizer?Character-level and word-level tokenizers
    02BPE: Learning a Subword VocabularyHow does BPE learn a vocabulary from text?Merge rules, encode, decode
    03Token Embeddings and Distributed RepresentationsHow do token IDs become vectors?Token embeddings, distributed representations
    04Position EncodingHow does the model represent word order?Sinusoidal encoding, input assembly
    05Self-Attention and Transformer BlocksHow does attention pass contextual information?MHA, residual connections, normalization
    06Build GPT from ScratchHow are the components assembled into a GPT-style model?Decoder-only model, LM head
    07The BERT EncoderWhy can an encoder read context in both directions?MiniBERT, MLM head

    Part 2: Training

    #NotebookMain questionImplementation focus
    08Modern Language Model Architecture EvolutionWhat changed in model architecture after GPT-2?RMSNorm, SwiGLU, RoPE, GQA, QK-Norm, MLA
    09Reading a Language Model's ConfigurationWhat does each field in a real config.json mean?vocab_size, hidden_size, layers, heads
    09aLoss and the First Parameter UpdateHow does a model learn from its first error?Logits, cross-entropy, gradients, parameter updates
    10Language Model Pretraining and Fine-tuningHow does MiniGPT train, and how does that map to production interfaces?Training loop, chat templates, MTP, Trainer, SWIFT, label shifting
    11KV Cache and Architecture EvolutionHow can KV-cache memory be reduced for long contexts?MHA/GQA/MQA, MLA latent compression, decoupled RoPE
    12Distributed Training: The Production ToolchainWhat if a model does not fit on one GPU?Accelerate, ZeRO settings, Megatron-LM 3D parallelism, fine-tuning tools
    13From Dense to MoE ArchitecturesHow does sparse expert routing work?Router gates, top-k experts, auxiliary-loss-free balancing
    14Scaling Laws and Compute BudgetsHow should model size, data, and compute be balanced?Power laws, Kaplan/Chinchilla/overtraining, FLOPs/GPU-hours/memory estimates
    15Pretraining Data EngineeringWhere does training data come from, and how is it cleaned, synthesized, and mixed?Corpus sources, Data-Juicer, deduplication, synthesis, mixtures, packing, FIM
    16LoRA: Low-Rank Fine-tuningWhy does low-rank adaptation work?LoraLinear, merging for inference
    17Knowledge DistillationHow can a small model learn from a larger one?Soft labels, temperature, logit distillation
    18Function Calling and AgentsHow does a model call external tools?Structured output, tool calls, training-data construction
    19Preference Alignment and RLHFHow do preferences become optimization objectives?Reward models, PPO, DPO

    Part 3: Inference

    #NotebookMain questionImplementation focus
    20Decoding StrategiesHow do decoding strategies change model behavior?Greedy, top-k, top-p, beam search
    21Inference Acceleration and OptimizationWhy is generation often limited by memory access?KV cache, FlashAttention, PagedAttention
    22Low-Bit QuantizationHow can 4-bit quantization retain accuracy?Symmetric/asymmetric, per-channel/group, GPTQ, AWQ
    23Verification in Speculative DecodingHow can a small model accelerate a larger one?Draft-then-verify acceptance
    24Modern Inference EnginesHow are throughput and latency balanced with concurrent requests?PagedAttention, continuous batching, prefix caching, prefill/decode disaggregation
    25Model Evaluation MethodologyHow do we know whether a model is really better?Win-rate matrices, RAGAS, judge metrics
    26Model Deployment and ServingHow does a trained model become a callable service?vLLM, SGLang, custom architecture registration

    Part 4: Frontiers

    #NotebookMain questionImplementation focus
    27Long ContextHow can a model extend beyond its training context length?RoPE extrapolation, YaRN, sliding-window attention
    28Reasoning Models and Inference-Time ComputeWhy can thinking before answering improve accuracy, and how does extra inference compute help?R1-Zero, test-time scaling, thinking-budget control
    29Vision-Language ModelsHow does visual information enter a language model?Patch embeddings, cross-attention
    30Efficient AttentionHow can attention complexity fall from O(N²) to O(N)?Linear attention, SSM/Mamba, sparse attention, hybrid architectures
    31On-Policy Distillation (OPD)How can distillation reduce exposure bias?OPSD, KL estimator categories

    Advanced Appendices

    Probability and information theory, FLOPs and memory, mixed precision, FlashAttention, collective communication, parallelism, kernels, GPU hardware, and diffusion language models. See the advanced appendix directory.

    Local Setup

    Run the Notebooks Locally

    Requirements:

    • Python 3.9+
    • PyTorch 2.0+
    • NumPy, Matplotlib, and Jupyter
    • 16 GB RAM recommended
    git clone https://github.com/walkinglabs/modern-llm-notebook.git
    cd modern-llm-notebook
    
    python3 -m venv .venv
    source .venv/bin/activate
    
    python -m pip install --upgrade pip
    python -m pip install -r requirements.txt
    python -m ipykernel install --user \
      --name modern-llm-notebook \
      --display-name "Python (modern-llm-notebook)"
    
    jupyter notebook notebooks-en/part1-foundation/01-tokenizer-basics.ipynb
    

    If jupyter: command not found appears, the virtual environment may not be active. Run:

    source .venv/bin/activate
    

    You can also invoke Jupyter directly from the virtual environment:

    .venv/bin/jupyter notebook notebooks-en/part1-foundation/01-tokenizer-basics.ipynb
    

    Most notebooks run on CPU. Experiments involving larger training workloads are easier with a GPU.

    Language layout:

    • Chinese source notebooks: notebooks/
    • English notebook mirror: notebooks-en/

    Run the Web Reader Locally

    The React/Vite reader renders the original .ipynb files directly, so the website and notebooks stay in sync.

    npm install
    npm run dev
    

    Build and preview the static site:

    npm run build
    npm run preview
    

    Batch-Execute English Notebooks in Restricted Environments

    Some sandbox or CI environments prohibit opening local sockets, which can prevent the standard Jupyter kernel protocol, nbclient, and nbconvert --execute from working. The repository provides a kernel-free runner for this case. It executes code cells sequentially in Python and writes their outputs back to the English notebook files:

    python scripts/execute_notebooks_en_no_kernel.py
    

    Data Pipeline Details

    Data Sources and Cleaning

    DotLM's recorded run uses the Chinese shards of Ultra-FineWeb for pretraining and BelleGroup/train_1M_CN for SFT. The data engineering notebook introduces web, encyclopedic, book, code, and domain-specific corpora, then explains selection, cleaning, synthesis, and mixing.

    The executable path in preprocess_ufw.py has four commands: download, clean, truncate, and pack.

    StepOperationResult to inspect
    DownloadFetch Chinese shards from openbmb/Ultra-FineWebRaw text, quality scores, and source labels
    Quality filteringParse quality scores; keep score ≥ 0.8 for mini or ≥ 0.7 for fullRetained documents and their score distribution
    CleaningUse Data-Juicer for HTML removal, Unicode repair, whitespace normalization, and length filteringCleaned JSONL and retained document counts
    Token budgetCount actual BPE tokens and retain documents in score order up to the tier budgetPer-source statistics and a truncation manifest
    Training preparationSplit documents into training/validation sets, add EOS boundaries, and pack token sequencestrain.bin, val.bin, val.jsonl, and a packing manifest

    The script writes a Data-Juicer YAML recipe with clean_html_mapper → fix_unicode_mapper → whitespace_normalization_mapper → text_length_filter (100–8,000 characters). It relies on upstream deduplication and skips an additional SimHash pass. Dataset scale and retained counts come from the generated manifests.

    Synthetic Data and Data Mixtures

    The notebook explains Self-Instruct, Evol-Instruct, teacher distillation, and STaR, with small examples of generation and filtering. To extend this into a Data-Juicer synthesis pipeline, use the following reference route:

    StepWhat to doReference
    Generate QA pairsStart from cleaned documents; configure a teacher model to generate questions and answersData-Juicer generate_qa_from_text_mapper
    Filter and formatDeduplicate, check length and answer quality, inspect samples, and convert retained pairs into the SFT conversation formatData engineering · SFT data loader
    Mix and validateMix retained synthetic examples with real data, record the proportions, and compare a small training run on held-out tasksData recipes and sampling

    Current status: the notebook contains synthesis demonstrations; the training pipeline implements corpus cleaning. Data-Juicer synthesis is an extension reference, and DotLM's reported SFT results use Belle data. Consult the official Data-Juicer quick start for generation dependencies and YAML execution.

    Project Status

    AreaCurrent status
    CourseChinese source notebooks, English mirror, four main parts, and advanced systems appendices
    Dense trainingData processing, pretraining, SFT, evaluation scripts, and a recorded 64M-class experiment in llm_train/
    Online accessBilingual reader, Colab / ModelScope notebook links, and AMD project template
    DevelopmentActive updates to explanations, bilingual consistency, and experiment reproduction

    Next Training Experiments

    • Consolidate the Dense recipe with consistent tokenizer, data manifests, checkpoint export, and complete evaluation.
    • Add a small MoE pretraining recipe and publish both total and active parameter counts with its configuration.
    • Train and evaluate a small tool-calling model, including executable calls and recovery from errors.
    • Compare small-model preference training, distillation, and model merging against explicit baselines.
    • Continue refining the examples, hand calculations, and data / systems appendices.

    Course Preview

    Papers and Systems

    The course connects readable implementations to influential papers and production systems:

    Paper or systemConcepts covered
    Attention Is All You NeedMulti-Head Attention, position encoding
    BERTEncoder-only models, masked language modeling
    LLaMARMSNorm, SwiGLU, RoPE, Pre-Norm
    DeepSeek-V2 / DeepSeek-V3MLA, multi-token prediction, auxiliary-loss-free MoE load balancing
    Mixtral / Qwen3Sliding-window attention, MoE with shared experts
    Scaling Laws / ChinchillaParameter, data, and compute trade-offs
    LoRALow-rank adaptation
    RLHF / PPO / DPOPreference alignment
    Code Llama / DeepSeek-CoderFill-in-the-Middle
    FlashAttention / vLLMInference acceleration and memory management
    Speculative DecodingDraft-and-verify generation
    RoPE / YaRNLong-context extrapolation
    Chain-of-ThoughtReasoning traces and Self-Consistency
    Flamingo / LLaVAVision-language modeling
    Knowledge Distillation / OPDModel compression and behavior transfer

    Repository Structure

    modern-llm-notebook/
    ├── notebooks/           # Chinese source notebooks
    │   ├── part1-foundation/
    │   ├── part2-training/
    │   ├── part3-inference/
    │   ├── part4-frontiers/
    │   └── appendix-advanced/
    ├── notebooks-en/        # English notebook mirror
    │   ├── part1-foundation/
    │   ├── part2-training/
    │   ├── part3-inference/
    │   ├── part4-frontiers/
    │   └── appendix-advanced/
    ├── llm_train/           # Data processing, training, evaluation, and experiment reports
    ├── assets/              # README and course assets
    ├── web/                 # React/Vite course reader
    ├── docs/                # Static website build output
    ├── scripts/             # Notebook maintenance and verification scripts
    ├── requirements.txt
    ├── package.json
    ├── README.md
    └── README-CN.md
    

    Contributing

    Contributions are welcome when they make the course clearer, more accurate, easier to reproduce, or easier to navigate.

    Good contributions include:

    • Fixing incorrect explanations, broken cells, or outdated APIs.
    • Improving hand calculations and visualizations.
    • Adding small exercises with assertions.
    • Improving the Chinese and English documentation.
    • Proposing a notebook for an important model architecture, training method, or system.

    Please keep pull requests focused and read CONTRIBUTING.md before submitting one.

    Star History

    Citation

    If Modern LLM Notebook helps your research, teaching, or work, please cite:

    @misc{modern-llm-notebook,
      title   = {Modern LLM Notebook: Build Modern LLMs from Scratch},
      author  = {WalkingLabs},
      year    = {2025},
      url     = {https://github.com/walkinglabs/modern-llm-notebook},
      note    = {GitHub repository, accessed 2026}
    }
    

    License

    This course is released under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.