Skip to content

Save and load optimizer state at full precision in checkpoints - #899

Closed
khazic wants to merge 3 commits into
vllm-project:mainfrom
khazic:khazic/fix/optimizer-state-precision
Closed

khazic wants to merge 3 commits into
vllm-project:mainfrom
khazic:khazic/fix/optimizer-state-precision

Conversation

@khazic

@khazic khazic commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Problem

Checkpointing converts the entire optimizer state dict to bf16 (the default float_dtype), including the AdamW exp_avg/exp_avg_sq moments and the float step counters. bf16 has an 8-bit mantissa: any step count above 256 rounds (10000 rounds to a multiple of 64), and the second moments lose their low bits, so resumed runs use wrong bias correction and quantized moments, visibly deviating from an uninterrupted run. Both SingleGPUCheckpointer and DistributedCheckpointer are affected, and the load paths re-applied the same cast (to the model dtype), so bf16 models were re-quantized even when the file was fine.

Fix

Optimizer state is saved and loaded without any dtype conversion. Optimizer.load_state_dict already aligns per-param float state with the param dtype and leaves step untouched; the distributed loader's step-to-float32 repair loop is kept for legacy bf16-saved checkpoints. Model weights still save as bf16 as before.

Note on scope: this changes what new checkpoints contain (optimizer state roughly doubles in size, fp32 instead of bf16) while remaining able to load old bf16-saved files. Flagging it here since it touches the checkpoint save/load path; happy to adjust if you prefer an opt-in flag.

Tests

A round-trip unit test in test_checkpoint.py steps AdamW past step 10000, saves, reloads through the checkpointer, and asserts the step counters and moments are bit-exact fp32. Fails on main.

@khazic
khazic requested review from fynnsu and shanjiaz as code owners August 3, 2026 12:49
@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 95888ea5-def1-4127-8e34-88ae6a0e65a3

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The checkpointer now preserves full-precision optimizer state during single-GPU and distributed checkpoint saves and loads. A regression test verifies exact restoration of AdamW step counters and moment tensors.

Changes

Optimizer checkpoint precision

Layer / File(s) Summary
Preserve optimizer state precision
src/speculators/train/checkpointer.py
Single-GPU and distributed checkpoint paths no longer cast optimizer state to the model or checkpoint dtype. Distributed loading still converts legacy step counters to float32.
Validate optimizer state round trip
tests/unit/train/test_checkpoint.py
The test creates a stepped AdamW optimizer and verifies exact restoration of step counters and float32 moment tensors.

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: preserving optimizer state at full precision during checkpoint save and load.
Description check ✅ Passed The description directly explains the optimizer precision problem, the fix, compatibility behavior, scope, and regression test.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@mergify

mergify Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Merge Protections

🔴 1 of 1 protections blocking · waiting on 👀 reviews

Protection Waiting on
🔴 Require approval from approved reviewers list 👀 reviews

🔴 Require approval from approved reviewers list

Waiting for any of

  • approved-reviews-by = dsikka
  • approved-reviews-by = fynnsu
  • approved-reviews-by = orestis-z
  • approved-reviews-by = rahul-tuli
  • approved-reviews-by = shanjiaz
This rule is failing.

All pull requests must have at least one approving review from a member of the approved reviewers list before merging.

  • any of:
    • approved-reviews-by = dsikka
    • approved-reviews-by = fynnsu
    • approved-reviews-by = orestis-z
    • approved-reviews-by = rahul-tuli
    • approved-reviews-by = shanjiaz

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fd79c7fbe9

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

# model dtype (e.g. bf16), undoing the full-precision save.
for opt, state_dict in zip(optimizers, loaded_list, strict=True):
opt.load_state_dict(convert_float_dtype(state_dict, dtype))
opt.load_state_dict(state_dict)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Restore legacy step tensors to float32

When SingleGPUCheckpointer resumes a checkpoint written by the previous implementation, AdamW's step tensors are stored as BF16. The default non-capturable optimizer loader deliberately leaves step in its saved dtype, so this direct load preserves BF16; once the count is sufficiently large, in-place increments round or stop changing, corrupting bias correction during the resumed run. The old code converted these tensors back to the FP32 model dtype, and the distributed path still explicitly repairs legacy steps, so the single-GPU path needs the equivalent post-load conversion.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed: the single-GPU load path now casts step tensors back to float32, matching the distributed path. Added a test that writes a bf16-step checkpoint and asserts the repair.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/speculators/train/checkpointer.py`:
- Around line 327-332: Update load_optimizer_state_dict at both
src/speculators/train/checkpointer.py:327-332 and
src/speculators/train/checkpointer.py:395-403 so optimizer state restoration
preserves saved float32 moments and step tensors instead of casting them to bf16
parameter dtypes; retain strict optimizer/state alignment and apply the same fix
to single-GPU and distributed loading paths. Update
tests/unit/train/test_checkpoint.py:320-352 to verify restored optimizer
floating-point state remains float32 for bf16 parameters.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: d6bed57f-d1f3-48f5-bd7f-ef4850a8d0b0

📥 Commits

Reviewing files that changed from the base of the PR and between 11f4d1e and fd79c7f.

📒 Files selected for processing (2)
  • src/speculators/train/checkpointer.py
  • tests/unit/train/test_checkpoint.py

Comment thread src/speculators/train/checkpointer.py Resolved
khazic added 2 commits August 4, 2026 10:53
The distributed path already casts step tensors back to float32 after loading;
the single-GPU path did not, and the non-capturable optimizer loader keeps step
in its saved dtype. A checkpoint written by the previous bf16 save path would
therefore resume with a bf16 counter whose in-place increments round, corrupting
bias correction.

Signed-off-by: khazic <[email protected]>
load_optimizer_state_dict maps the state onto the current accelerator, so on a
GPU host the restored tensors are on cuda while the reference is on cpu and
torch.equal raises. CPU-only CI never hit it. Also assert the moment dtype
explicitly, which is what the test is really about.

Signed-off-by: khazic <[email protected]>
@khazic

khazic commented Sep 20, 2026

Copy link
Copy Markdown
Contributor Author

Gentle follow-up on this one. It saves and restores optimizer state at full precision so a resumed run does not lose Adam moments to a dtype round-trip; checks are green. Happy to rebase or adjust if anything is off.

@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had any activity within 60 days. It will be automatically closed if no further activity occurs within 30 days.

@github-actions github-actions Bot added the stale label Nov 21, 2026
@mergify

mergify Bot commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

Merge Protections

🔴 1 of 1 protections blocking · waiting on 👀 reviews and 🙋 you

Protection Waiting on
🔴 Require approval from approved reviewers list 👀 reviews and 🙋 you

🔴 Require approval from approved reviewers list

Waiting for

  • body ~= (?i)[-*]\s*\[x\]\s*I \(a human\) have written or reviewed
  • any of:
    • approved-reviews-by = dsikka
    • approved-reviews-by = fynnsu
    • approved-reviews-by = orestis-z
    • approved-reviews-by = rahul-tuli
    • approved-reviews-by = shanjiaz
This rule is failing.

All pull requests must have the human-review checklist item checked and at least one approving review from a member of the approved reviewers list before merging.

  • body ~= (?i)[-*]\s*\[x\]\s*I \(a human\) have written or reviewed
  • any of:
    • approved-reviews-by = dsikka
    • approved-reviews-by = fynnsu
    • approved-reviews-by = orestis-z
    • approved-reviews-by = rahul-tuli
    • approved-reviews-by = shanjiaz

1 similar comment
@mergify

mergify Bot commented Nov 28, 2026

Copy link
Copy Markdown
Contributor

Merge Protections

🔴 1 of 1 protections blocking · waiting on 👀 reviews and 🙋 you

Protection Waiting on
🔴 Require approval from approved reviewers list 👀 reviews and 🙋 you

🔴 Require approval from approved reviewers list

Waiting for

  • body ~= (?i)[-*]\s*\[x\]\s*I \(a human\) have written or reviewed
  • any of:
    • approved-reviews-by = dsikka
    • approved-reviews-by = fynnsu
    • approved-reviews-by = orestis-z
    • approved-reviews-by = rahul-tuli
    • approved-reviews-by = shanjiaz
This rule is failing.

All pull requests must have the human-review checklist item checked and at least one approving review from a member of the approved reviewers list before merging.

  • body ~= (?i)[-*]\s*\[x\]\s*I \(a human\) have written or reviewed
  • any of:
    • approved-reviews-by = dsikka
    • approved-reviews-by = fynnsu
    • approved-reviews-by = orestis-z
    • approved-reviews-by = rahul-tuli
    • approved-reviews-by = shanjiaz

@mergify mergify Bot closed this Nov 28, 2026
@mergify

mergify Bot commented Nov 28, 2026

Copy link
Copy Markdown
Contributor

Closing this pull request because the "I (a human) have written or reviewed the code in this pr to the best of my ability." checklist item is unticked and there has been no activity for 7 days. Pull requests are reviewed only once a human has written or reviewed the code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant