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_proj and v_b_proj instead of Megatron-Core’s combined linear_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_layer it forwards to the core), and

  • runs 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:forward and

    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#

Ernie55LatentMQASelfAttention

AbsorbedMLASelfAttention for ERNIE 5.5 D layers.

Functions#

ernie55_d_layer_config

Return a shallow copy of config configured for an ERNIE 5.5 D layer.

validate_ernie55_config

Raise ValueError if config is outside the supported ERNIE 5.5 D-layer envelope.

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,
) → megatron.core.transformer.transformer_config.TransformerConfig#

Return a shallow copy of config configured for an ERNIE 5.5 D layer.

The copy is not re-finalized; derived fields of config are kept. Changes:

  • Geometry: every non-None ernie_d_* field replaces its Megatron-Core counterpart (ernie_d_rotary_base replaces rotary_base); None inherits the stack value.

  • num_query_groups = num_attention_heads and kv_channels is set to v_head_dim when it is None.

  • Plain RoPE without YaRN scaling: rope_type="rope", rotary_percent=1.0, rotary_interleaved=False, rotary_scaling_factor=1.0, mscale=1.0 and mscale_all_dim=0.0, so AbsorbedMLA’s softmax scale is 1 / 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 for rope_type="rope".

  • qk_layernorm=True and attention_output_gate=False (the ERNIE gate lives in the core and is driven by the q latent).

  • attention_latent_norm_epsilon falls back to layernorm_epsilon when unset (:func:validate_ernie55_config rejects any other value, because Megatron-Core main normalizes the q/kv latents with layernorm_epsilon and dev with attention_latent_norm_epsilon).

experimental_attention_variant is 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; config is not modified.

bridge.models.ernie.modeling_ernie55.latent_mqa_attention.validate_ernie55_config(
config: megatron.core.transformer.transformer_config.TransformerConfig,
) → None#

Raise ValueError if config is 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, no quant_recipe and no Kitchen quantization.

  • No CUDA graphs, no delayed weight-gradient computation, and no selective recompute of core_attn or mla_up_proj (full recompute is fine).

  • Per-token top-k every layer and the ERNIE indexer settings.

  • dsa_kernel_backend "cudnn" (with a fused attention_backend; an unfused backend would silently run the PyTorch reference) or "none".

  • q/kv latent norms with layernorm_epsilon (attention_latent_norm_epsilon unset 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 through DSAIndexerLossAutoScaler, the only way the D layer injects the KL gradient: experimental_attention_variant "dsa" or "dsv4_hybrid" without experimental_attention_variant_loss_scale_func, or that function set to DSAIndexerLossAutoScaler.set_loss_scale. Any other function replaces the schedule’s hook, DSAIndexerLossAutoScaler keeps its stale scale, and the indexer gradients are off by num_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.AbsorbedMLASelfAttention

AbsorbedMLASelfAttention for ERNIE 5.5 D layers.

The constructor validates config, builds the module from ernie55_d_layer_config(config), then checks that the spec produced real q/kv latent norms, an :class:Ernie55LatentMQACoreAttention core (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 H heads, C = kv_lora_rank, nope = qk_head_dim and v = v_head_dim:

  • k_b_proj [H * C, nope]: rows h * C to (h + 1) * C hold W_UK[h]^T;

  • v_b_proj [H * v, C]: rows h * v to (h + 1) * v hold W_UV[h];

where head h computes k_nope = W_UK[h] c_kv and value = W_UV[h] c_kv. Megatron-Core builds one linear_kv_up_proj [H * (nope + v), C] whose head h block is [W_UK[h]; W_UV[h]] (dev’s split-projection specs stack W_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 one kv_b_proj in 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:

forward only adds the zigzag context-parallel conversion around it.

Positional and keyword arguments after config are passed through unchanged to AbsorbedMLASelfAttention.

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:

  1. 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 host cu_seqlens, packed_seq_params.cp_partition_mode equal to config.cp_partition_mode);

  2. converts hidden_states to zigzag with Megatron-Core’s convert_module_input_tensors_cp_partition_mode (one all-to-all over the CP group, routed by the prebuilt route), which also sets packed_seq_params.cp_partition_mode to "zigzag";

  3. runs AbsorbedMLA’s forward unchanged on the zigzag rows;

  4. converts the linear_proj output back to the stack partition (the narrowest tensor of the layer, [rows, hidden]);

  5. restores packed_seq_params.cp_partition_mode in a finally block, 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; output is 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_proj and v_b_proj.

Megatron-Core main always builds the combined linear_kv_up_proj; dev builds it or, for split-projection specs, linear_k_up_proj and linear_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_proj defers its own.

Autograd computes the k_b_proj and v_b_proj gradients during the backward pass. Megatron-Core main would also call the deleted linear_kv_up_proj.