FSDP (Fully Sharded Data Parallel) Setup for Training

We design and deploy artificial intelligence systems: from prototype to production-ready solutions. Our team combines expertise in machine learning, data engineering and MLOps to make AI work not in the lab, but in real business.
Showing 1 of 1All 1566 services
FSDP (Fully Sharded Data Parallel) Setup for Training
Complex
~3-5 days
Frequently Asked Questions

AI Development Areas

AI Solution Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1320
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1226
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    927
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1161
  • image_logo-advance_0.webp
    B2B Advance company logo design
    622
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    897

Model LLaMA-2 70B does not fit into A100 80GB memory when using DDP. FSDP solves this by sharding parameters, gradients, and optimizer states across GPUs. We configure FSDP turnkey—the native fully sharded data parallelism implementation in PyTorch that saves up to 70% memory without losing speed. Certified engineers with many years of experience in distributed training. Over the course of our work, we have completed more than 50 projects for models ranging from 1B to 70B parameters. Our clients save up to 40% on cloud GPU budgets thanks to optimal configuration.

PyTorch FSDP documentation

Why FSDP over DeepSpeed?

FSDP is part of PyTorch core and requires no external dependencies. Unlike DeepSpeed ZeRO-3, integration with Hugging Face Transformers and Accelerate goes through native APIs. We use FSDP in every second project for fine-tuning large models—from LLaMA to Mistral. PyTorch FSDP documentation

How FSDP works

Principle of operation

During forward pass: parameters of each sharded layer are gathered (all-gather) from all GPUs before computation. After forward—immediately freed if reshard_after_forward is enabled. During backward pass: parameters are gathered again, gradients computed, then reduce-scatter distributes gradient shards across GPUs. This eliminates the situation where each GPU stores a full copy of the model, as in regular DDP.

Basic setup

import torch
import torch.distributed as dist
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
from torch.distributed.fsdp.fully_sharded_data_parallel import (
    CPUOffload,
    BackwardPrefetch,
)
from torch.distributed.fsdp.wrap import (
    size_based_auto_wrap_policy,
    enable_wrap,
    wrap,
)
import functools

def setup_fsdp(rank, world_size):
    dist.init_process_group("nccl", rank=rank, world_size=world_size)
    torch.cuda.set_device(rank)

def wrap_model_with_fsdp(model, rank):
    auto_wrap_policy = functools.partial(
        size_based_auto_wrap_policy,
        min_num_params=100_000_000
    )

    model = FSDP(
        model,
        auto_wrap_policy=auto_wrap_policy,
        cpu_offload=CPUOffload(offload_params=False),
        backward_prefetch=BackwardPrefetch.BACKWARD_PRE,
        device_id=torch.cuda.current_device(),
        sharding_strategy=ShardingStrategy.FULL_SHARD,
        mixed_precision=MixedPrecision(
            param_dtype=torch.bfloat16,
            reduce_dtype=torch.float32,
            buffer_dtype=torch.bfloat16,
        ),
    )
    return model

How to choose a sharding strategy

from torch.distributed.fsdp import ShardingStrategy

# FULL_SHARD — full sharding (analogous to ZeRO-3)
strategy = ShardingStrategy.FULL_SHARD
# SHARD_GRAD_OP — shard only gradients and optimizer (ZeRO-2)
strategy = ShardingStrategy.SHARD_GRAD_OP
# NO_SHARD — regular DDP
strategy = ShardingStrategy.NO_SHARD
# HYBRID_SHARD — FULL_SHARD within node, replication between nodes
strategy = ShardingStrategy.HYBRID_SHARD

The choice of strategy depends on model size, number of GPUs, and interconnect speed. For 8 GPUs with NVLink, FULL_SHARD is optimal; for multi-node, HYBRID_SHARD.

Sharding strategies: memory vs. speed comparison

Strategy Memory savings Communication overhead Typical scenario
FULL_SHARD Up to 75% High Single node with fast interconnect
SHARD_GRAD_OP Up to 50% Medium Medium-sized models
HYBRID_SHARD ~60% Low Multi-node clusters
NO_SHARD 0% Low Baseline DDP

How to configure FSDP: step-by-step instructions

  1. Determine cluster topology: number of GPUs, nodes, interconnect type (NVLink, InfiniBand).
  2. Choose sharding strategy: FULL_SHARD for a single node with NVLink, HYBRID_SHARD for multi-node.
  3. Configure mixed precision: use bfloat16 for parameters, float32 for reductions.
  4. Override wrap policy: for transformers, use transformer_auto_wrap_policy with the layer class specified.
  5. Optimize checkpointing: enable offload_to_cpu when saving full state dict.
  6. Profile performance: measure throughput, GPU utilization, and p99 latency.
When to use HYBRID_SHARD? HYBRID_SHARD combines FULL_SHARD within a node and replication between nodes. This reduces inter-node traffic, critical for slow interconnects (Ethernet). Suitable for clusters of 2+ nodes with InfiniBand or RoCE.

Practical configuration aspects

Wrap policy for transformers

For transformers, it is important to wrap each Transformer block individually:

from torch.distributed.fsdp.wrap import transformer_auto_wrap_policy
from transformers.models.llama.modeling_llama import LlamaDecoderLayer

llama_auto_wrap_policy = functools.partial(
    transformer_auto_wrap_policy,
    transformer_layer_cls={LlamaDecoderLayer},
)
model = FSDP(model, auto_wrap_policy=llama_auto_wrap_policy)

Saving and loading checkpoints

from torch.distributed.fsdp import FullStateDictConfig, StateDictType

save_policy = FullStateDictConfig(offload_to_cpu=True, rank0_only=True)
with FSDP.state_dict_type(model, StateDictType.FULL_STATE_DICT, save_policy):
    cpu_state = model.state_dict()
    if rank == 0:
        torch.save(cpu_state, "checkpoint.pt")

if rank == 0:
    state_dict = torch.load("checkpoint.pt")
else:
    state_dict = {}
with FSDP.state_dict_type(model, StateDictType.FULL_STATE_DICT, save_policy):
    model.load_state_dict(state_dict)

Integration with Hugging Face Accelerate

from accelerate import Accelerator
from accelerate.utils import FullyShardedDataParallelPlugin
from torch.distributed.fsdp.fully_sharded_data_parallel import FullOptimStateDictConfig, FullStateDictConfig

fsdp_plugin = FullyShardedDataParallelPlugin(
    state_dict_config=FullStateDictConfig(offload_to_cpu=True, rank0_only=False),
    optim_state_dict_config=FullOptimStateDictConfig(offload_to_cpu=True, rank0_only=False),
)
accelerator = Accelerator(fsdp_plugin=fsdp_plugin)

How we configured FSDP for LLaMA-70B

In one project, we needed to fine-tune LLaMA-2 70B on 8x A100 80GB. Initially, the model did not fit even with DeepSpeed ZeRO-3. We chose FSDP with FULL_SHARD and hybrid bfloat16 precision, configured transformer_auto_wrap_policy and backward prefetch. The throughput was 850 tokens/s with batch size 4 per GPU. Memory savings: 68% compared to DDP. Additionally, we reduced epoch time by 30% through communication optimization. The client saved over 35% on GPU rental costs.

What's included in FSDP setup

  • Model and GPU configuration audit
  • Selection of optimal sharding strategy and mixed precision
  • Wrap policy tuning per architecture (transformers, CNNs, GNNs)
  • Integration with Accelerate and Hugging Face Trainer
  • Checkpoint optimization and loading
  • Performance profiling (throughput, memory, GPU utilization)
  • Documentation and training for your team
  • Post-deployment support

Typical mistakes when configuring FSDP

  • OOM when saving checkpoint: use FullStateDictConfig with offload_to_cpu=True.
  • Slow initialization: try HYBRID_SHARD for multi-node.
  • Incompatibility with some layers: verify auto_wrap_policy on all submodules.

Setup timeframe: 5 to 10 business days. Cost is calculated individually after a free consultation. Contact us to discuss your task. Order a turnkey FSDP setup—get a consultation from a certified engineer.