Below is a concise comparison of the two calls — init_process_group and init_device_mesh — and when you’d reach for one versus the other:
| Aspect | init_process_group | init_device_mesh |
|---|
| Module | torch.distributed | torch.distributed._spmd.mesh_utils (or torch.distributed.mesh) |
| Purpose | Bootstraps the communication layer across processes. | Defines a logical mesh of devices on top of an existing PG. |
| When to use | Any time you want NCCL/Gloo/MPI-based collective ops: broadcast, all‐reduce, etc. | When you’re doing DTensor/SPMD‐style distributed tensor parallelism and need a named device‐mesh. |
| What it sets up | - World size & rank - Backend (NCCL/Gloo/MPI) - Low‐level PG handles | - A mapping from mesh‐axes ↔ device IDs - Thin wrapper around one or more process groups |
| Returns | A ProcessGroup object (or uses the default PG) | None (it registers the mesh globally under a string name) |
| Dependencies | None (just needs environment variables or explicit args) | Assumes you already called init_process_group (or have a PG) |
1) init_process_group
This is the classic “start distributed PyTorch” call. It:
- Negotiates ranks & world size (via env vars or parameters you pass).
- Instantiates a backend (nccl/gloo/mpi).
- Gives you a
ProcessGroup handle for collective operations:
import os
import torch
import torch.distributed as dist
os.environ.update({
"MASTER_ADDR": "127.0.0.1",
"MASTER_PORT": "29500",
"RANK": "0",
"WORLD_SIZE": "2"
})
dist.init_process_group(backend="nccl")
# now dist.get_world_size(), dist.get_rank(), collective calls all‐reduce, all‐gather, …
2) init_device_mesh
Once you have a PG up, you can build higher-level SPMD/DTensor logic on top of it. A device mesh is simply:
- A named collection of devices (CUDA or CPU)
- A shape (e.g. a 2×2 mesh of 4 GPUs)
- Optionally tied to one or more PGs for implementing collectives along each mesh axis
import torch
import torch.distributed as dist
from torch.distributed._spmd.mesh_utils import init_device_mesh
# 1) start low-level PG
dist.init_process_group(backend="nccl", rank=rank, world_size=world_size)
# 2) build a 2×2 CUDA mesh (here 4 GPUs total)
devices = [torch.device(f"cuda:{i}") for i in range(4)]
# mesh_shape is implicitly inferred here as [2, 2]
init_device_mesh(name="cuda_mesh", device_ids=devices, process_group=dist.group.WORLD)
# Now you can create DTensors or use SPMD transforms that target "cuda_mesh"
When to call which?
- If you only need point-to-point or collective ops (all-reduce, barrier, broadcast), call init_process_group and go.
- If you want to leverage the new DTensor/SPMD APIs (auto-sharding, tensor-parallel layouts, reshapes across axes), you first call init_process_group and then call init_device_mesh to describe your physical topology.
❓ Feel free to ask if you’d like a deeper dive on DTensor‐centric SPMD examples, or if you’re curious how those meshes get used in e.g. nn.Linear(...).to_batch_parallel(…)!