Transformers documentation

FSDP2

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.25.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

FSDP2

Fully Sharded Data Parallel (FSDP2) shards the model, gradients, and optimizer states across GPUs. Before computation, each GPU gathers a complete set of parameters from all shards, then frees them afterward. Sharding lets you train models larger than a single GPU’s memory, at the cost of more communication than DDP. Use FSDP when your model or optimizer states don’t fit on a single GPU.

                      ┌─────────────────┐
                      │  training data  │
                      └────────┬────────┘
            ┌──────────────────┼──────────────────┐
            │ shard 0          │ shard 1          │ shard 2
            ▼                  ▼                  ▼
     ┌─────────────┐    ┌─────────────┐    ┌─────────────┐
     │  param      │    │  param      │    │  param      │
     │  shard 0    │    │  shard 1    │    │  shard 2    │
     │  GPU 0      │    │  GPU 1      │    │  GPU 2      │
     └──────┬──────┘    └──────┬──────┘    └──────┬──────┘
            │                  │                  │
            └──────── all-gather (params) ────────┘
                               │
                    full params on each GPU
                               │
            ┌──────────────────┼──────────────────┐
            ▼                  ▼                  ▼
         forward             forward             forward
            │                  │                  │
            └───── reduce-scatter (grads) ────────┘
                               │
            ┌──────────────────┼──────────────────┐
            ▼                  ▼                  ▼
     grad shard 0       grad shard 1       grad shard 2
     optim shard 0      optim shard 1      optim shard 2
        step               step               step

Transformers supports two ways to train with FSDP2.

  • Shard at load time with DistributedConfig. from_pretrained() applies FSDP2 as the model loads, and Trainer trains the sharded model as is. This path supports HSDP for multi-node training and combines with tensor and expert parallelism.

    Shard at load time if you’re training a mixture-of-experts model with expert parallelism, or want the model’s predefined FSDP plan instead of configuring wrapping yourself. Expert parallelism is only available through DistributedConfig.

  • Shard with Accelerate through ~TrainingArguments.fsdp_config. Trainer loads the full model, and Accelerate wraps it with FSDP2 when training starts.

    Shard with Accelerate if you need to resume training from a checkpoint or use context parallelism. A model sharded at load time can’t save its optimizer state, so you can’t pick up a failed run where it left off. DistributedConfig doesn’t support context parallelism.

Shard at load time

Create a DistributedConfig with the number of GPUs in fsdp_size and pass it to from_pretrained(). Transformers initializes the device mesh and shards the model with its predefined FSDP plan.

from transformers import AutoModelForCausalLM, DistributedConfig, Trainer, TrainingArguments

model = AutoModelForCausalLM.from_pretrained(
    "Qwen/Qwen3-8B",
    distributed_config=DistributedConfig(fsdp_size=4),
)

args = TrainingArguments(
    output_dir="out",
    save_only_model=True,
    ...,
)
trainer = Trainer(model=model, args=args, train_dataset=train_dataset)
trainer.train()

Don’t set fsdp or fsdp_config in TrainingArguments. Transformers already sharded the model and handles its gradient reduction, so Trainer skips the Accelerate FSDP wrap. Set save_only_model=True or save_strategy="no". Otherwise, Trainer raises an error when you create it, because a model sharded at load time can’t save its optimizer state.

Launch the script with torchrun, one process per GPU.

torchrun --nproc-per-node 4 train.py

These DistributedConfig fields control FSDP2.

  • fsdp_size is the number of GPUs that shard the parameters, gradients, and optimizer states.

  • fsdp_plan is a dictionary that maps module names to one of two values. Leave it as None to use the model’s predefined plan, or pass a dictionary to override individual modules.

    valuebehavior
    "free_full_weight"reshard the parameters after the forward pass and gather them again for the backward pass to save memory
    "keep_full_weight"keep the parameters gathered between the forward and backward passes to skip the second all-gather, at the cost of higher peak memory

    The predefined plan for a causal LM with untied embeddings, like Llama 3 8B, looks like this. If the input embeddings and lm_head share weights, the plan keeps model.embed_tokens gathered instead and drops the lm_head entry.

    {
        "model.embed_tokens": "free_full_weight",
        "model.layers.*": "free_full_weight",
        "model.norm": "keep_full_weight",
        "lm_head": "keep_full_weight",
    }

    The final norm and lm_head run last in the forward pass and first in the backward pass. Resharding them would only force a second all-gather right away, so the plan keeps them gathered.

  • fsdp_cpu_offload offloads parameters and gradients to CPU when they aren’t in use.

  • fsdp_mixed_precision gathers parameters in bfloat16 for compute and reduces gradients in float32.

save_pretrained() gathers the full weights on rank 0 by default and writes a regular checkpoint. Call it on every rank. Saving a sharded model requires torch>=2.8. Pass distributed_checkpoint=True to have each rank write its own shard with distributed checkpointing (DCP) instead. DCP is faster for large models, but it’s meant for saving and resuming training rather than sharing the model.

For mixture-of-experts models, combine fsdp_size with tp_size and ep_size to shard the experts across one mesh dimension and everything else across the other. See expert parallelism.

Multi-node training with HSDP

Plain FSDP all-gathers parameters and reduce-scatters gradients across every GPU at every step. Across nodes, that traffic runs over the slower inter-node network. Hybrid Sharded Data Parallel (HSDP) shards the model within each node and replicates it across nodes. In other words, HSDP runs FSDP inside a node and DDP between nodes. All-gathers and reduce-scatters stay on the fast intra-node links, and only a gradient all-reduce crosses the network.

             node 0                               node 1
  ┌──────────────────────────┐        ┌──────────────────────────┐
  │  GPU 0          GPU 1    │        │  GPU 2          GPU 3    │
  │  shard 0        shard 1  │        │  shard 0        shard 1  │
  │    └── all-gather ──┘    │        │    └── all-gather ──┘    │
  │    └ reduce-scatter ┘    │        │    └ reduce-scatter ┘    │
  └────────────┬─────────────┘        └────────────┬─────────────┘
               └────────── all-reduce (grads) ─────┘

Set dp_replicate_size to the number of nodes and fsdp_size to the number of GPUs per node. HSDP uses more memory per GPU than plain FSDP because each GPU splits the parameters only with the other GPUs in its node.

import os
from transformers import AutoModelForCausalLM, DistributedConfig

local_gpus = int(os.environ["LOCAL_WORLD_SIZE"])
num_nodes = int(os.environ["WORLD_SIZE"]) // local_gpus

model = AutoModelForCausalLM.from_pretrained(
    "Qwen/Qwen3-8B",
    distributed_config=DistributedConfig(fsdp_size=local_gpus, dp_replicate_size=num_nodes),
)

Set gradient_accumulation_steps above 1 in TrainingArguments. Trainer reduce-scatters gradients within each node after every micro-batch, but waits to all-reduce across nodes until the last micro-batch of each step. The network traffic per optimizer step stays the same as you add micro-batches.

Launch one torchrun per node, and set $MASTER_ADDR to the hostname or IP address of node 0 on every node.

# node 0
torchrun --nnodes 2 --nproc-per-node 2 --node-rank 0 --master-addr $MASTER_ADDR --master-port 29500 train.py
# node 1
torchrun --nnodes 2 --nproc-per-node 2 --node-rank 1 --master-addr $MASTER_ADDR --master-port 29500 train.py

Shard with Accelerate

Trainer loads the full model, then Accelerate wraps it with FSDP2 when training starts.

Choose a resharding strategy

~TrainingArguments.fsdp_config controls how FSDP2 shards the model. Set fsdp=True to enable FSDP, and set reshard_after_forward in the FSDP config to choose the memory and throughput tradeoff.

reshard_after_forwardbehavior
truereshard parameters after the forward pass to save more memory
falsekeep parameters gathered between forward and backward to avoid the re-all-gather, at the cost of higher peak memory

auto_wrap_policy controls how FSDP wraps modules into FSDP units. It defaults to "TRANSFORMER_BASED_WRAP", which wraps the model’s transformer layers. Without wrapping ("NO_WRAP"), the entire model is one FSDP unit and you lose the memory benefit of sharding.

Configure wrapping, offloading, and checkpoints

These fields control how FSDP2 wraps, shards, and loads the model. Choose a resharding strategy covers reshard_after_forward and auto_wrap_policy.

  • cpu_offload offloads parameters and gradients to CPU when they aren’t in use to save GPU memory.

  • transformer_layer_cls_to_wrap defines the transformer layer to wrap into an FSDP unit when auto_wrap_policy is "TRANSFORMER_BASED_WRAP". Each unit manages its own gather and scatter ops. During the forward pass, FSDP gathers only the current unit’s parameters and releases the previous units’ parameters to save memory.

    Wrapping only the top-level model saves no GPU memory. Wrapping every individual Linear layer adds so many units that communication between them dominates training time. Leave this field empty and FSDP reads the value from the model definition.

  • min_num_params sets the minimum number of parameters per module for size-based wrapping. FSDP only uses it when auto_wrap_policy is "SIZE_BASED_WRAP".

  • state_dict_type controls the checkpoint format. It defaults to "FULL_STATE_DICT" for a single Transformers-compatible checkpoint. Use "SHARDED_STATE_DICT" for one checkpoint file per rank, which is faster for large models. Sharded checkpoints only load back into FSDP, so save a "FULL_STATE_DICT" for the final checkpoint you want to share or load outside FSDP.

  • cpu_ram_efficient_loading loads the checkpoint from disk on rank 0 only. Other GPUs initialize an empty model and receive the weights by broadcast, so only one process loads the model into CPU RAM.

  • activation_checkpointing recomputes activations during the backward pass instead of storing them. Use this instead of gradient checkpointing in TrainingArguments. Setting both raises an error.

Configure FSDP training with either an Accelerate config file or an FSDP config file passed to fsdp_config.

Accelerate config file
FSDP config file

Run the accelerate config command and answer questions about your hardware and training setup. This creates a default_config.yaml file in your cache.

Run accelerate launch with a Trainer-based script. The fsdp_config is unnecessary because the Accelerate config file covers the same settings.

accelerate launch train.py

Evaluate with context parallelism

Set context parallelism (CP) with FSDP2 through the cp_size field of Accelerate’s ParallelismConfig. At launch, pass both --use_parallelism_config and --parallelism_config_cp_size. A non-empty parallelism_config in the Accelerate YAML also turns use_parallelism_config on. If you pass only --parallelism_config_cp_size, Accelerate ignores it and cp_size stays 1.

Under FSDP2, CP shards the sequence across ranks so each GPU holds a slice of the context (allgather or alltoall). That differs from Ulysses sequence parallelism, which runs through DeepSpeed ALST and uses sp_size on the same config. Pick CP or Ulysses SP. Don’t set both cp_size and sp_size above 1.

evaluate() uses the same context-parallel context as train() through prediction_step(). Each rank runs its sequence shard while that context is active. eval_loss is the correct loss (not multiplied by cp_size). Early stopping and load_best_model_at_end use that metric.

Logits stay sharded along the sequence, and nothing reassembles them into full-length predictions. Predictions and compute_metrics over logits aren’t supported under CP.

Reuse your existing FSDP2 launch with cp_size when you need eval_loss.

If you subclass prediction_step() and count tokens yourself, count num_items_in_batch before entering the context-parallel context. While that context is active, it shards the sequence buffers in place across ranks. Counting afterward undercounts the batch. The default Trainer already counts first, and you only need this if you override prediction_step.

Next steps

  • See DDP for data-parallel training when your model fits on one GPU.
  • See DeepSpeed for ZeRO optimization and NVMe offloading.
  • See Multi-node training in the Hub docs to run HSDP across several Hugging Face Jobs.
  • For FSDP on TPUs with PyTorch/XLA, set xla, xla_fsdp_settings, and xla_fsdp_grad_ckpt in ~TrainingArguments.fsdp_config.
  • Read the FSDP chapter from The Ultra-Scale Playbook for more information about how FSDP works.
Update on GitHub