torch.compile replaces that walk with generated kernels, and torch.distributed runs the same program in several processes that must call the same collectives in the same order.Fig. 1 follows one training step of the running example (below) from your loop down to the bytes, one station per layer; each layer has a child page, and each step links the child's own figure. This page is the map, the comparisons across the layers, and the one running example they all share.
torch.compile may stand in front of it; every operator call walks the dispatcher's keys; autograd records a graph beside them; a kernel does the arithmetic on a tensor's bytes; the same step runs on every rank; the profiler measures it along the front. Drawn: one station per layer, left to right along the path a call takes; cubes, cells and nodes stand for the counts in the steps, not one for one illustrative layout.model(x, y), loss.backward(), opt.step(): the step every lever edits, on 3,186,944 parameters (12.75 MB of float32 weights). Libraries that run the loop for you (Hugging Face Trainer and Accelerate, Lightning, torchtitan, DeepSpeed) make the same calls below, plus defaults that change the run. Owners: Making training fast, section 7 (the loop); Libraries on top of PyTorch, whose Fig. 1 gives eight duties of the loop to six libraries and Fig. 2 records one step call by call. Here: sections 4 and 9, the Ecosystem map.torch.mm through three machines and Fig. 3 walks one call down the keys in seven situations. Lab: Inside one step. Section 2.x of shape (3, 4) has strides (4, 1), and x.t() reads the same 12 cells with strides (1, 4), so a transpose or a slice copies nothing. Owner: Tensors, the dispatcher and autograd, whose Fig. 2 lays one storage under many headers. Section 1.torch.library.custom_op with a fake implementation is one opaque node to the compiler: a function calling tolist() gave 3 graphs and 2 breaks as plain Python, 1 graph and 0 breaks as a custom operator, with the same result measured. Owner: Extending PyTorch, whose Fig. 1 walks one call down the keys and its slots, Fig. 2 shows one forward as Dynamo recorded it and Fig. 3 one weight as a tensor subclass. Section 8.fused=True takes the optimizer from 5.64 to 2.08 ms measured on Apple M1 Pro (section 6). Owner: Making training fast, whose Fig. 1 splits a step's time and memory, Fig. 2 fixes one bottleneck at a time, Fig. 3 reads one MPS step's profiler trace and Fig. 4 follows memory through a step.The running example. A character-level GPT in plain PyTorch: 43 distinct characters as its vocabulary, 4 transformer blocks of width 256 with 4 attention heads, a context of 64 characters, 3,186,944 parameters, trained with AdamW on batches of 8 windows cut from the first three paragraphs of Alice's Adventures in Wonderland. Its first loss is 3.8014, just above ln 43 = 3.761 (a uniform guess), and after 300 steps it reaches 0.546 measured on Apple M1 Pro. Every tab of this page and every child page uses this model, these batches and this seed, which is why their numbers can be compared. Machine: an Apple M1 Pro laptop, its CPU (4 threads) and its GPU through Apple's MPS backend, PyTorch 2.14.1 (released 2026-09-30, PyPI). There is no NVIDIA GPU here: each page says what carries over to one, and published GPU numbers are labelled with who measured them.
You need: nothing beyond Python and the idea of a gradient; this topic starts from zero. The parallelism forms themselves (data, tensor, pipeline parallelism, ZeRO) are taught on Distributed Training; the GPU underneath on Topic: cuda-and-gpu-programming.
aten::addmm; ATen is PyTorch's C++ tensor library where every operator is defined.AutogradCPU, AutocastCPU, Python, CPU) that selects one kernel from an operator's table.Shard(d), Replicate(), Partial().| Layer | What it costs on the running example | The lever, measured | Owner |
|---|---|---|---|
| Python and dispatch, per call | 142 calls per forward, 295 in backward, 486 in the default optimizer step measured | torch.compile: 142 calls become 35 launches; the step on the CPU is no faster (23.20 ms compiled against 22.75 ms eager), on MPS 1.18 times faster, 1.85 times with a fused optimizer as well | torch.compile from the user's side |
| The optimizer step | A quarter of the CPU step: the default for-loop AdamW launches several small operations per parameter tensor | fused=True: the optimizer phase 2.7 times faster on the CPU and 4.1 times on MPS | Making training fast, section 5 |
| Saved activations | 34.76 MB after one forward, against 12.75 MB of weights | Checkpointing each block: 34.85 to 3.33 MB added by forward, for a step that went from 22.5 to 31.6 ms on the CPU | Mechanism: Tensors, the dispatcher and autograd, 3.6; the trade: Making training fast, section 9 |
| Autograd when no gradient is needed | One forward: 6.52 ms with gradients, 6.16 ms under no_grad and 6.12 ms under inference_mode on the CPU; 4.29, 2.41 and 2.40 ms on MPS | inference_mode for serving, no_grad for evaluation | Tensors, the dispatcher and autograd, 3.5 |
| Weights and optimizer state per process | On the 25.3M-parameter variant, 303 MB of weights and AdamW state on every DDP rank | FSDP2 on 4 ranks: the peak from 548 MB to 249 MB, for 14 collectives per step against DDP's 2 all-reduces | Distributed PyTorch, sections 3 and 4 |
| A library's defaults | The Hugging Face Trainer clips at 1.0, decays the learning rate and shuffles by default, so a ported loop no longer matches | Matched defaults: the same three losses, 3.80137, 3.18793, 3.16783, from a plain loop, Lightning, the Trainer and Accelerate | Libraries on top of PyTorch, sections 1 and 2 |
| Code PyTorch does not ship | A Python function in the middle of a model breaks the compiled graph; a backward registered too late silently drops gradients | A custom operator with a fake implementation is one graph node; register everything before anything traces | Extending PyTorch, sections 1 and 2 |
All measured on Apple M1 Pro, PyTorch 2.14.1, step times as medians of 5 trials of 20 steps: the calls, phases and checkpointing on the Inside one step tab, compiled steps on the Compile lab (section 8), memory per rank on the Distributed lab (section 6), the library losses on the Ecosystem map ("Same step, five doors"). What carries over to NVIDIA GPUs is the structure (calls, graphs, bytes, collectives); the times do not.
A tensor is two things: a storage, one flat block of bytes on one device, and a small header saying how to read it: a shape, one stride per dimension (how many elements to step in storage to move one along that dimension), an offset, a dtype (float32 at 4 bytes, bfloat16 at 2) and a device (cpu, mps, cuda).
So a transpose, a slice or a reshape that keeps the element order writes a new header over the same storage, a view, and copies nothing. A tensor is contiguous when its elements, read in order, sit one after another in storage; kernels that need that copy first. Whether a copy happens depends on the device: in the running example, attention's .transpose(1, 2).contiguous() moves 0 bytes on the CPU, whose attention kernel already writes in the needed order, and 524,288 bytes per layer on MPS measured on Apple M1 Pro (Inside one step, section 1).
The bytes every other section counts. The model's 3,186,944 parameters in float32 take 12,747,776 bytes (12.75 MB) 3,186,944 × 4; AdamW keeps two more tensors of the same size (25.5 MB) and the gradients another 12.75 MB. Moving data between devices is explicit (.to("mps")), and on a GPU a stray .item() or .cpu() makes the CPU wait for the GPU (section 6).
.contiguous() stepped, memory formats, dtypes and promotion, pinned memory), its Fig. 2 (one storage under many headers) and its Stride explorer tab.For every operator PyTorch keeps a table of kernels indexed by dispatch key. Each tensor carries a set of keys; the dispatcher takes the union over a call's inputs, removes the keys switched off for the current thread, and runs the kernel of the highest-priority key left. That kernel does its job (autocast casts, autograd records a node) and calls the operator again with its own key masked out, until a backend kernel does the arithmetic. Keys with nothing to do are fallthrough and skipped. On MPS the keys are MPS, AutogradMPS and AutocastMPS; on a CUDA tensor CUDA, AutogradCUDA and AutocastCUDA.
Two switches show the mechanism. torch.no_grad() leaves the autograd key in place and tells its kernel to record nothing; torch.inference_mode() removes the key, so that layer is skipped outright (the timings are in the comparison above). Autocast works the other way round: every tensor always carries an Autocast key, every thread starts with it excluded, and entering torch.autocast lifts the exclusion, turning casting on for every operator without touching a tensor (c10/core/DispatchKeySet.h L670 to L686, v2.14.1).
TorchDispatchMode recorders like the one that counted 923 calls in Inside one step, and tensor subclasses such as DTensor (section 7) and torchao's quantized tensors (section 8). Every call pays a few microseconds of Python and dispatch before any arithmetic, nothing for a large matrix multiply and a lot for the small element-wise operations of a transformer: one of the two things torch.compile removes (section 5).Autograd applies the chain rule automatically. During forward, the autograd kernel of each operator (section 2) adds a node to a graph (MmBackward0 for a matrix multiply) and keeps the forward tensors its gradient formula needs, the saved tensors. loss.backward() walks the graph from the loss to the parameters; AccumulateGrad nodes add into each parameter's .grad, and each node's saved tensors are freed once it has run.
The fact the rest of the topic builds on: what fills memory in training is the saved tensors, and they grow with batch size and sequence length while the weights do not. One forward of the running example builds 187 nodes (135 operators plus 52 AccumulateGrad, one per parameter tensor) and keeps 34.76 MB, against 12.75 MB of parameters measured on Apple M1 Pro. Activation checkpointing (torch.utils.checkpoint.checkpoint(fn, x, use_reentrant=False)) trades that memory for compute by keeping only a region's input and re-running the region in backward; per block, backward recomputed 112 calls, not a whole forward, because the non-reentrant variant stops once it has rebuilt what backward asked for. Pass use_reentrant=False: at 2.14.1 leaving it out still runs the older reentrant variant (checkpoint.py L635 to L647).
A gradient autograd cannot derive goes in a torch.autograd.Function with its own forward and backward, checked with torch.autograd.gradcheck in float64; an operator that must also work under torch.compile is better a torch.library.custom_op with register_autograd (section 8).
autograd.Function, turning gradients off, saved-tensor hooks and both checkpoint variants); checkpointing as a speed and memory lever is section 9 of Making training fast; the whole step's graph, memory timeline and checkpointing are on Inside one step, sections 3 to 5.An nn.Module registers its parameters (tensors autograd treats as leaves), its buffers (saved, not trained) and its sub-modules, so model.parameters() finds every weight; the state_dict is the name-to-tensor dictionary you save and load. The running example ties its output layer to its input embedding, so model.parameters() yields 52 tensors while the state_dict has 53 entries, two names for one storage measured here; tools that walk names see the weight twice (torch.export listed 53 parameter inputs on the Compile lab). An optimizer holds the parameters and its own state (AdamW: two tensors per parameter); it comes as a for-loop, a foreach (each operation over all tensors at once) or a fused (one kernel) implementation, and at 2.14.1 the CPU and MPS default to the for-loop (_foreach_utils.py L8 to L23).
The step every later section edits, written once:
Three lines carry most of the surprises, and each has an owner. Autocast runs matrix multiplies in bfloat16 and keeps softmax, losses and norms in float32, with per-device lists; float16 also needs torch.amp.GradScaler, because its narrow range lets small gradients underflow to zero, while bfloat16 has float32's range; and fewer bits only pay on hardware built for them (Making training fast, section 6; formats on Quantization and Precision). Accumulation divides by the number of micro-batches, which is exact only when every micro-batch counts the same number of tokens (Libraries on top of PyTorch, section 3), and under DDP all but the last micro-batch belong in model.no_sync() (section 7). Seeding by step number is what lets every page of this topic, and four libraries, reproduce the same losses.
torch.autocast is the Autocast key of section 2: it casts the inputs of chosen operators (matrix multiplies, attention) to bfloat16 and leaves precision-sensitive ones (softmax, losses, norms) in float32. The weights and the optimizer stay in float32. With float16 instead of bfloat16 you also need torch.amp.GradScaler, because float16's narrow range lets small gradients underflow to zero; bfloat16 has float32's range and needs no scaler. The lists are per device: on the CPU the running example kept layer norms, adds, log_softmax and the loss in float32, while on MPS log_softmax ran in bfloat16 (Tensors, the dispatcher and autograd, section 2.4). And fewer bits only pay on hardware built for them: on this laptop a bfloat16 autocast step of a larger variant (8 blocks, dmodel 512, 25.4 million parameters) was slower than float32 on MPS (208.0 against 143.0 ms) and over 100 times slower on the CPU, which has no bfloat16 arithmetic (43.7 s against 0.37 s) measured on Apple M1 Pro (Making training fast, section 6).torch.manual_seed), make the data order a function of the step, and turn on torch.use_deterministic_algorithms(True) when you need bit-identical reruns (some GPU kernels are non-deterministic by default). The running example's batches are seeded by step number, which is what let the Ecosystem map tab show the same three losses, 3.80137, 3.18793, 3.16783, from a plain loop, Lightning 2.6.6, the Hugging Face Trainer 5.19.0 and Accelerate 1.15.0 measured on Apple M1 Pro, CPU.max_grad_norm=1.0, uses learning rate 5e-5 with a linear decay schedule, weight decay 0, adamw_torch_fused and seed 42, and shuffles the data; Lightning 2.6.6 does not clip and trains in 32-bit by default read from the installed libraries, Apple M1 Pro. Porting a loop to a framework changes the run unless you set these.Accumulating 4 micro-batches without dividing the loss by 4 gives a gradient 4 times larger than one batch 4 times as large, because the mean loss of a big batch is the average of the four micro-batch means, and backward() sums. (That holds when every micro-batch has the same number of counted tokens. With padding or packed sequences of different lengths it does not: averaging the micro-batch means gave a 59.1% relative gradient error in a measured case, and of the Trainer, Accelerate and Lightning only the Trainer corrected it, and only for a model whose forward accepts **kwargs; Libraries on top of PyTorch, section 3.) AdamW nearly hides the error (it divides by a running scale of the gradient), but gradient clipping, SGD and anything that logs gradient norms do not. Divide the loss, or compare gradient norms against a one-batch run.
Counts measured on Apple M1 Pro, CPU, torch 2.14.1: 142 ATen calls in one eager forward (Inside one step); 1 graph of 59 operations, 0 breaks, 549 guards, and 35 launches per compiled forward, of which 14 are generated C++ kernels, 17 matrix multiplies in the BLAS library and 4 attention calls; on MPS 191 calls became 62, and the backward went from 295 calls to 60 launches on the CPU (Compile lab). Compile time 9.0 to 10.0 s with an empty cache.
Eager PyTorch runs one operator at a time: each pays Python and dispatch overhead, and each reads its inputs from memory and writes its output back, so a chain of small element-wise operations moves the same activation through memory again and again. torch.compile(model) does nothing until the first call; then three stages run:
Reads the function's bytecode as it runs (PEP 523) into an FX graph, with the assumptions it relied on as guards. Python it cannot trace is a graph break: that part runs eagerly between graphs.
Traces through autograd ahead of time into a forward and a backward graph, and decides which values backward keeps and which it recomputes.
Fuses element-wise chains and reductions into single loops: Triton on NVIDIA and AMD GPUs, C++ with OpenMP on CPUs, Metal on Apple GPUs. Matrix multiplies usually stay library calls.
Fig. 2 runs one forward of the running example down the stack, eagerly or compiled (switch above the figure); predict first what autograd sees of a compiled forward.
logits, loss = model(x, y) with x a batch of 8 windows of 64 character ids. Nothing is compiled: PyTorch runs the Python as written.model(x, y), after model = torch.compile(model). The model code did not change.CompiledFunctionBackward node; backward runs the precompiled backward graph, 60 launches instead of 295 calls.Fewer launches is not a faster step everywhere. On this CPU the compiled step took 23.20 ms against 22.75 ms eager: most of a CPU step is matrix multiplies, which stay BLAS calls, and a CPU's caches absorb much of the element-wise traffic. On the Apple GPU it was 1.18 times faster. On NVIDIA GPUs, where launches and memory traffic dominate small operations, the PyTorch team reported compile working on 93% of 163 open-source models and training 43% faster on average on an A100 vendor, PyTorch team, 2023 (PyTorch 2.x). What it costs: compile time, recompiles when a guard fails (a new input shape, eval() under no_grad), and graph breaks that leave code eager. torch.export is the whole-graph sibling: one graph or an error, then AOTInductor packages it into a library that runs without Python.
On the CPU the compiled step was about the same: 23.20 ms compiled against 22.75 ms eager. On the CPU most of the step is matrix multiplies, which stay BLAS calls either way, and a CPU's large caches already absorb much of the element-wise traffic. On MPS, a GPU, the same compile gives 1.18 times; with the fused optimizer as well, 1.85 times.
What it costs. Compile time: the first call of the compiled training step took 9.0 to 10.0 s with an empty cache and 0.86 to 1.04 s with a warm one, and every new input shape compiled again for 7.2 to 8.6 s until Dynamo marked the dimension dynamic measured on Apple M1 Pro. Memory: none saved here, AOTAutograd kept 34.81 MB against eager's 34.76 MB. Fragility: a print inside a block split the model into pieces, left the outer forward uncompiled and made the step 7 to 9% slower; switching to model.eval() under no_grad recompiled because a guard checks the grad mode. After recompile_limit (8 at 2.14.1) recompilations of one function, Dynamo gives up and runs it eagerly.
When it matters. On NVIDIA GPUs, where launches and memory traffic dominate small operations: the PyTorch team reported compile working on 93% of 163 open-source models and training 43% faster on average on an A100 (21% in float32, 51% with AMP) vendor, PyTorch team, 2023 (PyTorch 2.x). What transfers from this laptop is everything structural: the graph, guards, breaks, recompiles and the fused kernels' logic. What does not is the speed-up, and mode="reduce-overhead", which records CUDA graphs and does nothing here (CUDA only per its 2.14.1 docstring).
How to check. TORCH_LOGS="graph_breaks,recompiles" first; torch._dynamo.explain(fn)(*args) counts graphs and breaks; fullgraph=True turns the first break into an error; TORCH_LOGS=output_code prints what Inductor wrote; backend="aot_eager" runs Dynamo and AOTAutograd without Inductor, to tell which stage broke numerics.
torch.export and AOTInductor. torch.export is the whole-graph sibling of torch.compile: it must capture one graph with no breaks (an untraceable spot is an error, not a fallback) and produces a portable program for deployment. AOTInductor compiles that program ahead of time into a shared library that runs without Python. The running example's logits path, exported with a dynamic batch dimension, gave 95 operations (329 core ATen operations after decomposition; one of the 95 reads the symbolic batch size, and with static shapes the same export gives 94 and 326, torch.compile from the user's side, section 11) and packaged into a 14.3 MB .pt2 file whose outputs matched eager within 1.3e-6 measured on Apple M1 Pro. ExecuTorch (on-device) and the ONNX exporter build on torch.export; formats are on Local and on-device inference, section 3.
measured on Apple M1 Pro, CPU, 4 threads, PyTorch 2.14.1, medians of 5 trials of 20 steps after 5 warm-up steps; load average 10 to 17 from other jobs (Inside one step, section 7). The "after" optimizer bar is the fused AdamW measured on its own; the step with it was measured separately at 19.08 ms by the Compile lab (load average 2.7 to 6.6), against 19.19 ms forward + backward + fused optimizer. The lesson: count launches as well as FLOPs; on a GPU the same pattern is hundreds of tiny kernels with the GPU idle between them.
Most slow training jobs are slow for one reason. Split the step into its phases (forward, backward, optimizer), time each honestly (warm up, repeat, take medians, and on a GPU synchronise before reading the clock, because GPU work runs asynchronously), and fix the largest one you can. On the running example the answer is not the one anyone guesses:
fused=True. The fused AdamW does the whole update in one kernel: 5.64 ms becomes 2.08 ms (2.7 times faster; foreach, 5.78 ms, does not help on the CPU). Predicted step: 19.19 ms.The symptom decides the tool, and the tools span several pages:
| Symptom | Tool | Usual fix | Owner |
|---|---|---|---|
| Out of memory | Memory snapshot: torch.cuda.memory._record_memory_history(), run, _dump_snapshot("s.pickle"), open in memory_viz | Checkpointing, a smaller micro-batch with accumulation, sharding, a fused loss | Making training fast, 8 to 10; sharding: Distributed PyTorch, 4 |
| Slow, cause unknown | torch.profiler, trace opened in Perfetto | Read the trace: which phase, which kernels, where the GPU idles | Making training fast, 2 and 3 |
| GPU idle between kernels | Profiler: gaps on the GPU timeline, CPU busy launching | torch.compile, CUDA graphs (mode="reduce-overhead"), fused optimizer | torch.compile, 7; Streams, CUDA graphs and multi-GPU |
| CPU waits for the GPU every step | Profiler: synchronisations or device-to-host copies | Remove .item(), .cpu(), printing the loss every step | Making training fast, 1 |
| Attention slow or memory-hungry | Which SDPA backend ran | Keep inputs eligible for a fused backend, or FlexAttention | Making training fast, 11 |
| Data loading | Profiler: gaps before forward | num_workers, pin_memory=True, pre-tokenised data | Making training fast, 4 |
| Hang across ranks | Flight recorder | Find the rank that called a different collective | Distributed PyTorch, 11 |
Behind the attention row: F.scaled_dot_product_attention is one function with several backends (flash, memory-efficient, cuDNN, math) chosen by the inputs, and FlexAttention compiles your own score or mask function into one fused kernel; on this laptop's GPU the math path always ran, and FlexAttention's sparse-pattern speed-ups did not reproduce. Lower precision for weights and training (int8, float8, MX) is torchao, which works by swapping weights for tensor subclasses (section 8); the largest single activation of a big-vocabulary model, the logits, is what fused linear cross-entropy avoids storing.
Nobody would guess that the optimizer, a few element-wise updates, costs a quarter of the step. It does because the default for-loop AdamW launches several small operations for each of 52 parameter tensors: 486 operator calls per step against 142 for the whole forward measured. On a GPU the same pattern shows up as hundreds of tiny kernels with the GPU idle between them, which is why foreach became the default there. The general lesson: count launches as well as FLOPs.
Attention backends. F.scaled_dot_product_attention (SDPA) is one function with several implementations behind it; at 2.14.1 the SDPBackend enum lists FLASH_ATTENTION, EFFICIENT_ATTENTION, CUDNN_ATTENTION, MATH and OVERRIDEABLE read from the installed wheel. It picks the first one whose constraints the inputs meet (dtype, head size, mask, device). The fused backends never write the full sequence-by-sequence score matrix to memory, the idea of FlashAttention; the MATH backend does, and always works. On this laptop the CPU ran a flash-style CPU kernel, while MPS always takes the math path at 2.14.1, whatever the shapes measured. Force or debug the choice with torch.nn.attention.sdpa_kernel([SDPBackend.FLASH_ATTENTION]): if the inputs do not qualify, the call fails ("No viable backend for scaled_dot_product_attention was found" on the CPU at 2.14.1, measured; on CUDA a warning also names the reason), instead of silently falling back to a slower backend. On MPS sdpa_kernel has no effect: the math path runs whatever you ask for (Making training fast, section 11).
FlexAttention (torch.nn.attention.flex_attention) covers the variants the fixed backends do not: you write a score_mod (change a score: relative bias, soft-capping) or a mask_mod (which query may see which key: sliding windows, documents packed into one sequence) as small Python functions, and torch.compile generates one fused kernel that skips fully masked blocks. Its authors measured 90% of FlashAttention-2's speed in forward and 85% in backward vendor, PyTorch team, 2024 (FlexAttention blog); it runs on Apple GPUs since 2.13 (2.13 release notes), but for inference only: at 2.14.1 FlexAttention has no backward on the CPU or MPS, and compiled FlexAttention on the CPU needs AVX2 and refuses macOS. On this laptop's GPU (float32, 4,096 positions, inference) it was slower than SDPA with a dense mask for every mask except a sliding window (16.9 against 17.4 ms), and causal masking took 148 ms against 7.7 ms for SDPA with is_causal measured on Apple M1 Pro; the 2.13 notes' "up to about 12x over SDPA on sparse patterns" did not reproduce (Making training fast, section 11).
torchao is PyTorch's library for lower precision: quantized weights for inference, float8 and MX formats for training, sparsity. It works by replacing weights with tensor subclasses (section 8). Applied to the running example on the CPU, Int8WeightOnlyConfig turned each of 17 linear weights into an Int8Tensor (int8 data plus one float32 scale per row) and moved the first loss from 3.80137 to 3.8009 measured on Apple M1 Pro (Ecosystem map). On GPUs, its float8 training gave up to 1.5 times the throughput at 512 GPUs on a 405B model vendor, torchao README (torchao). For the largest single activation of a big-vocabulary LLM, the logits, 2.13 added nn.LinearCrossEntropyLoss, which fuses the output layer into the loss so the batch × sequence × vocabulary tensor is never stored ("up to 4x lower peak memory", release-note figure, 2.13 notes). It saves memory only when asked: at 2.14.1 the default (options=None) runs the reference, unchunked path, and chunking needs options=LinearCrossEntropyOptions(). On that page's larger variant (8 blocks, dmodel 512) with a 50,257-token vocabulary, the step's peak was 2394.2 MB unfused and the same with the default call, 1278.8 MB chunked, for a slower step (827 to 1398 ms on the CPU) measured on Apple M1 Pro (Making training fast, section 10).
Distributed PyTorch runs one copy of your script per device. torchrun --nproc_per_node 8 train.py starts 8 processes, each with a rank (0 to 7) and the world size (8); torch.distributed.init_process_group connects them through c10d, using NCCL between NVIDIA GPUs or gloo on CPUs. They cooperate only through collectives: all-reduce (everyone ends with the sum), all-gather (everyone ends with everyone's pieces), reduce-scatter (sum, then each keeps one piece), broadcast. The rule that explains every hang: all ranks must call the same collectives, with the same shapes, in the same order. Why each scheme saves memory, and what it sends at scale, is Distributed Training; what follows is what PyTorch's APIs do, recorded by the flight recorder on 2 and 4 CPU processes measured on Apple M1 Pro, CPU, gloo (Distributed lab).
DDP keeps a full copy of the model on every rank and averages gradients with all-reduces during backward, grouped into buckets so communication overlaps the rest of backward. FSDP2 (fully_shard) splits every parameter across ranks, gathers a block's full weights just before using it, frees them after, and reduce-scatters gradients so each rank keeps only its part.
Distributed PyTorch draws both on the running example: its Fig. 1 shows what each rank holds under DDP, FSDP2, tensor and pipeline parallelism, Fig. 2 steps DDP's buckets through one recorded backward and Fig. 3 one FSDP2 step on 4 ranks. Recorded here, rank 0's flight-recorder entries for the second step (step 1) at world size 2 measured on Apple M1 Pro, CPU, gloo: DDP's step 1 all-reduces 1,051,648 B, then 11,696,128 B (its first step uses one bucket; Distributed PyTorch, section 3, steps both); FSDP2 makes 14 collectives. Both give the same losses, 3.80137, 3.09551, 3.16247.
Peak memory per rank = weights + AdamW state + DDP's gradient buckets + the step's peak of activations and temporaries measured on Apple M1 Pro, CPU (Distributed lab, section 6). On the tiny model activations dominate, so sharding saves less than the ratio of ranks; on the 25.3M-parameter variant, with 303 MB of weights and AdamW state per DDP rank, FSDP2 on 4 ranks cuts the peak from 548 MB to 249 MB.
One vocabulary for every split. A DeviceMesh arranges ranks as a grid; a DTensor is a tensor plus a mesh plus one placement per mesh dimension, and changing placement is a collective. That is why DDP, FSDP2 and tensor parallelism read as one table:
| From | To | Collective | Where you meet it |
|---|---|---|---|
| Shard(0) | Replicate() | all-gather | FSDP2 gathering a block's weights |
| Partial() | Replicate() | all-reduce | DDP gradients; the output of a row-parallel matrix multiply |
| Partial() | Shard(0) | reduce-scatter | FSDP2 gradients |
| Replicate() | Shard(0) | none (each rank keeps its slice) | Sharding a loaded model |
Each row run with redistribute on 2 and 4 CPU ranks measured on Apple M1 Pro (Distributed lab, section 7, has every pair). Gloo has no native reduce-scatter: it all-reduces and keeps a chunk, so CPU byte counts overstate that one collective.
The other forms are placements or stages on the same mesh: tensor parallelism splits the matrices inside a layer (one all-reduce per MLP in forward and one in backward), pipeline parallelism gives each rank different layers and streams micro-batches, context parallelism splits the sequence inside attention, and DCP has every rank write its own shards so a checkpoint saved on 4 ranks loads on 2 or 1. A hang is a rank in a different collective: the flight recorder shows which, and the default timeouts (10 minutes for NCCL, 30 for other backends) make it look like a silent job first. What carries over to NVIDIA GPUs: which collectives run, their order and sizes, sharding and memory per rank, the hang diagnostics; what does not: speed (gloo over local sockets is nothing like NCCL over NVLink).
Three things the measurements add to the textbook picture. DDP's first step puts every gradient in a single bucket and only then rebuilds buckets in the order gradients actually arrived (from step 1: 1,051,648 B, then 11,696,128 B), because the default 25 MiB cap applies only after that first pass (torch/nn/parallel/distributed.py at v2.14.1; Distributed lab, section 3). Tuning bucket_cap_mb after watching one step tells you nothing about the first. FSDP2 makes 14 collectives per step against DDP's 2 all-reduces, trading many smaller messages for memory. And on the tiny model, activations dominate, so sharding the weights saves less than the ratio of ranks suggests: the step's own peak is 43.9 MB on 2 and on 4 FSDP2 ranks, and only the persistent part shrinks; on the bigger variant, where weights and AdamW state are 303 MB per DDP rank, FSDP2 on 4 ranks cuts the peak from 548 MB to 249 MB.
| From | To | Collective | Where you meet it |
|---|---|---|---|
| Shard(0) | Shard(1) | all-gather, then a local slice at 2.14.1 | Changing layouts between layers |
Each row was run with redistribute on 2 and 4 CPU ranks measured on Apple M1 Pro (Distributed lab, section 7, which lets you pick any mesh and placement). Replicate to Partial is refused at 2.14.1 ("only Shard to Partial(sum) redistribution is supported"); an uneven Shard(0) of 6 rows over 4 ranks gives 2, 2, 2 and 0 rows. Gloo has no native reduce-scatter: it all-reduces the whole tensor and keeps a chunk (ProcessGroupGloo.cpp), so byte counts from CPU runs overstate that one collective; NCCL has a real one.
Tensor and context parallelism are placements too; pipelining instead gives each rank different layers. Tensor parallelism (TP) splits the weight matrices inside a layer: ColwiseParallel on the MLP's first matrix and RowwiseParallel on the second leave one all-reduce per MLP in forward and one in backward (8 all-reduces of 524,288 B per step for the running example on 2 ranks, loss equal to one process). Applied blindly to the fused qkv matrix, ColwiseParallel gave rank 0 all of q and half of k, and the forward failed: fused layers need a custom split. Pipeline parallelism (torch.distributed.pipelining) puts different layers on different ranks and streams micro-batches through them; with 2 stages and 4 micro-batches the 1F1B schedule peaked at 16.8 and 12.4 MB per rank against GPipe's 21.1 and 21.1 MB, and the tied embedding, now on two stages, needed a manual all-reduce of its gradient. Context parallelism (2.7) splits the sequence inside attention for long contexts; it was not run here. torchtitan composes all of them on one mesh.
Checkpoints. Distributed checkpointing (DCP, torch.distributed.checkpoint) has every rank write its own shards plus one metadata file, and can load into a different number of ranks: saved from 4 FSDP2 ranks (a 144,161-byte .metadata and four files of about 9.8 MB), it loaded into 2 ranks and into a single process with a largest parameter difference of 6.9e-6 against a one-process run of the same steps.
A rank that skips one all-reduce leaves the others waiting. With a 10-second timeout, both ranks failed with "Timed out waiting 10000ms for recv operation to complete", and the flight recorder showed why: at sequence number 4, rank 0 was in all_reduce while rank 1 was in barrier. The default timeouts are 10 minutes for NCCL and 30 minutes for other backends (init_process_group docstring at 2.14.1), so in production a hang looks like a silent job for ten minutes. A shape mismatch was caught at once with TORCH_DISTRIBUTED_DEBUG=DETAIL ("Detected mismatch between collectives on ranks ... Tensor shapes: 1000vs 999"), at the price of 2 extra all-gathers per collective, and monitored_barrier names the missing rank ("Rank 1 failed to pass monitoredBarrier in 5000 ms") measured, CPU, gloo (Distributed lab, section 11, has each case with its error text and flight-recorder entries).
torchrun hangs at start-up unless MASTER_ADDR=127.0.0.1, and fully_shard without an explicit CPU mesh fails because it picks the MPS accelerator.Everything PyTorch does not ship (your kernel, a quantized weight format, a call into another library) plugs into one slot of the path a call takes (section 2), and the choice decides whether autograd, torch.compile and torch.export keep working. From lightest to heaviest: plain PyTorch code; a torch.autograd.Function to change a backward; a torch.library.custom_op, a new operator that the compiler treats as one opaque node once you tell it the output's shape (register_fake) and gradient (register_autograd); triton_op for a Triton or Helion kernel Inductor can see into; a tensor subclass with __torch_dispatch__ to change what a tensor is (DTensor, torchao's int8 and float8 weights); a TorchDispatchMode to watch every call in a region (the recorder behind Inside one step); a new backend key for a whole device.
Two measured traps show why the order matters: registering a C++ operator's backward after it had already been traced left 16 of the running example's 52 parameters with no gradient under torch.compile, with no error, and the wrong compiled result then sat in the AOTAutograd cache for the next process measured on Apple M1 Pro. Register everything before anything traces.
| Hook | What it changes | Use it for | Under compile and export |
|---|---|---|---|
| Plain PyTorch code | Nothing; composes existing operators | Most new layers | Traced like any code |
torch.autograd.Function | The backward of a piece of code | A custom or more stable gradient | Traced if forward and backward are traceable |
torch.library.custom_op | Adds a new operator to the dispatcher, opaque to the compiler; register_fake says what shape it returns, register_autograd its backward | Code the compiler cannot or should not trace: C++ or CUDA kernels, calls into other libraries | One node in the graph, no break |
torch.library.triton_op with wrap_triton | A Triton kernel registered as an operator | Your own GPU kernels (Triton, or Helion, which compiles to Triton) | Visible to Inductor, which can optimise around it |
Tensor subclass with __torch_dispatch__ | What a tensor is: every operator on it goes through your Python code at the Python key | New representations: DTensor (sharded), torchao's int8 and float8 weights, NF4 | Supported for subclasses written to the traceable-subclass protocol |
TorchDispatchMode | Sees every operator call while active | Recorders, debuggers, counting FLOPs (the Inside one step recorder is one) | Eager tool |
A new backend key (PrivateUse1) | A whole device | Hardware vendors | Through the vendor's compiler backend |
The fake implementation is the key idea: the compiler and torch.export need to know the output's shape, dtype and device without running your code, so you tell them. The Compile lab shows what the same kind of break costs inside the running example (the outer forward left uncompiled, 7 to 9% slower).
Tensor subclasses in practice. torchao's int8 weight-only quantization (section 6) replaced each linear weight of the running example with an Int8Tensor, a subclass of torch.Tensor that defines __torch_dispatch__ and holds an int8 qdata of the original shape plus a float32 scale per row measured on Apple M1 Pro. The model code did not change: the linear layers call F.linear as before, the dispatcher reaches the Python key, and the subclass decides how to multiply. DTensor (section 7) is a tensor subclass too, which is why FSDP2 can shard a model without rewriting it; at 2.14.1, though, its constructor and its common operator path run in C++ for speed, and its Python __torch_dispatch__ only serves subclasses of DTensor (Extending PyTorch, section 5).
Writing kernels. When a fused kernel is the fix, the order of preference is usually: let Inductor generate it (section 5); write it in Helion, a kernel language hosted by the PyTorch Foundation that compiles to Triton by default (1.4.0 also has Pallas, CuTe and Metal backends; the Metal one ran on this laptop's GPU, Extending PyTorch, section 4) and autotunes the tiling (1.0 released 2026-04-03, PyPI; helionlang.com); write Triton by hand; write CUDA. Register whichever you write as an operator (triton_op or custom_op) so the rest of PyTorch can use it.
Every library above PyTorch answers one question differently: how much of the training loop do you want to own? They call the same core pieces (FSDP2, DTensor, torch.compile, SDPA), so the choice is about defaults, recipes and how much code you read when something breaks; which one for which job is Libraries on top of PyTorch, section 10. This page keeps what is alive: statuses read from each project's own repository or release page on 2026-10-12, and the Ecosystem map with 42 entries, their sources, licences and what each calls in core.
| You want | Reach for | Status | In one line |
|---|---|---|---|
| Pretraining at scale, PyTorch-native, full control | torchtitan 0.3.0 | active | PyTorch's reference: FSDP2, TP, PP, CP, EP on one DeviceMesh, compile, float8, DCP; a codebase to fork, not a framework to configure. It assumes a GPU: on a Mac CPU it ran only after four small patches |
| Hugging Face models with your own loop | Accelerate 1.15.0 | active | DDP, FSDP2 and DeepSpeed behind one object |
| Standard fine-tuning (SFT, DPO, GRPO) with little code | TRL 1.15.0, PEFT 0.21.2, or Axolotl 0.20.0 (YAML) | active | Breadth of recipes and day-one model support, for defaults you did not choose |
| Structured research code, not only LLMs | Lightning 2.6.6 (or Fabric to keep your loop) | active | Callbacks, logging, checkpointing; new LLM parallelism lands here later |
| Largest-scale NVIDIA training | Megatron Core 0.19.2; DeepSpeed 0.19.7 | active | Megatron: GPU-optimised TP/PP/CP/EP; DeepSpeed: ZeRO and offload, a PyTorch Foundation project since May 2025 |
| Running on phones and laptops | ExecuTorch 1.5.1 | active | Built on torch.export; "part of PyTorch Core" since April 2026 |
| Fine-tuning recipes from PyTorch | torchtune 0.6.1 | no longer maintained | Active development stopped 2025-07-15 (issue 2883); do not start on it |
| RL post-training from PyTorch | torchforge | paused | README: development paused, "LLM training at PyTorch is being consolidated in torchtitan" |
| Serving PyTorch models | TorchServe | archived | For LLMs use vLLM or SGLang (Topic: inference-and-serving) |
| Composer, Colossal-AI, torchaudio, NeMo (LLM side) | quiet or maintenance | Composer's last release 2025-07-26; torchaudio is in a maintenance phase (its README says 2.11 works with every future torch); the NeMo repository is now speech only |
Versions and dates: PyPI, read 2026-10-12, as recorded by the Ecosystem map tab. The catches found by running them (Accelerate silently returning DDP on a CPU, Axolotl's pins, Lightning's FSDPStrategy being FSDP1, DeepSpeed clipping at 1.0 by default since 0.19.3) are on Libraries on top of PyTorch, sections 4 to 9.
Inside core, what was replaced. FSDP2's fully_shard (2.4) replaces the FullyShardedDataParallel wrapper, which still ships at 2.14 with no formal deprecation notice; torch.compile and torch.export replace TorchScript, whose torch.jit now raises a FutureWarning (2.14); torchao replaces torch.ao.quantization (deprecated 2.8, its PT2E flow moved out in 2.11); torch.distributed.pipelining replaced torch.distributed.pipeline; torch.load defaults to weights_only=True since 2.6 (release notes).
Who governs what. The PyTorch Foundation now hosts PyTorch, vLLM and DeepSpeed (May 2025), Ray (October 2025), Helion and Safetensors (April 2026) (Foundation year in review, PyTorch Conference Europe 2026). Meta-owned satellites (torchtune, torchforge, monarch) live in the separate meta-pytorch GitHub organisation, while torchtitan stays under pytorch. Hugging Face, home of transformers, Accelerate, PEFT, TRL and the model Hub, signed a definitive agreement on 2026-09-02 to be acquired by NVIDIA for about $11.9 billion to its stockholders plus up to about $1.0 billion of retention equity, expected to close in the first half of 2027 subject to regulatory approval (NVIDIA Form 8-K); NVIDIA's announcement the next day said the Hub "will remain an open platform for the entire AI ecosystem" (Semafor). Until it closes, Hugging Face is independent.
Each child owns one layer in depth on the same running example; read them in this order, or jump to the layer you need.
Neighbours: the parallelism forms are Distributed Training; codegen below Inductor is The compiler stack; CUDA graphs are Streams, CUDA graphs and multi-GPU; kernel writing is Triton and Gluon and Writing kernels; optimizer algorithms are Optimisers. Not made into children: export and deployment (it would split torch.export from the compile child), debugging hangs (one section of the distributed child), a release history (the Ecosystem map carries it).
time.perf_counter() around it measures the launch. Synchronise before reading the clock, warm up, repeat, report medians (or use torch.utils.benchmark.Timer)..item() or printing the loss every steptorch.compile it is a graph break (section 5). Log every N steps, or keep a running tensor and read it rarely.no_grad to save memory while trainingreshape never copies, or that view always worksview fails on non-contiguous tensors; reshape silently copies (section 1). In-place writes through a view change the original.no_sync under DDPtorch.compile to speed up anythingeval() versus train(), Python scalars that change).torch.amp.GradScaler.if rank == 0: all_reduce(...), uneven data, or a different tensor shape on one rank hangs the job until the timeout (section 7).fully_shard is where the work goes (section 9).weights_only=Falseweights_only=True (since 2.6) or use safetensors.x.t().view(-1) fail, and what does reshape do instead?reshape returns a view when possible and otherwise copies.torch.mm(a, b) and the BLAS call?MmBackward0 and saves inputs, a subclass's __torch_dispatch__ may run at the Python key, and the backend kernel finally calls BLAS.no_grad or inference_mode?inference_mode also drops the autograd keys and version counters from new tensors, so it is a little faster, but those tensors cannot later be used in autograd. Use it for serving; no_grad for evaluation inside training code.recompile_limit, 8). A graph break is Python Dynamo cannot capture: it ends the graph, runs eagerly, and starts a new one. Find both with TORCH_LOGS="graph_breaks,recompiles".torch.compile not speed a model up?Shard(d), Replicate(), Partial()); operators propagate placements and insert the collectives needed. FSDP2, tensor parallelism and distributed checkpoints are built on it.TORCH_DISTRIBUTED_DEBUG=DETAIL to catch mismatched shapes or order, then look for rank-dependent code paths and uneven data.custom_op, autograd.Function or a tensor subclass?autograd.Function to change a backward; custom_op to add an opaque operator that compile and export can treat as one node (with a fake implementation); a subclass to change what a tensor is (sharded, quantized).One real training step of the running example, a tiny GPT, recorded op by op on an Apple M1 Pro: every call that reached PyTorch's dispatcher in forward, backward and the optimizer, the route each call took through the dispatcher, the autograd graph forward builds and backward consumes, and the memory held after every op. Then the same step with activation checkpointing, and the same forward with gradients switched off. Go deeper: the child page Tensors, the dispatcher and autograd takes each layer further.
The model (the topic's src/model/, shared by every tab): a GPT-2-shaped decoder in plain PyTorch, character level on 1,329 bytes of Alice's Adventures in Wonderland. 43-character vocabulary, dmodel 256, 4 blocks (pre-LayerNorm, 4 attention heads through F.scaled_dot_product_attention, GELU MLP of 1,024), learned positions, output layer tied to the input embedding: 3,186,944 parameters. Batch 8 windows of 64 characters. AdamW, lr 6e-4. Seeded, so the weights and batches are the same on every run.
The step recorded is the second step (batch 1), after one warm-up step, so AdamW's state already exists (the first step also creates it: 104 extra zeros_like calls for the two moments and 52 lift_fresh for the step counters). Loss 3.1879 on CPU and on MPS.
How: a TorchDispatchMode (PyTorch's hook for seeing every ATen call that reaches the dispatcher below autograd) logs each call's inputs and outputs (shape, strides, storage offset, dtype) and whether an output got a new storage. Live bytes are tracked per storage, with a finalizer on each storage object, so a storage counts from its allocation until the last tensor using it dies. The dispatch route is reconstructed from each input tensor's dispatch key set (torch._C._dispatch_keys), the thread state (grad mode, inference mode) and the op's dispatch table (torch._C._dispatch_dump_table, which says which keys have a real kernel). The autograd graph is walked from the loss after forward; pre-hooks on every node record the order backward runs them. Scripts: src/step/record_step.py, basics.py, time_step.py; torch 2.14.1, CPU with 4 threads, and MPS. Measured on Apple M1 Pro. What carries over to NVIDIA GPUs is at the end.
A tensor is a header (shape, strides, offset) over a flat storage, and a view is a new header over the same bytes; the mechanism, stepped and explorable, is on Tensors, the dispatcher and autograd, section 1, and its Stride explorer. What this step adds is where views happen in a real model.
The model does exactly this in attention. One qkv Linear writes a (512, 768) block; view makes it (8, 64, 768); split cuts q, k and v as three views at storage offsets 0, 256 and 512, all with strides (49152, 768, 1); view and transpose turn each into (batch, head, position, 64) with strides (49152, 64, 768, 1). Eight view ops, zero bytes copied, all read from the recorded step ().
Predict. After attention the model writes y.transpose(1, 2).contiguous().view(B, T, C). On the CPU, how many bytes does that .contiguous() copy per layer? And on MPS?
Every call walks down its operator's table of kernels by dispatch key, from autocast and autograd down to a backend; the walk itself, key by key, and the tables are on Tensors, the dispatcher and autograd, sections 2.2 and 2.3. A parameter of the model on the CPU carries . Three entries of the real tables (torch 2.14.1 wheel, torch._C._dispatch_dump_table) show up in the recorded step:
linear is a math kernel on the CPU, so on the CPU every nn.Linear decomposes at the autograd key into t (a view of the weight) and addmm (one fused multiply-add kernel), and autograd records a node for each. On MPS linear has its own kernel and its own autograd kernel: the MPS trace has 17 linear calls where the CPU trace has 17 t plus 16 addmm plus one mm.ADInplaceOrView has a real kernel only for views and in-place ops (view, add_); for addmm it is a fallthrough. That is where PyTorch records that a view shares its base's storage and bumps the version counter that catches an in-place write to a tensor backward still needs._scaled_dot_product_flash_attention_for_cpu has no MPS kernel, so on MPS F.scaled_dot_product_attention takes another route for this model: the MPS trace shows it written out (mul, bmm, _safe_softmax, bmm), with the full 64 × 64 attention matrix per head in memory.The recording in section 3 is itself a dispatch mode at the Python key; the Reading tab's section 8 and the Compile lab build on the same table.
Forward runs the model and, because the parameters require gradients, autograd records a node for every differentiable op: a small object that knows how to compute that op's gradient and which tensors it must keep (saved tensors). Backward walks those nodes from the loss back to the parameters. The optimizer then updates every parameter. Below is every call that reached the dispatcher, in order. The stack beside the call (below it on a phone) is the route it took through the dispatcher; the chart is the memory this step holds on top of the 38.25 MB that sits there all the time (12.75 MB of parameters, 25.5 MB of AdamW state, 8 KB of batch).
The recorded forward built . How the engine orders them and what a node holds is Tensors, the dispatcher and autograd, sections 3.1 and 3.2, stepped on one block; here is what the whole step kept.
Activation checkpointing (torch.utils.checkpoint.checkpoint(block, x, use_reentrant=False), here around each of the 4 blocks) tells autograd not to keep a block's intermediate tensors. Forward keeps only each block's input. In backward, when a node inside the block needs a tensor it did not keep, PyTorch reruns the block's forward to rebuild it, then carries on. The trade: memory for compute. Watch the same step both ways, drawn to the same scale.
Pass use_reentrant=False explicitly. At 2.14.1 a call that leaves it out still runs the older reentrant variant and only warns (checkpoint.py L635 to L647); on this step that variant recomputed all 16 block matrix multiplies instead of 12 (Tensors, the dispatcher and autograd, section 3.6).
Predict. With checkpointing, backward reruns each block's forward. Each block's forward has 4 addmm calls. How many addmm calls does the checkpointed backward make?
For evaluation and generation you do not need a graph. Two switches turn it off. torch.no_grad() sets grad mode off: every call still enters the autograd kernel, which sees there is nothing to record and passes the call on. torch.inference_mode() goes further: it removes the autograd and ADInplaceOrView keys for the thread, so calls skip those layers entirely, and tensors created inside are inference tensors with no version counter (using one later in autograd raises an error). Same weights, same batch, three ways:
Wall time per phase, with .item()-free timing: on MPS each phase ends with torch.mps.synchronize(), because MPS (like CUDA) queues work and returns before it is done.
Inside one profiled CPU step (torch.profiler, self time per ATen op), the biggest items:
Predict. The optimizer phase is about a quarter of the CPU step. AdamW has three implementations: a Python loop over parameters (what PyTorch picked here), foreach (one call per operation over the list of all parameters) and fused (one kernel doing the whole update). Which is fastest on the M1 Pro CPU, and by how much?
The op sequence and the graph. On a CUDA tensor the keys become AutogradCUDA and CUDA; the same Python code makes the same autograd nodes and the same saved tensors. Saved bytes at float32 are the same; under bf16 autocast most activations halve.
The dispatch mechanics: math kernels decomposing, views costing nothing, no_grad against inference_mode, checkpointing's memory-for-compute trade and its early stop, the version counter.
Which kernels run. On CUDA, scaled_dot_product_attention picks FlashAttention or memory-efficient kernels (not the CPU flash kernel, not the MPS math path); linear decomposes as on the CPU and the matmul goes to cuBLAS. See Writing kernels for FlashAttention.
The optimizer default. On CUDA PyTorch picks foreach by default (here: the for-loop), and fused=True is one opt-in away. The for-loop reads the step counter with .item() once per parameter (adam.py L528); the counter lives on the CPU unless capturable=True or fused=True (L168), so by default that read is not a GPU sync. See Optimisers.
Times. These are CPU and Apple-GPU times at a toy size, where per-call overhead in Python and the dispatcher is a large share (). On a GPU the same overhead shows up as launch gaps between short kernels: the case for torch.compile and CUDA graphs (Compile lab, Streams, CUDA graphs and multi-GPU).
Exact live bytes. CUDA's caching allocator rounds blocks up and keeps freed memory for reuse, so torch.cuda.memory_allocated is close to these numbers and memory_reserved is higher. See Memory allocators.
.view() and .reshape() are the same"view never copies and fails when the strides do not allow it (try x.t().view(12): ). reshape returns a view when it can and silently copies when it cannot, so whether you got a copy depends on the input's layout..contiguous() always costs a copy"no_grad and inference_mode are the same"no_grad still enters the autograd and view-tracking layers on every call; inference_mode skips them and makes inference tensors you cannot later use in a graph. On this toy forward the difference was within noise on both devices (section 6); the gain grows with the number of small ops.addmm calls). Forward is about a third of a step's arithmetic, so the extra is about a third, not double; here the CPU step went from 22.5 to 31.6 ms.torch.no_grad()"ADInplaceOrView kernels maintain.time.time() around it is enough"torch.mps.synchronize()), repeat, and report the spread; see Profiling, benchmarking and correctness.x.untyped_storage().data_ptr() tells you whether two tensors do.torch.add(a, b) on two CPU tensors that require grad.AddBackward0 node (with grad mode on) and redispatches with autograd masked out; ADInplaceOrView is a fallthrough for add; the CPU kernel allocates the output and computes it.y = x @ W.t() + b?AddmmBackward0 saved its input and the weight.retain_graph=True), while gradients appear as AccumulateGrad nodes run. Here live memory fell from +34.8 MB after forward to +12.8 MB after backward: the gradients, freed by zero_grad(set_to_none=True).linear on CPU), so it needs no backward formula and no backend kernel of its own: it decomposes before autograd records anything. A backend may still register its own kernel to avoid the decomposition (MPS does for linear), and compilers see the decomposed ops.torch.cuda.memory._record_memory_history() and the memory snapshot viewer; anywhere, a TorchDispatchMode that logs output storage sizes, as this tab does, or the profiler with profile_memory=True.Data: one step recorded 2026-10-12 on Apple M1 Pro, torch 2.14.1; scripts and raw traces in the page's src/step/. Every number on this tab is read from those traces or recomputed from them in the browser.
The running example, a tiny GPT, put through torch.compile on an Apple M1 Pro: the graph Dynamo captures and the guards it writes, deliberate graph breaks and what each costs, recompiles when shapes change, what AOTAutograd saves for backward, the kernels Inductor writes (C++ with OpenMP on the CPU, Metal shaders on MPS) next to the eager ops they replace, the speed and the compile time, and torch.export plus AOTInductor. Every number below was measured or recorded here; the published GPU results are kept apart at the end. Go deeper: the child page torch.compile from the user's side (every kind of graph break and its fix, the partitioner at each memory budget, compiled autograd, regional compilation, caches, export in detail).
The model is the topic's shared one (described in Inside one step): a GPT-2-shaped decoder, 4 blocks, dmodel 256, 3,186,944 parameters, batch 8 windows of 64 characters, AdamW. It is imported from src/model/, never copied; graph-break variants replace Block.forward at run time in the script, not in the file.
Recorded (deterministic: the same on every run): Dynamo's graph via torch._dynamo.explain; guards via TORCH_LOGS=guards; the forward and backward graphs after AOTAutograd's partitioner, captured by wrapping Inductor's per-graph compiler (compile_fx(..., inner_compile=...), with the FX-graph and AOTAutograd caches switched off so the graphs are really built); Inductor's generated code via torch._inductor.utils.run_and_get_code, its kernel launches parsed from the generated wrapper; eager ops with a TorchDispatchMode. Timed (under a lock shared with the other agents on this machine, 5 trials of 20 steps after 5 warm-up steps, medians with the range of trials): CPU with 4 threads, MPS with torch.mps.synchronize(). Other work was running on the machine: load averages from 2.7 to about 30 are stored with each file, so read differences under about 5% as noise. torch 2.14.1, 2026-10-12. Scripts: src/comp/ (README there). Measured on Apple M1 Pro.
torch.compile does, on this modelEager mode is PyTorch's normal way of running: each Python line calls one operator, which runs one kernel right away and writes its result to memory (the Inside one step tab follows all 142 forward calls of this model that way). torch.compile(model) instead watches the Python code run once, turns it into a graph (a list of operations with their data dependencies), optimises the whole graph, and from then on runs generated code instead. Four pieces do it. Click one to jump to its section.
Two words appear everywhere below. A guard is a check Dynamo writes next to each compiled graph ("the input is int64 of shape (8, 64)", "grad mode is on"); on every call the guards run first, and if one fails the code is recompiled for the new situation. A graph break is a point where Dynamo cannot follow the Python (a print, a tensor turned into a Python number): it ends the graph there, runs that bit as ordinary Python, and starts a new graph after it. The mechanics of each piece, on small programs and with every log, are on The compiler stack: PTX, SASS, NVRTC, torch.compile and Inductor (section 8 and its Inside torch.compile tab); this tab measures them on a whole training step.
Most operations in a model, other than matrix multiplies and attention, are pointwise (each output element depends on one input element: add, multiply, GELU) or small reductions (a row's mean, as in LayerNorm). In eager mode each one is its own kernel: it reads its inputs from memory and writes a full-size result back, and the next op reads that result again. Fusion merges a chain of them into one kernel that reads each input once, keeps the intermediate values in registers, and writes only the final result. The work done is the same; the memory traffic is not.
Below: GPT-2's GELU written out with tanh (the form in the original GPT-2 code), on a tensor the size of this model's MLP activation, (8, 64, 1024) float32 = 2 MiB; or the residual add plus LayerNorm that opens every block's second half. Eager first, then switch to Fused: the bytes are counted from the recorded ops, and the times are measured.
The steps above follow the function and mode chosen over the figure; they are written from the recorded byte counts.
Predict. Fused, the tanh GELU moves times fewer bytes. How much faster is it on this CPU (4 threads)? And on the M1 Pro's GPU (MPS)?
One OpenMP loop over the 524,288 elements, 4 at a time (Vectorized<float> on this machine is a 128-bit NEON register of 4 floats; Inductor picked the VecNEON ISA). Each tmp is a register, not a tensor: the 8 eager ops are the arithmetic between one loadu and one store.
ATen's own native_layer_norm is already a single hand-written kernel, so fusion only saves the add's round trip. Inductor's version makes several passes per row (a sum for the mean, a pass for the variance, the normalisation) and, in this build, divides the 512 row sums inside an omp single block, which one thread runs. Reading code like this is how you find out why a compiled region is slower than you expected.
Dynamo is the front end. It hooks into CPython's frame evaluation (PEP 523), reads the bytecode of GPT.forward as it runs, follows every call into Block.forward, nn.Linear and so on, and records each tensor operation into an FX graph (PyTorch's Python-level graph format). Python control flow that does not depend on tensor values, such as the for blk in self.blocks loop, is simply unrolled: the graph has 4 copies of the block.
Still high-level: linear, layer_norm, scaled_dot_product_attention, views. Decomposition into ATen ops (addmm, native_layer_norm) happens in the next stage.
Guards. The graph is only valid for what Dynamo saw: these input dtypes and shapes, these parameter objects, grad mode on, 4 threads, no autocast. Dynamo wrote guards for this model; most check that a parameter is still a tensor of the same shape and has not been marked dynamic. They run in C++ before every call, which Dynamo timed at microseconds when it built them (once on CPU, once on MPS): small next to a 20 ms step, but this is the per-call price of a compiled region.
TORCH_LOGS=guards prints themPaths shortened. GLOBAL_STATE is why switching to no_grad for evaluation triggers a recompile (section 5); TENSOR_MATCH with size=[8, 64] is why a new batch size does.
Four common lines, each added to Block.forward between attention and the MLP. For each: Dynamo's own reason, what was compiled, and the training step's time. The strip shows one forward pass: green pieces ran as compiled code, dashed ones ran as ordinary Python, op by op.
Predict. With the print inside each block, which parts of the forward still run compiled?
What the five runs show: a break does not stop compilation, it fragments it. The model goes from one compiled piece per forward to , with the Python in between run eagerly, and fusion cannot cross a break. Here the cost was per step; on a GPU, where each piece also launches its own kernels and a CUDA graph cannot span a break, it is usually larger. Find breaks with torch._dynamo.explain(model)(x, y) (used here) or TORCH_LOGS=graph_breaks; make them errors with fullgraph=True, which is what you want in a training loop you control.
When a guard fails, Dynamo compiles again for the new situation and keeps both versions (up to torch._dynamo.config.recompile_limit, at 2.14.1, after which that function runs eagerly). On a shape guard failure it does something smarter, automatic dynamic shapes (on by default): the second compile treats the dimension that changed as a symbol (s0) so any later size reuses it. torch._dynamo.mark_dynamic(t, dim) asks for the symbol from the first compile. The same seven calls on one compiled model, three ways:
Three lessons from the table. Marking only the input tokens did not help, because the targets carry the same batch and length dimensions and were guarded too: mark every tensor that shares the dimension. A shape that changes once (the short last batch of an epoch) costs one recompile and then nothing; the recompile cost with an empty cache. And switching to model.eval() under torch.no_grad() recompiles once, because grad mode is part of the global-state guard: budget for it in your evaluation loop. Python numbers behave like shapes: a small compiled update p - lr * g called with five different float learning rates compiled at these calls: . The first value was guarded, the second failed the guard, and from then on the float was a symbol. Five different ints: . Five 0-d tensors: . Values that are not numbers or shapes (a string flag, a module attribute, a dtype) are guarded by value, like the EQUALS_MATCH and ID_MATCH guards in section 3, so each new value is a new compile, up to the limit (not run here).
Dynamo captures only the forward. AOTAutograd runs PyTorch's autograd once on fake tensors (shapes and dtypes, no data) to trace the backward too, producing one joint graph, then a partitioner cuts it into a forward graph and a backward graph. The cut decides what the forward must save for backward: by default a min-cut algorithm that may recompute cheap values in backward instead of storing them (min_cut_rematerialization_partition, torch/_functorch/partitioners.py). Here the graphs were decomposed into ATen ops first, which is why they are longer than Dynamo's.
Inductor is the default back end. It lowers each graph to a loop-level form, groups the operations that can share one pass over memory, writes one kernel per group (C++ with OpenMP for CPUs, Triton for NVIDIA and AMD GPUs, Metal shaders for Apple GPUs), and sends matrix multiplies to a library (extern_kernels.addmm and mm: the BLAS ATen uses) unless autotuning picks a generated template. Ops it has no lowering for run as fallbacks: the original ATen kernel, called from the generated code. Left: the eager calls for one training step's forward or backward. Right: what the compiled step launches instead. Click a green kernel to read it.
The honest headline first: on this CPU, compiling the model did not make the training step faster; on the M1 Pro's GPU it did. The per-step bars are medians of 5 trials of 20 steps; whiskers span the trials.
Why no gain on the CPU. The profiler splits the CPU time of the forward and backward (optimizer excluded). Eager: in matrix multiplies and attention, and in everything else, which is the part Inductor can fuse. Compiled: the matmuls and attention are the same library kernels (), the two generated graphs that replace everything fusible took , and went to what is left outside them (copies, fills, entering the compiled region). The fusible part got cheaper, but it was under half of the time to begin with, and Inductor's C++ on this ARM CPU (128-bit NEON vectors of 4 floats) gains little over ATen's hand-written kernels for these ops. The phase timings below agree, and show how much two runs of the same script vary.
Memory. Compiling did not change what the forward keeps for backward on this model: AOTAutograd saved against eager's 34.76 MB (section 6), and the MPS allocator held after the forward. To cut activation memory you still need activation checkpointing or a smaller batch.
Compile time. The first call of the compiled training step, in a fresh process: with an empty cache directory, when the cache from an earlier run was there (Inductor's FX-graph cache and AOTAutograd's cache are on by default and live in TORCHINDUCTOR_CACHE_DIR). Modes add more: max-autotune's first call took . Whether compiling pays is arithmetic:
The optimizer. torch.compile(model) compiles the forward and backward only; opt.step() stays eager. Compiling it too (torch.compile(opt.step)) brought the CPU step to ; simply passing fused=True to AdamW, with no compile at all, did better, (the Inside one step tab shows why: the default on CPU and MPS is a for-loop over 52 parameters). On MPS, the compiled model with fused AdamW was the fastest combination measured, against eager.
torch.export and AOTInductor: compile once, run without Pythontorch.compile is just-in-time: it compiles inside your Python process and falls back to Python wherever it must. torch.export is the ahead-of-time path: it traces the whole model into one graph or fails (no graph breaks allowed), records the allowed range of every dynamic dimension, and returns an ExportedProgram, a file-able graph plus its weights. AOTInductor then runs Inductor on that graph and writes a shared library, packaged as a .pt2 file that a C++ or Python program loads with no model code at all. Here the inference path (tokens in, logits out) with a dynamic batch dimension:
Use export when the model must run where your training code cannot: a C++ server, a different machine, a mobile device (ExecuTorch also starts from an ExportedProgram; formats are compared on Local and on-device inference, section 3). For training, torch.compile is the tool; export's job is deployment. torch.onnx.export uses this same exporter by default since 2.9.
mode="reduce-overhead" records the compiled step as a CUDA graph and replays it with one launch; the 2.14.1 docstring says "we only reduce overhead for CUDA only graphs which do not mutate inputs". On this CPU it changed nothing ( against ). CUDA graphs are explained on Streams, CUDA graphs and multi-GPU. max-autotune on a GPU benchmarks Triton matmul templates; here on the CPU it benchmarked and kept ATen's BLAS for every matmul ().model.eval() with no_grad, a string flag that changes. Each costs a full compile ( here). Run with TORCH_LOGS=recompiles once; it prints the failing guard, as in the table in section 5.idx still recompiled on targets.print, .item() or logging call left inside forwardfullgraph=True to be told.torch.compile(model) to speed up the optimizerfused=True (or foreach) or compile the step function.torch.compile, and what does each produce?recompile_limit (8) the function runs eagerly.print or logging (move it out, or register it as reorderable logging); .item() or data-dependent if (keep the value as a tensor, use torch.where, or torch.cond; capture_scalar_outputs for .item()); calls into non-PyTorch libraries on real data (do them outside, or wrap as a custom op).reduce-overhead and max-autotune do?The running example spread over several processes on one Mac: 2 and 4 CPU processes talking through PyTorch's gloo backend, launched with torchrun. The same training step under DDP, FSDP2, tensor parallelism and a two-stage pipeline, recorded collective by collective with PyTorch's own flight recorder; every placement change DTensor can make, with the collective it triggers; a sharded checkpoint saved on 4 ranks and loaded on 2 and on 1; and three deliberate hangs, with the evidence each leaves. Go deeper: the child page Distributed PyTorch: c10d, DDP, FSDP2, DTensor, TP, PP, DCP: DDP comm hooks and their bytes (section 3), a mesh explorer over six real layouts, and every pipeline schedule timed (section 8).
The model is the topic's running example (a 3,186,944-parameter character-level GPT; see Inside one step), imported from the root's src/model/, plus one bigger variant (8 blocks, dmodel 512: 25,274,880 parameters) where memory needs a larger model to show its shape. Rank r trains on batch s × world + r at step s, so every strategy sees the same data.
Collectives come from PyTorch's flight recorder (a ring buffer of every collective a process group issues: name, sizes, dtypes, sequence number; switched on with TORCH_FR_BUFFER_SIZE and read with torch._C._distributed_c10d._dump_fr_trace_json), which works with gloo at 2.14.1. DTensor's own view of what it asked for comes from CommDebugMode. Memory is PyTorch's memory profiler (the engine behind torch.profiler's export_memory_timeline), which follows every tensor's storage from allocation to free, on CPU too. A first attempt summed each op's own allocations instead; it put AdamW's frees at the wrong moment and never saw FSDP2 free its gathered weights (it does that with storage.resize_(0)), so its curve drifted by exactly the gathered bytes each step. The memory profiler's start-of-step total equals the persistent state counted tensor by tensor.
Scripts: src/dist/ (ddp.py, fsdp.py, dtensor.py, tp.py, pp.py, dcp.py, hang.py, time_dist.py), each launched by run.sh; torch 2.14.1, one thread per process. CPU, 2 or 4 processes, gloo, measured on Apple M1 Pro, 2026-10-12. Collective order, sizes, shard shapes, memory and losses are deterministic and carry over to GPUs in kind; times do not (gloo over loopback is not NCCL over NVLink). What carries over is at the end. The theory (ZeRO stages, the parallelism maths, which split to use at which scale) belongs to Distributed Training; this tab is PyTorch's APIs and what they actually do.
Everything so far ran in one process: one Python interpreter with its own memory. Data-parallel training runs the same script in N processes at once, usually one per GPU, each holding its own copy (or slice) of the model. This is SPMD, single program, multiple data: the code is identical, the data and the rank differ. The rank is the process's number, 0 to N − 1; N is the world size.
torchrun starts the N processes and gives each its identity through environment variables (RANK, LOCAL_RANK, WORLD_SIZE, MASTER_ADDR, MASTER_PORT). Each process then calls torch.distributed.init_process_group(backend): they meet at a small key-value store on the master address (the rendezvous) and build a process group, the set of ranks that can talk. c10d is the PyTorch library that does this; its backends move the bytes: NCCL for NVIDIA GPUs, gloo for CPUs (and as a fallback), plus MPI and vendor libraries.
torchrun waited forever at the rendezvous until MASTER_ADDR=127.0.0.1 was set (the hostname did not resolve to a usable address). And fully_shard with no mesh tried to build one on the "current accelerator", which on a Mac is MPS, and failed with AttributeError: module 'torch.mps' has no attribute 'is_initialized' (_fsdp_init.py L198, device_mesh.py L496). Passing mesh=init_device_mesh("cpu", (world,)) fixed it. Related: Accelerate on CPU silently ignores an FSDP plugin and hands back DDP (Ecosystem map).A collective is an operation every rank in a group calls together, each with its own tensor. Distributed training is built from five of them, plus point-to-point send and recv between two ranks. Pick one: the tensors before and after, on 4 ranks.
The identity worth remembering: all-reduce = reduce-scatter + all-gather. Each half moves (n − 1)/n of the data per rank, so an all-reduce costs about twice either half. FSDP's whole design rests on doing the two halves at different times.
reduce_scatter_single clones the whole input, all-reduces it, and copies out this rank's chunk (ProcessGroupGloo.cpp L1557). The flight recorder shows it plainly: every reduce-scatter below appears as gloo:all_reduce of the full tensor. So on this machine FSDP2's gradient step moves twice the bytes and holds a full-size temporary that NCCL's real reduce-scatter would not. The page labels these "reduce-scatter (run as all-reduce)".DistributedDataParallel (DDP) keeps a full copy of the model on every rank and makes their gradients identical before each optimizer step, so the copies never drift apart. It does three things, all visible in the recording:
Why buckets? One all-reduce per parameter would mean 52 small messages, each paying a fixed latency; one for the whole model could start only when backward ends, so nothing overlaps. The default cap is 25 MiB, with a smaller first bucket of 1 MiB so the first all-reduce can start early (distributed.py L31, L86). Buckets fill in reverse parameter order, because backward produces the last layer's gradients first.
Predict. The model is 12.75 MB of float32 gradients, under one 25 MiB bucket but over the 1 MiB first bucket. How many all-reduces does DDP issue in the first backward?
One. Recorded on both ranks: a single all-reduce of 12,747,776 bytes, issued only once every gradient was final, so nothing overlapped in step 0. Unless find_unused_parameters=True or an explicit bucket list is given, the first iteration puts everything in one bucket (a size limit of sys.maxsize, L151); during that iteration DDP records the order in which gradients actually arrived, and at the start of step 1 rank 0 broadcasts a new bucket layout in that order (the two small broadcasts of 212 and 8 bytes in step 1). From then on: two buckets, 1,051,648 and 11,696,128 bytes.
The bucket strip and the step timeline of this recording, step 0 against the rebuilt buckets, are now one stepper on Distributed PyTorch, section 3, which owns DDP's buckets and hooks.
Two details the recording shows. The tied weight tok.weight is the output layer too, so its gradient has two contributions: the output layer's arrives first, the embedding's arrives last, and the parameter is final only then. It is always in the last bucket. And with bucket_cap_mb=1 the same step issues 13 all-reduces of about 1 MB, each one launched while backward is still running: more overlap, more per-message overhead. Which wins depends on the network; on GPUs the default is usually right, which is why it is the default.
Memory cost of DDP's buckets. DDP keeps its buckets as separate flat buffers, so by default every gradient exists twice: in param.grad and in its bucket. Here that is 12.75 MB per rank on top of the 12.75 MB of weights and 25.5 MB of AdamW state. gradient_as_bucket_view=True makes each .grad a view into its bucket and removes the copy; on this model the step's peak did not move (), because the peak comes at the very start of backward, when every activation is still held and only the first gradients exist. On a model whose peak falls later in backward, it does.
DDP's memory per rank never shrinks: 16 bytes per parameter of weights, gradients and Adam state on every rank (more with its buckets). FSDP (fully sharded data parallel) is PyTorch's version of ZeRO stage 3 (the theory is on Distributed Training, and the ZeRO paper page steps through DDP against ZeRO-3 on GPUs): each rank permanently keeps only 1/n of every parameter, its gradient and its optimizer state, and rebuilds a whole layer just before using it.
FSDP2 is the current API, torch.distributed.fsdp.fully_shard (in PyTorch since 2.4; FSDP1, the FullyShardedDataParallel wrapper with flattened parameters, is still shipped at 2.14 without a formal deprecation notice: see Ecosystem map). fully_shard(module) turns each of the module's parameters into a DTensor (section 7) with placement Shard(0): rank r owns rows r·k to (r+1)·k of every weight. The model is wrapped the way torchtitan does it: fully_shard on each of the 4 blocks, then on the whole model, which picks up what is left (embeddings, final LayerNorm, tied output layer). Each call makes one unit: one all-gather brings its weights in, one reduce-scatter sends its gradients out.
What happens in one step, per unit, in order (drawn in 3D, on 4 ranks, as Fig. 3 of Distributed PyTorch):
reshard_after_forward defaults to None: True for the blocks, False for the root unit, "because the root module is typically required immediately when the backward pass begins" (_fully_shard.py L180). FSDP2 also prefetches: it issues the next unit's all-gather before the current unit finishes, which you can see below as all-gathers launched early. Setting it False everywhere skips all four backward all-gathers and keeps every block's full weights alive from forward to backward.
The same step (step 2, batch 4 on rank 0 and batch 5 on rank 1), recorded under each strategy on 2 ranks. Lanes are ranks; the bar is the step's compute (forward, backward, optimizer); each mark above it is a collective at the moment it was issued, its height to scale with the bytes it carries. The memory line is rank 0's live bytes over the same step.
What each rank holds at its peak during one step: persistent state (weights, AdamW's two moments, DDP's bucket buffers) plus the step's own peak (activations saved for backward, gathered weights, full-size gradients before they are reduced, collective temporaries). Bars to scale within a model size.
Predict. On the tiny model, going from 2 to 4 FSDP2 ranks cuts the persistent state in half. What happens to the step's own peak (activations and everything gathered)?
It stays the same: . Each rank still processes a full batch of 8 sequences, so its activations do not shrink, and the gathered weights of one block are full-size whatever n is. FSDP shards model state, not activations: that is what activation checkpointing (Inside one step), tensor parallel and context parallel are for. On the tiny model activations dominate, so the total falls only from ; on the 8-block variant, where weights and Adam state are 303 MB, from .
FSDP2, tensor parallel and distributed checkpoints are all built on one abstraction. A DeviceMesh arranges the ranks in a grid: 4 ranks as a line of 4, or as 2 × 2 (say, data parallel along one axis and tensor parallel along the other). A DTensor is one logical tensor spread over a mesh, described by one placement per mesh dimension:
Shard(d): split along tensor dimension d; each rank holds one piece (like torch.chunk, so 6 rows over 4 ranks gives rows: the last rank can be empty).Replicate(): every rank holds the whole tensor.Partial(): every rank holds a full-shape tensor, and the real value is their sum (a pending reduction). This is what a row-split matrix multiply produces before its all-reduce.Every operation on DTensors either works locally or needs a redistribute, which is a collective. Knowing which placement change needs which collective is most of what tensor parallelism is. Pick a mesh and two placements: the 4 × 4 tensor arange(16), which rank holds which elements before and after, and the collectives the real run issued. Distributed PyTorch draws placements on 2 ranks as its Fig. 4.
CommDebugMode) and as gloo ran them (flight recorder). The local values are computed in the page from the placements and were checked against the recorded local tensors of every rank in every pair. A Partial source is built with integer pieces that sum to the tensor (element k on mesh coordinate k mod n).Summary of the 1-D mesh of 4. Read across: Shard to Replicate is an all-gather, Partial to Replicate an all-reduce, Partial to Shard a reduce-scatter, Replicate to Shard is free (each rank keeps its piece), and Shard to Partial is free too (fill the rest with zeros). Two things the recording added: at 2.14.1 Shard(0) to Shard(1) is an all-gather followed by a local slice, not an all-to-all; and Replicate to Partial raises "only Shard to Partial(sum) redistribution is supported".
Tensor parallelism (TP) splits each weight matrix across ranks that all see the same batch. The Megatron-LM recipe for an MLP, which PyTorch exposes as ColwiseParallel and RowwiseParallel in torch.distributed.tensor.parallel: split the first Linear by output columns (each rank computes half of the 1,024 hidden units, and GELU works on its half alone), split the second by input rows (each rank multiplies its half and gets a Partial sum), then one all-reduce adds the halves. Backward mirrors it: one all-reduce of the input gradient. The maths and its cost model are on Distributed Training and the Megatron-LM paper page.
ColwiseParallel on it gives rank 0 rows (all of q and half of k) and rank 1 the rest, and the forward fails at once: ValueError: not enough values to unpack (expected 3, got 2), because a 384-wide local output cannot be split into three 256-wide pieces. Column-splitting needs whole heads on each rank. torchtitan's fused projection is laid out head-group by head-group for exactly this reason ("Compatible with ColwiseParallel on the wqkv linear layer", torchtitan 0.3.0 attention.py L785), and its unfused version shards wq, wk, wv separately. The parallel plan is a property of the model's layout, not only of the module types.Two dimensions at once. On 4 ranks as a 2 × 2 mesh, the MLPs were tensor-parallel over one axis and the whole model was fully_shard-ed over the other, the layout torchtitan calls 2-D parallelism. The first MLP weight's placements came out as : sharded on dimension 0 by both axes, the FSDP part as a "strided" shard so that each rank's rows are the right ones. Collectives now come in two groups: . Losses matched the 1-D runs ().
Pipeline parallelism puts consecutive layers on different ranks: here rank 0 runs the embeddings and blocks 0 and 1, rank 1 runs blocks 2 and 3 and the output layer. The batch of 8 is cut into 4 micro-batches of 2 so both ranks can work at once; activations flow forward by send/recv, their gradients flow back the same way. A schedule decides the order. torch.distributed.pipelining (PyTorch 2.4 onward) ships several; two are run here, on the same input:
GPipe runs all forwards, then all backwards: simple, but stage 0 holds the activations of all 4 micro-batches at once. 1F1B starts each backward as soon as it can and then alternates one forward with one backward, so stage 0 never holds more than 2. Same gradients, same communication (4 activations of 131,072 bytes sent forward and 4 gradients of 131,072 bytes sent back per step), lower peak. The idle gaps at the start and end are the pipeline bubble; the schedules that shrink it (interleaved 1F1B, zero-bubble, DualPipe) are in torch.distributed.pipelining too and their maths is on Distributed Training.
With FSDP2 no rank holds the whole model, so torch.save(model.state_dict()) on rank 0 is not an option. Distributed checkpointing (torch.distributed.checkpoint, DCP) lets every rank write its own shards in parallel and records, in a small .metadata file, where every piece of every tensor lives. get_state_dict(model, optimizer) returns the state as DTensors; dcp.save plans, writes and commits; dcp.load reads into whatever sharding the loading job has, so a checkpoint from 4 ranks loads onto 2, or onto one process. Section 3 of Local and on-device inference covers the file formats themselves (pickle, safetensors).
Recorded (the running example after two FSDP2 steps on 4 ranks, weights and AdamW state):
The same checkpoint read back two ways, in 3D: Fig. 5 of Distributed PyTorch.
A collective only completes when every rank in the group calls it, with matching sizes. If one rank skips it, calls a different one, or is stuck elsewhere, the others wait. On GPUs that wait is a hang: no error, no progress, GPUs at full utilisation spinning, until a timeout fires (by default 10 minutes for NCCL, 30 for other backends, ProcessGroupNCCL.hpp L159, Backend.hpp L37). The usual causes: a rank-dependent branch around a collective (logging, evaluation, an early break), a data loader giving ranks different numbers of batches, a parameter unused on one rank, or a crash on one rank that the others never hear about. Three were caused on purpose here, with a 10-second timeout:
How to read one. The flight recorder is the first thing to look at: every rank's last collectives with their sequence numbers. Find the first sequence number at which the ranks disagree (different operation, different sizes, or one rank missing it); the code that issued it on the odd rank is the bug. On NCCL, TORCH_NCCL_DUMP_ON_TIMEOUT=1 makes the watchdog write each rank's record when the timeout fires, and torchfrtrace (the analyser shipped with PyTorch, torch.distributed.flight_recorder.fr_trace) lines them up across ranks; NCCL also tracks each entry's state (scheduled, started, completed), which gloo does not (every entry here stays "scheduled"). TORCH_DISTRIBUTED_DEBUG=DETAIL catches mismatches before they hang, at a price measured above: two extra all-gathers per collective, so use it to find a bug, not in production. monitored_barrier (gloo only) names the rank that did not arrive.
Which collectives, in which order, of which sizes. DDP's bucket layout and rebuild, FSDP2's all-gather and reduce-scatter per unit with prefetch, TP's two all-reduces per MLP, the pipeline schedules' send/recv order and DCP's planning are backend-independent Python and C++ above the backend.
Memory per rank, in kind. What is sharded and what is not: FSDP shards weights, gradients and optimizer state, never activations; 1F1B holds fewer micro-batches than GPipe. Absolute numbers change with bf16 (half the bytes), the CUDA caching allocator (Memory allocators) and NCCL's own buffers.
Reduce-scatter. NCCL has a real one, moving half the bytes of gloo's all-reduce substitute and needing no full-size temporary, so FSDP's gradient step is cheaper on GPUs than here. FSDP's total traffic is about 1.5 times DDP's on NCCL (the Distributed Training formula) and 2 times here.
Overlap. On GPUs, collectives run on their own CUDA stream next to compute, so DDP's buckets and FSDP's prefetched all-gathers really overlap; on CPU with one thread per rank, gloo's work competes for the same cores. Streams, CUDA graphs and NCCL are on Streams, CUDA graphs and multi-GPU; link speeds on Interconnects and scaling.
Times and speedups. Loopback TCP between processes on one laptop is nothing like NVLink or InfiniBand; neither is a CPU matmul like a GPU one. Published GPU scaling comes from the torchtitan paper and PyTorch's own posts, quoted on Distributed Training.
How hangs look. On gloo a mismatched size crashed one rank at once; on NCCL the same bug usually hangs silently until the watchdog's timeout, which is why the flight recorder and TORCH_NCCL_DUMP_ON_TIMEOUT exist.
if rank == 0:torch.save(model.state_dict())get_model_state_dict(..., options=StateDictOptions(full_state_dict=True, cpu_offload=True)) for small models.reshard_after_forward=False), and a reduce-scatter of the gradients. In ring terms that is about 3 × (n − 1)/n of the model per rank against DDP's 2 × (n − 1)/n, so 1.5 times the traffic, for model-state memory divided by n.TORCH_NCCL_DUMP_ON_TIMEOUT=1, then torchfrtrace), find the first sequence number where ranks disagree or a rank is missing, then look at that rank's Python stack (py-spy dump) to see what it was doing instead. Check data loader lengths and rank-dependent branches; reproduce small with TORCH_DISTRIBUTED_DEBUG=DETAIL.PyTorch is the engine: tensors, the dispatcher, autograd, the compiler and the distributed APIs. Almost every training library you will meet is a wrapper around that engine: it writes the training loop, launches the processes or swaps in faster kernels for you, and then calls the same core functions you could call yourself. This tab is a dated atlas of those libraries as of 12 October 2026: what each one is, who owns it, whether it is alive, which core APIs it actually calls, and when to pick it. Go deeper: the child page Libraries on top of PyTorch: HF stack, torchtitan, Lightning, Axolotl, DeepSpeed runs the same step through the HF Trainer, Accelerate, Lightning, DeepSpeed ZeRO 0 to 3 and torchtitan, and reads each one's defaults.
src/map/scan_source.py, scan_deps.py).
docs versions and dates from PyPI, licences from PyPI and the repository's LICENSE file, statuses from the project's own README, issue or announcement, each linked. A status the project has not stated (a long silence) is labelled quiet and called an inference.Measured on Apple M1 Pro, CPU, torch 2.14.1, 2026-10-12 (src/map/checks/c_stacks.py; the two-process run with torchrun --nproc_per_node 2 on the gloo backend). Frames come from traceback.extract_stack() inside a forward pre-hook and an optimizer step pre-hook; frames from the Python standard library are dropped. Line numbers are those of the installed versions.
Start with the idea the whole map rests on. A training step is always the same four things: run the model forward to get a loss, run loss.backward() to get gradients, call optimizer.step() to change the weights, and clear the gradients. A plain PyTorch loop writes those four lines itself. A trainer (Lightning, the Hugging Face Trainer) writes them for you inside its own loop, with callbacks, logging and checkpointing around them. A launcher wrapper (Accelerate) leaves your loop alone and instead swaps your model for the right core class for how you launched the job. None of them has its own maths: the forward still ends in your nn.Module, and the weights still change in torch.optim.
The animation below replays the Python call stack, recorded for real, at the moment the model's forward starts (and, on the second view, the moment optimizer.step starts). Each row is one function that was running, outermost first: green is your script, orange is the library, blue is PyTorch, purple is the model. Pick a door; the frames appear one by one, top to bottom, as the call descends.
What the stacks teach. The plain loop reaches the model in 5 frames. Lightning takes 31, and the surprise is where: the model's forward runs inside optimizer.step, because Lightning passes a closure (a function that computes the loss and the gradients) to the optimizer and the optimizer calls it, the API L-BFGS needs. The HF Trainer adds 5 frames (train, _inner_training_loop, _run_epoch, training_step, compute_loss). Accelerate on one process adds none: prepare() handed back your own model. On two processes it hands back torch.nn.parallel.DistributedDataParallel, the core class itself, and its forward appears in the stack; after three steps the weights on both ranks were bit-identical, which is DDP's whole contract. The Distributed lab shows what DDP does inside those frames.
Every library around PyTorch that a training engineer is likely to meet, on one grid. The layer says where it sits: core is PyTorch itself; satellite is a PyTorch or Meta library that extends it (quantization, fault tolerance, orchestration); kernels are libraries of fast GPU code; HF is the Hugging Face stack; trainers write your training loop; scale frameworks bring their own parallelism engine; RL is post-training with generation in the loop; deploy runs a trained model elsewhere; data loads it. Click a card for owner, licence, latest release, status with its source, which core APIs its released source calls (with a real line), and when to choose it.
"Built on FSDP2" or "uses DTensor" is easy to claim and hard to check. Here it is checked: for each library, its released Python source was searched for the names of PyTorch's core APIs (and for imports of the other libraries), and the count is the number of files that mention each one. Pick a library to see its lines into the core on the left and into other libraries on the right; thicker means more files. The matrix below the picture holds every count, and clicking a cell shows a real line it matched.
fully_shard counts 1, and a docstring that mentions DTensor also counts 1 (the example line shows which you are looking at). Folders named tests, examples, benchmarks and docs are skipped. The scan reads Python only, so C++ and CUDA calls are invisible, and a library that receives core objects from its user (Lightning's ModelParallelStrategy, where you call fully_shard yourself) shows fewer hits than it enables. Patterns: src/map/scan_source.py; versions: the latest on PyPI on 2026-10-12, shown in the atlas.PyTorch 2.0 (March 2023) added torch.compile without breaking anything written for 1.x; every release since has been a 2.x. The top lane is the fifteen minor releases, the bars under it the days since the previous one, and the lower lane what happened around PyTorch in the same weeks (releases, status changes, foundation news). Click a release for its highlights and what it deprecated, both taken from the release notes on GitHub; the slider moves a date line and colours the atlas below the timeline by status as of that date, where a dated status change is known.
Old APIs and libraries you will still find in tutorials and in older code, with the replacement the project itself names. Interviewers like this table.
| Old | Use instead | When |
|---|
Pick a task, a scale and the hardware; the chooser names a stack, an alternative and what to avoid, each with the evidence from this tab. These are judgements, built from the statuses and source counts above, not measurements: the reasons say which fact each rests on so you can disagree with it. Parallelism theory (when ZeRO-3 beats TP, memory per GPU) belongs to Distributed Training; LoRA and QLoRA to PEFT; serving engines to Topic: inference-and-serving.
The small real runs behind this tab, on the CPU of an Apple M1 Pro with torch 2.14.1, each in src/map/checks/ with its output in src/map/inputs/checks/.
Data as of 2026-10-12. Generated from src/map/gen_data.py; versions from PyPI, statuses from each project's own pages, source counts from the released packages.
The child pages in reading order, the tabs of this page, the knowledge base pages it leans on and the best outside resources. Times for knowledge base pages are the reading times their headers state (2026-10-23); outside times are approximate. Links checked on 2026-10-12.
The header over storage, the walk down the dispatch keys, the autograd graph and its engine, version counters, custom Functions, checkpointing's mechanism; Reading sections 1 to 3 in depth. 27 min, plus 29 in closed details
Dynamo, guards, graph breaks and their fixes, recompiles and dynamic shapes, the partitioner, Inductor, modes, compiled autograd, caches, export; section 5 in depth. 37 min, plus 14 in closed details
The measured hunt, the profiler, the loop line by line, data loading, optimizers, mixed precision, memory, checkpointing, fused losses, attention kernels, torchao; sections 4 and 6 in depth. 38 min, plus 20 in closed details
Launch and process groups, collectives, DDP buckets and hooks, FSDP2, DTensor, TP and SP, CP, pipelining schedules, DCP, composing them, hangs; section 7 in depth. 36 min, plus 20 in closed details
Custom operators and opcheck, two traps under compile, C++ extensions, Metal, Triton and Helion kernels, tensor subclasses, dispatch modes; section 8 in depth. 35 min, plus 13 in closed details
The same loop through eight libraries, the defaults that change results, loss averaging, which library for which job; section 9 in depth. 27 min, plus 12 in closed details
The map: one training step from your loop down to the bytes, the cost of each layer on the running example compared, the definitions every child assumes, and the child pages. 31 min, plus 15 in closed details
All 923 operator calls of one real step with their dispatch routes, the graph and its saved tensors, memory over the step, checkpointing and no_grad on the same step, where the time goes. 12 min, plus 4 in closed details
torch.compile on the running example on CPU and MPS: graph, guards, breaks, recompiles, AOTAutograd's partition, Inductor's code, fusion, timing, export and AOTInductor. 20 min, plus 9 in closed details
The running example on 2 and 4 CPU processes: DDP, FSDP2 collectives, memory per rank, DTensor placements, TP, pipelining, DCP, hangs. 25 min, plus 4 in closed details
42 libraries with status, owner, licence, what they call in core, the same step through five entry points, releases 2.0 to 2.14 and a chooser. 14 min, plus 1 in closed details
Parallelism theory and memory math: ZeRO, TP, PP, EP. 32 min, plus 5 in closed details
What happens below Inductor. 37 min, plus 22 in closed details
Block-level kernels, autotuning. 37 min, plus 9 in closed details
Reductions, softmax, tiled matmul, fusion, FlashAttention. 34 min, plus 15 in closed details
Overlap, launch overhead, NCCL. 33 min, plus 15 in closed details
Nsight, honest timing, numerical checks. 28 min, plus 8 in closed details
Including PyTorch's caching allocator.
FLOPs, memory, MFU.
Why the network picks your parallelism.
Number formats behind AMP and torchao. 34 min, plus 11 in closed details
AdamW and friends.
LoRA and its family. 26 min, plus 2 in closed details
Failures, checkpoint and restart, and elastic training at scale.
The training stages these tools serve. 26 min, plus 22 in closed details
The GPU side of everything here. 28 min, plus 4 in closed details
vLLM, SGLang, serving. 34 min, plus 3 in closed details
Model file formats: pickle, safetensors, ONNX, ExecuTorch. 41 min, plus 49 in closed details, for the page
The algorithm behind SDPA's flash backend.
Neighbouring topics.
Strides, storage, dispatch, autograd, from a core developer. 40 min
Dispatch keys and tables. 25 min
Official notes: saved tensors, no_grad, inference mode, in-place. 30 min
autograd.Function, subclasses, modes. 30 min
torch.library custom_op, fake implementations, Triton ops. 20 min
Guards, graph breaks, specialisation. The old page's link to this moved. 50 min
Bytecode tracing and guards. 40 min
Edward Yang's troubleshooting guide. 1 h 15 min
Official TORCH_LOGS and bisection workflow. 25 min
The design of Dynamo and Inductor. 45 min
Full-graph capture and ahead-of-time packages. 30 min
The team's published A100 speed-ups (vendor). 15 min
Buckets and overlap. 20 + 45 min
The FSDP2 reference. 30 + 25 min
Placements and meshes. 25 + 15 min
Schedules; resharded checkpoints. 20 + 15 min
Debugging hangs. 15 min
FSDP2, TP, PP, CP and compile composed. 1 h + 45 min
Hugging Face's interactive guide to parallelism. 2 h or more
API reference. 20 min
The memory snapshot workflow. 35 + 10 min
Backends and their constraints. 20 min
score_mod, block masks, performance. 30 min
Low precision for training and inference. 45 + 15 min
The kernel language hosted by the Foundation. 30 min
What changed in January 2026. 20 min
Post-training trainers; YAML fine-tuning. 45 min each
The primary source on the wind-down. 15 min
Following the 2.x line. 10 to 20 min a month
Where compiler and distributed design is discussed. 30 min
Governance and hosted projects. 10 min each