Repository navigation
Fix optimizer resume bug - #411
Conversation
Signed-off-by: shanjiaz <[email protected]>
Signed-off-by: shanjiaz <[email protected]>
|
Important Review skippedAuto incremental reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
WalkthroughThis PR introduces persistent tracking of best validation loss across training sessions via a new Changes
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes 🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
|
All links are now valid - this issue has been resolved. Marked as resolved: 7caeebb |
|
All links are now valid - this issue has been resolved. Marked as resolved: 7caeebb |
There was a problem hiding this comment.
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
📒 Files selected for processing (4)
src/speculators/train/checkpointer.pysrc/speculators/train/trainer.pytests/e2e/smoke/test_resume_optimizer.pytests/unit/train/test_checkpoint.py
Signed-off-by: shanjiaz <[email protected]>
Signed-off-by: shanjiaz <[email protected]>
<!-- 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]>
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.This is because
init_best_val_loss_from_checkpoint_best()was called insidesetup_model(), we ran a forward pass in validation to calculate thebest_val_loss. This forward pass converts model parameters into DTensors with some other bookkeeping params andset_optimizer_state_dictthen crashes because it was expecting clean tensors.There's another issue with
stepdata type now becauseconvert_float_dtypecasts all floating-point tensors to bfloat16 when saving/loading, including Adam's step counters. PyTorch's_group_tensors_by_device_and_dtypeonly 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_lossin 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.pyand ran locally to make sure it captures this bug properly. Had to updatetests/unit/train/test_checkpoint.pyas well because the flow is now different.I have filled in: