Add MXFP8 Support (#2910)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s

* Add MXFP8 Linear Layer

* Add MXFP8 Receipe

* Add MXFP8

* Refractor, remove constants, cleanup

* Remove import from local path

* Reformat

* Add MXFP8 expert parallel impl to support TorchAO's MXTensor in backward for all2all in MXFP8

* Build torchao from source for py3.12 MXFP8 CUDA kernel

Pin torchao to the pytorch/ao git source (rev 02105d4) and build its CUDA
kernels from source against the local torch cu128 / cpython-3.12. The PyPI
wheel ships the MXFP8 kernel as a cpython-310-only .so that fails to load on
prime-rl's Python 3.12, so torchao::mxfp8_quantize was never registered with a
CUDA backend and MXFP8 died in backward. Building from source produces a
cpython-312 extension (_C_mxfp8.cpython-312-*.so).

- no-build-isolation-package += torchao (build against local torch)
- extra-build-variables: CUDA_HOME=/usr/local/cuda-12.8,
  TORCH_CUDA_ARCH_LIST=10.0a (B200/sm_100a), USE_CPP=1

Enables the MXFP8 all-to-all and dense-linear paths (verified on 8xB200).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Relax torchao MXFP8 grouped-GEMM torch-nightly gate

torchao's _get_tensor_cls_for_config (added in pytorch/ao#4141, "require torch
nightly and cuda 12.8+", Mar 2026) asserts two post-2.11.0 DTensor symbols
(_ops.scaled_mm_single_dim_strategy, _dispatch.is_pinned_handler) exist, else
raises "install the latest torch nightly". This blanket-blocks all MXFP8 training,
but is over-broad for us: prime-rl's EP path pulls expert weights local
(.to_local()) before the grouped GEMM, so the DTensor scaled-mm strategy is never
hit, and current torch's non-single-dim scaled_mm_strategy covers the rest.

Neutralize just that assert (MXFP8 branch only) before quantize_, so
enable_grouped_gemm works on our pinned torch 2.11 without a nightly bump.

Verified 8xB200 SFT (GLM-0.5B, ep=8, grouped_gemm + a2a): 8/8 steps, all ranks;
numerics vs bf16 within mxfp8 range (out ~4.8%, grads ~6-7%) for both
mxfp8_rceil and mxfp8_rceil_wgrad_with_hp recipes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Use prebuilt torchao wheel from v0.6.0 release (x86_64)

Replace the torchao build-from-source git dependency with the prebuilt
cp312 CUDA wheel hosted on the prime-rl v0.6.0 release, matching how
deep-ep / deep-gemm / nixl-cu12 are shipped. Avoids requiring the CUDA
toolchain at install time on x86_64.

- torchao source -> release wheel URL, scoped to platform_machine == 'x86_64'
  (aarch64 continues to resolve torchao from the default index, untouched)
- drop torchao from no-build-isolation-package + the extra-build-variables block
- add torchao to the exclude-newer-package trusted-sources list

Wheel is H100 (sm90a) + B200 (sm100a), built from pytorch/ao@02105d4,
verified in a fresh py3.12 env (mxfp8 op registers, a2a imports).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Sort imports in expert_parallel.py (ruff I001)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Fix comments

* Fix alignment of 32 for grouped gemm backward

* Apply Samis Suggestions

* Add back default ignore patterns

* Fix name bug

* Reformat with ruff

* Config verifier

* Fix kernel redirect for > 32 token groups

* Ruff reformat

* chore: update uv.lock for torchao dependency

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* style: fix import sorting in MXFP8 files

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Move config check to config code

* Fix ruff

* Move config check to trainer

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Neo
2026-07-17 01:26:22 +02:00
committed by GitHub
co-authored by Claude Opus 4.8
parent 4d8df5120e
commit d7bcd1b1f5
11 changed files with 422 additions and 35 deletions
+15 -1
View File
@@ -36,7 +36,21 @@ impl = "custom" # or "hf" to force the HF path
| GLM-4 / GLM-4.5 / INTELLECT-3 | `THUDM/GLM-4-9B-0414`, `zai-org/GLM-4.5`, `PrimeIntellect/INTELLECT-3`, … | ✅ | ✅ |
| GPT-OSS (HF MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | ❌ | ✅ |
The custom path enables you to set EP, CP, selective activation checkpointing, FP8 training (`model.fp8 = true`, requires SM90+), and faster MoE kernels (`moe_use_grouped_mm = true`, default). Forcing `impl = "hf"` is mostly useful when debugging — it's slower and disables most MoE-specific knobs.
The custom path enables you to set EP, CP, selective activation checkpointing, low-precision training (`[trainer.model.quantization]`), and faster MoE kernels (`moe_use_grouped_mm = true`, default). Forcing `impl = "hf"` is mostly useful when debugging — it's slower and disables most MoE-specific knobs.
### Low-precision training
Set `[trainer.model.quantization]` to train dense linears and MoE expert GEMMs in low precision. Two backends are available via the `type` discriminator:
- `type = "fp8"` — DeepGEMM FP8 blockwise (requires SM90+ / Hopper). Options: `enable_grouped_gemm` (FP8 MoE expert GEMM). Both default on.
- `type = "mxfp8"` — torchao MXFP8 microscaling (requires SM100+ / Blackwell). Options: `enable_grouped_gemm`, `enable_a2a` (MXFP8 expert-parallel all-to-all), and `recipe` (`mxfp8_rceil` default or `mxfp8_rceil_wgrad_with_hp`).
```toml
[trainer.model.quantization]
type = "mxfp8"
recipe = "mxfp8_rceil"
enable_a2a = true
```
GLM-5.2 adds IndexShare: the DSA sparse-attention indexer runs only on a subset of layers and the remaining layers reuse the cached top-k indices. The trainer reads this schedule from the model's `indexer_types` config field and enables the index cache automatically, so no extra config is needed. To override the schedule manually, set `[trainer.model.index_cache]` (`topk_freq` or `topk_pattern`).
+3 -1
View File
@@ -61,7 +61,9 @@ fused_lm_head_token_chunk_size = 1024
cp = 4 # context parallel for the 131K seq len
ep = 8
optim_cpu_offload = true
fp8 = true
[trainer.model.quantization]
type = "fp8"
[trainer.model.ac]
freq = 1
@@ -116,6 +116,42 @@ class DebugModelConfig(BaseConfig):
"""Replace MoE token-choice routing with a round-robin assignment so every expert sees an equal share. Intended for fake-data smoke tests where untrained routing would otherwise OOM under severe imbalance. Gating scores are still gathered from the override indices so the forward pass stays consistent."""
MXFP8Recipe: TypeAlias = Literal["mxfp8_rceil", "mxfp8_rceil_wgrad_with_hp"]
_DEFAULT_FP8_IGNORE_PATTERNS: list[str] = [
"lm_head",
"router",
# Use escaped dots — re.search treats `.` as any-char, so the previous
# "mlp.gate." pattern was also matching dense MLP `mlp.gate_proj` (the
# trailing `.` was matching `_`). That left the dense MLP gate projection
# in BF16 on the trainer while inference quantized it to FP8, causing
# hidden-state drift before the MoE router.
r"mlp\.gate\.",
"shared_expert_gate", # Qwen3.5 MoE: nn.Linear(hidden, 1, bias=False)
"eh_proj",
"weights_proj",
"in_proj_a",
"in_proj_b",
]
class FP8Config(BaseConfig):
type: Literal["fp8"] = "fp8"
enable_grouped_gemm: bool = True
ignore_patterns: list[str] = _DEFAULT_FP8_IGNORE_PATTERNS
class MXFP8Config(BaseConfig):
type: Literal["mxfp8"] = "mxfp8"
recipe: MXFP8Recipe = "mxfp8_rceil"
enable_grouped_gemm: bool = True
enable_a2a: bool = True
ignore_patterns: list[str] = _DEFAULT_FP8_IGNORE_PATTERNS
QuantizationConfig: TypeAlias = Annotated[FP8Config | MXFP8Config, Field(discriminator="type")]
class ModelConfig(BaseModelConfig):
conversion_dir: Path | None = None
"""Directory for the auto-converted weights (written to a `prime`/`hf` subdirectory). If not set, we write into the model snapshot directory."""
@@ -180,8 +216,7 @@ class ModelConfig(BaseModelConfig):
moe_use_grouped_mm: bool = True
"""Use grouped mm for MoE layers. Requires compute capability ≥ 9.0."""
fp8: bool = False
"""FP8 training via DeepGEMM. Replaces ``nn.Linear`` with FP8 blockwise linear and uses FP8 grouped GEMM for MoE experts. Requires SM90 (Hopper) GPUs and ``model.impl='custom'``."""
quantization: QuantizationConfig | None = None
index_cache: IndexCacheConfig | None = None
"""DSA IndexCache sub-configuration. If set, sparse-attention top-k indices are reused across decoder layers per the configured schedule (mirrors vLLM's IndexCache HF overrides). If None, every layer recomputes its own indices."""
@@ -255,9 +290,9 @@ class ModelConfig(BaseModelConfig):
return self
@model_validator(mode="after")
def fp8_only_with_custom_impl(self):
if self.fp8 and self.impl not in ("custom", "auto"):
raise ValueError("FP8 training is only supported with model.impl='custom' or 'auto'.")
def quantization_only_with_custom_impl(self):
if self.quantization is not None and self.impl not in ("custom", "auto"):
raise ValueError(f"{self.quantization.type} training is only supported with model.impl='custom' or 'auto'.")
return self
@model_validator(mode="after")
@@ -270,6 +305,12 @@ class ModelConfig(BaseModelConfig):
return self
@model_validator(mode="after")
def mxfp8_only_with_torch_ep_backend(self):
if isinstance(self.quantization, MXFP8Config) and self.ep_comm_backend != "torch":
raise ValueError("MXFP8 quantization requires model.ep_comm_backend='torch'.")
return self
class TokenizerConfig(BaseConfig):
name: str | None = None
+3
View File
@@ -44,6 +44,7 @@ dependencies = [
"orjson>=3.10",
"pandas>=2.0",
"msgspec>=0.18",
"torchao>=0.17.0",
]
[project.scripts]
@@ -179,6 +180,7 @@ dion = false
deep-ep = false
deep-gemm = false
nixl-cu12 = false
torchao = false
[tool.uv.sources]
prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
@@ -193,6 +195,7 @@ torch = { index = "pytorch-cu128" }
torchvision = { index = "pytorch-cu128" }
torchaudio = { index = "pytorch-cu128" }
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "23e4dfc" }
torchao = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.6.0/torchao-0.17.0+git02105d46c-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" }
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
vllm-router = [
+2 -2
View File
@@ -1,3 +1,3 @@
from prime_rl.trainer.distributed.expert_parallel import DeepEPExpertParallel, get_ep_group
from prime_rl.trainer.distributed.expert_parallel import DeepEPExpertParallel, MXFP8AllToAllExpertParallel, get_ep_group
__all__ = ["DeepEPExpertParallel", "get_ep_group"]
__all__ = ["DeepEPExpertParallel", "MXFP8AllToAllExpertParallel", "get_ep_group"]
@@ -1,7 +1,67 @@
import torch
import torch.distributed as dist
import torch.nn as nn
from torch.distributed import ProcessGroup
from torch.distributed.distributed_c10d import _resolve_process_group
from torch.distributed.tensor import DeviceMesh, Shard, distribute_module, distribute_tensor
from torch.distributed.tensor.parallel import ParallelStyle
from torchao.prototype.moe_training.ep import a2a_combine_hp_fwd_mxfp8_bwd, a2a_dispatch_mxfp8_fwd_hp_bwd
from torchao.prototype.mx_formats.mx_tensor import MXTensor
from torchtitan.distributed.expert_parallel import ExpertParallel
class _MXFP8Dispatch(torch.autograd.Function):
@staticmethod
def forward(ctx, routed_input, output_splits, input_splits, group_name):
mx_routed_input = a2a_dispatch_mxfp8_fwd_hp_bwd(routed_input, output_splits, input_splits, group_name)
ctx.input_splits = input_splits
ctx.output_splits = output_splits
ctx.group = _resolve_process_group(group_name)
return mx_routed_input.dequantize(routed_input.dtype)
@staticmethod
def backward(ctx, grad_output):
grad_input = grad_output.new_empty((sum(ctx.input_splits),) + tuple(grad_output.shape[1:]))
dist.all_to_all_single(
grad_input, grad_output.contiguous(), ctx.input_splits, ctx.output_splits, group=ctx.group
)
return grad_input, None, None, None
class _DequantMXGradInBwd(torch.autograd.Function):
@staticmethod
def forward(ctx, x, hp_dtype):
ctx.hp_dtype = hp_dtype
return x
@staticmethod
def backward(ctx, grad_output):
if isinstance(grad_output, MXTensor):
grad_output = grad_output.dequantize(ctx.hp_dtype)
return grad_output, None
class MXFP8AllToAllExpertParallel(ExpertParallel):
def _token_dispatch(self, mod, inputs, device_mesh):
routed_input, num_tokens_per_expert = inputs
with torch.no_grad():
num_tokens_per_expert_group = num_tokens_per_expert.new_empty(num_tokens_per_expert.shape[0])
dist.all_to_all_single(num_tokens_per_expert_group, num_tokens_per_expert, group=device_mesh.get_group())
self.input_splits = num_tokens_per_expert.view(device_mesh.shape[0], -1).sum(dim=1).tolist()
self.output_splits = num_tokens_per_expert_group.view(device_mesh.shape[0], -1).sum(dim=1).tolist()
routed_input = _MXFP8Dispatch.apply(
routed_input, self.output_splits, self.input_splits, device_mesh.get_group().group_name
)
return routed_input, num_tokens_per_expert_group
def _token_combine(self, mod, routed_output, device_mesh):
routed_output = _DequantMXGradInBwd.apply(routed_output, routed_output.dtype)
return a2a_combine_hp_fwd_mxfp8_bwd(
routed_output,
self.input_splits,
self.output_splits,
device_mesh.get_group().group_name,
)
class DeepEPExpertParallel(ParallelStyle):
+48 -6
View File
@@ -26,8 +26,15 @@ from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, Genera
from transformers.tokenization_utils import PreTrainedTokenizer
from transformers.utils.import_utils import is_flash_attn_3_available
from prime_rl.configs.trainer import ActivationCheckpointConfig, CompileConfig, ModelConfig, TokenizerConfig
from prime_rl.trainer.distributed import DeepEPExpertParallel
from prime_rl.configs.trainer import (
ActivationCheckpointConfig,
CompileConfig,
FP8Config,
ModelConfig,
MXFP8Config,
TokenizerConfig,
)
from prime_rl.trainer.distributed import DeepEPExpertParallel, MXFP8AllToAllExpertParallel
from prime_rl.trainer.lora import apply_lora_to_model, freeze_all_except_lora_and_specified, strip_lora_from_state_dict
from prime_rl.trainer.models import (
AutoModelForCausalLMPrimeRL,
@@ -46,6 +53,8 @@ from prime_rl.trainer.models.layers.checkpointing import (
from prime_rl.trainer.models.layers.fp8_linear import replace_linear_with_fp8_blockwise_linear
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.trainer.models.layers.moe import LatentMoE, MoE, TokenChoiceTopKRouter
from prime_rl.trainer.models.layers.mxfp8_grouped_gemm import apply_mxfp8_moe_grouped_gemm
from prime_rl.trainer.models.layers.mxfp8_linear import replace_linear_with_mxfp8_linear
from prime_rl.trainer.parallel_dims import ParallelDims
from prime_rl.trainer.weights import (
load_state_dict,
@@ -527,7 +536,11 @@ def get_model(
if subconfig is not None and hasattr(subconfig, "use_cache"):
subconfig.use_cache = False
model_config.use_grouped_mm = config.moe_use_grouped_mm
model_config.fp8 = config.fp8
# MoEArgs.fp8 (read via getattr(config, "fp8") in the modeling files) gates the
# DeepGEMM FP8 grouped GEMM. MXFP8 grouped GEMM is applied by wrapping the expert
# weights with torchao (see apply_quantization), so it leaves this flag False and
# the experts keep calling torch._grouped_mm — which the wrapper tensor intercepts.
model_config.fp8 = isinstance(config.quantization, FP8Config) and config.quantization.enable_grouped_gemm
if config.index_cache is not None:
model_config.use_index_cache = True
@@ -1037,13 +1050,43 @@ def apply_compile(model: nn.Module, compile_config: CompileConfig):
get_logger().info(f"Compiled {len(language_model.layers)} layers (fullgraph={compile_config.fullgraph})")
def apply_quantization(model: nn.Module, config: ModelConfig) -> None:
"""Swap dense linears and MoE expert GEMMs to the configured low-precision path.
Runs after the LM head is injected but before LoRA / EP / FSDP so the swapped
modules and wrapped parameters are picked up by the later parallelisms. The
FP8 grouped GEMM (DeepGEMM) is gated separately via ``model_config.fp8`` since
it lives inside the modeling code; here we only handle the dense-linear swap
and the torchao MXFP8 expert-weight wrapping.
"""
quant = config.quantization
if quant is None:
return
if isinstance(quant, FP8Config):
replace_linear_with_fp8_blockwise_linear(model, ignore_modules=quant.ignore_patterns)
elif isinstance(quant, MXFP8Config):
capability = torch.cuda.get_device_capability()
if capability < (10, 0):
raise ValueError(
f"MXFP8 quantization requires SM100 (Blackwell) or newer, but device is SM{capability[0]}{capability[1]}."
)
replace_linear_with_mxfp8_linear(model, recipe=quant.recipe, ignore_modules=quant.ignore_patterns)
if quant.enable_grouped_gemm:
apply_mxfp8_moe_grouped_gemm(model, recipe=quant.recipe)
def apply_ep(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDims):
language_model = get_language_model(model)
for transformer_block in language_model.layers:
block_mlp = getattr(transformer_block, "mlp", None)
if block_mlp is not None and isinstance(block_mlp, (MoE, LatentMoE)):
if config.ep_comm_backend == "torch":
parallelize_plan = ExpertParallel()
quant = config.quantization
if isinstance(quant, MXFP8Config) and quant.enable_a2a:
parallelize_plan = MXFP8AllToAllExpertParallel()
else:
parallelize_plan = ExpertParallel()
else:
parallelize_plan = DeepEPExpertParallel()
parallelize_module(
@@ -1144,8 +1187,7 @@ def setup_model(
inject_prime_lm_head(model, chunk_size=lm_head_chunk_size, fused_cross_entropy=fused_cross_entropy)
if config.fp8:
replace_linear_with_fp8_blockwise_linear(model)
apply_quantization(model, config)
# Apply LoRA before FSDP setup
if config.lora is not None:
@@ -110,24 +110,7 @@ class Float8BlockwiseLinear(nn.Linear):
return new_mod
DEFAULT_FP8_IGNORE_PATTERNS: list[str] = [
"lm_head",
"router",
# Use escaped dots — re.search treats `.` as any-char, so the previous
# "mlp.gate." pattern was also matching dense MLP `mlp.gate_proj` (the
# trailing `.` was matching `_`). That left the dense MLP gate projection
# in BF16 on the trainer while inference quantized it to FP8, causing
# hidden-state drift before the MoE router.
r"mlp\.gate\.",
"shared_expert_gate", # Qwen3.5 MoE: nn.Linear(hidden, 1, bias=False)
"eh_proj",
"weights_proj",
"in_proj_a",
"in_proj_b",
]
def replace_linear_with_fp8_blockwise_linear(model: nn.Module, ignore_modules: list[str] | None = None) -> None:
def replace_linear_with_fp8_blockwise_linear(model: nn.Module, ignore_modules: list[str]) -> None:
"""Replace nn.Linear in `model` with Float8BlockwiseLinear, skipping any
module whose qualified name matches an ignore pattern (substring or regex).
@@ -147,8 +130,6 @@ def replace_linear_with_fp8_blockwise_linear(model: nn.Module, ignore_modules: l
Conv1d, layer norms, and embedding tables are not nn.Linear and are
skipped automatically by the type check; we don't need to list them.
"""
if ignore_modules is None:
ignore_modules = list(DEFAULT_FP8_IGNORE_PATTERNS)
logger = get_logger()
logger.info(f"Replacing linear layers with FP8 blockwise linear layers (ignore={ignore_modules})")
replaced_modules = []
@@ -0,0 +1,88 @@
from __future__ import annotations
import torch
from torch import nn
from torchao.prototype.moe_training import conversion_utils as cu
from torchao.prototype.moe_training import mxfp8_grouped_mm as tao_mxfp8_gmm
from torchao.prototype.moe_training.config import MXFP8TrainingOpConfig, MXFP8TrainingRecipe
from torchao.prototype.moe_training.kernels.mxfp8 import triton_mx_block_rearrange_2d_M_groups
from torchao.prototype.moe_training.tensor import MXFP8TrainingWeightWrapperTensor
from torchao.quantization.quant_api import quantize_
from torchtitan.distributed.expert_parallel import set_token_group_alignment_size_m
from torchtitan.experiments.kernels.moe import indices as tt_indices
from prime_rl.configs.trainer import MXFP8Recipe
from prime_rl.trainer.models.layers.moe import GroupedExperts, NonGatedGroupedExperts
from prime_rl.utils.logger import get_logger
_MXFP8_TOKEN_GROUP_ALIGN: int = 32
# torchao CUDA scale rearrange kernel supports at most 32 token groups,
# the Triton variant has no such cap and produces the same swizzled layout, so fall back to it for wider MoEs
_CUDA_REARRANGE_MAX_GROUPS: int = 32
def _fallback_to_triton_rearrange_for_wide_moes() -> None:
if getattr(tao_mxfp8_gmm.mx_block_rearrange_2d_M_groups_cuda, "_prime_rl_wide_moe", False):
return
original = tao_mxfp8_gmm.mx_block_rearrange_2d_M_groups_cuda
def mx_block_rearrange_2d_M_groups(
scales_tensor: torch.Tensor, input_group_end_offsets: torch.Tensor, chunks_per_tb: int = 4
) -> torch.Tensor:
if input_group_end_offsets.shape[0] > _CUDA_REARRANGE_MAX_GROUPS:
return triton_mx_block_rearrange_2d_M_groups(scales_tensor, input_group_end_offsets)
return original(scales_tensor, input_group_end_offsets, chunks_per_tb)
mx_block_rearrange_2d_M_groups._prime_rl_wide_moe = True
tao_mxfp8_gmm.mx_block_rearrange_2d_M_groups_cuda = mx_block_rearrange_2d_M_groups
def _relax_torchao_mxfp8_version_gate() -> None:
if getattr(cu._get_tensor_cls_for_config, "_prime_rl_relaxed", False):
return
original = cu._get_tensor_cls_for_config
def _get_tensor_cls_for_config(config):
if isinstance(config, MXFP8TrainingOpConfig):
return MXFP8TrainingWeightWrapperTensor
return original(config)
_get_tensor_cls_for_config._prime_rl_relaxed = True
cu._get_tensor_cls_for_config = _get_tensor_cls_for_config
def _align_permute_indices_buffer() -> None:
"""
Align the permuted index buffer to a multiple of alignment as the kernel requires rows % 32 = 0 and cols % 32 = 0.
"""
if getattr(tt_indices.generate_permute_indices, "_prime_rl_aligned", False):
return
original = tt_indices.generate_permute_indices
def generate_permute_indices(
tokens_per_expert_group, experts_per_rank, num_ranks, max_len, alignment, use_cpu=False
):
al_mask = alignment - 1
assert alignment > 0 and (alignment & al_mask) == 0
max_len = (max_len + al_mask) & ~al_mask
return original(tokens_per_expert_group, experts_per_rank, num_ranks, max_len, alignment, use_cpu=use_cpu)
generate_permute_indices._prime_rl_aligned = True
tt_indices.generate_permute_indices = generate_permute_indices
def apply_mxfp8_moe_grouped_gemm(model: nn.Module, recipe: MXFP8Recipe) -> None:
_relax_torchao_mxfp8_version_gate()
_align_permute_indices_buffer()
_fallback_to_triton_rearrange_for_wide_moes()
set_token_group_alignment_size_m(_MXFP8_TOKEN_GROUP_ALIGN)
op_config = MXFP8TrainingOpConfig.from_recipe(MXFP8TrainingRecipe(recipe))
def filter_fn(module: nn.Module, fqn: str) -> bool:
return isinstance(module, (GroupedExperts, NonGatedGroupedExperts))
quantize_(model, config=op_config, filter_fn=filter_fn)
get_logger().info(
f"Wrapped MoE expert weights with MXFP8 grouped GEMM (recipe={recipe}, "
f"token_group_align={_MXFP8_TOKEN_GROUP_ALIGN})"
)
@@ -0,0 +1,99 @@
from __future__ import annotations
import re
import torch
from torch import nn
from torchao.prototype.mx_formats import ScaleCalculationMode
from torchao.prototype.mx_formats.mx_linear import _to_mxfp8_then_scaled_mm
from torchao.quantization.quantize_.common import KernelPreference
from prime_rl.configs.trainer import MXFP8Recipe
from prime_rl.utils.logger import get_logger
class MXFP8Linear(nn.Linear):
def __init__(
self,
in_features: int,
out_features: int,
bias: bool = True,
*,
kernel_preference: KernelPreference = KernelPreference.AUTO,
wgrad_with_hp: bool = False,
scale_calculation_mode: ScaleCalculationMode = ScaleCalculationMode.RCEIL,
device=None,
dtype=None,
) -> None:
super().__init__(in_features, out_features, bias, device=device, dtype=dtype)
self.kernel_preference = kernel_preference
self.wgrad_with_hp = wgrad_with_hp
self.scale_calculation_mode = scale_calculation_mode
def forward(self, input: torch.Tensor) -> torch.Tensor:
output = _to_mxfp8_then_scaled_mm(
input,
self.weight,
self.kernel_preference,
self.scale_calculation_mode,
wgrad_with_hp=self.wgrad_with_hp,
)
if self.bias is not None:
output = output + self.bias
return output
@classmethod
def from_linear(
cls,
mod: nn.Linear,
*,
kernel_preference: KernelPreference = KernelPreference.AUTO,
wgrad_with_hp: bool = False,
scale_calculation_mode: ScaleCalculationMode = ScaleCalculationMode.RCEIL,
) -> "MXFP8Linear":
with torch.device("meta"):
new_mod = cls(
mod.in_features,
mod.out_features,
bias=mod.bias is not None,
kernel_preference=kernel_preference,
wgrad_with_hp=wgrad_with_hp,
scale_calculation_mode=scale_calculation_mode,
)
new_mod.weight = mod.weight
new_mod.bias = mod.bias
return new_mod
def replace_linear_with_mxfp8_linear(model: nn.Module, recipe: MXFP8Recipe, ignore_modules: list[str]) -> None:
wgrad_with_hp = recipe == "mxfp8_rceil_wgrad_with_hp"
logger = get_logger()
logger.info(f"Replacing linear layers with MXFP8 linear layers (recipe={recipe}, ignore={ignore_modules})")
replaced_modules: list[str] = []
skipped_modules: list[str] = []
skipped_unaligned: list[str] = []
for name, module in dict(model.named_modules()).items():
if not isinstance(module, nn.Linear):
continue
if any(re.search(pattern, name) for pattern in ignore_modules):
skipped_modules.append(name)
continue
if (module.in_features & 31) != 0 or (module.out_features & 31) != 0:
skipped_unaligned.append(f"{name}({module.in_features}->{module.out_features})")
continue
parent_name, attr_name = name.rsplit(".", 1) if "." in name else ("", name)
parent = model.get_submodule(parent_name) if parent_name else model
setattr(
parent,
attr_name,
MXFP8Linear.from_linear(module, kernel_preference=KernelPreference.AUTO, wgrad_with_hp=wgrad_with_hp),
)
replaced_modules.append(name)
logger.info(
f"Replaced {len(replaced_modules)} linear layers with MXFP8 linear "
f"(skipped {len(skipped_modules)} by name, {len(skipped_unaligned)} by 32-div); "
f"first replaced={replaced_modules[:3]}, "
f"first skipped(name)={skipped_modules[:3]}, "
f"first skipped(unaligned)={skipped_unaligned[:3]}"
)
Generated
+57
View File
@@ -26,6 +26,7 @@ flash-attn-3 = false
prime-tunnel = false
deep-gemm = false
prime-evals = false
torchao = false
tokenspeed-mla = false
deep-ep = false
prime-sandboxes = false
@@ -4949,6 +4950,8 @@ dependencies = [
{ name = "tenacity" },
{ name = "tilelang" },
{ name = "torch" },
{ name = "torchao", version = "0.17.0", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine != 'x86_64'" },
{ name = "torchao", version = "0.17.0+git02105d46c", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.6.0/torchao-0.17.0+git02105d46c-cp312-cp312-linux_x86_64.whl" }, marker = "platform_machine == 'x86_64'" },
{ name = "torchaudio" },
{ name = "torchdata" },
{ name = "torchtitan" },
@@ -5068,6 +5071,8 @@ requires-dist = [
{ name = "tenacity", specifier = ">=8.2.0" },
{ name = "tilelang", specifier = ">=0.1.8" },
{ name = "torch", specifier = ">=2.9.0", index = "https://download.pytorch.org/whl/cu128" },
{ name = "torchao", marker = "platform_machine != 'x86_64'", specifier = ">=0.17.0" },
{ name = "torchao", marker = "platform_machine == 'x86_64'", url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.6.0/torchao-0.17.0+git02105d46c-cp312-cp312-linux_x86_64.whl" },
{ name = "torchaudio", index = "https://download.pytorch.org/whl/cu128" },
{ name = "torchdata", specifier = ">=0.11.0" },
{ name = "torchtitan", git = "https://github.com/pytorch/torchtitan?rev=23e4dfc" },
@@ -7183,6 +7188,58 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/e2/79/a914539b4785f3e44f891aa012a886edb8bc10fe081c440981c57543ce21/torch_c_dlpack_ext-0.1.5-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e6f9da4bb9af70e27facc777458be62e10dbbbddda7672d16138db0553c5a524", size = 897846, upload-time = "2026-01-12T11:24:48.168Z" },
]
[[package]]
name = "torchao"
version = "0.17.0"
source = { registry = "https://pypi.org/simple" }
resolution-markers = [
"platform_machine == 'aarch64' and sys_platform == 'linux'",
]
wheels = [
{ url = "https://files.pythonhosted.org/packages/c9/37/ef37ca885265e5f79a168616767dd416a3cea1cc3b28bb6b503ce4a5b652/torchao-0.17.0-py3-none-any.whl", hash = "sha256:02eba449036715b9ae784fbaa1a6f97994bb7b0421ce92d1d5d1c08e5bd6d349", size = 1200680, upload-time = "2026-03-30T22:25:54.457Z" },
]
[[package]]
name = "torchao"
version = "0.17.0+git02105d46c"
source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.6.0/torchao-0.17.0+git02105d46c-cp312-cp312-linux_x86_64.whl" }
resolution-markers = [
"platform_machine == 'x86_64' and sys_platform == 'linux'",
]
wheels = [
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.6.0/torchao-0.17.0+git02105d46c-cp312-cp312-linux_x86_64.whl", hash = "sha256:899ee5ac05292a5ffac1e44817c524b63fff850c6d5f679d3087f6770ba628c6" },
]
[package.metadata]
requires-dist = [
{ name = "bitsandbytes", marker = "extra == 'dev'" },
{ name = "blobfile", marker = "extra == 'dev'" },
{ name = "cmake", marker = "extra == 'dev'", specifier = ">=3.19.0,<4.0.0" },
{ name = "diskcache", marker = "extra == 'dev'" },
{ name = "expecttest", marker = "extra == 'dev'" },
{ name = "fire", marker = "extra == 'dev'" },
{ name = "hypothesis", marker = "extra == 'dev'" },
{ name = "importlib-metadata", marker = "extra == 'dev'" },
{ name = "lm-eval", marker = "extra == 'dev'" },
{ name = "matplotlib", marker = "extra == 'dev'" },
{ name = "ninja", marker = "extra == 'dev'" },
{ name = "packaging", marker = "extra == 'dev'" },
{ name = "pandas", marker = "extra == 'dev'" },
{ name = "parameterized", marker = "extra == 'dev'" },
{ name = "pre-commit", marker = "extra == 'dev'" },
{ name = "pycocotools", marker = "extra == 'dev'" },
{ name = "pytest", marker = "extra == 'dev'", specifier = "==8.4.2" },
{ name = "pyyaml", marker = "extra == 'dev'" },
{ name = "ruff", marker = "extra == 'dev'", specifier = "==0.11.6" },
{ name = "sentencepiece", marker = "extra == 'dev'" },
{ name = "tabulate", marker = "extra == 'dev'" },
{ name = "tiktoken", marker = "extra == 'dev'" },
{ name = "tqdm", marker = "extra == 'dev'" },
{ name = "transformers", marker = "extra == 'dev'" },
{ name = "unittest-xml-reporting", marker = "extra == 'dev'" },
]
provides-extras = ["dev"]
[[package]]
name = "torchaudio"
version = "2.11.0+cu128"