A training step is slow or out of memory for one main reason at a time: measure where its time and its peak memory go, fix the biggest piece with the lever aimed at it, and measure again.
The job is the topic's running example (a small GPT, see the root page) and its larger variant (8 blocks, d 512, 8 heads, context 256, batch 8: 25.4M parameters), measured on an Apple M1 Pro's CPU and GPU. Every result says what carries over to NVIDIA GPUs. Fig. 1 is one step of the larger variant on the Apple GPU, as first written: every lever on this page aims at one part of its time or its memory.
Fig. 1, step by step
.item() sync lets the CPU run ahead (3). What is left is matmuls, measured by MFU (3).measured on Apple M1 Pro, PyTorch 2.14.1: phases on MPS with a synchronize after each (section 3); memory alive at the peak, float32 (section 8). Section numbers in brackets. Lever labels on the figure name the part each one shrinks; drag to turn the scene.
F.scaled_dot_product_attention, one call, several kernels.item(), printing, copying to the CPU). Timings and traces must account for that.torch.utils.benchmark.Timer (section 1)..item() for the GPU (sections 2, 3).torch.compile are not automatic wins (sections 3 to 6).Labels: measured here (src/exp/), vendor, derived, illustrative. Timed runs held a lock so no other job of this knowledge base ran at the same time; the load average is quoted next to them.
Every fix is judged by a number, and three things make a naive timing lie. Asynchronous devices: on a GPU (CUDA or Apple's MPS) a PyTorch call only queues a kernel and returns, so you must wait for the device (torch.cuda.synchronize(), torch.mps.synchronize()) before reading the clock. Warm-up: the first calls pay one-off costs (memory allocation into the caching allocator, kernel selection, compilation for torch.compile, lazy initialisation); run a few untimed steps first. Noise: other processes, thermal limits and frequency scaling move every number; repeat, report the median and the spread, and record the machine's load.
torch.utils.benchmark.Timer does the bookkeeping: it warms up, chooses how many runs fit in a time budget, sets the thread count, and reports the median and interquartile range (IQR, the spread of the middle half of the runs). At 2.14.1 its default clock calls torch.accelerator.synchronize() before every reading whenever an accelerator is present, CUDA or MPS alike (torch/utils/benchmark/utils/timer.py L15 to 18), so the synchronize inside this page's timed statement is redundant but harmless:
Whole training steps: warm up, synchronise, time N steps, synchronise, divide; median of three. What carries over to NVIDIA GPUs: the method, byte and op counts, which fixes apply; not the times (a fix that wins 20% here can win 2% or 2 times on an H100). CUDA events and Nsight: Profiling, benchmarking and correctness.
A step time says how slow, not where. torch.profiler records every operator PyTorch runs (start, end, thread; input shapes, Python stack and memory if asked) and, on CUDA, every GPU kernel and copy. Its output is a trace, a timeline you open in Perfetto or chrome://tracing.
The schedule records a few steps instead of the whole run; record_function ranges are cheap labels worth leaving in a loop for good; key_averages() sums events by name, where total time includes children (aten::linear includes its aten::addmm) and self time excludes them: sort by self time to find the ops doing the work.
What to look for. On a GPU the device lane should be busy end to end. A gap means the GPU waited: for the data loader (gaps before forward), for a CPU launching many tiny kernels (launch-bound), or for a synchronisation such as .item(), .cpu() or print(loss). In multi-GPU traces: communication that does not overlap compute. On a CPU the bars are the work. Launch-bound fixes: fusion (torch.compile), fused optimizers (section 5) and CUDA graphs, one recorded sequence of launches replayed with one call; torch.compile(mode="reduce-overhead") "reduces the overhead of python with CUDA graphs, useful for small batches", at the cost of memory, CUDA only (torch.compile from the user's side; mechanism: Streams, CUDA graphs and multi-GPU). Not measured here: this Mac has no equivalent.
schedule(wait, warmup, active, repeat) skips wait steps, runs the profiler without keeping results for warmup steps (its own start-up cost lands there), then records active steps; repeat cycles it; prof.step() at the end of each step drives it. Signature at 2.14.1: schedule(*, wait, warmup, active, repeat=0, skip_first=0, skip_first_wait=0) read from the installed wheel.with_stack=True links each op to the Python line that called it (larger traces); profile_memory=True records allocations (section 8). On CUDA with compiled code, TORCHINDUCTOR_UNIQUE_KERNEL_NAMES=1 gives generated kernels readable names.tensorboard_trace_handler(dir) writes files for TensorBoard; for many ranks at once, Holistic Trace Analysis summarises idle time, communication overlap and stragglers across ranks.with_stack=True and profile_memory=True traces get large and steps slow; the schedule is what keeps it to a few steps.The job. The larger variant trained through a DataLoader, written the way a first version usually is:
The dataset spends 2 ms of Python work per sample before returning a window of text illustrative cost: a stand-in for decoding and tokenising raw data, set by hand so that data loading is visible. Everything else is the real model.
Fig. 2 builds the step time fix by fix: each block is the median of three runs of 20 steps, compared with the block it was built on; a fix that is slower beyond the spread of both steps aside (to the back) and is reverted, and the next fix is built on the last kept block.
.item() every step the CPU can queue the next step while the GPU works; here the GPU is the bottleneck, so overlap buys little..item() costs nothing (no device to wait for); its range overlaps step 4's, so the difference is noise.In sum: on MPS 162 ms became 134 ms (1.21 times faster), and the biggest gain was the least glamorous, DataLoader workers (15.9 ms); on the CPU 429 ms became 362 ms (1.19 times), led by the attention kernel. bfloat16 autocast lost on both (on the CPU 43.7 seconds per step, 2 runs of 3 steps). On an NVIDIA GPU the ranking would likely change; the method would not.
measured on Apple M1 Pro, PyTorch 2.14.1; per stage the median of 3 runs of 20 steps after 8 warm-up steps, timed with a synchronize at both ends; bench lock, load average quoted in the recorded inputs (src/exp/hunt.py). Each stage is compared with the stage it was built on: kept when faster beyond the spread of both; within the spread is no measurable change; slower beyond it is reverted. bfloat16 and compile are each tried on top of stage 5 (no per-step sync); compile and bfloat16 together on top of compile. Block heights are to scale with the median; the CPU's bfloat16 block is cut at 1.3 times the baseline.
Two real torch.profiler traces of one MPS step: as first written, and with the fixes the hunt kept. Lanes are threads: the main thread runs the record_function ranges, a second lane is autograd's device thread running backward.
num_workers=0 the main thread builds the batch itself: the Dataset's Python work runs right here, and nothing else happens.addcmul_ and addcdiv_ 100 calls each), every one a launch..item() copies one number to Python, so it must wait until every queued GPU kernel has finished: this bar is the GPU's backlog showing up on the CPU (aten::_local_scalar_dense).aten::copy_, 123.7 ms of a 124.1 ms data range).The wait moves; it does not vanish. On MPS the CPU only enqueues work, so the GPU's timeline is not in this trace (Fig. 3 marks its lane as not recorded; on CUDA ProfilerActivity.CUDA adds it, on MPS it goes to Instruments via torch.mps.profiler.profile()). The 117.6 ms in .item() is every queued kernel finishing; after the hunt the same wait sits in the next batch's copy.
Two real torch.profiler traces: as first written, and with the fixes the hunt kept. Lanes are threads. Top row: the record_function ranges; below, the ATen ops they called, nested; a second lane is autograd's device thread running backward.
How close to the hardware's limit? Model FLOPs utilisation (MFU) = model FLOPs per step / step time / peak. One step needs 6 × 25,373,184 parameters × 2,048 tokens = 311.8 GFLOP plus 12 × L × T × d per token for attention (12 × 8 × 256 × 512 × 2,048 = 25.8 GFLOP): 337.6 GFLOP derived. With this GPU's measured float32 matmul rate as the peak (4,087.5 GFLOP/s, section 6; Apple publishes none), MFU = 337.6 / 0.162 / 4,087.5 = 51% as first written and 62% after the hunt; on the CPU (1,854.3 GFLOP/s) 42% and 50% derived, src/derive_mfu.py. The fixes removed overhead around the matmuls; what remains is matmuls. Peaks of real GPUs and MFU of published runs: Performance math.
With DataLoader(num_workers=0) (the default) the main process reads, decodes and collates every sample itself, between steps, so loading time adds straight onto step time. num_workers=n starts n worker processes that build whole batches in the background; prefetch_factor (default 2 when workers are used) is how many batches each keeps ready; persistent_workers=True keeps them alive between epochs instead of paying their start-up each epoch.
Without workers, every step waited 16.1 ms for its batch (8 samples × 2 ms) and took 44.5 ms. One worker builds the next batch while the step runs, and the wait fell to 0.22 ms; with two the step took 27.6 ms, within a millisecond or two of the loop with free data (27.1 ms). More workers or a deeper prefetch changed nothing here, because one worker already kept up; they help when loading is slower than the step, or uneven.
When it matters: decoding images or audio, tokenising on the fly, network storage, heavy augmentation; pre-tokenised data in memory-mapped arrays (as LLM pre-training usually uses) barely needs workers. Check: the data range in a trace (or gaps on the GPU before forward), or time next(iter(loader)) alone. On CUDA add pin_memory=True (page-locked host memory) so x.to("cuda", non_blocking=True) copies asynchronously.
Workers are separate processes: each holds its own copy of the Dataset, so keep it small; on macOS and Windows they start with spawn, so the Dataset must be importable and picklable. On an Apple chip CPU and GPU share one memory, so pin_memory was not measured here (signature at 2.14.1 includes pin_memory_device and in_order, read from the installed wheel).
In short: workers on macOS start with spawn; each worker seeds torch, random and NumPy; in the main process torch.manual_seed does not seed Python's random or NumPy. pin_memory=True on MPS warned "'pin_memory' argument is set as true but not supported on MPS now, device pinned memory won't be used." Defaults worth knowing at 2.14.1: prefetch_factor 2 batches per worker when num_workers > 0 (dataloader.py L293), workers restarted every epoch unless persistent_workers=True.
AdamW's update is a few element-wise ops per parameter tensor. The for-loop implementation calls them for each tensor in turn (100 tensors in the larger variant, 52 in the small one), each call with Python and dispatcher overhead and, on a GPU, a launch. foreach uses torch._foreach_* operators that take a whole list of tensors per call; fused does the whole update for all parameters in one kernel per device and dtype group (torch.optim.AdamW(..., foreach=True) or fused=True). At 2.14.1 the default is foreach on CUDA-like devices and the for-loop on CPU and MPS; fused is never the default though it runs on CPU, MPS and CUDA (torch/utils/_foreach_utils.py L8 to 23, per the root's Inside one step measurements).
Larger variant: fused 9.17 ms against 28.5 ms for the for-loop on the CPU (3.1 times), 7.67 ms against 25.0 ms on MPS (3.3 times); foreach within a few percent of the for-loop (26.7 and 24.5 ms), because each foreach op still makes a full pass over every tensor, while fused makes one pass for the whole update. It matters most with many small tensors, or a fast device where launches dominate. On CUDA foreach is already the default; fused is the switch to try (it needs every parameter on a supported device and dtype). What AdamW computes: Optimisers.
opt.step() alone)bfloat16 and float16 use 2 bytes per number against float32's 4: half the memory traffic and, on GPUs with tensor cores, much faster matmuls. Automatic mixed precision (AMP): inside torch.autocast(device_type, dtype=torch.bfloat16), ops on autocast's lists (matmuls, linear layers, attention) run in 16 bits, precision-sensitive ops (softmax, normalisation, losses) stay in float32, and the parameters stay float32. On the CPU the running example's step under bfloat16 autocast produced bfloat16 logits, a float32 loss and float32 gradients on float32 parameters measured: autocast changes the compute, not the weights or the optimizer. The formats themselves belong to Quantization and Precision.
bfloat16 keeps float32's 8 exponent bits: no overflow or underflow beyond float32's, so no loss scaling; the usual choice on recent GPUs. float16 has 5 exponent bits: below 2−14 it loses precision and below 2−24 it cannot represent a value at all, so small gradients vanish. torch.amp.GradScaler multiplies the loss by a scale (default 216 = 65,536) before backward, so every gradient is 65,536 times larger while in float16, then divides it out before the step; if any gradient overflowed to inf or NaN it skips the step and halves the scale, and every 2,000 clean steps it doubles it (defaults init_scale=2.0**16, growth_factor=2.0, backoff_factor=0.5, growth_interval=2000, grad_scaler.py L126 to 129 at v2.14.1).
Four steps of the running example with float16 autocast on the CPU: losses 3.80133, 3.18798, 3.16783, 2.9406, scale 65,536 throughout (no overflow, and far from 2,000 steps) measured. With clipping, the order matters: section 7.
measured on the running example's step-0 float32 gradients (CPU; recorded by the sibling Tensors, the dispatcher and autograd): 1,636 below 2−24 would flush, 436,592 below 2−14 lose precision; scaled, 58 and 1,031, and the largest becomes 33,812, under float16's 65,504. Axis in powers of two; the bar spans the nonzero magnitudes.
A 2,048-square matmul ran at 1,854.3 GFLOP/s in float32 on the CPU and 2.1 in bfloat16; on MPS 4,087.5 against 2,180.1 (float16: 4,276.9). The larger variant's training step with autocast(bfloat16): 44.0 s against 393 ms on the CPU, 216 ms against 149 ms on MPS. Bars are capped at 3 times.
sysctl hw.optional.arm.FEAT_BF16 = 0, FEAT_FP16 = 1) read on this machine, so bfloat16 is converted and pays for it; the MPS slowdown points the same way (not checked against Apple documentation). What transfers: check native support for the dtype before expecting a speedup, and measure.Every lever changes one line of the same loop, whose own rules decide whether a fix is correct. nn.Module adds bookkeeping, not a new machine: assigning an nn.Parameter to a module attribute registers a parameter (a leaf tensor with requires_grad=True that optimisers update), assigning a module registers a sub-module, and register_buffer registers a buffer (saved, not trained; persistent=False keeps it out of the state_dict). parameters(), .to(), state_dict() and train()/eval() walk that tree, and a state_dict is names over storages.
The running example ties its output head to its token embedding (head.weight is tok.weight). parameters() de-duplicates by object, the state_dict does not, so parameters() counts 52 tensors and the state_dict 53 (3,197,952 elements against 3,186,944) measured. Consequences: safetensors refuses to save the shared storage, two different values loaded under the two names leave the later one, and to_empty unties them (details below).
self.training on every sub-module; dropout and batch norm read it. It does not touch gradients.enabled=False every scaler call passes through..grad becomes None, freeing 12,747,776 bytes here until the next backward; set_to_none=False fills them with zeros. Code that reads p.grad afterwards must handle None.measured on the running example, CPU, PyTorch 2.14.1 (recorded by the sibling Tensors, the dispatcher and autograd, its exp/module_loop.py): four micro-batches of 2 with each loss divided by 4 gave the same gradient as one batch of 8 (norm 11.1032); without the division the norm was 44.41, exactly 4.00 times too large. clip_grad_norm_ returned the norm before clipping (11.1032 at step 0). zero_grad freed 12,747,776 bytes of gradients.
Three rules follow. Gradients accumulate into .grad across backwards, so micro-batch losses must be divided by their number; this is also a memory lever, because activations scale with the micro-batch while the gradient is that of the whole batch (section 8). A GradScaler's gradients must be unscaled before clipping, or you clip a gradient 65,536 times too large and the threshold means nothing. Log the norm clip_grad_norm_ returns: it is the cheapest training-health signal you have.
Determinism. Seed with torch.manual_seed and make the data order a function of the step, as get_batch(cfg, step) does (it made the first three losses identical across a plain loop and three frameworks on the root's Ecosystem map tab). In short: CPU with a fixed thread count was bit-for-bit repeatable; 1 against 4 threads differed in the last bits (max parameter difference 1.46e-06); MPS was not bit-repeatable even with use_deterministic_algorithms(True), which raised nothing measured. A seed fixes the random numbers but not where they land on a GPU: PyTorch's CUDA normal_ and uniform_ launch, for a large tensor, as many threads as the GPU holds at once (2,048 per SM times the SM count, G), and thread t fills positions t, t + G, t + 2G, ..., so torch.cuda.manual_seed plus normal_ gives a different tensor on a 132-SM H100 than on a 148-SM B200; initialise on the CPU, or on one GPU type, if weights must match across machines (the layout is readable from released checkpoints: Top Chinese Frontier AI Models Carry the Fingerprint of Export-Controlled NVIDIA Blackwell GPUs).
safetensors: "Some tensors share memory, this will lead to duplicate memory on disk and potential differences when loading them again"; save_model writes 52 tensors and drops tok.weight, and load_model restores the tie.
state_dict hold, counting each entry's tensor?tok.weight is all 1.0 and whose head.weight is all 2.0 into the tied model. What is model.tok.weight[0, 0] afterwards?load_state_dict matches by name. With the default strict=True, a renamed key (here blocks.0.ln1.weight saved as blocks.0.ln_1.weight) raised:
With strict=False nothing is raised and the call returns ; the missing parameter silently keeps its initial value. Check the return value, always. A shape mismatch is an error even with strict=False: "size mismatch for blocks.0.mlp.fc.weight: copying a param with shape torch.Size([512, 256]) from checkpoint, the shape in current model is torch.Size([1024, 256])."
register_forward_pre_hook sees a module's inputs before forward, register_forward_hook its inputs and output after; both may replace them. They are the standard way to read activations without editing the model: one hook per block of the running example, one batch, collected the output standard deviation per block, 0.0495, 0.0659, 0.0799 and 0.0924 measured, the residual stream growing block by block as expected at initialisation. Backward hooks are on Tensors, the dispatcher and autograd.
The thread count changes the order of floating-point sums, hence the last bits. On CUDA, use_deterministic_algorithms(True) swaps in deterministic kernels where they exist and raises a RuntimeError for operations without one, and torch.backends.cudnn.benchmark = False stops cuDNN from picking algorithms by timing (not run here).
Sources: Reproducibility notes, 2.14; use_deterministic_algorithms (the 2.14 docs list, for example, torch.histc on CUDA as an operation without a deterministic kernel).
Five things live in memory during training (float32, AdamW, P parameters): parameters, 4 bytes × P, always; gradients, 4 bytes × P, built layer by layer in backward, freed by zero_grad(set_to_none=True); optimizer state, 8 bytes × P from the first step(); activations, saved by forward for backward, scaling with batch × sequence length; and short-lived temporaries. The fixed cost is 16 bytes per parameter (4 + 4 + 8); mixed-precision training with float32 master weights also comes to 16, split differently (2 + 2 + 12 in the ZeRO paper's accounting; Distributed Training owns that arithmetic and how sharding divides it).
Fig. 4, step by step. The peak is a moment: memory by category through one step of the larger variant, plain behind, checkpointed in front
set_to_none frees every gradient tensor, and memory is back to 304.5 MB.So the textbook sum "16 bytes per parameter plus activations" (943.6 MB) overstates this peak: gradients grow while activations shrink, and the peak is the larger of two moments. The Memory budget tab turns this into a calculator with both moments.
measured on Apple M1 Pro, CPU, float32, PyTorch 2.14.1, deterministic (bytes, not time): PyTorch's memory profiler (torch.profiler with profile_memory=True, record_shapes=True, with_stack=True, then prof._memory_profile(), the engine behind export_memory_timeline) follows every tensor from allocation to free and puts it in a category. The second training step (optimizer state exists). Each column is the memory at one moment of the profiled run's own clock (moments placed by phase: before forward, four in forward, six in backward including the run's peak, the optimizer, after zero_grad), so only the heights are exact. src/exp/mem_step.py.
On your own job: prof.export_memory_timeline("m.html") draws this chart on any device; on CUDA the memory snapshot (memory_viz) adds each allocation's stack. On a GPU the bytes per category are the same; the attention kernel decides whether a T × T matrix is saved (section 11), and the caching allocator adds cached free blocks, so memory_reserved exceeds this peak (Memory allocators).
| Device | Tool | What it gives you |
|---|---|---|
| Any (CPU here) | torch.profiler.profile(profile_memory=True, record_shapes=True, with_stack=True), then prof.export_memory_timeline("m.html") | Live bytes by category (parameter, optimizer state, gradient, activation, autograd detail, temporary, input). It works on CPU, which is how this page measured it. |
| CUDA | torch.cuda.memory._record_memory_history(max_entries=100000), run a few steps, torch.cuda.memory._dump_snapshot("s.pickle"), drop the file on pytorch.org/memory_viz | Every allocation and free with the Python stack that made it, plus the caching allocator's segments: fragmentation and reserved-but-unused memory, which the CPU profiler cannot show. Signature at 2.14.1: _record_memory_history(enabled='all', context='all', stacks='all', max_entries=..., device=None, clear_history=False, compile_context=False, global_record_annotations=False, skip_actions=None, record_pinned_host_memory=False, record_cuda=True) read from the installed wheel. Walkthrough: Understanding GPU memory, part 1. Not run here: no CUDA device. |
| CUDA, quick numbers | torch.cuda.max_memory_allocated(), memory_reserved(), memory_summary(); device-agnostic torch.accelerator.max_memory_allocated() | Allocated is what tensors use; reserved is what the caching allocator holds from the driver. The gap is the allocator's cache and fragmentation; Memory allocators owns how it works and what PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True changes. |
| MPS | torch.mps.current_allocated_memory(), driver_allocated_memory(), recommended_max_memory() | Totals only; no per-allocation history at 2.14.1 checked on the installed wheel. |
Activation checkpointing keeps only each block's input in forward and reruns the block's forward in backward to rebuild what it needs: memory down, compute up by about one extra forward of the checkpointed part. Use checkpoint(block, x, use_reentrant=False); how it hooks autograd's saved tensors is on Tensors, the dispatcher and autograd, the trade at cluster scale on Distributed Training. Selective activation checkpointing (SAC) lets a policy, called for every ATen op in the region, save some outputs anyway; the usual one saves matmul outputs (expensive to recompute) and recomputes element-wise ops (PyTorch blog, 2025; prototype since 2.5). The six CheckpointPolicy values at 2.14.1: MUST_SAVE, PREFER_SAVE, MUST_RECOMPUTE, PREFER_RECOMPUTE, MUST_CPU_OFFLOAD, PREFER_CPU_OFFLOAD read from the installed wheel.
Full checkpointing cut the peak from 867.4 MB to 485.3 MB (44% less): forward now saves only each block's input, 42.3 MB instead of 546.4 MB. The price: backward runs 1,087 ATen calls instead of 567 (each block's forward again), and the step went from 389 ms to 475 ms on the CPU (+22%) and from 150 ms to 189 ms on MPS. SAC saving matmuls landed in between (724.6 MB, 411 ms on CPU); SAC saving only attention matched full checkpointing's peak (485.3 MB). Saving the matmuls saved little because here most activation bytes are matmul outputs (the MLP's 4d-wide fc and GELU outputs, the 3d-wide qkv projection); SAC pays off when expensive ops have small outputs, or when only some layers save. A policy must name the ops that actually run, and names differ by device (_scaled_dot_product_flash_attention_for_cpu on CPU, _scaled_dot_product_flash_attention or _efficient_attention on CUDA).
measured on Apple M1 Pro, float32, the same batch and the same loss (3.39147) in all four.
measured on Apple M1 Pro, PyTorch 2.14.1, float32, the same batch and the same loss (3.39147) in all four. Memory: CPU memory profiler, deterministic (src/exp/mem_step.py). ATen calls counted with a TorchDispatchMode. Time: median of 3 trials of 10 steps after 3 warm-up steps, CPU 4 threads and MPS, load average 3.5 (src/exp/time_misc.py ckpt, bench lock).
Under torch.compile the partitioner already decides what to save (torch.compile from the user's side owns it); torch._functorch.config.activation_memory_budget, default 1.0, makes it a memory target: in between it "solves a 0-1 knapsack to find the minimum recompute necessary to stay below the activation memory budget" (torch/_functorch/config.py L190 to 202 at 2.14.1). Budget 1.0 saves what eager saves: by default the partitioner optimises runtime, not memory. The PyTorch blog's example spells it torch._dynamo.config.activation_memory_budget; at 2.14.1 it lives in torch._functorch.config checked on the installed wheel.
measured on the larger variant, CPU, deterministic (src/exp/budget.py): activation bytes saved for backward; at 0.0 backward recomputes the whole forward.
Eager saves 546.4 MB; compiled at budget 1.0 546.8 MB, at 0.5 273.0 MB, at 0.2 109.1 MB, and at 0.0 nothing beyond the inputs (0.0 MB); eager checkpointing of every block keeps the block inputs, 42.3 MB. The loss is the same in all (3.81230, freshly initialised model on batch 1).
When: activations dominate the peak and you would otherwise shrink the batch; not when weights and optimizer state dominate (shard those: FSDP2, the root's Distributed lab). Check: peak and step time before and after, and the same loss on the same batch.
The logits, one score per vocabulary entry per position, are batch × sequence × V. With a real tokeniser (GPT-2's has 50,257 entries; the running example has 43 characters) the logits, their softmax and their gradient are the largest tensors of the step. To see it, the larger variant was given V = 50,257 (the batches still use only 43 characters, which changes no shapes and therefore no bytes): one logits tensor is 8 × 256 × 50,257 × 4 bytes = 411.7 MB.
A fused linear cross-entropy processes the positions in chunks: for each chunk it computes that chunk's logits, the loss and the gradient pieces, then frees them, so the full logits tensor never exists. The same idea is behind Liger Kernel's fused linear cross-entropy and Apple's Cut Cross-Entropy (2024); PyTorch 2.13 added it to core as nn.LinearCrossEntropyLoss and F.linear_cross_entropy (2.13 release notes, "up to 4x lower peak memory", release-note figure).
F.linear_cross_entropy(x, W, y) with the default options=None runs the reference path, which materialises all logits like the unfused code. The chunked path needs options=LinearCrossEntropyOptions() (from torch.nn.modules.linear_cross_entropy_options; its docstring: "Pass options=None to use the reference path; pass an instance of this class to opt in"). Measured below: the default saves exactly nothing.The unfused step peaks at 2394.2 MB; at that moment the backward temporaries alone hold 823.4 MB, the softmax's gradient and the logits' gradient, two tensors of 411.7 MB each. The chunked loss brings the peak to 1278.8 MB (1.87 times lower), and its saved activations from 957.8 MB to 541.9 MB, about what the 43-character model saves (546.4 MB): the vocabulary no longer costs activation memory. The default call (2394.2 MB) is byte for byte the unfused peak. Against the release notes' "up to 4x", this whole step (weights, AdamW state, block activations included) gains 1.87 times, and pays in time: +69% on the CPU, +84% on MPS. The docstring's rule: chunking "is a win when num_batches >= in_features and num_classes > in_features; below that, the reference path is cheaper". Logits scale with tokens × V, not width, so a small model with a big tokenizer is hit hardest. Check: the peak with and without, and the loss to rounding.
measured on Apple M1 Pro, the same loss in every run (8.9544 for all four).
measured on Apple M1 Pro, CPU, float32, PyTorch 2.14.1, deterministic (CPU memory profiler, src/exp/mem_step.py); the same loss in every run (8.9544 for all four). Step time, median of 3 trials of 5 steps: unfused 827 ms, chunked 1398 ms on CPU; 491 ms and 900 ms on MPS (load average 3.5; bench lock).
Written out (the running example's attn="manual"), attention builds a sequence × sequence matrix of scores per head, softmaxes it and keeps it for backward: double the context, four times the memory. The fix, from FlashAttention, computes attention in tiles and keeps only the output plus one number per row (the log of the softmax's sum, logsumexp), recomputing the tiles in backward, so memory becomes linear in sequence length (Writing kernels owns how the kernel does it; the attention designs themselves are on Attention variants).
On the CPU, SDPA ran the flash-style CPU kernel and kept the output and one logsumexp per row and head: 4.3 MB at 2,048 positions, growing linearly (0.5 MB at 256). Written out, the same attention kept the 8 × T × T softmax: 138.4 MB at 2,048, 32 times more. On MPS, SDPA with gradients takes the math path and keeps the T × T matrix too (142.6 MB): there is no memory-efficient attention for training on Apple GPUs in PyTorch 2.14.1.
measured on Apple M1 Pro, float32, PyTorch 2.14.1, deterministic: unique storages passed to autograd's saved-tensor hooks, q, k and v excluded (src/exp/attn_backends.py).
SDPA: one function, several kernels. F.scaled_dot_product_attention (SDPA) checks the inputs against each backend's constraints in a fixed priority order and runs the first that qualifies. CUDA tries flash, efficient, math, cuDNN (cuDNN first on Hopper and Blackwell with recent cuDNN), and an arbitrary attn_mask or a float32 input rules flash out; the CPU tries a flash-style kernel, then math; MPS always runs math. Measured here: on the CPU the flash kernel took every case except dropout; on MPS forcing a backend changes nothing; bfloat16 is less exact (largest error 8.1e-3 against 8.4e-7 for float32). Check which ran: profile one call and read the op name (aten::_scaled_dot_product_flash_attention, ..._efficient_attention, ..._cudnn_attention, ..._attention_math), or force one with sdpa_kernel([SDPBackend.FLASH_ATTENTION]), which raises instead of falling back silently.
| Device | Order tried | What disqualifies the fused kernel |
|---|---|---|
| CUDA | flash, efficient, math, cuDNN by default (aten/src/ATen/Context.h L483 to 488); cuDNN first on compute capability 9.x or 10.x with cuDNN newer than 9.15 (aten/src/ATen/native/transformers/cuda/sdp_utils.cpp L94 to 136; with CUDA 12 wheels only minor version 0 or 3; TORCH_CUDNN_SDPA_DEPRIORITIZED=1 turns it off) | dtype (flash needs float16 or bfloat16), head size, an arbitrary attn_mask (flash takes only is_causal; a mask falls to memory-efficient attention, which supports additive masks, or math), dropout for some kernels. Not run here. |
| CPU | flash (a CPU kernel), then math (sdp_utils_cpp.cpp L61 to 104) | dropout, nested tensors, unsupported shapes or strides (L36 to 57); dtypes float32, float64, bfloat16, float16 all qualify |
| MPS | none: MPS registers no fused-choice function, so the backend is always math (attention.cpp L814); without gradients it runs a fused MPS math kernel, with gradients the generic math path (L862 to 866) | everything; and sdpa_kernel([...]) does not change it |
measured on Apple M1 Pro, PyTorch 2.14.1: the ATen ops recorded by the profiler for one call; error against a float64 reference computed on the CPU (src/exp/attn_backends.py). On the CPU the flash kernel handled every case except dropout, including boolean and float masks and head size 80, and forcing EFFICIENT or cuDNN raises ("No viable backend for scaled_dot_product_attention was found. This is likely due to turning off both the math kernel and the fused kernels."); on MPS the path never consults the backend choice. bfloat16's larger error is what its 8-bit mantissa (against 24) predicts. On CUDA a warning names the failed constraint.
Newer FlashAttention versions plug in from outside: torch.nn.attention.list_flash_attention_impls() returns ['FA3', 'FA4'] at 2.14.1 measured; activate_flash_attention_impl("FA4") imports flash_attn.cute.interface from the separately installed flash-attn package and needs compute capability 9.0 or 10.0 (torch/nn/attention/_fa4.py L45, L110); FA3 needs exactly 9.0 (_fa3.py L154). Not run here.
FlexAttention: attention variants as two small functions. Sliding windows, packed documents, prefix-LM masks, relative biases and soft-capping used to mean a custom kernel or the math path. FlexAttention (torch.nn.attention.flex_attention, prototype in 2.5) takes two Python functions: score_mod(score, b, h, q_idx, kv_idx) changes one score (add a bias, cap it), and mask_mod(b, h, q_idx, kv_idx) says whether query q_idx may see key kv_idx. create_block_mask evaluates the mask once per tile of 128 × 128 (the default block size, flex_attention.py L444) and stores, per row of tiles, which tiles are fully allowed, partly allowed (the kernel applies the mask inside) or empty (the kernel skips them). That BlockMask is where the speed comes from.
The figure beside this text is that sweep for the mask, length and kernel you choose: on the left the positions a query may see, on the right the 128 × 128 tiles, coloured full, partial or empty; Play walks the kernel over the tiles it computes. Dense SDPA cannot know a tile is empty without reading the mask, so it computes every tile and discards what the mask forbids; FlexAttention reads the BlockMask and never visits an empty tile.
What the BlockMask buys, counted here (deterministic): at 4,096 positions a causal mask leaves 48.4% of the 128 × 128 tiles empty, a 128-token sliding window 93.8%, four packed documents 81.0%. On MPS (compiled) its largest error against float64 was 8.5e-7, the size of SDPA's own. At 4,096 positions it did not win on time: sliding window 16.9 ms against 17.4 ms for SDPA with a dense boolean mask (a tie), four documents 54.5 ms against 17.6 ms, causal 148 ms against 7.69 ms for SDPA with is_causal. Its cost tracks the tiles it visits, as designed; the per-tile kernel is just slower than Apple's fused SDPA. The 2.13 release notes' "up to ~12x speedup over SDPA on sparse patterns" on MPS vendor did not reproduce on this M1 Pro in float32 (other chips, dtypes and sizes not tried). On GPUs the authors report 90% of FlashAttention-2 forward and 85% backward vendor, PyTorch team, 2024 (FlexAttention blog).
flex_attention.py L2204 to 2219) reproduced; on CUDA (or XPU or HPU) it trains.sys.platform == "darwin" (flex_cpu.py L31 to 40); "torch.compile on current platform is not supported for CPU" reproduced. Eager works and is exact but materialises the scores.Correctness: measured on Apple M1 Pro, PyTorch 2.14.1, B = 2, 4 heads, T = 256, head size 64, float32; largest absolute difference from attention computed in float64 on the CPU with the same mask (src/exp/flex_lab.py). On the CPU, compiled FlexAttention is unavailable on macOS and FlexAttention ran eagerly; on MPS it ran compiled. Backward was attempted on both and raised.
Packing several sequences into one row avoids padding; the mask then has to stop sequences seeing each other. Two ways: a document mask in FlexAttention (above), or torch.nn.attention.varlen.varlen_attn(q, k, v, cu_seq_q, cu_seq_k, max_q, max_k) (added in 2.10), which takes all sequences concatenated as (total tokens, heads, head size) plus cumulative lengths, like flash_attn_varlen_func. At 2.14.1 it calls aten._flash_attention_forward or cuDNN, both CUDA kernels (torch/nn/attention/varlen.py L54, L139). Called here: CPU "NotImplementedError: Could not run 'aten::_flash_attention_forward' with arguments from the 'CPU' backend."; MPS "NotImplementedError: The operator 'aten::_flash_attention_forward' is not currently implemented for the MPS device." measured.
Fewer bits mean less memory, less data moved and, with matching hardware, faster matmuls. torchao (pip install torchao, 0.18.0 here, released 2026-08-03) is PyTorch's library for that, for inference and training; the formats themselves (int8, int4, float8 E4M3 and E5M2, the MX block formats) belong to Quantization and Precision. quantize_(model, config) walks the model and replaces each nn.Linear's weight with a tensor subclass (a Python class that wraps the low-bit data and its scales and intercepts every op on it; built as on Extending PyTorch). The module code is unchanged: when F.linear reaches the subclass it dispatches to a quantized kernel or dequantizes, and because it is a subclass it composes with torch.compile, FSDP2 and DTensor.
Int8 weight-only cut the Linear weights from 100.8 MB to 25.4 MB (3.96 times smaller: 1 byte per weight plus one float32 scale per row) and moved the loss by 0.00002. Int4WeightOnlyConfig failed with "ImportError: Requires mslk >= 1.0.0" (it needs a separate kernel package), and the CPU-capable IntxWeightOnlyConfig(int4) stores each 4-bit value in a full byte (IntxUnpackedToInt8Tensor) plus a scale per group of 32, so it is larger than int8 (29.2 MB). "int4" names the value grid, not the storage: check bytes, do not assume them. float8 weight-only runs on the CPU; dynamic float8 activations do not.
measured on Apple M1 Pro, CPU: the larger variant after 150 training steps, every Linear except the tied head quantized.
measured on Apple M1 Pro, CPU, torchao 0.18.0, PyTorch 2.14.1 (src/exp/torchao_lab.py): the larger variant after 150 training steps, every Linear except the tied head quantized. "Linear bytes": every inner tensor of the 32 block weights plus the head's float32 weight (data, scales, zero points). Loss on 8 fixed batches of the same text (the model has no held-out data: it is a toy). Logit difference against the float32 model on one batch.
A one-token matmul is memory-bound, so fewer bytes per weight should mean less time. Yet int8 weight-only took 3.16 ms and int4 (Intx) 5.99 ms against float32's 2.18 ms at M = 1: in eager mode the int8 weight is converted to float32 on every call, then multiplied with an ordinary torch.mm (torchao 0.18.0, int8_tensor.py L337 to 354). Dynamic int8 activations with int8 weights multiply int8 by int8 (int_scaled_matmul, L315): 0.40 ms for one token (5.4 times faster than float32) but 250 ms for 2,048 tokens against 37.0 ms (float32 BLAS is far better tuned here). On GPUs the weight-only paths have dedicated kernels, not represented here. The rule: weight-only for memory-bound work (small-batch decoding), quantized activations for compute-bound work (large batches, prefill, training).
float8 training (torchao.float8.convert_to_float8_training(model)) swaps each Linear for a Float8Linear that casts inputs, weights and output gradients to float8 with a scale per tensor (or row), runs the matmul on float8 tensor cores and keeps master weights in higher precision: up to 1.5 times the throughput at 512 GPUs on a 405B model vendor, torchao README (torchao). It needs compute capability 8.9 or newer (Ada, Hopper, Blackwell) or AMD MI300 ("requires CUDA compute capability ≥8.9 or MI300+ or XPU", reproduced as the error here). Float8LinearConfig(emulate=True) runs the same casts and scales with a float32 matmul: the numerics, not the speed.
Quantizing after training (PTQ) rounds weights the model never saw rounded. Quantization-aware training (QAT) fine-tunes with fake quantization: forward rounds weights to the target grid and back to float, backward treats the rounding as identity, so the weights learn to sit where rounding hurts least. In torchao: quantize_(m, QATConfig(base_config, step="prepare")), train, then quantize_(m, QATConfig(base_config, step="convert")). Run here on the running example: fake quantization reproduced the converted model's loss exactly (0.35054 both), which is the whole point; on a model this small int4 costs almost nothing, so QAT had nothing to recover.
measured on Apple M1 Pro, CPU, torchao 0.18.0, the running example; the head (256 × 43) stays in float32 because float8 matmuls need both dimensions divisible by 16 (src/exp/torchao_lab.py). The two runs end at 2.183 (float32) and 2.194 (float8), within the step-to-step noise, except for one spike at step 11 (5.39 against 2.90) that the next step recovers from. A spike like that, from a tensor whose scale is set by one large value, is what scaling recipes (per-row scales, MX blocks) and loss-spike monitoring exist for; this run did not investigate its cause.
QAT run. CPU, IntxWeightOnlyConfig(int4, group 32) as the base config: 300 float32 steps, then 100 more steps either in float32 followed by quantization (PTQ) or with fake-quantized weights (QAT) followed by conversion. PTQ: loss 0.3289 before quantizing, 0.3332 after (+0.0044). QAT: 0.35054 with fake quantization and 0.35054 after conversion, identical. QAT ended slightly worse than PTQ here; its value shows on large models where PTQ loses accuracy.
MX formats (MXFP8, MXFP4; and NVIDIA's NVFP4) put one shared scale on every block of 32 (MX) or 16 (NVFP4) values, so outliers cost less precision than with one scale per tensor. In torchao 0.18.0 they live in torchao.prototype.mx_formats (MXDynamicActivationMXWeightConfig, NVFP4DynamicActivationNVFP4WeightConfig; listed from the installed package) and target Blackwell's block-scaled tensor cores. Not run here: no Blackwell GPU, and no CPU emulation was attempted.
Other pieces: torchao.optim.AdamW8bit and AdamW4bit (optimizer state in 8 or 4 bits: the 8 bytes per parameter of section 8 shrink to about 2 or 1), CPUOffloadOptimizer (state and the step on the CPU), sparsify_ for 2:4 sparsity on GPUs that accelerate it. All present in 0.18.0 checked; not run here.
"Likely" means reasoning from how the hardware differs, not a measurement; published GPU figures are quoted where they exist.
| Technique | Transfers exactly | Likely different on an H100-class GPU |
|---|---|---|
| Honest timing, profiler, traces | The method; record_function ranges; key_averages | Add ProfilerActivity.CUDA for the GPU lane; Nsight Systems for kernel-level detail (Profiling, benchmarking and correctness) |
| DataLoader workers | The overlap mechanism | Matters more: a faster GPU leaves less time per step to hide loading; add pin_memory=True with non_blocking=True copies |
| Fused optimizer | Ops per step (one fused kernel against several per tensor) | foreach is already the CUDA default; fused gains less over foreach than over the for-loop |
| bfloat16 autocast | Which ops autocast casts; memory of 16-bit activations | Opposite sign: bfloat16 tensor cores make matmuls several times faster than float32 |
| torch.compile and CUDA graphs | Graphs, fusion decisions, recompiles (the root's Compile lab) | Triton kernels and CUDA graphs; the PyTorch team measured 43% faster training on average over 163 models on A100 vendor (PyTorch 2.x) |
| Loop, accumulation, GradScaler, determinism | Accumulation and scaler arithmetic; float16 underflow counts (properties of the gradients, not the device) | Deterministic mode raises on ops without a deterministic kernel; pinned host buffers let host-to-device copies run asynchronously |
| Memory categories and peaks | Bytes per category for the same dtype and kernels; the formulas of the Memory budget tab | The caching allocator adds reserved-but-free memory; flash attention saves no T × T matrix (as the CPU kernel here) |
| Checkpointing, SAC | Memory saved, ops recomputed | Relative time cost similar (one extra forward of the checkpointed part); SAC policies must name the CUDA attention ops |
| Fused linear cross-entropy | Peak memory saved | The same trade; the time cost was not measured on a GPU here |
| SDPA | The API and sdpa_kernel | Real backend choice: flash, efficient, cuDNN (first on Hopper and Blackwell with recent cuDNN), FA3/FA4 plug-ins |
| FlexAttention | score_mod, mask_mod, BlockMask counts, numerics | Compiled Triton kernels with backward: trainable, near FlashAttention-2 speed vendor |
| torchao | Bytes per format, which configs exist, numerics (emulated float8) | float8 training needs compute capability 8.9 or newer; MX and NVFP4 need Blackwell; Int4WeightOnlyConfig needs its kernel package (mslk at 0.18.0), not installed here |
torch.utils.benchmark.Timer, which synchronises for you at 2.14.1 (1)..item() bar as the problem: it is where queued work surfaces; removing the .item() moves the wait elsewhere unless the GPU had idle time to overlap. Look at the device lane, or time phases with a synchronize after each (3).torch.compile made this machine slower; each fix is a hypothesis (3).torch.manual_seed seeds everything: it does not seed Python's random or NumPy in the main process; DataLoader workers seed all three for you (4, 7).load_state_dict(strict=False)'s return value: missing keys keep their random initialisation silently; and tied weights break safetensors, loading and to_empty (7).F.linear_cross_entropy without options: the reference path saves no memory at 2.14.1 (10).sdpa_kernel([FLASH_ATTENTION]) to force a kernel everywhere: on MPS it is ignored; on CPU and CUDA it restricts the choice and raises if nothing qualifies (11).flex_attention without torch.compile, or building the BlockMask every step: eager materialises the whole score matrix; build the mask once per shape (11).IntxWeightOnlyConfig(int4) stored a byte per value and came out larger than int8 (12).torch.cuda.synchronize() for timing. Why, and is the number wrong?__next__. Or time next(iter(loader)) alone against the step. Fix with workers, prefetching, pre-processing offline.nn.LinearCrossEntropyLoss, PyTorch 2.13+).attn_mask on CUDA?is_causal, so it falls to memory-efficient attention (supports additive masks) or math. FlexAttention covers structured masks without a dense mask tensor.Float8Linear casts inputs, weights and gradients to float8 with per-tensor or per-row scales and keeps master weights in high precision; on other hardware it can only emulate.How much memory will one training step of a GPT-shaped model need at its peak? Set the shape and the switches; the calculator adds up parameters, gradients, optimizer state and saved activations with formulas read off the tensors PyTorch actually saved, and shows how far it lands from the peaks measured on the running example.
torch.cuda.memory_reserved()).Where to go next, and where the neighbouring subjects live. Times are reading or working estimates.
A calculator for one step's peak, its formulas read off the saved tensors and checked against measured peaks.
The whole stack from zero with the running example; section 6 is the intuition this page deepens.
Every ATen call of one step of the small running example, the autograd graph, memory and plain checkpointing.
What torch.compile does to the running example: graphs, fusion, the measured speedups and cold and warm compile times.
DDP and FSDP2 on gloo with per-rank memory: the next step after this page's single-device memory.
Saved tensors, version counters, saved-tensor hooks, the autograd engine: what checkpointing hooks into.
The min-cut partitioner behind the activation memory budget, modes, CUDA graphs, caching.
When one device's memory is not enough: FSDP2, TP, pipelines; flight recorder for hangs.
Tensor subclasses (how torchao's quantized tensors are built) and custom ops.
Which of these switches HF, torchtitan and Lightning turn on for you.
Nsight Systems and Compute, honest GPU timing, correctness checks.
PyTorch's CUDA caching allocator, fragmentation, expandable segments.
int8, int4, float8, MX and NVFP4 formats and what they lose.
FLOPs per token, MFU, memory-bound against compute-bound.
How a tiled attention kernel avoids the T × T matrix.
Memory math across GPUs: ZeRO stages, activation memory formulas at scale.
What AdamW computes; this page only measures its implementations.
CUDA graphs, the fix for launch overhead that has no MPS equivalent here.
Schedules, record_function, stacks, memory, exporting traces.
Timer, blocked_autorange, comparing results; why naive timing lies.
The memory snapshot workflow and finding reference cycles; open snapshots in memory_viz.
AC, SAC and the compile memory budget on one speed against memory diagram.
score_mod, mask_mod, BlockMask, and the performance model.
Arguments, backends, the math reference implementation.
quantize_, float8 training (float8 README), QAT, low-bit optimizers.
A checklist of general switches: DataLoader workers, pinned memory, set_to_none, channels_last, fused optimizers.
autocast's op lists and GradScaler.
workers, prefetch_factor, persistent_workers, pin_memory, samplers.
Opens the JSON from export_chrome_trace in the browser.
Reads many ranks' traces at once: idle time, communication overlap, stragglers.
Reading traces of compiled code.
Fused losses outside core, the ancestors of LinearCrossEntropyLoss.
Sources for every number are linked where the number appears. Measured results: src/exp/ in this page's folder (scripts and recorded inputs). PyTorch 2.14.1, torchao 0.18.0, Apple M1 Pro, October 2026.