How-to guides

PyTorch DDP multi-GPU training with torchrun

PyTorch DDP multi-GPU training runs one process per GPU, each holding a full copy of the model and a different slice of the data. Gradients are averaged with all-reduce during the backward pass. Wrap the model in DistributedDataParallel, shard data with DistributedSampler, launch with torchrun --nproc-per-node=gpu train.py, and save checkpoints from rank 0 only.

NEURAMESH / COMPUTE FIELD NOTES00 / 10

Prerequisites and which GPU to rent

DDP is data parallelism. Every process keeps its own full model and optimizer, and they stay in sync because they start from the same weights and apply the same averaged gradients each step. That means the model, its gradients, optimizer state and activations for one micro-batch must fit on a single GPU. If they do not, use sharding instead, covered in PyTorch FSDP training.

Size one GPU first with the VRAM calculator, then add GPUs for speed. You need a Linux server with two or more NVIDIA GPUs, a recent NVIDIA driver, a CUDA build of PyTorch, and your dataset on local disk. DDP works over PCIe, but gradient traffic every step favors GPUs linked by NVLink for large models; NVLink vs PCIe explains the difference.

Prerequisites and which GPU to rent
Model fits on one GPU?Typical rentalApproach
Yes, with room for a useful batch2-8 GPUs in one serverDDP on one node
Yes, but one node is too slowSeveral 8-GPU serversDDP across nodes with rendezvous
No2-8 GPUs or moreFSDP or another sharded strategy

References: PyTorch notes: Distributed Data Parallel design · PyTorch docs: DistributedDataParallel

Step 1: check the server before you write code

Run nvidia-smi and confirm every GPU appears with the expected memory. Run nvidia-smi topo -m to see how the GPUs connect; NV entries mean NVLink, while PIX, PXB or SYS mean PCIe paths.

Then run python -c "import torch; print(torch.cuda.is_available(), torch.cuda.device_count())". It should print True and your GPU count. If it prints False, fix the driver or PyTorch build before going further. Copy the dataset to local NVMe now, not during the run.

References: NVIDIA System Management Interface

Step 2: adapt the training script for DDP

Four changes turn a single-GPU script into a DDP script. First, set up the process group. torchrun sets LOCAL_RANK, RANK and WORLD_SIZE for each process, so read them instead of hard-coding: local_rank = int(os.environ["LOCAL_RANK"]), then torch.cuda.set_device(local_rank), then dist.init_process_group("nccl"). NCCL is the backend for NVIDIA GPUs.

Second, wrap the model after moving it to its GPU: model = DDP(model.to(local_rank), device_ids=[local_rank]), with DDP imported from torch.nn.parallel as DistributedDataParallel. Build the optimizer from the wrapped model’s parameters.

Third, shard the data. Create sampler = DistributedSampler(dataset), pass sampler=sampler to the DataLoader and drop shuffle=True there, because the sampler shuffles by default. Call sampler.set_epoch(epoch) at the start of every epoch; the PyTorch docs say shuffling will not work properly across epochs without it.

Fourth, clean up. Log and save only when dist.get_rank() == 0, and call dist.destroy_process_group() at the end. The training loop itself does not change: forward, loss.backward(), optimizer.step(). DDP overlaps the gradient all-reduce with the backward pass by reducing gradients in buckets as they become ready.

References: PyTorch tutorial: Getting started with Distributed Data Parallel · PyTorch docs: torchrun (Elastic Launch) · PyTorch docs: torch.utils.data (DistributedSampler) · PyTorch notes: Distributed Data Parallel design · PyTorch docs: DataParallel

Step 3: launch PyTorch DDP multi-GPU training with torchrun

On one server, run torchrun --standalone --nproc-per-node=gpu train.py. The value gpu starts one process per visible GPU; you can also pass an integer such as 8. To use a subset, set CUDA_VISIBLE_DEVICES=0,1,2,3 before the command.

Across servers, run the same command on every node: torchrun --nnodes=2 --nproc-per-node=8 --rdzv-id=job1 --rdzv-backend=c10d --rdzv-endpoint=HOST:29400 train.py. HOST is the address of one node that all others can reach, the rendezvous id must match on every node, and PyTorch recommends the c10d backend. Open the port between nodes in the firewall.

Add --max-restarts=3 to restart all workers after a failure. The torchrun docs warn that on a failure all surviving workers are killed immediately, so load the latest checkpoint at the start of main() or every restart begins from step zero.

References: PyTorch docs: torchrun (Elastic Launch) · PyTorch tutorial: Getting started with Distributed Data Parallel

Settings that matter

Most runs need only the defaults. Change one setting at a time and record step time, so you know what helped. With a mean loss, the learning rate that suits a given global batch on one GPU suits the same global batch on DDP, per the DDP API docs.

Settings that matter
SettingDefaultWhen to change it
--nproc-per-node1Set to gpu or the GPU count
Per-GPU batch sizeYour choiceGlobal batch = per-GPU batch x GPU count x accumulation steps
bucket_cap_mb25 MiBTune only after profiling communication
find_unused_parametersFalseTrue only if some parameters get no gradient; it adds overhead
gradient_as_bucket_viewFalseTrue to cut peak memory by avoiding gradient copies
no_sync()Not usedSkip all-reduce on accumulation micro-steps; include the forward pass inside it
DistributedSampler drop_lastFalseTrue to drop the uneven tail instead of padding

References: PyTorch docs: DistributedDataParallel · PyTorch docs: torchrun (Elastic Launch) · PyTorch docs: torch.utils.data (DistributedSampler)

Save and resume checkpoints

Every rank holds identical weights, so save once. The PyTorch tutorial saves torch.save(model.state_dict(), path) inside if rank == 0, then calls dist.barrier() so no process loads before the save completes. When loading, pass map_location so each rank loads onto its own GPU rather than all onto GPU 0, and use weights_only=True.

Save the optimizer state, the epoch and the step too, and write to persistent storage rather than the instance disk. A full method for choosing intervals and storage is in GPU training checkpoints.

References: PyTorch tutorial: Getting started with Distributed Data Parallel · PyTorch docs: torchrun (Elastic Launch)

Common errors and fixes

Distributed jobs fail in a small number of ways. Set NCCL_DEBUG=INFO in the environment to print NCCL’s setup and transport choices when diagnosing. For a hang that ends in a timeout, see NCCL timeout.

Common errors and fixes
SymptomLikely causeFix
All processes use GPU 0 and run out of memoryDevice not set per processCall torch.cuda.set_device(local_rank) before init and DDP
Error about parameters that did not receive gradSome layers unused in forwardFix the model, or set find_unused_parameters=True
Job hangs at start on multi-nodeNodes cannot reach the endpointCheck rdzv endpoint, port, firewall and NCCL_SOCKET_IFNAME
Hang mid-run, then NCCL timeoutOne rank skipped a collective or stalledMake every rank run the same steps; check uneven data
Every epoch sees the same orderset_epoch not calledCall sampler.set_epoch(epoch) each epoch
Script rejects --local-rankOld argparse for --local_rankRead LOCAL_RANK from the environment instead
Speed barely improves with more GPUsData loader or small batchProfile; raise num_workers and per-GPU batch

References: NVIDIA NCCL environment variables · PyTorch docs: DistributedDataParallel · PyTorch docs: torchrun (Elastic Launch) · PyTorch docs: torch.utils.data (DistributedSampler)

Estimate time and GPU-hours

Measure, then multiply. Run 100 steps on one GPU and 100 steps on all GPUs, and record samples per second for each. Divide samples per epoch by the multi-GPU rate to get epoch time. Scaling is rarely perfectly linear, so use the measured rate, not one GPU times eight. If it scales poorly, start with low GPU utilization.

The example below is illustrative, with assumed numbers. Suppose 1 GPU processes 400 samples per second and 8 GPUs process 2,800 (87.5% scaling). A 10 million sample job takes about 6.9 hours on one GPU and about 1 hour on eight, plus an assumed 0.5 hours of setup. At an assumed $2 per GPU-hour, the totals are shown in the table.

Estimate time and GPU-hours
Item1 GPU8 GPUs with DDP
Assumed throughput400 samples/s2,800 samples/s
Training time for 10M samples6.9 hours1.0 hour
Setup time0.5 hours0.5 hours
GPU-hours7.412.0
Cost at an assumed $2 per GPU-hour$14.80$24.00

Checklist and next step

Confirm the model fits on one GPU. Check nvidia-smi and topology. Read LOCAL_RANK, set the device, init NCCL. Wrap with DDP, add DistributedSampler and set_epoch. Save from rank 0 with a barrier and resume at start-up. Launch with torchrun, measure samples per second, then estimate GPU-hours.

When the numbers are ready, choose a multi-GPU server on rent GPUs: pick the GPU, plan, GPU count, hours and region, and you receive a confirmed quotation, typically within one business day, with nothing charged until you approve. For help picking a GPU, ask the compute advisor.

NeuraMesh prices for these GPUs

NeuraMesh prices per GPU-hour in USD, excluding taxes, as of 2026-11-27. Live prices are on the rental pages.
GPUMemoryData centerValue
RTX 409024 GB$0.46$0.40
L40S48 GB$1.26$0.54
A10080 GB$1.56$0.98
H10080 GB$2.88$2.00

Every order is confirmed in a quotation before you pay. See all GPU prices.

Questions readers ask

How do I run PyTorch DDP multi-GPU training on one machine?

Wrap the model in DistributedDataParallel, use a DistributedSampler, and start the script with torchrun --standalone --nproc-per-node=gpu train.py. torchrun starts one process per GPU and sets LOCAL_RANK, RANK and WORLD_SIZE for each.

What is the difference between DDP and DataParallel?

DataParallel runs one process that splits each batch across GPUs. DDP runs one process per GPU and overlaps gradient all-reduce with the backward pass. The DataParallel docs recommend DDP instead for multi-GPU training.

Should I use DDP or FSDP?

Use DDP when the model, gradients and optimizer state fit on one GPU. Use FSDP when they do not, since it shards them across GPUs at the cost of more communication.

Do I need to change the learning rate with DDP?

DDP averages gradients, so with a mean loss the same learning rate fits the same global batch size. If you raise the per-GPU batch, the global batch grows with GPU count and you may need to retune.

Why does torchrun pass --local-rank to my script?

Since PyTorch 2.0 torchrun passes --local-rank with a dash. Reading the LOCAL_RANK environment variable avoids the argument entirely.

Sources and editorial notes

Primary documentation reviewed November 24, 2026. Provider descriptions reflect published documentation. Recommendations are our analysis; worked figures are illustrative unless explicitly stated otherwise. No independent provider benchmark or uptime ranking is claimed.

Read the editorial policy.

Need this GPU? Rent it from NeuraMesh: choose a GPU and plan, get a confirmed quotation, and pay only when you approve. See pricing.