DeepSpeed icon indicating copy to clipboard operation
DeepSpeed copied to clipboard

Refactor/torch autocast encapsulate global state

Open nathon-lee opened this issue 8 months ago • 1 comments

refactor: replace bare global vars in torch_autocast with _AutocastState

TORCH_AUTOCAST_INITIALIZED and TORCH_AUTOCAST_DTYPE were module-level globals mutated via global statements inside init_autocast_params(). This pattern is fragile: it is invisible to type checkers, prevents isolation between multiple engine instances, and makes the state harder to reset in tests.

Replace them with a private _AutocastState dataclass instance _autocast_state. The public API (is_autocast_initialized, get_autocast_dtype) is unchanged, so no call sites are affected.


fix: store autocast state per-engine to support multiple engine configs

Previously, _autocast_state was a module-level singleton in torch_autocast.py. When a second DeepSpeed engine called init_autocast_params(), it would overwrite the first engine's dtype and initialized state, making it impossible to run two engines with different autocast configurations concurrently.

Fix by attaching _AutocastState directly to the engine instance (engine._autocast_state). Update is_autocast_initialized() and get_autocast_dtype() to accept an engine argument. For ZeRO optimizers (which hold no engine reference), switch from the global state query to the per-parameter has_comm_dtype() check; parameters are already stamped by their own engine inside init_autocast_params(), so isolation is automatic.

nathon-lee avatar Apr 02 '26 06:04 nathon-lee

**tohtana **

@tohtana thank you, good catch, — I still need to make one more change.

nathon-lee avatar Apr 03 '26 13:04 nathon-lee