Repository navigation
feat(sglang): mxfp8 quantized rollout and refit #3614
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
Open
Kh4L
wants to merge
14
commits into
NVIDIA-NeMo:main
Choose a base branch
from
Kh4L:recut/sglang-mxfp8
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
34a4f3d
feat(sglang): mxfp8 quantized rollout and refit
xiuhu17 2773e9e
chore(sglang): satisfy the repo-pinned ruff formatter
Kh4L 833bd8d
fix(sglang): keep MoE routers in BF16, convert single-shard checkpoin…
Kh4L 5cb1672
fix(sglang): keep quantization config singular
Kh4L fa9106f
fix(sglang): require preconverted mxfp8 startup
Kh4L df1a35d
fix(sglang): backport non-gated fp8 moe sizing
Kh4L 878943f
fix(sglang): pad MXFP8 MoE scales for Triton
Kh4L 0718ac5
test(sglang): include quantization in controller fixture
Kh4L ffbf63d
fix(sglang): select MXFP8 backend before model load
Kh4L d5597e3
fix(sglang): pad Nemotron MXFP8 MoE hidden size
Kh4L 9d4b8c2
test(sglang): declare BF16 in fault-tolerance fixture
Kh4L 5babc80
test(sglang): update real BF16 fixtures
Kh4L 98e0fe4
chore(sglang): refresh MXFP8 rollout on current main
Kh4L 321e188
chore(sglang): refresh MXFP8 rollout against main
Kh4L 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
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
155 changes: 155 additions & 0 deletions
155
nemo_rl/models/generation/sglang/mxfp8_quantization_core.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,155 @@ | ||
| # Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| """Shared MXFP8 tensor quantization rules for SGLang rollout weight updates. | ||
|
|
||
| Offline conversion (``mxfp8_setup.py``) and the Megatron SGLang online-refit | ||
| path must call into this module so they make the exact same | ||
| quantization decision for any given HF tensor name. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from collections.abc import Iterable, Iterator | ||
| from typing import Any | ||
|
|
||
| import torch | ||
|
|
||
| SKIP_WEIGHT_SUBSTRINGS: tuple[str, ...] = ( | ||
| "layernorm", | ||
| "embed", | ||
| "router", | ||
| # A top-k router is a discrete argmax, so quantization error flips expert | ||
| # selection outright -- the one failure an RL rollout cannot absorb. Every | ||
| # MoE family spells it differently and only some contain "router": | ||
| # ``mlp.gate.`` (Qwen3-MoE, DeepSeek), ``block_sparse_moe.gate.`` | ||
| # (Mixtral), ``mixer.gate.`` (NemotronH/nanov3) and the separate | ||
| # ``shared_expert_gate`` (Qwen2-MoE). ``.gate.`` covers the first three as | ||
| # a class rather than enumerating families we happen to have seen. | ||
| # The dots are load-bearing: ``gate_proj``, ``gate_up_proj`` and | ||
| # ``shared_expert.gate_proj`` are ordinary MLP weights and stay quantized. | ||
| # The repo already draws this line -- see ``DEFAULT_NVFP4_IGNORE`` in | ||
| # ``nemo_rl/modelopt/utils.py`` and the nanov3 recipe's | ||
| # ``real_quant_ignore``. | ||
| ".gate.", | ||
| "shared_expert_gate.", | ||
| "norm", | ||
| "lm_head", | ||
| "eh_proj", | ||
| "weights_proj", | ||
| ) | ||
| TARGET_MXFP8_BLOCK_SIZE: list[int] = [1, 32] | ||
| # Suffix of the block-scale tensor emitted alongside each quantized weight. | ||
| MXFP8_SCALE_KEY_SUFFIX: str = ".weight_scale_inv" | ||
|
|
||
| MXFP8_QUANTIZATION_CONFIG: dict[str, Any] = { | ||
| "activation_scheme": "dynamic", | ||
| "fmt": "e4m3", | ||
| "quant_method": "mxfp8", | ||
| "weight_block_size": TARGET_MXFP8_BLOCK_SIZE, | ||
| "scale_fmt": "ue8m0", | ||
| } | ||
|
|
||
|
|
||
| def strip_weight_suffix(weight_key: str) -> str: | ||
| if not weight_key.endswith(".weight"): | ||
| raise ValueError(f"Expected key ending with '.weight', got: {weight_key}") | ||
| return weight_key[: -len(".weight")] | ||
|
|
||
|
|
||
| def is_mxfp8_quantization_config(config: dict[str, Any] | None) -> bool: | ||
| if not isinstance(config, dict): | ||
| return False | ||
| return ( | ||
| config.get("quant_method") == "mxfp8" | ||
| and list(config.get("weight_block_size", [])) == TARGET_MXFP8_BLOCK_SIZE | ||
| and config.get("scale_fmt") == "ue8m0" | ||
| ) | ||
|
|
||
|
|
||
| def is_bf16_source_checkpoint(cfg: dict[str, Any]) -> bool: | ||
| qcfg = cfg.get("quantization_config", {}) if isinstance(cfg, dict) else {} | ||
| if not isinstance(qcfg, dict) or not qcfg: | ||
| return True | ||
| return qcfg.get("quant_method") in (None, "", "bf16") | ||
|
|
||
|
|
||
| def should_quantize( | ||
| name: str, | ||
| weight: torch.Tensor, | ||
| *, | ||
| skip_weight_substrings: tuple[str, ...] = SKIP_WEIGHT_SUBSTRINGS, | ||
| ) -> bool: | ||
| allowed_dtypes: tuple[torch.dtype, ...] = ( | ||
| torch.float16, | ||
| torch.bfloat16, | ||
| torch.float32, | ||
| ) | ||
| if not name.endswith(".weight"): | ||
| return False | ||
| if any(substr in name for substr in skip_weight_substrings): | ||
| return False | ||
| if weight.dtype not in allowed_dtypes: | ||
| return False | ||
| if weight.dim() < 2: | ||
| return False | ||
| if weight.shape[-1] % 32 != 0: | ||
| return False | ||
| return True | ||
|
|
||
|
|
||
| def quantize_mxfp8(weight: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: | ||
| """Return ``(qweight, scale)`` in the SGLang MXFP8 layout. | ||
|
|
||
| Uses flashinfer's swizzle-free MXFP8 kernel | ||
| (``is_sf_swizzled_layout=False``). | ||
| """ | ||
| try: | ||
| from flashinfer import mxfp8_quantize as flashinfer_mxfp8_quantize | ||
| except ImportError as e: | ||
| raise ImportError( | ||
| "flashinfer is required for MXFP8 weight quantization but is not " | ||
| "installed in the current actor environment. In NeMo-RL this is " | ||
| "normally provided by the pinned `mcore` or `sglang` extras." | ||
| ) from e | ||
|
|
||
| weight = weight.contiguous() | ||
| k = weight.shape[-1] | ||
| if k % 32 != 0: | ||
| raise ValueError(f"Last dim {k} must be divisible by 32 for MXFP8.") | ||
|
|
||
| weight_flat = weight.view(-1, k).contiguous() | ||
| qweight, scale = flashinfer_mxfp8_quantize(weight_flat, is_sf_swizzled_layout=False) | ||
| qweight = qweight.view_as(weight) | ||
| scale = scale.view(*weight.shape[:-1], k // 32).contiguous() | ||
| return qweight, scale | ||
|
|
||
|
|
||
| def iter_mxfp8_quantized_tensor_groups( | ||
| named_tensors: Iterable[tuple[str, torch.Tensor]], | ||
| *, | ||
| skip_weight_substrings: tuple[str, ...], | ||
| ) -> Iterator[list[tuple[str, torch.Tensor]]]: | ||
| """Yield each HF tensor and any MXFP8 scale companion as one group.""" | ||
| for name, tensor in named_tensors: | ||
| if should_quantize( | ||
| name, | ||
| tensor, | ||
| skip_weight_substrings=skip_weight_substrings, | ||
| ): | ||
| qweight, scale = quantize_mxfp8(tensor) | ||
| scale_name = strip_weight_suffix(name) + MXFP8_SCALE_KEY_SUFFIX | ||
| yield [(name, qweight), (scale_name, scale)] | ||
| else: | ||
| yield [(name, tensor)] | ||
Oops, something went wrong.
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.