Skip to content

Preserve BF16 optimizer states when resuming checkpoints - #4615

Merged
tianyu-l merged 2 commits into
pytorch:mainfrom
taking-lying-flat:fix/bf16-optimizer-state-resume
Sep 12, 2026
Merged

tianyu-l merged 2 commits into
pytorch:mainfrom
taking-lying-flat:fix/bf16-optimizer-state-resume

Conversation

@taking-lying-flat

@taking-lying-flat taking-lying-flat commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

With FP32 parameters and fused_opt_states_bf16, resuming a checkpoint silently promotes Adam/AdamW moments to FP32: the native optimizer loader casts states to the parameter dtype, and the step pre-hook skips nonempty state. This doubles the persistent memory for the two moment buffers and changes subsequent updates because the moments are no longer rounded back to BF16.

Register a load-state post-hook for the BF16 implementation to restore exp_avg, exp_avg_sq, and optional AMSGrad max_exp_avg_sq to BF16. Preserve the native policy for step and other state, and keep the generic checkpoint helpers optimizer-agnostic. Update the checkpointing documentation to describe the behavior.

The post-hook fixes persistent state and continuation behavior; the native loader can still allocate temporary FP32 state during loading.

Local validation on PyTorch 2.13.0+cu130, NVIDIA RTX A1000 Laptop GPU:

  • Existing CPU optimizer/state-dict tests: 31 passed; 16 additional local load checks passed, covering native/container loads, repeated loads, multiple parameter groups, and ordinary fused optimizers.
  • 16 local CUDA checkpoint checks passed, covering Adam/AdamW, AMSGrad on/off, FP32/BF16 parameters, and plain/single-rank FSDP parameters. Real DCP round-trips preserved dtype/device/placements, and two resumed updates matched uninterrupted training exactly.
  • Negative control: the CPU load check fails against the previous implementation with torch.float32 != torch.bfloat16.
  • Changed-file pre-commit checks pass except Pyrefly: its 10 errors reproduce unchanged on base commit c48650f in this environment (unavailable upstream APIs/imports and existing offset RMSNorm typing errors). No errors are reported in the changed optimizer code.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 11, 2026

@tianyu-l tianyu-l left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm ... sounds correct & improper at the same time

if len(state) == 0:
state["step"] = (
torch.zeros((), dtype=torch.float32, device=p.device)
if group.get("capturable") or group.get("fused")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what is "capturable" and what is "fused"?

``load_state_dict`` casts floating-point states to the parameter dtype.
"""

def _bf16_state_init_hook(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm now confused by why we had this function -- is it because torch optimizer doesn't allow specifying states dtype upon construction?

cc @vivekgoe @janeyx99

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review this PR and give feedback on my comments

@claude

claude Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 3m 22s —— View job


PR Review: Preserve BF16 optimizer states when resuming checkpoints

I read optimizer.py, utils.py, and the doc, and traced the PyTorch load path. Answering your two inline comments first, then overall assessment.


Re: line 345 — "why we had this function... does torch not allow specifying state dtype at construction?"

Correct, that's exactly it. torch.optim.Adam/AdamW have no API to choose optimizer-state dtype. States are allocated lazily inside _init_group on the first step() as torch.zeros_like(p, ...), i.e. always the parameter dtype (fp32 here). Native bf16 states are being tracked upstream in pytorch/pytorch#146542 but don't exist yet.

So the only lever available is to pre-seed optimizer.state[p] before the first step. _init_group guards allocation with if len(state) == 0; the pre-hook fills in bf16 tensors so that guard is false and torch skips its fp32 allocation. Then the fused kernel sees fp32-param / bf16-state and dispatches to FusedAdamMathFunctorMP. The whole function is a workaround for that missing construction-time API — worth stating in the docstring in exactly those terms.

Re: line 356 — "what is capturable and what is fused?"

Both are per-param-group Adam options:

  • fused — use the fused CUDA kernel (what this feature relies on).
  • capturable — the optimizer step is safe to record inside a CUDA graph.

They appear here only to reproduce PyTorch's own policy for the step tensor: in _init_group, torch creates step as an on-device tensor (torch.zeros((), device=p.device)) when capturable or fused, and otherwise as a host scalar (torch.tensor(0.0)). The pre-hook mirrors that branch so step matches what torch would have produced. Since this path is always fused, the capturable half is effectively dead, but keeping it makes the hook a faithful copy of torch's logic. This deserves a one-line comment — right now it reads as a magic condition. The dtype is hardcoded float32; torch actually derives it from _get_scalar_dtype() (also fp32 by default), so this is fine but is another place that silently tracks a torch internal.

Re: "correct & improper at the same time"

That's the right instinct. The change is correct — there's a genuine bug and this fixes it:

Optimizer.load_state_dict casts loaded floating-point state to the parameter's dtype (fp32), not the existing materialized state's dtype. So even though init_optim_state (via the pre-hook) already made exp_avg/exp_avg_sq bf16, the native load overwrites them back to fp32. Without the post-hook you silently get fp32 moments on resume — 2x the moment memory and different updates (no bf16 rounding). The negative-control test (float32 != bfloat16 on the old code) confirms the bug is real.

It's "improper" in that it's a hack layered on a hack: both the pre-hook and this new post-hook depend on undocumented _init_group / load_state_dict cast internals, and the fix is after-the-fact re-casting rather than preventing the fp32 allocation (the PR honestly notes fp32 temporaries are still allocated during load). That's acceptable given no upstream API exists, but it's inherently fragile against torch changes and should carry a # TODO(pytorch#146542): remove once native bf16 states land marker.


Assessment of the change itself

  • Placement is right. Keeping the bf16 logic in a registered hook (rather than in the generic utils.py helpers or the container's load_state_dict) keeps get/load_flat_optim_state_dict optimizer-agnostic, matching the repo's stated goal. Good call.
  • step handling is deliberate and correct — the load hook only re-casts exp_avg/exp_avg_sq/max_exp_avg_sq and leaves step to torch's policy. Comment says so. Good.
  • Consistency: the load hook's ("exp_avg", "exp_avg_sq", "max_exp_avg_sq") set matches the pre-hook's amsgrad-guarded init, and if key in state correctly skips absent amsgrad state. .to(bf16) is a no-op when already bf16, so re-loads are cheap.

Points worth pushing on before merge

  1. No CPU regression test in the PR. The prior commit (7db9214) removed the BF16 regression test files, and the described "16 local checks" aren't in the tree. Per CLAUDE.md ("New features need CPU unit tests at minimum"), the negative-control case — load fp32-cast state, assert exp_avg.dtype == bfloat16 after the post-hook — should be a committed CPU test. This is the single most valuable thing to add, since the whole fix guards against a silent dtype regression.
  2. Comment the capturable or group.get("fused") branch (line 356) and the hardcoded fp32 step dtype — note they mirror torch's _init_group so future readers know why.
  3. Add the upstream-tracking TODO in the docstring tying both hooks to pytorch#146542.
  4. Cross-check the training.dtype="bfloat16" case. When params are already bf16, the native loader casts loaded state to bf16 anyway and the post-hook is a harmless no-op — but worth a sentence confirming the hook can't downcast something unexpectedly (e.g. if a user somehow had fp32 params but bf16... covered, since it only ever forces bf16, which is the feature's contract).

Net: I'd approve the direction. It fixes a real silent-correctness bug, and the placement respects the repo's separation rules. Ask for (1) a committed CPU test and (2)/(3) the clarifying comments before merge.
· branch fix/bf16-optimizer-state-resume

@tianyu-l
tianyu-l merged commit e2c1a39 into pytorch:main Sep 12, 2026
13 of 14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants