Skip to content

Fix optimizer resume bug - #411

Merged
shanjiaz merged 6 commits into
mainfrom
fix-optimizer-resume
Apr 15, 2026
Merged

shanjiaz merged 6 commits into
mainfrom
fix-optimizer-resume

Conversation

@shanjiaz

@shanjiaz shanjiaz commented Apr 13, 2026 •

Copy link
Copy Markdown
Collaborator

PLEASE FILL IN THE PR DESCRIPTION HERE ENSURING ALL CHECKLIST ITEMS (AT THE BOTTOM) HAVE BEEN CONSIDERED.

Purpose

Fix optimizer resume dtype error.

Description

When we resume distributed training from the previous best_checkpoint, there is a type mismatch bug.

RuntimeError: aten._foreach_mul_.Scalar: got mixed torch.Tensor and DTensor, need to convert all torch.Tensor to DTensor before calling distributed operators!

This is because init_best_val_loss_from_checkpoint_best() was called inside setup_model(), we ran a forward pass in validation to calculate the best_val_loss. This forward pass converts model parameters into DTensors with some other bookkeeping params and set_optimizer_state_dict then crashes because it was expecting clean tensors.

There's another issue with step data type now because convert_float_dtype casts all floating-point tensors to bfloat16 when saving/loading, including Adam's step counters. PyTorch's _group_tensors_by_device_and_dtype only exempts CPU step tensors that are float32 or float64, so bfloat16 step tensors cause a device/dtype grouping error at optimizer.step().

Now we're saving best_val_loss in a json along with best checkpoint and loading it directly instead of running a full validation forward pass to avoid this type mismatch and casting step dtype back to float32.

Related Issue

Tests

Added /home/shanjiaz/speculators/tests/e2e/smoke/test_resume_optimizer.py and ran locally to make sure it captures this bug properly. Had to update tests/unit/train/test_checkpoint.py as well because the flow is now different.

I have filled in:

  • The purpose of the PR, such as "Fix some issue (link existing issues this PR will resolve)".
  • The test plan/results, such as providing test command and pasting the results.
  • (Optional) The necessary documentation update.
  • I (a human) have written or reviewed the code in this pr to the best of my ability.

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

coderabbitai Bot commented Apr 13, 2026 •

Copy link
Copy Markdown
Contributor

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

Run ID: baf9b5f3-75cf-484f-b7b1-ff287d48e1f8

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

This PR introduces persistent tracking of best validation loss across training sessions via a new best_val_loss.json file. New methods are added to BaseCheckpointer and DistributedCheckpointer to save and load this value, trainer restoration logic is updated to restore best validation loss on resume, and corresponding unit and E2E tests are added.

Changes

Cohort / File(s) Summary
Checkpointer Implementation
src/speculators/train/checkpointer.py
Added best_val_loss_path(), save_best_val_loss(), and load_best_val_loss() methods to BaseCheckpointer for persistent best-loss tracking. DistributedCheckpointer overrides save_best_val_loss() to write only on rank 0 with barrier synchronization. Checkpoint cleanup updated to preserve best_val_loss.json.
Trainer Integration
src/speculators/train/trainer.py
Updated setup_trainer() to restore best_val_loss from checkpoint when resuming. Removed init_best_val_loss_from_checkpoint_best() method. Modified maybe_save_checkpoint() to save best_val_loss alongside best and periodic checkpoints.
Unit Tests
tests/unit/train/test_checkpoint.py
Replaced test_init_best_val_loss_on_resume_with_and_without_checkpoint_best with two new tests: test_save_and_load_best_val_loss directly exercises checkpointer persistence; test_best_val_loss_restored_on_resume validates trainer restoration on resume.
E2E Tests
tests/e2e/smoke/test_resume_optimizer.py
Added test_resume_after_checkpoint_best() to verify distributed training can resume successfully with checkpoint_best symlink present, plus helper _run_distributed_training() for orchestrating training runs.

Sequence Diagram(s)

sequenceDiagram
    actor User
    participant Trainer
    participant Checkpointer
    participant FileSystem as File System

    User->>Trainer: Resume training with checkpoint
    Trainer->>Trainer: setup_trainer()
    Trainer->>Checkpointer: load_best_val_loss()
    Checkpointer->>FileSystem: Read best_val_loss.json
    FileSystem-->>Checkpointer: best_val_loss value
    Checkpointer-->>Trainer: best_val_loss (or None)
    Trainer->>Trainer: Restore self.best_val_loss

    Note over Trainer,Checkpointer: Training Loop

    Trainer->>Trainer: Training step
    Trainer->>Trainer: Validation check
    alt Best validation achieved
        Trainer->>Checkpointer: save_best_val_loss(value)
        Checkpointer->>FileSystem: Write best_val_loss.json
        Trainer->>Checkpointer: save_model_state_dict()
        Checkpointer->>FileSystem: Write checkpoint files
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 15.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Fix optimizer resume bug' directly matches the PR's main objective of fixing a type-mismatch bug in distributed training resume from best checkpoint.
Description check ✅ Passed The description explains the optimizer resume dtype error, root causes (DTensor conversion and bfloat16 casting), and the fix (JSON persistence and step dtype normalization).

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-optimizer-resume

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

@github-actions

github-actions Bot commented Apr 13, 2026 •

Copy link
Copy Markdown

Link Check Results (DOCS)

All links are now valid - this issue has been resolved.


Marked as resolved: 7caeebb

@github-actions

github-actions Bot commented Apr 13, 2026 •

Copy link
Copy Markdown

Link Check Results (REPO)

All links are now valid - this issue has been resolved.


Marked as resolved: 7caeebb

@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: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/speculators/train/checkpointer.py`:
- Around line 310-313: SingleGPUCheckpointer.load_optimizer_state_dict()
currently runs optimizer state through convert_float_dtype(), which can leave
state["step"] tensors in reduced dtypes (e.g., bfloat16); after calling
optimizer.load_state_dict() add the same normalization as in
DistributedCheckpointer: iterate over optimizer.state.values(), check for "step"
entries that are torch.Tensor and cast them back to float32 via .float() so step
counters are restored to the correct dtype before subsequent optimizer.step()
calls.

In `@src/speculators/train/trainer.py`:
- Around line 94-100: When resuming in Trainer (when resume_from_checkpoint is
True and checkpointer.previous_epoch != -1) handle the case where
checkpointer.load_best_val_loss() returns None by adding a compatibility
fallback: attempt to read an older-style checkpoint metric (e.g., inspect the
checkpoint metadata or call a legacy loader on the Checkpointer class) and if
found set self.best_val_loss to that value, otherwise keep the existing
self.best_val_loss but log a WARN indicating no best_val_loss found and that
resume will continue with current best (so checkpoint_best won't be
inadvertently repointed). Update the checkpointer.load_best_val_loss call path
to return a fallback value when possible or have Trainer explicitly try a legacy
migration before leaving best_val_loss as inf; reference
checkpointer.load_best_val_loss, Trainer.resume_from_checkpoint,
checkpointer.previous_epoch, and self.best_val_loss to locate the change.

In `@tests/e2e/smoke/test_resume_optimizer.py`:
- Around line 70-72: The test currently calls subprocess.run(cmd, stderr=...,
text=True, check=False) but only checks exit status; change the subprocess.run
calls in test_resume_optimizer.py (the invocation using variable cmd) to also
capture stdout (add stdout=subprocess.PIPE) and then assert that the
combined/stdout contains a concrete resume signal such as "Found checkpoint",
"Resuming training", or an explicit "Resuming from epoch 1" message to prove the
second run actually resumed; apply the same change to the other subprocess.run
calls around the 99-105 region so each invocation validates the resume log
rather than merely a clean exit.
🪄 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

Run ID: 42a02623-b9f5-47c1-a169-1111c6c37316

📥 Commits

Reviewing files that changed from the base of the PR and between d8cc1c1 and a95184a.

📒 Files selected for processing (4)
  • src/speculators/train/checkpointer.py
  • src/speculators/train/trainer.py
  • tests/e2e/smoke/test_resume_optimizer.py
  • tests/unit/train/test_checkpoint.py

Comment thread src/speculators/train/checkpointer.py Resolved
Comment thread src/speculators/train/trainer.py Resolved
@shanjiaz shanjiaz added two-reviews bug Something isn't working labels Apr 14, 2026
Comment thread src/speculators/train/checkpointer.py Resolved

@fynnsu fynnsu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for updating

@shanjiaz
shanjiaz merged commit a72faa6 into main Apr 15, 2026
12 checks passed
@shanjiaz
shanjiaz deleted the fix-optimizer-resume branch April 15, 2026 17:59
my-other-github-account pushed a commit to my-other-github-account/speculators that referenced this pull request May 15, 2026
<!-- markdownlint-disable -->

PLEASE FILL IN THE PR DESCRIPTION HERE ENSURING ALL CHECKLIST ITEMS (AT
THE BOTTOM) HAVE BEEN CONSIDERED.

## Purpose
Fix optimizer resume dtype error.    
<!--- Why your changes are needed -->

## Description

When we resume distributed training from the previous `best_checkpoint`,
there is a type mismatch bug.
```
RuntimeError: aten._foreach_mul_.Scalar: got mixed torch.Tensor and DTensor, need to convert all torch.Tensor to DTensor before calling distributed operators!
```
This is because `init_best_val_loss_from_checkpoint_best()` was called
inside `setup_model()`, we ran a forward pass in validation to calculate
the `best_val_loss`. This forward pass converts model parameters into
DTensors with some other bookkeeping params and
`set_optimizer_state_dict` then crashes because it was expecting clean
tensors.

There's another issue with `step` data type now because
`convert_float_dtype` casts all floating-point tensors to bfloat16 when
saving/loading, including Adam's step counters. PyTorch's
`_group_tensors_by_device_and_dtype` only exempts CPU step tensors that
are float32 or float64, so bfloat16 step tensors cause a device/dtype
grouping error at optimizer.step().

Now we're saving `best_val_loss` in a json along with best checkpoint
and loading it directly instead of running a full validation forward
pass to avoid this type mismatch and casting step dtype back to float32.

<!--- High-level concise summary of changes -->

## Related Issue

<!--- Link related issue if applicable -->

## Tests

Added
`/home/shanjiaz/speculators/tests/e2e/smoke/test_resume_optimizer.py`
and ran locally to make sure it captures this bug properly. Had to
update `tests/unit/train/test_checkpoint.py` as well because the flow is
now different.

<!--- Please describe in detail how you tested your changes. -->

I have filled in:

- [x] The purpose of the PR, such as "Fix some issue (link existing
issues this PR will resolve)".
- [x] The test plan/results, such as providing test command and pasting
the results.
- [ ] (Optional) The necessary documentation update.
- [x] I (a human) have written or reviewed the code in this pr to the
best of my ability.

---------

Signed-off-by: shanjiaz <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working two-reviews

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants