Skip to main content

When the model does not fit one GPU

Author

Marie-Hélène Burle

DDP replicates: every GPU holds the whole model, so per-GPU memory is whatever one GPU would need. When that is too much — the arithmetic says a 7-billion-parameter model wants about 104 GiB for weights, gradients, and optimizer state before a single activation — replication is the wrong strategy. Fully sharded data parallel (FSDP) splits the training state across GPUs, and each GPU stores only its fraction.

Sharding the training state

PyTorch 2.13 ships FSDP’s second generation, built on one call, fully_shard:

flowchart TB
    classDef default color:#0081c2, stroke:#0081c2;
    subgraph G0 [GPU 0]
        S0[stores shard 0 of every parameter] --> A
        A([all-gather: this layer's parameters, in full]) --> C0[forward + backward]
        C0 --> R([reduce-scatter: each GPU keeps<br>its shard of the gradients])
        R --> O0[optimizer updates<br>the local shards only]
    end
    subgraph G1 [GPU 1]
        S1[stores shard 1 of every parameter] --> A
        C1[forward + backward] --> R
        R --> O1[optimizer updates<br>the local shards only]
    end

  • Parameters live as shards, distributed across the GPUs, between steps.
  • Just before a layer computes, its parameters are gathered in full across the GPUs (an all-gather), used, then released back to shards.
  • After the backward pass, gradients are summed and each GPU keeps only its shard (a reduce-scatter).
  • Optimizer state is created per shard, so it is sharded too: momentum and second moments never exist in full anywhere.

The 104 GiB of our 7-billion-parameter example spread over 8 GPUs becomes about 13 GiB per GPU: training-state memory divides by the number of GPUs. What does not divide is the activations of the current microbatch (each GPU computes its own data shard) — activation checkpointing is the companion lever when those become the obstacle.

Example

Our course CNN trains comfortably on one GPU, so sharding it would be artificial. The following script demonstrates the mechanics on a synthetic model instead, and it runs on plain CPUs (the sharding logic does not need GPUs):

fsdp_demo.py
"""A minimal FSDP2 demonstration: shard a model, take a step, save sharded.

FSDP matters when a model does not fit on one GPU. Our course CNN does fit,
so this demo uses a synthetic model to show the mechanics -- the sharding of
parameters, the sharded optimizer state, and a distributed checkpoint --
without any training time. Run it on CPUs, no GPU required:

    torchrun --nproc-per-node 2 fsdp_demo.py
"""

import os

import torch
import torch.distributed as dist
from torch import nn
from torch.distributed.checkpoint import FileSystemWriter, save
from torch.distributed.checkpoint.state_dict import get_model_state_dict
from torch.distributed.device_mesh import init_device_mesh
from torch.distributed.fsdp import fully_shard


class Block(nn.Module):
    def __init__(self, width):
        super().__init__()
        self.fc = nn.Linear(width, width)
        self.act = nn.ReLU()

    def forward(self, x):
        return self.act(self.fc(x))


class Big(nn.Module):
    """Stand-in for a model too large for one GPU."""

    def __init__(self, width=1024, depth=8):
        super().__init__()
        self.blocks = nn.ModuleList([Block(width) for _ in range(depth)])
        self.head = nn.Linear(width, 10)

    def forward(self, x):
        for block in self.blocks:
            x = block(x)
        return self.head(x)


def main():
    dist.init_process_group(backend="gloo")  # nccl on GPUs
    rank, world_size = int(os.environ["RANK"]), int(os.environ["WORLD_SIZE"])
    mesh = init_device_mesh("cpu", (world_size,))
    is_main = rank == 0

    torch.manual_seed(0)  # identical model on every rank before sharding
    model = Big()
    n_full = sum(p.numel() for p in model.parameters())
    if is_main:
        print(f"model created: {n_full:,} parameters")

    # --- shard it: children first, root last --------------------------------
    for block in model.blocks:
        fully_shard(block, mesh=mesh)
    fully_shard(model.head, mesh=mesh)
    fully_shard(model, mesh=mesh)

    # parameters are now DTensors: global view from here, shard on disk
    n_local = sum(p.to_local().numel() for p in model.parameters())
    if is_main:
        print(f"parameters visible per rank after sharding: "
              f"{n_full:,} (global shape)")
        print(f"parameters actually stored per rank: "
              f"{n_local:,} (~1/{round(n_full / n_local)} of the model)")

    optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)

    # --- one sharded training step ------------------------------------------
    x = torch.randn(8, 1024)
    y = torch.randint(0, 10, (8,))
    loss = nn.functional.cross_entropy(model(x), y)
    loss.backward()
    optimizer.step()
    dist.barrier()
    if is_main:
        print(f"one sharded step OK, loss {loss.item():.3f}")

    # --- a distributed checkpoint: each rank writes its own shards ----------
    state = {"model": get_model_state_dict(model)}
    save(state, storage_writer=FileSystemWriter("fsdp_ckpt"))
    dist.barrier()
    if is_main:
        print("distributed checkpoint written to fsdp_ckpt/")

    dist.destroy_process_group()


if __name__ == "__main__":
    main()

Here are the key points in that script:

mesh = init_device_mesh("cpu", (world_size,))  # "cuda" and NCCL in production

for block in model.blocks:   # shard the children first...
    fully_shard(block, mesh=mesh)
fully_shard(model.head, mesh=mesh)
fully_shard(model, mesh=mesh)   # ...the root last

The order matters: sharding the root module first would freeze its view of unsharded children. After this loop, the model’s parameters are DTensors: tensors with a global shape and local storage. Code that reads p.shape still sees the global tensor; p.to_local() exposes the shard this rank actually holds.

You can run the script quickly from the command line on 2 CPUs with:

$ torchrun --nproc-per-node 2 fsdp_demo.py
model created: 8,407,050 parameters
parameters visible per rank after sharding: 8,407,050 (global shape)
parameters actually stored per rank: 4,203,525 (~1/2 of the model)
one sharded step OK, loss 2.308
distributed checkpoint written to fsdp_ckpt/

Half the parameters stored per rank, as promised. The rest of the demo takes one training step, and the code for it is exactly the single-GPU code — loss, backward(), optimizer.step() — because the gathering and scattering happen inside the sharded modules. FSDP’s whole point is that the training loop does not know about the sharding.

Distributed checkpoints

torch.save(model.state_dict()) would silently save each rank’s local view of the DTensors, incomplete on its own. Distributed checkpoints (DCP) handle sharded state: every rank writes its own shards, and a load can even re-shard into a different world size (resume your 8-GPU training on 4):

state = {"model": get_model_state_dict(model)}
save(state, storage_writer=FileSystemWriter("fsdp_ckpt"))

The fsdp_ckpt/ directory of the demo holds one .distcp file per rank. For long training runs, DCP also has an asynchronous variant that saves on a background thread, so checkpoints do not stall the training loop.

From DDP to FSDP

Nothing from the DDP section is discarded; four things change:

  1. Replace the DDP(model, ...) wrap with the fully_shard calls (children first, root last). Do not use both on one model.
  2. If the GPUs are recent (Ampere and later), add a mixed-precision policy so gathered parameters compute in bf16: fully_shard(..., mp_policy=MixedPrecisionPolicy(param_dtype=torch.bfloat16)) — the same hardware gate as our autocast decisions, one level down.
  3. Replace torch.save checkpoints with DCP, and load with dcp.load + set_model_state_dict.
  4. Keep everything else: torchrun, the DistributedSampler, rank-0-only printing, the all-reduced metrics.

When does FSDP beat DDP? Only when the model does not fit. The sharded flow gathers and scatters parameters at every layer of every step, which is more communication than DDP’s one gradient all-reduce — so FSDP is slower than DDP on a model that fits on one GPU. The two levers answer different questions: DDP buys speed, FSDP buys capacity.

The wider map

Data parallelism (DDP, FSDP) is one axis of a small map. Tensor parallelism splits individual matrix multiplications across GPUs; pipeline parallelism splits the layers into stages; context parallelism shards very long input sequences. At transformer scale they are combined; torchtitan is PyTorch’s reference implementation of such recipes, and a good place to see FSDP2 used in earnest. For research training up to a few billion parameters, what this page covers is the standard answer.

Your turn:

Run the demonstrator with 4 ranks (torchrun --nproc-per-node 4 fsdp_demo.py). Predict the two parameter counts and the number of files in fsdp_ckpt/ before you run it. Then break it on purpose: shard the root module first and try again.

  • Hint: fully_shard re-shards what it is given; a root sharded before its children sees modules it can no longer wrap.