@@ -2435,6 +2435,29 @@ def _init_expert_kernel(shape, dtype):
24352435 ):
24362436 self .wo .value = self .wo .value * self .per_expert_scale .value [:, None , None ]
24372437
2438+ def _fold_expert_scale_into_wo (self ) -> bool :
2439+ """moe_fold_expert_scale_into_wo: sparse_matmul scales wo by per_expert_scale instead of the top-k weights.
2440+
2441+ Config and layer conditions only; `__call__` also requires `model_mode == MODEL_MODE_TRAIN` and threads the
2442+ result down to `get_topk` as `fold_expert_scale`, so get_topk never reads it.
2443+ """
2444+ cfg = self .config
2445+ return (
2446+ self .per_expert_scale is not None
2447+ and cfg .moe_fold_expert_scale_into_wo
2448+ and cfg .sparse_matmul
2449+ and not cfg .mlp_bias # wo_bias is added after wo; the top-k path scales it, a scaled wo would not.
2450+ # fsdp_prefetch hands __call__ the all-gathered wo, so the multiply would cover every expert, not a shard.
2451+ and not cfg .prefetch_fsdp_weights
2452+ and not cfg .te_moe_block
2453+ and cfg .attention not in ("vllm_rpa" , "vllm_batched_rpa" )
2454+ and self .wo_scale is None
2455+ and not quantizations .in_serve_mode (self .quant )
2456+ and not (cfg .model_call_mode == "inference" and cfg .fuse_expert_scales )
2457+ # fp8 weight all-gather (QWAG): wo's fixed or (by default) cross-expert scale would not follow a scaled wo.
2458+ and ctypes .moe_qwag_flag (cfg ) is None
2459+ )
2460+
24382461 def _maybe_shard_with_logical (self , inputs , logical_name ):
24392462 return maybe_shard_with_logical (
24402463 inputs ,
@@ -2524,13 +2547,17 @@ def get_topk(
25242547 forced_routed_experts = None ,
25252548 per_expert_scale = None ,
25262549 token_mask = None ,
2550+ fold_expert_scale = False ,
25272551 ):
25282552 """get topk.
25292553
25302554 `per_expert_scale` (Gemma 4 only) is normally read off the module, but the
25312555 sparse path runs inside a `jax.shard_map` that cannot close over an array
25322556 living on explicit mesh axes, so it hands the value in instead.
25332557
2558+ `fold_expert_scale` (moe_fold_expert_scale_into_wo): the caller already multiplied per_expert_scale into wo,
2559+ so it is not applied to the top-k weights here.
2560+
25342561 `token_mask` (batch, sequence) bool, True for real tokens, marks padding rows (e.g. the all-zero rows of
25352562 `elastic_global_batch_size_mode='constant_padded'`). It is applied after the router has run, so the real
25362563 tokens' weights are untouched for every router type; a padded token gets every expert id set to -1 (an unused
@@ -2546,7 +2573,8 @@ def apply_token_mask(top_k_weights, top_k_indices):
25462573 top_k_weights = jnp .where (keep , top_k_weights , jnp .zeros ((), top_k_weights .dtype ))
25472574 return top_k_weights , top_k_indices
25482575
2549- if per_expert_scale is None and self .per_expert_scale is not None :
2576+ # fold_expert_scale (moe_fold_expert_scale_into_wo): the caller multiplied per_expert_scale into wo instead.
2577+ if per_expert_scale is None and self .per_expert_scale is not None and not fold_expert_scale :
25502578 per_expert_scale = self .per_expert_scale [...]
25512579 # shape of top_k_weights & top_k_indices:
25522580 # (batch, sequence, num_experts_per_tok).
@@ -2853,6 +2881,7 @@ def permute(
28532881 physical_route_fn = None ,
28542882 has_invalid_slots = False ,
28552883 _return_sorted_weights = False ,
2884+ fold_expert_scale = False ,
28562885 ):
28572886 """Permute tokens to group by expert to fit gmm call.
28582887
@@ -2879,6 +2908,8 @@ def permute(
28792908 home/replica slots after `-1` padding slots have been replaced with safe indices.
28802909 has_invalid_slots: True when `precomputed_topk` may contain unused (-1) expert slots even if
28812910 `forced_routed_experts` / `token_mask` were already consumed before the EP all-gather.
2911+ fold_expert_scale: moe_fold_expert_scale_into_wo is active, so get_topk leaves per_expert_scale out of the
2912+ top-k weights (the caller multiplied it into wo).
28822913 """
28832914 is_qarray = isinstance (inputs , qpl .QArray )
28842915 has_per_token_scale = is_qarray and inputs .scale .size > 1
@@ -2902,6 +2933,7 @@ def permute(
29022933 forced_routed_experts ,
29032934 per_expert_scale = per_expert_scale ,
29042935 token_mask = token_mask ,
2936+ fold_expert_scale = fold_expert_scale ,
29052937 )
29062938 # Unused slots (expert id -1, from forced routing or token_mask padding) and physical_route_fn's replica bins are
29072939 # counted by the bincount group sizes below but not by summed_expert_mask, so those calls keep that path.
@@ -3778,6 +3810,7 @@ def _check_ragged_overflow(
37783810 n_chunks ,
37793811 per_expert_scale = None ,
37803812 token_mask = None ,
3813+ fold_expert_scale = False ,
37813814 ):
37823815 """Returns True if permute()'s ragged buffer would overflow for any chunk on any EP shard.
37833816
@@ -3793,6 +3826,7 @@ def _check_ragged_overflow(
37933826 forced_routed_experts ,
37943827 per_expert_scale = per_expert_scale ,
37953828 token_mask = token_mask ,
3829+ fold_expert_scale = fold_expert_scale ,
37963830 )
37973831 batch , seq_len , top_k = selected_experts .shape
37983832 # Forced-routing and token_mask padding (-1) maps to no shard, so one_hot gives it an all-zero row.
@@ -3822,6 +3856,7 @@ def sparse_matmul(
38223856 forced_routed_experts = None ,
38233857 token_mask = None ,
38243858 moe_qwag_weight_amax = None ,
3859+ fold_expert_scale = False ,
38253860 ):
38263861 """Perform sparse matrix multiplication of inputs and Experts.
38273862
@@ -4538,6 +4573,7 @@ def maybe_pack_and_all_gather_routing(
45384573 forced_routed_experts ,
45394574 per_expert_scale = per_expert_scale ,
45404575 token_mask = token_mask ,
4576+ fold_expert_scale = fold_expert_scale ,
45414577 )
45424578 packed = _ep_all_gather (pack_routing_for_all_gather (local_weights , local_ids ))
45434579 tag_fn = routing_tag_fn (self .config )
@@ -4620,6 +4656,7 @@ def token_all_gather(z):
46204656 forced_routed_experts ,
46214657 per_expert_scale = per_expert_scale ,
46224658 token_mask = token_mask ,
4659+ fold_expert_scale = fold_expert_scale ,
46234660 )
46244661 precomputed_topk = (_ep_all_gather (weights ), _ep_all_gather (selected_experts ))
46254662 has_invalid_slots_override = forced_routed_experts is not None or token_mask is not None
@@ -4675,6 +4712,7 @@ def token_all_gather(z):
46754712 precomputed_topk = precomputed_topk ,
46764713 precomputed_density_prob = precomputed_density_prob ,
46774714 per_expert_scale = per_expert_scale ,
4715+ fold_expert_scale = fold_expert_scale ,
46784716 token_mask = token_mask ,
46794717 has_invalid_slots = has_invalid_slots_override ,
46804718 )
@@ -4800,6 +4838,7 @@ def _physical_route_fn(flat_logical, valid_mask=None):
48004838 compute_lb_loss = not use_megatron_seq_aux_loss ,
48014839 return_expert_counts = True ,
48024840 per_expert_scale = per_expert_scale ,
4841+ fold_expert_scale = fold_expert_scale ,
48034842 skip_token_gather = skip_token_gather ,
48044843 token_mask = token_mask ,
48054844 physical_route_fn = physical_route_fn ,
@@ -5968,7 +6007,8 @@ def _unpermute_inputs(intermediate_output, routing):
59686007 # Gemma 4's per-expert router scale is consumed by get_topk, deep inside the
59696008 # shard_map below. A shard_map cannot close over an array that lives on explicit
59706009 # mesh axes, so it is threaded down as an argument instead of read off the module.
5971- per_expert_scale = None if self .per_expert_scale is None else self .per_expert_scale [...]
6010+ # With `fold_expert_scale` the caller already multiplied it into wo.
6011+ per_expert_scale = None if self .per_expert_scale is None or fold_expert_scale else self .per_expert_scale [...]
59726012
59736013 def keep_reduced (pspec , w ):
59746014 # Weights all-gathered by fsdp_prefetch arrive typed `reduced` over the FSDP axes; shard_map requires
@@ -6375,6 +6415,7 @@ def _per_device_flag(has_overflow):
63756415 n_chunks ,
63766416 per_expert_scale ,
63776417 token_mask = token_mask ,
6418+ fold_expert_scale = fold_expert_scale ,
63786419 )
63796420
63806421 # Both branches return required_rbf with the same structure: None when the
@@ -7668,6 +7709,7 @@ def __call__(
76687709 forced_routed_experts : jax .Array | None = None ,
76697710 token_mask : jax .Array | None = None ,
76707711 moe_qwag_weight_amax : tuple [jax .Array , jax .Array , jax .Array ] | None = None ,
7712+ model_mode : str | None = None ,
76717713 ) -> tuple [jax .Array , jax .Array | None , jax .Array | None ]:
76727714 """Executes the routed MoE block.
76737715
@@ -7684,12 +7726,15 @@ def __call__(
76847726 load-balance loss and the routed-bias update, and get a zero output; real tokens are computed exactly
76857727 as without the mask. Not supported with `te_moe_block` or the fused inference MoE kernel.
76867728 moe_qwag_weight_amax: Optional precomputed (wi_0, wi_1, wo) amax for dynamic QWAG; computed here if None.
7729+ model_mode: One of the `common_types.MODEL_MODE_*` values, if the caller knows it. Only
7730+ `moe_fold_expert_scale_into_wo` reads it: the fold applies only for MODEL_MODE_TRAIN.
76877731
76887732 Returns:
76897733 A tuple containing the MoE output, the load balance loss (if applicable),
76907734 and any routed bias updates.
76917735 """
76927736 cfg = self .config
7737+ fold_expert_scale = model_mode == ctypes .MODEL_MODE_TRAIN and self ._fold_expert_scale_into_wo ()
76937738 if cfg .te_moe_block and gate_inputs is not None :
76947739 raise ValueError ("te_moe_block=True does not support separate gate_inputs." )
76957740 if cfg .te_moe_block and cfg .use_random_routing and forced_routed_experts is not None :
@@ -7783,6 +7828,18 @@ def _maybe_native_fused_weight(kernel, scale):
77837828 wo_scale = self .wo_scale [...] if self .wo_scale is not None else None
77847829 if is_fused_moe_path :
77857830 wo_kernel , wo_native_scale = _maybe_native_fused_weight (self .wo [...], wo_scale )
7831+ elif fold_expert_scale :
7832+ # Scale the sharded f32 weight (~1 expert per device under shard_exp_on_fsdp) before the cast, instead of a
7833+ # per-token gather of the scale in get_topk.
7834+ wo = self .wo [...]
7835+ scale = self .per_expert_scale [...].astype (wo .dtype )
7836+ if cfg .shard_mode == ShardMode .EXPLICIT :
7837+ # Explicit mode does not reshard a broadcast operand. The scale is sharded on "exp", but wo's expert dim
7838+ # may be on other mesh axes (shard_exp_on_fsdp puts it on fsdp), so replicate the scale. Matching wo's
7839+ # `reduced` axes also covers a wo all-gathered by fsdp_prefetch, which the gate excludes today.
7840+ scale = jax .sharding .reshard (scale , NamedSharding (self .mesh , P (None , reduced = _reduced_axes (wo ))))
7841+ wo = wo * scale [:, None , None ]
7842+ wo_kernel , wo_native_scale = _maybe_native_gmm_weight (wo , None ), None
77867843 else :
77877844 wo_kernel , wo_native_scale = _maybe_native_gmm_weight (self .wo [...], wo_scale ), None
77887845
@@ -7839,7 +7896,8 @@ def _maybe_native_fused_weight(kernel, scale):
78397896 # For fused MoE path (inference only), if we have not fused expert
78407897 # scales at init, we must apply them to wo_kernel here because
78417898 # fused_moe_func doesn't support them. Other paths (dense/sparse
7842- # matmul) apply them to top_k_weights in get_topk.
7899+ # matmul) apply them to top_k_weights in get_topk, or to wo above
7900+ # under moe_fold_expert_scale_into_wo.
78437901 if is_fused_moe_path :
78447902 if self .per_expert_scale is not None and not (cfg .model_call_mode == "inference" and cfg .fuse_expert_scales ):
78457903 if wo_native_scale is not None :
@@ -7907,6 +7965,7 @@ def _maybe_native_fused_weight(kernel, scale):
79077965 forced_routed_experts = forced_routed_experts ,
79087966 token_mask = token_mask ,
79097967 moe_qwag_weight_amax = moe_qwag_weight_amax ,
7968+ fold_expert_scale = fold_expert_scale ,
79107969 )
79117970 else :
79127971 output , lb_loss , bias_updates = self .dense_matmul (
0 commit comments