-
Notifications
You must be signed in to change notification settings - Fork 384
[megatron] Accept dtype-string optimizer_config_kwargs (coerce exp_avg_dtype etc. to torch.dtype) #1805
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
SumanthRH
merged 4 commits into
NovaSky-AI:main
from
dyurk-lila:feat/optimizer-state-dtype-coercion
Jul 10, 2026
Merged
[megatron] Accept dtype-string optimizer_config_kwargs (coerce exp_avg_dtype etc. to torch.dtype) #1805
Changes from 3 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
02333ad
[megatron] Accept dtype-string optimizer_config_kwargs (coerce exp_av…
dyurk-lila b580133
docs: tighten optimizer dtype comments
dyurk-lila 43658cf
test: narrow optimizer dtype coercion coverage
dyurk-lila 6f50dbe
test: make optimizer dtype test CPU-only
dyurk-lila File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
64 changes: 64 additions & 0 deletions
64
skyrl/backends/skyrl_train/distributed/megatron/optimizer_dtype.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| """Torch-only coercion for Megatron optimizer dtype kwargs.""" | ||
|
|
||
| from typing import Any, Dict, Set | ||
|
|
||
| import torch | ||
|
|
||
| # Megatron short names plus common YAML spellings. TE stores FP8 optimizer state | ||
| # as uint8, matching Megatron-LM's dtype map. | ||
| _DTYPE_NAME_TO_TORCH: Dict[str, torch.dtype] = { | ||
| "fp32": torch.float32, | ||
| "float32": torch.float32, | ||
| "float": torch.float32, | ||
| "bf16": torch.bfloat16, | ||
| "bfloat16": torch.bfloat16, | ||
| "fp16": torch.float16, | ||
| "float16": torch.float16, | ||
| "half": torch.float16, | ||
| "fp8": torch.uint8, | ||
| "float8": torch.uint8, | ||
| "uint8": torch.uint8, | ||
| } | ||
|
|
||
| # Only TE FusedAdam-backed fields get field-specific checks. ``main_grads_dtype`` | ||
| # is not forwarded at the pinned megatron-core rev, so it is coerced only and | ||
| # left to ``OptimizerConfig.__post_init__``. | ||
| _LEGAL_FIELD_DTYPES: Dict[str, Set[torch.dtype]] = { | ||
| "main_params_dtype": {torch.float32, torch.float16}, | ||
| "exp_avg_dtype": {torch.float32, torch.bfloat16, torch.float16, torch.uint8}, | ||
| "exp_avg_sq_dtype": {torch.float32, torch.bfloat16, torch.float16, torch.uint8}, | ||
| } | ||
|
|
||
|
|
||
| def coerce_optimizer_dtype_kwargs(optimizer_config_kwargs: Dict[str, Any] | None) -> Dict[str, Any]: | ||
| """Return kwargs with recognized ``*_dtype`` strings converted to ``torch.dtype``.""" | ||
| if optimizer_config_kwargs is None: | ||
| return {} | ||
|
|
||
| coerced: Dict[str, Any] = {} | ||
| for key, value in optimizer_config_kwargs.items(): | ||
| if not key.endswith("_dtype"): | ||
| coerced[key] = value | ||
| continue | ||
|
|
||
| if isinstance(value, torch.dtype): | ||
| dtype = value | ||
| elif isinstance(value, str): | ||
| name = value.strip().lower() | ||
| if name not in _DTYPE_NAME_TO_TORCH: | ||
| raise ValueError( | ||
| f"Unrecognized dtype name {value!r} for optimizer kwarg {key!r}. " | ||
| f"Expected one of {sorted(_DTYPE_NAME_TO_TORCH)} or a torch.dtype." | ||
| ) | ||
| dtype = _DTYPE_NAME_TO_TORCH[name] | ||
| else: | ||
| # Let Megatron validate non-string, non-dtype values. | ||
| coerced[key] = value | ||
| continue | ||
|
|
||
| legal = _LEGAL_FIELD_DTYPES.get(key) | ||
| if legal is not None and dtype not in legal: | ||
| legal_names = sorted({n for n, d in _DTYPE_NAME_TO_TORCH.items() if d in legal}) | ||
| raise ValueError(f"Illegal dtype {dtype} for optimizer kwarg {key!r}; legal values are {legal_names}.") | ||
| coerced[key] = dtype | ||
| return coerced | ||
48 changes: 48 additions & 0 deletions
48
tests/backends/skyrl_train/distributed/test_optimizer_dtype_coercion.py
|
dyurk-lila marked this conversation as resolved.
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| """Tests for Megatron optimizer dtype coercion.""" | ||
|
|
||
| import pytest | ||
| import torch | ||
|
|
||
| from skyrl.backends.skyrl_train.distributed.megatron.optimizer_dtype import ( | ||
| coerce_optimizer_dtype_kwargs, | ||
| ) | ||
|
|
||
|
|
||
| def test_coerces_dtype_strings_and_preserves_other_kwargs(): | ||
| kwargs = { | ||
| "exp_avg_dtype": " BF16 ", | ||
| "exp_avg_sq_dtype": "fp8", | ||
| "main_params_dtype": "fp16", | ||
| "params_dtype": "float32", | ||
| "main_grads_dtype": "bfloat16", | ||
| "use_precision_aware_optimizer": True, | ||
| } | ||
|
|
||
| out = coerce_optimizer_dtype_kwargs(kwargs) | ||
|
|
||
| assert out == { | ||
| "exp_avg_dtype": torch.bfloat16, | ||
| "exp_avg_sq_dtype": torch.uint8, | ||
| "main_params_dtype": torch.float16, | ||
| "params_dtype": torch.float32, | ||
| "main_grads_dtype": torch.bfloat16, | ||
| "use_precision_aware_optimizer": True, | ||
| } | ||
| assert kwargs["exp_avg_dtype"] == " BF16 " | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "kwargs,match", | ||
| [ | ||
| ({"exp_avg_dtype": "bf17"}, "Unrecognized dtype name"), | ||
| ({"main_params_dtype": "bf16"}, "main_params_dtype"), | ||
| ], | ||
| ) | ||
| def test_rejects_unknown_or_field_illegal_dtype_names(kwargs, match): | ||
| with pytest.raises(ValueError, match=match): | ||
| coerce_optimizer_dtype_kwargs(kwargs) | ||
|
|
||
|
|
||
| def test_none_mapping_is_empty_but_none_field_values_pass_through(): | ||
| assert coerce_optimizer_dtype_kwargs(None) == {} | ||
| assert coerce_optimizer_dtype_kwargs({"main_grads_dtype": None}) == {"main_grads_dtype": None} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.