🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Fine-Tuning LLMs at Scale with ZeRO and FSDP

Advanced LLMOpsLLM Fine-Tuning at ScaleđŸŸĸ Free Lesson

A 70-billion-parameter model in bf16 holds 140 GB of weights alone. Add gradients, AdamW optimizer states, and activations, and a single GPU cannot come close to holding a full fine-tune. Distributed training is therefore not an optimization you add later; it is the entry requirement. The good news is that the strategy space is well understood: shard the states that dominate memory, synchronize gradients efficiently, and checkpoint often enough that a failing rank does not cost you a day of compute.

This lesson covers the memory arithmetic that decides which strategy you need, DeepSpeed ZeRO stages and what each one actually shards, PyTorch FSDP as the native alternative, and the operational details — mixed precision, gradient checkpointing, failure recovery — that determine whether a multi-day run finishes.

The memory arithmetic first

Before choosing a framework, do the arithmetic. For a model with P parameters trained with AdamW in mixed precision, the dominant consumers per GPU are: parameters in bf16 (2 bytes each), gradients in bf16 (2 bytes), and optimizer states — fp32 master weights plus two Adam moments (8 bytes) — plus activations, which scale with batch size and sequence length rather than parameter count. Without sharding, that is roughly 12–16 bytes per parameter before activations, which is why naive data parallelism caps out so low.

StateBytes per param (naive)With ZeRO-1With ZeRO-2With ZeRO-3
Parameters (bf16)2222 / N
Gradients (bf16)222 / N2 / N
Optimizer states88 / N8 / N8 / N
Activationsvariesvariesvaries+ checkpointing helps

(N is the number of GPUs; activation memory is orthogonal to sharding stage.) A 13B model needs about 160 GB of pure state — eight 24 GB consumer cards sharded with ZeRO-2 gets you under 25 GB per GPU, leaving room for activations. Move to ZeRO-3 or FSDP full sharding when parameters themselves no longer fit.

Choosing and configuring a sharding strategy

DeepSpeed's ZeRO (Zero Redundancy Optimizer) partitions states progressively. Stage 1 shards optimizer states, Stage 2 additionally shards gradients, and Stage 3 additionally shards parameters, gathering them layer-by-layer during the forward and backward passes. For most instruction-tuning and LoRA work on models up to ~30B with decent GPUs, Stage 2 is the sweet spot; Stage 3 pays a communication tax you only accept when you must.

python
import json


def build_zero_config(stage: int, learning_rate: float = 2e-5,
                      micro_batch: int = 1, grad_accum: int = 8) -> dict:
    config = {
        "train_micro_batch_size_per_gpu": micro_batch,
        "gradient_accumulation_steps": grad_accum,
        "gradient_clipping": 1.0,
        "steps_per_print": 50,
        "bf16": {"enabled": True},
        "optimizer": {
            "type": "AdamW",
            "params": {"lr": learning_rate, "betas": [0.9, 0.95],
                       "weight_decay": 0.1},
        },
        "scheduler": {
            "type": "WarmupDecayLR",
            "params": {"warmup_min_lr": 0,
                       "warmup_max_lr": learning_rate,
                       "total_num_steps": 1000},
        },
        "zero_optimization": {
            "stage": stage,
            "overlap_comm": True,
            "contiguous_gradients": True,
            "reduce_bucket_size": 5e8,
            "allgather_bucket_size": 5e8,
        },
    }
    if stage >= 2:
        config["zero_optimization"]["allgather_partitions"] = True
        config["zero_optimization"]["reduce_scatter"] = True
    if stage == 3:
        config["zero_optimization"].update({
            "stage3_prefetch_bucket_size": 5e7,
            "stage3_param_persistence_threshold": 1e6,
            "stage3_max_live_parameters": 1e9,
            "offload_optimizer": {"device": "cpu", "pin_memory": True},
            "offload_param": {"device": "cpu", "pin_memory": True},
        })
    return config


def write_dsl(path: str, stage: int) -> None:
    with open(path, "w", encoding="utf-8") as fh:
        json.dump(build_zero_config(stage), fh, indent=2)


if __name__ == "__main__":
    write_dsl("ds_zero2.json", 2)
    write_dsl("ds_zero3.json", 3)

Two configuration details cause most first-run failures. Gradient accumulation steps multiplied by micro-batch size and GPU count must equal your intended global batch size, or your effective learning rate silently changes. And CPU offload trades GPU hours for wall-clock time — it unblocks runs that otherwise cannot fit, but expect throughput to drop, sometimes by half.

FSDP: the native PyTorch path

Fully Sharded Data Parallel is PyTorch's answer to the same problem and has become the default for many teams because it lives inside the standard torch.distributed stack, integrates with torch.compile, and does not require a separate config file. Full sharding behaves like ZeRO-3; SHARD_GRAD_OP behaves closer to ZeRO-2.

python
import torch
import torch.nn as nn
from torch.distributed.fsdp import (
    FullyShardedDataParallel as FSDP,
    MixedPrecision,
    ShardingStrategy,
    CPUOffload,
)
from torch.distributed.fsdp.wrap import transformer_auto_wrap_policy
import functools


class Block(nn.Module):
    def __init__(self, dim: int):
        super().__init__()
        self.attn = nn.Linear(dim, dim)
        self.mlp = nn.Linear(dim, dim)

    def forward(self, x):
        return x + self.mlp(torch.relu(self.attn(x)))


def build_fsdp_model(model: nn.Module, block_type=Block,
                     offload: bool = False) -> FSDP:
    mp = MixedPrecision(
        param_dtype=torch.bfloat16,
        reduce_dtype=torch.float32,
        buffer_dtype=torch.bfloat16,
    )
    policy = functools.partial(
        transformer_auto_wrap_policy, transformer_layer_cls={block_type}
    )
    return FSDP(
        model,
        sharding_strategy=ShardingStrategy.FULL_SHARD,
        mixed_precision=mp,
        auto_wrap_policy=policy,
        cpu_offload=CPUOffload(offload_params=offload),
        device_id=torch.cuda.current_device(),
        use_orig_params=True,
    )


def per_gpu_state_gb(params_billion: float, world_size: int,
                     full_shard: bool = True) -> dict:
    factor = world_size if full_shard else 1
    p = params_billion * 2 / factor
    g = params_billion * 2 / factor
    o = params_billion * 8 / factor
    return {"params_gb": round(p, 2), "grads_gb": round(g, 2),
            "optim_gb": round(o, 2), "total_gb": round(p + g + o, 2)}

Wrapping transformer blocks individually matters: FSDP shards at wrap boundaries, so a single unwrapped giant module forces whole-model gathers and defeats the memory savings. use_orig_params=True makes parameter inspection and debugging far less painful, at a small memory overhead that is usually worth it.

Precision choices: bf16, fp8, and numerical drift

Mixed precision is not a single switch but a set of trade-offs that deserve explicit naming. bf16 keeps the exponent range of fp32 while halving storage, which makes it the safe default for LLM fine-tuning — gradient explosions that would silently corrupt fp16 training instead surface as visible instability you can catch with loss-scale monitoring or gradient-norm clipping. fp16 still appears in older stacks, and if you use it, keep dynamic loss scaling enabled; static loss scales are a frequent source of mysterious NaNs on the second day of a run.

fp8 is the newer frontier: another halving of bandwidth and memory, with hardware support on recent accelerators, but it demands calibration and per-tensor scaling factors to keep signal-to-noise acceptable. Teams shipping fp8 training usually keep a bf16 shadow of sensitive layers — attention and the final projection — because the error budget is not uniform across the network. Whatever precision you choose, verify it empirically: train a small model for a few hundred steps under each setting and compare loss curves, because a configuration that "runs" can still be quietly 1–2 percent worse in final quality, and that gap is invisible in a memory dashboard.

Throughput levers that actually move the needle

Once the run fits in memory, the question becomes tokens per second per GPU. Mixed precision is table stakes: bf16 is numerically safer than fp16 for training and roughly doubles throughput versus fp32. Gradient checkpointing recomputes activations during the backward pass, cutting activation memory by an order of magnitude at a cost of about 30 percent extra compute — a trade almost always worth making on long-context data. Sequence packing, covered in the data pipeline lesson, removes padding waste that can silently eat 30–50 percent of throughput on ragged corpora.

Data loading deserves attention too. A distributed sampler must shard without overlap, and tokenized datasets should be memory-mapped so the loader is not the bottleneck. When GPU utilization dips below roughly 70 percent in steady state, the cause is almost always the input pipeline, not the model.

Checkpointing and surviving failures

Long distributed runs fail. A node drops, a bit-flip corrupts a gradient, a spot instance gets reclaimed. The recovery plan is therefore part of the training design, not an afterthought. Save checkpoints from rank 0 only, include optimizer and scheduler state, and write to a path atomically — write to a temporary name, then rename — so a crash mid-save never corrupts the last good checkpoint. For ZeRO-3 and FSDP, consolidate sharded state at save time so inference and evaluation do not need the full distributed group.

Save often enough that a failure costs at most a few minutes of compute, and keep the last N checkpoints on fast storage with one archived copy in object storage. Resume must restore the data loader position too, or you will silently re-train on the start of the corpus every time you restart.

Common Mistakes

Picking ZeRO-3 or FSDP full shard for a model that fits comfortably at Stage 2

Fix: Run the memory arithmetic first; extra sharding buys headroom you pay for in communication overhead.

Forgetting that gradient accumulation defines the effective batch size

Fix: Compute micro-batch × accumulation × world size explicitly and set the learning rate against that global batch.

Saving checkpoints only from rank 0 without consolidating sharded state

Fix: Consolidate or use framework-native checkpointing that gathers shards before writing to disk.

Ignoring the data loader during throughput debugging

Fix: Profile GPU utilization first; below about 70 percent steady-state, the input pipeline is usually the cause.

Relying on spot instances without checkpoint-resume automation

Fix: Automated resume plus frequent atomic checkpoints makes preemption a non-event instead of a lost day.

Best Practices

  • Start with bf16 mixed precision and gradient checkpointing; they solve most memory problems before you reach for heavier sharding.
  • Wrap transformer blocks individually so sharding granularity matches the model's natural structure.
  • Log per-GPU memory high-water marks and throughput every step; regressions here are silent budget killers.
  • Test resume-from-checkpoint on a two-GPU run before launch, because broken resume logic only surfaces mid-job.
  • Keep the optimizer and scheduler state in every checkpoint, or your warmup restarts from scratch after every preemption.

Key Takeaways

  • Fine-tune memory is roughly 12–16 bytes per parameter before activations; do this arithmetic before choosing a framework.
  • ZeRO stages 1–3 progressively shard optimizer states, gradients, then parameters; Stage 2 fits most instruction-tuning jobs.
  • FSDP provides the same sharding natively in PyTorch, with per-block wrapping being the key to real memory savings.
  • Throughput comes from bf16, gradient checkpointing, sequence packing, and a data loader that never starves the GPUs.
  • Durable checkpointing — atomic writes, rank-0 consolidation, data-loader state — is what turns multi-day runs from fragile to boring.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert AI Ops & LLM Ops Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement