Time is limited because one GPU sets a ceiling on samples per second.
Memory is limited because the model, optimizer and activations must fit on the device.
Operations suffer on a shared cluster, where jobs queue, time out, fail and multiply.
Scaling a run means moving all three walls, usually in this order.
Four levers
More GPUs raise throughput, and sharding lets them pool their memory.
Fewer bytes per parameter and per activation make a model fit.
Less waiting keeps each GPU busy before you add another.
Less babysitting lets a long run survive queues and failures.
How to read the deck
Each section opens with the problem, then shows the mechanism, then the code.
The left panel animates the idea, and the right panel shows the code where it matters.
The training script stays the same from 1 GPU to 384, while the launch command changes.
The last section compares the trackers and maps how the techniques connect.
Why one GPU is not enough
The problem1 / 3
Time wall
Time: one GPU sets the pace
One GPU processes a fixed number of samples per second.
Training time is samples × epochs ÷ throughput, and only the throughput can change.
At 1,000 images/s, 1.28M images × 90 epochs take about 32 hours.
Measure the single-GPU throughput first, because it is the baseline for everything else.
Memory: the model must fit
Mixed-precision Adam needs about 16 bytes per parameter, or 16P bytes for P parameters.
An 80 GB GPU is full at 5B parameters with no room left for activations.
Activations add more, in proportion to batch size and sequence length.
Past this wall more speed is not enough, because the states themselves must be split.
The goal: speedup you can keep
Perfect scaling gives N times the throughput on N GPUs.
Real jobs lose some to communication, data loading and the slowest rank.
In this chart, 64 GPUs give a 15.4× speedup, which is an efficiency of 24%.
At 50% efficiency, half of the GPU budget is wasted.
Three ways to split training
Parallelism strategies1 / 3
Data parallel
PyTorch
# One full replica per GPU; split the batchmodel = DDP(model.to(local_rank),device_ids=[local_rank])# Shard each layer's weights across 4 GPUsmesh = init_device_mesh("cuda", (4,))parallelize_module(block.mlp, mesh, {"fc1": ColwiseParallel(),"fc2": RowwiseParallel(),})# One stage per GPU, 4 micro-batchespipe = pipeline(model, mb_args=(x_mb,), split_spec={ f"layers.{2 * i}": SplitPoint.BEGINNING for i in (1, 2, 3)})stage = pipe.build_stage(rank, device)schedule = ScheduleGPipe(stage, n_microbatches=4)schedule.step(x) # rank 0 feeds the batch
Copy the model, split the data
Every GPU holds the full model and trains on its own slice of the batch.
An all-reduce averages the gradients, so the replicas stay identical.
Throughput scales with GPUs, but memory per GPU does not shrink.
Split every layer
Each GPU holds a quarter of every weight matrix in the MLP.
Column-split fc1 and row-split fc2 need only one all-reduce in forward.
Layers talk in every forward and backward, so keep this on NVLink.
Split the layers into stages
Each GPU runs a block of consecutive layers, which is one pipeline stage.
Micro-batches flow through the stages so they work at the same time.
With stages and micro-batches, of the time is idle.
The dots count the activations a stage keeps for backward, and 1F1B keeps fewer of them.
The problem DDP solves
Before the code1 / 3
One GPUAnimated diagram of a single-GPU training loop, the limits of DataParallel, and the four guarantees DistributedDataParallel provides.The baseline: one process, one GPUbatch1DataLoader yields x, y;.cuda() moves themforward2layer by layer; everyactivation is keptloss3one number: how faroutput is from labelbackward4chain rule in reverse:one gradient per weightoptimizer.step()5AdamW nudges everyweight downhillnext mini-batchOne Python processruns the loop on the CPUDataLoader workersread, decode and collatebatch x, ypinned, ready to copyGPU 0One card holds everything the loop touchesand each step reads or writes a different partbatchx, y of this stepweightsthe model itselfactivationskept for backwardgradientsone per weightAdamW statetwo moments eachNothing to synchroniseone set of weights, one optimizerOne batch at a timespeed is capped by one GPUOne card of memorymodel and batch must fit on itFirst attempt: nn.DataParallelWhat DDP has to guaranteeOne process per GPUno shared interpreter; the same code spans machinestorchrunslide: launch and initializationDisjoint datano two ranks train on the same sample in a stepDistributedSamplerslide: split dataset indicesIdentical weightsevery replica starts the same and stays the sameDDP(model)slide: replicas and optimizerOne shared gradientlocal gradients are averaged before each updateall-reduce in backward()slide: backward and updateOne GPU
From one GPU to many
for x, y in loader: x, y = x.cuda(), y.cuda() # 1 batch out = model(x) # 2 forward loss = criterion(out, y) # 3 loss loss.backward() # 4 backward optim.step(); optim.zero_grad() # 5 updatemodel = nn.DataParallel(Net().cuda()) # one processout = model(x) # scatter x, copy weights, run threads,# gather the outputs on GPU 0loss = criterion(out, y.cuda()) # computed on GPU 0dist.init_process_group("nccl") # process per GPUsampler = DistributedSampler(dataset) # disjoint datamodel = DDP(model, device_ids=[local_rank])loss.backward() # all-reduce: one shared gradientoptim.step() # the same update on every rank
Start from the loop you know
One process owns the model, the optimizer and the data loader.
Each step moves a batch to the GPU, runs forward and backward, then updates.
Nothing is shared, so nothing has to be kept in sync.
The question is how to run N of these loops without the copies drifting apart.
Where one GPU stops
Speed and memory are both capped by what a single card can do.
Why DataParallel is not the answer
It splits each batch across GPUs from inside a single process.
The weights are copied to every GPU again on each forward pass.
Python threads drive the replicas, so the interpreter lock limits them.
Outputs and gradients collect on GPU 0, which fills up first.
Watch out
It is one line, so it survives in old tutorials, but PyTorch itself recommends DDP.
Four guarantees, four mechanisms
Separate processes remove the interpreter lock and work across machines.
A distributed sampler gives each process its own share of the data.
DDP broadcasts the weights once, then keeps every update identical.
An all-reduce during backward gives every process the same averaged gradient.
Why it matters
Break any one guarantee and the replicas silently diverge.
Rank, local rank, world size
Vocabulary1 / 3
One machineDiagram of processes on one and on two machines with their local rank, rank and world size, and what each number is used for.One machine: a process per GPUone machine, four GPUs, four Python processesGPU 0local rank0rank0GPU 1local rank1rank1GPU 2local rank2rank2GPU 3local rank3rank3world size = 4: the number of processes in the jobTwo machines: the two numbers part waysnode 0GPU 0local rank0rank0GPU 1local rank1rank1GPU 2local rank2rank2GPU 3local rank3rank3node 1GPU 0local rank0rank4GPU 1local rank1rank5GPU 2local rank2rank6GPU 3local rank3rank7world size = 8: every process on every nodeWhich number answers which questionWhich GPU is mine?an index on this machine onlylocal_ranktorch.cuda.set_deviceWho am I in the job?my share of the data; rank 0 logs and savesranksampler, logging, checkpointsHow many of us are there?how the data and the batch are dividedworld_sizesampler, global batchenvironment variables torchrun sets for every processLOCAL_RANKRANKWORLD_SIZEMASTER_ADDRMASTER_PORTOne machine
Reading the three numbers
local_rank = int(os.environ["LOCAL_RANK"]) # 0..3 heretorch.cuda.set_device(local_rank) # my GPUdist.init_process_group("nccl") # join the grouprank = dist.get_rank() # 0..7, uniqueworld_size = dist.get_world_size() # 8device = torch.device("cuda", local_rank) # which GPUsampler = DistributedSampler(dataset, # which datanum_replicas=world_size, rank=rank)if rank == 0: # who writes save_checkpoint(model)global_batch = batch_size * world_size # how many
A job is a set of numbered processes
A distributed job is a set of Python processes, one per GPU, each running the whole script.
Local rank numbers the processes on one machine, starting at 0.
It doubles as the GPU index, so local rank 2 drives cuda:2.
World size counts every process, and on one machine the rank equals the local rank.
Rank is global; local rank is not
The launcher gives every process in the job a rank, from 0 to world size − 1.
Local rank starts again at 0 on each node, because each node numbers its own GPUs.
Using rank as the GPU index fails on the second node, because it has no cuda:5.
Using local rank for the data makes two nodes read the same samples.
Three numbers, three jobs
Use local rank only to choose the device.
Use rank to give each process its share of the data and to let rank 0 log and save.
Use world size wherever work is divided, as in the sampler and the global batch.
Torchrun sets all three as environment variables before main() starts.
Also
The ranks join a process group at the master address, and NCCL carries its messages.
DDP code: launch and initialization
DistributedDataParallel1 / 3
Launch processesAnimated four-rank DDP diagram. Advance with the presentation arrows to reveal each stage alongside its code.One host, four training processestorchrun--nproc_per_node=4Process 0Process 1Process 2Process 3LOCAL_RANK = 0GPU 0LOCAL_RANK = 1GPU 1LOCAL_RANK = 2GPU 2LOCAL_RANK = 3GPU 3NCCL process groupRANK 0RANK 1RANK 2RANK 3WORLD_SIZE = 4Launch processes
Running torchrun --nproc_per_node=4 train.py starts four copies of the script.
Each process runs main() on its own, and no Python state is shared between them.
Torchrun sets RANK, LOCAL_RANK, WORLD_SIZE and the master address for each one.
If one worker fails, torchrun stops the group, or restarts it with --max-restarts.
Select the local device
The value of LOCAL_RANK numbers the GPUs on this machine, from 0 to 3 here.
Calling set_device makes later CUDA and NCCL calls use that GPU.
Without it, every process would put its memory and kernels on GPU 0.
Set it before creating tensors or the process group.
Join the process group
All processes meet at the master address and form one group.
Every rank number is unique across machines, and WORLD_SIZE counts every process.
NCCL runs the collectives on the GPUs, and gloo replaces it in CPU-only tests.
The call blocks until every process has joined.
Each local GPU is owned by one independent Python process.
DDP code: create the dataset
DistributedDataParallel1 / 3
Seed each rankAnimated four-rank DDP diagram. Advance with the presentation arrows to reveal each stage alongside its code.The same synthetic data on every ranktorch.manual_seed(42)Rank 0same RNG stateRank 1same RNG stateRank 2same RNG stateRank 3same RNG stateFeaturesrandom feature vectorsLabels011010011000 binary targetsTensorDataset(X, y)dataset[i] = (X[i], y[i])Seed each rank
Inside main()
torch.manual_seed(42) X = torch.randn(1000, 128) y = torch.randint(0, 2, (1000,)) dataset = TensorDataset(X, y)
Reproduce the same dataset
Every process runs this code, so each one builds its own copy of the data.
Seeding with 42 first makes all four copies identical.
Without a shared seed, the ranks would hold different random tensors.
Real projects read the same files from shared storage, which has the same effect.
In practice
Seed Python, NumPy and CUDA as well for full reproducibility.
Give augmentation a per-rank seed, such as 42 plus the rank.
Create feature vectors and labels
The matrix holds 1,000 vectors with 128 features each.
The vector holds a class, 0 or 1, for every row of .
The labels are random, so there is nothing to learn here.
The example shows the mechanics of DDP, not a real task.
In practice
Real pipelines read samples from disk instead of holding them in memory.
Keep labels as integer class indices for cross-entropy.
Wrap the tensors
A TensorDataset pairs row of with entry of .
Indexing with dataset[i] returns that pair as one sample.
The dataset itself is not split between ranks.
The sampler on the next slide decides which indices each rank reads.
In practice
Any class with __len__ and __getitem__ is a map-style dataset.
For data too large to index, shard an IterableDataset yourself.
DDP code: split dataset indices
DistributedDataParallel1 / 3
Partition indicesAnimated four-rank DDP diagram. Advance with the presentation arrows to reveal each stage alongside its code.DistributedSampler assigns disjoint indicesShared shuffled index listRank 0250indicesRank 1250indicesRank 2250indicesRank 3250indicessamples per stepfinal step:samplesPartition indices
Inside main()
sampler = DistributedSampler( dataset, num_replicas=world_size, rank=rank, shuffle=True ) loader = DataLoader( dataset, batch_size=32, sampler=sampler )# batch_size applies per process.# The last batch can be smaller.
Create one sampler per process
All ranks shuffle the indices with the same seed, so they agree on the order.
Rank then takes every fourth index, starting at position .
Each rank gets 250 of the 1,000 samples, and no sample appears twice.
If the split is uneven, the sampler repeats a few indices to even it out.
Load a local mini-batch
The sampler replaces shuffle=True, and passing both raises an error.
Each rank batches only its own 250 indices.
The batch size is per process, which makes samples per step in total.
Set num_workers and pin_memory=True so loading keeps up with the GPU.
Account for the last batch
Each rank holds samples, so an epoch has 8 steps.
The last batch is smaller, but every rank has one, so the all-reduces stay in step.
Setting drop_last=True in the DataLoader would skip the short batch.
Equal step counts matter, because a rank with an extra step would wait forever.
DDP code: replicas and optimizer
DistributedDataParallel1 / 3
Build the modelAnimated four-rank DDP diagram. Advance with the presentation arrows to reveal each stage alongside its code.Complete model replicas on four GPUs128 featuresLinear 256ReLULinear 2DDPinitial parameter broadcast from rank 0GPU 0sameGPU 1sameGPU 2sameGPU 3sameAdamWm, v statesAdamWm, v statesAdamWm, v statesAdamWm, v statesBuild the model
Each process builds the full model and moves it to its own GPU.
It maps a 128-feature vector to 256 hidden units, then to two logits.
DDP will replace these weights with rank 0’s copy in the next step.
Every replica must have the same architecture, or the broadcast fails.
Wrap the model with DDP
At construction, DDP broadcasts rank 0’s parameters and buffers.
It registers hooks that all-reduce gradients during backward().
Passing device_ids tells DDP which single GPU this replica uses.
Parameters without gradients need find_unused_parameters=True, which is slower.
Create an optimizer on every rank
Each rank owns an AdamW optimizer for its own replica.
Identical gradients give identical updates, so replicas never drift.
The cross-entropy loss takes raw logits and applies log-softmax itself.
Create the optimizer after wrapping, from model.parameters().
DDP code: local forward pass
DistributedDataParallel1 / 3
Shuffle for the epochAnimated four-rank DDP diagram. Advance with the presentation arrows to reveal each stage alongside its code.Independent forward passes on local batchessampler.set_epoch(epoch)new shuffle every epoch30517264Rank 0indices 3, 7, …Rank 1indices 0, 2, …Rank 2indices 5, 6, …Rank 3indices 1, 4, …[B, 128] + [B]GPU 0[B, 128] + [B]GPU 1[B, 128] + [B]GPU 2[B, 128] + [B]GPU 3logits [B, 2]CE losslogits [B, 2]CE losslogits [B, 2]CE losslogits [B, 2]CE lossShuffle for the epoch
Inside main() · epoch loop
for epoch inrange(10): sampler.set_epoch(epoch) model.train()for images, labels in loader: images = images.to(local_rank) labels = labels.to(local_rank) optimizer.zero_grad() outputs = model(images) loss = criterion(outputs, labels)
Set the epoch before loading
Calling set_epoch(epoch) reseeds the shared shuffle for this epoch.
Without it, every epoch would visit the samples in the same order.
Calling model.train() re-enables dropout after an evaluation pass.
Watch out
A missing set_epoch is a silent bug, because training still runs without it.
Load and transfer the local batch
Each rank’s loader yields only that rank’s indices.
Each .to(local_rank) copies the batch to this rank’s GPU.
With pin_memory=True, the copy can overlap with compute using non_blocking=True.
In practice
Several loader workers per GPU keep the input pipeline from stalling.
Compute local logits and loss
Calling zero_grad() clears the gradients from the previous step.
The forward pass sees only this rank’s 32 samples, with no communication.
Each rank’s loss differs because each rank saw different samples.
Watch out
The loss is never synchronized across ranks, and only the gradients are averaged.
DDP code: backward and update
DistributedDataParallel1 / 3
Local gradientsAnimated four-rank DDP diagram. Advance with the presentation arrows to reveal each stage alongside its code.Different local gradients, one shared updateOne scalar from a gradient bucketRank 0batch 0 lossRank 1batch 1 lossRank 2batch 2 lossRank 3batch 3 lossNCCL bucket all-reducethe surface is the mean of the four lossesthe averaged stepAdamWAdamWAdamWAdamWLocal gradients
Continued inside the mini-batch loop
# loss is local to this rank.# Gradients come from different samples. loss.backward() optimizer.step()
Different batches produce different gradients
All ranks hold the same weights θ, but each batch has its own loss surface.
So the downhill direction −g, drawn as an arrow, differs from rank to rank.
Their mean is the gradient of the loss over all 128 samples.
That mean is what a single GPU would compute on the full batch.
Watch out
Batch-norm statistics are not averaged, so convert to SyncBatchNorm if you need that.
Backward triggers synchronization
DDP groups the gradients into buckets of about 25 MB.
When a bucket is ready, its all-reduce starts while backward continues.
When backward() returns, every rank holds the same averaged gradient.
The grey surface is the mean of the four losses, and the teal arrow is its downhill step.
In practice
Gradient accumulation uses no_sync() to skip this all-reduce.
Each optimizer updates its local replica
Each rank calls optimizer.step() with the same gradients.
AdamW’s moment estimates evolve identically on every rank.
Only gradients cross the network, and the parameters are never sent after the broadcast.
The replicas therefore stay identical for the whole run.
On every surface the weights make the same move, from θ to θ′.
Watch out
Never step the optimizer on one rank only, because the replicas would diverge.
Training, step after step
DistributedDataParallel1 / 1
The loopAnimated loss surface. Four ranks compute gradients on their own batches, the gradients are averaged, and the weights move; the loop repeats for four epochs.One update, repeated for four epochsThe loop
The loop every rank runs
for epoch in range(4): sampler.set_epoch(epoch) # new shuffle for X, y in loader: # this rank's batch loss = loss_fn(model(X), y) optimizer.zero_grad() loss.backward() # grads + all-reduce optimizer.step() # same step, all ranks
The same three moves, thousands of times
Every step computes four local gradients, averages them, and moves all ranks identically.
The average is a noisy estimate of the full-data gradient, so the path wobbles.
An epoch ends when every sample has been used once, and set_epoch then reshuffles.
Early steps are long because the slope is steep, and they shrink near the bottom.
Try it
Set the ranks to 1, and one batch per step gives a rougher path to the same place.
DDP code: logging and cleanup
DistributedDataParallel1 / 3
Log on rank 0Animated four-rank DDP diagram. Advance with the presentation arrows to reveal each stage alongside its code.One log stream, cleanup on every rankRank 0GPU 0Rank 1GPU 1Rank 2GPU 2Rank 3GPU 3RANK 0 / STDOUTEpoch 0 completedone print per epochRanks 1–3 train without printing, so the log has no duplicates.destroy_process_group() on all four ranksRank 0 closedRank 1 closedRank 2 closedRank 3 closedif __name__ == "__main__": main()torchrun --standalone --nproc_per_node=4 train.pyLog on rank 0
Complete the epoch loop and program
if rank == 0:print(f"Epoch {epoch} completed") dist.destroy_process_group()if __name__ == "__main__":main()
Log once per epoch
All ranks train, but only rank 0 prints, so each message appears once.
The same rule applies to checkpoints and experiment trackers.
To report a global metric, all-reduce it first, then log it on rank 0.
A collective inside a rank 0 branch hangs, because the other ranks never join it.
In practice
Use dist.barrier() sparingly, because it only makes the ranks wait for each other.
Release distributed resources
Calling destroy_process_group() frees the NCCL communicators.
Every rank calls it once training is done.
Skipping it can leave warnings or hangs when the processes exit.
Put it in a finally block so it runs even when training fails.
Watch out
Destroying the group while other ranks still train makes them hang.
Run main in each launched process
Torchrun runs this file once per process.
The __main__ guard keeps imports from starting training.
The same script runs on 1 GPU or on 64, and only the launch command changes.
Torchrun sets the environment variables before main() starts.
In practice
Test with one process first, then scale up the launch command.
Inside the all-reduce
All-reduce1 / 3
Bucket the gradientsAnimated diagram of DDP gradient buckets and a ring all-reduce across four GPUs.Gradients are reduced in buckets during backwardRing all-reduce = reduce-scatter + all-gatherGPU 0GPU 1GPU 2GPU 30123012301230123Reduce-scattersteps; each GPU endswith the full sum of one chunkAll-gathermore steps; everyGPU receives all summed chunksData each GPU sendsaboutwhatever the number of GPUsBucket the gradients
PyTorch
model = DDP(model, device_ids=[local_rank],bucket_cap_mb=25) # the defaultloss.backward() # full buckets start all-reducing# What all_reduce does to one bucket (ring)shard = bucket.new_empty(bucket.numel() // world)dist.reduce_scatter_tensor(shard, bucket)# Every GPU shares its summed chunkdist.all_gather_into_tensor(bucket, shard)bucket /= world # sum -> mean
Overlap communication with backward
DDP packs gradients into buckets of about 25 MB in reverse layer order.
A bucket’s all-reduce starts as soon as all of its gradients exist.
Meanwhile backward keeps computing the earlier layers.
A larger bucket_cap_mb means fewer messages but less overlap.
Watch out
A parameter that never gets a gradient blocks its bucket.
Reduce-scatter around a ring
Each bucket is cut into chunks, one per GPU.
In steps, each GPU passes a chunk to its neighbour, which adds its own copy.
At the end, each GPU holds the full sum of one chunk.
Every link is busy at every step, so no GPU becomes a bottleneck.
Why it matters
Each GPU sends only in this phase.
All-gather the summed chunks
Another steps pass the finished chunks around the ring.
Each GPU sends in total for a bucket of size .
That is about however many GPUs join, so the cost per GPU stays flat.
Dividing by turns the sum into the mean gradient.
In practice
NCCL picks rings or trees by message size and topology.
Where the memory goes
The problem1 / 3
Four consumersAnimated diagram of the four consumers of GPU memory in training, how each grows, and which technique reduces each.Four consumers on every GPU6%6%36%44%othermemory of one GPU during a training stepParametersthe weights: a 16-bit copyfor the forward pass+ expandGradientsone value per weightafter backward()+ expandOptimizer statesfp32 master weights andAdam's two moments+ expandActivationsevery layer output, keptfor the backward pass+ expandWhat grows with whatmemorybatch size per GPU8163264states: fixed by the modelactivationsGPU capacityout of memoryStates16 bytes per parameter;the batch does not change themActivationsbatch × tokens × width × depth;they grow with every sampleMatch the lever to the consumerParameters, gradients, optimizer statesthe same bytes on every GPUFSDP or ZeROshard them across GPUsActivationsstored at full precisionautocast to 16 bitshalve every tensorActivationsall kept until backwardcheckpoint(block, x)recompute instead of storingActivationsone large batch at onceaccumulate k micro-batchessame update, smaller peakStill too largeeven when shardedZeRO-Offloadmove states to CPU or NVMeFour consumers
Know the four terms
Parameters and gradients each hold one value per weight.
Optimizer states are the largest fixed term, at 12 of the 16 bytes per parameter.
Activations are every intermediate tensor that backward will need.
The rest is the CUDA context and the allocator cache, which torch.cuda.max_memory_allocated() does not count.
Two different growth laws
The states depend only on the parameter count, not on the batch.
Activations scale with batch size, sequence length, width and depth.
Sweep the batch size once and the two terms separate.
Halving the batch shrinks only the activations, so states that do not fit need sharding.
Each lever fits one term
Sharding divides the states by the number of GPUs.
Autocast halves the activations, and checkpointing trades them for extra compute.
Accumulation lowers the peak by running smaller micro-batches.
Offloading is the last resort, because it always costs speed.
FSDP: shard everything
torch.distributed.fsdp1 / 3
Shard the modelAnimated diagram of fully sharded data parallel training on four GPUs.Every GPU keeps one slice of every unitBlock 1Block 2Block 3GPU 0GPU 1GPU 2GPU 3Block 1 sliceBlock 2 sliceBlock 3 sliceBlock 1 sliceBlock 2 sliceBlock 3 sliceBlock 1 sliceBlock 2 sliceBlock 3 sliceBlock 1 sliceBlock 2 sliceBlock 3 sliceDDPFSDPForward: gather a unit, use it, free itcommunicationcomputeAG1AG2AG3F1F2F3timeBackward: gather again, then reduce-scatterGPU 0GPU 1GPU 2GPU 3parameter slicesgatherfull parametersbackwardfull gradientsreduce-scatterGPU 0 keepsits summed slicethen optimizer.step()AG3B3AG2RS3B2AG1RS2B1RS1stepPeak memory stays near one GPU’s slicesplus the one or two units that are gathered at the moment.Shard the model
PyTorch
from torch.distributed.fsdp import fully_shardfor block in model.blocks: # one unit per blockfully_shard(block)fully_shard(model) # then the rootoptim = torch.optim.AdamW(model.parameters())out = model(x) # gather, forward, free each unitloss.backward() # gather, backward, reduce-scatteroptim.step() # updates this rank's slice only
Shard parameters, gradients and optimizer states
fully_shard splits every parameter of a unit, here one block, across the GPUs.
With parameters, a GPU keeps about bytes instead of .
Each call makes one unit, and smaller units lower peak memory but add messages.
Sharding avoids full replicas, at the cost of extra all-gathers.
In practice
Shard each block, then the root, and create the optimizer only afterwards.
FullyShardedDataParallel is the older FSDP1 wrapper, and new code uses fully_shard.
Gather a unit, use it, free it
Before a unit runs, an all-gather rebuilds its full parameters on every GPU.
After the unit’s forward, the full copy is freed and only the shard stays.
All-gathers run on their own stream, so the next one overlaps the current compute.
Peak memory is one full unit plus the shards, not the whole model.
In practice
Activation checkpointing pairs well, since it frees activations while FSDP frees weights.
Reduce-scatter the gradients
Backward gathers each unit again and computes its gradients.
A reduce-scatter leaves each GPU the summed gradient of its own slice.
The optimizer updates only that slice, so its states stay sharded too.
Total traffic is about 1.5 times that of DDP.
In the figure, RS stands for reduce-scatter.
Watch out
state_dict() returns sharded tensors, so save them with distributed checkpoint.
Fitting more on each GPU
Memory savers1 / 3
Mixed precisionAnimated diagram of mixed precision, gradient accumulation and activation checkpointing.Mixed precision: fewer bits per numberGradient accumulation: several micro-batches per updateGPU 0stepGPU 1stepGPU 2stepGPU 3stepall-reduceno_sync()no_sync()no_sync()sync.gradmicro-batchstepsGPUsper updateActivation checkpointing: recompute, don’t storeMixed precision
PyTorch
scaler = torch.amp.GradScaler("cuda") # fp16 onlywith torch.autocast("cuda", dtype=torch.float16): loss = loss_fn(model(x), y)scaler.scale(loss).backward()scaler.step(optim); scaler.update()for i, (x, y) in enumerate(loader): sync = (i + 1) % k == 0 with nullcontext() if sync else model.no_sync(): (loss_fn(model(x), y) / k).backward() if sync: optim.step(); optim.zero_grad()from torch.utils.checkpoint import checkpointfor block in self.blocks: # in forward() x = checkpoint(block, x, use_reentrant=False)
Train in 16-bit
fp32 keeps about 7 significant digits, fp16 about 3 and bf16 about 2.
The bf16 format keeps fp32’s 8 exponent bits, so it rarely overflows and needs no scaler.
With only 5 exponent bits in fp16, GradScaler scales the loss so small gradients survive.
Activations take half the memory, and Tensor Cores run much faster.
Autocast runs matrix multiplies in 16-bit, while softmax and the loss stay in fp32.
Accumulate before syncing
Run micro-batches, then take one optimizer step.
The no_sync() context skips the all-reduce for the first micro-batches.
Dividing each loss by keeps the gradient an average.
Each update sees samples with GPUs.
Accumulation saves memory but not time, because each update takes passes.
Recompute instead of storing
Only each block’s input is saved during the forward pass.
Backward re-runs the block to rebuild its activations when needed.
The cost is about one extra forward pass, roughly a third more compute.
Use use_reentrant=False, the implementation PyTorch recommends.
Checkpoint every block, or every few, to trade compute for memory.
Where the time goes
Profiling1 / 3
Split the stepAnimated breakdown of a training step, a profiler trace with an operator table, and a table of symptoms and causes.Split one training stepwait for datacopy to GPUforwardbackwardall-reduceoptimizerA healthy step32%42%10%8%92%GPU busyAn input-bound step55%15%19%42%GPU busyTrace a few stepsWatch every GPU, then drill downnvidia-smi dmonone node, liveDCGMevery GPU, over timeNsight Systemsone process, in depthpy-spya stuck PythonGPU utilisation low, CPU cores saturatedthe loader cannot keep upinput pipelineGPUs busy, yet efficiency drops with scaletime goes into all-reducecommunicationOne rank slower than the otherseveryone waits for it at each all-reducea stragglerUtilisation dips at regular intervalsthe job pauses on something periodiccheckpoints, epoch restartsSplit the step
Timers, profiler and monitors
for x, y in loader: # t0 set before the loop t1 = time.perf_counter() # waited for data train_step(x, y); torch.cuda.synchronize() t2 = time.perf_counter() # computed data_t += t1 - t0; step_t += t2 - t1; t0 = t2from torch.profiler import profile, schedulesch = schedule(wait=10, warmup=5, active=20, repeat=1)with profile(schedule=sch, profile_memory=True) as p: for x, y in loader: # CPU + CUDA by default train_step(x, y); p.step()p.export_chrome_trace("trace.json")print(p.key_averages().table(sort_by="cuda_time_total", row_limit=10))nvidia-smi dmon-s um -d 5 # utilisation, memorydcgmi dmon-e 203,1002,1004 # util, SM, Tensor Coresnsys profile-t cuda,nvtx,osrt python train.pypy-spy dump--pid $PID # where is Python stuck?
Measure before you add GPUs
Time two things in every step, the wait for the batch and the compute on it.
Call torch.cuda.synchronize() before reading the clock, because CUDA calls return early.
If data time is a large share, more GPUs will only wait faster.
From outside both steps look the same, and only a breakdown tells them apart.
Let the profiler name the operators
The schedule skips warm-up steps and records only a short window.
The table ranks operators by the GPU time spent inside them.
Perfetto or chrome://tracing opens the trace with one lane per thread and CUDA stream.
Profiling slows training down, so record tens of steps, not epochs.
Read the symptom, find the cause
Utilisation says only that a kernel ran, while SM and Tensor Core activity say how hard.
Low utilisation with busy CPUs points at the input pipeline.
A slow rank holds everyone back, since each all-reduce waits for all.
Nsight Systems shows CUDA, NCCL and the OS on one timeline when the cause is unclear.
Inside one GPU
GPUArchitecture1 / 3
Host to deviceDiagram of the path from host memory to the GPU, the layout of streaming multiprocessors and Tensor Cores, and throughput against batch size.From host memory to the deviceInside the chipGPU die: an array of streaming multiprocessors (SMs)HBM memory stacks beside the diean A100 has 108 SMsone SMCUDA coresgeneral fp32 and integer workTensor Coresmatrix multiply: fp16, bf16, TF32On-chip memoryregisters, L1 and shared memory+ expand+ expand+ expandA kernel is many threadsgrouped in blocks; each blockruns on one SMKeep the SMs busysamples per secondbatch size per GPU (log scale)141664256launch overheaddominatesevery SM busy:throughput is flatUse 16 bits or TF32otherwise the Tensor Coressit idleDo not sync inside the loop.item() and print() makePython wait for the GPUKeep shapes fixedcuDNN and the compiler canthen pick the fastest kernelHost to device
Settings that follow from the hardware
dl = DataLoader(ds, batch_size=256, pin_memory=True)x = x.to("cuda", non_blocking=True) # async copyout = model(x) # returns before it is donetorch.cuda.synchronize() # wait, e.g. before timing# TF32 on the Tensor Cores for fp32 matmulstorch.set_float32_matmul_precision("high")# convolutions use TF32 by defaultwith torch.autocast("cuda", dtype=torch.bfloat16): out = model(x) # 16-bit matmulsmodel = model.to(memory_format=torch.channels_last)torch.backends.cudnn.benchmark = True# fixed shapesif step % 50 == 0: log(loss.item()) # .item() waits for the GPUprint(torch.cuda.get_device_name(0)) # which GPU?
The link into the GPU is the narrow part
Batches reach the GPU over PCIe, at about 32 GB/s on PCIe 4.0 ×16 and 64 GB/s on 5.0.
Pinned memory lets that copy run asynchronously, beside the compute.
Inside the GPU, HBM feeds the cores at 1.5 to 2 TB/s, some 50 times faster.
So keep data on the device once it is there, and avoid round trips to the CPU.
Watch out
CUDA calls return before the work is done, so an unsynchronised timer reads too low.
Thousands of cores, grouped in SMs
A GPU is an array of streaming multiprocessors, each of which runs many threads.
Tensor Cores inside each SM do the matrix multiplies of deep learning.
They are used at fp16, bf16 or TF32, not at plain fp32.
TF32 keeps fp32 tensors but rounds the mantissa inside the multiply.
In practice
channels_last lets convolutions use the Tensor Cores without reshuffling memory.
Utilisation is yours to lose
Very small batches spend their time launching kernels, not running them.
Once every SM is busy, a larger batch only adds memory.
Each .item() or print of a tensor stalls Python until the GPU catches up.
Fixed input shapes let cuDNN benchmark once and reuse the best algorithm.
Feeding the GPUs
Data pipeline1 / 3
A starved GPUAnimated timelines of a GPU waiting on a single-process loader, of parallel workers with a prefetch queue, and of the CPU core budget on a node.A starved GPUWorkers build batches aheadBudget the CPU cores per rankA starved GPU
DataLoader settings
loader = DataLoader(ds, batch_size=256)for x, y in loader: # decode + augment run here, train_step(x, y) # between two GPU stepsloader = DataLoader(ds, batch_size=256,sampler=sampler, drop_last=True,num_workers=8, # per rankpin_memory=True, # page-locked memorypersistent_workers=True, # kept across epochsprefetch_factor=2) # batches per workerjob.sbatch#SBATCH --gpus-per-node=8 --cpus-per-task=96train.pycores = len(os.sched_getaffinity(0)) # SLURM's grantworkers = min(8, cores // gpus_per_node - 1)
The problem: loading and training take turns
By default the DataLoader builds each batch in the training process.
Decoding and augmenting images is CPU work, and one core is slow.
With 0.5 s to build a batch and 0.15 s to train on it, the GPU is busy 23% of the time.
Adding GPUs makes this worse, because each one needs its own stream of batches.
The fix: build batches in parallel, ahead of time
Each worker is a separate process that produces whole batches.
The prefetch queue holds finished batches and absorbs the slow samples.
Persistent workers avoid restarting every process at each epoch.
Pinned memory and non_blocking=True let the copy overlap the previous step.
In practice
Raise num_workers until data time per step stops falling.
Workers multiply with ranks
Each rank has its own DataLoader, so 8 ranks × (1 trainer + 8 workers) are 72 processes.
Request the cores with --cpus-per-task, or the workers share a few.
Use os.sched_getaffinity, not os.cpu_count, to see what the job really owns.
If the CPUs still cannot keep up, move decoding to the GPU with DALI.
Watch out
Each worker copies the dataset object, so a large in-memory index is multiplied too.
Sharded streaming data
WebDatasetLarge datasets1 / 3
Small filesDiagram of small-file access through a metadata server, of tar shards with a shuffle buffer, and of shard assignment to ranks and workers.Millions of small filesOne whole-slide imageH&Eone gigapixel scan of tissue,cut into about 20,000 tilesOne tileat (18432, 7168)256 × 256pixels≈ 15 KBas JPEG1training samplethe label sits in a table, keyed by slideTwo ways to store the tilesone HDF5 per slide, as CLAM writespatches/slide_00421.h5 coords [20134, 2] tile corners imgs [20134, 256, 256, 3] optionalone image per tiletiles/slide_00421/x18432_y07168.jpg … and 20,133 more in this folder5,000 slides:5,000 filesor100 million filesWhat one sample costs on a shared filesystemper-slide HDF5 skips the opens; the reads stay small and random512 loader workers64 ranks × 8 eachmetadata serverfile per tile: a lookupand an open() per samplestorage targetslookup, openread 15 KB100M opens per epochwith one image file per tile1.5 TB in 15 KB piecesthe disks seek instead of streaming512 workers at onceall asking the same metadata serverPack samples into shardsEach rank and worker takes its own shardsSmall files
From files to shards
class Tiles(Dataset): # map-style def __getitem__(self, i): return decode(open(self.paths[i], "rb").read())# 100M tiles: 100M opens per epoch on shared storageimport webdataset as wdsurls = "/lustre/tiles/tiles-{000000..009999}.tar"ds = (wds.WebDataset(urls, shardshuffle=10_000,nodesplitter=wds.split_by_node) .shuffle(10_000) # in-memory buffer .decode("pil").to_tuple("jpg", "cls").batched(256))dl = wds.WebLoader(ds, batch_size=None, num_workers=8)steps = n_samples // (256 * world_size)dl = dl.with_epoch(steps) # the same on every rank# plain IterableDataset: info = get_worker_info()mine = shards[rank::world][info.id::info.num_workers]
The problem: one file per sample
Saved one image per tile, 5,000 slides of 20,000 tiles are 100 million files.
A map-style dataset opens a file for every index, and each open is a metadata request.
One HDF5 per slide, as CLAM writes, cuts the file count but still reads at random.
Lustre is built for long sequential reads, not for millions of opens.
The fix: large files, read in order
Pack samples into tar shards, where 000123.jpg and 000123.cls form one sample.
Read each shard front to back, because shared storage is best at sequential reads.
Random order comes from shuffling shards, then mixing samples in a buffer.
A larger buffer shuffles better and uses more memory in every worker.
In practice
The same shards stream from object storage through a pipe: URL.
Split shards, not samples
An iterable dataset has no indices, so DistributedSampler does not apply.
Each rank takes its own shards, and each worker a share of those.
WebDataset refuses to run on several ranks until you name a node splitter.
Fix the epoch length with with_epoch, because resampled=True makes the stream endless.
Watch out
Unequal step counts hang DDP at the end of the epoch, as on the sampler slide.
Where the data waits
StorageData path1 / 3
MetadataDiagram of data loaders on two nodes sending one open per sample to a single Lustre metadata server, of a job copying its shards to node-local NVMe once before training, and of a node's memory filled by processes, batches in shared memory and a dataset copied to /dev/shm.Every open goes through one metadata serverCopy the data to the node once/dev/shm is memory with a file nameMetadata
Stage the data, then train
#SBATCH --nodes=2 --gpus-per-node=4#SBATCH --mem=400G --tmp=1T # RAM and local diskexport SRC=/lustre/proj/wsi/shards # tar shards# one copy per node, before training startssrun --ntasks-per-node=1 bash -c \'mkdir -p $TMPDIR/d && cp $SRC/*.tar $TMPDIR/d'srun torchrun --nproc-per-node=4 train.py \ --data "$TMPDIR/d/shard-{000000..000999}.tar"df -h /dev/shm # a tmpfs: half the RAM by defaultcp $SRC/index.parquet /dev/shm/ # small and hotloader = DataLoader(ds, batch_size=256,num_workers=8) # batches cross /dev/shm
One metadata server answers every open
Lustre stores file contents on many storage targets and file names on a metadata server.
A dataset of small files asks that server to open a file for every sample.
If 8 GPUs each read 2,000 images per second, the job asks for 16,000 opens per second.
The server is shared by every job on the cluster, so the GPUs wait whenever it is busy.
Copy once, then read locally
At job start, each node copies the tar shards to its own NVMe disk in one sequential read.
Ask for the space with --tmp, and find the disk at $TMPDIR or the site’s local scratch.
Every epoch after the copy reads locally, with no network and no metadata server.
A dataset larger than the local disk stays on Lustre as shards and streams sequentially.
Treat /dev/shm as part of the job’s memory
/dev/shm is a tmpfs, so its files live in RAM, by default up to half of it.
With cgroups, files there count against the job’s memory, so a big copy can end in OOM.
DataLoader workers also hand every batch to the trainer through shared memory.
A container’s 64 MB default causes bus errors, so start it with --shm-size or --ipc=host.
Compiling the model
torch.compile1 / 3
Eager overheadDiagram of per-operation overhead in eager mode, the torch.compile pipeline and its modes, and guard checks that trigger recompilation.Eager mode pays per operationWhat torch.compile doesTorchDynamoreads the Pythonbytecode, capturesa graph and guards+ expandAOTAutogradtraces thebackward passahead of time+ expandInductorfuses operationsand generateskernels+ expandCompiled codecached and reusedwhile the guardsstill hold+ expandmode=defaultbalanced compile timereduce-overheadreplays CUDA graphsmax-autotunesearches longerGuards decide: reuse or recompileEager overhead
Compile, then train as before
def block(x): # eager: one kernel per op h = x @ w1 + b1 # matmul, add h = F.gelu(h) # gelu return h * g + x # mul, addmodel.compile() # or mode="max-autotune"model = DDP(model, device_ids=[local_rank]) # then wrapfor x, y in loader: loss = loss_fn(model(x), y) # compiled forward loss.backward(); optim.step() # compiled backwardtrain.py# run with TORCH_LOGS=recompiles to see the reasonsloader = DataLoader(ds, batch_size=256, drop_last=True)model.compile(dynamic=True) # or allow any shapesd = model.module.state_dict() # no wrapper prefix
The problem: overhead between kernels
In eager mode, Python decides each operation one at a time.
Every operation pays for the interpreter, the dispatcher and a kernel launch.
Small operations cannot be fused, so each writes its result to memory.
The gain is large for many small operations and small for a few huge matmuls.
The fix: capture once, generate fused code
TorchDynamo captures the forward pass as a graph the first time it runs.
AOTAutograd derives the backward graph before training continues.
Inductor fuses neighbouring operations and emits optimised kernels.
Modes trade compile time for run time, and reduce-overhead replays CUDA graphs.
In practice
Current PyTorch guidance is to compile the inner module, then wrap it in DDP or FSDP.
Compiled code is valid only under its guards
Each compiled graph records the assumptions it was built on.
A new shape, dtype or Python value fails the guards and triggers a recompile.
Use drop_last=True so the last batch has the usual shape.
Every rank compiles for itself, so start-up takes longer on all of them.
Watch out
Exclude the first steps from any timing, because they contain the compilation.
CUDA graphs
torch.cuda.graph1 / 3
Launch costDiagram of per-kernel launch overhead, capturing a training step as a CUDA graph and replaying it with one launch, and the constraints a graph imposes.Every kernel launch has a fixed costEager stepthe CPU launches every kernel separately8 launchesCPUGPUk1k2k3k4k5k6k7k8A launch has a fixed costmicroseconds of CPU work per kernel,whatever the size of the kernelSmall kernels leave the GPU idleit waits while Python and the driverprepare the next launchCapture once, replay with one launchWhat a graph requiresStatic shapesevery replay uses the tensor sizes seen at capturedrop_last=TrueStatic control flowno Python branch on a tensor's value inside the graphtorch.whereFixed memory addressescopy each batch into the captured input tensorsstatic_x.copy_(x)GPU work onlyno .item(), print or other CPU synchronisationlog outsideWarm up firstrun a few steps before capture so allocations settle3 stepsLaunch cost
Capture a step, then replay it
for x, y in loader: # eager loss = loss_fn(model(x), y) # many small launches loss.backward() optimizer.step()g = torch.cuda.CUDAGraph()optimizer.zero_grad(set_to_none=True)with torch.cuda.graph(g): # capture, after warm-up loss = loss_fn(model(static_x), static_y) loss.backward() optimizer.step()for x, y in loader: static_x.copy_(x) # refill in place static_y.copy_(y) g.replay() # one launch
The problem: launches, not math
Each GPU operation is a kernel that the CPU has to launch.
A launch costs CPU time in Python, the dispatcher and the driver.
With small batches or many tiny kernels, launching outweighs computing.
The sign is low GPU utilisation while one CPU core sits at 100%.
A CUDA graph records the launch sequence
Capture runs the step’s code once and records each kernel launch instead of executing it.
The record is a graph with the kernels as nodes and their order as edges.
g.replay() hands the whole graph to the driver in one call.
The kernels are unchanged, and only the CPU work between them disappears.
Replay repeats exactly what was captured
Shapes, control flow and memory addresses are frozen at capture.
New data goes in by copying into the captured input tensors.
Read loss after the replay, because anything that syncs the CPU must stay outside.
torch.compile(mode="reduce-overhead") does all of this for you.
When it pays
It pays with small batches and many small kernels, where the step is CPU-limited.
What breaks beyond one node
SLURMThe problem1 / 3
A shared machineAnimated diagram of the scheduler queue, the bandwidth inside and between nodes, and job survival against node count.You share the machinelogin nodesbatch job.sbatchno GPUs herescheduler queue81230Rrunning, 19 h left81231Rrunning, 2 h left81234PDyours: Priority81235PDResources81236PDResourcescompute nodesin usein usein usein useyoursyoursin usein useLinks get slower as they get longernode 0GPU 0GPU 1GPU 2GPU 3NVLinknode 1GPU 0GPU 1GPU 2GPU 3NVLinkInfiniBandbetween nodesbandwidth per GPUNVLink, inside a node600 to 900 GB/sInfiniBand, per port25 to 50 GB/s+ see the hardwareMore nodes, more failureschance that a 24-hour job sees no node failure0%50%100%99%1 node92%8 nodes53%64 nodes0.6%512 nodesCheckpoint and requeuesave often; resume fromthe last stepRestart in placetorchrun restarts acrashed worker groupScale on purposea larger global batchchanges the optimizationA shared machine
A cluster is a shared, scheduled machine
You submit a job from a login node, and the scheduler decides when it starts.
Partitions set a time limit, often 24 or 48 hours.
Higher-priority work can preempt a running job.
A script that assumes it runs once, from start to finish, will not survive a cluster.
Communication now has a geography
GPUs in one node talk over NVLink at hundreds of GB/s.
Between nodes they use InfiniBand at 200 to 400 Gb/s, which is only 25 to 50 GB/s.
An all-reduce is only as fast as its slowest link.
If NCCL falls back to TCP sockets, a multi-node job crawls without any error.
Failure becomes routine
With a 1% chance of failure per node per day, survival is 0.99 to the power of the node count.
At 64 nodes, about half of all day-long jobs are interrupted.
Time limits and preemption interrupt a long run even when nothing breaks.
So every long job needs to checkpoint and resume by itself.
Launching on a cluster
SLURMMulti-node launch1 / 3
Request the nodesAnimated diagram of a two-node SLURM job launched with torchrun.Two nodes, eight GPUs, one jobsbatch job.sbatch--nodes=2 --gpus-per-node=4node 0 (head)torchrunGPU 0GPU 1GPU 2GPU 3node 1torchrunGPU 0GPU 1GPU 2GPU 3c10d :29500RANK 0RANK 1RANK 2RANK 3RANK 4RANK 5RANK 6RANK 7NVLinkNVLinkInfiniBand switchinit_process_group("nccl"): one group of 8 ranksRequest the nodes
SLURM job and training script
job.sbatch#!/bin/bash#SBATCH--nodes=2#SBATCH--ntasks-per-node=1# one torchrun each#SBATCH--gpus-per-node=4head=$(hostname) # the batch script runs on node 0srun torchrun--nnodes=2--nproc_per_node=4 \--rdzv_id=$SLURM_JOB_ID --rdzv_backend=c10d \--rdzv_endpoint=$head:29500 train.pytrain.pylocal_rank = int(os.environ["LOCAL_RANK"]) # 0..3torch.cuda.set_device(local_rank)dist.init_process_group("nccl") # RANK, WORLD_SIZE
Ask SLURM for whole nodes
Two nodes with four GPUs each give eight GPUs in total.
One task per node runs torchrun, which starts one worker per GPU.
Whole nodes keep traffic between local GPUs on NVLink.
Add --exclusive so no other job shares the GPUs or network.
Rendezvous and number the workers
The srun command starts one torchrun agent on each node.
The agents meet at a c10d store on the head node, port 29500.
They assign ranks 0–7 globally and local ranks 0–3 on each node.
Passing the job ID as --rdzv_id keeps separate jobs apart.
Join one NCCL group
The call init_process_group reads the rank and world size from the environment.
NCCL uses NVLink inside each node and InfiniBand between nodes.
The training script is the same as on a single node.
Set NCCL_DEBUG=INFO once to confirm NCCL found the network.
Everyday SLURM commands
SLURMCommand reference1 / 4
Submit and runA reference table of common SLURM commands grouped into submitting, monitoring and inspecting jobs, followed by the main job script options.Submit and runCommandWhat it doesSubmit and runsbatch job.sbatchQueue a batch script; prints the job IDsalloc -N 1 --gpus=4Reserve a node for interactive worksrun python train.pyStart tasks inside an allocationWatch and controlsqueue --meYour jobs: PD pending, R running, and whyscontrol show job 81234Every detail: nodes, limits, reasonscancel 81234Cancel a job, or all of yours with -usinfo -p gpuPartitions and node states: idle, mix, allocAfter the jobsacct -j 81234 -XState, run time and exit codeseff 81234CPU and memory efficiency, if installedsstat -j 81234.0Live usage of a running job stepWatch and controlCommandWhat it doesSubmit and runsbatch job.sbatchQueue a batch script; prints the job IDsalloc -N 1 --gpus=4Reserve a node for interactive worksrun python train.pyStart tasks inside an allocationWatch and controlsqueue --meYour jobs: PD pending, R running, and whyscontrol show job 81234Every detail: nodes, limits, reasonscancel 81234Cancel a job, or all of yours with -usinfo -p gpuPartitions and node states: idle, mix, allocAfter the jobsacct -j 81234 -XState, run time and exit codeseff 81234CPU and memory efficiency, if installedsstat -j 81234.0Live usage of a running job stepAfter the jobCommandWhat it doesSubmit and runsbatch job.sbatchQueue a batch script; prints the job IDsalloc -N 1 --gpus=4Reserve a node for interactive worksrun python train.pyStart tasks inside an allocationWatch and controlsqueue --meYour jobs: PD pending, R running, and whyscontrol show job 81234Every detail: nodes, limits, reasonscancel 81234Cancel a job, or all of yours with -usinfo -p gpuPartitions and node states: idle, mix, allocAfter the jobsacct -j 81234 -XState, run time and exit codeseff 81234CPU and memory efficiency, if installedsstat -j 81234.0Live usage of a running job stepJob script essentials#SBATCH optionWhat it sets--nodes=2Nodes for the job--ntasks-per-node=1Tasks per node: one torchrun each--gpus-per-node=4GPUs reserved on each node--cpus-per-task=32CPU cores per task, for data loading--time=24:00:00Wall-clock limit; the job stops after it--output=logs/%x-%j.outLog file named by job name and job ID--array=0-3132 copies, each with its own task index--requeueAllow a requeue after preemption or node failureEnvironment variables set by SLURMSLURM_JOB_IDSLURM_JOB_NODELISTSLURM_NTASKSSLURM_PROCIDSLURM_ARRAY_TASK_IDLog name patterns%xjob name%jjob ID%Aarray job ID%aarray indexSubmit and run
Commands on the login node
login nodesbatchjob.sbatch# Submitted batch job 81234sbatch--dependency=afterok:81234eval.sbatchsalloc-N1--gpus=4-t1:00:00srun--ptybash# a shell on the nodesqueue--me# PD pending, R runningscontrol show job81234# nodes, limits, reasonscancel81234# or: scancel -u $USERsacct-j81234-X-oJobID,State,Elapsed,ExitCodeseff81234# CPU and memory efficiencyjob.sbatch#SBATCH--nodes=2--ntasks-per-node=1#SBATCH--gpus-per-node=4--time=24:00:00#SBATCH--output=logs/%x-%j.out--requeue
Submit and run
Use sbatch for unattended jobs, since it prints the job ID and returns at once.
With --dependency=afterok:ID, a job starts only after another succeeds.
For debugging, salloc holds a node and srun --pty bash opens a shell on it.
Inside a job, srun starts the tasks the script asked for.
In the figure, job 81234 stands for whatever ID sbatch printed.
Watch and control
The ST column of squeue shows PD for pending and R for running.
A pending job lists its reason, such as Priority or Resources.
Avoid watch squeue, because constant polling loads the shared scheduler.
Use scancel to stop a job, or -u $USER to stop all of yours.
After the job
Use sacct once a job has left the queue, and add -X to hide the job steps.
States such as TIMEOUT or OUT_OF_MEMORY tell you how a job ended.
Where installed, seff compares requested and used CPU and memory.
ExitCode reads status:signal, so 0:0 means a clean finish.
Job script essentials
Only #SBATCH lines before the first command count, and later ones are ignored.
Match nodes, tasks and GPUs per node to the torchrun command.
Name logs with %x and %j, and create logs/ first, because SLURM will not.
Inside the job, SLURM_JOB_ID and SLURM_JOB_NODELIST describe the allocation.
Options given to sbatch on the command line override the #SBATCH lines.
Keeping sessions alive with tmux
tmuxPersistent sessions1 / 3
The problemDiagram of an SSH session lost on disconnect and kept by tmux, a tmux window with three panes, and when tmux is needed on a cluster.A shell dies with its connectionwithout tmuxlaptopssh clientconnection drops✕login nodebashyour SSH shellsallocinteractive jobpython train.pyon the GPU nodewith tmuxlaptopssh clientdetachedlogin nodetmux server: owns the shellsbashsallocpython train.pySessions, windows and panes$ srun torchrun --nproc_per_node=4 train.pystep 4100 loss 0.412 1,912 img/sstep 4150 loss 0.398 1,907 img/sstep 4200 loss 0.391 1,915 img/sstep 4250 loss 0.385 1,910 img/sstep 4300 loss 0.377 1,913 img/s▌$ squeue --me -i 30JOBID NAME ST TIME NODES81234 train R 2:14 181240 eval PD 0:00 1$ nvidia-smi dmon -s um# gpu sm mem fb 0 97 41 61234 1 96 40 61190 2 97 41 61208[train] 0:run* 1:logs 2:tensorboardlogin01panepanepanesessionone workspace, namedwindowa full-screen tab›panea split of a window›Where tmux fits on a clusterA batch job from sbatchthe scheduler already runs it without your shellno tmux neededAn interactive job: salloc, srun --ptyit lives exactly as long as its shellstart it inside tmuxSeveral login nodesthe session exists only where you created itreattach on the same hostMonitoring, long copies, port forwardsanything that should outlive the connectionone window eachThe problem
Start, detach, reattach
laptop, then login nodessh you@login01.cluster # note the login nodetmux new -s train # a named sessionsalloc-N 1 --gpus=4 -t 4:00:00 # the job, inside tmux# Ctrl-b d detaches; everything keeps running# every key follows the prefix Ctrl-b# c new window n / p next, previous# % split left|right " split top/bottom# arrows change pane [ scroll back, q quitstmux split-window -h"squeue --me -i 30"ssh you@login01.cluster # the same nodetmux ls # train: 3 windowstmux attach -t train # back where you lefttmux kill-session -t train # when the work is done
The problem: your work hangs off the connection
A closed lid or a VPN timeout drops the connection, and the SSH shell is hung up with it.
An interactive job from salloc or srun --pty ends with that shell.
tmux runs a server on the login node that owns the shells, and SSH only views them.
Detach with Ctrl-b d, close the laptop, and the session carries on.
One session per experiment
A session is a named workspace, a window is one of its tabs, and a pane splits a window.
The status line names the session and its windows, and a star marks the current one.
A useful layout puts the job in one pane, with the queue and the GPUs beside it.
Every key binding starts with the prefix, Ctrl-b by default.
Know when you need it
Batch jobs do not need tmux, because sbatch already detaches them from your shell.
Interactive jobs do need it, so start tmux first and run salloc inside it.
Clusters have several login nodes, so reconnect to the one that holds the session.
Never train on the login node itself, because tmux is not a way around the scheduler.
Where the bandwidth is
NCCLInterconnects1 / 3
Inside a nodeAnimated diagram of GPU interconnects inside and between nodes.Inside a node: NVLink, not PCIeone 8-GPU nodeNVSwitchGPU 0GPU 1GPU 2GPU 3GPU 4GPU 5GPU 6GPU 7Every GPU reaches everyother one at full NVLinkspeed through NVSwitch.Bandwidth per GPU, both directionsH100 NVLink900 GB/sA100 NVLink600 GB/sH100 PCIe Gen5128 GB/sA100 PCIe Gen464 GB/sBetween nodes: InfiniBand and GPUDirect RDMAnode 0GPUhostmemoryNICnode 1GPUhostmemoryNICcopy throughhost memoryIB switchGPUDirect RDMAInfiniBand bandwidth per portHDR 200 Gb/sNDR 400 Gb/sbits, not bytes:25 and 50 GB/sPut each parallelism on the right linkParallelismWhat it sendsHow oftenPlace it onTensorpartial results of each layerevery layerNVLink, one nodePipelineactivations between stagesevery micro-batchnetworkDatagradients, all-reducedonce per stepnetwork, outermostless trafficMegatron-LMtensor parallel inside a server, pipeline across servers,data parallel outside: 52% of peak on 3,072 A100 GPUsInside a node
NVSwitch gives each GPU 600 GB/s (A100) or 900 GB/s (H100) to any peer.
That is about 7 to 9 times the bandwidth of a PCIe link.
In nvidia-smi topo -m, NV# marks NVLink, while PIX, PXB and SYS mark PCIe paths.
Collectives inside a node are therefore cheap.
In practice
Check that every GPU pair shows NV links before a long run.
InfiniBand between nodes
Each port runs at 200 Gb/s (HDR) or 400 Gb/s (NDR), often one per GPU.
GPUDirect RDMA lets the adapter read GPU memory without a copy through the host.
With NCCL_DEBUG=INFO, NCCL logs which transport it picked.
Even so, a node’s network is far slower than its NVLink.
Watch out
If NCCL falls back to TCP sockets, multi-node training slows sharply.
Match each parallelism to a link
Tensor parallelism talks in every layer, so its group stays inside a node.
Pipeline stages exchange activations, so they can span nodes.
Data parallelism syncs once per step and goes outermost.
A device mesh with dimensions (dp, pp, tp) encodes this placement.
In practice
Keep each tensor-parallel group inside one node, usually 8 GPUs or fewer.
Checkpointing the run
Fault tolerance1 / 3
The problemTimelines of a failed job with and without checkpoints, the state a checkpoint must hold, and single-file against sharded saving.A node failure, with and without checkpointsEverything that shapes the next stepModel weightsevery parameter and bufferOptimizer stateAdam's two momentsLR schedulerwhere the schedule isGrad scalerthe fp16 loss scaleStep and epochwhere training stoppedRNG statesPython, NumPy, PyTorchSampler epochthe next shuffleTracker run IDto log into the same runwrite atomicallyckpt/tmp.ptos.replaceckpt/last.pta crash in the middle of a savenever damages the last good fileOne writer, or one shard per rankDDPrank 0 writes one fileGPU 0full copyGPU 1full copyGPU 2full copyGPU 3full copylast.ptFSDP or ZeRO-3every rank writes its shardGPU 0shard 0GPU 1shard 1GPU 2shard 2GPU 3shard 3The problem
Interval, state and writer
# Young's rule for the interval between savesinterval = math.sqrt(2 * save_time * mtbf)# 60 s to save, a failure every 24 h -> every 54 minstate = {"model": model.module.state_dict(),"optim": optim.state_dict(),"sched": sched.state_dict(), "step": step,"rng": torch.get_rng_state()}if rank == 0: # DDP: one writer torch.save(state, "ckpt/tmp.pt") os.replace("ckpt/tmp.pt", "ckpt/last.pt") # atomicmsd, osd = get_state_dict(model, optim) # any wrapperstate = {"model": msd, "optim": osd, "step": step}dcp.save(state, checkpoint_id=f"ckpt/{step}")
The problem: long jobs get interrupted
Time limits, preemption and node failures end long jobs early.
Without a checkpoint, everything since the first step is lost.
With checkpoints, a failure costs at most one interval.
Young’s rule balances saving against losing work.
Save the whole training state
The optimizer’s moments and the schedule matter as much as the weights.
The step, RNG states and sampler epoch let the data order carry on.
The tracker’s run ID lets the resumed job log into the same run.
Write to a temporary file, then rename it over the last one.
Match the writer to the wrapper
With DDP every rank holds the same weights, so rank 0 saves one file.
With FSDP or ZeRO-3 no rank holds the full model.
Distributed checkpointing lets every rank write its shard at once.
get_state_dict works for DDP, FSDP and tensor parallelism alike.
Requeue and resume
SLURMFault tolerance1 / 3
Before the limitTimeline of a job requeued before its time limit, a flow showing one resume path for every kind of start, and a checkpoint resharded from eight GPUs to four.Leave before the time limitSame job IDthe tracker run and the logs carry onSame scriptit finds the checkpoint and resumes by itselfOne code path for every startfirst startsbatch job.sbatchrestart after a crashtorchrun --max-restarts=3requeue after the limitscontrol requeuecheckpointexists?nostart at step 0yesload and continueResume on a different number of GPUssaved by 8 GPUsshard 0shard 1shard 2shard 3shard 4shard 5shard 6shard 7dcp.loadreshardsloaded on 4 GPUsGPU 02 shardsGPU 12 shardsGPU 22 shardsGPU 32 shardsthe global batch is now half as largerestore✓model✓optimizer✓scheduler✓step✓RNG states✓sampler epochBefore the limit
Job script and resume logic
job.sbatch#SBATCH --requeue#SBATCH --signal=B:USR1@90 # 90 s before the limittrap'scontrol requeue $SLURM_JOB_ID' USR1srun torchrun --max-restarts=3 ... train.py &waittrain.pystart = 0if os.path.exists("ckpt/last.pt"): # restart, requeue start = load_checkpoint(model, optim, sched) + 1for step in range(start, total_steps): train_step(step) if step % save_every == 0: save_checkpoint(step)dcp.load(state, checkpoint_id=latest) # reshardsset_state_dict(model, optim,model_state_dict=state["model"],optim_state_dict=state["optim"])
Leave before the time limit
SLURM signals the batch script 90 s before the limit.
The trap requeues the job, which goes back into the queue.
The requeued job keeps its ID, so trackers can resume the same run.
The periodic checkpoints do the saving, and the signal only arranges the restart.
One code path for every start
A first start, a torchrun restart and a SLURM requeue run the same script.
The script looks for a checkpoint and continues from it if one exists.
With --max-restarts=3, torchrun restarts a crashed worker group in place.
Test it on purpose by killing a short job and checking that the curve carries on.
Resume on a different cluster size
Loading reshards the saved tensors for the current world size.
Restore the step, the RNG states and the sampler epoch as well.
A new world size changes the global batch, so adjust the rate or accumulation.
The loss curve then continues from the same point.
Scaling the batch
Large-batch training1 / 3
Global batchAnimated diagram of global batch size, learning-rate scaling and the critical batch size.The global batch counts every sample in an updatenode 0GPU 032323232GPU 132323232GPU 232323232GPU 332323232node 1GPU 432323232GPU 532323232GPU 632323232GPU 732323232Each GPU runs four micro-batches of 32, then all GPUs update together.per GPUaccumulationGPUsper updateScale the learning rate with the batchLarger batches stop paying offbatch size (log scale)steps to reach the target loss (log scale)perfect scalingmore samples, barely fewer stepsLARS and LAMB adapt the step size per layerand have trained with batches in the tens of thousands.Global batch
Batch size and schedule
micro, accum = 32, 4world = dist.get_world_size() # 8global_batch = micro * accum * world # 1,024lr = 0.1 * global_batch / 256# 3.2 at 8,192optim = torch.optim.SGD(params, lr=lr, momentum=0.9)def lr_factor(step): # E steps per epoch e = step / E if e < 5: return (1 + 31 * e / 5) / 32 return 0.1 ** sum(e >= m for m in (30, 60, 80))sched = LambdaLR(optim, lr_factor) # per batchtput = global_batch / step_time # samples / seff = tput / (world * tput_1) # efficiency# beyond the critical batch, steps stop shrinking
Count every sample in an update
The global batch is , the product of micro-batch, accumulation steps and GPUs.
Here that is samples per optimizer step.
Changing any factor changes the batch the optimizer sees.
Report the global batch in configs and papers, not the per-GPU size.
Changing any factor may also call for a new learning rate.
Scale the learning rate with the batch
Linear scaling multiplies the rate by when the batch grows -fold.
One step on samples then roughly matches steps on .
Early on the gradient changes fast, so warm up to the scaled rate.
Goyal et al. trained ResNet-50 with batch 8,192 on 256 GPUs in one hour.
Larger is not always faster
Past the critical batch size, more samples per step barely cut the step count.
Extra GPUs then add cost without shortening training.
LARS and LAMB adapt the step size per layer to push that limit.
Track scaling efficiency as you add GPUs.
The curve is a schematic after McCandlish et al. (2018).
What DeepSpeed adds
DeepSpeedOverview1 / 3
What it isIntroduction to DeepSpeed: the engine around a PyTorch model, its features, and when to use it.An engine wrapped around your modelWhat you getWhen to reach for itWhat it is
Install and first run
terminalpip installdeepspeedds_report# CUDA, PyTorch and compiled opstrain.pyimport deepspeedengine, *_ = deepspeed.initialize(model=model,model_parameters=model.parameters(),config="ds_config.json")terminaldeepspeed--num_gpus=8 train.py # one nodedeepspeed--hostfile=hosts train.py # many nodes
An engine around your model
DeepSpeed is an open-source library on top of PyTorch, started at Microsoft.
Its engine wraps your model, optimizer and data loader in one object.
Underneath, it still uses torch.distributed and NCCL across the GPUs.
Running ds_report after installing shows which fused ops are ready.
What you get
ZeRO shards optimizer states, gradients and parameters across GPUs.
Offload moves states to CPU memory or NVMe when the GPUs run out.
Mixed precision, pipeline parallelism and fused optimizers are built in.
Most features are switched on in the JSON config, not in the training loop.
When to reach for it
If the model and its optimizer state fit on one GPU, plain DDP is simpler.
If they fit only when sharded, FSDP and ZeRO-3 do the same job.
If they do not fit even then, ZeRO-Offload and ZeRO-Infinity still can.
The deepspeed launcher starts one process per GPU on every host.
ZeRO: stop replicating
DeepSpeedZeRO stages1 / 4
BaselineAnimated diagram of per-GPU memory under the three ZeRO stages: each GPU card holds rows of memory cells, and each stage frees the slices other GPUs own.Baseline: every GPU holds everythingfp16 parametersfp16 gradientsfp32 optimizer statesis the number of parametersGPU 0GPU 1GPU 2GPU 3Memory per GPUwith the 4 GPUs drawnZeRO paper example7.5B parameters on 64 GPUs120 GBper GPU32 GB0123stagedoes not fit on a 32 GB GPURajbhandari et al., 2020Stage 1: shard the optimizer statesfp16 parametersfp16 gradientsfp32 optimizer statesis the number of parametersGPU 0GPU 1GPU 2GPU 3Memory per GPUwith the 4 GPUs drawnZeRO paper example7.5B parameters on 64 GPUs31.4 GBper GPU32 GB0123stagefits on a 32 GB GPURajbhandari et al., 2020Stage 2: also shard the gradientsfp16 parametersfp16 gradientsfp32 optimizer statesis the number of parametersGPU 0GPU 1GPU 2GPU 3Memory per GPUwith the 4 GPUs drawnZeRO paper example7.5B parameters on 64 GPUs16.6 GBper GPU32 GB0123stagefits on a 32 GB GPURajbhandari et al., 2020Stage 3: also shard the parametersfp16 parametersfp16 gradientsfp32 optimizer statesis the number of parametersGPU 0GPU 1GPU 2GPU 3Memory per GPUwith the 4 GPUs drawnZeRO paper example7.5B parameters on 64 GPUs1.9 GBper GPU32 GB0123stagefits on a 32 GB GPURajbhandari et al., 2020Baseline
With parameters, mixed-precision Adam keeps fp16 weights and gradients in bytes.
The fp32 master weights, momentum and variance add bytes.
Data parallelism copies all bytes to every GPU.
A 7.5B-parameter model needs 120 GB per GPU before activations.
Why it matters
Optimizer states, not weights, take most of the training memory.
Shard the optimizer states
Each GPU keeps 1 of slices of the optimizer states.
Memory per GPU drops to .
Communication stays the same as plain data parallelism.
Stage 1 cuts memory about 4 times when is large.
In practice
Stage 1 is a near-free win for any data-parallel job.
Shard the gradients too
Gradients are reduce-scattered, so each GPU keeps only its slice.
Memory per GPU drops to .
Communication is still the same as data parallelism.
Stage 2 approaches 8 times less memory as grows.
In practice
Stage 2 is a common default when sharding is enough.
Shard the parameters too
Parameters are gathered layer by layer when needed, then freed.
Memory per GPU drops to , shrinking with every GPU.
Communication rises to about 1.5 times that of data parallelism.
The zero.Init context builds the model already sharded.
Watch out
Stage 3 adds all-gathers to every forward and backward pass.
Offloading to CPU and NVMe
DeepSpeedOffload1 / 3
ZeRO-OffloadAnimated diagram of ZeRO-Offload, ZeRO-Infinity and the offload trade-off.ZeRO-Offload: the optimizer runs on the CPUZeRO-Infinity: GPU, CPU and NVMe togetherGPU memory0.5 TBCPU memory1.5 TBNVMe SSDs30 TBlarger, slowerWhat it reached32T parameterson 512 V100 GPUs (32 DGX-2 nodes)1T parametersfine-tuned on one DGX-2 nodeEach layer is partitioned acrossall GPUs and fetched when needed.Parameters, gradients and optimizer statescan each live on the GPU, in CPU memory or on NVMe.The three sizes are those of one NVIDIA DGX-2 node: 16 V100 GPUs with 32 GB each.Offload only what does not fitZeRO-Offload
The GPU keeps fp16 weights and runs the forward and backward passes.
Gradients stream to the CPU, which updates the fp32 states with a vectorised Adam.
New fp16 weights return to the GPU for the next step.
This trained 13B-parameter models on a single V100.
Watch out
The CPU Adam step can become the bottleneck for small batches.
Add NVMe as a third tier
ZeRO-Infinity can put parameters, gradients and optimizer states on NVMe.
Each layer’s data is prefetched just before the layer runs.
It reached 32 trillion parameters on 512 V100s.
Fast NVMe drives and pinned buffers keep the GPUs fed.
In practice
Use it to fit huge models on few GPUs, not to go faster.
Offload only what does not fit
Each step to the right frees GPU memory and costs speed.
Estimate the memory each option needs before you launch.
Pick the leftmost option that fits, because GPU memory is the fastest tier.
Offloading parameters costs more speed than offloading the optimizer.
In practice
Try ZeRO-3 on more GPUs before reaching for NVMe.
DeepSpeed in code
DeepSpeedDeepSpeed1 / 3
ConfigureAnimated diagram of a DeepSpeed config, the engine loop and a multi-node launch.One config file describes the runThe engine wraps the model and optimizerLaunch on two nodes, then checkpointhostfilenode1 slots=4node2 slots=4deepspeednode1node2engine.save_checkpoint("ckpt", tag="step1000")ckpt/latest(contains "step1000")step1000/model statesoptimizer states, one shard per rankConfigure
Config and training script
ds_config.json{"train_batch_size": 512,"train_micro_batch_size_per_gpu": 16,"gradient_accumulation_steps": 4,"bf16": {"enabled": true},"zero_optimization": {"stage": 2},"optimizer": {"type": "AdamW"}}train.pyengine, _, loader, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(),training_data=dataset, config="ds_config.json")for x, y in loader: loss = loss_fn(engine(x.cuda()), y.cuda()) engine.backward(loss) # reduce-scatters grads engine.step() # updates every 4th call# launch: deepspeed --hostfile=hostfile train.pyengine.save_checkpoint("ckpt", tag=f"step{step}")
Configure the run in one file
Batch sizes, precision, ZeRO stage and optimizer live in one JSON file.
DeepSpeed checks that at startup.
Switching ZeRO stages needs no code change.
Let the engine drive each step
The engine returned by initialize wraps model, optimizer and loader.
Its backward reduce-scatters the gradients across ranks.
Its step updates the weights on every fourth call.
With bf16 on, the engine casts the weights, so cast float inputs to bf16 as well.
Launch with a hostfile
The launcher starts one process per GPU on every listed host.
Each rank saves its own optimizer shard in parallel.
Resume with engine.load_checkpoint("ckpt", tag).
3D parallelism at scale
DeepSpeedBLOOM-176B1 / 3
Tensor parallel in a nodeAnimated diagram of tensor, pipeline and data parallelism in BLOOM-176B training.3D parallelism: BLOOM-176B on 384 GPUsone node: 8 A100 GPUsstage 1: TP group0123NVLinkstage 2: TP group0123NVLinkevery weight matrix, split 4 ways0123each GPU multipliesby its slice; partialresults are all-reducedin every layerone replica: 12 stages, 48 GPUs, 6 nodesabout 6 of the 70 layers per stage8 replicas with ZeRO stage 1; each column all-reduces its stage’s gradientsA100 GPUsTensor parallel in a node
Tensor parallelism shards every weight matrix across a group of 4 GPUs.
It communicates in every layer, so each group stays on one node’s NVLink.
Each GPU holds a quarter of every layer it serves.
Megatron-LM splits attention heads and MLP columns across the group.
Watch out
Tensor parallelism across nodes would be limited by InfiniBand.
Chain stages across nodes
Pipeline parallelism splits the 70 layers into 12 stages.
Two stages fill one 8-GPU node, so only activations cross node boundaries.
Micro-batches keep all 12 stages busy.
The pipeline bubble shrinks as the number of micro-batches grows.
In practice
Balance layers across stages so no stage holds the others back.
Replicate the pipeline
One pipeline uses GPUs.
Data parallelism runs 8 copies, which makes GPUs on 48 nodes.
Gradients are averaged across the 8 replicas once per step.
This is the layout used to train BLOOM-176B.
Why it matters
Each dimension lifts a different limit, namely layer size, depth or throughput.
What Ray adds
RayThe problem1 / 3
The problemDiagram of the many workloads of a pathology project, the layers of the Ray stack, and the division of work between SLURM, Ray, DDP, NCCL and trackers.Many workloads, one cluster55,000 whole-slide imagesTissue segmentationfind the tissue on every slideCPU coresPatch extractiontiles at several magnificationsCPU cores and storageEmbeddings25 pathology foundation modelsGPUsMIL trainingdownstream slide-level modelsGPUsHyperparameter searchmany trials at the same timemany GPUsEvaluationevery model on every datasetCPUs and GPUsOne runtime, several librariesApplicationcodelibrariesRay DatapipelinesRay TraintrainingRay TunesearchRay ServeservingRay Coretasks · actors · objects · schedulingruntimeSLURM · Kubernetes · cloud VMsallocationCPUs · GPUs · nodeshardwareWho does whatAllocate nodes for a fixed timequeue, limits, accountingSLURMDistribute Python work over those nodestasks, actors, pipelines, trialsRayKeep the model replicas in stepaverage gradients, shard the statesDDP · FSDP · DeepSpeedCarry the messages between GPUsall-reduce over NVLink or InfiniBandNCCLRecord what every run didconfigs, metrics, checkpointsW&B · MLflowThe problem
The problem: more than one training job
A real project is a pipeline that segments, tiles, embeds, trains, tunes and evaluates.
Some stages need CPUs and storage, others GPUs, and each feeds the next.
By hand you manage the processes, the GPU assignment, the hand-offs and the retries.
DDP solves only one box of this picture, the training step.
One runtime under several libraries
Ray Core schedules Python functions and objects across CPUs, GPUs and machines.
Ray Data, Train and Tune are built on that core, and you can use them alone or together.
Ray runs on what you already have, whether SLURM, Kubernetes or cloud machines.
Ray Serve and RLlib also exist, but lie outside training.
Ray does not replace the rest of this deck
SLURM still allocates the nodes, and Ray runs inside the allocation.
PyTorch still trains, and DDP, FSDP or DeepSpeed still keep the replicas in step.
For one large training job, SLURM with FSDP or DeepSpeed is enough.
Ray pays off when many different workloads share the cluster.
Ray Core: tasks, actors, objects
RayRay Core1 / 3
TasksDiagram of Ray tasks scheduled onto workers, of GPU actors that keep a model loaded, and of the object store shared by reference.Tasks: functions that run anywhereActors: workers that keep stateRay schedulerGPU 0Extractor actormodel loaded onceGPU 1Extractor actormodel loaded onceGPU 2Extractor actormodel loaded onceGPU 3Extractor actormodel loaded onceTaskstateless: nothing is kept between callsActorstateful: the model stays on its GPUObjects: share data by referenceTasks
Three building blocks
import rayray.init()@ray.remote(num_cpus=4) # resources per calldef segment(slide_path): return tissue_mask(slide_path)futures = [segment.remote(p) for p in slides]masks = ray.get(futures) # wait for the results@ray.remote(num_gpus=1) # one GPU per actorclass Extractor: def __init__(self): self.model = load_model().cuda() # once def extract(self, patches): return self.model(patches.cuda()).cpu()actors = [Extractor.remote() for _ in range(4)]ref = ray.put(embeddings) # stored onceout = [score.remote(ref, k) for k in range(8)]
Tasks: distributed function calls
@ray.remote turns a function into a task that any worker can run.
Calling .remote() returns a future at once, and ray.get waits for the value.
Declare what a task needs, and Ray finds a worker with those CPUs or GPUs.
Use tasks for independent, stateless work such as preprocessing slides.
Actors: distributed objects
An actor is a class instance that lives in its own worker process.
It keeps state between calls, so a model is loaded onto its GPU only once.
Four actors with one GPU each are four model replicas to send batches to.
Use actors for repeated inference, and tasks when nothing has to persist.
Objects: values with an address
ray.put stores a value once in the object store and returns a reference.
Tasks and actors receive the reference, and Ray fetches the value where they run.
Workers on the same node read large arrays from shared memory without a copy.
Objects are immutable, and moving one to another node still costs a transfer.
Ray Data: streaming pipelines
RayRay Data1 / 3
The problemTimelines of stage-by-stage against streaming execution, a three-stage Ray Data pipeline with backpressure, and dataset shards feeding training workers.Stages that wait for each otherOne pipeline, three kinds of workerThe same dataset feeds trainingThe problem
From loops to a pipeline
masks = [segment(p) for p in slides] # CPUs onlyfeats = [encode(m) for m in masks] # then GPUsclass Encoder: # one actor per GPU def __init__(self): self.model = load_model().cuda() def __call__(self, batch): batch["feat"] = embed(self.model, batch) return batchpool = ray.data.ActorPoolStrategy(size=4) # 4 actorsds = ray.data.from_items(slides).flat_map(read_patches)ds = ds.map_batches(Encoder, compute=pool, num_gpus=1,batch_size=256)ds.write_parquet("/lustre/feats") # starts the run# inside the Ray Train loopshard = ray.train.get_dataset_shard("train")for batch in shard.iter_torch_batches(batch_size=256): loss = loss_fn(model(batch["feat"]), batch["y"])
The problem: stages wait for each other
Reading and tiling slides is CPU and I/O work, while encoding patches is GPU work.
Run one after the other, the GPUs idle during preprocessing and the CPUs after it.
Every intermediate result must be held in memory or written to disk.
For terabytes of patches, that neither fits nor finishes.
Ray Data streams blocks between stages
A function becomes parallel CPU tasks, and a class becomes a pool of actors.
Here the pool is four encoders with one GPU each, fed in batches of 256.
Backpressure slows the readers when the encoders fall behind, so memory stays bounded.
Nothing runs until a sink such as write_parquet asks for the data.
One data layer for inference and training
The same dataset can feed distributed training in place of a DataLoader.
Ray Train hands each worker its own shard, as a distributed sampler would.
iter_torch_batches yields tensors already on that worker’s GPU.
Preprocessing then scales on CPU nodes, apart from the GPU nodes that train.
Ray Train and Ray Tune
RayTrain and Tune1 / 3
Ray TrainDiagram of Ray Train replacing hand-written DDP set-up, of reporting and recovery from checkpoints, and of trials stopped early by ASHA.Ray Train wraps DDPReport, checkpoint, recoverworkersstorageepoch 0epoch 1epoch 2epoch 3✕ lostepoch 3epoch 4report(metrics, checkpoint) after every epochrestore the last checkpointMetricsevery worker calls report() each epochCheckpointswritten to storage all nodes can reachRay Tune: many trials, stopped earlyvalidation lossepochs3927rung✕✕✕✕✕✕best trialSearch spacelearning rate on a log scale,choices from a listASHAstops the weakest trialsat every rungResourcesone GPU per trial; as manytrials at once as GPUsRay Train
Scaling one run, then many
import ray.train.torch as rtdef train_fn(config): model = rt.prepare_model(Net()) # DDP loader = rt.prepare_data_loader(loader) # samplerscaling = ScalingConfig(num_workers=8, use_gpu=True)rt.TorchTrainer(train_fn, scaling_config=scaling).fit()# in train_fn, once per epoch, on every workerckpt = None# only rank 0 attaches a checkpointif ray.train.get_context().get_world_rank() == 0: ckpt = Checkpoint.from_directory(ckpt_dir)ray.train.report({"loss": epoch_loss}, checkpoint=ckpt)cfg = tune.TuneConfig(metric="val_loss", mode="min",num_samples=32, scheduler=ASHAScheduler(max_t=27, grace_period=3, reduction_factor=3))trial = tune.with_resources(train_mil, {"gpu": 1})tuner = tune.Tuner(trial, tune_config=cfg,param_space={"lr": tune.loguniform(1e-5, 1e-2)})best = tuner.fit().get_best_result()
Ray Train: the same DDP, less set-up
Ray Train starts the workers, forms the process group and assigns the ranks.
prepare_model moves the model to its GPU and wraps it in DDP.
prepare_data_loader adds the distributed sampler and moves each batch.
PyTorch, DDP and NCCL still do the training.
Fault tolerance is part of the trainer
Every worker calls ray.train.report with its metrics each epoch.
Attach a checkpoint to the report, and save it from rank 0 only.
Checkpoints go to storage that every node can reach.
FailureConfig(max_failures=3) restarts the workers from the last checkpoint.
Ray Tune: a search across the cluster
Each trial is one training run with its own sampled hyperparameters.
Declare the resources per trial and Ray runs as many trials as fit.
ASHA compares trials at rungs, here epochs 3, 9 and 27, and stops the weakest.
The Tuning section explains rungs, which W&B sweeps and Optuna pruners use too.
Configs: from flags to a file
ConfigurationFrom flags to files1 / 3
argparseDiagram of a training configuration given as argparse flags, then as a nested YAML file, then as an OmegaConf object merged from the file and command-line overrides.argparse: every setting is a flag$ python train.py --model vit_l --patch 16 --lr 3e-4 \--weight-decay 0.05 --warmup 10 --batch-size 256 \--tiles /data/tcga --tile 256 --epochs 90 --seed 7 args: one flat namespace10 flags here, often 40 or moreargs.modelargs.patchargs.lrargs.weight_decayargs.warmupargs.batch_sizeargs.tilesargs.tileargs.epochsargs.seedwhat each one configuresmodeloptimizerdatarunTyped and validated, and --help comes for freeStandard library: nothing to installOne flat list, however many flags there areThe command you typed is the only recordA YAML file holds the settingsconfig.yamlin gitmodel:name: vit_lpatch: 16optim:lr: 1.0e-4weight_decay: 0.05data:root: /data/tcgabatch_size: 256train.py reads ita plain dictcfg = yaml.safe_load(open("config.yaml"))cfg["optim"]["lr"]0.0001One change, one more fileconfig.yamlconfig_lr3e-4.yamlconfig_lr3e-4_bs512.yamlconfig_vit_h_final.yamlSettings are grouped by what they configureThe file is versioned with the codeEvery variant is an edit or another copyNo schema: a misspelt key can go unnoticedOmegaConf: the file plus overridesconfig.yamlbasemodel.namevit_loptim.lr0.0001data.batch_size256run.name${model.name}_lr${optim.lr}$ python train.py \optim.lr=3e-4 \data.batch_size=512mergecfg: one merged objectDictConfigmodel.namevit_lfrom the fileoptim.lr0.0003command linedata.batch_size512command linerun.namevit_l_lr0.0003from ${...}cfg.optim.lr0.0003dots, not bracketsAny value is overridden without editing the file${...} keeps linked values in stepA dataclass schema rejects wrong keys and typesSwapping a whole block, say the model, is manualargparse
Every setting is a flag, declared with a type and a default in the script.
args is one flat namespace that model, optimizer and data settings all share.
Defaults live in the code, so changing one is a code change.
The command you typed is the only record of what ran.
A file gives the settings a shape
Nested YAML groups the settings by what they configure.
The file is committed with the code, so a commit pins a config.
Each variant needs an edit or a copy, and copies drift apart.
PyYAML reads 1e-4 as a string, so write 1.0e-4 instead.
OmegaConf merges the layers
merge lays the command line over the file, and the later source wins.
Values are reached with dots, and a missing key raises an error.
${...} builds one value from others, here the run name.
It reads 1e-4 as a number, and a dataclass schema adds type checks.
Hydra: composing the config
HydraComposition1 / 3
Config groupsDiagram of Hydra composing a config from config groups, running overrides and sweeps from the command line, and saving the composed config that MLflow and W&B record.Config groups and the defaults listOverride and sweep from the command lineEvery run keeps its configoutputs/2026-11-26/22-51-07/.hydra/config.yamlthe composed config, exactly as it ran.hydra/overrides.yamlwhat was typed: model=vit_h optim.lr=3e-4.hydra/hydra.yamlHydra’s own settings for the jobtrain.logthe job’s log fileMLflowparams are flatmodel.name=vit_hoptim.lr=0.0003data.tile=256config.yamlas an artifactWeights & Biasesnested, as ismodel {name, patch, dim, depth}optim {lr, weight_decay}data {...}Repeat a run from its saved configpython train.py -cp <run>/.hydra -cn configPrint the config without runningpython train.py model=vit_h --cfg jobConfig groups
Each folder under conf/ is a config group, and each file in it is one option.
The defaults list picks one option per group.
_self_ places this file’s own keys in the merge order, where the later entry wins.
The result is an OmegaConf object, so dots and ${...} still work.
The command line edits the composition
model=vit_h swaps a whole group, while optim.lr=3e-4 changes one value.
-m runs every combination of the comma-separated values.
A misspelt key is refused, and a wrong group option lists the ones that exist.
Each job gets its own folder, so runs never overwrite each other.
The saved config is what a tracker stores
Hydra writes the composed config to .hydra/config.yaml in the run folder.
overrides.yaml beside it records exactly what was typed.
MLflow params are flat, so join nested keys with dots and attach the file itself.
W&B takes the nested dict directly, as in wandb.init(config=d).
Tuning: hand, grid, random
TuningSearch1 / 3
By handDiagram of nine training runs spent three ways on the same two settings: guessed by hand one after another, laid out on a grid, and drawn at random.By hand: one run at a timeGrid search: every combinationRandom search: the same budget, spent betterBy hand
By hand: serial, slow, hard to repeat
A hyperparameter, such as the learning rate or weight decay, is set before training.
When you tune by hand, you change one setting, train, look at the loss and guess again.
Each guess waits for the last run, so most of your GPUs sit idle.
It can work for one or two settings, but nobody can repeat how you got there.
A grid multiplies with every setting
A grid tries every combination, and all its runs can train at the same time.
With k values for each of d settings, a grid needs k to the power d runs.
Nine runs test only three learning rates, because the other six runs repeat them.
A grid suits two or three settings, and Hydra’s -m on the last slide runs exactly this.
Random search covers each setting better
Each trial draws every setting at random, with the learning rate on a log scale.
Nine trials now test nine learning rates, which helps because only a few settings matter.
Trials are independent, so you can add more, drop failed ones and run them all at once.
With sixty trials, there is a 95% chance that one lands in the best 5% of the space.
TPE: learning from trials
TuningTPE1 / 3
Good and badDiagram of the Tree-structured Parzen Estimator: finished trials split into a good and a bad group, a density fitted to each, the next trial chosen where their ratio is largest, and the joint density and constant-liar strategy that Optuna uses by default.Split the finished trialsTwo densities, one ratioSeveral settings, several workersGood and bad
Random search never looks back
Random search ignores every result, so trial 50 is chosen as blindly as trial 1.
TPE, the Tree-structured Parzen Estimator, uses the finished trials instead.
It splits them into a good group, which is the best tenth, and a bad group.
Optuna’s TPE runs 10 random trials first, so that there is something to split.
Sample where good is dense and bad is not
One density, l(x), is fitted to the good trials, and another, g(x), is fitted to the rest.
Optuna draws 24 candidates from l(x) and keeps the one with the largest l(x) / g(x).
The loss itself is never modelled, so categories and conditional settings are easy.
Every new result moves the split, so the search narrows as it runs.
What Optuna 5 switches on by default
A joint density keeps the settings of a trial together, so it sees interactions.
Constant liar counts running trials as bad, so parallel workers spread out.
Both multivariate and constant_liar have been switched on by default since Optuna 5.
The more workers ask at once, the less each suggestion knows about the others.
Stopping weak trials early
TuningPruning1 / 3
Successive halvingDiagram of successive halving cutting 27 trials to one over four rungs, of Hyperband running several brackets so that a slow starter survives, and of ASHA promoting trials without waiting for a rung to fill.Successive halving: keep the best thirdHyperband: hedge the first cutASHA: no worker waitsSuccessive halving
Most trials show their rank early
A sampler chooses what to try, and a pruner decides how long to keep trying it.
Successive halving trains every trial briefly, keeps the best third, and repeats.
Here the 27 trials cost 81 epochs in place of 729.
It needs a metric reported during training, such as the loss after each epoch.
The first cut can be wrong
A trial with a low learning rate or a long warm-up starts slowly and may end best.
Cutting after one epoch loses such a trial, while cutting late saves little.
Hyperband runs several brackets, from many short trials to a few long ones.
Its last bracket stops nobody, so it is plain random search, kept as insurance.
On a cluster, do not wait for the rung
Synchronous halving waits for a whole rung, so one slow trial idles the workers.
ASHA promotes a trial as soon as it ranks in the top third of its rung so far.
If none qualifies, the free worker starts a new trial on the bottom rung.
Ray Tune’s ASHA and Optuna’s SuccessiveHalvingPruner both implement this algorithm.
Optuna: the search as code
OptunaStudy and trial1 / 3
Objective and studyDiagram of an Optuna study calling an objective once per trial, of a trial reporting its loss each epoch so that the pruner can stop it, and of the finished study read as a history plot, importances and a table of trials.An objective, a trial, a studyReport every epoch; the pruner decidesRead the studyObjective and study
One objective, one study
def objective(t): # called once per trial lr = t.suggest_float("lr", 1e-5, 1e-2, log=True) op = t.suggest_categorical("opt", ["adamw", "sgd"]) if op == "sgd": # only in SGD trials mom = t.suggest_float("momentum", 0.8, 0.99) return train(t) # the validation lossstudy = optuna.create_study(direction="minimize")study.optimize(objective, n_trials=50)def train(t): # inside the objective for epoch in range(27): val = one_epoch(t.params) t.report(val, step=epoch) # tell the pruner if t.should_prune(): raise optuna.TrialPruned() return valstudy.best_params # {"lr": 4.8e-4, "opt": "adamw"}df = study.trials_dataframe() # one row per trialoptuna.importance.get_param_importances(study)optuna.visualization.plot_optimization_history(study)
The search space is ordinary Python
A study is one search, and a trial is one call of the objective with its own values.
Each suggest_ call asks the sampler for a value and records its range.
The space is defined as the code runs, so momentum exists only in SGD trials.
Without a named sampler Optuna uses TPE, and n_trials counts this process’s trials.
The objective reports; the pruner decides
report stores the metric of this step, and should_prune asks the pruner.
Raising TrialPruned ends the trial, but its reported values stay in the study.
Without a named pruner, MedianPruner stops trials worse than the median at their step.
Pass pruner=HyperbandPruner() to create_study to pair TPE with Hyperband.
A study is a table you can query
best_params names the winner, and the dataframe holds every trial with its state.
Importances rank the settings, and Optuna 5 computes them with PED-ANOVA.
The plots are Plotly figures, and optuna-dashboard shows a study live from its storage.
Check the winner on held-out data, because the best of many trials flatters itself.
Optuna on a cluster
OptunaOn a cluster1 / 3
One study, many jobsDiagram of SLURM array jobs sharing one Optuna study through a database, of one trial run by several DDP ranks with rank 0 holding the trial, and of a killed trial being marked failed by the heartbeat and queued again.One study, many jobsA trial that spans several GPUsWhen a trial never finishesOne study, many jobs
Optuna under SLURM
DB = "postgresql://optuna@db/optuna"# every nodestudy = optuna.create_study(study_name="vit-hpo",storage=DB, load_if_exists=True) # create or joinstudy.optimize(objective, n_trials=8) # 8 per jobdef objective(single): # None on every rank but 0 t = TorchDistributedTrial(single) lr = t.suggest_float("lr", 1e-5, 1e-2, log=True) ... # DDP loop: report, pruneif rank == 0: study.optimize(objective, n_trials=8)else: for _ in range(8): # follow rank 0 try: objective(None) except optuna.TrialPruned: passstore = optuna.storages.RDBStorage(DB, # storage=storeheartbeat_interval=60, grace_period=120)study.optimize(objective, timeout=18 * 3600,catch=(torch.OutOfMemoryError,))
Every job joins the same study
The study lives in storage that every node can reach, which here is PostgreSQL.
load_if_exists=True lets the first job create the study and the rest join it.
n_trials counts per process, so 16 jobs of 8 trials make 128 trials in total.
A journal file is fine on one node, but across nodes its file locks can fail on NFS.
One trial, many ranks
With DDP every rank runs the objective, but only rank 0 holds the trial.
TorchDistributedTrial sends each suggested value from rank 0 to the others.
All ranks must call suggest, report and should_prune at the same point.
Rank 0 decides to prune, and every rank raises TrialPruned together.
Plan for trials that never finish
A job killed at its time limit leaves its trial marked RUNNING for good.
With a heartbeat, RDBStorage marks such a trial FAIL once it falls silent.
timeout stops asking for new trials, so set it a full trial short of the limit.
catch lets the study survive a trial’s error, and a callback can requeue a killed trial.
Why track experiments
Experiment trackingThe problem1 / 3
Lost contextDiagram of untracked checkpoints and logs, the six things every run should record, and the three trackers covered next.Three months later$ ls ckpt/final.ptfinal_v2.ptfinal_v2_lr3e-4.ptbest_REAL.ptbest_REAL_fixed.pt$ tail slurm-81234.out[rank 3] step 4100 loss 0.412[rank 0] step 4100 loss 0.398[rank 5] step 4100 loss 0.431[rank 1] step 4100 loss 0.405[rank 0] step 4150 loss 0.391final_v2_lr3e-4.ptfinal.ptbest_REAL_fixed.ptWhich one was the good run?final_v2.pt? best_REAL_fixed.pt?final_v2.ptbest_REAL.pt???DO NOT DELETE(maybe)The record every run needsConfigevery hyperparameterand command-line flagCodethe git commit, plusany uncommitted diffDatathe dataset versionor the list of shardsEnvironmentpackages, GPU type,world size, global batchMetricslogged against theoptimizer stepArtifactscheckpoints, linked tothe run that wrote themThree tools, one ideaWeights & Biaseshosted dashboardssweeps, artifacts, registrylittle setupMLflowa server you run yourselfmodel registry and servingopen sourceTensorBoardevent files on diskno account, no databasebuilt into PyTorchLost context
The problem is lost context
Scaling the training also scales the number of runs you have to tell apart.
A checkpoint without its configuration cannot be reproduced or trusted.
Standard output mixes every rank and vanishes with the job’s log file.
A sweep of 32 jobs produces 32 curves that only a table can compare.
Record six things per run
The config and code version say what ran, while data version and environment say on what.
Metrics against the optimizer step say what happened.
Artifacts tie each checkpoint to the run that produced it.
Record them at the start of the run, before the first step can fail.
Pick by where the data may live
W&B is the quickest to start and the richest for comparing runs.
MLflow keeps everything on your own servers and adds serving.
TensorBoard needs nothing but a folder, and works without a network.
All three accept the same call, which takes a name, a value and a step.
What W&B records
Weights & BiasesOverview1 / 3
What it isIntroduction to Weights and Biases: how a script reaches a shared dashboard, the main features, and where it fits.From your script to a shared dashboardcompute nodeGPU 0GPU 1GPU 2GPU 3train.pywandb.init(...)run.log({...})uploadW&B serverwandb.ai, orself-managedscaleable-trainingtrain_losssunny-river-12calm-lake-4bold-sky-7Each run records its config, metrics and system stats,plus the git commit it ran from.The main piecesRunsMetrics, config andsystem stats per runArtifactsVersioned datasetsand modelsSweepsHyperparameter searchrun by agentsTablesPredictions and mediayou can queryRegistryModels other teamscan find and useReportsShareable write-upswith live chartsEvery piece hangs off the same runs,so a report links to the exact run, data and model.Where it fitsStrengthsWatch forDashboards the whole team shareswith comparisons and reportsSweeps, artifacts and a registrybuilt in, not bolted onOne-line integrationsLightning, Hugging Face, DeepSpeedData leaves the clusterunless you run W&B Server yourselfNodes without internetneed offline mode and a later syncVery frequent logginglog every few steps in large jobsA good default when a team wants shared, hosted tracking.What it is
Install and first run
terminalpip installwandbwandb login# paste your API key oncetrain.pyimport wandbrun = wandb.init(project="scaleable-training")run.log({"loss": loss.item()})run.finish()terminal# a self-managed W&B Serverwandb login--hosthttps://wandb.lab.org
A hosted tracker for every run
Weights & Biases records metrics, configs and system stats from your script.
Runs appear live in a shared web dashboard for the whole team.
Data goes to wandb.ai, or to a W&B Server you host yourself.
Run wandb login once with your API key.
The SDK uploads from a background process, so logging does not block training.
The main pieces
Runs hold metrics and configs, and artifacts version data and models.
Sweeps search hyperparameters, and tables hold predictions and media.
The registry shares models, and reports turn runs into write-ups.
All of them link back to the runs that produced them.
Where it fits
It suits teams that want shared, hosted dashboards with little setup.
Nodes without internet need offline mode and a later sync.
For a self-managed server, log in with wandb login --host.
Log every few steps in large jobs to keep runs light.
Tracking runs with W&B
Weights & BiasesExperiment tracking1 / 4
Start a runAnimated diagram of a Weights and Biases run: config, metrics, gradients and system metrics.One W&B run per training jobtrain.pywandb.init(project, config)sunny-river-12project: scaleable-trainingConfigrunninglr3e-4global_batch1024zero_stage2modelvit-b16git commita1b2c3dhostgpu-node-07train_losslrval_accsummary: maxgradientsrun.watchblocks.0blocks.6headGPU utilization (%)logged automaticallyGPU 0GPU 1GPU 2GPU 3eval pausefinishedOr let the framework log for youHugging Face Trainerreport_to="wandb"PyTorch Lightninglogger=WandbLogger(...)DeepSpeed"wandb": {"enabled": true}project: scaleable-traininghf-finetune-3lightning-ssl-8ds-zero2-5Start a run
W&B in a training script
PROJECT = "scaleable-training"run = wandb.init(project=PROJECT,config=vars(args)) # all CLI flagsrun.define_metric("val_acc", summary="max")run.log({"train_loss": loss.item(),"lr": sched.get_last_lr()[0]}, step=step)run.watch(model, log="gradients", log_freq=100)# GPU, CPU and memory metrics: automaticrun.finish() # or: with wandb.init(...) as run:# Hugging Face TrainerTrainingArguments(..., report_to="wandb")# PyTorch LightningTrainer(logger=WandbLogger(project=PROJECT))# DeepSpeed config"wandb": {"enabled": True, "project": PROJECT}
Start a run
The call wandb.init creates a run in the project.
The config stores every CLI flag, so each curve traces back to its settings.
The project table compares runs by any config value.
Use name, group and tags to keep the project table readable.
wandb.init also records the git commit and the host of every run.
Log metrics
Each run.log call sends a dict of values at one step.
With summary="max", the run keeps its best val_acc.
Steps must increase, so log with the optimizer step.
Log at a fixed interval, such as every 50 steps, to keep runs light.
Watch the model and finish
The run.watch call logs gradient histograms every 100 batches.
GPU, CPU and memory metrics are collected automatically.
Calling run.finish() uploads what is left and closes the run.
Use the run as a context manager so it finishes even after an error.
Use a framework integration
With Hugging Face, set report_to="wandb" in the training arguments.
Lightning uses WandbLogger, and DeepSpeed takes a "wandb" block.
Each integration logs from the main process only.
WANDB_PROJECT names the project when an integration is not given one.
Each integration creates the run and logs the training metrics for you.
W&B on a GPU cluster
Weights & BiasesMulti-GPU logging1 / 4
Log from rank 0Animated diagram of Weights and Biases logging patterns for multi-GPU and offline cluster jobs.Multi-GPU: log from rank 0one node, 4 GPUsrank 0rank 1rank 2rank 3logstrains onlytrains onlytrains onlysunny-river-12one runtrain_loss (rank 0)GPU utilization (all 4 GPUs)Each metric is logged once, by rank 0.System metrics still cover every GPU on that node.Every rank logs: grouped runsgroup: exp-42rank 0rank0rank 1rank1rank 2rank2rank 3rank3Shared mode: all ranks write to one runlabelled rank_0 to rank_3; SDK 0.19.9 or newer, settings in previewCompute nodes without internetW&B servercompute nodeGPU 0GPU 1GPU 2GPU 3WANDB_MODE=offlineno internetshared filesystemwandb/offline-run-*login nodewandb sync --sync-alluploadRuns appear in the project once they are synced.Sync again during long jobs to watch progress.Resume the same run after a requeuejobSLURM job 81234time limitrequeued: still job 81234run slurm-81234train_loss by stepresumedresume="allow" continues the run if the ID existsand starts a new run with that ID if it does not.Log from rank 0
Distributed logging
train.pyrun = Noneif dist.get_rank() == 0: # one process logs run = wandb.init(project=PROJECT)if run: run.log({"train_loss": loss.item()})# or: every rank logs, grouped in the UIrun = wandb.init(project=PROJECT, group="exp-42",name=f"rank{dist.get_rank()}")job.sbatchexport WANDB_MODE=offline# no internet on nodeslogin nodewandb sync--sync-all# upload offline runstrain.py, rank 0job = os.environ["SLURM_JOB_ID"] # kept on requeuerun = wandb.init(project=PROJECT, id=f"slurm-{job}",resume="allow")
Log from rank 0
Only rank 0 calls wandb.init, so each metric is logged once.
System metrics still cover every GPU on rank 0’s machine.
The other ranks train without logging.
Logging from rank 0 only is the usual choice for DDP.
Or give every rank its own run
Runs that share a group appear together in the UI.
Per-rank runs reveal a slow or failing GPU.
Shared mode instead puts all ranks in one run.
Train offline, sync later
With WANDB_MODE=offline, runs are written to disk.
The wandb sync command uploads them from the login node.
Write the runs to a filesystem both nodes can see.
Offline runs are written under ./wandb unless the directory is changed.
Resume after a requeue
A requeued SLURM job keeps its job ID, so the run ID matches.
With resume="allow", W&B continues the run or creates it.
Log with the restored step so the curve has no gap.
Artifacts and lineage in W&B
Weights & BiasesArtifacts1 / 3
Dataset by referenceAnimated diagram of a W&B dataset artifact tracked by reference, checkpoint versions with aliases, and the lineage graph with a model registry.Version a dataset without copying itS3 bucketlab-data/tiles/slide_001/412 tilesslide_002/388 tilesslide_003/404 tiles1,204 files, 38 GBadd_referencetilesdatasetv1v2v3pathsizechecksumslide_001/t0001.png31 KB9f2c41e0slide_001/t0002.png29 KB41ab07d3slide_002/t0001.png33 KBc03e9d18slide_002/t0002.png30 KB7d6a2b95slide_003/t0001.png32 KBe81c5f2a1,199 more entriesOnly the manifest is uploaded; the files stay in S3.Logging again makes v4 only if a file was added, removed or changed.Every checkpoint becomes a versionvit-b16modelv9step 4500val_acc 0.771v10step 5000val_acc 0.788v11step 5500val_acc 0.802v12step 6000val_acc 0.812v13step 6500val_acc 0.806v14step 7000val_acc 0.809bestlatest0.810.77checkpoint versionval_accAn alias is a movable name for one version.latest follows every save; best moves only when val_acc improves.Lineage graph and the model registrydatasettiles:v3runtrainsunny-river-12modelvit-b16:v12runevaluatecalm-lake-4link_artifactModel registrycollection: vit-b16v0from vit-b16:v4val_acc 0.744v1from vit-b16:v9val_acc 0.771v2from vit-b16:v12val_acc 0.812productionrun: serveuse_artifact(".../vit-b16:production")From any model you can walk back to the data and code that made it.Dataset by reference
Artifacts and the registry
prepare.pyds = wandb.Artifact("tiles", type="dataset")ds.add_reference("s3://lab-data/tiles/")run.log_artifact(ds) # new version only on changetrain.pytiles = run.use_artifact("tiles:v3") # inputck = wandb.Artifact("vit-b16", type="model")ck.add_dir(f"ckpt/step{step}")run.log_artifact(ck, aliases=["latest", "best"])promote.pyREG = "wandb-registry-model/vit-b16"ck = run.use_artifact("vit-b16:best")run.link_artifact(ck, target_path=REG,aliases=["production"])
Version the dataset by reference
An artifact is a versioned set of files with a name and a type.
With add_reference, W&B stores paths, sizes and checksums, while the files stay in S3.
Logging again creates a new version only if a file changed.
Use add_dir instead to upload a small dataset into W&B storage.
add_reference lists the objects under the prefix, and max_objects caps how many it tracks.
Version every checkpoint
Each logged checkpoint becomes the next version, such as v12 and then v13.
The latest alias moves on every save, so add best only when validation improves.
Calling use_artifact records the dataset version this run read.
Download any version later with use_artifact(...).download().
use_artifact("vit-b16:best") fetches whichever version holds the alias.
Trace lineage and promote
Inputs and outputs form a graph from dataset to model to evaluation.
Linking to the registry with alias production publishes the model.
Other jobs load the production alias, so promotion needs no code change.
Automations can start an evaluation job when an alias moves.
The registry is shared across the organization, so other teams find the model there.
Hyperparameter sweeps
Weights & BiasesSweeps1 / 3
Define the searchAnimated diagram of a W&B sweep: the search space, agents on SLURM with Hyperband early stopping, and the results.Define the search spacesweep configurationmethodbayesmetricval_loss, minimizelrlog-uniformweight_decay0, 0.05 or 0.1early_terminatehyperbandlearning rate, log scaleequal chance in every decadefirst trials spread outlater trials focusThe sweep controller runs on the W&B server.It proposes each configuration from the results reported so far.Agents on the cluster; Hyperband stops weak runssweep controllerarray task 0lr = 2.4e-5array task 1lr = 6.1e-4array task 2lr = 1.9e-4array task 3lr = 3.2e-4each task runs: wandb agent --count 1epochval_loss3927two runs train to the endWhich settings mattered?learning rate (log scale)val_lossbestparameter importancecorrelationlrweight_decayseedbest run: lr 3.0e-4val_loss 0.70 after 30 epochsMost of the gain came from the learning rate.Narrow its range and add new parameters to the next sweep.Define the search
The sweep names the program, the search method and the metric to optimize.
Each parameter gets values or a distribution, such as log-uniform for the rate.
Bayesian search fits a model to finished trials to choose the next one.
Run agents as SLURM jobs
The wandb sweep command registers the search and prints its ID.
Each array job runs one agent that asks the controller for one configuration.
Hyperband stops weak runs at 3, 9 and 27 epochs to free their GPUs.
With min_iter 3 and the default eta of 3, Hyperband checks runs at 3, 9, 27 and 81 iterations.
Read the results
The scatter plot shows val_loss for every learning rate tried.
Parameter importance ranks which settings mattered most.
The API call best_run() returns the winner by the sweep metric.
Tables, images and charts in W&B
Weights & BiasesMedia and tables1 / 3
ImagesAnimated diagram of W&B media logging: captioned tissue tiles, a filtered predictions table, a confusion matrix and ROC curves.Images with captions, step by stepval/tiles8 of 16 tilespred: tumorpred: stromapred: normalpred: tumorpred: stromapred: tumorpred: normalpred: stromastep9000The same tiles at every validation step show what the model learns.A table of predictions you can queryval/predictionsfilter: label != predtilelabelpredp_tumortumortumor0.97stromatumor0.88normalnormal0.04tumorstroma0.31stromastroma0.09tumortumor0.91Built-in charts from your predictionsval/confusionpredictedtumorstromanormaltumorstromanormalrows: true class4122171836515412390val/rocfalse positive ratetrue positive ratetumor AUC 0.98stroma AUC 0.95normal AUC 0.99Most errors are tumor and stroma confused with each other.Images
Media, tables and charts
validate.pyimgs = [wandb.Image(x, caption=f"pred: {p}") for x, p in zip(tiles[:16], preds)]run.log({"val/tiles": imgs}, step=step)cols = ["tile", "label", "pred", "p_tumor"]table = wandb.Table(columns=cols)for x, y, p, s in samples: table.add_data(wandb.Image(x), y, p, s)run.log({"val/predictions": table})cm = wandb.plot.confusion_matrix(y_true=ys,preds=preds, class_names=CLASSES)roc = wandb.plot.roc_curve(ys, probs, labels=CLASSES)run.log({"val/confusion": cm, "val/roc": roc})
Log images with captions
Wrapping a tensor in wandb.Image logs it as a picture.
Captions show the prediction under each tile.
A step slider lets you compare the same tiles across epochs.
Masks and bounding boxes can be drawn over the same image.
Log a predictions table
A wandb.Table holds rows of images, labels, predictions and scores.
In the UI, filter to rows where the label and prediction differ.
Sort by confidence to find confident mistakes.
Log a fixed validation subset so rows compare across epochs.
Plot a confusion matrix and ROC curves
The confusion matrix counts each true class against each prediction.
ROC curves need the predicted probabilities, one column per class.
Both are built from logged tables, so you can re-plot them later.
Log them after validation, not on every training step.
What MLflow manages
Overview1 / 3
What it isIntroduction to MLflow: a self-hosted tracking server with its stores, the main components, and where it runs.Open source, and you run itYour training jobmlflow.log_params(cfg)mlflow.log_metric("loss", l)mlflow.pytorch.log_model(m)Click a call to follow it.RESTTracking serverApache 2.0mlflow serverport 5000REST APIweb UIlast requestwaiting for a callBackend storePostgreSQL or SQLiteparamsmetricstagsArtifact storeS3, MinIO or a foldermodelckptsplotshttp://mlflow:5000/#/experiments/1what the web UI showsExperimentsscaleable-trainingvit-hpodebugRunlrval_accstatusbright-owl-73e-40.812finishedcalm-fox-31e-40.794finishedquick-bee-91e-30.402runningParameters of bright-owl-7lr 3e-4global_batch 1024zero_stage 2train_lossArtifactsmodel/MLmodelmodel.pthrequirements.txtconda.yamlThe main piecesTrackingin this decklr 3e-4bs 1024Runs with params,metrics and artifactsModelsin this deckMLmodelmodel.pthrequirements.txtsignaturepytorchpyfuncOne format with flavors,such as pytorchRegistryin this deckv10.731v20.794v30.812@championVersions, aliasesand tagsServingin this deckPOST /invocations{"predictions"}model:5001A REST endpointor batch scoringEvaluationnot coveredaccf1aucMetrics on held-out data,compared across modelsTracingnot coveredagentretrievellmtoolStep-by-step tracesof LLM applicationsWhere it runsmlflow.dbLaptopmlflow server witha local SQLite fileTeam serverPostgreSQL and S3on the clusterManagedDatabricks, SageMakeror Azure ML$ export MLFLOW_TRACKING_URI=http://mlflow:5000the training code stays the sameWho sees the runsEveryone who can reachthe cluster network.What you look afterThe server, PostgreSQL, the artifactstore, backups and access control.What it is
Install and first run
terminalpip installmlflowmlflow server--port5000# API and UItrain.pyimport mlflowmlflow.set_tracking_uri("http://localhost:5000")with mlflow.start_run(): mlflow.log_metric("loss", loss.item())terminal# the same code against a team serverexport MLFLOW_TRACKING_URI=http://mlflow:5000
An open-source platform you run
MLflow is open source under Apache 2.0, started at Databricks in 2018.
A tracking server keeps run metadata in a database and files in an artifact store.
Clients talk to the server over REST, so any node that reaches it can log.
Running mlflow server starts the API and the web UI together.
The main pieces
Tracking records runs, and Models packages them in one format with flavors.
The registry versions models and names them with aliases.
Serving and evaluation reuse the same packaged model.
MLflow 3 made logged models first-class and expanded tracing for GenAI apps.
Where it runs
On a laptop, mlflow server with a local database is enough.
A team runs one server on the cluster, backed by PostgreSQL and S3.
Managed versions exist on Databricks, SageMaker and Azure ML.
The client code stays the same, and only MLFLOW_TRACKING_URI changes.
Tracking runs with MLflow
Experiment tracking1 / 4
Start a runAnimated diagram of an MLflow run: parameters, metrics, system metrics and logged checkpoints.One MLflow run per training jobtrain.pymlflow.start_run()tracking servermlflow:5000experiment: scaleable-trainingbright-owl-7ParametersRUNNINGlr3e-4global_batch1024zero_stage2modelvit-b16epochs90train_losslrsystem metrics: GPU utilization (%)every 10 sgpu_0gpu_1gpu_2gpu_3logged models (checkpoints)ranked by val_accvit-b16-step9000step 9000val_acc 0.812vit-b16-step6000step 6000val_acc 0.794vit-b16-step3000step 3000val_acc 0.731FINISHEDOr let the framework log for youPyTorch Lightninglogger=MLFlowLogger(...)Hugging Face Trainerreport_to="mlflow"Lightning autologgingmlflow.pytorch.autolog()experiment: scaleable-traininglightning-ssl-8hf-finetune-3autolog-run-2Start a run
Setting the tracking URI sends runs to the shared server.
The experiment groups this job’s runs, and it is created on first use.
The call log_params stores the configuration with the run.
Log metrics and system metrics
One log_metrics call sends the dict in a single request.
GPU, CPU and memory are sampled every 10 seconds by default.
Metrics are stored against the training step.
Track checkpoints as models
In MLflow 3, each log_model call creates a logged model.
Passing model_id links val_acc to that checkpoint.
Then search_logged_models ranks checkpoints by metric.
Use a framework integration
Lightning uses MLFlowLogger, and Hugging Face uses report_to="mlflow".
Autologging records Lightning metrics, params and the model.
Environment variables can set the server and experiment.
MLflow on a GPU cluster
Self-hosted tracking1 / 3
Tracking serverAnimated diagram of a self-hosted MLflow server, rank-0 logging with resuming, and the model registry.Host the tracking server inside the clustercluster networkcompute node 0rank 0 logs to the servercompute node 1the other ranks only trainService node:5000mlflow serverREST API and web UI--host 0.0.0.0--backend-store-uri--artifacts-destinationPostgreSQLruns, params,metrics, registryS3 or MinIOmodels, checkpoints,other artifactsYour laptopthe web UI, through a tunnelssh -L 5000:mlflow:5000 login01Listen on every interfaceCompute nodes reach the server by name.Also set --allowed-hosts to the namesthat clients use.No internet neededTraining nodes talk onlyto this server.Log from rank 0, resume after a requeuetwo nodes, 8 ranksrank 0rank 1rank 2rank 3rank 4rank 5rank 6rank 7bright-owl-7run_id 3f9c...resumedjob 1 (preempted)checkpointstate["run_id"] = "3f9c..."job 2: start_run(run_id)Model registry: versions and aliasesregistered model: vit-b16Version 1step 3000val_acc 0.731Version 2step 6000val_acc 0.794Version 3step 9000val_acc 0.812championevaluation or serving jobmodels:/vit-b16@championTracking server
Server, logging and registry
service nodemlflow server--host0.0.0.0--port5000 \--backend-store-uripostgresql://mlflow@db/mlflow \--artifacts-destinations3://mlflow-artifactstrain.pyif dist.get_rank() == 0: # one process logs rid = state.get("run_id") # saved in checkpoint run = mlflow.start_run(run_id=rid) # resume state["run_id"] = run.info.run_idpromote.pymv = mlflow.register_model(info.model_uri, "vit-b16")client = mlflow.MlflowClient()client.set_registered_model_alias("vit-b16", "champion", mv.version)model = mlflow.pytorch.load_model("models:/vit-b16@champion")
Host the tracking server
Run metadata goes to PostgreSQL, and artifacts go to S3 or MinIO.
Nodes upload artifacts through the server, so they need no S3 keys.
With --host 0.0.0.0, also set --allowed-hosts.
Nodes only have to reach this server, so training needs no internet.
Log from rank 0 and resume
Only rank 0 opens a run, so each metric is logged once.
The run ID is saved in the checkpoint with the weights.
A requeued job passes it to start_run and keeps logging.
Register and promote
Each registration adds a numbered version of the model.
Moving the champion alias promotes a version.
Aliases replace the stages deprecated in MLflow 2.9.
Tuning with nested runs
Nested runs1 / 3
Parent and child runsAnimated diagram of an Optuna search logged to MLflow as nested runs across several SLURM jobs, then queried and compared.One parent run, one child run per trialRun namelrval_lossvit-hpoparenttrial-03.1e-051.21trial-18.0e-040.98trial-22.2e-040.79trial-34.6e-040.83trial-42.9e-040.72trial-51.2e-051.48trial-63.4e-040.75Optuna proposes lrEach child run is taggedmlflow.parentRunIdThe UI nests children underthat parent automatically.Several SLURM jobs share one studyPostgreSQLOptuna studyvit-hpotrial states12 running13 running11 complete10 prunedSLURM job 1trial 10SLURM job 2trial 11SLURM job 3trial 12SLURM job 4trial 13MLflow servervit-hpotrial-7donetrial-8donetrial-9donetrial-10donetrial-11donetrial-12runningtrial-13runningQuery the trials and compare themsearch_runs(...) returns a DataFrametags.mlflow.runNameparams.lrparams.wdmetrics.val_losstrial-42.9e-040.050.72trial-63.4e-040.040.75trial-22.2e-040.080.79trial-34.6e-040.030.83lrwdval_lossbestParent and child runs
Optuna trials as nested runs
hpo.pydef objective(t): lr = t.suggest_float("lr", 1e-5, 1e-3, log=True) wd = t.suggest_float("wd", 0.0, 0.1) with mlflow.start_run(parent_run_id=PARENT): mlflow.log_params({"lr": lr, "wd": wd}) return train(lr, wd) # val_loss# every SLURM job runs the same scriptstudy = optuna.load_study(study_name="vit-hpo",storage=DB) # sharedstudy.optimize(objective, n_trials=8)analyze.pyq = f"tags.mlflow.parentRunId = '{PARENT}'"runs = mlflow.search_runs(filter_string=q,order_by=["metrics.val_loss ASC"])
One child run per trial
Optuna suggests a learning rate on a log scale and a weight decay.
Each trial opens a child run with parent_run_id and logs its parameters.
The UI nests the children under the parent, so the search stays together.
Returning the validation loss lets Optuna steer the next trials.
Spread trials over SLURM jobs
Optuna keeps the study in PostgreSQL, so every job shares it.
Each job loads the study, pulls the next trial and trains it.
A parent ID works across processes, where nested=True cannot.
Optuna pruners can stop weak trials early, like Hyperband.
Find the best trial
The call search_runs returns the runs as a pandas DataFrame.
Filter on the parent tag and sort by validation loss.
The compare view draws the trials as parallel coordinates.
Retrain or load the best trial’s model from its run.
Serving MLflow models
Models1 / 3
Signature and filesAnimated diagram of an MLflow model package with a signature, loading it by alias with input checks, and serving it over REST.What log_model writesvit-b16/MLmodelflavors and signaturedata/model.pththe weightsrequirements.txtpinned librariespython_env.yamlPython versioninput_example.jsona valid requestMLmodelflavors:pytorchpython_functionsignature:inputs: float32 [-1, 3, 224, 224]outputs: float32 [-1, 3]run_id: 3f9c...Load by alias, check every inputmodels:/vit-b16@championpyfunc modelpredict(input)float32 [8, 3, 224, 224]matches the signatureuint8 [8, 224, 224, 3]rejected: shape does not matchbatch jobnightly scoringnotebookerror analysisSpark UDFmillions of tilesA REST endpoint from the command lineclientPOST /invocations{"inputs":[[[0.12, ...]]]}returns{"predictions": ...}model serverport 5001/invocationspredict/pinghealth check/versionMLflow versionbuild-dockermodelenvironmentserverimage: vit-b16-servingSignature and files
The signature records types and shapes, and -1 accepts any batch size.
The input example shows callers a valid request.
Registering creates the next version of the model.
Load it anywhere as a Python function
A PyTorch model also loads as a generic pyfunc model.
Inputs are checked against the signature before predict runs.
Batch jobs load by alias, so they pick up promotions.
Serve it over REST
The serve command starts an HTTP server for the model.
Clients POST JSON to /invocations and get predictions back.
The build-docker command packages the same server as an image.
What TensorBoard shows
TensorBoardOverview1 / 3
What it isIntroduction to TensorBoard: event files served by a local process, its dashboards, and where it fits.Files in, dashboards outtrain.pySummaryWriterevent filesruns/demo/tensorboard--logdir runsbrowserlocalhost:6006writeson diskreads and serveschartsNo account and no database:just files on disk and one local process.The dashboardsScalarsLoss, accuracy,learning rateImagesSamples, masks,attention mapsHistogramsWeights andgradients over timeDistributionsPercentile bandsat every stepGraphsThe tracedmodel graphProjectorEmbeddings withPCA, t-SNE, UMAPHParamsSettings againstfinal metricsPR curvesPrecision and recallat each thresholdThe next slides log to most of these from a training job.Where it fitsStrengthsWatch forNothing to hostfiles plus one processWorks offlineeven on air-gapped clustersBuilt into many trainersLightning, Keras, Hugging FaceNo run databaseand no registry or artifact storeSharing takes workcopy the logs or expose the serverTensorBoard.dev is gonethe hosted service closed in 2023A good default for a single user or an air-gapped cluster.What it is
Install and first run
train.pyfrom torch.utils.tensorboard import SummaryWriterwriter = SummaryWriter("runs/demo")writer.add_scalar("loss", loss.item(), step)writer.close()terminalpip installtensorboardtensorboard--logdirruns# localhost:6006train.py, optional# later: mirror the same logs into W&Bwandb.init(sync_tensorboard=True)
Files in, dashboards out
A writer appends records to event files in a run folder.
The tensorboard command reads those files and serves the web UI.
There is no account, no database and no service to maintain.
PyTorch writes the format directly with torch.utils.tensorboard.
TensorBoard comes from TensorFlow, and torch.utils.tensorboard writes the same file format.
The dashboards
Scalars, images and histograms cover most training needs.
Graphs, the embedding projector and PR curves help with debugging.
The HParams view compares settings against final metrics.
Each dashboard is a plugin that reads its own record type.
Where it fits
It suits a single user, quick experiments and air-gapped clusters.
It has no run database, registry or artifact store.
The hosted TensorBoard.dev service shut down at the end of 2023.
W&B can mirror the logs with sync_tensorboard=True if you outgrow it.
Existing logs can be uploaded to W&B later with wandb sync --sync-tensorboard.
TensorBoard on a cluster
TensorBoardEvent files1 / 4
Writer on rank 0Animated diagram of TensorBoard logging on rank 0, dashboards, SSH viewing and resuming with purge_step.One event-file writer on rank 0one node, 4 GPUsrank 0rank 1rank 2rank 3writestrains onlytrains onlytrains onlyflush every 120 sshared filesystemruns/vit-b16-zero2/events.out.tfevents.*2.1 MBcheckpoints/TensorBoard reads this folderwhile training is still running.Writes are buffered and flushed every two minutes.Call writer.close() at the end so nothing is lost.Scalars, histograms and imageslossloss/trainloss/valhead.weighthistogram over stepsstep 0step 9000attentionstep 9000drag the step slider to see earlier epochsView it from your laptoplocalhost:6006your laptopSSHlogin nodetensorboard--logdir runs--port 6006listens on localhostshared filesystemruns/compute nodeswritereadOpen localhost:6006 on the laptoponce the tunnel is up; nothing is exposed to the network.Resume after a requeue with purge_steploss/trainone log_dir, two jobspurgedcheckpoint at step 4000resumed jobLightningTensorBoardLogger("runs")Hugging Facereport_to="tensorboard"DeepSpeed"tensorboard": {...}Writer on rank 0
The writer appends event files to a run folder on shared storage.
Only rank 0 writes, so each value is recorded once.
Events flush every 120 s, and close() writes the rest.
Log scalars, histograms and images
Tags that share a prefix, like loss/train, are grouped.
Histograms show a weight distribution shifting over training.
Images and histograms are heavy, so log them less often.
View it through an SSH tunnel
TensorBoard listens on localhost, the default since 2.0.
The SSH tunnel forwards port 6006 to your laptop.
It rereads the folder, so charts update during training.
Resume cleanly
The purge_step option hides events at or after the restored step.
The resumed curve continues without overlapping the old one.
Keep the same log folder so both jobs form one run.
Frameworks write the same event files, so keep one log_dir per run.
Comparing runs in TensorBoard
TensorBoardComparing runs1 / 3
One folder per runAnimated diagram of TensorBoard run folders overlaid on one chart, the HParams dashboard, and how TensorBoard samples long logs.Each folder under runs/ is a runruns/lr3e-4_bs1024events.out.tfevents.*lr1e-3_bs1024events.out.tfevents.*lr3e-4_bs512events.out.tfevents.*loss/trainall runs, one chartsmoothing0.6Name each folder after the settings that differ.Faint lines are raw values. Drag the smoothing, hover, or click a run to hide it.The HParams dashboardtable viewrunlrbatchhparam/val_acclr3e-4_bs10243e-410240.812lr1e-3_bs10241e-310240.776lr3e-4_bs5123e-45120.801lr1e-4_bs10241e-410240.768parallel coordinates viewlrbatchhparam/val_accbestTensorBoard keeps a sample of long logsloss/trainlogged every steploggedkept in memoryattentionimages: 10 kept per seriesRaise the limit with--samples_per_plugin images=100More samples cost memory in the TensorBoard process.Fast loading reads large logs much faster.It is on by default since TensorBoard 2.5.One folder per run
TensorBoard treats each subfolder of the log directory as a run.
Naming folders by their settings makes the run list readable.
All runs share one chart per tag, so curves overlay directly.
The smoothing slider averages noise without changing the data.
A regex filter in the run list hides the runs you are not comparing.
Watch out
Reusing a folder for a new run mixes its curves with the old ones.
Log hyperparameters with results
The call add_hparams pairs a run’s settings with its final metrics.
The HParams tab shows them as a table and as parallel coordinates.
It writes a small sub-run, and run_name sets its folder name.
Prefix the metric, as in hparam/val_acc, to keep it apart from training scalars.
In practice
Log hyperparameters once per run, with the final metrics.
Know what TensorBoard keeps
TensorBoard keeps a random sample per tag to save memory.
By default only 10 images per series survive.
The --samples_per_plugin flag raises those limits.
Fast loading, on by default since 2.5, reads large logs much faster.
Sampling only changes what TensorBoard shows, and the event files keep every value.
In practice
Thin heavy logs at the source before raising the limits.
Beyond scalar metrics
TensorBoardBeyond scalars1 / 3
Embedding projectorAnimated diagram of the TensorBoard embedding projector with tissue tiles, precision-recall curves over training, and a traced model graph.Tile embeddings in the projectorprojector2,000 points768 dimensionsreduce withPCAt-SNEUMAPcolor bylabeltumorstromanormalA few stroma tiles sit inside the tumor cluster: worth a look.Precision and recall at every thresholdpr/tumorone curve per logged steprecallprecision01epoch 1epoch 5epoch 10threshold 0.50precision 0.91, recall 0.84The traced model graphEmbedding projector
The call add_embedding saves one feature vector per tile, here 768 values.
Metadata labels color the points, and thumbnails show the tiles themselves.
The projector reduces the vectors with PCA, t-SNE or UMAP.
Clusters that mix classes point to confusable tissue types.
Embeddings are saved as TSV and sprite files next to the event files.
In practice
Keep to a few thousand points, because t-SNE slows down beyond that.
Track precision and recall
A PR curve plots precision against recall over all thresholds.
It takes binary labels and the predicted probability of the class.
A step slider shows the curve improving over training.
Hover a point to read the threshold behind it.
add_pr_curve stores 127 thresholds by default.
Why it matters
Pick the operating threshold from the curve instead of defaulting to 0.5.
Inspect the model graph
The call add_graph traces one forward pass with an example input.
Unwrap DDP with model.module so the graph shows your own modules.
The figure is a real trace of ViT-B/16, and clicking a shaded group opens it.
Models with data-dependent control flow may not trace cleanly.
Watch out
Tracing records one path, so branches that were not taken are missing.
Choosing a tracker
Experiment trackingComparison1 / 3
Side by sideComparison tables of Weights and Biases, MLflow and TensorBoard, their cluster patterns, and a rule of thumb for choosing one.Side by sideWeights & BiasesMLflowTensorBoardHostinghosted, or a server you managea server you runnone: files on diskComparing runsproject table, reportsexperiment UI, search_runsoverlaid curves, HParamsModels and dataartifacts and a registrylogged models, a registrynot includedHyperparameter searchbuilt-in sweepsOptuna with nested runsnot includedNodes without internetoffline mode, sync laterserver inside the clusteralways worksThe same three rules on a clusterWeights & BiasesMLflowTensorBoardOne process logsif rank == 0: wandb.init(...)if rank == 0: mlflow.start_run()if rank == 0: SummaryWriter(...)Resume after requeueid=f"slurm-{job}",resume="allow"start_run( run_id=rid)purge_step= start_stepNo internetWANDB_MODE=offlinewandb syncMLFLOW_TRACKING_URI= cluster server--logdir onshared storageA rule of thumbA team wants shared dashboards with little setupand may send metrics to a hosted serviceWeights & BiasesData must stay on your own serversand you want a model registry and servingMLflowOne person, a quick experiment, or an air-gapped clusterand curves are all you needTensorBoardSide by side
What surrounds the curves
All three log scalars against a step, but they differ in what surrounds the curves.
W&B bundles dashboards, sweeps, artifacts and a registry behind one login.
MLflow gives the same record on infrastructure you operate, plus model serving.
TensorBoard reads event files and nothing else, so it needs no hosting.
One pattern for all three
Only rank 0 opens a run, so each value is logged once.
The run identity survives a requeue as a job ID, a saved run ID, or a folder.
Log against the optimizer step restored from the checkpoint.
Compute nodes without internet need offline mode or a server inside the cluster.
How to choose
Start from the constraint of whether metrics may leave your network.
Then ask who reads them, whether one person, a team, or a deployment pipeline.
TensorBoard is enough to debug, but a shared tracker is what makes results defensible.
Switching later is cheap, because the logging calls are almost identical.
one GPU is too slowOne GPU, one process → DataParallelWeak spotOne GPU processes a fixed number of samples per second, so a long run takes days.FixDataParallel copies the model to several GPUs and splits every batch across them.
a single processDataParallel → DDPWeak spotOne Python process re-copies the model every step and gathers the outputs on GPU 0, which fills first.FixDDP runs one process per GPU. Each keeps its own replica, and only gradients are exchanged.
idle networkDDP → Gradient bucketsWeak spotAveraging the gradients only after backward has finished leaves the network idle while it runs.FixGradients are packed into buckets, and each bucket’s all-reduce starts while backward continues.
one machine onlyDDP → SLURM launchWeak spottorchrun on one node cannot start processes on other machines.FixSLURM allocates the nodes and srun starts torchrun on each one; the ranks meet through a rendezvous.
time limits, failuresSLURM launch → Checkpoint and requeueWeak spotJobs hit their time limit, get preempted or lose a node, and the run is lost.FixSave atomic checkpoints, catch the warning signal, requeue, and resume through one code path.
SSH dropsSLURM launch → tmuxWeak spotA dropped SSH connection kills the shell and everything started from it.FixA tmux session on the login node keeps running; reattach and the panes are still there.
global batch growsDDP → Batch and LR scalingWeak spotN ranks make the global batch N times larger, so the old learning rate no longer fits.FixScale the learning rate with the batch, warm it up, and know where that rule stops working.
out of memoryOne GPU, one process → Mixed precisionWeak spotActivations stored as 32-bit floats fill the GPU before the batch is large enough.FixAutocast runs most operations in 16 bits, which roughly halves activation memory.
activations storedMixed precision → Activation checkpointingWeak spotEvery layer’s output is kept in memory until backward needs it.FixCheckpointing drops them and recomputes each block during backward: memory traded for compute.
batch too bigMixed precision → Gradient accumulationWeak spotThe batch the optimizer needs does not fit in a single forward pass.FixAccumulate gradients over k micro-batches, then take one optimizer step.
a full copy per GPUDDP → FSDPWeak spotEvery rank holds all parameters, gradients and optimizer states, so adding GPUs adds no memory.FixFSDP shards all three and gathers a layer’s parameters only while that layer runs.
replicated statesDDP → ZeROWeak spotOptimizer states are 12 of the 16 bytes per parameter, and DDP copies them to every rank.FixZeRO partitions them in stages: 1 the optimizer states, 2 the gradients, 3 the parameters.
still too largeZeRO → ZeRO-OffloadWeak spotEven when sharded, the states can exceed the GPUs you have.FixZeRO-Offload moves optimizer states and the update to CPU memory; ZeRO-Infinity adds NVMe.
data parallel onlyZeRO → 3D parallelismWeak spotData parallelism cannot split a single layer, or a very deep model, across devices.FixTensor parallel inside a node, pipeline across nodes, data parallel across replicas.
slow, but where?One GPU, one process → ProfilingWeak spotA slow step does not say whether data, compute or communication is the cause.FixTime the three parts of a step, then trace with the profiler before changing anything.
GPU waits for dataProfiling → DataLoader workersWeak spotDecoding and augmentation on one CPU core cannot keep up with the GPU.FixWorker processes, pinned memory and prefetching keep the next batch ready.
many small filesDataLoader workers → Sharded streamingWeak spotOpening one small file per sample over a network filesystem throttles every worker.FixPack samples into tar shards, read them sequentially, and give each rank its own shards.
per-op overheadProfiling → torch.compileWeak spotEager mode pays the interpreter and dispatcher for every operation and cannot fuse them.Fixtorch.compile captures the graph, fuses elementwise operations and generates kernels.
launch per kerneltorch.compile → CUDA graphsWeak spotEach kernel is still launched separately from the CPU, so many small kernels leave the GPU idle.FixA CUDA graph records the launch sequence once and replays it with a single call.
one node’s CPUsSharded streaming → Ray DataWeak spotPreprocessing is tied to the CPU cores of the training node.FixRay Data runs it on a pool of workers across the cluster and streams batches to the GPUs.
hand-written recoveryCheckpoint and requeue → Ray Train and TuneWeak spotRequeue and resume logic is written by hand for every project.FixRay Train restarts failed workers from the last reported checkpoint; Ray Tune schedules the trials.
numbers in a log fileOne GPU, one process → TensorBoardWeak spotPrinted metrics cannot be compared across runs and are gone with the terminal.FixTensorBoard writes event files and plots scalars, images, histograms and the model graph.
no model registryTensorBoard → MLflowWeak spotEvent files hold curves, but not which checkpoint is in production.FixMLflow adds a tracking server, logged artifacts and a model registry with aliases.
hard to shareTensorBoard → W&BWeak spotThe log directory lives on the cluster, so sharing a view means tunnels and copies.FixW&B hosts runs, artifacts, tables and reports, and resumes a run after a requeue.
manual searchW&B → SweepsWeak spotTrying hyperparameters by hand does not scale past a few runs.FixA sweep defines the search space; agents run the trials and Hyperband stops the weak ones.
settings in codeOne GPU, one process → argparseWeak spotHyperparameters edited inside the script leave no record of what a run actually used.Fixargparse makes each setting a typed flag with a default, set from the command line.
flags pile upargparse → OmegaConfWeak spotForty flags share one flat namespace, and their defaults are buried in the script.FixA nested YAML file groups the settings; OmegaConf lays command-line overrides over it.
file copiesOmegaConf → HydraWeak spotEvery model or dataset variant becomes another copy of the file, and the copies drift apart.FixHydra composes the config from groups, takes overrides and sweeps on the command line, and saves the result with each run.
tuned by handOne GPU, one process → Random searchWeak spotSettings guessed one run at a time leave most GPUs idle, and nobody can repeat the path to the result.FixRandom search draws every setting of every trial at random, so all the trials can train at once.
ignores resultsRandom search → TPEWeak spotRandom search never looks at a result: trial 50 is drawn as blindly as trial 1.FixTPE splits the finished trials into good and bad, and samples where good ones are dense and bad ones are not.
runs to the endTPE → Early stoppingWeak spotA better sampler still trains every trial for its full length, the hopeless ones included.FixSuccessive halving, Hyperband and ASHA stop the weakest trials at fixed cuts and spend the epochs on the rest.
pieces to wire upEarly stopping → OptunaWeak spotA sampler, a pruner, shared storage and the record of every trial are four things to write and keep in step.FixOptuna puts them behind one study: the objective asks for values and reports its loss, and the study does the rest.
reduce-scatterGradient buckets ⇢ FSDPShared ideaFSDP’s gradient step is the first half of DDP’s all-reduce: a reduce-scatter that leaves each rank with only its shard.
shard, not replicateFSDP ⇢ ZeROShared ideaFSDP and ZeRO stage 3 are the same idea in two libraries: shard the parameters, gradients and optimizer states.
early stoppingSweeps ⇢ Ray Train and TuneShared ideaHyperband in a W&B sweep and ASHA in Ray Tune both end unpromising trials early and spend the GPUs on the rest.
the run’s configHydra ⇢ MLflowShared ideaHydra saves the composed config in the run folder; MLflow stores it with the run’s metrics, as flat params plus the file itself.
Starting point
Solid: weak spot, then the fix. Dashed: a shared idea.
Click a label for its card, a dot for its slide, a family to show it alone.
Start from one GPU
Each arrow names a weak spot of the technique it leaves and points to the technique built to fix it. Press → to grow the map one fix at a time, or use Show everything and click any label.
Eight families, one starting point
32 techniques in eight families. Click a label to read its card and light up its lineage; click a family to show it alone.