Maps to: UC Berkeley EE 290/194 Scalable AI, Fall 2026 Lecture 7 (Sep 21, 2026), the NVIDIA guest lecture NeMo AutoModel by Huiying Li, Zhiyu Li and Alexandros Koumparoulis, slides
lecture7.pdf. Part 1 introduces AutoModel; Part 2 is a DeepSeek-V4 case study. Spring 2026 had an NVIDIA framework guest lecture as Lecture 5. Recommended reading (course schedule): the NeMo AutoModel repository (GitHub,NVIDIA-NeMo/Automodel). Other sources: the Hugging Face blog post Accelerating fine-tuning with NVIDIA NeMo AutoModel, linked from the slides; H. He, Making Deep Learning Go Brrrr From First Principles, the “mental model” the slides reuse; the PyTorch documentation for FSDP2 (fully_shard),torch.distributed.pipeliningand Distributed Checkpoint (DCP); the DeepEP repository; the DeepSeek-V4 report as cited on the slides. Every number labelled measured comes fromcode/lecture08/on the author’s laptop. Numbers labelled reported are the slides’ own; demo 06 checks them for internal consistency. Code:code/lecture08/:miniframe.py, a miniature training framework built from Lectures 1–7, and six demos. Reading time: ~2 hours for the prose; ~20 minutes for the demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Say what a training framework is for. Name the decisions it makes once (model definitions, parallel plans, checkpoints, mixed precision, MoE components) and why a run should be described by configuration rather than code.
- Specify a correct checkpoint. List everything a resumable checkpoint must hold, and explain how a sharded checkpoint is reloaded at a different world size.
- Run an honest optimization loop. Fix the evaluation contract, change one thing, measure with replicates against a noise floor, keep or revert, record, and check the measurement itself.
- Read the case study critically. Follow the AutoModel DeepSeek-V4 journey from 3.85% to 12.27% MFU. Say which interventions mattered and why, and verify a published performance table with a few cheap checks.
0.2 Prerequisites and scope
- Prerequisites: Lectures 3 (profiling, MFU, fusion), 4 (MoE, sparse attention), 5–7 (DP/FSDP/EP, TP/PP, FlashAttention, CP, grouped GEMM).
- Scope: what a framework provides and how AutoModel is organized; configuration → model → plan → loop → checkpoint, built in miniature; correctness testing; the profiling and optimization workflow; the DeepSeek-V4 / Moonlight case study and its parallelism (DeepEP, HybridEP, the MoK megakernel, AutoPipeline, CP with sparse attention).
- Not in scope today: the NeMo container and cluster setup; fine-tuning recipes such as SFT/LoRA (Part III); the internals of FlashAttention-class kernels (Lecture 7).
0.3 Section → code map
| Section | Idea | Code in code/lecture08/ |
|---|---|---|
| §2 | recipe → configuration → model; the checkpoint-name contract; AutoPipeline’s renaming pitfall | miniframe.py, 01_config_to_model.py |
| §3.1–3.2 | resume bit for bit; what a checkpoint must hold | 02_train_and_resume.py |
| §3.3–3.4 | sharded checkpoints, resharding, consolidated export | 03_reshard_checkpoint.py |
| §5.3 | the experiment loop with a noise floor | 04_experiment_loop.py |
| §5.4 | the kernel factory: one operator, a contract, a crossover | 05_kernel_factory.py |
| §6 | the case study’s tables, checked | 06_case_study_check.py |
0.4 Notation
As before: MFU, tokens/s, step time, . New words: a recipe (训练配方) is a configuration file plus the script that runs it; a plan (并行方案) is the ordered list of transformations that turn a model into its parallel form; a contract (契约) is a fixed specification that candidates must meet: an evaluation contract for experiments, a numerical contract for kernels.
1. Why frameworks
Every lecture so far wrote its own training loop, and every loop repeated the same decisions: how to build the model, how to split the batch, which collectives to issue, what to save, how to resume. At scale these decisions are numerous and interacting (Lectures 5–7), and getting one wrong is silent: a wrong checkpoint name, a missed optimizer state, a pipeline stage in the wrong order. A training framework (训练框架) makes them once, behind a configuration. A run then becomes data that can be repeated, resumed, re-laid-out and compared.
The slides place frameworks on an ease-of-use vs speed spectrum. Some are performance-first, fast but complex to use and with limited model coverage. Some are simple, easy and broad but slow. NeMo AutoModel aims to have both. It is an open-source, PyTorch-based framework for LLM and VLM training, organized in two layers:
- Application layer (recipes): LLM fine-tuning (SFT, LoRA, QLoRA; single- and multi-turn), VLM fine-tuning, knowledge distillation, pre-training, sequence classification, quantization-aware training.
- Component layer: model definitions (Transformers), distributed, checkpointing, datasets, launcher, loggers, quantization, PEFT, MoE, loss, config.
Its contract is Hugging Face-native: drop-in, HF-style APIs for model instantiation, “thousands of models supported out of the box”, and no checkpoint conversion. A new model is validated by pointing a recipe at its Hub name. Speed comes from fused kernels (Liger, Transformer Engine), FSDP2, DeepEP and full n-D parallelism. Two paths share the components:
| Out-of-the-box (OOTB) path | Custom-model path | |
|---|---|---|
| model | wraps models from transformers | optimized re-implementations of the layers |
| parallelism | FSDP2, TP, PP via AutoPipeline | + CP and SP (Transformer Engine attention), MoE with DeepEP |
| speed-ups | fused cross-entropy (less memory), torch.compile, TorchAO, Liger and Triton kernels | Transformer Engine attention and dense kernels, rewritten model skeleton |
| contract | the HF model as it is | still loads and saves the HF checkpoint format |
code/lecture08/miniframe.py is this design at toy scale: configuration → model registry → parallel plan → training loop → checkpoints, built from Lectures 1–7. The rest of the lecture uses it to make each part concrete.
2. The front half: configuration, model, plan
2.1 A run is data
A recipe is a configuration file, YAML in AutoModel. Command-line overrides change one field without editing the file; the slides’ example points a recipe at a newly released model with --model.pretrained_model_name_or_path NEW_MODEL_ID. miniframe mirrors this with typed dataclasses and section.key=value overrides. Four overrides turn the dense ZeRO-1 recipe into an MoE run with activation checkpointing and 4 micro-steps per rank (demo 01).
Validation turns silent mistakes into errors before any process starts. Demo 01 rejects all 7 deliberate mistakes:
- a global batch not divisible by micro-batch;
- heads not divisible by KV heads;
- an unknown strategy;
- a warm-up longer than the run;
- MoE top- larger than the number of experts;
- a typo in a recipe key;
- a typo in an override key.
The last two matter most: a dict-of-anything configuration would silently ignore train.stpes = 10 and train with the default.
2.2 Models from a registry, checked against formulas
The registry builds a dense TinyTransformer or replaces its MLPs with Lecture 4’s MoE layer. As every lecture has insisted, the counts are checked against the formulas: 193,088 parameters for the dense recipe and 1,141,312 for the 8-expert MoE (330 K activated per token). They match exactly in all four configurations tested. A framework’s model zoo is only as good as the tests that pin it to its specification.
2.3 The checkpoint-name contract
AutoModel’s “no conversion” contract means checkpoints are saved under the model’s own parameter names, the HF format. miniframe saves model.state_dict() as is. Two checks in the demos:
- Lecture 1’s plain TinyTransformer, a class that knows nothing about the framework, loads a framework checkpoint with
strict=Trueand produces identical logits. An MoE checkpoint (131 tensors) loads into a freshly built MoE model exactly. - Strict loading rejects a checkpoint with a single key renamed. Name contracts are checked, not hoped for.
2.4 AutoPipeline: pipelines for any Hugging Face model
Pipeline parallelism (Lecture 6) needs the model cut into stages. AutoPipeline applies PyTorch-native pipelining to any HF causal-LM model in seven steps:
- analyze the
nn.Moduletree (typically embeddings → [Transformer + MoE blocks] × depth → final norm, LM head, MTP); - compute virtual stages from
layers_per_stage; - assign modules to stages;
- split the model by deep-copying it per stage and deleting the other stages’ modules;
- wrap each chunk in a
PipelineStage; - apply further parallelization through a
parallelize_fn; - build the schedule (1F1B, interleaved, …).
Three problems had to be solved:
- Placement requirements. Input embeddings must be on the first stage only. Transformer layers are distributed. The final norm and LM head go on the last (or second-to-last) stage. Rotary embeddings are needed on every stage. VLMs make this harder.
- Layer indexing. With
nn.ModuleList, a stage holding layers 8–15 renumbers them 0–7, and saving or loading checkpoints then silently maps them onto the wrong layers. Demo 01 reproduces it: stage 1 of an 8-layer model built asnn.ModuleList(blocks[4:8])has state-dict namesblocks.0–blocks.3. All 36 of its keys reuse layers 0–3’s names, so a checkpoint merged from the stages would silently overwrite layers 0–3 with 4–7. The fix, converting tonn.ModuleDictwith explicit string indices, keeps the names4/5/6/7. - Forward methods. A stage must run when some modules are missing (
embed_tokens is Noneon later stages), and it must return a plain tensor for the next stage, not aCausalLMOutputWithPast. AutoPipeline patches the HF forward accordingly.
2.5 The order of a plan
A plan is a sequence of model transformations, and the order matters. AutoModel’s order for the case study ( GPUs, PP = , FSDP = 4, EP = 4):
- split the model into stages (AutoPipeline);
- apply CP (Transformer Engine’s
DotProductAttention, or the model’s own CP); - apply EP (grouped experts);
- apply activation checkpointing;
- apply FSDP, with a default mesh for non-expert layers and an MoE mesh for experts.
Each step works on what the previous ones produced. FSDP must wrap the modules that exist after the pipeline split, and units that already contain their checkpoint wrappers. EP must have decided which parameters are experts before FSDP decides how to shard everything else. miniframe’s plan is the two-step tail of this list: activation checkpointing, then data parallelism (DDP or ZeRO-1 over one flat buffer).
3. Reliability: checkpoints that resume, reshard and export
3.1 A resumed run must be the same run
Long training runs are interrupted: preemption, hardware failures (Lecture 14), planned restarts. The framework’s contract is that a run resumed from its checkpoint is the same run. Demo 02 trains 24 steps on 2 ranks with ZeRO-1. The loss falls from 4.170 to 2.875, with a 4-step linear warm-up to 3e-3 and a cosine decay to 3e-4. It then “preempts” the run at step 12 and resumes. Result: the resumed run’s 24 losses and final weights are bit-identical to the uninterrupted run’s.
That requires the checkpoint to hold everything that determines the future:
| piece | why |
|---|---|
| weights | obviously |
| optimizer state: Adam , and its step counter | the update depends on them, including bias correction |
| the learning-rate schedule’s position | the next step’s learning rate |
| the data loader’s position (here, its generator state) | the next batch |
| configuration + sharding metadata (world size, strategy, padding) | to rebuild, and to reshard |
| (any other RNG: dropout, data augmentation) | none in this model |
3.2 How each missing piece fails, silently
Demo 02 resumes while forgetting one piece at a time:
| resumed without | what goes wrong | final weights vs uninterrupted | final loss |
|---|---|---|---|
| — (full checkpoint) | nothing | identical | 2.875 |
| optimizer state | Adam restarts at , step 1, so the first update is a full step | 1.4e-2 | 2.860 |
| loader position | re-trains on the first 12 batches (its step-13 loss is lower, 3.17 vs 3.23: that batch was seen) | 8.1e-3 | 2.830 |
| schedule position | warms up again (lr 7.5e-4 at step 13 instead of 1.86e-3), then stays high | 1.7e-2 | 2.519 |
None of the broken resumes crashes, and all their loss curves look plausible. The restarted schedule even ends with a lower loss, because it kept the learning rate high: a broken resume can look like an improvement. This is why frameworks test resume bit for bit instead of eyeballing a loss curve.
3.3 Sharded checkpoints and resharding
With a sharded optimizer, each rank should write only its own shard. That is what PyTorch’s Distributed Checkpoint (DCP) does at scale, and what miniframe.save_checkpoint does in small. A 4-rank ZeRO-1 checkpoint consists of 4 optimizer files of 388 kB (Adam’s and for a quarter of the parameters each), one weights file and small loader and metadata files. A naive DDP checkpoint writes a full copy per rank: 3.09 MB for 2 ranks, of which one copy suffices.
Resharding (重新分片): to load at a different world size, concatenate the saved shards, strip the padding, and cut the slice each new rank owns. Demo 03 saves at step 12 on 4 ranks with ZeRO-1 and finishes on several layouts:
| resumed on | final weights vs the uninterrupted 4-rank run |
|---|---|
| 4 ranks, ZeRO-1 (same layout) | bit-identical |
| 2 ranks, ZeRO-1 / 2 ranks, DDP | 1.4e-8 |
| 1 rank | 1.1e-7 |
| 4 ranks, optimizer state lost | 1.4e-2 (about 10⁵× larger) |
Only the same layout can be bit-identical: a different world size groups the gradient additions differently (Lecture 5 §4.6). The yardstick is the size of a real error. Resharding preserved the optimizer state up to rounding, five orders of magnitude below what losing it costs.
3.4 Correctness testing
The slides list three levels of verification for an optimized model:
- Numerical equivalence: compare each layer’s activations and gradients against the reference (OOTB) implementation, within tolerance.
- Loss-curve validation: training loss should match the reference on the same data.
- Downstream validation: evaluate on benchmarks after training.
Lectures 5–7 practiced the first level throughout. Every parallel implementation was compared with a dense reference: bit-for-bit where shapes and reduction order matched, to a dtype-appropriate tolerance otherwise. Section 3.2 shows why the second level alone is not enough: a broken run’s loss can look fine. In the slides’ words, performance and correctness go hand in hand.
4. The mental model for performance
The slides reuse Horace He’s model of where training time goes:
- compute: time in matmuls and other arithmetic;
- memory bandwidth: moving tensors between HBM and the chips;
- overhead: everything else, including Python, framework dispatch and kernel launches.
Each calls for a different intervention. Kernel fusion avoids unnecessary HBM traffic. On an H100, shared memory runs at ~33 TB/s vs HBM’s ~3.35 TB/s, a 10× gap. Epilogue fusion folds activations into a GEMM’s last stage. Overhead is removed by launching fewer kernels: tiny kernels can take longer to launch than to run, and a queue full of them can stall the launching thread. CUDA graphs, torch.compile and grouped GEMMs (N launches → 1) all attack overhead. This is Lecture 3’s “three regimes”, now applied by a framework team to a real model.
5. Profiling and the optimization loop
5.1 Tools
torch.profiler | Nsight Systems (nsys) | |
|---|---|---|
| best for | quick Python- and operator-level profiling; correlating CPU and CUDA activity; shapes, memory, stack traces (with overhead) | the end-to-end timeline: CPU threads, GPU work, CUDA runtime, NVTX ranges, NCCL and its overlap with compute |
| typical question | which ops are expensive? is CPU launch overhead visible? | why is the GPU idle? is data loading blocking the step? do collectives overlap? |
| output | traces for TensorBoard / Perfetto | .nsys-rep, exportable to SQLite |
The slides’ newer point concerns who reads the trace. A human scrolling a timeline recognizes patterns, but cannot count, aggregate or compare across five profiles. An agent querying the exported SQLite can. It can report, for example, “1,770 gaps, mean 23.8 µs, 81% host-side”, “22.8% of the stall”, or “five profiles in one table”. It can also attach a measurement mean and an error bar to each claim. The human supplies the suspicion; every correction in the slides’ session began with a human challenge.
5.2 Verification keeps the measurement honest
Each claim needs a cheap check that could prove it wrong. The slides’ principles:
- Derive a noise floor. Runs that should not differ become replicates; a delta inside their spread is not a finding.
- Check the measurement. Span vs busy time. Forward vs forward + backward. Warm vs cold. The metric’s name rarely tells you what it measures.
- The question limits the answer. A narrow question can produce a confidently wrong answer.
5.3 The experiment loop (demo 04, measured)
The loop: baseline (fix the workload and the metric) → target (classify the bottleneck) → experiment (change one bounded thing) → measure (repeat the same workload) → decide (keep repeatable gains, revert the rest) → record (configuration, metric, variation). Throughout, a fixed evaluation contract holds the workload, hardware, metric and acceptance rule constant. The slides apply the same loop to three search surfaces: training code (“autoresearch”), kernel implementations (the kernel factory), and whole applications.
Demo 04 runs it on this machine: 2 ranks, the 1.16 M-parameter model, 25 steps, metric = median step time of steps 6–25 as tokens/s, 3 replicates per configuration. Rule: keep a change if its gain exceeds the baseline’s replicate spread and 2%.
| change | gain vs baseline | decision |
|---|---|---|
| (baseline: 37.0 k tokens/s, replicates within 1.8%) | — | — |
| micro-batch 4 (2 accumulation steps) | +22.9% | keep |
| micro-batch 8 (no accumulation) | +36.2% | keep |
| bf16 autocast | −88.6% (no fast bf16 matmul on this CPU) | revert |
| activation checkpointing | −38.1% (a memory knob: it recomputes the forward) | revert |
| ZeRO-1 instead of DDP | −3.1% | revert |
| garbage collection every 10 steps | −0.8% | revert (within noise) |
The two micro-batch sizes are alternatives, so stacking keeps only micro-batch 8. Re-measuring it gives +36.6%, a 0.4-point difference inside the noise floor. The first step takes 1.9× the steady-state time, so including it would bias every comparison: warm vs cold.
Two lessons go beyond the table:
- Replicates must be representative. Back-to-back replicates spread by only 1.8–2.6%, but the micro-batch-8 gain was +43.9%, +37.9% and +36.2% in three separate sessions of the same demo. Session-to-session variation is larger than within-session noise, so a 3% “win” from one session should not be trusted, even with replicates.
- Context decides. Scheduled garbage collection gave +8.4% throughput and cut the iteration spread from 1.7% to 0.1% on the slides’ 256-GPU Kimi K3 job. Here it is within noise for throughput, though it roughly halved the step-time spread: a tiny model allocates few Python objects per step.
5.4 The kernel factory: one operator under a contract (demo 05)
The slides’ kernel factory applies the loop to a kernel. For RMSNorm in DeepSeek-V4, the resolved contract is: hidden 2,048, eps 1e-6, input in BF16, FP32 accumulation and one BF16 store, forward only. Nsight provides the workload shapes: 1,024 tokens to capture, 4,096 for a micro-benchmark, 8,192 for the end-to-end gate. Migrating to the winning backend is one YAML line, rms_norm: torch_fp32 → kf_triton_h2048. Reported results (8 × H100, 8,192 tokens):
| backend | kernel | wall | share of the 20.0 µs HBM roofline |
|---|---|---|---|
| factory Triton kernel | 23.8 µs | 83.5 µs | 84% |
| Transformer Engine 2.11 | 25.6 µs | 46.7 µs | 78% |
| torch | 27.1 µs | 28.8 µs | 74% |
shipped torch_fp32 | 147.3 µs | 153.1 µs | 14% |
The factory kernel wins every one of the nine tested sizes as a kernel. But at 8K tokens, dispatch dominates: 83.5 µs of wall clock around 23.8 µs of CUDA. Torch wins the wall clock up to 16K tokens and the factory kernel from 32K. The training workload runs below the crossover. The optimization order is therefore: first CUDA-graph the launch path (the dispatch floor, not the kernel, decides the wall clock); second, remove the full FP32 copy.
Demo 05 runs the same loop for RMSNorm on this CPU, with four candidates:
- Numerics. Everything except “eager in bf16” meets the contract. That candidate accumulates in bf16, with error 5.0e-2 against 1.6e-2, beyond one bf16 ulp.
- Bytes. The shipped version moves 40 bytes per element in 7 eager passes; a fused kernel needs 4.
torch.compileof the shipped code takes 3.0 ms at 32,768 tokens vs 11.8 ms eager. - The floor. At 64 tokens the work would take ~2 µs at copy bandwidth, yet every candidate takes 55–180 µs: the per-call floor of Python, dispatch and guards. On this CPU the compiled kernel wins at every size, so there is no crossover. On the H100 there is one because the factory kernel’s launch path costs more than torch’s.
- The roof. The eager passes each run at ~98% of the measured copy bandwidth: the eager version is slow because of the bytes, not the passes. The compiled kernel reaches only 38%, so it is limited by something else, and there is headroom left. Comparing against a measured roof (the slide’s “84% of HBM”) turns “faster” into “how much is left”.
The case study’s other kernel-level changes follow the same logic:
- mHC with
torch.compile: 23 + 51 kernels forward and backward → 9 + 25, for a 5.5% shorter step. Pros: quick to implement. Cons: dynamic shapes, compile time, compiler bugs. - GroupedGEMM for the experts: many launches → one.
6. The DeepSeek-V4 case study
6.1 The architecture
DeepSeek-V4, as summarized on the slides, extends sparsity from the FFN to attention:
- Hybrid attention: compressed sparse attention (CSA) and HCA layers compress the KV sequence through a token compressor (4× or 128×). A CSA query attends to 128 window entries plus 512 selected compressed entries; an HCA query to 128 plus .
- Manifold-constrained hyper-connections (mHC) in place of plain residual connections.
- Context: up to 1M tokens. At 1M tokens, DeepSeek-V4-Pro needs 27% of DeepSeek-V3.2’s FLOPs per token and 10% of its KV cache.
Configurations (reported):
| model | total | active | layers | experts (top-k) | CSA / HCA / SWA layers |
|---|---|---|---|---|---|
| DeepSeek-V4-Pro | 1.573 T | 49.8 B | 61 | 384 routed + 1 shared (6) | 30 / 31 / 0 |
| DeepSeek-V4-Flash | 284.3 B | 13.8 B | 43 | 256 + 1 (6) | 21 / 20 / 2 |
| Moonlight-V4-16B-A3B | 16.5 B | 3.0 B | 27 | 64 + 1 (6) | 13 / 12 / 2 |
Moonlight-V4-16B-A3B is a downscaled DeepSeek-V4 created for the lecture. It is small enough to profile and tune on a single node, yet keeps the architecture’s specialized attention and MoE. Its memory budget, from the slides and checked in demo 06:
- model states B = 132 GB (BF16 parameters, gradients and Adam states);
- 16.5 GB per GPU under FSDP over 8, leaving ~63.5 GB for activations;
- KV cache 31.1 KB/token for Moonlight-16B vs 2.4 KB for Moonlight-V4, i.e. 243 MiB vs 18.6 MiB at 8K and 30.4 GiB vs 2.1 GiB at 1M.
6.2 The optimization journey
8 × H100, BF16, global batch 256 × 2,048 tokens, as reported:
| change | step | MFU | tokens/s | gain | what it was |
|---|---|---|---|---|---|
| stock HF model | 28.734 s | 3.85% | 18.25k | — | baseline (32 accumulation steps) |
| native EP8, eager attention | 19.748 s | 5.59% | 26.55k | +31.3% | AutoModel’s native implementation plus expert parallelism |
| grouped_gemm + DeepEP | 19.853 s | 5.57% | 26.41k | −0.5% | combined kernel and communication change; slightly slower at this micro-batch |
| TileLang sparse attention, indexer, Sinkhorn | 14.520 s | 7.61% | 36.11k | +26.9% | kernel replacement, not fusion |
| compiled mHC | 13.721 s | 8.05% | 38.21k | +5.5% | kernel fusion |
| BF16 gradient reduction | 13.584 s | 8.13% | 38.60k | +1.0% | halves gradient-reduction traffic |
| BF16 mHC and LM-head projections | 13.341 s | 8.28% | 39.30k | +1.8% | precision |
| local batch 2 | 9.005 s | 12.27% | 58.22k | +32.5% | batching / utilization, no kernel change |
Demo 06 checks the table against itself, and every row holds to the printed precision:
- tokens/s equals 524,288 tokens divided by the step time;
- MFU scales as 1/step time from the baseline;
- every incremental gain equals .
End to end that is 3.19× faster. The two largest wins are not kernels: native expert parallelism and a larger local batch. The biggest kernel change (the TileLang sparse-attention kernels) comes third. Fusion and BF16 gradient reduction are small. A slightly negative step was reported rather than hidden.
One more cheap check. The reported MFU implies FLOPs per token. That is 2.78 B “6N-equivalent” parameters, against the 3.0 B activated parameters reported; B would give 4.2% MFU. A ~7% disagreement like this means the MFU definition differs: which parameters are counted, whether attention FLOPs are added. That is a reason to ask for the definition, not to distrust the table.
6.3 Expert parallelism across NVLink domains
The most detailed part of the case study is how a token travels through an MoE layer on 4 nodes, each one 8-GPU NVLink domain. Take a token on rank 0 whose experts are A on rank 2, B and C on rank 25, and D on rank 27.
Dispatch: de-duplicate, then expand. The token crosses the network once per destination domain, on its rail: from rank 0 to rank 24, the same local rank in node 3. NVLink then fans it out to ranks 25 and 27. A second de-duplication sends one copy to rank 25 for both B and C. Only then is it expanded into one row per expert and permuted into expert-major order for the grouped GEMM. This is Lecture 5 §5.4’s de-duplication: for DeepSeek-V3 on 8 nodes, 4.6 remote nodes instead of 7 remote experts per token under uniform routing. The three libraries differ in mechanism:
| within an NVLink domain | across domains | |
|---|---|---|
| DeepEP v1 | CUDA peer-memory loads/stores, TMA over NVLink | NVSHMEM / IBGDA, GPU-initiated RDMA |
| HybridEP | CUDA peer-memory access | DOCA, GPU-initiated RDMA |
| DeepEP v2 | NCCL LSA | NCCL GIN, RDMA over InfiniBand / RoCE |
GPUDirect RDMA lets the NIC read GPU memory without staging through the CPU.
Expert compute: two grouped GEMMs. The first fuses gate and up into one GEMM; then SwiGLU runs; then the down projection. Per-expert segments are described by token counts or cumulative offsets, which change on every step with routing. AutoModel offers four backends:
grouped_gemm.ops.gmm;- native
torch._grouped_mm, which demo 06 of Lecture 7 measured on CPU; - Transformer Engine’s
GroupedLinear, with FP8 / MXFP8 recipes; - TorchAO’s MXFP8 grouped GEMM.
Combine: restore order, reduce locally, send one partial sum. On the expert rank, the outputs are un-permuted from expert-major to source-token order, and B(x) and C(x) are added locally. Within the remote domain, rank 24 reads ranks 25 and 27 and adds their results. One partial sum crosses the network back to rank 0, which adds the local and remote contributions. Dispatch fans inputs out; combine adds expert contributions back together.
Mixture of Kittens (MoK) goes one step further. On GB200/GB300 NVL72 domains, dispatch (as pulls), expert compute and combine (as pushes) run in one persistent megakernel. Communication SMs move tokens while compute SMs run whatever expert work is ready, and GPU-local counters connect the two. Reported on DeepSeek-V4-Flash, 64 GB200 GPUs: step 9.164 s with separate HybridEP kernels, 8.064 s with MoK in BF16 (1.136×), 7.425 s with MoK in MXFP8 (1.234×). The plain HF + FSDP baseline ran out of memory.
6.4 n-D parallelism in the case study
- FSDP + EP share one mesh axis. FSDP shards the non-expert layers (attention, shared FFN); EP distributes the experts. Two meshes, a default one and an MoE one, describe the same GPUs. This enables sparser and bigger MoEs, with hundreds of experts, at the price of careful communication scheduling.
- PP for models of 700B+ parameters, such as the 1.6 T-parameter DeepSeek-V4-Pro. Each stage is sharded with FSDP + EP on its own, scheduled with 1F1B or interleaved 1F1B, through AutoPipeline (§2.4).
- CP with sparse attention. DeepSeek-V4-Flash’s CSA layers at 16,384 tokens with CP = 4 keep each rank’s 4,096 queries local, but AllGather the K/V-side tensors: raw KV (16,384), compressed KV (4,096) and indexer keys (4,096). Each query then attends to 128 recent raw entries plus 512 compressed entries chosen by the indexer from the global pool, and autograd sums gradients back to the KV owners. This is Lecture 7’s “AllGather K/V” pattern, viable here because sparsity and compression make the gathered K/V small.
6.5 Field notes from Kimi K3
The slides close the performance story with independent A/B results from a 2.78 T-parameter Kimi K3 run (256 GB200, PP8 / EP32, 2K synthetic benchmark). These gains are not additive:
- Memory / PP buffers: save BF16 inputs and recompute the FP32 math in chunks (~45 GiB saved on middle stages); reuse 1F1B receive buffers as a ring.
- Kernel fusion: compiled SiTU / router-weight / RMSNorm chains, Triton attention-residual kernels, fused KDA kernels: a few percent each.
- Host synchronization: reuse static metadata; bounded-capacity dispatch.
- Runtime stalls: Python garbage collection every 10 steps, +8.4% throughput, iteration spread 1.7% → 0.1%.
- Startup: compiling pipeline stages concurrently cut iteration 0 from 607 s to 71 s.
The latest reported stack runs at 839.6 tokens/s/GPU and 21.1% MFU. Demo 06 computes what that MFU implies: FLOPs per token.
6.6 The takeaways
The slides end with four:
- Optimize at the kernel level with a combination of
torch.compileand specialized kernels. - Start small, then scale out with n-D parallelism for large models and long sequences.
- Performance and correctness go hand in hand.
- Always read the source code.
7. Summary
- A framework makes the repeated decisions once: model definitions, a parallel plan applied in order, mixed precision, checkpoints, MoE components. A run is then described by configuration that is validated before it starts.
- AutoModel’s contract is Hugging Face-native models, no checkpoint conversion, and speed through fused kernels and n-D parallelism, on two paths (OOTB and custom) that share components. AutoPipeline cuts HF models into pipeline stages, solving placement, layer naming (
ModuleDict) and forward-signature problems. - Checkpoints must hold weights, optimizer state with its step counter, schedule position, loader position and sharding metadata. Then a resumed run is bit-identical (measured). Each missing piece fails silently, sometimes with a better-looking loss. Sharded checkpoints reshard by concatenate-and-slice; only the same layout is bit-identical, others agree to rounding (≤ 1.1e-7 vs 1.4e-2 for a real error).
- Optimization is a loop under a fixed contract: one change, replicates, a noise floor, a decision rule, a record. Measured here, bigger micro-batches won (+36%) and checkpointing and bf16-on-CPU lost. Replicates within one session understated the noise between sessions.
- Kernel work is a contract plus a roofline plus a dispatch floor. The best kernel can lose the wall clock below a crossover; compare against a measured roof.
- The case study: 3.85% → 12.27% MFU (3.19×), with the largest wins from expert parallelism and batch size. Communication-aware EP (de-duplicated dispatch, local reduction, MoK) and FSDP + EP + PP + sparse-attention CP carry it to scale. Its published table is internally consistent, which is worth checking for any table.
8. Common pitfalls
- Configuration as an untyped dict. Typos become defaults.
- Testing resume by looking at the loss curve. Compare bits.
- Forgetting Adam’s step counter or the scheduler state in a checkpoint, or the data loader’s position.
- Expecting bit-identical results after resharding. Expect rounding-level agreement, and compare with the size of a real error.
- Splitting
nn.ModuleLists across pipeline stages, and saving checkpoints whose layer names restart at 0. - Applying FSDP before the pipeline split or EP. Order the plan.
- Calling a 2% gain a win from three back-to-back runs. Check across sessions.
- Optimizing the kernel when the dispatch floor decides the wall clock. Measure wall time at the workload’s real sizes.
- Comparing MFU numbers with different definitions.
9. Exercises
- Checkpoint size. A 7 B-parameter model is trained with mixed-precision AdamW (BF16 weights; FP32 master weights, and ) on 64 GPUs with ZeRO-1. How many bytes does each rank write, and how big is the whole checkpoint?
Answer
Each rank writes its shard of the FP32 master weights, and : GB. Rank 0 (or a sharded writer) writes the BF16 weights once: 14 GB, unless the consolidated weights are reconstructed from the FP32 master shards. In total ~84 GB of optimizer state plus 14 GB of weights ≈ 98 GB. A naive replicated (DDP) checkpoint would write 84 GB per rank.
- Resharding. A ZeRO-1 run on 4 ranks pads its flat parameter vector of 1,000,001 elements to a multiple of 4. How long is each shard, and what does a 3-rank resume do with the saved shards?
Answer
Padded to 1,000,004, so 250,001 per shard (the last has 3 padding zeros). To resume on 3 ranks: concatenate the 4 shards, strip to 1,000,001, pad to a multiple of 3 (1,000,002), and give each rank 333,334 elements.
- Which piece is missing? After a resume, the first few losses are fine, but the loss later stops falling as it should, and the learning rate printed at the resume step equals the warm-up’s first value. What was lost?
Answer
The scheduler’s position: the schedule restarted from step 0. Fine early losses rule out the weights. A lost optimizer state would show as a jump at the first resumed update. A replayed loader would show as suspiciously low losses on already-seen batches.
- Noise floor. Three baseline runs give 1,000, 1,030 and 985 tokens/s; a candidate gives 1,020, 1,045 and 1,010. Keep it under the rule “gain > max(spread, 2%)”?
Answer
Baseline median 1,000, spread . Candidate median 1,020: a +2.0% gain, inside the 4.5% floor. Revert, or gather more replicates. The ranges also overlap.
- Dispatch floor. A kernel takes 24 µs on the GPU, but each call costs 60 µs of host-side launch work; the alternative takes 27 µs with 2 µs of launch. At what point does the faster kernel win the wall clock, and what are two ways to get there?
Answer
Per call: 84 µs vs 29 µs, so the alternative wins at this size. The faster kernel wins when its work dominates its overhead, i.e. at larger inputs (the kernel times grow, the launch costs do not). Or remove the launch overhead: capture the step in a CUDA graph, or fuse the call into a neighbouring kernel. The slides’ order of optimization: CUDA-graph the launch path first.
- Read the table. In the AutoModel journey, “local batch 2” gave +32.5% with no kernel change. Using Lecture 3, explain why a larger micro-batch helps an MoE model particularly.
Answer
Each micro-batch’s tokens are split over many experts. With local batch 1 (2,048 tokens), each of 64 experts sees on average tokens: skinny GEMMs with partial tiles (Lecture 7 §4.1), plus fixed per-micro-batch costs (launches, AllToAll startups, host synchronization). Doubling the micro-batch halves the number of micro-steps (32 → 16) and doubles the rows per expert GEMM, which raises utilization on every one of those fronts.
- Plan order. Why must FSDP be applied after the pipeline split, and after EP?
Answer
After the pipeline split, because each stage holds only its own layers, and FSDP must wrap (and shard) those modules on that stage’s ranks; wrapping first would shard modules that are then deleted. After EP, because experts are distributed over the EP group and must be excluded from (or handled by a separate mesh in) FSDP’s default sharding. Applying FSDP first would shard expert weights along the wrong axis.
- MFU definitions. A team reports 40% MFU using per token; another reports 34% for the same run, adding the attention-score FLOPs and counting only non-embedding parameters. Can both be right? Which numbers would you ask for?
Answer
Yes. MFU is model FLOPs / (GPUs × peak × time), and the “model FLOPs” depend on the convention: which parameters, whether attention’s term is included, whether recomputation counts. Ask for tokens/s, the number and type of GPUs, the peak used (dense BF16?), and the FLOPs-per-token formula. Then recompute both, as demo 06 does.
10. The related assignment (concepts only)
Fall 2026’s Assignment 2 (pre-training) trains a model on the group’s 8×H100 node with a framework, and the project builds on it. The concepts from this lecture that the assignment exercises:
- reading and writing a recipe, and validating it before launching;
- choosing a parallel plan for one node and justifying its order;
- making runs resumable and testing that they are;
- reporting performance with a defined metric (MFU convention, tokens/s), a noise floor and a record of what was tried, including what did not help.
No assignment solutions are given here; miniframe.py is independent of the course’s starter code.
11. Research directions
- Agent-driven optimization. The slides’ “autoresearch” and “kernel factory” loops are agent-friendly, with a fixed contract, cheap verification and a decision rule. What fraction of a framework team’s tuning can be automated safely, and which human checks remain essential?
- Checkpointing at scale. Asynchronous, sharded, resharding-capable checkpoints (DCP) trade I/O against step time. How often to checkpoint given failure rates (Lecture 1’s Young interval, Lecture 14), and how to make resume verifiable cheaply?
- Communication-compute fusion for MoE. MoK fuses dispatch, experts and combine into one kernel. Where else can communication move inside compute kernels, and what does it cost in portability?
- Verified frameworks. Systematic numerical-equivalence tests across parallel layouts (the bit-for-bit vs tolerance distinctions of Lectures 5–8) could become part of CI for every new model a framework supports on day 0.
- Better performance reporting. A standard for MFU definitions, noise floors and recorded negative results would make published optimization tables comparable.
12. Further reading
- NVIDIA NeMo AutoModel: the GitHub repository (
NVIDIA-NeMo/Automodel) and its documentation (performance summary, recipes). - Hugging Face blog, Accelerating fine-tuning with NVIDIA NeMo AutoModel; the AutoModel blog posts on native MoE training in PyTorch and on enabling PyTorch-native pipeline parallelism for Hugging Face models (linked from the slides).
- H. He, Making Deep Learning Go Brrrr From First Principles (horace.io).
- PyTorch documentation: FSDP2 (
torch.distributed.fsdp.fully_shard), DTensor and DeviceMesh,torch.distributed.pipelining, Distributed Checkpoint (torch.distributed.checkpoint). - DeepSeek-AI, DeepEP (GitHub): MoE dispatch and combine kernels.
- The DeepSeek-V4 technical report, as cited on the slides.
13. Next lecture
Lecture 9 · Introduction to Pre-Training. Part I built the machine: the accounting, the kernels, the parallelism, and now a framework that runs it reliably. Part II uses it to make a base model. Lecture 9 introduces tokenization and the language-modelling objective, the training step as a whole, and what a pre-training run’s loss curve can and cannot tell you. It builds a lighter, single-process pre-training stack on Lecture 1’s model and trains small models on a toy web whose true probabilities are known, so their behaviour can be measured end to end.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| training framework | 训练框架 |
| recipe / application layer / component layer | 训练配方 / 应用层 / 组件层 |
| configuration / override / validation | 配置 / 覆盖 / 校验 |
| Hugging Face-native / day-0 support | 原生兼容 Hugging Face / 发布当天即支持 |
| out-of-the-box (OOTB) path / custom-model path | 开箱即用路径 / 自定义模型路径 |
| model registry | 模型注册表 |
| checkpoint conversion | 检查点格式转换 |
| parallel plan / order of application | 并行方案 / 应用顺序 |
| device mesh (default mesh, MoE mesh) | 设备网格(默认网格、MoE 网格) |
| AutoPipeline / pipeline stage / virtual stage | 自动流水线 / 流水线阶段 / 虚拟阶段 |
| layer indexing / ModuleList / ModuleDict | 层编号 / 模块列表 / 模块字典 |
| checkpoint / resume / preemption | 检查点 / 断点续训 / 抢占 |
| sharded checkpoint / resharding / consolidated weights | 分片检查点 / 重新分片 / 合并后的权重 |
| Distributed Checkpoint (DCP) | 分布式检查点 |
| learning-rate scheduler state / data-loader state | 学习率调度器状态 / 数据加载器状态 |
| numerical equivalence / loss-curve validation | 数值等价 / 损失曲线校验 |
| compute / memory bandwidth / overhead (three regimes) | 计算 / 内存带宽 / 开销(三种瓶颈) |
| profiler / timeline / trace / NVTX range | 性能分析器 / 时间线 / 追踪 / NVTX 区间 |
| noise floor / replicate / error bar | 噪声底 / 重复实验 / 误差棒 |
| experiment loop / evaluation contract / decision rule | 实验循环 / 评测约定 / 决策规则 |
| kernel factory / numerical contract | 算子工厂 / 数值契约 |
| dispatch floor / launch overhead / CUDA graph | 调度开销下限 / 启动开销 / CUDA 图 |
| crossover | 交叉点 |
| expert parallelism dispatch / combine / de-duplication | 专家并行分发 / 合并 / 去重 |
| expand / permute / unpermute | 展开 / 重排 / 逆重排 |
| GPU-initiated RDMA / GPUDirect RDMA | GPU 发起的远程直接内存访问 / GPU 直连 RDMA |
| megakernel (Mixture of Kittens, MoK) | 巨型融合内核 |
| hyper-connections (mHC) | 超连接 |
| compressed sparse attention (CSA) | 压缩稀疏注意力 |
| garbage collection / iteration-time spread | 垃圾回收 / 迭代时间波动 |