accelerate icon indicating copy to clipboard operation
accelerate copied to clipboard

[Bug] FSDP2 + fp16: load_state() does not round-trip the GradScaler state

Open HaomingSong opened this issue 2 months ago • 0 comments

Fixes

#4291

Summary

Under FSDP2 with mixed_precision="fp16", Accelerator.load_state() does not restore the GradScaler state it saved.

When load_state() runs Symptom
In a fresh process (the normal resume) The restored loss scale differs from scaler.pt with no warning.
In a process whose scaler has already been used (train → save → load) AssertionError: _growth_tracker initialized before _scale

The cause is that load_fsdp_optimizer hands torch's optimizer DCP API anAcceleratedOptimizer. torch.distributed.checkpoint.state_dict._init_optim_state materializes an empty optimizer state by calling optimizer.step(), and through the wrapper that dummy step runs scaler.step() and scaler.update(), which advances the very scaler state that was just restored.

The workaround currently in load_state (accelerator.py:3863-3876, added in #3671) pre-initializes the scaler so that scaler.step() does not hit its own _scale is None assertion. It removes that assertion but not the mutation, and it introduces the second symptom, because GradScaler._lazy_init_scale_growth_tracker asserts that the tracker is still None.

System Info

- accelerate: 1.16.0.dev0 (source, commit b795b4838eb33bde60eb398649c4ab006874e3e9)
- torch:      2.10.0+cu128
- python:     3.12.12
- numpy:      2.2.6
- platform:   Linux-5.15.0-174-generic-x86_64-with-glibc2.35
- GPU:        2x NVIDIA H200 (driver 595.71.05, CUDA 13.2)

Information

  • [ ] The official example scripts
  • [x] My own modified scripts

Tasks

  • [ ] One of the scripts in the examples/ folder of Accelerate or an officially supported no_trainer script in the examples folder of the transformers repo (such as run_no_trainer_glue.py)
  • [x] My own task or dataset (A two-layer nn.Linear model on synthetic data. No dataset is involved; the loss scale is the only quantity under test.)

Reproduction

# repro.py
import argparse, json, os, torch
from accelerate import Accelerator
from accelerate.utils import FullyShardedDataParallelPlugin, GradScalerKwargs

INIT_SCALE, GROWTH_INTERVAL, HIDDEN = 1024.0, 2, 16


def build():
    plugin = FullyShardedDataParallelPlugin(
        fsdp_version=2, auto_wrap_policy="size_based_wrap", min_num_params=1
    )
    accelerator = Accelerator(
        mixed_precision="fp16",
        fsdp_plugin=plugin,
        kwargs_handlers=[GradScalerKwargs(init_scale=INIT_SCALE, growth_interval=GROWTH_INTERVAL)],
    )
    model = torch.nn.Sequential(torch.nn.Linear(HIDDEN, HIDDEN), torch.nn.Linear(HIDDEN, HIDDEN))
    optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)
    return (accelerator, *accelerator.prepare(model, optimizer))


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--phase", required=True, choices=["save", "load", "same-process"])
    parser.add_argument("--dir", required=True)
    args = parser.parse_args()

    accelerator, model, optimizer = build()
    say = lambda *a: accelerator.is_main_process and print(*a, flush=True)

    if args.phase in ("save", "same-process"):
        # Stop one finite update short of a scale growth, so the extra update the resume
        # performs shows up as a doubling rather than only as a tracker offset.
        for _ in range(GROWTH_INTERVAL - 1):
            accelerator.backward(model(torch.randn(4, HIDDEN, device=accelerator.device)).sum())
            optimizer.step()
            optimizer.zero_grad()
            assert not accelerator.optimizer_step_was_skipped
        saved = dict(accelerator.scaler.state_dict())
        say(f"[save] scaler after training : {saved}")
        accelerator.save_state(args.dir)
        if accelerator.is_main_process:
            json.dump(saved, open(os.path.join(args.dir, "expected_scaler.json"), "w"))

    if args.phase == "same-process":
        say("[same-process] calling load_state() with an already-used scaler ...")
        try:
            accelerator.load_state(args.dir)
        except AssertionError as error:
            say(f"[same-process] RESULT: AssertionError: {error}")
        return

    if args.phase == "load":
        expected = json.load(open(os.path.join(args.dir, "expected_scaler.json")))
        say(f"[load] scaler.pt on disk      : "
            f"{torch.load(os.path.join(args.dir, 'scaler.pt'), weights_only=True)}")
        accelerator.load_state(args.dir)
        restored = dict(accelerator.scaler.state_dict())
        say(f"[load] scaler after load_state: {restored}")
        say(f"[load] expected (saved)       : {expected}")
        say(f"[load] ROUND-TRIPS            : {restored == expected}")


if __name__ == "__main__":
    main()
torchrun --nproc-per-node=2 repro.py --phase save         --dir ./ckpt
torchrun --nproc-per-node=2 repro.py --phase load         --dir ./ckpt
torchrun --nproc-per-node=2 repro.py --phase same-process --dir ./ckpt2

Observed:

############################## phase=save ##############################
[save] scaler after training : {'scale': 1024.0, 'growth_factor': 2.0, 'backoff_factor': 0.5, 'growth_interval': 2, '_growth_tracker': 1}

############################## phase=load ##############################
[load] scaler.pt on disk      : {'scale': 1024.0, 'growth_factor': 2.0, 'backoff_factor': 0.5, 'growth_interval': 2, '_growth_tracker': 1}
[load] scaler after load_state: {'scale': 2048.0, 'growth_factor': 2.0, 'backoff_factor': 0.5, 'growth_interval': 2, '_growth_tracker': 0}
[load] expected (saved)       : {'scale': 1024.0, 'growth_factor': 2.0, 'backoff_factor': 0.5, 'growth_interval': 2, '_growth_tracker': 1}
[load] ROUND-TRIPS            : False

############################## phase=same-process ##############################
[same-process] RESULT: AssertionError: _growth_tracker initialized before _scale

The state written to scaler.pt is correct; it is the load that changes it.

Minimal, no-GPU version of the same mechanism

import copy, torch
from accelerate import Accelerator
from accelerate.optimizer import AcceleratedOptimizer
from torch.distributed.checkpoint.state_dict import get_optimizer_state_dict, set_optimizer_state_dict

Accelerator(cpu=True)  # AcceleratedOptimizer reads the global AcceleratorState

def fresh(state=None):
    torch.manual_seed(0)
    model = torch.nn.Linear(4, 4)
    scaler = torch.amp.GradScaler("cpu", init_scale=1024.0, growth_interval=2)
    if state is not None:
        scaler.load_state_dict(state)
    return model, AcceleratedOptimizer(torch.optim.AdamW(model.parameters()), scaler=scaler), scaler

model, opt, scaler = fresh()
scaler.scale(model(torch.randn(2, 4)).sum()).backward()
opt.step(); opt.zero_grad()
saved_scaler = copy.deepcopy(scaler.state_dict())
saved_optim = copy.deepcopy(get_optimizer_state_dict(model, opt.optimizer))

# What accelerator.py:3867-3874 + fsdp_utils.py:440 do, in order:
model, opt, scaler = fresh(saved_scaler)
scaler._lazy_init_scale_growth_tracker(scaler._device)
set_optimizer_state_dict(model, opt, saved_optim)
print(scaler.state_dict() == saved_scaler)   # False

# Without the pre-init:  AssertionError: Attempted step but _scale is None.
# With the inner optimizer instead of the wrapper:  True

Expected behavior

accelerator.load_state(d) after accelerator.save_state(d) should leave accelerator.scaler.state_dict() equal to what save_state wrote, and should not raise, regardless of whether the scaler in the loading process has been used yet.

Why it happens

  1. Accelerator.load_state passes the prepared optimizer (AcceleratedOptimizer) to load_fsdp_optimizer (accelerator.py:3883).
  2. load_fsdp_optimizer forwards it to torch's optimizer DCP API (fsdp_utils.py:416 and fsdp_utils.py:440).
  3. Torch's _init_optim_state (torch/distributed/checkpoint/state_dict.py:615) materializes an empty optimizer state by zeroing the gradients, setting the learning rates to 0 and calling optim.step().
  4. AcceleratedOptimizer.step routes that call through the scaler (optimizer.py:169-174): scaler.step(...) followed by scaler.update(). With no overflow (the gradients are zero), update() increments _growth_tracker, and on reaching growth_interval multiplies the scale by growth_factor and resets the tracker.

So every FSDP2 fp16 resume performs one extra, invisible scaler update. The pre-init at accelerator.py:3873 only removes GradScaler.step's _scale is None assertion; it does not keep the scaler off the path. And because GradScaler._lazy_init_scale_growth_tracker itself asserts self._growth_tracker is None (torch/amp/grad_scaler.py:172), calling it on a scaler that has already been used raises

HaomingSong avatar Sep 20 '26 13:09 HaomingSong