Lesson 2 of 2 Training Pipelines and Distributed Training

Distributed Training for Large Models

This lesson explains when training is distributed, how distributed jobs are configured, which environment variables the platform sets, and which hardware makes multi-node training efficient.

Learning outcomes

After completing this lesson, you will be able to:

  • Distinguish data parallelism from model and sharded parallelism.
  • Describe instance_count, distribution and process_count_per_instance.
  • Identify the environment variables set for PyTorch.
  • Explain why InfiniBand sizes speed up multi-node training.

Why distribute training

Distributed training spreads one training run across several GPUs, on one node or many. It solves two different problems. When a model fits in one GPU's memory but training is too slow, more GPUs process more data at the same time. When a model is too large for one GPU, its parameters, gradients and optimizer state must be split across GPUs.

Data parallelism
What is splitThe data: each GPU holds a full model copy and trains on a different slice of each batch
SolvesTraining is too slow
ExamplesPyTorch DistributedDataParallel (DDP), Horovod
Choose when The model fits on one GPU
Model or sharded parallelism
What is splitThe model state: each GPU holds part of the parameters, gradients or optimizer state
SolvesThe model does not fit in one GPU's memory
ExamplesDeepSpeed ZeRO, PyTorch Fully Sharded Data Parallel (FSDP), tensor and pipeline parallelism
Choose when It does not

Microsoft notes that more than 90 percent of the time, data parallelism is the right approach. Sharded methods add complexity and communication, and are needed only when memory is the limit.

Configuring a distributed job

A command job becomes distributed with two settings: resources.instance_count, the number of nodes, and distribution, which says how processes are launched on them.

$schema: https://azuremlschemas.azureedge.net/latest/commandJob.schema.json
code: ./src
command: python train.py --epochs 10 --data ${{inputs.images}} --output ${{outputs.model}}
environment: azureml:pytorch-gpu-env:3
compute: azureml:gpu-cluster
resources:
  instance_count: 2
distribution:
  type: pytorch
  process_count_per_instance: 4
inputs:
  images:
    type: uri_folder
    path: azureml:product-images:1
outputs:
  model:
    type: uri_folder

This job runs on two nodes with four GPUs each, launching eight processes in total. process_count_per_instance should equal the number of GPUs per node; if it is omitted, only one process runs on each node and the other GPUs sit idle.

Distribution types and environment variables

Azure Machine Learning supports three distribution types and sets the environment variables that each framework expects, so the script does not have to discover the cluster itself.

TypeSettingsUsed for
pytorchprocess_count_per_instancePyTorch DDP, FSDP, DeepSpeed and Hugging Face Accelerate launched with torch distributed
mpiprocess_count_per_instanceHorovod, and DeepSpeed launched through MPI
tensorflowworker_count, parameter_server_countTensorFlow distribution strategies; sets TF_CONFIG

For PyTorch, the variables include MASTER_ADDR and MASTER_PORT (where process 0 listens), WORLD_SIZE (total processes), RANK (this process's global index), LOCAL_RANK (its index on the node) and NODE_RANK. The script calls torch.distributed.init_process_group(backend="nccl"), which reads them, wraps the model in DistributedDataParallel, and uses a DistributedSampler so each process sees a different slice of the data.

import os, torch, torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP

dist.init_process_group(backend="nccl")
local_rank = int(os.environ["LOCAL_RANK"])
torch.cuda.set_device(local_rank)
model = DDP(build_model().cuda(local_rank), device_ids=[local_rank])
# ... training loop with a DistributedSampler ...
if dist.get_rank() == 0:
    torch.save(model.module.state_dict(), os.path.join(args.output, "model.pt"))

Hardware and efficiency

Distributed training spends time synchronizing gradients between processes, and between nodes that traffic crosses the network. GPUs on one node communicate fastest, so using all GPUs of a node before adding nodes is efficient. For multi-node jobs, VM sizes with InfiniBand, indicated by an r in the size name, such as Standard_NC24rs_v3 or ND-series sizes, give the low-latency, high-bandwidth interconnect that makes scaling across nodes worthwhile.

  • Checkpoint regularly to an output, saved by rank 0, so a failed or evicted job resumes rather than restarts.
  • Mixed precision (16-bit floating point) reduces memory and speeds up computation on modern GPUs.
  • Gradient accumulation simulates a larger batch when memory limits the per-GPU batch size.
  • Data loading must keep up with GPUs: use download mode or local caching for data read every epoch, and enough data loader workers.
  • Use curated GPU environments such as the Azure Container for PyTorch (ACPT) images, which include tested CUDA, NCCL and DeepSpeed versions.
Worked example

Idle GPUs

A distributed PyTorch job runs on a cluster of two Standard_NC24rs_v3 nodes, each with four GPUs. Monitoring shows that only one GPU on each node is busy and training is barely faster than on one node. The job sets instance_count: 2 and distribution: {type: pytorch}.

Without process_count_per_instance, the PyTorch distribution launches one process per node, so each node uses one GPU. Set process_count_per_instance: 4, the number of GPUs per node, so the job launches eight processes, and make sure the script uses LOCAL_RANK to place each process on its own GPU.

Adding more nodes would add more single-GPU processes and more network traffic. Switching to the MPI distribution type would not help without the same per-instance process count. A larger VM size would add GPUs that would also sit idle.

Check yourself

A PyTorch job runs on two nodes with four GPUs each. What should process_count_per_instance be?

Show answer

4, one process per GPU on each node, with instance_count: 2, giving a world size of 8.

Exam Tips

Remember for the exam

  • Data parallelism for speed; sharded or model parallelism when the model does not fit in GPU memory.
  • Set instance_count and distribution; process_count_per_instance equals GPUs per node.
  • Azure Machine Learning sets MASTER_ADDR, WORLD_SIZE, RANK and LOCAL_RANK for PyTorch.
  • InfiniBand sizes (an r in the name) speed up multi-node training; checkpoint from rank 0.