A data-parallel training job can divide model weights among workers to reduce how much each process keeps in memory between computations. On a single CPU host, PyTorch FSDP2 can use Gloo to run a training step across two processes and save the updated weights as a sharded checkpoint.

FSDP2 gathers the weights when the layer needs them and distributes the reduced gradients back to the workers during backpropagation. Each worker then applies the optimizer update to its own shard.

A small linear layer makes the split easy to see. Each process holds two rows of a four-row weight matrix outside computation, and the distributed checkpoint keeps those slices in separate files with shared metadata.

The two workers need PyTorch 2.15 with Gloo support and NumPy in the same Python environment. Distributed Checkpoint uses NumPy for the exchange of save plans on this CPU path.
Related: How to install PyTorch with pip

The run requires a trusted Linux host where untrusted clients cannot reach inbound TCP ports. PyTorch's TCPStore can listen on all host interfaces during the run, even with a localhost rendezvous address.

Steps to run FSDP2 training on CPU in PyTorch:

  1. Create train_fsdp2.py with the Gloo process group and a one-dimensional CPU mesh.
    train_fsdp2.py
    import torch
    import torch.distributed as dist
    import torch.distributed.checkpoint as dcp
    from torch.distributed.device_mesh import init_device_mesh
    from torch.distributed.fsdp import fully_shard
    from torch.distributed.tensor import DTensor, Shard
     
     
    dist.init_process_group("gloo")
    rank = dist.get_rank()
    mesh = init_device_mesh("cpu", (dist.get_world_size(),))
  2. Append the FSDP2 layer and local shard check to train_fsdp2.py.
    try:
        torch.manual_seed(42)
        model = fully_shard(torch.nn.Linear(4, 4), mesh=mesh)
        weight = model.weight
        assert isinstance(weight, DTensor)
        assert weight.placements == (Shard(0),)
        before = weight.to_local().detach().clone()
        assert before.shape == (2, 4)
        kind = type(weight).__name__
        placement = weight.placements[0]
        print(f"rank {rank}: {kind} {placement!r}, "
              f"local {tuple(before.shape)}", flush=True)

    The common seed gives both processes the same initial weights before sharding. Shard(0) splits the rows of the weight matrix across the CPU mesh, and to_local() exposes the slice owned by the current rank.

  3. Append the optimizer step inside the try block in train_fsdp2.py.
        optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
        batch = torch.full((2, 4), float(rank + 1))
        loss = model(batch).square().mean()
        loss.backward()
        optimizer.step()
        assert not torch.equal(before, model.weight.to_local())
        print(f"rank {rank}: SGD changed local weights", flush=True)

    The optimizer is built after fully_shard() so it receives the sharded parameters. Each rank uses a different input batch and reports its update only after its local weights differ from the saved copy.

  4. Append the distributed checkpoint save to train_fsdp2.py.
        writer = dcp.FileSystemWriter("checkpoint", overwrite=False)
        state = {"model": model.state_dict()}
        dcp.save(state, storage_writer=writer)
        print(f"rank {rank}: saved checkpoint", flush=True)
    finally:
        dist.destroy_process_group()

    Both ranks must call dcp.save() because the save is collective. The save contains model state only, and the finally block closes the process group on each rank.

    The checkpoint path in the launch directory must be unused. overwrite=False refuses to save over a checkpoint with .metadata. A partial save may leave shard files without that metadata, and a later save can replace those files. If checkpoint already exists, use a fresh directory containing train_fsdp2.py.

  5. Save train_fsdp2.py in your text editor.
  6. Launch two local workers with torchrun from the directory containing train_fsdp2.py.
    $ OMP_NUM_THREADS=1 GLOO_SOCKET_IFNAME=lo torchrun \
        --standalone --local-addr=127.0.0.1 \
        --nproc-per-node=2 train_fsdp2.py
    rank 0: DTensor Shard(dim=0), local (2, 4)
    rank 1: DTensor Shard(dim=0), local (2, 4)
    rank 0: SGD changed local weights
    rank 1: SGD changed local weights
    rank 0: saved checkpoint
    rank 1: saved checkpoint

    GLOO_SOCKET_IFNAME=lo keeps Gloo connections on the Linux loopback interface. --standalone sets up a local rendezvous on a free port, and --local-addr=127.0.0.1 gives the workers a loopback address for their store connection. OMP_NUM_THREADS=1 limits each worker to one OpenMP thread. Each rank should report a local 2 × 4 shard, a weight update, and a completed save. The rank lines may appear in either order.
    Related: How to launch a PyTorch script with torchrun

  7. Confirm that checkpoint contains the metadata and a shard file from each rank.
    $ ls -1A checkpoint
    .metadata
    __0_0.distcp
    __1_0.distcp

    The -A option includes the hidden .metadata file. The metadata and both .distcp files belong to the same checkpoint and must stay together.

Share this guide