PyTorch multi-GPU training: a minimal DDP example and scaling checks

· Nodeox

Adding a second GPU takes more than wrapping a model and hoping that the input is divided correctly.

A basic PyTorch DDP job uses one process per GPU, a distributed process group, a model replica in each process and an explicit way to divide the data. DDP synchronizes gradients; the launcher and input pipeline complete the arrangement.

This PyTorch multi-GPU training example builds a single-machine NVIDIA job with torchrun, then explains what its timing tells you. It uses a small synthetic classification problem so the mechanics are visible without downloading a dataset.

For the broader choice between data parallelism, partitioning and independent runs, see our multi-GPU training guide.

Tested environment

We ran the script on 14 November 2026 on one Linux machine with two NVIDIA A40 GPUs connected over PCIe, without NVLink. The environment was a Debian 13 container on Linux 6.8, Python 3.14.10, PyTorch 2.15.0+cu132 (CUDA 13.2 build), NVIDIA driver 595.91.07 and NCCL 2.30.7. The installation command was pip install torch==2.15.0. NumPy was absent; its initialization warning did not prevent these runs. The two-process run needed the NCCL setting described below.

Record your actual Linux, Python, PyTorch, CUDA build, driver, NCCL and GPU versions, plus the exact installation command. Use the official PyTorch installation selector for your machine. These timings belong to this setup; repeat the correctness and timing checks on yours.

What each process owns

torchrun launches the workers and provides LOCAL_RANK, RANK and WORLD_SIZE. LOCAL_RANK selects the device within this machine; RANK identifies the process within the job.

The DDP reference separates gradient synchronization from input distribution. Each worker owns a model replica and optimizer. DistributedSampler gives each process its share of the examples; set_epoch changes its shuffle between epochs. The sampler and loader behavior is documented in torch.utils.data.

This is replicated data parallelism. A training replica must fit each participating GPU. The example does not pool VRAM, partition layers or join AMD and NVIDIA devices.

Conceptual single-machine PyTorch DDP layout: torchrun launches two workers. DistributedSampler gives each worker different training examples. Each GPU holds a full model replica and optimizer; DDP synchronizes gradients during backward. Global batch 128 is 64 examples per worker times two workers.
Conceptual two-worker DDP layout. The sampler divides examples; DDP synchronizes gradients. A complete training replica must fit each GPU.

The complete script

Save the following as ddp_example.py. The synthetic labels come from a fixed random teacher. The separate held-out inputs provide a correctness signal for this toy task, not evidence of real-model quality.

"""Minimal NVIDIA/Linux DDP example, tested on one and two GPUs with PyTorch 2.15."""
import argparse
import json
import os
import platform
import time
from pathlib import Path

import torch
import torch.distributed as dist
from torch import nn
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import DataLoader, DistributedSampler, TensorDataset


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--batch', type=int, default=64)
    parser.add_argument('--epochs', type=int, default=5)
    parser.add_argument('--warmup-epochs', type=int, default=1)
    parser.add_argument('--workers', type=int, default=0)
    parser.add_argument('--out', default='ddp-result.pt')
    args = parser.parse_args()
    if args.batch < 1 or args.epochs <= args.warmup_epochs:
        parser.error('Use batch > 0 and epochs > warmup-epochs.')
    if args.warmup_epochs < 0 or args.workers < 0:
        parser.error('Warm-up epochs and workers must be non-negative.')
    if not torch.cuda.is_available() or torch.version.hip is not None:
        raise RuntimeError('This example targets NVIDIA CUDA GPUs on Linux.')
    local_rank = int(os.environ['LOCAL_RANK'])
    torch.cuda.set_device(local_rank)
    device = torch.device('cuda', local_rank)
    dist.init_process_group(backend='nccl')
    try:
        rank, world = dist.get_rank(), dist.get_world_size()
        n, features, classes = 8192, 128, 10
        if n % (world * args.batch):
            raise ValueError('8192 must be divisible by world_size * per-rank batch.')
        torch.manual_seed(1234)
        generator = torch.Generator().manual_seed(7)
        teacher = torch.randn(features, classes, generator=generator)
        train_x = torch.randn(n, features, generator=generator)
        train_y = (train_x @ teacher).argmax(dim=1)
        test_x = torch.randn(1024, features, generator=generator)
        test_y = (test_x @ teacher).argmax(dim=1)
        dataset = TensorDataset(train_x, train_y)
        sampler = DistributedSampler(dataset, num_replicas=world, rank=rank,
                                     shuffle=True, seed=17, drop_last=True)
        loader = DataLoader(dataset, batch_size=args.batch, sampler=sampler,
                            num_workers=args.workers, pin_memory=True,
                            drop_last=True)
        model = DDP(nn.Sequential(nn.Linear(features, 512), nn.ReLU(),
                                  nn.Linear(512, classes)).to(device),
                    device_ids=[local_rank])
        optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
        criterion = nn.CrossEntropyLoss()
        measured_samples = 0
        start = None
        for epoch in range(args.epochs):
            sampler.set_epoch(epoch)
            if epoch == args.warmup_epochs:
                dist.barrier()
                torch.cuda.synchronize(device)
                torch.cuda.reset_peak_memory_stats(device)
                start = time.perf_counter()
            model.train()
            for x, y in loader:
                x = x.to(device, non_blocking=True)
                y = y.to(device, non_blocking=True)
                optimizer.zero_grad(set_to_none=True)
                loss = criterion(model(x), y)
                loss.backward()
                optimizer.step()
                if epoch >= args.warmup_epochs:
                    measured_samples += x.size(0)
        torch.cuda.synchronize(device)
        elapsed = torch.tensor(time.perf_counter() - start,
                               dtype=torch.float64, device=device)
        peak = torch.tensor(torch.cuda.max_memory_allocated(device),
                            dtype=torch.int64, device=device)
        samples = torch.tensor(measured_samples, device=device)
        dist.all_reduce(elapsed, op=dist.ReduceOp.MAX)
        dist.all_reduce(peak, op=dist.ReduceOp.MAX)
        dist.all_reduce(samples, op=dist.ReduceOp.SUM)
        final_loss = loss.detach().clone()
        dist.all_reduce(final_loss, op=dist.ReduceOp.SUM)
        final_loss /= world
        # Identical held-out set evaluated independently on every replica.
        model.eval()
        with torch.no_grad():
            predictions = model.module(test_x.to(device)).argmax(dim=1)
            accuracy = (predictions == test_y.to(device)).float().mean()
        min_acc, max_acc = accuracy.clone(), accuracy.clone()
        dist.all_reduce(min_acc, op=dist.ReduceOp.MIN)
        dist.all_reduce(max_acc, op=dist.ReduceOp.MAX)
        if rank == 0:
            record = {
                'os': platform.platform(), 'python': platform.python_version(),
                'pytorch': str(torch.__version__), 'cuda_build': torch.version.cuda,
                'nccl': torch.cuda.nccl.version(),
                'gpu': torch.cuda.get_device_name(device), 'world_size': world,
                'precision': 'FP32; default backend math settings',
                'tf32_matmul': torch.backends.cuda.matmul.allow_tf32,
                'per_rank_batch': args.batch, 'global_batch': args.batch * world,
                'epochs': args.epochs, 'warmup_epochs': args.warmup_epochs,
                'last_step_mean_rank_loss': final_loss.item(),
                'measured_samples': samples.item(),
                'measured_seconds': elapsed.item(),
                'samples_per_second': samples.item() / elapsed.item(),
                'max_rank_peak_allocated_bytes': peak.item(),
                'held_out_accuracy_min': min_acc.item(),
                'held_out_accuracy_max': max_acc.item(),
            }
            path = Path(args.out)
            path.parent.mkdir(parents=True, exist_ok=True)
            torch.save({'model': model.module.state_dict(),
                        'optimizer': optimizer.state_dict(), 'record': record},
                       path)
            print(json.dumps(record, indent=2))
        dist.barrier()
    finally:
        dist.destroy_process_group()


if __name__ == '__main__':
    main()

The divisibility check makes this example deliberately narrow: every rank processes the same number of full batches, with no padded or discarded examples for the supported batch/world-size combinations. Do not silently remove the check when adapting it to another dataset; decide how incomplete or uneven inputs should be handled.

The file is a model-and-optimizer checkpoint, not a complete resumable training system. Restoring exact data-loader and random-generator progress would need additional state and testing.

Run one GPU, then two

Use the same synthetic problem, seed, number of epochs and effective batch for the fixed-work comparison:

CUDA_VISIBLE_DEVICES=0 torchrun --standalone --nnodes=1 --nproc-per-node=1 ddp_example.py --batch 128 --epochs 50 --out one-gpu.pt
CUDA_VISIBLE_DEVICES=0,1 torchrun --standalone --nnodes=1 --nproc-per-node=2 ddp_example.py --batch 64 --epochs 50 --out two-gpu.pt

If the two-process run stops at its first synchronization and fails after ten minutes with an NCCL timeout, rerun with NCCL_DEBUG=INFO and inspect nvidia-smi topo -m. On some virtualized or containerized PCIe machines, direct GPU-to-GPU (P2P) transfers are reported as available but do not work. NCCL_P2P_DISABLE=1 disables that P2P path; our test used exchange through host memory instead. Our machine needed this setting. It is a workaround for this environment, not a general performance recommendation.

The two-GPU results below used this command:

NCCL_P2P_DISABLE=1 CUDA_VISIBLE_DEVICES=0,1 torchrun --standalone --nnodes=1 --nproc-per-node=2 ddp_example.py --batch 64 --epochs 50 --out two-gpu.pt

See NVIDIA's NCCL environment-variable reference for the setting.

The global batch is per-process batch multiplied by world size: both commands use 128 examples per update. Keeping batch 128 on each of two processes would make the global batch 256 and change the comparison.

Both commands use the DDP wrapper, including the one-process reference. This controls that choice; it is not a comparison with the fastest possible unwrapped single-GPU implementation.

The script prints one JSON record from rank zero and saves one checkpoint. DistributedSampler gives these two processes the same global batches that one process sees. On the tested setup, both 50-epoch runs reached a last-step loss of 0.0192 and 88.67% held-out accuracy, apart from floating-point rounding in loss. Replica accuracy MIN equaled MAX in every run. Reloading the saved weights on CPU reproduced the held-out accuracy.

Reload the saved checkpoint on CPU

Save the following as check_reload.py and run python check_reload.py two-gpu.pt. It restores the weights and reconstructs the same held-out examples before checking accuracy; printing a stored metric alone would not re-evaluate the model.

"""Reload a checkpoint written by ddp_example.py on CPU and re-evaluate it."""
import sys

import torch
from torch import nn

path = sys.argv[1]
ckpt = torch.load(path, map_location='cpu', weights_only=True)
model = nn.Sequential(nn.Linear(128, 512), nn.ReLU(), nn.Linear(512, 10))
model.load_state_dict(ckpt['model'])
generator = torch.Generator().manual_seed(7)
teacher = torch.randn(128, 10, generator=generator)
torch.randn(8192, 128, generator=generator)  # the training inputs, drawn first in the script
test_x = torch.randn(1024, 128, generator=generator)
test_y = (test_x @ teacher).argmax(dim=1)
model.eval()
with torch.no_grad():
    acc = (model(test_x).argmax(dim=1) == test_y).float().mean().item()
rec = ckpt['record']
print(f'{path}: reloaded on CPU, held-out accuracy {acc:.6f}; recorded {rec["held_out_accuracy_min"]:.6f}'
      f'..{rec["held_out_accuracy_max"]:.6f}; optimizer state keys {sorted(ckpt["optimizer"].keys())}')

Read the timing boundary before the throughput

The first epoch is training warm-up and is excluded from the measured window. The remaining epochs still include input iteration, transfers, forward/backward computation, optimizer updates and DDP synchronization. This is steady-state fixed-work timing, not full wall-clock time from process launch to checkpoint availability. Five epochs gave a measured window of about one second with noticeable variation; the commands above use 50 epochs, which gave 13–16 seconds.

CUDA work is asynchronous. The example synchronizes the device at timing boundaries, then uses the largest per-rank elapsed interval and the total processed examples. That avoids treating one worker's shorter interval as the job's result. Evaluation, record aggregation and checkpoint writing are outside the timed window.

For this fixed work, speed-up is one-GPU measured time divided by two-GPU measured time. Two-device efficiency divides that speed-up by two. Do not call samples-per-second a time-to-quality result: the tiny synthetic task establishes neither production workload behavior nor useful-model convergence.

Repeat the measurements and retain every result. Record other activity on the machine and check the same global batch and backend math settings. Our benchmarking guide explains the broader comparison discipline.

If two GPUs are slower, inspect the interval

Observation

Inspect

Useful next experiment

Long pauses before kernels

Input preparation, loading and transfers

Compare a prepared-input run with the real pipeline

Large host-side gaps

CPU work and process/thread contention

Tune worker counts per job, not per rank in isolation

One rank reaches synchronization late

Per-rank inputs, timings and hardware

Make the workload comparable before tuning collectives

Exchange dominates useful computation

Model size, local work and topology

Test a representative model and inspect communication

Throughput rises but the comparison changed

Global batch, examples and optimizer updates

Restore the intended training configuration

This model is intentionally small; launch and synchronization overhead can be prominent. On our two A40s, two GPUs took 16.0 seconds against 13.5 for one (a speed-up of 0.84). This is a plain PyTorch toy-example measurement, not a Nodeox benchmark. A poor scaling result here does not establish how a larger model scales on the same machine.

Use a short profiler trace for diagnosis and repeat timing without heavy instrumentation. The performance tuning guide gives input-pipeline candidates; their benefit still depends on the workload.

Measured toy PyTorch DDP example on A40 GPUs: one GPU took 13.5 seconds and two took 16.0 seconds for 50 epochs with global batch 128, excluding one warm-up epoch. Both reached 88.67 percent held-out accuracy and final loss about 0.0192. The two-GPU run used NCCL P2P disabled. One long run per setup, not a Nodeox benchmark.
One long run per setup, measured 14 November 2026. Small synthetic classifier, global batch 128, 50 epochs with the first excluded from timing; one versus two A40s on PCIe without NVLink. Two GPUs used NCCL_P2P_DISABLE=1. Timing excludes startup, evaluation and checkpoint writing. These are tutorial measurements, not Nodeox results.

Common questions

Does DDP split the input automatically?

No. This example uses DistributedSampler and a per-process DataLoader. DDP's responsibility is the synchronized model update, not choosing each process's examples.

Can this run on multiple machines unchanged?

The training structure can be adapted, but this example's commands and verification scope are single-node. Multi-node rendezvous, network/backend configuration and failure behavior need their own check.

Can I use this as a mixed-vendor recipe?

No. It targets NVIDIA CUDA with NCCL. Our mixed-GPU article treats that separate execution question.

The useful outcome is a working baseline with a recorded environment, correct input distribution and a clear measurement boundary. Once that is verified, change the workload or layout deliberately and compare again.