PyTorch Distributed Training
As models grow larger and data increases, a single GPU can no longer meet training demands.
Distributed training uses multiple GPUs or even multiple machines in parallel, significantly reducing training time.
This section introduces distributed training techniques in PyTorch in detail, including DataParallel, DistributedDataParallel, and mixed-precision distributed training.
1. Fundamentals of distributed training
1.1 Why distributed training is needed
Deep learning models grow in size year by year, and training time increases accordingly. The core goal of distributed training is to spread computation across multiple compute units so that large models and data can be trained within an acceptable time.
Distributed training mainly solves two problems:
- Insufficient VRAM: Large models require large GPU memory for parameters, optimizer states, and gradients
- Excessive training time: Training a large model on a single GPU may take weeks or even months
1.2 Two major modes of distributed training
Distributed training is mainly divided into two modes:
| Mode | Principle | Applicable scenarios |
|---|---|---|
| Data Parallel | Each compute unit holds a full copy of the model, and different units process different data | The model fits in a single GPU's memory; the dataset is large and needs faster training; small team with limited machine resources |
| Model Parallel | Split the model across multiple compute units, each holding only part of the model | The model is too large to fit on one GPU; dedicated cluster with multi-machine training |
In real production environments, data parallelism is the most common approach. PyTorch provides two implementations: DataParallel and DistributedDataParallel.
2. Guide to using DataParallel
2.1 Single machine, multiple GPUs: DataParallel
DataParallel (DP) is the simplest multi-GPU training approach provided by PyTorch. With just a few lines of code changed, it lets you train on multiple GPUs in a single machine.
Example
import
torch
import
torch.
nn
as
nn
import
torch.
optim
as
optim
---- Model Definition -------------------------------------
class
SimpleModel
(
nn.
Module
)
:
def
init
(
self
)
:
super
(
)
.
init
(
)
self
.
net
=
nn.
Sequential
(
nn.
Linear
(
128
,
256
)
,
nn.
ReLU
(
)
,
nn.
Linear
(
256
,
256
)
,
nn.
ReLU
(
)
,
nn.
Linear
(
256
,
10
)
)
def
forward
(
self
,
x
)
:
return
self
.
net
(
x
)
Check the number of available GPUs
(
f
"Number of available GPUs: {torch.cuda.device_count()}"
)
Create the model and move it to the GPU
model
=
SimpleModel
(
)
-- Method 1: Using DataParallel (simplest) --------
if
torch.
cuda
.
device_count
(
)
1
:
model
=
nn.
DataParallel
(
model
)
Move to GPU (when using DataParallel, device_ids is handled automatically)
device
=
torch.
device
(
"cuda"
if
torch.
cuda
.
is_available
(
)
else
"cpu"
)
model
=
model.
to
(
device
)
Loss function and optimizer
criterion
=
nn.
CrossEntropyLoss
(
)
optimizer
=
optim.
Adam
(
model.
parameters
(
)
,
lr
=
1e-3
)
-- Training loop ------------------------------------
def
train_epoch_dp
(
model
,
loader
,
criterion
,
optimizer
,
device
)
:
model.
train
(
)
total_loss
=
0
correct
=
0
total
=
0
for
inputs
,
labels
in
loader:
inputs
=
inputs.
to
(
device
,
non_blocking
=
True
)
labels
=
labels.
to
(
device
,
non_blocking
=
True
)
optimizer.
zero_grad
(
)
outputs
=
model
(
inputs
)
loss
=
criterion
(
outputs
,
labels
)
loss.
backward
(
)
optimizer.
step
(
)
total_loss +
=
loss.
item
(
)
- inputs.
size
(
0
)
_
,
predicted
=
outputs.
max
(
1
)
correct +
=
predicted.
eq
(
labels
)
.
sum
(
)
.
item
(
)
total +
=
labels.
size
(
0
)
return
total_loss / total
,
correct / total
Simulated data
train_loader
=
[
(
torch.
randn
(
32
,
128
)
,
torch.
randint
(
0
,
10
,
(
32
,
)
)
)
for
_
in
range
(
10
)
]
Start training
for
epoch
in
range
(
3
)
:
loss
,
acc
=
train_epoch_dp
(
model
,
train_loader
,
criterion
,
optimizer
,
device
)
(
f
"Epoch {epoch+1}: Loss={loss:.4f}, Acc={acc:.4f}"
)
(
"DataParallel training complete!"
)
2.2 How DataParallel works
The DataParallel workflow is as follows:
- Model replication: Copy the model to each GPU
- Data distribution: Split the batch evenly across GPUs
- Parallel computation: Each GPU independently computes the forward pass
- Gradient aggregation: Gather gradients from all GPUs on the master GPU
- Parameter update: The master GPU updates parameters and then syncs them to the other GPUs
Example
Key DataParallel parameters
model
=
nn.
DataParallel
(
module
,
The model to parallelize (required)
device_ids
=
[
0
,
1
,
2
,
3
]
,
GPU device IDs to use; by default all cards
output_device
=
0
,
The device to gather outputs on; by default the first card
dim
=
0
The dimension along which to split data; by default the batch dimension
)
Check which device the current model is on
(
f
"Model device: {next(model.parameters()).device}"
)
Check the devices actually in use
(
f
"Number of GPUs used: {model.device_ids if hasattr(model, 'device_ids') else 'N/A'}"
)
DataParallel is simple to use but has two main issues: 1) high memory pressure on the master GPU (it must gather gradients); 2) low communication efficiency between GPUs. Therefore, DistributedDataParallel is officially recommended.
3. DistributedDataParallel in detail
3.1 DDP basics
DistributedDataParallel (DDP) is the distributed training approach recommended by PyTorch. Compared with DataParallel, DDP has the following advantages:
- Each GPU computes gradients independently, with no need to gather them on a master GPU
- Uses an efficient gradient synchronization algorithm (Ring AllReduce)
- Supports multi-machine, multi-GPU training
- Faster training and more efficient GPU memory usage
3.2 Single-machine multi-GPU training with DDP
Example
import
torch
import
torch.
nn
as
nn
import
torch.
optim
as
optim
import
torch.
distributed
as
dist
from
torch.
nn
.
parallel
import
DistributedDataParallel
as
DDP
import
os
-- Initialize the distributed environment -----------
def
setup
(
rank
,
world_size
)
:
"""Set up the distributed environment"""
Set the GPU used by the current process
torch.
cuda
.
set_device
(
rank
)
Initialize the process group
dist.
init_process_group
(
backend
=
"nccl"
,
Use the NCCL backend (recommended for GPUs)
init_method
=
"env://"
,
Environment-variable initialization method
world_size
=
world_size
,
Total number of processes
rank
=
rank
Current process rank
)
def
cleanup
(
)
:
"""Clean up the distributed environment"""
dist.
destroy_process_group
(
)
-- Data loader (distributed-aware) ------------------
def
get_distributed_loader
(
batch_size
,
world_size
)
:
"""Create a distributed-aware data loader"""
from
torch.
utils
.
data
import
DataLoader
,
DistributedSampler
Mock dataset
dataset
=
torch.
utils
.
data
.
TensorDataset
(
torch.
randn
(
100
,
3
,
32
,
32
)
,
torch.
randint
(
0
,
10
,
(
100
,
)
)
)
DistributedSampler automatically partitions the data
sampler
=
DistributedSampler
(
dataset
,
num_replicas
=
world_size
,
rank
=
rank
,
shuffle
=
True
)
loader
=
DataLoader
(
dataset
,
batch_size
=
batch_size
,
sampler
=
sampler
,
num_workers
=
2
,
pin_memory
=
True
)
return
loader
---- Model Definition -------------------------------------
class
ImageClassifier
(
nn.
Module
)
:
def
init
(
self
)
:
super
(
)
.
init
(
)
self
.
features
=
nn.
Sequential
(
nn.
Conv2d
(
3
,
32
,
3
,
padding
=
1
)
,
nn.
ReLU
(
)
,
nn.
MaxPool2d
(
2
)
,
nn.
Conv2d
(
32
,
64
,
3
,
padding
=
1
)
,
nn.
ReLU
(
)
,
nn.
AdaptiveAvgPool2d
(
1
)
,
nn.
Flatten
(
)
)
self
.
classifier
=
nn.
Linear
(
64
,
10
)
def
forward
(
self
,
x
)
:
x
=
self
.
features
(
x
)
x
=
self
.
classifier
(
x
)
return
x
-- DDP training function ----------------------------
def
train_ddp
(
rank
,
world_size
,
epochs
=
3
)
:
"""Main distributed training function"""
Initialization
setup
(
rank
,
world_size
)
Create the model and move it to the appropriate GPU
model
=
ImageClassifier
(
)
.
cuda
(
rank
)
Wrap it as a DDP model
ddp_model
=
DDP
(
model
,
device_ids
=
[
rank
]
,
Specify the device used by the current process
output_device
=
rank
,
find_unused_parameters
=
False
Whether to detect unused parameters
)
Loss function and optimizer
criterion
=
nn.
CrossEntropyLoss
(
)
optimizer
=
optim.
Adam
(
ddp_model.
parameters
(
)
,
lr
=
1e-3
)
Get the data loader
loader
=
get_distributed_loader
(
batch_size
=
16
,
world_size
=
world_size
)
Training loop
for
epoch
in
range
(
epochs
)
:
Set the epoch number at the start of each epoch (used to shuffle data)
loader.
sampler
.
set_epoch
(
epoch
)
for
batch_idx
,
(
inputs
,
labels
)
in
enumerate
(
loader
)
:
inputs
=
inputs.
cuda
(
rank
,
non_blocking
=
True
)
labels
=
labels.
cuda
(
rank
,
non_blocking
=
True
)
optimizer.
zero_grad
(
)
outputs
=
ddp_model
(
inputs
)
loss
=
criterion
(
outputs
,
labels
)
loss.
backward
(
)
optimizer.
step
(
)
if
rank
==
0
and
batch_idx %
5
==
0
:
(
f
"Epoch {epoch+1}, Batch {batch_idx}, Loss: {loss.item():.4f}"
)
Clean up
if
rank
==
0
:
(
"Training complete!"
)
cleanup
(
)
Note: in a real run, rank and world_size must be specified via command-line arguments
This code must run independently in each process
3.3 Launching distributed training
PyTorch distributed training must be launched with torchrun or torch.distributed.launch. Common launch methods are:
Example
Method 1: Use torchrun (recommended, PyTorch 2.0+)
File: train_ddp.py
""
"
Usage:
torchrun --nproc_per_node=4 train_ddp.py
"
""
Method 2: Use python -m (traditional)
""
"
python -m torch.distributed.launch --nproc_per_node=4 train_ddp.py
"
""
Method 3: Multi-machine multi-GPU launch
Machine 1 (master node)
torchrun
--nnodes
=
2
--nproc_per_node=
4
--node_rank=
0
--master_addr=192.168.1.1 --master_port=
29500
train_ddp.py
Machine 2 (worker node)
torchrun
--nnodes
=
2
--nproc_per_node=
4
--node_rank=
1
--master_addr=192.168.1.1 --master_port=
29500
train_ddp.py
Parameter Description:
--nproc_per_node: number of GPUs per node
--nnodes: number of nodes
--node_rank: current node index (starting from 0)
--master_addr: master node IP address
--master_port: master node port
3.4 Complete DDP training script
Example
Complete DDP training script (save as train_ddp.py)
import
torch
import
torch.
nn
as
nn
import
torch.
optim
as
optim
import
torch.
distributed
as
dist
from
torch.
nn
.
parallel
import
DistributedDataParallel
as
DDP
from
torch.
utils
.
data
import
DataLoader
,
DistributedSampler
import
argparse
import
os
def
parse_args
(
)
:
parser
=
argparse.
ArgumentParser
(
)
parser
.
add_argument
(
"--local_rank"
,
type
=
int
,
default
=
1
,
help
=
"Automatically passed by torchrun"
)
parser
.
add_argument
(
"--epochs"
,
type
=
int
,
default
=
10
)
parser
.
add_argument
(
"--batch_size"
,
type
=
int
,
default
=
32
)
parser
.
add_argument
(
"--lr"
,
type
=
float
,
default
=
1e-3
)
return
parser
.
parse_args
(
)
class
TrainModel
(
nn.
Module
)
:
def
init
(
self
)
:
super
(
)
.
init
(
)
self
.
net
=
nn.
Sequential
(
nn.
Conv2d
(
3
,
64
,
3
,
padding
=
1
)
,
nn.
ReLU
(
)
,
nn.
MaxPool2d
(
2
)
,
nn.
Conv2d
(
64
,
128
,
3
,
padding
=
1
)
,
nn.
ReLU
(
)
,
nn.
AdaptiveAvgPool2d
(
1
)
,
nn.
Flatten
(
)
,
nn.
Linear
(
128
,
10
)
)
def
forward
(
self
,
x
)
:
return
self
.
net
(
x
)
def
setup
(
rank
,
world_size
)
:
os
.
environ
[
"MASTER_ADDR"
]
=
"localhost"
os
.
environ
[
"MASTER_PORT"
]
=
"12355"
dist.
init_process_group
(
"nccl"
,
rank
=
rank
,
world_size
=
world_size
)
torch.
cuda
.
set_device
(
rank
)
def
cleanup
(
)
:
dist.
destroy_process_group
(
)
def
train
(
rank
,
world_size
,
args
)
:
setup
(
rank
,
world_size
)
Create the model
model
=
TrainModel
(
)
.
cuda
(
rank
)
model
=
DDP
(
model
,
device_ids
=
[
rank
]
)
Optimizer and loss function
optimizer
=
optim.
Adam
(
model.
parameters
(
)
,
lr
=
args.
lr
)
criterion
=
nn.
CrossEntropyLoss
(
)
Dataset
dataset
=
torch.
utils
.
data
.
TensorDataset
(
torch.
randn
(
1000
,
3
,
32
,
32
)
,
torch.
randint
(
0
,
10
,
(
1000
,
)
)
)
DistributedSampler ensures each process sees different data
sampler
=
DistributedSampler
(
dataset
,
num_replicas
=
world_size
,
rank
=
rank
,
shuffle
=
True
)
loader
=
DataLoader
(
dataset
,
batch_size
=
args.
batch_size
,
sampler
=
sampler
,
num_workers
=
2
,
pin_memory
=
True
)
Training loop
for
epoch
in
range
(
args.
epochs
)
:
Key: set the epoch at every epoch to shuffle the data partition
sampler.
set_epoch
(
epoch
)
model.
train
(
)
epoch_loss
=
0
for
inputs
,
labels
in
loader:
inputs
=
inputs.
cuda
(
rank
,
non_blocking
=
True
)
labels
=
labels.
cuda
(
rank
,
non_blocking
=
True
)
optimizer.
zero_grad
(
)
outputs
=
model
(
inputs
)
loss
=
criterion
(
outputs
,
labels
)
loss.
backward
(
)
optimizer.
step
(
)
epoch_loss +
=
loss.
item
(
)
Synchronize all processes to ensure each has finished the current epoch
dist.
barrier
(
)
if
rank
==
0
:
avg_loss
=
epoch_loss /
len
(
loader
)
(
f
"Epoch {epoch+1}/{args.epochs}, Loss: {avg_loss:.4f}"
)
cleanup
(
)
if
name
==
"main"
:
args
=
parse_args
(
)
Get world_size from the environment variable
world_size
=
int
(
os
.
environ
[
"WORLD_SIZE"
]
)
Get rank from the environment variable (set automatically by torchrun)
rank
=
int
(
os
.
environ
[
"RANK"
]
)
if
torch.
cuda
.
is_available
(
)
:
train
(
rank
,
world_size
,
args
)
else
:
(
"A CUDA environment is required to run distributed training"
)
Key point: call
sampler.set_epoch(epoch)at every epoch to ensure the data partition is shuffled; otherwise multiple processes will see the same data.
4. Mixed precision in distributed training
4.1 Combining DDP and AMP
Combining distributed training with mixed-precision training can further speed up training. DDP in PyTorch 2.0+ is fully integrated with AMP.
Example
import
torch
import
torch.
nn
as
nn
import
torch.
optim
as
optim
import
torch.
distributed
as
dist
from
torch.
nn
.
parallel
import
DistributedDataParallel
as
DDP
from
torch.
cuda
.
amp
import
autocast
,
GradScaler
class
AMPModel
(
nn.
Module
)
:
def
init
(
self
)
:
super
(
)
.
init
(
)
self
.
net
=
nn.
Sequential
(
nn.
Conv2d
(
3
,
64
,
3
,
padding
=
1
)
,
nn.
ReLU
(
)
,
nn.
MaxPool2d
(
2
)
,
nn.
Conv2d
(
64
,
128
,
3
,
padding
=
1
)
,
nn.
ReLU
(
)
,
nn.
AdaptiveAvgPool2d
(
1
)
,
nn.
Flatten
(
)
,
nn.
Linear
(
128
,
10
)
)
def
forward
(
self
,
x
)
:
return
self
.
net
(
x
)
def
train_ddp_amp
(
rank
,
world_size
)
:
"""Distributed + mixed-precision training"""
Initialization
torch.
cuda
.
set_device
(
rank
)
dist.
init_process_group
(
"nccl"
,
rank
=
rank
,
world_size
=
world_size
)
Create the model
model
=
AMPModel
(
)
.
cuda
(
rank
)
model
=
DDP
(
model
,
device_ids
=
[
rank
]
)
Optimizer and GradScaler
optimizer
=
optim.
Adam
(
model.
parameters
(
)
,
lr
=
1e-3
)
scaler
=
GradScaler
(
)
criterion
=
nn.
CrossEntropyLoss
(
)
Training loop
model.
train
(
)
for
inputs
,
labels
in
loader:
inputs
=
inputs.
cuda
(
rank
,
non_blocking
=
True
)
labels
=
labels.
cuda
(
rank
,
non_blocking
=
True
)
optimizer.
zero_grad
(
)
Use autocast to switch precision automatically
with
autocast
(
device_type
=
'cuda'
)
:
outputs
=
model
(
inputs
)
loss
=
criterion
(
outputs
,
labels
)
Use the scaler to handle gradient scaling
scaler.
scale
(
loss
)
.
backward
(
)
Gradient clipping (unscale first)
scaler.
unscale_
(
optimizer
)
torch.
nn
.
utils
.
clip_grad_norm_
(
model.
parameters
(
)
,
max_norm
=
1.0
)
scaler.
step
(
optimizer
)
scaler.
update
(
)
dist.
destroy_process_group
(
)
Launch command
torchrun --nproc_per_node=4 train_ddp_amp.py
4.2 Gradient synchronization in distributed training
DDP uses the Ring AllReduce algorithm for gradient synchronization, which works as follows:
- Each GPU splits its gradients into n chunks (n is the number of GPUs)
- Each GPU exchanges one chunk with its neighboring GPUs
- After n rounds, each GPU holds the complete gradients
Example
DDP gradient synchronization settings
1. Set the gradient bucket buffer size
model
=
DDP
(
model
,
device_ids
=
[
rank
]
,
gradient_as_bucket_view
=
True
,
Save GPU memory (PyTorch 1.8+)
broadcast_buffers
=
False
,
Do not broadcast buffers, reducing communication
bucket_cap_mb
=
25
Gradient bucket size (MB)
)
2. Manually synchronize model parameters (if needed)
In some scenarios, model parameters must be synchronized manually
def
sync_params
(
model
)
:
for
param
in
model.
parameters
(
)
:
dist.
broadcast
(
param
,
src
=
0
)
3. Check gradient synchronization status
DDP handles gradient synchronization automatically; no manual action is needed
but you can check it as follows
for
name
,
param
in
model.
named_parameters
(
)
:
if
param.
grad
is
not
None
:
(
f
"{name}: grad requires_grad={param.grad.requires_grad}"
)
5. Model parallelism and pipelining
5.1 Simple model parallelism
When a model is too large to fit on a single GPU, it must be split across multiple GPUs.
Example
Model parallelism example: place different layers on different GPUs
class
ModelParallel
(
nn.
Module
)
:
def
init
(
self
,
num_gpus
=
2
)
:
super
(
)
.
init
(
)
self
.
num_gpus
=
num_gpus
Part 1: GPU 0
self
.
features1
=
nn.
Sequential
(
nn.
Conv2d
(
3
,
64
,
3
,
padding
=
1
)
,
nn.
ReLU
(
)
,
nn.
MaxPool2d
(
2
)
)
.
to
(
f
"cuda:0"
)
Part 2: GPU 1
self
.
features2
=
nn.
Sequential
(
nn.
Conv2d
(
64
,
128
,
3
,
padding
=
1
)
,
nn.
ReLU
(
)
,
nn.
AdaptiveAvgPool2d
(
1
)
,
nn.
Flatten
(
)
)
.
to
(
f
"cuda:1"
)
Classifier: GPU 0
self
.
classifier
=
nn.
Linear
(
128
,
10
)
.
to
(
f
"cuda:0"
)
def
forward
(
self
,
x
)
:
Data is passed between GPUs
x
=
x.
to
(
"cuda:0"
)
x
=
self
.
features1
(
x
)
x
=
x.
to
(
"cuda:1"
)
x
=
self
.
features2
(
x
)
x
=
x.
to
(
"cuda:0"
)
x
=
self
.
classifier
(
x
)
return
x
Use
model
=
ModelParallel
(
num_gpus
=
2
)
output
=
model
(
torch.
randn
(
1
,
3
,
32
,
32
)
)
(
f
"Output device: {output.device}"
)
5.2 Pipeline Parallelism
PyTorch provides the torch.distributed.pipeline.sync module (the PP package) for pipeline parallelism, which splits a model layer by layer into a computation pipeline.
Example
Pipeline parallelism example (requires the torch-pipeline dependency)
pip install torch-pipeline
"""
Note: native PyTorch pipelining requires a specific version or a third-party library
This demonstrates the concept with a simplified implementation
from torch.distributed.pipeline.sync import Pipe
class SimpleModel(nn.Module):
def init(self):
super().init()
self.layer1 = nn.Linear(128, 256)
self.layer2 = nn.Linear(256, 256)
self.layer3 = nn.Linear(256, 10)
def forward(self, x):
x = torch.relu(self.layer1(x))
x = torch.relu(self.layer2(x))
x = self.layer3(x)
return x
Split the model by layers across different GPUs
layer1 -> GPU 0
layer2 -> GPU 1
layer3 -> GPU 2
model = SimpleModel()
model.layer1 = model.layer1.cuda(0)
model.layer2 = model.layer2.cuda(1)
model.layer3 = model.layer3.cuda(2)
Connect the model using Pipeline
Note: real use requires installing the matching version of the pipeline library
from torch.distributed.pipeline.sync import Pipe
model = Pipe(model, chunks=4)
"""
(
"Pipeline parallelism requires installing the torch-pipeline library"
)
(
"pip install torch-pipeline-sync"
)
6. Best practices for distributed training
6.1 Performance optimization tips
| Optimization item | Tip | Description |
|---|---|---|
| Communication optimization | Use the NCCL backend | NCCL is the best choice for GPUs; faster than Gloo |
| Data loading | Set num_workers and pin_memory | Set num_workers to the number of CPU cores; pin_memory speeds up CPU-to-GPU transfers |
| Gradient synchronization | Tune bucket_cap_mb | Larger models can use a bigger bucket; smaller models can reduce it for better responsiveness |
| Mixed precision | DDP + AMP | Reduce communication volume; increase training speed |
6.2 Common problems and solutions
| Problem | Reason | Solution |
|---|---|---|
| Slow communication | Insufficient network bandwidth | Use InfiniBand or a high-speed network |
| Insufficient VRAM | Batch size too large | Reduce the batch size or use gradient accumulation |
| Uneven load | Unreasonable model partition | Adjust the layer distribution to be as even as possible |
| Synchronization errors | NaN gradients | Check gradient clipping and scaling settings |
6.3 Complete multi-machine multi-GPU training script
Example
Complete multi-machine multi-GPU training script template
import
torch
import
torch.
nn
as
nn
import
torch.
optim
as
optim
import
torch.
distributed
as
dist
from
torch.
nn
.
parallel
import
DistributedDataParallel
as
DDP
from
torch.
utils
.
data
import
DataLoader
,
DistributedSampler
import
argparse
import
os
class
TrainingConfig:
def
init
(
self
)
:
self
.
local_rank
=
1
self
.
epochs
=
30
self
.
batch_size
=
32
self
.
lr
=
1e-3
self
.
num_workers
=
4
self
.
gradient_clip
=
1.0
self
.
use_amp
=
True
def
init_distributed
(
config
)
:
"""Initialize the distributed environment"""
Get configuration from environment variables
local_rank
=
config.
local_rank
NCCL configuration
os
.
environ
[
"NCCL_DEBUG"
]
=
"WARN"
torch.
cuda
.
set_device
(
local_rank
)
dist.
init_process_group
(
backend
=
"nccl"
)
return
local_rank
def
create_dataloader
(
dataset
,
config
,
world_size
,
rank
)
:
"""Create the data loader"""
sampler
=
DistributedSampler
(
dataset
,
num_replicas
=
world_size
,
rank
=
rank
,
shuffle
=
True
,
drop_last
=
True
)
loader
=
DataLoader
(
dataset
,
batch_size
=
config.
batch_size
,
sampler
=
sampler
,
num_workers
=
config.
num_workers
,
pin_memory
=
True
,
persistent_workers
=
True
)
return
loader
,
sampler
def
train_epoch
(
model
,
loader
,
criterion
,
optimizer
,
scaler
,
config
,
rank
)
:
"""Train for one epoch"""
model.
train
(
)
total_loss
=
0
correct
=
0
total
=
0
for
inputs
,
labels
in
loader:
inputs
=
inputs.
cuda
(
rank
,
non_blocking
=
True
)
labels
=
labels.
cuda
(
rank
,
non_blocking
=
True
)
optimizer.
zero_grad
(
)
if
config.
use_amp
and
scaler
is
not
None
:
Mixed-precision training
with
torch.
cuda
.
amp
.
autocast
(
)
:
outputs
=
model
(
inputs
)
loss
=
criterion
(
outputs
,
labels
)
scaler.
scale
(
loss
)
.
backward
(
)
scaler.
unscale_
(
optimizer
)
torch.
nn
.
utils
.
clip_grad_norm_
(
model.
parameters
(
)
,
config.
gradient_clip
)
scaler.
step
(
optimizer
)
scaler.
update
(
)
else
:
Regular training
outputs
=
model
(
inputs
)
loss
=
criterion
(
outputs
,
labels
)
loss.
backward
(
)
torch.
nn
.
utils
.
clip_grad_norm_
(
model.
parameters
(
)
,
config.
gradient_clip
)
optimizer.
step
(
)
total_loss +
=
loss.
item
(
)
- inputs.
size
(
0
)
_
,
predicted
=
outputs.
max
(
1
)
correct +
=
predicted.
eq
(
labels
)
.
sum
(
)
.
item
(
)
total +
=
labels.
size
(
0
)
return
total_loss / total
,
correct / total
def
main
(
)
:
parser
=
argparse.
ArgumentParser
(
)
parser
.
add_argument
(
"--local_rank"
,
type
=
int
,
default
=
1
)
args
=
parser
.
parse_args
(
)
config
=
TrainingConfig
(
)
config.
local_rank
=
args.
local_rank
rank
=
init_distributed
(
config
)
world_size
=
dist.
get_world_size
(
)
(
f
"Process {rank}/{world_size} initialized"
)
Create the model
model
=
YourModel
(
)
.
cuda
(
rank
)
model
=
DDP
(
model
,
device_ids
=
[
rank
]
)
Optimizer
optimizer
=
optim.
Adam
(
model.
parameters
(
)
,
lr
=
config.
lr
)
GradScaler (if using mixed precision)
scaler
=
GradScaler
(
)
if
config.
use_amp
else
None
Dataset (replace with your dataset)
dataset
=
YourDataset
(
)
loader
,
sampler
=
create_dataloader
(
dataset
,
config
,
world_size
,
rank
)
criterion
=
nn.
CrossEntropyLoss
(
)
Training loop
for
epoch
in
range
(
config.
epochs
)
:
sampler.
set_epoch
(
epoch
)
loss
,
acc
=
train_epoch
(
model
,
loader
,
criterion
,
optimizer
,
scaler
,
config
,
rank
)
Print only on rank 0
if
rank
==
0
:
(
f
"Epoch {epoch+1}/{config.epochs}: Loss={loss:.4f}, Acc={acc:.4f}"
)
dist.
destroy_process_group
(
)
Launch method:
torchrun --nnodes=2 --nproc_per_node=4 --node_rank=0 --master_addr=192.168.1.1 --master_port=29500 train.py
torchrun --nnodes=2 --nproc_per_node=4 --node_rank=1 --master_addr=192.168.1.1 --master_port=29500 train.py
The keys to distributed training are: 1) choose the right parallelism mode (data parallel vs model parallel); 2) use DDP instead of DataParallel for better performance; 3) combine with mixed-precision training to speed things up further; 4) configure the data loader and communication parameters sensibly.
7. Monitoring and debugging distributed training
7.1 Common monitoring tools
Example
Distributed training monitoring code
def
monitor_training
(
rank
,
world_size
)
:
"""Monitor distributed training status"""
1. Check the process group status
(
f
"Rank: {rank}, World Size: {world_size}"
)
(
f
"Backend: {dist.get_backend()}"
)
(
f
"Rank: {dist.get_rank()}"
)
(
f
"CUDA Device: {torch.cuda.current_device()}"
)
2. Monitor GPU memory usage
if
torch.
cuda
.
is_available
(
)
:
for
i
in
range
(
torch.
cuda
.
device_count
(
)
)
:
allocated
=
torch.
cuda
.
memory_allocated
(
i
)
/
1024
**
2
reserved
=
torch.
cuda
.
memory_reserved
(
i
)
/
1024
**
2
(
f
"GPU {i}: allocated {allocated:.1f} MB, reserved {reserved:.1f} MB"
)
3. Monitor gradient synchronization
DDP automatically records synchronization time
Enable detailed logging by setting environment variables
os.environ["NCCL_DEBUG"] = "INFO"
Call periodically inside the training loop
monitor_training
(
rank
,
dist.
get_world_size
(
)
)
7.2 Debugging tips
- Test on a single machine first, then scale to multiple machines
- Use
os.environ["NCCL_DEBUG"] = "INFO"Check detailed communication logs - Make sure all machines have synchronized clocks (using NTP)
- Check that the firewall allows the NCCL communication ports
Although distributed training adds complexity, the performance gains are significant; for large-model training it is almost an essential technique.