[Bug] ZeRO-3 generation exceptions leave model hooks removed
Checklist / 检查清单
- I have searched existing issues and PRs, and found no matching report.
Bug Description / Bug 描述
swift.utils.unwrap_model_for_generation removes DeepSpeed ZeRO-3 optimizer hooks before yielding the unwrapped model, then restores them only after the yield returns normally. If generation raises, add_hooks(model) is skipped and the original model remains without its training hooks even if the caller catches the generation error.
This affects both SwiftSeq2SeqTrainer.prediction_step and the non-fast rollout path in RolloutTrainerMixin._generate_completions.
Minimal reproduction
Using lightweight stubs for DeepSpeed and TRL hooks, enter the context and raise from its body. The observed event order on current main (dbc395ff0) is:
gather-enter, remove-hooks, generate, gather-exitExpected:
gather-enter, remove-hooks, generate, add-hooks, gather-exitThe outer GatheredParameters context cleans itself up, but the statement after yield is never reached because the exception is thrown back into the generator context manager.
Proposed fix
Wrap only the yield in the gathered ZeRO-3 branch with try/finally, restoring hooks in finally. Add a CPU-only regression test with stubbed DeepSpeed/TRL modules that verifies:
- hooks are restored after a normal exit;
- hooks are restored when the context body raises;
- the original generation exception still propagates.
I plan to submit this focused fix. AI assistance was used for source review and drafting; the reproduction above was executed locally.
Source: modelscope/ms-swift