Topic: pytorch-ecosystem

Reading: 30 min, plus 15 in closed details. The map of PyTorch from zero: one training step from your loop down to the bytes, how each layer (tensors, the dispatcher, autograd, the loop, torch.compile, performance, distributed, extending, the libraries on top) costs on one running example, and which child page owns it. Measured on an Apple M1 Pro and on CPU, with published GPU results kept apart. Data as of October 2026.

0. The map: one training step's life

The core idea
PyTorch runs your Python one operator call at a time, and every call walks down a table of kernels chosen by keys its tensors carry (autocast, autograd, device), with autograd recording on the way down the graph that backward walks back up; 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.

  1. One step, seven layers. Your loop (or a library running it) calls the model; 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.
  2. Your loop, or a library's. 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.
  3. Every call walks the dispatcher's keys. Autocast casts, Autograd records a node, Python hands the call to a subclass or mode, the backend key runs the kernel; keys with nothing to do are skipped. One step makes 923 calls: 142 in forward, 295 in backward, 486 in the default optimizer measured. Every extension plugs into one of these slots. Owner: Tensors, the dispatcher and autograd, whose Fig. 1 takes one torch.mm through three machines and Fig. 3 walks one call down the keys in seven situations. Lab: Inside one step. Section 2.
  4. Autograd records the graph on the way down. One node per differentiable call, keeping saved tensors: 187 nodes and 34.76 MB after one forward, against 12.75 MB of weights; backward walks the graph back from the loss and frees each node's saved tensors as it goes. Owner: Tensors, the dispatcher and autograd, whose Fig. 4 builds the graph of one block. Section 3.
  5. A kernel runs on a tensor's bytes. A tensor is a header (shape, strides, offset) over a flat storage: 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.
  6. torch.compile replaces the walk. Dynamo captures the forward behind guards (1 graph of 59 operations, 549 guards), AOTAutograd splits forward and backward, Inductor fuses: 142 calls become 35 launches per forward measured. Owner: torch.compile from the user's side, whose Fig. 1 follows one call into a compiled function, Fig. 2 a graph break frame by frame and Fig. 3 the cut between forward and backward. Lab: Compile lab. Section 5.
  7. Your own code plugs into a slot. A 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.
  8. The same step on every rank. DDP keeps a full copy per rank and all-reduces gradients (2 all-reduces a step); FSDP2 shards every parameter across the ranks and gathers a block only to use it (14 collectives a step); on the 25.3M-parameter variant the peak per rank falls from 548 MB to 249 MB on 4 ranks measured, CPU, gloo. Owner: Distributed PyTorch, whose Fig. 1 shows what each rank holds, Fig. 2 DDP's buckets, Fig. 3 one FSDP2 step and Fig. 4 placements. Lab: Distributed lab. Section 7.
  9. The profiler finds what is slow. On the CPU the step splits into forward 6.57, backward 10.54 and optimizer 5.41 ms of 22.51; the default for-loop AdamW is a quarter of it, and 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.

New terms
Operator: a named operation such as aten::addmm; ATen is PyTorch's C++ tensor library where every operator is defined.
Kernel: one compiled function that does the arithmetic of an operator on one device.
Dispatch key: a label (AutogradCPU, AutocastCPU, Python, CPU) that selects one kernel from an operator's table.
Storage, strides, view: the flat bytes; how many elements to step per dimension; a new tensor over the same bytes.
Saved tensors: what autograd nodes keep from forward for backward; they, not the weights, fill memory in training.
Guard, graph break: a condition under which compiled code stays valid; a spot Dynamo cannot capture, run eagerly between graphs.
Rank, collective: one process of a job; an operation every rank calls together (all-reduce, all-gather, reduce-scatter).
Placement: how a DTensor is split over ranks: Shard(d), Replicate(), Partial().

The comparison: one step of the running example, where its cost goes and which page fixes it

LayerWhat it costs on the running exampleThe lever, measuredOwner
Python and dispatch, per call142 calls per forward, 295 in backward, 486 in the default optimizer step measuredtorch.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 welltorch.compile from the user's side
The optimizer stepA quarter of the CPU step: the default for-loop AdamW launches several small operations per parameter tensorfused=True: the optimizer phase 2.7 times faster on the CPU and 4.1 times on MPSMaking training fast, section 5
Saved activations34.76 MB after one forward, against 12.75 MB of weightsCheckpointing 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 CPUMechanism: Tensors, the dispatcher and autograd, 3.6; the trade: Making training fast, section 9
Autograd when no gradient is neededOne 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 MPSinference_mode for serving, no_grad for evaluationTensors, the dispatcher and autograd, 3.5
Weights and optimizer state per processOn the 25.3M-parameter variant, 303 MB of weights and AdamW state on every DDP rankFSDP2 on 4 ranks: the peak from 548 MB to 249 MB, for 14 collectives per step against DDP's 2 all-reducesDistributed PyTorch, sections 3 and 4
A library's defaultsThe Hugging Face Trainer clips at 1.0, decays the learning rate and shuffles by default, so a ported loop no longer matchesMatched defaults: the same three losses, 3.80137, 3.18793, 3.16783, from a plain loop, Lightning, the Trainer and AccelerateLibraries on top of PyTorch, sections 1 and 2
Code PyTorch does not shipA Python function in the middle of a model breaks the compiled graph; a backward registered too late silently drops gradientsA custom operator with a fake implementation is one graph node; register everything before anything tracesExtending 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.

1. Tensors: a header over bytes

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).

address of x[i, j] = offset + i × stride0 + j × stride1

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).

Go deeper: Tensors, the dispatcher and autograd, section 1 (strides against .contiguous() stepped, memory formats, dtypes and promotion, pinned memory), its Fig. 2 (one storage under many headers) and its Stride explorer tab.

2. The dispatcher: one table of kernels per operator

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).

Why the dispatcher spans the whole topic: it is the extension point
Everything that changes PyTorch's behaviour without changing your model plugs in as a kernel for some key: autograd itself, autocast, a new device (MPS, XPU and out-of-tree backends register their own keys), functionalisation for the compiler, 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).
Go deeper: Tensors, the dispatcher and autograd, section 2 (the keys in priority order, one call walked key by key in its Fig. 3, table slots, autocast, functionalisation and fake tensors, what dispatch costs); the Inside one step tab draws the route of every call of a real step.

3. Autograd: the graph built during forward

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).

Go deeper: Tensors, the dispatcher and autograd, section 3 (the graph built in forward, drawn for one block in its Fig. 4, and run by the engine, version counters, 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.

4. nn.Module, the optimizer and the loop

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:

# one training step (device = "cuda", "mps" or "cpu") model.train() opt = torch.optim.AdamW(groups, lr=6e-4, betas=(0.9, 0.95), weight_decay=0.1, fused=True) # section 6 for step in range(steps): for micro in range(accum): # gradient accumulation x, y = get_batch(cfg, step * accum + micro, device) # seeded: batch k is the same on every run with torch.autocast(device, dtype=torch.bfloat16): # the Autocast key of section 2 logits, loss = model(x, y) (loss / accum).backward() # gradients add up across micro-batches torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) opt.step(); sched.step() opt.zero_grad(set_to_none=True)

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.

What this page measured and read for this section, in full (optional)
  • Mixed precision (AMP). 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).
  • Determinism. Seed everything (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.
A framework is a set of defaults
That identical-loss result needed the Trainer's defaults switched off. Out of the box, the Hugging Face Trainer at 5.19.0 clips gradients at 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.

Go deeper: Making training fast, section 7 owns the loop line by line (registration, state_dict and tied weights, accumulation, unscale before clipping, the GradScaler, zero_grad, determinism and DataLoader seeding); optimizer algorithms are on Optimisers; how libraries run this loop for you, and their defaults, on Libraries on top of PyTorch.

5. Eager or compiled: torch.compile

Fig. 2 · the same forward down the stack: 142 calls eagerly, 35 launches compiled

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:

TorchDynamo
capture

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.

AOTAutograd
forward + backward

Traces through autograd ahead of time into a forward and a backward graph, and decides which values backward keeps and which it recomputes.

TorchInductor
codegen

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.

  1. Your code calls the model. 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.
  2. Python runs the forward, line by line. Embeddings, 4 blocks (LayerNorm, attention, MLP), the final norm, the tied output layer and the loss. Every line calls a torch function.
  3. Each call goes through the dispatcher. The inputs carry the keys CPU, ADInplaceOrView, AutogradCPU and AutocastCPU; each call walks them (section 2). One forward makes 142 such calls.
  4. The autograd key records the graph. For every call that needs a gradient, the autograd kernel adds a node and keeps tensors for backward: 135 nodes and 34.76 MB of saved activations after one forward (section 3).
  5. A kernel does the arithmetic, one call at a time. Matrix multiplies go to the BLAS library, attention to a CPU flash kernel, and each small element-wise operation reads its input from memory and writes its output back.
  6. Eager: 142 calls, each paying its own overhead. Simple, debuggable, and every call costs Python and dispatch time plus a memory round trip. Forward 6.52 ms on the CPU.

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.

What this page measured and read for this section, in full (optional)

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.

Go deeper: torch.compile from the user's side (Dynamo, guards, every kind of break and its fix, recompiles and dynamic shapes, the partitioner, Inductor, modes, compiled autograd, regional compilation, caches, export, debugging), whose Fig. 1 follows one call into a compiled function, Fig. 2 a graph break frame by frame and Fig. 3 the cut between forward and backward; the Compile lab measures this model on CPU and MPS; codegen below Inductor is The compiler stack.

6. Performance: measure the step, then fix the largest part

Fig. 3 · the optimizer, a few element-wise updates, is a quarter of the step; one argument fixes it

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:

  1. Measure the phases first. Forward 6.57 ms, backward 10.54 ms, optimizer 5.41 ms: 22.51 ms per step.
  2. The surprise: the optimizer is a quarter of the step. AdamW takes 24% of the step. The default for-loop implementation makes 486 operator calls per step, against 142 for the whole forward.
  3. The fix: one argument, 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.
  4. Measure again. Measured with the fused optimizer: 19.08 ms per step, 1.18 times faster, matching the prediction. torch.compile, by contrast, gave nothing here (section 5): fix the bottleneck you measured, not the one you expect.

The symptom decides the tool, and the tools span several pages:

SymptomToolUsual fixOwner
Out of memoryMemory snapshot: torch.cuda.memory._record_memory_history(), run, _dump_snapshot("s.pickle"), open in memory_vizCheckpointing, a smaller micro-batch with accumulation, sharding, a fused lossMaking training fast, 8 to 10; sharding: Distributed PyTorch, 4
Slow, cause unknowntorch.profiler, trace opened in PerfettoRead the trace: which phase, which kernels, where the GPU idlesMaking training fast, 2 and 3
GPU idle between kernelsProfiler: gaps on the GPU timeline, CPU busy launchingtorch.compile, CUDA graphs (mode="reduce-overhead"), fused optimizertorch.compile, 7; Streams, CUDA graphs and multi-GPU
CPU waits for the GPU every stepProfiler: synchronisations or device-to-host copiesRemove .item(), .cpu(), printing the loss every stepMaking training fast, 1
Attention slow or memory-hungryWhich SDPA backend ranKeep inputs eligible for a fused backend, or FlexAttentionMaking training fast, 11
Data loadingProfiler: gaps before forwardnum_workers, pin_memory=True, pre-tokenised dataMaking training fast, 4
Hang across ranksFlight recorderFind the rank that called a different collectiveDistributed 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.

What this page measured and read for this section, in full (optional)

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).

Go deeper: Making training fast: profiling, memory, attention, torchao, whose Fig. 2 fixes one bottleneck at a time and Fig. 3 reads a profiler trace before and after (the measured hunt, the profiler, data loading, optimizers, mixed precision, memory, checkpointing, fused losses, SDPA and FlexAttention, torchao); honest timing and Nsight on Profiling, benchmarking and correctness; the caching allocator on Memory allocators; FLOPs and MFU on Performance math.

7. Distributed: the same program in several processes

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.

Fig. 4 · peak memory per rank, DDP against FSDP2

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:

FromToCollectiveWhere you meet it
Shard(0)Replicate()all-gatherFSDP2 gathering a block's weights
Partial()Replicate()all-reduceDDP gradients; the output of a row-parallel matrix multiply
Partial()Shard(0)reduce-scatterFSDP2 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).

What this page measured and read for this section, in full (optional)

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.

FromToCollectiveWhere you meet it
Shard(0)Shard(1)all-gather, then a local slice at 2.14.1Changing 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).

What carries over to NVIDIA GPUs, and what does not
Carries over: which collectives run, in what order, with what sizes (except gloo's reduce-scatter), bucket layouts, sharding and memory per rank, DCP files, the hang diagnostics (the flight recorder works on any backend at 2.14). Does not: speed. Gloo over local sockets is nothing like NCCL over NVLink, so no step time from these runs predicts a GPU cluster; overlap of communication with compute, the reason buckets and prefetching exist, only pays where communication is fast and asynchronous. Two macOS quirks met on the way: 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.
Go deeper: Distributed PyTorch: c10d, DDP, FSDP2, DTensor, TP, PP, DCP (launch and the store, collectives and their cost, DDP buckets and hooks, FSDP2, DTensor, TP and SP, CP, pipelining schedules, DCP, composing them the torchtitan way, debugging hangs); the Distributed lab has each run with its error texts; NCCL and overlap on Streams, CUDA graphs and multi-GPU; links on Interconnects and scaling.

8. Extending PyTorch: plug into one slot of the call path

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.

What this page measured and read for this section, in full (optional)
HookWhat it changesUse it forUnder compile and export
Plain PyTorch codeNothing; composes existing operatorsMost new layersTraced like any code
torch.autograd.FunctionThe backward of a piece of codeA custom or more stable gradientTraced if forward and backward are traceable
torch.library.custom_opAdds a new operator to the dispatcher, opaque to the compiler; register_fake says what shape it returns, register_autograd its backwardCode the compiler cannot or should not trace: C++ or CUDA kernels, calls into other librariesOne node in the graph, no break
torch.library.triton_op with wrap_tritonA Triton kernel registered as an operatorYour 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 keyNew representations: DTensor (sharded), torchao's int8 and float8 weights, NF4Supported for subclasses written to the traceable-subclass protocol
TorchDispatchModeSees every operator call while activeRecorders, debuggers, counting FLOPs (the Inside one step recorder is one)Eager tool
A new backend key (PrivateUse1)A whole deviceHardware vendorsThrough 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.

Go deeper: Extending PyTorch: custom ops, tensor subclasses, kernels, whose Fig. 1 shows which slot each kind of extension fills, Fig. 2 one forward as Dynamo recorded it with a custom operator and Fig. 3 one weight as a tensor subclass (its comparison table of every hook, custom ops and opcheck, the two traps, C++ extensions, Metal, Triton and Helion kernels, subclasses, dispatch modes); kernels themselves on Triton and Gluon and Writing kernels.

9. The ecosystem: what sits on top, and what is alive

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 wantReach forStatusIn one line
Pretraining at scale, PyTorch-native, full controltorchtitan 0.3.0activePyTorch'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 loopAccelerate 1.15.0activeDDP, FSDP2 and DeepSpeed behind one object
Standard fine-tuning (SFT, DPO, GRPO) with little codeTRL 1.15.0, PEFT 0.21.2, or Axolotl 0.20.0 (YAML)activeBreadth of recipes and day-one model support, for defaults you did not choose
Structured research code, not only LLMsLightning 2.6.6 (or Fabric to keep your loop)activeCallbacks, logging, checkpointing; new LLM parallelism lands here later
Largest-scale NVIDIA trainingMegatron Core 0.19.2; DeepSpeed 0.19.7activeMegatron: GPU-optimised TP/PP/CP/EP; DeepSpeed: ZeRO and offload, a PyTorch Foundation project since May 2025
Running on phones and laptopsExecuTorch 1.5.1activeBuilt on torch.export; "part of PyTorch Core" since April 2026
Fine-tuning recipes from PyTorchtorchtune 0.6.1no longer maintainedActive development stopped 2025-07-15 (issue 2883); do not start on it
RL post-training from PyTorchtorchforgepausedREADME: development paused, "LLM training at PyTorch is being consolidated in torchtitan"
Serving PyTorch modelsTorchServearchivedFor LLMs use vLLM or SGLang (Topic: inference-and-serving)
Composer, Colossal-AI, torchaudio, NeMo (LLM side)quiet or maintenanceComposer'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.

Go deeper: Ecosystem map (the atlas, "what calls what" from released source, releases 2.0 to 2.14, the chooser, and the same training step through five entry points); child page Libraries on top of PyTorch: HF stack, torchtitan, Lightning, Axolotl, DeepSpeed, whose Fig. 1 gives the loop's eight duties to six libraries and Fig. 2 records one step call by call (the defaults that change results, loss averaging under accumulation, the HF stack, Lightning, torchtitan and DeepSpeed run on the same step).

10. Child pages

Each child owns one layer in depth on the same running example; read them in this order, or jump to the layer you need.

Tensors, the dispatcher and autogradChild page, about 27 min, plus 29 in closed details.The header over storage, the walk down the dispatch keys, the autograd graph and its engine, version counters, custom Functions, checkpointing's mechanism.
torch.compile from the user's sideChild page, about 36 min, plus 14 in closed details.Dynamo, guards, graph breaks and their fixes, recompiles and dynamic shapes, the partitioner, Inductor, modes, compiled autograd, regional compilation, caches, export, debugging.
Making training fast: profiling, memory, attention, torchaoChild page, about 38 min, plus 20 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.
Distributed PyTorch: c10d, DDP, FSDP2, DTensor, TP, PP, DCPChild page, about 35 min, plus 20 in closed details.Launch and process groups, collectives, DDP buckets, FSDP2, DTensor, TP and SP, CP, pipelining, DCP, composing them, debugging hangs.
Extending PyTorch: custom ops, tensor subclasses, kernelsChild page, about 34 min, plus 13 in closed details.Custom operators and opcheck, the two traps under compile, C++ extensions, Metal, Triton and Helion kernels, tensor subclasses, dispatch modes.
Libraries on top of PyTorch: HF stack, torchtitan, Lightning, Axolotl, DeepSpeedChild page, about 27 min, plus 12 in closed details.The same loop through eight libraries, the defaults that change results, loss averaging under accumulation, which library for which job.

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).

Common mistakes, one line each (optional)
Timing GPU code without synchronising
GPU work is queued and returns at once; time.perf_counter() around it measures the launch. Synchronise before reading the clock, warm up, repeat, report medians (or use torch.utils.benchmark.Timer).
Calling .item() or printing the loss every step
Each one makes the CPU wait for the GPU, and under torch.compile it is a graph break (section 5). Log every N steps, or keep a running tensor and read it rarely.
Using no_grad to save memory while training
No graph, so no backward (section 3). Use activation checkpointing, a smaller micro-batch with accumulation, or sharding.
Assuming reshape never copies, or that view always works
view fails on non-contiguous tensors; reshape silently copies (section 1). In-place writes through a view change the original.
Accumulating gradients without dividing the loss, or without no_sync under DDP
The first gives a gradient N times too large (and dividing is exact only when every micro-batch counts the same number of tokens); the second pays an all-reduce per micro-batch (sections 4 and 7).
Expecting torch.compile to speed up anything
On this laptop's CPU it gave nothing; on MPS 1.18 times. Measure; then check breaks and recompiles (varying shapes, eval() versus train(), Python scalars that change).
float16 without a GradScaler
Small gradients underflow to zero. Use bfloat16 where the hardware supports it, or torch.amp.GradScaler.
Moving a loop into a framework and expecting the same run
Defaults differ: the Hugging Face Trainer clips at 1.0, decays the learning rate linearly and shuffles (section 4); DeepSpeed also clips at 1.0 by default since 0.19.3 (section 9).
A collective that only some ranks call
An if rank == 0: all_reduce(...), uneven data, or a different tensor shape on one rank hangs the job until the timeout (section 7).
Starting new work on torchtune, TorchScript or the FSDP1 wrapper
torchtune is no longer maintained, TorchScript is deprecated, and FSDP2's fully_shard is where the work goes (section 9).
Loading untrusted checkpoints with weights_only=False
A pickle can run code. Keep the default weights_only=True (since 2.6) or use safetensors.
Interview rehearsal, with short answers (optional)
Why does x.t().view(-1) fail, and what does reshape do instead?
The transpose has strides (1, 4): its elements in order are not adjacent in storage, so no single stride can describe a flat view. reshape returns a view when possible and otherwise copies.
What happens between torch.mm(a, b) and the BLAS call?
The dispatcher computes the call's key set from the inputs and thread-local state and runs the highest-priority kernel: autocast may cast, autograd records 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?
Both stop graph recording. 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.
What takes memory in training a model with AdamW?
Parameters, gradients (same size), optimizer state (two more copies), and saved activations, which grow with batch and sequence length. Running example: 12.75 + 12.75 + 25.5 MB of model state against 34.76 MB of activations at batch 8 by 64.
How does activation checkpointing trade memory for compute?
It keeps only a region's inputs and re-runs the region in backward. Running example: 34.85 to 3.33 MB added by forward, 112 recomputed calls, 22.5 to 31.6 ms per step on the CPU.
Guards, graph breaks and recompiles: what are they?
Guards are the conditions under which a compiled graph is valid; when one fails, Dynamo recompiles (up to 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".
Why might torch.compile not speed a model up?
The time is in operations it does not change (large matrix multiplies already in cuBLAS or BLAS), the step is dominated by something else (data, the optimizer, communication), or breaks and recompiles eat the gain. Profile first.
for-loop, foreach or fused optimizer?
Same maths; the for-loop launches small operations per tensor, foreach batches each operation over all tensors, fused does the whole update in one kernel. Fused was 2.7 times faster than the default on this CPU and 4.1 times on MPS for the optimizer phase.
DDP or FSDP2?
See section 7: DDP keeps a full copy per rank and all-reduces gradients; FSDP2 shards every parameter and gathers it only when needed, cutting memory per rank for more communication.
What is a DTensor?
A tensor plus a device mesh plus one placement per mesh dimension (Shard(d), Replicate(), Partial()); operators propagate placements and insert the collectives needed. FSDP2, tensor parallelism and distributed checkpoints are built on it.
A multi-GPU job hangs. What do you do?
Find which rank is in which collective: the flight recorder dump (or py-spy on each rank), 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).
Which stack for: pretraining from scratch on 512 GPUs; LoRA on one GPU; your own loop on Hugging Face models?
torchtitan (or Megatron Core on an NVIDIA-committed stack); PEFT with TRL, or Axolotl, or Unsloth for single-GPU speed; Accelerate (or Lightning Fabric).