bridge.models.ernie.modeling_ernie55.moe#
ERNIE 5.5 MoE layer (hybrid symbol E) on Megatron-Core’s MoELayer.
Per token, with x_r = fp32(pre_mlp_layernorm(x)), E experts and top-k routing:
Split-feature scores
s = sigmoid(x_r W^T) + sigmoid(x_r W_1^T), two fp32[E, h]GEMMs, each entry in(0, 2)(:meth:Ernie55SplitFeatureRouter.gating).noaux_tc selection:
I = top_k(s + b)with the fp32 expert biasb; the gate values are the unbiasedp = s[I], so the bias only selects.With
ernie_norm_topk_probandk > 1:p = p / (sum(p) + 1e-20).A learned fp32 per-expert scale:
p = p * rho[I](routed_scaling_factor_param, initialized tomoe_router_topk_scaling_factor, the Hugging Facerouted_scaling_factor).Dropless dispatch to the grouped routed experts and an ungated shared expert on the full-width input; the probabilities scale each expert’s activation before its fc2, and the layer output is the combined routed output plus the shared output.
Megatron-Core reused unchanged: MoELayer and its dispatchers, TEGroupedMLP,
SharedExpertMLP(gate=False), TopKRouter.apply_z_loss (on the scores s),
TopKRouter._apply_expert_bias (token counting) and the expert_bias buffer, and the
finalize_model_grads expert-bias update b <- b + rate * sign(mean(c) - c) with
moe_router_bias_update_rate. Bridge adds only what Megatron-Core cannot express: the second
gate matrix, the per-expert learned scale and the unbiased-gate selection
(:class:Ernie55SplitFeatureRouter), and fp32 latent projections (:class:Ernie55MoELayer).
Precision contract (the reference implementation’s):
weight,weight_1androuted_scaling_factor_paramare fp32 parameters markedkeep_in_fp32;weightandweight_1stay 2-D and are taggeduse_muon=Falseundermoe_router_skip_muon(which the ERNIE 5.5 bridge sets), so AdamW updates them like the reference (muon_exclude_patterns"mlp.gate") does.expert_biasis markedkeep_in_fp32too, as in the reference. Bridge’s model provider already restores it around theFloat16Modulewrap (model_provider._apply_mixed_precision_wrapper); the mark also covers code that wraps a router withFloat16Moduledirectly, where Megatron-Core’s_maintain_float32_expert_biaswould only restore the dtype of a bias already rounded to bf16.Gating, z-loss, selection, normalization and scaling run in fp32;
moe_router_dtypeis ignored, as in the reference. Experts compute in the activation dtype.Tokens are counted only while autograd is enabled, so full activation recompute (no-grad forward, grad-enabled replay) counts each token once. With
moe_router_bias_update_rate == 0the bias is frozen: no counting and no update collective.
Latent MoE (moe_latent_size, unused by the 4-layer proxy): Megatron-Core’s data path is reused
(router and shared expert on the full-width input, fc1_latent_proj before dispatch, experts at
latent width, fc2_norm when moe_use_norm_before_up_proj, then fc2_latent_proj).
- class:
Ernie55MoELayerreplaces the two latent projections with :class:Ernie55LatentProjection, whose fp32 weight is cast to the activation dtype at use: the forward equals Megatron-Core’s bf16TELinear, but the Hugging Face checkpoint stores these weights in fp32, and a bf16 parameter would round them at load and give the optimizer a rounded master copy.
MLP activation (dense - layers, routed and shared experts): hidden_act="silu" is
Megatron-Core’s SwiGLU (gated_linear_unit=True, activation_func=F.silu). hidden_act="situ"
uses Megatron-Core’s SiTU-GLU knob: activation_func_tanh_clamp_scale = beta and
activation_func_tanh_clamp_scale_linear = linear_beta (None leaves the up half unclamped,
exactly the reference’s linear_beta=None branch). No other candidate covers the formula:
Megatron-Core’s situlu always clamps the up half, and Kimi K3’s situ_and_mul has no
linear_beta=None branch.
Rounding against the reference, which runs with bias_activation_fusion=False: SwiGLU is
Megatron-Core’s unfused path, SiTU is computed in fp32 and rounded once, and routed experts round the
activation and then its product with the fp32 routing probability. Measured on CPU (torch inductor) on
bf16 fc1 outputs (4096 x 2 x 512, sigma 1 and 4, beta 1 and 4, both linear-beta modes):
bias_activation_fusion=False(the reference setting and the default) is bitwise equal in every MLP: for SwiGLU it runs the reference’s own code, and Megatron-Core’s compiledsitu_glurounds once, as the reference does.bias_activation_fusion=Truerounds once inside the fused kernels. For SiTU this changes only the routed experts, where 25-26% of outputs differ by 1 ulp. For SwiGLU it changes every MLP: 26-28% of dense and shared outputs differ by 1 ulp, and 35-36% of routed outputs by up to 2 ulps. A parity run must therefore keepbias_activation_fusion=False.Without the jit fuser (eager mode),
situ_glurounds its intermediates: 31-44% of outputs differ by up to 3 ulps.Input gradients of the compiled SiTU kernels differ from the reference’s in at most 0.06% of elements.
GPU kernels lower tanh and sigmoid differently; test_ernie55_moe_gpu.py rechecks the SiTU
kernels there. Bridge’s rule is that rounding differences alone do not justify replacing a
Megatron-Core block.
With ernie_fused_ops (the default), SiTU-GLU on CUDA runs the reference implementation’s own Triton
kernel instead (fp32 inside, one rounding), in the dense MLPs, the shared
expert and the grouped routed experts.
- mod:
~megatron.bridge.models.ernie.modeling_ernie55.fused_dispatchinstalls it around thesitu_gluthat Megatron-Core’s MLP modules call, so the Megatron-Core blocks stay; the MLPactivation_funcslot (use_te_activation_func=True) is not usable, because Megatron-Core rejects it together withactivation_func_tanh_clamp_scale.
Known differences from the reference implementation (not bugs):
Expert token counts are exact int64 in Megatron-Core. The reference implementation registers an fp32 buffer that
Float16Modulecasts to bf16, so its counts are rounded while they accumulate (the spacing is 8 between 1024 and 2048 tokens). The first bias update can then differ for an expert whose count is within rounding of the mean, so routing can differ from the second iteration on. Bridge does not emulate this rounding.Random initialization only: the reference rounds
weightto bf16 at init (Megatron-Core casts it toparams_dtypebefore ERNIE re-casts it to fp32) and initializesfc2_latent_projwithinit_method; Bridge drawsweightin fp32 and keeps Megatron-Core’soutput_layer_init_methodforfc2_latent_proj. Checkpoint loads are unaffected.Logging only: with
moe_z_loss_coeff=0(z-loss tracked, no gradient), Megatron-Core records the mean z-loss; the gradient is zero.
Module Contents#
Classes#
Megatron-Core |
|
Latent-MoE projection |
|
Megatron-Core |
Functions#
Raise |
Data#
API#
- bridge.models.ernie.modeling_ernie55.moe.__all__#
[‘Ernie55LatentProjection’, ‘Ernie55MoELayer’, ‘Ernie55SplitFeatureRouter’, ‘validate_ernie55_moe_co…
- bridge.models.ernie.modeling_ernie55.moe._TOPK_NORM_EPS#
1e-20
- bridge.models.ernie.modeling_ernie55.moe._UNSUPPORTED_BALANCING#
(‘sinkhorn’, ‘quantile_balancing’)
- bridge.models.ernie.modeling_ernie55.moe._as_list(value: object) list#
- bridge.models.ernie.modeling_ernie55.moe.validate_ernie55_moe_config(
- config: megatron.core.transformer.transformer_config.TransformerConfig,
Raise
ValueErrorifconfigis outside the supported ERNIE 5.5 MLP and MoE envelope.Supported:
Gated MLPs shared by dense and expert layers:
gated_linear_unit=Trueandactivation_func=F.silu(SwiGLU, or SiTU-GLU through Megatron-Core’sactivation_func_tanh_clamp_scale[_linear]), noactivation_func_clamp_valueand noglu_linear_offset.The split-feature router:
moe_router_score_function="sigmoid", the noaux_tc expert bias (moe_router_enable_expert_bias=True,moe_router_bias_update_rate >= 0), no expert groups, no auxiliary loss (everymoe_aux_loss_coeffis 0; sinkhorn and quantile balancing are rejected), no hash routing, no routing replay, no router fusion,moe_router_dtypeunset or"fp32"(the router always computes in fp32), a finitemoe_router_topk_scaling_factor(orNonefor 1.0) and a booleanernie_norm_topk_prob. The benchmark knobsmoe_router_force_load_balancingandmoe_router_force_biasedare rejected: they replace the scores with random logits before routing, and this router uses the scores directly as gate values.Dropless experts (
moe_expert_capacity_factor=None) without biases, an ungated shared expert, and no fused RMSNorm-linear latent up-projection.
- Parameters:
config – Transformer config of the MoE layers.
- Raises:
ValueError – On the first violated requirement.
- class bridge.models.ernie.modeling_ernie55.moe.Ernie55SplitFeatureRouter(
- config: megatron.core.transformer.transformer_config.TransformerConfig,
- *args,
- **kwargs,
Bases:
megatron.core.transformer.moe.router.TopKRouterMegatron-Core
TopKRouterwith ERNIE 5.5’s split-feature gating and learned per-expert scale.gatingreturns the fp32 scoressigmoid(x W^T) + sigmoid(x W_1^T)instead of logits, androutingselectstop_k(scores + expert_bias), gathers the unbiased scores, normalizes them (ernie_norm_topk_prob,k > 1) and multiplies them byrouted_scaling_factor_param. The inheritedforward(input jitter, observation hooks),apply_z_lossand_apply_expert_biasare unchanged, andfinalize_model_gradsupdatesexpert_biasas for anyTopKRouter.Because
gatingreturns scores, Megatron-Core’srouter_logitstensor observation records the scores, and itsrouter_scoresobservation (the configured score function applied to those values) is not meaningful for this router.Positional and keyword arguments after
configare passed through unchanged toTopKRouter.Initialization
- _reset_fp32_matrix(param: torch.nn.Parameter) None#
Initialize a gate matrix with
init_methodand keep it in fp32.
- _reset_split_feature_parameters() None#
Initialize
weight_1and set every per-expert scale tomoe_router_topk_scaling_factor.
- reset_parameters() None#
Initialize the gate parameters in fp32 (Megatron-Core casts
weighttoparams_dtype).
- gating(input: torch.Tensor) torch.Tensor#
Return the fp32 split-feature scores
sigmoid(x W^T) + sigmoid(x W_1^T)(not logits).- Parameters:
input – Router input
[..., hidden](the pre-MLP norm output).- Returns:
Scores
[..., num_experts]in fp32, each in(0, 2).
- routing(
- logits: torch.Tensor,
- padding_mask: torch.Tensor | None = None,
- input_ids: torch.Tensor | None = None,
- packed_seq_params: object | None = None,
Select experts on the biased scores and weight them with the unbiased ones.
- Parameters:
logits – Scores from :meth:
gating,[..., num_experts].padding_mask – Optional
True-is-padding mask over the tokens; padding is excluded from the z-loss and from the token counts, as inTopKRouter.input_ids – Unused (no hash routing).
packed_seq_params – Unused; ERNIE routing does not depend on sequence boundaries.
- Returns:
fp32 probabilities
[tokens, num_experts]withknon-zero entries per row, and the matching boolean map.- Return type:
(probs, routing_map)
- class bridge.models.ernie.modeling_ernie55.moe.Ernie55LatentProjection(
- config: megatron.core.transformer.transformer_config.TransformerConfig,
- input_size: int,
- output_size: int,
- *,
- init_method,
Bases:
megatron.core.transformer.module.MegatronModuleLatent-MoE projection
y = x W^Twhose fp32 weight is cast to the input dtype at use.It replaces Megatron-Core’s duplicated
TELinearlatent projections and keeps their call contract:forwardreturns(y, None)andbackward_dwis a no-op.- Parameters:
config – Transformer config.
input_size – Input width.
output_size – Output width.
init_method – Weight initializer, applied when
config.perform_initializationis set.
Initialization
- forward(hidden_states: torch.Tensor) tuple[torch.Tensor, None]#
Project
hidden_stateswith the weight rounded to their dtype.
- backward_dw() None#
No delayed weight-gradient computation.
- class bridge.models.ernie.modeling_ernie55.moe.Ernie55MoELayer(
- config: megatron.core.transformer.transformer_config.TransformerConfig,
- *args,
- **kwargs,
Bases:
megatron.core.transformer.moe.moe_layer.MoELayerMegatron-Core
MoELayerwith the ERNIE 5.5 router and fp32 latent projections.The routing, dispatch, expert, shared-expert and combine code is Megatron-Core’s. The constructor checks that the spec installed :class:
Ernie55SplitFeatureRouterand, for latent MoE, replacesfc1_latent_proj(init_method) andfc2_latent_proj(output_layer_init_method) with- Class:
Ernie55LatentProjection.fc2_norm(moe_use_norm_before_up_proj) stays Megatron-Core’sTENorm.
Arguments after
configare passed through toMoELayer.Initialization