From e3c24ae463bfc0214663f1cda916c4795f2beaae Mon Sep 17 00:00:00 2001 From: Ilyas Moutawwakil Date: Tue, 27 Oct 2026 06:17:09 -0700 Subject: [PATCH 1/3] MXFP4 GPT-OSS experts take routed tokens, so expert parallelism runs on `ep_dispatch_experts` `Mxfp4GptOssExperts.forward` takes `(hidden_states, top_k_index, top_k_weights)` like every other experts class and builds the Triton routing metadata for its own experts from them (`routing_from_top_k`), skipping other ranks' routes. Under expert parallelism the patched MLP calls the router, then the experts, so every `ep_strategy` applies; single-device inference keeps the fused Triton routing through `forward_routed`. Replaces `routing_torch_dist`, which picked the local experts from `LOCAL_RANK` and the world size rather than the EP mesh. Co-Authored-By: Claude Opus 5.5 --- src/transformers/integrations/mxfp4.py | 111 ++++++++++--------------- 1 file changed, 42 insertions(+), 69 deletions(-) diff --git a/src/transformers/integrations/mxfp4.py b/src/transformers/integrations/mxfp4.py index a6908efdd345..adaa5b77ff3c 100644 --- a/src/transformers/integrations/mxfp4.py +++ b/src/transformers/integrations/mxfp4.py @@ -342,7 +342,16 @@ def __init__(self, config): self.down_proj_precision_config = None self.limit = getattr(config, "swiglu_limit", 7.0) - def forward(self, hidden_states: torch.Tensor, routing_data, gather_idx, scatter_idx) -> torch.Tensor: + def forward( + self, hidden_states: torch.Tensor, top_k_index: torch.Tensor, top_k_weights: torch.Tensor + ) -> torch.Tensor: + """Experts on `top_k_index` ids in `[0, num_experts)`; other ids (another rank's routes under expert + parallelism) are skipped.""" + with on_device(hidden_states.device): + routing_data, gather_idx, scatter_idx = routing_from_top_k(top_k_index, top_k_weights, self.num_experts) + return self.forward_routed(hidden_states, routing_data, gather_idx, scatter_idx) + + def forward_routed(self, hidden_states: torch.Tensor, routing_data, gather_idx, scatter_idx) -> torch.Tensor: FnSpecs, FusedActivation, matmul_ogs = ( triton_kernels_hub.matmul_ogs.FnSpecs, triton_kernels_hub.matmul_ogs.FusedActivation, @@ -378,72 +387,36 @@ def forward(self, hidden_states: torch.Tensor, routing_data, gather_idx, scatter # Adapted from GPT_OSS repo # TODO: Add absolute link when the repo is public -def routing_torch_dist( - logits, - n_expts_act, -): - import os - +def routing_from_top_k(top_k_index, top_k_weights, num_experts): + """Triton routing metadata for `num_experts` experts from routes already selected: `top_k_index` holds expert ids + in `[0, num_experts)` and `top_k_weights` their weights; routes outside that range are skipped.""" GatherIndx, RoutingData, ScatterIndx, compute_expt_data_torch = ( triton_kernels_hub.routing.GatherIndx, triton_kernels_hub.routing.RoutingData, triton_kernels_hub.routing.ScatterIndx, triton_kernels_hub.routing.compute_expt_data_torch, ) + replace_value = -1 + num_tokens, num_top_k = top_k_index.shape - with on_device(logits.device): - world_size = torch.distributed.get_world_size() - rank = int(os.environ.get("LOCAL_RANK", "0")) - replace_value = -1 - - n_tokens = logits.shape[0] - n_expts_tot = logits.shape[1] - - n_local_experts = n_expts_tot // world_size - local_expert_start = rank * n_local_experts - local_expert_end = (rank + 1) * n_local_experts - - n_gates_pad = n_tokens * n_expts_act - - def topk(vals, k): - tk_indx = torch.argsort(-vals, dim=1, stable=True)[:, :k] - tk_indx = tk_indx.long() - tk_val = torch.take_along_dim(vals, tk_indx, dim=1) - return tk_val, tk_indx.int() - - expt_scal, expt_indx = topk(logits, n_expts_act) - expt_scal = torch.softmax(expt_scal, dim=-1) - expt_indx, sort_indices = torch.sort(expt_indx, dim=1) - expt_scal = torch.gather(expt_scal, 1, sort_indices) - - # Flatten and mask for local experts - expt_scal = expt_scal.reshape(-1) - - hist = torch.histc(expt_indx, bins=n_expts_tot, max=n_expts_tot - 1)[local_expert_start:local_expert_end] - - expt_indx = expt_indx.view(-1).to(torch.int32) - - # we use a large value to replace the indices that are not in the local expert range - var = 1000 - expt_indx = torch.where(expt_indx < local_expert_start, var, expt_indx) - topk_indx = torch.argsort(expt_indx, stable=True).to(torch.int32) - gate_indx = torch.argsort(topk_indx).to(torch.int32) - expt_indx = torch.where(expt_indx < local_expert_end, expt_indx, replace_value) - expt_indx = torch.where(local_expert_start <= expt_indx, expt_indx, replace_value) + expt_indx, sort_indices = torch.sort(top_k_index.to(torch.int32), dim=1) + expt_scal = torch.gather(top_k_weights, 1, sort_indices).reshape(-1) + # out-of-range ids fall outside the histogram's bins, so only this module's experts are counted + hist = torch.histc(expt_indx, bins=num_experts, min=0, max=num_experts - 1) - gate_indx = torch.where(expt_indx == replace_value, replace_value, gate_indx) - gate_scal = expt_scal[topk_indx] + expt_indx = expt_indx.view(-1) + local = (expt_indx >= 0) & (expt_indx < num_experts) + # the skipped routes sort after every expert's + topk_indx = torch.argsort(torch.where(local, expt_indx, num_experts), stable=True).to(torch.int32) + gate_indx = torch.argsort(topk_indx).to(torch.int32) + gate_indx = torch.where(local, gate_indx, replace_value) + gate_scal = expt_scal[topk_indx] + topk_indx = torch.where(gate_indx[topk_indx] == replace_value, replace_value, topk_indx) - topk_indx = torch.where(gate_indx[topk_indx] == replace_value, replace_value, topk_indx) - - # # Routing metadata for local expert computation - gather_indx = GatherIndx(src_indx=topk_indx.int(), dst_indx=gate_indx.int()) - scatter_indx = ScatterIndx(src_indx=gate_indx.int(), dst_indx=topk_indx.int()) - - expt_data = compute_expt_data_torch(hist, n_local_experts, n_gates_pad) - - hit_experts = n_expts_act - return RoutingData(gate_scal, hist, n_local_experts, hit_experts, expt_data), gather_indx, scatter_indx + gather_indx = GatherIndx(src_indx=topk_indx.int(), dst_indx=gate_indx.int()) + scatter_indx = ScatterIndx(src_indx=gate_indx.int(), dst_indx=topk_indx.int()) + expt_data = compute_expt_data_torch(hist, num_experts, num_tokens * num_top_k) + return RoutingData(gate_scal, hist, num_experts, num_top_k, expt_data), gather_indx, scatter_indx @use_kernel_forward_from_hub("MegaBlocksMoeMLP") @@ -454,19 +427,19 @@ def __init__(self, router, experts): self.experts = experts def forward(self, hidden_states): - if _is_torch_distributed_initialized() and hasattr(self, "_is_hooked"): - routing = routing_torch_dist - else: - routing = triton_kernels_hub.routing.routing - batch_size = hidden_states.shape[0] hidden_states = hidden_states.reshape(-1, self.router.hidden_dim) - router_logits = nn.functional.linear(hidden_states, self.router.weight, self.router.bias) - - with on_device(router_logits.device): - routing_data, gather_idx, scatter_idx = routing(router_logits, self.router.top_k) - - routed_out = self.experts(hidden_states, routing_data, gather_idx, scatter_idx=scatter_idx) + if _is_torch_distributed_initialized() and hasattr(self, "_is_hooked"): + # expert parallelism: the `ep_dispatch_experts` strategy brings the experts the routes they own + router_logits, router_scores, router_indices = self.router(hidden_states) + routed_out = self.experts(hidden_states, router_indices, router_scores) + else: + router_logits = nn.functional.linear(hidden_states, self.router.weight, self.router.bias) + with on_device(router_logits.device): + routing_data, gather_idx, scatter_idx = triton_kernels_hub.routing.routing( + router_logits, self.router.top_k + ) + routed_out = self.experts.forward_routed(hidden_states, routing_data, gather_idx, scatter_idx) routed_out = routed_out.reshape(batch_size, -1, self.router.hidden_dim) return routed_out, router_logits From 0616556bcaa6e9df39aa2992d1aea8aa056d4496 Mon Sep 17 00:00:00 2001 From: Ilyas Moutawwakil Date: Mon, 2 Nov 2026 07:24:48 -0800 Subject: [PATCH 2/3] MXFP4 GPT-OSS: check the experts for the EP hook, declare packed params 3-D so EP shards the scales Co-Authored-By: Claude Opus 5.5 --- src/transformers/integrations/mxfp4.py | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/src/transformers/integrations/mxfp4.py b/src/transformers/integrations/mxfp4.py index adaa5b77ff3c..09ff89dedfb1 100644 --- a/src/transformers/integrations/mxfp4.py +++ b/src/transformers/integrations/mxfp4.py @@ -20,7 +20,6 @@ from torch import nn from ..core_model_loading import ConversionOps, _IdentityOp -from ..distributed.utils import _is_torch_distributed_initialized from ..quantizers.quantizers_utils import get_module_from_name, on_device, should_convert_module from .hub_kernels import use_kernel_forward_from_hub @@ -145,6 +144,8 @@ def convert( ) -> dict[str, torch.Tensor]: param_data = {} proj = "gate_up_proj" if "gate_up_proj" in full_layer_name else "down_proj" + import torch.distributed as _d + print("DBG", _d.get_rank(), full_layer_name, {k: [tuple(t.shape) for t in v] if isinstance(v, list) else tuple(v.shape) for k, v in input_dict.items()}, flush=True) if f"{proj}_blocks" in input_dict.keys(): if isinstance(input_dict[f"{proj}_blocks"], list): @@ -319,8 +320,10 @@ def __init__(self, config): self.intermediate_size = config.intermediate_size self.hidden_size = config.hidden_size + # The packed FP4 bytes, two values per byte. They are declared 3-D like the scales, so expert parallelism + # shards the checkpoint's blocks and scales the same way. self.gate_up_proj = nn.Parameter( - torch.zeros(self.num_experts, 2 * self.intermediate_size, self.hidden_size // 32, 16, dtype=torch.uint8), + torch.zeros(self.num_experts, 2 * self.intermediate_size, self.hidden_size // 2, dtype=torch.uint8), requires_grad=False, ) @@ -329,7 +332,7 @@ def __init__(self, config): ) self.down_proj = nn.Parameter( - torch.zeros((self.num_experts, self.hidden_size, self.intermediate_size // 32, 16), dtype=torch.uint8), + torch.zeros(self.num_experts, self.hidden_size, self.intermediate_size // 2, dtype=torch.uint8), requires_grad=False, ) @@ -345,8 +348,8 @@ def __init__(self, config): def forward( self, hidden_states: torch.Tensor, top_k_index: torch.Tensor, top_k_weights: torch.Tensor ) -> torch.Tensor: - """Experts on `top_k_index` ids in `[0, num_experts)`; other ids (another rank's routes under expert - parallelism) are skipped.""" + """Run the routes to this module's experts, the ids in `[0, num_experts)`. Expert parallelism marks other + ranks' routes with ids outside that range, and they are skipped.""" with on_device(hidden_states.device): routing_data, gather_idx, scatter_idx = routing_from_top_k(top_k_index, top_k_weights, self.num_experts) return self.forward_routed(hidden_states, routing_data, gather_idx, scatter_idx) @@ -388,8 +391,8 @@ def forward_routed(self, hidden_states: torch.Tensor, routing_data, gather_idx, # Adapted from GPT_OSS repo # TODO: Add absolute link when the repo is public def routing_from_top_k(top_k_index, top_k_weights, num_experts): - """Triton routing metadata for `num_experts` experts from routes already selected: `top_k_index` holds expert ids - in `[0, num_experts)` and `top_k_weights` their weights; routes outside that range are skipped.""" + """Build the Triton routing metadata of `num_experts` experts from selected routes. Ids outside + `[0, num_experts)` are skipped.""" GatherIndx, RoutingData, ScatterIndx, compute_expt_data_torch = ( triton_kernels_hub.routing.GatherIndx, triton_kernels_hub.routing.RoutingData, @@ -429,8 +432,8 @@ def __init__(self, router, experts): def forward(self, hidden_states): batch_size = hidden_states.shape[0] hidden_states = hidden_states.reshape(-1, self.router.hidden_dim) - if _is_torch_distributed_initialized() and hasattr(self, "_is_hooked"): - # expert parallelism: the `ep_dispatch_experts` strategy brings the experts the routes they own + if getattr(self.experts, "_is_hooked", False): + # the expert-parallel forward brings the experts the routes they own router_logits, router_scores, router_indices = self.router(hidden_states) routed_out = self.experts(hidden_states, router_indices, router_scores) else: From 7e41d090ab7297d2e9b34b649b12ba7cce6dbacd Mon Sep 17 00:00:00 2001 From: Ilyas Moutawwakil Date: Mon, 2 Nov 2026 07:29:20 -0800 Subject: [PATCH 3/3] Remove a debug print Co-Authored-By: Claude Opus 5.5 --- src/transformers/integrations/mxfp4.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/transformers/integrations/mxfp4.py b/src/transformers/integrations/mxfp4.py index 09ff89dedfb1..14acc7f8d561 100644 --- a/src/transformers/integrations/mxfp4.py +++ b/src/transformers/integrations/mxfp4.py @@ -144,8 +144,6 @@ def convert( ) -> dict[str, torch.Tensor]: param_data = {} proj = "gate_up_proj" if "gate_up_proj" in full_layer_name else "down_proj" - import torch.distributed as _d - print("DBG", _d.get_rank(), full_layer_name, {k: [tuple(t.shape) for t in v] if isinstance(v, list) else tuple(v.shape) for k, v in input_dict.items()}, flush=True) if f"{proj}_blocks" in input_dict.keys(): if isinstance(input_dict[f"{proj}_blocks"], list):