torch.compile, stage 1

TorchDynamo: from Python to a graph

How a compiler gets a graph out of ordinary Python without asking you to rewrite the model, and how it knows when that graph can be reused.

Dynamo sits between your call and the interpretermodel(x)CPythonabout to run forward()TorchDynamoframe evaluation hookFX graphthe tensoroperationsGuardswhen itstays validwithout torch.compilethe interpreter runs every line offorward() again on every stephanded to the backend:AOTAutograd, then InductorIt evaluates the bytecode symbolicallybytecode of forward()LOAD_FAST xLOAD_GLOBAL w1BINARY_OP @LOAD_GLOBAL b1BINARY_OP +LOAD_GLOBAL FLOAD_ATTR geluCALL 1RETURN_VALUEtensors areproxiesxmatmuladdgeluoutputevaluated once at trace time, so absent from the graphattribute lookupsloops over layersbranches on constantsThe assumptions behind this graphx is a float32 tensor of shape [32, 128]inputx.device == cuda:0inputself.training is Truemodule statelen(self.layers) == 4Python valuew1 and b1 are the same objectsglobalson the next callall holdrun the compiled codeone failstrace and compile againWhat it cannot trace splits the graphforward()h = self.body(x)if h.sum() > 0: # needs the tensor's value h = h * 2return self.head(h)graph 1body, sumPythonevaluates the ifgraph 2mul, headother common causesprint(h)h.item()h.cpu().numpy()a C extension

Hook the frame

CPython lets an extension replace the function that evaluates a frame. TorchDynamo installs itself there, so it sees forward() just before the interpreter would run it and can substitute compiled code.

model = torch.compile(model)
out = model(x)    # the first call triggers tracing
where it attachesthe frame evaluation API of CPython (PEP 523)

Trace the bytecode

Dynamo steps through the bytecode with stand-in tensors. Every tensor operation becomes a node in an FX graph. Plain Python, such as attribute lookups or a loop over layers, is executed during tracing and leaves no trace in the graph.

# see the captured graph
TORCH_LOGS=graph_code python train.py
what is leftmatmul, add, gelu: only the tensor work

Record the guards

The graph is correct only for the inputs and Python state seen during tracing. Dynamo writes those assumptions down as guards: cheap checks on shapes, dtypes, devices, flags and object identities.

# list the guards of each compiled frame
TORCH_LOGS=guards python train.py
checked on every calla few microseconds, before the compiled code runs

Graph breaks

A branch on a tensor's value, a print, or a call into a library Dynamo cannot see ends the current graph. Python runs that piece, then tracing resumes. The model still works, but each break is a missed chance to fuse.

torch._dynamo.explain(model)(x)   # lists the breaks
torch.compile(model, fullgraph=True)  # error instead
after a breaktwo smaller graphs with interpreter work between them

Dynamo turns Python into a graph plus the conditions under which that graph stays valid.

torch.compile, stage 2

AOTAutograd: the backward pass, ahead of time

Eager PyTorch discovers the backward pass while the forward runs. AOTAutograd works it out once, in advance, so the compiler can optimize training and not only inference.

Eager autograd records the tape while it runsforward, every stepmatmulMmBackwardaddAddBackwardgeluGeluBackwardlossNllBackwardgrad_fn nodes, created again on every stepBuilt at run timeone Python object per operation,allocated and freed each stepInvisible to a compilerthe backward pass does not existuntil the forward has runAOTAutograd traces both directions onceforwardbackwardmatmuladdgelulossd lossd gelud addd matmuleach backward node reads tensors its forward node producedone graph a backend can optimize end to endIt rewrites the graph into pure, simple operationsmutation becomes a new valueh.add_(b)h2 = add(h, b)a composite op becomes core opsF.silu(h)mul(h, sigmoid(h))gradients become explicit outputsloss.backward()grads = backward(saved, d_loss)backends then handle a small, fixed set of operatorsThen it splits the graph and chooses what to keepforward graphruns in the training stepbackward graphruns at loss.backward()savedtensorsfor backwardthe partitioner decides, tensor by tensorsave itmore memoryrecompute itmore computea min-cut over the joint graph picks the cheapest setboth halves go to Inductor as ordinary graphs

Eager builds a tape

In eager mode every operation attaches a grad_fn node to its output. loss.backward() then walks those nodes one by one. The tape is rebuilt on every step, and no tool sees the backward pass as a whole.

loss = loss_fn(model(x), y)   # records grad_fn nodes
loss.backward()                # walks them
costbookkeeping per operation, on every step

One joint graph

AOTAutograd runs autograd on the graph Dynamo captured, using stand-in tensors, and records the result. Forward and backward now sit in one graph, traced once.

# stop after this stage to isolate a bug
torch.compile(model, backend="aot_eager")
AOTahead of time: before the first real step finishes

Pure, simple ops

Two clean-ups make the graph easy to optimize. Functionalization replaces in-place updates and views with operations that return new values. Decomposition rewrites composite operators into a small core set.

h.add_(b)      ->  h2 = add(h, b)
F.silu(h)      ->  mul(h, sigmoid(h))
why it mattersa backend implements a small core set, not the whole API

Split and save

The joint graph is cut into a forward half and a backward half. Any tensor the backward half needs must be saved by the forward half or recomputed. A min-cut partitioner chooses the split that saves the least.

# the pair is wrapped as one autograd Function
loss.backward()   # runs the compiled backward
resulttwo graphs, with the saved tensors passed between them

The backward pass becomes an ordinary graph, so the compiler can optimize it like the forward pass.

torch.compile, stage 3

Inductor: from graph to kernels

The default backend. It takes the forward and backward graphs, merges neighbouring operations into single loops, and writes real kernel code for the device.

Eager: one kernel and one pass over memory per operationmatmulwritetmp1addwritetmp2geluwritetmp3mulwritetmp4addwrite outresult5 kernel launcheseach one starts from Pythonand the dispatcher4 temporary tensorseach written to memory, thenread back by the next kernelfor small tensors the launches dominate; for large ones the memory traffic doesInductor fuses elementwise operations into one loopmatmuladdgelumuladdmatmullibrary callone fused kernelfor i in range(n): out[i] = gelu(a[i] + b[i]) * g[i] + x[i]kernels52temporaries41passes over memory52It writes the kernel source, then compiles itfused loopsin Inductor's IRGPU: a Triton kernel (simplified)@triton.jitdef fused_add_gelu_mul_add(a, b, g, x, out, n): i = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK) t = tl.load(a + i) + tl.load(b + i) t = gelu(t) * tl.load(g + i) + tl.load(x + i) tl.store(out + i, t)CPU: C++ with OpenMP (simplified)#pragma omp parallel forfor (long i = 0; i < n; i++) out[i] = gelu(a[i] + b[i]) * g[i] + x[i];matmul and convolutionstill call cuBLAS and cuDNNThe mode decides how hard it tries, and how kernels launchdefaultFuse, generate, launch each kernelthe shortest compile timereduce-overheadRecord the kernels as a CUDA graphreplayed with a single launch; uses more memorymax-autotuneTry several variants of each kernelbenchmarks them while compiling; the slowest to compile

The eager cost

The block computes gelu(x @ w + b) * g + x. Eager mode runs it as five separate kernels. Each one is launched from Python, writes a full tensor, and the next kernel reads that tensor back.

h = F.gelu(x @ w1 + b1)
return h * g + x
two costslaunch overhead, and a trip through memory per operation

Fusion

Add, GELU, multiply and add all work element by element, so Inductor merges them into one loop that reads each input once and writes one output. The matmul stays a call into a tuned library.

# whole block: 5 kernels   ->  2
# temporaries: 4           ->  1
what fuseselementwise operations, reductions and indexing

Code generation

Inductor emits source code: Triton kernels for a GPU, C++ with OpenMP for a CPU. That source is compiled to machine code, which is why the first call takes long. You can read exactly what it generated.

TORCH_LOGS=output_code python train.py
first callthis compile step is where the start-up time goes

Modes

The mode sets how much work goes into compiling. reduce-overhead also changes how kernels start: the whole sequence is recorded as a CUDA graph, which the next slide explains.

model = torch.compile(model, mode="reduce-overhead")
rule of thumbdefault first; reduce-overhead for small batches and many small kernels

Fewer, larger kernels: less launch overhead and fewer trips through memory.

torch.compile, stage 4

Compiled code: reused while the guards hold

Compilation is expensive, so its result is cached next to the function. What matters in training is how often the cache misses.

The first call pays for everythingtime of the first calltracebackwardgenerate and compile kernelsrunseconds to minutes, oncecache entryguardswhen it is validcompiled codeforward and backwardstored on the code object of forward(), in this processLater calls check the guards and runmodel(x)check guardsmicrosecondscompiled codeno tracing, no Pythonstep timestep 1: compileExclude the warm-uptime and benchmark only afterthe first few stepsEvery rank compileseach DDP process builds its owncache, so start-up is slowerA failed guard adds another entrycache of forward()x: [256, 128], trainingthe usual batchx: [112, 128], trainingthe short last batchx: [256, 128], evalvalidationeach new entryis a full compilelimit reachedfalls back to eagertorch.compiler.config.recompile_limitentries per function, 8 by defaultKeep the input signatures fewKeep shapes fixeddrop the short last batchDataLoader(ds, drop_last=True)Declare what variesone graph for any batch sizetorch.compile(model, dynamic=True)Find the causeprints the guard that failedTORCH_LOGS=recompilesWarm up before timingtrain and eval each compile oncefor _ in range(3): step()

First call

The first call runs the whole pipeline: trace, derive the backward pass, generate and compile kernels. The result is stored as a cache entry holding the guards and the compiled forward and backward code.

model = torch.compile(model)
model(x)   # slow: compiles
model(x)   # fast: cache hit
where it livesin memory, attached to the function it was compiled from

Later calls

From the second call on, Dynamo evaluates the guards and, if they hold, jumps straight to the compiled code. Under DDP each rank is its own process with its own cache, so all ranks compile at start-up.

# compile the inner module, then wrap it
model.compile()
model = DDP(model, device_ids=[local_rank])
steady statea guard check, then compiled forward and backward

Recompiles

When a guard fails, Dynamo compiles again for the new situation and keeps both entries. A function that keeps changing would compile forever, so there is a limit; past it, that function runs in eager mode.

# why did it recompile?
TORCH_LOGS=recompiles python train.py
typical causesthe last batch, switching to eval, a changing Python value

Keep them rare

A training loop should settle on one or two entries: train and eval. Fix the batch shape, or declare the dimension dynamic so one graph covers every size.

loader = DataLoader(ds, 256, drop_last=True)
model.compile(dynamic=True)  # or allow any shape
checkstep time is flat after the first steps of train and eval

Compilation is paid once per distinct input signature, so keep the signatures few.

inside one SM

CUDA cores: thousands of simple threads

The general-purpose arithmetic units of a GPU. Each one is slow; the speed comes from running thousands of threads through them at once.

64 arithmetic units in every SMone SM64 FP32 coresOne operation per threadadd, multiply, compare, convert:ordinary scalar arithmetic108 SMs on an A100108 × 64 = 6,912 cores on one chipSlow alone, fast togethereach is far simpler than a CPU core;the speed comes from the countwhat runs on them in a training stepx + ygelu, expindexingargmaxfp32 matmul without TF32A kernel is a grid of blocks, and a block runs on one SMadd(x, y)one kernel launchgrid of blocksone block: up to 1,024 threadseach row is a warp: 32 threadsone SMup to 64 warps resident: 2,048 threadsrunning nowthe rest wait for memory or for their turnwarp = 32 threadsblock ≤ 1,024 threadsa block stays on one SMA warp runs one instruction on 32 threadsout[i] = a[i] + b[i] # the same instruction, i = 0 … 31all 32 lanes active: nothing is wasteda branch that depends on the dataif a[i] > 0: out[i] = a[i]else: out[i] = 0pass 1: the threads that took the ifpass 2: the rest. Both paths run, and half the lanes idle each timeA small workload leaves most SMs emptybatch of 49 of 108 SMs busybatch of 256every SM busyGPU-Util can misleadnvidia-smi reports the share of timea kernel was running, not how manySMs it usedFill the chiplarger batches, or fewer and largerkernels through fusion

What they are

An SM holds 64 FP32 cores, with integer units beside them. Every operation that is not a Tensor Core matrix product runs here: elementwise math, indexing, reductions, and fp32 matmuls when TF32 is off.

torch.cuda.get_device_properties(0)
# name, total_memory, multi_processor_count
A100108 SMs × 64 cores = 6,912 CUDA cores

Threads and warps

A kernel launches thousands of threads, grouped into blocks. A block runs on one SM, which executes its threads 32 at a time; that group of 32 is a warp. The SM keeps many warps resident and switches to another whenever one waits for memory.

# an elementwise op on a [256, 197, 768] tensor
# is 38.7 million values: one thread each
per SM on an A100up to 64 warps, 2,048 threads, 32 blocks

One instruction, 32 lanes

All 32 threads of a warp execute the same instruction on different data. A branch that depends on the data splits the warp: the two paths run one after the other with the other lanes masked. Neural-network operations rarely branch, which is why they suit GPUs.

y = torch.where(a > 0, a, 0)
# no branch: every lane computes, then selects
the name for thisSIMT: single instruction, multiple threads

Keeping them busy

A kernel on a small tensor has too few threads to fill 108 SMs, so most of the chip idles while the launch overhead stays the same. Utilisation from nvidia-smi does not show this, because it measures time, not occupancy.

nvidia-smi --query-gpu=utilization.gpu --format=csv
# share of time a kernel ran, not share of SMs
what to dogrow the batch until samples per second stop rising

CUDA cores do everything except the matrix products, so they set the pace of every small or elementwise operation.

inside one SM

Tensor Cores: the matrix product in hardware

Units that multiply small matrices and add the result in a single instruction. Most of a transformer’s or CNN’s time can run here, but only for certain data types.

One instruction multiplies two small matricesCUDA corea×b+cone multiply-addper threadTensor Core×+=D = A × B + C on whole tilesa matrix multiply-accumulate in hardwarea warp of scalar multiply-adds32per instructionone Tensor Core instruction2,048multiply-addsTensor Cores per SM4on an A100a transformer spends most of its time in matrix products: this is where it should runOnly some data types reach the Tensor Coresmatmul data typeruns onpeak TFLOPS on an A100fp16, bf16autocastTensor Cores312TF32fp32 tensors, TF32 onTensor Cores156fp32fp32 tensors, TF32 offCUDA cores19.516 times apartthe same matmul, fp32 against bf16Also int8 and fp64for inference and for HPCTF32 keeps the range of fp32 and the precision of fp16signexponent: rangemantissa: precisionfp3232 bits823TF32inside the multiply81013 bits rounded awaybf1616 bits87fp1616 bits510TF32inputs and outputs stay fp32bf16fp32's range, so no loss scalingFour habits that keep matmuls on the Tensor CoresMixed precisionmatmuls and convolutions in 16 bitstorch.autocast("cuda", torch.bfloat16)TF32 for what stays fp32off by default for matmulset_float32_matmul_precision("high")Channels last for CNNsthe layout cuDNN's kernels expectmodel.to(memory_format=channels_last)Sizes in multiples of 8batch, channels and hidden sizeshidden = 768 # 8 × 96

One instruction

A CUDA core performs one multiply-add for one thread. A Tensor Core instruction takes tiles of two matrices and produces A × B + C for the whole warp at once. Linear layers, attention and convolutions are all built from this operation.

y = x @ w + b     # the product: Tensor Cores
y = F.gelu(y)     # the rest: CUDA cores
per SM on an A1004 Tensor Cores beside the 64 CUDA cores

Which data types

Tensor Cores accept 16-bit floats and TF32, plus int8 and fp64 for other workloads. A plain fp32 matmul with TF32 off never reaches them and runs on the CUDA cores, 16 times slower at peak.

x.dtype     # what the matmul will see
torch.get_float32_matmul_precision()
# 'highest' by default: no TF32
peak on an A100312 TFLOPS in fp16 or bf16, 156 in TF32, 19.5 in fp32

TF32, bf16, fp16

TF32 is not a tensor type. The inputs and outputs stay fp32; only inside the multiply is the mantissa rounded to 10 bits, and the sum is accumulated in fp32. bf16 keeps fp32’s 8-bit exponent, so it rarely overflows; fp16 has more precision but a small range, which is why it needs a GradScaler.

torch.set_float32_matmul_precision("high")
# convolutions use TF32 by default
rule of thumbbf16 autocast for transformers; TF32 for whatever stays fp32

Getting there

Autocast moves the heavy operations to 16 bits and leaves sensitive ones, such as the loss, in fp32. TF32 covers the fp32 remainder. For convolutions, channels-last avoids layout conversions, and sizes that are multiples of 8 let the library use its Tensor Core kernels throughout.

with torch.autocast("cuda", dtype=torch.bfloat16):
    loss = loss_fn(model(x), y)
checkthe profiler shows the matmul’s share of GPU time falling

The same matmul is up to 16 times faster on Tensor Cores, and the data type decides whether it gets there.

inside one SM

Registers, L1 and shared memory

GPU memory gets larger and slower the further it is from the cores. These three levels sit inside the SM, and fast kernels are written to stay in them.

The closer to the cores, the smaller and the fasterregisters64K 32-bit registers per SMprivate to one threadL1 cache and shared memory192 KB per SMshared by the threads of a blockL2 cache40 MB, shared by all 108 SMsHBM40 or 80 GB, 1.5 to 2 TB/s across the whole chipfasterA100 figures. A fast kernel keeps its working data in the top two levels.One register file, divided among the threads on the SM32 registers per thread64 warps fit: 2,048 threads128 registers per thread16 warps fit: 512 threadsthe register file is the same size both times: 65,536 registersPrivate and immediatea thread's loop counters, pointers andintermediate values live here; noother thread can see themA budget, not a givenat most 255 per thread; a kernel thatneeds many keeps fewer warpsresident, so less latency is hiddenOne 192 KB block per SM, split two waysshared memoryup to 164 KB, managed by the kernelL1 cacheautomaticthe split is chosen per kernelHBMthe full matricescopy a tileshared memoryone tile, on the SMreadmany timesTensor Coresmultiply the tileA scratchpad for a blockall threads of one block see it; a tileis fetched once and then reusedwithout touching HBMWho uses itcuBLAS, cuDNN and generated kernels;not something you manage fromPyTorchFused kernels keep values in registerseager: every result goes to HBM and comes backaddHBMwrite, readgeluHBMwrite, readmulHBMwritefused by torch.compileone kernel: add, gelu, multhe values between them stay in registersHBMone writeLess traffic to HBMmemory bandwidth, not arithmetic, limitselementwise work; fusion removes theround tripsHelp the cachescontiguous or channels-last tensorsput neighbours next to each otherin memory

The hierarchy

A tensor lives in HBM, tens of gigabytes shared by the whole chip. Reading it costs time, so each SM has its own small, fast storage: registers for each thread and a block of L1 cache and shared memory. The L2 cache sits between them.

torch.cuda.memory_allocated()  # your tensors
torch.cuda.mem_get_info()      # free, total
what PyTorch reportsonly HBM; the levels inside the SM are invisible

Registers

Each thread keeps its working values in registers, the fastest storage there is. The SM has one register file for all resident threads. A kernel that needs more registers per thread leaves room for fewer warps, and with fewer warps the SM has less to switch to while one waits.

# 65,536 registers ÷ 2,048 threads = 32 each
# at 128 each, only 512 threads fit
A10064K 32-bit registers per SM, at most 255 per thread

Shared memory and L1

The SM has one 192 KB block. Part is an automatic L1 cache. The rest is shared memory: a scratchpad that the threads of a block read and write directly. Matrix kernels copy a tile from HBM into it once, and the Tensor Cores then read it many times.

# the kernel library chooses the split;
# from PyTorch you only choose the library call
A100192 KB per SM, of which up to 164 KB shared memory

Why it matters

You never allocate these yourself, but they explain two rules. Elementwise operations are limited by HBM bandwidth, so fusing them, which keeps intermediate values in registers, is faster than three separate kernels. Tensors laid out contiguously make every cache level work better.

model = torch.compile(model)   # fuses the ops
x = x.to(memory_format=torch.channels_last)
in one linethe fewer trips to HBM a kernel makes, the faster it runs

Speed on a GPU is mostly about keeping data close to the cores; the libraries do it for you when the shapes and layouts let them.

GPU memory, term 1 of 4

Parameters: the weights themselves

The numbers the model learns. They are the smallest of the four terms, and the one the other fixed terms are measured against.

A parameter is one learned numbernn.Linear(4, 3)0.12-0.480.070.910.05-0.330.260.58-0.14-0.210.75-0.09-0.620.400.33W: 3 × 4 = 12 weightsb: 3y = W @ x + b15 parameters in this one layerLearned, not computedthey start random and movea little on every stepA model is millions of them87 million in ViT-B/16,1.1 billion in ViT-g/14They are the checkpointmodel.state_dict() is thesetensors, written to diskwhat counts as a parameterweightsbiasesembeddingsnorm scale and shiftSize is the count times the bytes per valueparametershow many×bytes per value4 in fp32, 2 in fp16 or bf16=memoryfor the weightsViT-B/1687 M0.35 GB0.17 GBViT-L/16304 M1.22 GB0.61 GBViT-H/14632 M2.53 GB1.26 GBViT-g/141.1 B4.4 GB2.2 GBfp3216-bitfp3216-bita few gigabytes at most: the weights alone rarely fill a cardThe same on every GPU, at every batch sizeDDP: every rank holds the whole modelGPU 0100%GPU 1100%GPU 2100%GPU 3100%FSDP or ZeRO stage 3: every rank holds one shardGPU 0¼GPU 1¼GPU 2¼GPU 3¼Not a batch-size problemhalving the batch leavesthis term untouchedSharding is the levereach rank stores a slice andgathers a layer just in timeCount them before you launchcount and sizeps = list(model.parameters())n = sum(p.numel() for p in ps)nbytes = sum(p.numel() * p.element_size() for p in ps)print(f"{n / 1e6:.1f} M parameters, {nbytes / 1e9:.2f} GB")torchvision vit_b_16: 86.6 M parameters, 0.35 GBBuffers are extrarunning statistics and indextables: model.buffers()Frozen still countsa frozen weight takes memorybut needs no gradientp.numel()p.element_size()p.requires_grad

One learned number

A parameter is a number the model is free to change: an entry of a weight matrix, a bias, an embedding. nn.Linear(4, 3) holds a 3 × 4 matrix and 3 biases, so 15 parameters. Training is the search for good values of all of them.

layer = nn.Linear(4, 3)
layer.weight.shape   # [3, 4]
layer.bias.shape     # [3]
counts as a parameteranything registered as nn.Parameter

Count times bytes

Each value takes 4 bytes in fp32 and 2 bytes in fp16 or bf16. Multiply by the count and you have the size. Even a billion-parameter model is only a few gigabytes of weights, so the weights are rarely what fills a card.

86.6e6 * 4 / 1e9   # ViT-B/16: 0.35 GB
1.1e9  * 4 / 1e9   # ViT-g/14: 4.4 GB
on the slide's bar6%: a 16-bit copy used by the forward pass

Fixed by the model

This term depends only on the architecture. A larger batch does not grow it, and more GPUs do not shrink it: under DDP every rank holds a full copy. Only sharding changes that, by giving each rank a slice and gathering a layer just before it runs.

model = DDP(model)     # N full copies
fully_shard(model)     # N shards
grows withthe parameter count, nothing else

Measure it

Two sums give the count and the bytes. Buffers such as BatchNorm running statistics are stored with the model but are not parameters. Frozen parameters still take this memory, but they need no gradient and no optimizer state.

ps = list(model.parameters())
n = sum(p.numel() for p in ps)
vit_b_1686.6 M parameters, 0.35 GB in fp32

Parameters set the scale: gradients and optimizer states are multiples of this count.

GPU memory, term 2 of 4

Gradients: one slope per weight

What backward() produces and the optimizer consumes. Same shape as the weights, and alive for part of every step.

A gradient has the shape of its parameterWW.grad0.12+0.02-0.48-0.310.07+0.080.91+0.44-0.33-0.120.26+0.270.58-0.05-0.14+0.090.75+0.36-0.09-0.02-0.62-0.210.40+0.15same shape, same dtype, one value per weightW.grad.shape == W.shapeWhich way, how muchthe sign is the direction,the size is how stronglythe loss reactsOnly if it trainsa frozen weight hasno gradient at allgradient = d loss / d weight, for every weight at oncefilled by loss.backward()read by optimizer.step()cleared by zero_grad()They exist from backward() until zero_grad()forwardbackwardstepzero_gradmemoryactivationsgradientsDropped, then refilledzero_grad() sets them to None;the next backward allocates againAccumulation is freea second backward() adds intothe same tensorsThe bytes, and one detail of DDPweightgradient4 bytes in fp32the same 4 bytes: a gradient has its parameter's dtypeunder autocast the weights stay fp32, so the gradients do tooDDP copies gradients into buckets for the all-reducep.gradcopybucket 0bucket 1bucket 2≈ 25 MB eachone extra copyDDP(model, gradient_as_bucket_view=True) # grads live in the bucketsthat flag saves peak memory equal to the size of the gradientsTrain fewer weights, store fewer gradientsFull fine-tuningevery weight trainsweightsgradientsFrozen backbone, new headrequires_grad_(False) on the backboneweightsgradientsLoRA adapterslow-rank matrices beside frozen weightsweightsgradientsthe optimizer states shrink with them: Adam tracks only what it updates

One slope per weight

The gradient of a weight says how the loss would change if that weight moved a little. Autograd computes one for every trainable weight, so p.grad always has the shape of p. The optimizer reads it to decide the step.

loss.backward()
W.grad.shape == W.shape   # True
memoryone value per trainable parameter

A short life

Gradients are filled during backward(), read by optimizer.step() and dropped by zero_grad(), which sets them to None by default. During backward they share the card with the activations that are not freed yet.

optim.zero_grad()   # grads become None
loss.backward()     # allocated and filled
optim.step()        # read
accumulationrepeated backward() adds in place: no extra memory

Bytes, and DDP

A gradient has the dtype of its parameter, so in fp32 it costs the same 4 bytes. DDP also copies the gradients into its all-reduce buckets. With gradient_as_bucket_view the gradients become views of the buckets, which saves that copy.

model = DDP(model,
    gradient_as_bucket_view=True)
savespeak memory equal to the size of the gradients

Train less, store less

Only parameters with requires_grad=True get a gradient. Freeze a backbone and train a head, or train small LoRA adapters, and this term shrinks to the trainable part. The optimizer states shrink with it.

for p in model.backbone.parameters():
    p.requires_grad_(False)
activationsstill kept from the first trainable layer onward

Gradients cost as much as the weights that train, and nothing for the weights that do not.

GPU memory, term 3 of 4

Optimizer states: what Adam remembers

The running averages an optimizer keeps for every weight. Invisible in the model code, and the largest fixed term on the card.

What the optimizer keeps between stepsSGDkeeps nothingweight+0bytesSGD(momentum=0.9)one running average of the gradientweightvelocity+4bytesAdamWtwo running averagesweightmv+8bytessame shape as the parameteralways fp32one set on every rankWhy Adam keeps two1running mean of the gradient: a steady direction2running mean of its square: its usual size3so every weight gets its own step sizeone weight, 40 stepsg, the raw gradientm, its running meanv sets the scalelarge, noisy gradientsget smaller stepstwo extra numbers for every weight: the price of a per-weight stepSixteen bytes for every parameterfp32 AdamWweight 4gradient 4m 4v 4mixed precision with fp32 master weights: the split on the slidew 2g 2fp32 weights 4m 4v 4optimizer states: 12 of the 16 bytesViT-g/14: 1.1 B parameters16 bytes × 1.1 B = 17.6 GB,before the first activationGPT-2 XL: 1.5 B parameters16 bytes × 1.5 B = 24 GB:the ZeRO paper's examplefixed by the model: a smaller batch does not shrink any of itKept for the whole run, on every rankNever freedcreated on the first step(), kept until training endsPart of every checkpointsave optimizer.state_dict(), or Adam restarts cold on resumeThe first thing ZeRO shardsstage 1 splits the states across the N ranksbytes per parameter on each GPU1 GPU168 GPUs, ZeRO-14 + 12 / 8 = 5.5

The optimizer's memory

Plain SGD keeps nothing between steps. Momentum keeps one running average per weight. Adam and AdamW keep two: m, the average gradient, and v, the average squared gradient. Each has the shape of its parameter.

opt = torch.optim.AdamW(model.parameters())
opt.state[p]['exp_avg']      # m
opt.state[p]['exp_avg_sq']   # v
AdamWtwo extra tensors for every parameter tensor

Why two

m smooths the noisy gradient into a steady direction. v records how large the gradient of this weight usually is. Dividing one by the other gives every weight its own step size. That is why Adam is forgiving about the learning rate, and why it costs memory.

m = b1 * m + (1 - b1) * g
v = b2 * v + (1 - b2) * g * g
p -= lr * m / (v.sqrt() + eps)
left out herebias correction and weight decay

16 bytes per parameter

In fp32: weight 4, gradient 4, m 4, v 4. The slide's bar uses the ZeRO paper's accounting for mixed precision: 16-bit weights and gradients, plus fp32 master weights and the two moments. Both add up to 16 bytes.

16 * 1.1e9 / 1e9   # ViT-g/14: 17.6 GB
16 * 1.5e9 / 1e9   # GPT-2 XL: 24 GB
before any activation16 bytes × the parameter count

Kept for the whole run

The states are created on the first step and never freed. They belong in every checkpoint: resume without them and Adam starts cold. Every DDP rank holds its own identical copy, which is why ZeRO stage 1 shards them first.

torch.save({'model': model.state_dict(),
            'optim': opt.state_dict()}, f)
ZeRO-1 on 8 GPUs16 bytes per parameter become 4 + 12 / 8 = 5.5

With Adam, every parameter costs 16 bytes before the first sample arrives, and most of that is optimizer state.

GPU memory, term 4 of 4

Activations: what the forward pass leaves behind

The intermediate tensors of the forward pass, held until backward has used them. The only term that grows with the batch.

Every layer hands a tensor to the nextx[64, 197, 768]block 1h1[64, 197, 768]block 2h2[64, 197, 768]block 3…An activation is an outputthe tensor a layer producesfor the current batchNew on every stepweights persist; activationsare rebuilt for each batchone transformer block produces severalnorm outputqueries, keys, valuesattention weightsMLP hidden layer, 4× the widthresidual sumsThey are kept because backward needs themone linear layery = W @ xdL/dW = dL/dy @ x.Tthe gradient of W needs x,the input this layer sawso x cannot be thrown away yetafter forwardh4h3h2h1all four keptduring backwardfreedfreedh2h1freed in reversetrainingsaved until backward reaches the layertorch.no_grad()each one is freed right after usethe peak comes at the end of the forward passOne tensor: batch × tokens × width × bytes64batch×197tokens×768width×4bytes, fp32=38.7 MBone tensor× several per blockattention, MLP hidden,norm outputs× the depth12 blocks in ViT-B/16,32 in ViT-H/14× the batchthe only term that growswith the batch sizeresolution: tokens grow with the square of the image side224 px197 tokens448 px785 tokensactivations 4×, attention weights 16×Three ways to hold fewer of themautocast(dtype=bfloat16)16-bit activationsevery saved tensor takes half the bytesbeforeaftercheckpoint(block, x)Keep only each block's inputthe rest is recomputed during backwardbeforeafterk micro-batchesAccumulate gradientsthe same update with a peak k times lowerbeforeafter

Outputs along the way

An activation is the tensor a layer produces for the current batch. A transformer block produces several: the normalised input, queries, keys and values, the attention weights, the hidden layer of the MLP. Unlike weights, they are new on every step.

h = block(h)   # [batch, tokens, width]
ViT-B/16, batch 64[64, 197, 768] after every block

Why keep them

To get the gradient of a layer's weights, backward needs the input that layer saw. For y = W x that input is x. So autograd holds on to activations during the forward pass and frees each one as backward passes its layer.

with torch.no_grad():    # inference
    out = model(x)       # nothing is kept
why inference is cheapno backward, so nothing has to be saved

What sets the size

One tensor is batch × tokens × width values. A block keeps several, and the model stacks many blocks. This is the only term that grows with the batch, and it grows fast with resolution: twice the image side is four times the tokens.

64 * 197 * 768 * 4 / 1e6   # 38.7 MB
(448 // 16) ** 2 + 1       # 785 tokens
448 px instead of 2244× the tokens, 16× the attention weights

Three levers

Autocast stores activations in 16 bits. Checkpointing keeps only the input of each block and recomputes the rest during backward. Accumulating over smaller micro-batches lowers the peak without changing the update.

with torch.autocast('cuda', torch.bfloat16):
    h = checkpoint(block, h,
                   use_reentrant=False)
the tradecheckpointing pays with a second forward pass per block

Activations are the term you control from the training script: batch, resolution, precision and checkpointing.

Where the data waits

Lustre, node-local NVMe and /dev/shm

Three places a training job can read its data from: shared by the cluster, private to one node, or held in its memory.

Lustre: one file system for the whole clusternode 0clientnode 1clientnode 2clientnode 3clientnode 4clientthe cluster network, usually InfiniBandmetadata servernames, folders, permissions, layout1. open: where are its stripes?object storage targetsOST 0stripe 0OST 1stripe 1OST 2stripe 2OST 3stripe 32. read the stripes from alltargets at the same timeone big file, split into stripesOST 0OST 1OST 2OST 3OST 0OST 1OST 2OST 3Fast for big sequential readsSlow for many small opensNode-local NVMe: a fast disk inside the nodeone compute nodeCPUsRAM4 GPUsPCIeNVMe SSDa few TB, $TMPDIR or /localno network, no metadata serverother nodes cannot see this diskmost sites wipe it when the job endsLustreoutside the nodecopy onceat job startSmall files are cheap hereNever the only copy/dev/shm: a folder whose files live in RAMthe node's RAMprocesses: model, workers, CUDA/dev/shm: up to half the RAM by defaultcp index.parquet /dev/shm/an ordinary file, read at memory speeda tmpfsno disk underneathShared memory between processes lives here too8 loader workersbatch tensorsin /dev/shmthe trainerCounts as the job's memoryGone after the job or reboot

Lustre

Lustre is the parallel file system on many HPC clusters, mounted on every node. To open a file, a client first asks the metadata server for its name, permissions and layout; it then reads the file's stripes straight from several object storage targets at once. Big files read front to back are fast, because many targets serve them in parallel. Many small files are slow, because every open is a round trip to the metadata server, which all jobs share.

lfs df -h              # the targets, and how full
lfs getstripe big.tar  # which targets hold it
lfs setstripe -c 8 dir/  # stripe new files over 8
best forthe only copy of the data, read in large files

Node-local NVMe

Many GPU nodes have their own NVMe solid-state drive on PCIe. Reads go straight from that drive into the node's memory, with no network and no metadata server, so even small files are cheap. The disk belongs to one node: the other nodes of the job cannot see it, it holds a few terabytes, and most sites empty it when the job ends. Sites call it $TMPDIR, /tmp or /local, and SLURM's --tmp asks for space on it.

echo $TMPDIR          # this job's local folder
df -h $TMPDIR         # size of the disk
#SBATCH --tmp=1T      # ask for 1 TB of it
best fora per-job copy that every epoch reads

/dev/shm

/dev/shm is a tmpfs: a file system whose files live in RAM, with no disk underneath. Any program that opens files can use it, at memory speed. It is also where processes share memory, which is how DataLoader workers hand batches to the trainer. By default it may grow to half the RAM, every byte in it is memory the job no longer has, and with cgroups it counts against the job's --mem. Its files disappear at reboot and, on many clusters, when the job ends.

df -h /dev/shm        # size, and how much is used
du -sh /dev/shm/*     # what is in it
rm -rf /dev/shm/$USER-*  # clean up afterwards
best forsmall, hot files and shared memory

Keep the only copy on Lustre, copy what each node reads to its NVMe disk, and put only small, hot files in /dev/shm.

How a batch is built

18 samples, 4 ranks, batch size 2: small enough to follow every index

rank
epoch0

The hardware behind the two links

NVLink inside one node

The eight-GPU board of an Nvidia DGX B200: eight GPU modules under their heat sinks on one baseboard
This photograph loads from Wikimedia Commons and needs a connection.
Open the photograph’s page
The 8-GPU board of an Nvidia DGX B200. Photo: Pokiiri, Wikimedia Commons, CC BY-SA 4.0.

Nvidia’s own link from GPU to GPU. It is not a cable you plug in: on a board like this one, the eight GPUs sit side by side and the link is wiring in the board itself, joined by NVLink switch chips, so every GPU reaches every other one directly.

  • GPU to GPU
  • never leaves the node
  • 600 to 900 GB/s on A100, H100

InfiniBand between nodes

An InfiniBand switch in a rack with many cables plugged into its ports
This photograph loads from Wikimedia Commons and needs a connection.
Open the photograph’s page
An InfiniBand switch and its cables. Photo: ChrisDag, Wikimedia Commons, CC BY 2.0.
A dual-port InfiniBand adapter card for a server
This photograph loads from Wikimedia Commons and needs a connection.
Open the photograph’s page
The adapter card that goes into each node. Photo: Dmitry Nosachev, Wikimedia Commons, CC BY-SA 4.0.

The network that joins the nodes. Each node carries an adapter card; cables run from it to a switch, and switches connect to one another. Data goes from the memory of one node straight into the memory of another (RDMA), without passing through the operating system on the way.

  • adapter, cable, switch
  • node to node
  • 25 to 50 GB/s per port