Module 21

Distributed Training and Inference

How can we train and run models with billions of parameters while using compute efficiently?

lessons
28
duration
50 h 50 min
concepts
168
available in English
28 / 28
completed by you
0 of 28

Where it fits

Overview

Work through the full range of large-model efficiency techniques. Calculate FLOPs, memory, and bandwidth. Study mixed precision from FP16 to FP8 and FP4, recomputation, gradient accumulation, and custom Triton kernels. Build data parallelism, ZeRO and FSDP, tensor, pipeline, context, and expert parallelism from collective communication primitives. The second half covers inference: sampling, beam search, serving metrics and cost, paged KV caches, prefixes, compression, continuous batching, speculative decoding, quantization, pruning, and knowledge distillation. The single-GPU work targets the local RTX 4060. Exercises that require multiple GPUs use Gloo processes on the CPU, exact simulators, and visualizations of tensor partitioning.

Why it matters

These techniques let you train and serve the models you study. Plan memory and parallelism for a training run, write a missing kernel, quantize a model to fit in 8 GB, and build an inference engine with paged attention and speculative decoding. GPT from scratch, AlphaZero at scale, and products built around LLMs, including application-security tools, all use these techniques. They also provide the foundation for reading work on FP4, DiLoCo, disaggregated serving, and EAGLE.

Lessons 28

  1. 01Review: the arithmetic of training and serving a large modelThis opening lesson revisits the roofline model, GPU memory hierarchy, and transformer parameter and FLOP counts from m09 and m18. It turns them into the tools used throughout this module: the C ≈ 6ND rule, MFU, the 16 bytes per parameter for mixed-precision AdamW, and activation memory. It concludes with a taxonomy of bottlenecks: each subsequent technique addresses one of them. GPUReview80 min
  2. 02Mixed precision I: FP16, BF16, master weights and loss scalingTraining in 16 bits can double Tensor Core throughput and halve activation memory, but doing so naively can diverge or stall. We study three failures, gradient underflow, activation overflow, and updates absorbed by rounding, and a recipe addressing them: FP32 master weights and accumulation, dynamic loss scaling, and a per-operation precision policy. The lesson concludes with pure BF16, stochastic rounding, and Kahan summation in the optimizer. GPUCore105 min
  3. 03Mixed precision II: FP8, microscaling and the 4-bit frontierWith 8 bits a global scale is no longer enough: the range is short enough to require a per-tensor factor, while outliers motivate block scaling. We study E4M3 and E5M2, current and delayed tensor scaling, the FP8 matmul recipe, DeepSeek-V3 tile scaling and MX formats, and instabilities that emerge only in long training runs. The lab checks compatibility before measuring native FP8 matmuls: on the RTX 3060 used here it compares quantization, emulation, and BF16 without attributing native FP8 acceleration to that device. Code is also provided for compatible GPUs, and the lesson closes with the FP4 training frontier. GPUAdvanced110 min
  4. 04Activation memory: checkpointing, gradient accumulation and offloadingActivations rather than weights are often what does not fit in GPU memory. We examine what autograd saves for backward and three ways to reduce it: recomputation (full, √n, binomial and selective checkpointing), dividing the batch into microbatches with correctly normalized gradient accumulation, and moving tensors to CPU with overlapping transfers. All are applied to a GPT that does not fit in 8 GB until these methods are used. GPUCore105 min
  5. 05Triton kernels I: programming the GPU in blocksTriton enables GPU kernels in Python expressed in blocks instead of threads, with a compiler handling coalescing, shared memory and synchronization. We prepare a compatible environment and record the actual GPU used; this run uses an RTX 3060 with WSL2 Ubuntu. We debug on CPU with interpreter mode and write first kernels: vector addition, fused elementwise operations and row softmax, measured against actual bandwidth, PyTorch and torch.compile. GPUCore110 min
  6. 06Triton kernels II: matmul, fused normalization and logit-free cross-entropyWe write kernels that save memory and time in LLM training: tiled matmul with Tensor Cores, grouped L2 cache order and fused epilogues; fused RMSNorm forward and backward; and linear-head cross-entropy without materializing logits that can exceed model size at 128k vocabularies. The kernels are registered as PyTorch operators and integrated into the course GPT. GPUAdvanced120 min
  7. 07Attention kernels in Triton and the CUDA ecosystemModule m18 derived FlashAttention in NumPy; here we write the GPU kernel. We implement Triton forward with online softmax and causal-block skipping and backward with recomputation, including GQA and sliding-window variants. We then move up a level to FlexAttention, which generates kernels from a score function and block mask, and down to CUDA C++ and data-center GPU features behind FlashAttention-3. GPUAdvanced115 min
  8. 08Communication between GPUs: collectives, NCCL and the alpha-beta modelParallel strategies depend on which collectives run, how many bytes they move, and over which links. We define collective primitives and their identities, build the alpha-beta cost model, and prove ring all-reduce bandwidth optimality against tree algorithms that win for small messages. We review hardware (PCIe, NVLink, InfiniBand) and the NCCL and torch.distributed stack, and practice with CPU Gloo processes because NCCL requires a separate GPU per rank. GPUCore110 min
  9. 09Data parallelism: DDP, buckets and overlapThe simplest parallelism, always present: identical replicas process different data and average gradients. We prove equivalence to a large batch, build DDP from scratch through bucketed all-reduce overlap with backward, and address distributed sampling, unsynchronized accumulation, batch normalization and diverging ranks. We finish with scaling limits from communication and critical batch size. GPUCore100 min
  10. 10ZeRO and FSDP: sharding optimizer states, gradients and parametersWith DDP every GPU stores 16 bytes per parameter even when updating only a portion. ZeRO removes redundancy in stages: optimizer states, gradients, then parameters gathered just in time. We derive memory and communication volume, implement the stages from scratch with Gloo processes, study PyTorch FSDP and FSDP2 and CPU/NVMe offloading, and use ZeRO-Offload to fine-tune on an RTX 4060 a model that would not fit with GPU AdamW. GPUAdvanced115 min
  11. 11Tensor and sequence parallelismWhen one layer is too large or slow for a GPU, split the matmul itself. We build Megatron tensor parallelism from block multiplication: column- and row-parallel layers, conjugate operators f and g, MLP and per-head attention with one all-reduce per sublayer, and vocabulary-parallel embeddings and cross-entropy. Sequence parallelism shards what remained replicated and DTensor offers general notation for reasoning about layouts. GPUAdvanced115 min
  12. 12Pipeline parallelism: stages, micro-batches and bubblesSplitting a model by layers only requires point-to-point communication but leaves GPUs waiting. Starting from naive model parallelism, we progress through GPipe and 1F1B to interleaved pipelines and zero-bubble schedules that split backward into two halves. We derive bubble and memory for each schedule, build a schedule simulator and implement a real multiprocess pipeline. GPUAdvanced110 min
  13. 13Context and expert parallelismTwo parallelism axes address two modern problems. For contexts of hundreds of thousands of tokens, a single sequence's activations do not fit: context parallelism shards tokens throughout layers and ring attention or Ulysses handles attention with communication. With MoEs containing hundreds of billions of parameters, each GPU hosts experts and tokens travel by all-to-all. We simulate both with exact equality and implement expert parallelism with processes. GPUAdvanced110 min
  14. 14Composing parallelisms: planning, checkpointing and surviving failuresReal training combines five parallelisms across thousands of GPUs and experiences failures every few hours. We compose DP, TP, PP, CP and EP over topology, choose configurations with rules and a cost model compared with published designs, and keep training alive using distributed reshardable checkpoints, checkpoint interval optimization, slow-node detection and deadlock debugging. GPUAdvanced115 min
  15. 15Frontier: training with little communicationNetworks between data centers or across the internet are orders of magnitude slower than NVLink. This lesson surveys research on training without synchronization at every step: Local SGD, DiLoCo and its streaming version, gradient compression with error feedback, DeMo and early decentralized LLM training. We implement methods on small problems and the course GPT, comparing token and communication budgets explicitly. GPUResearch105 min
  16. 16Text sampling: temperature, top-k, top-p and the truncation familyThe same model can produce repetitive, incoherent or brilliant text depending on next-token selection. We study the decoding loop and logit processors, temperature, top-k and top-p, adaptive truncation (min-p, typical and eta), repetition penalties and Gumbel-max. We implement these from scratch, vectorize batches with per-request parameters, and evaluate diversity and quality. GPUCore105 min
  17. 17Search and control in decoding: greedy, beam search, constraints and MBRTranslation or summarization can seek a high-probability sequence, while valid JSON or a function call must obey a grammar. We study greedy decoding and length-normalized beam search, the paradox of finding a better mode but worse quality, diverse and stochastic variants, constrained decoding compiled to automata over a tokenizer vocabulary, and minimum Bayes risk decoding. GPUCore105 min
  18. 18Anatomy of serving: latency, throughput, memory and cost per tokenAn LLM user perceives the first token and generation rate, while its operator pays GPU hours. We define serving metrics, build a roofline performance model for prefill and decoding latency and throughput, budget memory and concurrency, calculate cost per million tokens, and examine serving-engine components. The design considers an RTX 4060 budget; the minimal server measurements were made on an RTX 3060. GPUCore100 min
  19. 19The KV cache as a resource: paged attention, shared prefixes and compressionModule m18 introduced KV cache for decoding; here it is treated as a serving resource. We measure waste from reserving maximum length, build PagedAttention with physical blocks, tables and a paged kernel, share blocks with copy-on-write and prefix caching, and study recomputation, CPU swapping and token eviction when cache does not fit. Everything is implemented from scratch and on the local GPU. GPUAdvanced115 min
  20. 20Continuous batching and scheduling: chunked prefill, disaggregation and determinismIn a static batch a long request holds up the others. Iteration-level scheduling lets requests enter and leave each step and leads to a modern engine scheduler: unpadded ragged batches, free-block admission, preemption, chunked prefill, service-level policies, prefill/decode disaggregation and inference model parallelism. We finish with batch-dependent nondeterminism and how to avoid it. GPUAdvanced110 min
  21. 21Speculative decoding I: exact speculative samplingAt small batch sizes decoding can be memory-bound, and verifying k tokens may cost close to generating one. Speculative decoding uses this opportunity: a cheap draft proposes and the larger model verifies in one pass. We prove exact target-distribution sampling, derive expected speedup from total variation, examine draft sources and implement real models; the documented measurement uses an RTX 3060. GPUAdvanced110 min
  22. 22Speculative decoding II: trees, draft heads and multi-token predictionTree-based verification checks candidate paths in parallel. This lesson studies draft heads, EAGLE, Jacobi decoding and multi-token prediction, then trains simplified Medusa-style heads on the local GPU. GPUResearch110 min
  23. 23Quantization I: foundationsQuantization reduces weight storage and can accelerate memory-bound decoding. Build symmetric and affine quantizers, analyze rounding and clipping, calibrate ranges, compare granularities and simulate integer matrix multiplication. A local lab measures packed weights on an RTX 3060. GPUCore105 min
  24. 24Quantization II: post-training quantization of LLMsActivation outliers can make a shared quantization scale too coarse. Study LLM.int8(), SmoothQuant, GPTQ and AWQ, implement layer reconstruction and apply GPTQ to a small model on the local GPU. GPUAdvanced120 min
  25. 25Quantization III: few bits, rotations, QAT and kernelsCompare low-bit formats, use Hadamard rotations, train with simulated quantization, quantize a KV cache and optimizer states, and measure a teaching W4A16 Triton kernel on the local GPU. GPUAdvanced115 min
  26. 26Pruning and sparsityStudy pruning by magnitude and second-order saliency, the lottery ticket hypothesis, structured and 2:4 sparsity, Wanda and SparseGPT. Measure quality and latency on an RTX 3060 and examine layer removal and recovery. GPUAdvanced110 min
  27. 27Knowledge distillation I: temperature, dark knowledge and compact studentsTransfer a teacher's softened probabilities to a compact student. Derive the temperature loss and its high-temperature limit, study intermediate features and capacity gaps, and compare distillation with supervised baselines in NumPy and a local CNN experiment. GPUCore105 min
  28. 28Knowledge distillation II: language models, reverse KL and on-policy distillationStudy token- and sequence-level distillation, forward and reverse KL, student-generated prefixes and sparse teacher logits. A local SmolLM2 experiment compares four objectives on a small arithmetic task on an RTX 3060. GPUAdvanced115 min

Module capstone

From efficient training to your own inference engine in 8 GB

Carry out a two-part project with a small open LLM, such as one from the SmolLM2 or Qwen2.5 family. In part A, distill a small draft from the target model using BF16, selective checkpointing, gradient accumulation, and the fused Triton cross-entropy from this module. Use four Gloo processes on the CPU to demonstrate that a ZeRO-3 step with tensor parallelism reproduces the gradient of a single-GPU step. In part B, build an inference engine with a paged KV cache and prefix caching, continuous batching with chunked prefill, a full sampler with constrained decoding, speculative decoding using the distilled draft, and target weights quantized to W4A16 with your own GPTQ implementation and a Triton kernel. Deliver a reproducible report using realistic Poisson arrivals. Measure TTFT and TPOT at P50 and P99, throughput, goodput under an SLO, peak memory, draft acceptance, and quality through perplexity and a task with verifiable answers after each improvement. Compare with transformers.generate and with vLLM if available in WSL2.

Check what you already know

  • Estimate FLOPs, GPU-days, and memory by component from N, D, and the hardware, then calculate model FLOPs utilization
  • Explain the role of FP32 master weights in mixed precision and why FP16 typically needs loss scaling while BF16 does not
  • Quantize a tensor to FP8 E4M3 with per-tensor and block scaling and estimate the error
  • Prove the O(√n) bound for segmented checkpointing and normalize loss under gradient accumulation
  • Write a masked fused kernel in Triton and measure its effective bandwidth
  • Implement tiled matrix multiplication and cross-entropy that avoids materializing the logits in Triton
  • Write a Triton FlashAttention forward pass that skips blocks under a causal mask
  • Calculate the alpha-beta cost of a ring all-reduce and decompose it into reduce-scatter and all-gather
  • Implement DDP buckets that overlap all-reduce with the backward pass
  • Calculate memory per GPU and communication volume for ZeRO stages 1, 2, and 3
  • Partition an MLP and attention across GPUs following Megatron and identify where each collective is required
  • Derive the GPipe bubble and explain how interleaved 1F1B and zero-bubble schedules reduce it
  • Explain ring attention with logsumexp merging and all-to-all dispatch in expert parallelism
  • Choose DP, TP, PP, CP, and EP for a given model and cluster and justify the choice with a cost model
  • Implement batched, vectorized top-k, top-p, and min-p sampling and prove the Gumbel-max trick
  • Implement beam search with length normalization and explain the beam search curse
  • Calculate TTFT, TPOT, maximum concurrency, and cost per million tokens using a roofline model
  • Implement an allocator with block tables, copy-on-write, and prefix caching
  • Explain continuous batching and chunked prefill and their effect on queue latency
  • Prove that speculative sampling reproduces the large model's distribution exactly
  • Calculate the scale and zero point of affine quantization and the expected rounding error
  • Derive the GPTQ update from Optimal Brain Surgeon
  • Explain how a Hadamard rotation helps W4A4 quantization
  • Compare SparseGPT, Wanda, and 2:4 sparsity in accuracy and measured speedup
  • Derive the temperature-scaled distillation gradient and justify the T² factor
  • Choose between forward KL, reverse KL, and on-policy distillation for a generative student

References