bridge.models.ernie.modeling_ernie55.latent_mqa_attention#
ERNIE 5.5 D-layer self attention: Megatron-Core AbsorbedMLASelfAttention on a D-layer config.
The D layer reuses AbsorbedMLA’s forward unchanged (projections, K absorption, RoPE,
linear_proj). The subclass
validates the supported envelope (:func:
validate_ernie55_config),builds the module from a shallow config copy with the D-layer geometry and the settings the ERNIE architecture fixes (:func:
ernie55_d_layer_config),stores the K and V up-projections as the reference implementation’s two matrices
k_b_projandv_b_projinstead of Megatron-Core’s combinedlinear_kv_up_proj, because Muon orthogonalizes every 2-D parameter as one matrix,sets the core’s indexer-loss tracker slot for MTP layers itself (the same slot Megatron-Core dev derives from the
is_mtp_layerit forwards to the core), andruns context parallelism (CP > 1) in the zigzag partition inside a contiguous stack: the forward converts its input rows to zigzag with Megatron-Core dev’s module-local converter, runs AbsorbedMLA’s forward unchanged and converts the output back (see :meth:
forwardand- mod:
~megatron.bridge.models.ernie.modeling_ernie55.context_parallel).
Because the rewrite lives in the attention module, it also reaches the nested MTP stack,
which reuses the decoder’s dsa_layer spec.
Module Contents#
Classes#
|
Functions#
Return a shallow copy of |
|
Raise |
Data#
API#
- bridge.models.ernie.modeling_ernie55.latent_mqa_attention.__all__#
[‘Ernie55LatentMQASelfAttention’, ‘ernie55_d_layer_config’, ‘validate_ernie55_config’]
- bridge.models.ernie.modeling_ernie55.latent_mqa_attention._D_LAYER_OVERRIDES#
((‘ernie_d_num_attention_heads’, ‘num_attention_heads’), (‘ernie_d_q_lora_rank’, ‘q_lora_rank’), (‘e…
- bridge.models.ernie.modeling_ernie55.latent_mqa_attention._SUPPORTED_DSA_KERNEL_BACKENDS#
(‘cudnn’, ‘none’)
- bridge.models.ernie.modeling_ernie55.latent_mqa_attention._LOSS_SCALED_ROOT_VARIANTS#
(‘dsa’, ‘dsv4_hybrid’)
- bridge.models.ernie.modeling_ernie55.latent_mqa_attention._FIXED_INDEXER_SETTINGS#
((‘dsa_indexer_rope_interleaved’, False), (‘dsa_indexer_rotate_activation’, True), (‘dsa_indexer_sco…
- bridge.models.ernie.modeling_ernie55.latent_mqa_attention.ernie55_d_layer_config(
- config: megatron.core.transformer.transformer_config.TransformerConfig,
Return a shallow copy of
configconfigured for an ERNIE 5.5 D layer.The copy is not re-finalized; derived fields of
configare kept. Changes:Geometry: every non-
Noneernie_d_*field replaces its Megatron-Core counterpart (ernie_d_rotary_basereplacesrotary_base);Noneinherits the stack value.num_query_groups = num_attention_headsandkv_channelsis set tov_head_dimwhen it isNone.Plain RoPE without YaRN scaling:
rope_type="rope",rotary_percent=1.0,rotary_interleaved=False,rotary_scaling_factor=1.0,mscale=1.0andmscale_all_dim=0.0, so AbsorbedMLA’s softmax scale is1 / sqrt(qk_head_dim + qk_pos_emb_head_dim). AbsorbedMLA always rotates adjacent channel pairs (mla_rotary_interleaved=True).apply_rope_fusion=False: Megatron-Core has no fused RoPE path forrope_type="rope".qk_layernorm=Trueandattention_output_gate=False(the ERNIE gate lives in the core and is driven by the q latent).attention_latent_norm_epsilonfalls back tolayernorm_epsilonwhen unset (:func:validate_ernie55_configrejects any other value, because Megatron-Core main normalizes the q/kv latents withlayernorm_epsilonand dev withattention_latent_norm_epsilon).
experimental_attention_variantis not changed; the q/kv latent norms come from the layer spec instead.- Parameters:
config – Finalized stack or per-layer transformer config.
- Returns:
A new config object;
configis not modified.
- bridge.models.ernie.modeling_ernie55.latent_mqa_attention.validate_ernie55_config(
- config: megatron.core.transformer.transformer_config.TransformerConfig,
Raise
ValueErrorifconfigis outside the supported ERNIE 5.5 D-layer envelope.Supported:
TP = 1.
CP >= 1. CP > 1 needs Megatron-Core’s module-local CP partition converter (dev; main raises),
cp_partition_mode"contiguous"or"zigzag"and static CP (:func:~megatron.bridge.models.ernie.modeling_ernie55.context_parallel.validate_ernie55_context_parallel_config); every micro-batch must then be packed THD with documents padded to a multiple of 2 * CP and prebuilt partition routes (checked in :meth:Ernie55LatentMQASelfAttention.forward).BF16 only:
bf16=True, no FP16 (Megatron-Core’s DSA indexer rotation needs bf16 activations), no FP8/FP4, noquant_recipeand no Kitchen quantization.No CUDA graphs, no delayed weight-gradient computation, and no selective recompute of
core_attnormla_up_proj(full recompute is fine).Per-token top-k every layer and the ERNIE indexer settings.
dsa_kernel_backend"cudnn"(with a fusedattention_backend; an unfused backend would silently run the PyTorch reference) or"none".q/kv latent norms with
layernorm_epsilon(attention_latent_norm_epsilonunset or equal to it).No attention dropout and a positive
ernie_vha_rank.
With an indexer loss (
dsa_indexer_loss_coeff > 0) the loss must be sparse, and the pipeline schedule must scale it throughDSAIndexerLossAutoScaler, the only way the D layer injects the KL gradient:experimental_attention_variant"dsa"or"dsv4_hybrid"withoutexperimental_attention_variant_loss_scale_func, or that function set toDSAIndexerLossAutoScaler.set_loss_scale. Any other function replaces the schedule’s hook,DSAIndexerLossAutoScalerkeeps its stale scale, and the indexer gradients are off bynum_microbatches * loss_scale.- Parameters:
config – Stack-level or per-layer transformer config.
- Raises:
RuntimeError – At CP > 1 if Megatron-Core has no CP partition converter.
ValueError – On the first violated requirement.
- class bridge.models.ernie.modeling_ernie55.latent_mqa_attention.Ernie55LatentMQASelfAttention(
- config: megatron.core.transformer.transformer_config.TransformerConfig,
- *args,
- **kwargs,
Bases:
megatron.core.transformer.experimental_attention_variant.absorbed_mla.AbsorbedMLASelfAttentionAbsorbedMLASelfAttentionfor ERNIE 5.5 D layers.The constructor validates
config, builds the module fromernie55_d_layer_config(config), then checks that the spec produced real q/kv latent norms, an :class:Ernie55LatentMQACoreAttentioncore (which consumes the V up-projection) and no AbsorbedMLA output gate.The K and V up-projections are two parameters in the reference implementation’s layout, with
Hheads,C = kv_lora_rank,nope = qk_head_dimandv = v_head_dim:k_b_proj[H * C, nope]: rowsh * Cto(h + 1) * CholdW_UK[h]^T;v_b_proj[H * v, C]: rowsh * vto(h + 1) * vholdW_UV[h];
where head
hcomputesk_nope = W_UK[h] c_kvandvalue = W_UV[h] c_kv. Megatron-Core builds onelinear_kv_up_proj[H * (nope + v), C]whose headhblock is[W_UK[h]; W_UV[h]](dev’s split-projection specs stackW_UK[h], the transpose of the reference’s blocks). The math is the same, but Muon orthogonalizes each 2-D parameter as one matrix, and the polar factor of a stack of blocks depends on how the blocks are laid out, so only the reference layout gives the reference’s optimizer updates. Hugging Face checkpoints store both projections as onekv_b_projin Megatron-Core’s combined layout, so converting a checkpoint needs a split on import and a join on export, not a rename.AbsorbedMLA’s forward runs unchanged: :meth:
_get_kv_up_weights, the accessor AbsorbedMLA reads both up-projections through, returns per-head views of the two parameters.- Meth:
forwardonly adds the zigzag context-parallel conversion around it.
Positional and keyword arguments after
configare passed through unchanged toAbsorbedMLASelfAttention.Initialization
- forward(
- hidden_states,
- attention_mask,
- key_value_states=None,
- inference_context=None,
- rotary_pos_emb=None,
- rotary_pos_cos=None,
- rotary_pos_sin=None,
- rotary_pos_cos_sin=None,
- attention_bias=None,
- packed_seq_params=None,
- position_ids=None,
- sequence_len_offset=None,
- *,
- inference_params=None,
AbsorbedMLA’s forward, run in the zigzag CP partition when context parallelism is active.
Without context parallelism this is AbsorbedMLA’s forward. At CP > 1 the stack hands the layer its rows in
config.cp_partition_mode("contiguous"in the DSv4 hybrid stack, whose H layers accept nothing else), while AbsorbedMLA’s RoPE and the D core need the zigzag partition. The layer therefore:checks the packed micro-batch on the host (:func:
~megatron.bridge.models.ernie.modeling_ernie55.context_parallel.check_thd_cp_metadata: packed THD, documents padded to a multiple of 2 * CP, prebuilt partition route and hostcu_seqlens,packed_seq_params.cp_partition_modeequal toconfig.cp_partition_mode);converts
hidden_statesto zigzag with Megatron-Core’sconvert_module_input_tensors_cp_partition_mode(one all-to-all over the CP group, routed by the prebuilt route), which also setspacked_seq_params.cp_partition_modeto"zigzag";runs AbsorbedMLA’s forward unchanged on the zigzag rows;
converts the
linear_projoutput back to the stack partition (the narrowest tensor of the layer,[rows, hidden]);restores
packed_seq_params.cp_partition_modein afinallyblock, so the next layer, a raised exception or a full-recompute replay of this layer all see the stack partition again.
The conversions are differentiable all-to-alls; their backward runs the reverse exchange. A zigzag stack (
cp_partition_mode="zigzag", a D-only"dsa"stack) needs no conversion.- Returns:
(output, bias)like AbsorbedMLA;outputis in the stack partition.- Raises:
NotImplementedError – For SBHD input at CP > 1.
RuntimeError – At CP > 1 without Megatron-Core’s CP partition converter.
ValueError – If the micro-batch’s packed metadata violates the CP requirements.
- _split_kv_up_projection() None#
Replace the K/V up-projection Megatron-Core built with
k_b_projandv_b_proj.Megatron-Core main always builds the combined
linear_kv_up_proj; dev builds it or, for split-projection specs,linear_k_up_projandlinear_v_up_proj. Megatron-Core’s own accessor reads either. The new parameters take the values Megatron-Core initialized (config.init_method), copied into the reference layout, so the layer computes the same function and no random numbers are drawn.
- _get_kv_up_weights() tuple[torch.Tensor, torch.Tensor]#
Per-head K and V up-projections
[H, nope, C]and[H, v, C], as views of the parameters.AbsorbedMLA absorbs the K view into the query (
einsum("...nd,ndk->...nk")takes the strided view as is) and hands the V view to the core, which applies it.
- _backward_kv_proj() None#
Deferred weight gradients of the K/V projections: only
linear_kv_down_projdefers its own.Autograd computes the
k_b_projandv_b_projgradients during the backward pass. Megatron-Core main would also call the deletedlinear_kv_up_proj.