Module 3 · Efficient fine-tuning

Distributed training: FSDP and DeepSpeed

6 min read

An 8-billion-parameter model needs more than 100 GB for full fine-tuning (lesson 1.3); a 70 B, nearly a terabyte. No GPU holds them. Distributed training spreads the work and the memory across several cards. This lesson explains the strategies — data parallelism, ZeRO/FSDP sharding, offloading — and gives ready-to-use configurations. A note of honesty: the course hardware is a single GPU; Forge's configurations are validated syntactically, not executed on several cards.

Data parallelism (DDP)

The simplest form: each GPU holds a full copy of the model, processes part of the batch, then gradients are averaged across cards (all-reduce) before the update. Throughput is multiplied by the number of GPUs; memory per card does not decrease. If the model and its optimizer do not fit on one card, DDP is useless.

Sharding: ZeRO and FSDP

The idea of ZeRO (DeepSpeed) and FSDP (PyTorch): instead of replicating, each GPU keeps only a share of the states, and the cards exchange the pieces they need at the moment they are used.

LevelSharded across N GPUsMemory per GPU for an 8 B in full (≈ 107 GB in total)
DDP (none)Nothing≈ 107 GB: impossible
ZeRO-1Optimizer statesweights + gradients + optimizer / N
ZeRO-2+ gradientsweights + (gradients + optimizer) / N
ZeRO-3 / FSDP "full shard"+ weights≈ 107 / N GB: ≈ 13 GB on 8 GPUs

The price: communications. With ZeRO-3, each layer's weights are gathered just before its computation, then released. On a machine with fast links between GPUs (NVLink), this is efficient; between machines connected by a slow network, communications dominate and throughput collapses.

Activations are not sharded by ZeRO: they are reduced by gradient checkpointing (lesson 1.3), and, for very long contexts, by sequence parallelism.

FSDP2 with Accelerate

With TRL, the simplest way is to launch the same script with accelerate launch and a configuration file:

compute_environment: LOCAL_MACHINE
distributed_type: FSDP
num_machines: 1
num_processes: 4                     # un processus par GPU
mixed_precision: bf16
fsdp_config:
  fsdp_version: 2
  fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP   # un « morceau » partagé par bloc Transformer
  fsdp_reshard_after_forward: true                # équivalent ZeRO-3 : poids re-partagés après usage
  fsdp_cpu_ram_efficient_loading: true            # seul le rang 0 lit les poids sur disque
  fsdp_state_dict_type: SHARDED_STATE_DICT        # checkpoints partagés ; FULL_STATE_DICT pour l'export
  fsdp_activation_checkpointing: true
accelerate launch --config_file configs/accelerate_fsdp.yaml examples/03_sft_lora.py full

(The comments of the configuration file: one process per GPU; one shard unit per Transformer block; weights re-sharded after use, the ZeRO-3 equivalent; only rank 0 reads the weights from disk; sharded checkpoints during training, a full state dict for export.) The training script does not change: Accelerate launches one process per GPU and TRL applies the sharding. Three settings deserve attention:

  • TRANSFORMER_BASED_WRAP: the model is split block by block; that is the unit gathered then released.
  • fsdp_cpu_ram_efficient_loading: without it, each process loads the whole model into RAM before sharding it — eight copies of a 70 B saturate any machine.
  • The checkpoint format: sharded during training (fast), full for the final export.

DeepSpeed ZeRO-3

DeepSpeed also integrates through a simple file, passed to SFTConfig(deepspeed=...) or to Accelerate:

{
  "bf16": {"enabled": "auto"},
  "zero_optimization": {
    "stage": 3,
    "overlap_comm": true,
    "contiguous_gradients": true,
    "offload_optimizer": {"device": "none"},
    "offload_param": {"device": "none"},
    "stage3_gather_16bit_weights_on_model_save": true
  },
  "gradient_accumulation_steps": "auto",
  "gradient_clipping": "auto",
  "train_batch_size": "auto",
  "train_micro_batch_size_per_gpu": "auto"
}

The "auto" values are filled in from the training arguments: a single source of truth. Offloading (offload_optimizer, offload_param to "cpu" or "nvme") moves states off the GPU: it makes it possible to train models larger than the cards' total memory, at the cost of a throughput often divided several times. DeepSpeed is not officially supported on Windows: use Linux or WSL.

FSDP or DeepSpeed?

FSDP2 (PyTorch)DeepSpeed
IntegrationNative in PyTorchExternal library
ShardingZeRO-2 and ZeRO-3 equivalentsZeRO-1, 2, 3
OffloadingCPUCPU and NVMe, more settings
PlatformWherever distributed PyTorch runsLinux

Both work well with TRL. FSDP2 is the natural choice to stay within the PyTorch ecosystem; DeepSpeed keeps the edge for aggressive offloading.

And for LoRA?

With LoRA or QLoRA, gradients and optimizer only concern 1 to 3% of the parameters: memory is dominated by the frozen weights. An 8 B in QLoRA fits on a single 24 GB GPU (lesson 1.3). Distribution then mainly serves to speed up (DDP, more data per second), or to fine-tune models of 70 B and more by sharding the frozen weights. Before distributing, always ask: would a smaller model, or QLoRA on a single card, be enough?

The cost of coordination

The efficiency of distributed training is measured as throughput per GPU: with 8 cards, do you get 8 times the throughput of one? On a single well-connected machine, you often get close; between machines, the gap widens without a fast network (InfiniBand). Measure throughput (tokens per second) over a few dozen steps before launching a long training run, as for the cost estimate of lesson 1.3.

Key takeaways

  • DDP speeds up but does not reduce memory per card: each GPU holds the whole model.
  • ZeRO / FSDP shard optimizer, gradients, then weights: memory per GPU is divided by the number of cards, at the cost of communications.
  • With TRL, the same script is launched with accelerate launch and an FSDP or DeepSpeed configuration file.
  • CPU/NVMe offloading allows larger models, at the cost of much lower throughput.
  • With LoRA/QLoRA, a single GPU is often enough: distribute to speed up, or for very large models.

Practice

  1. Compute, with forge/budget.py, the memory per GPU of a full fine-tuning of Llama-3.1-8B with ZeRO-2 then ZeRO-3 on 4 and 8 GPUs.
  2. On a Linux machine with at least two GPUs, run examples/03_sft_lora.py full --tiny with the FSDP configuration and compare throughput with a single GPU.
  3. Set offload_optimizer to "cpu" in the DeepSpeed configuration and measure GPU memory and throughput.

Resources