bridge.models.ernie.modeling_ernie55.hca_attention#

ERNIE 5.5 H layer (compress_ratio == 128) on Megatron-Core’s DSv4 hybrid attention.

An H layer is Megatron-Core’s DSv4HybridSelfAttention with CompressedSparseAttention and its Compressor at ratio 128 (no indexer), plus four ERNIE changes. For a query row at document position p, with x the layer input and c_q = RMSNorm_q(x W_qa^T) the q latent:

  1. Q/KV (Megatron-Core): q = rms(c_q W_qb^T) per head (weightless, over all v_head_dim channels), kv = RMSNorm_kv(x W_kv^T), one latent head; RoPE on the last qk_pos_emb_head_dim channels of q and kv, rotating adjacent channel pairs.

  2. Compressor (Megatron-Core): every complete block j of 128 tokens of a document is pooled, m_j = sum_i softmax_i(x_i W_gate^T + ape_i) * (x_i W_wkv^T) in fp32 and rounded once, then RMS-normalized and rotated at position 128 j. The L mod 128 tail tokens of a document, and documents shorter than 128, have no block.

  3. Core (Megatron-Core): each head attends to the window [max(0, p - W + 1), p] of its document and to every complete block j < floor((p + 1) / 128), with a learnable per-head sink in the softmax denominator only and scale v_head_dim^-1/2; key = value = the latent row. The output is rotated back (inverse RoPE) at p.

  4. VHA (ERNIE, this module’s core): o'_k = sum_h (I + V U^T)[k, h] o_h over the heads.

  5. Grouped wo_a (Megatron-Core): z_g = o_g W_oa,g^T for output_projection_groups groups of consecutive heads.

  6. Output gate (ERNIE, the _post_o_group_proj hook): z <- z * sigmoid(c_q W_g^T).

  7. linear_proj (Megatron-Core): y = z W_o^T.

ERNIE pieces, and where they live:

  • class:

    Ernie55HCACoreAttention subclasses CompressedSparseAttention. It owns the VHA factors vha_postmix_u / vha_postmix_v and applies the head mix out of place to the core output, so the sparse-attention Function keeps its saved output intact. It also draws the all-zero attention sink from N(0, 0.1) at construction when perform_initialization is set. The reference implementation draws it unconditionally; checkpoint loading overwrites it either way.

  • class:

    Ernie55HCASelfAttention subclasses DSv4HybridSelfAttention. It overrides only the _post_o_group_proj(attn_out, q_compressed) hook, where it applies the q-latent sigmoid gate linear_output_gate, and with ernie_hca_rope_type="rope" it replaces the YaRN rotary embedding Megatron-Core builds for compressed layers with plain RoPE (see below). forward is inherited: the core already applies the inverse RoPE on Megatron-Core dev, so porting the reference forward would rotate twice without any error.

The hook is DSv4HybridAttention._post_o_group_proj, present in Megatron-Core dev from f78809f6d on. Without it the constructor raises.

RoPE. Megatron-Core builds YarnRotaryEmbedding for every compressed layer, with base csa_compress_rotary_base (Hugging Face compress_rope_theta). ernie_hca_rope_type (Hugging Face hca_rope_type, "rope" when the key is missing) selects the H layers’ RoPE, as in the reference implementation:

  • "rope": plain RoPE. YarnRotaryEmbedding with rotary_scaling_factor = 1 equals plain RoPE only up to rounding: in the ramp band its blend inv * (1 - m) + inv * m can move inv_freq by one fp32 ulp, and the bf16 cos/sin table then differs in a handful of entries. The constructor therefore swaps in an exact plain RotaryEmbedding and rebinds every holder of the YaRN object (the attention, the core on dev, the compressor), so the stack’s YaRN settings do not reach H layers.

  • "yarn": Megatron-Core’s YarnRotaryEmbedding from the stack’s rotary_scaling_factor, original_max_position_embeddings, beta_fast and beta_slow. DSv4 attention rotates with mscale=1.0 (no concentration factor), as the reference implementation does. The constructor only checks that every holder shares the one YaRN object.

At context_parallel_size > 1 the rows’ RoPE (q, kv and the inverse on the output) goes through Megatron-Core’s cp_utils.apply_thd_cp_local_rope_unfused; with ernie_fused_ops it runs the reference implementation’s Triton kernel on CUDA (:mod:~megatron.bridge.models.ernie.modeling_ernie55.fused_dispatch).

Expected numerical differences from the reference implementation (rounding only):

  • q/kv/compressor norms are Transformer Engine RMSNorm (fp32 statistics, one rounding); the reference casts the input to the weight dtype first.

  • The gate projection is a Transformer Engine GEMM rather than torch.matmul.

  • On dev, the fused path builds the sparse index lists with thd_layout_kernels, which orders the FlashMLA accumulation differently from the reference implementation’s pin.

The fused path (dsa_kernel_backend="cudnn") runs FlashMLA’s sparse forward and the cuDNN DSA backward, as the reference implementation does even with dsa_kernel_backend="none". The compressor always pools eagerly, which is the reference recipe. On dev, the switch that selects the fused attention also enables cudnn-frontend’s fused Compressor kernel (cudnn.csa.compressor, which cudnn-frontend 1.29.1 ships) on SM100+ GPUs, so the constructor turns that kernel off for H layers.

Module Contents#

Classes#

Ernie55HCACoreAttention

CompressedSparseAttention at ratio 128 followed by the ERNIE VHA head mix.

Ernie55HCASelfAttentionSubmodules

DSv4HybridSelfAttentionSubmodules plus the ERNIE output gate.

Ernie55HCASelfAttention

DSv4HybridSelfAttention for ERNIE 5.5 H layers: plain RoPE or YaRN, and a q-latent output gate.

Functions#

validate_ernie55_hca_config

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

rotary_embedding_references

Return every rotary embedding reachable from root with its attribute path.

_seed_zero_attention_sink_

Draw an all-zero sink from N(0, ERNIE55_ATTN_SINK_INIT_STD) in place (the reference’s init).

check_ernie55_attention_layers

Check that every attention module of an ERNIE 5.5 model is an ERNIE H or D layer.

Data#

__all__

ERNIE55_HCA_COMPRESS_RATIO

Compression ratio of every ERNIE 5.5 H layer (Hugging Face compress_ratios entries == 128).

ERNIE55_HCA_ROPE_TYPES

Supported H-layer RoPE types (ernie_hca_rope_type, Hugging Face hca_rope_type): plain RoPE and Megatron-Core’s YaRN.

ERNIE55_ATTN_SINK_INIT_STD

Standard deviation of the H-layer attention sink drawn at initialization (the reference implementation’s N(0, 0.1) seed).

_SUPPORTED_DSA_KERNEL_BACKENDS

API#

bridge.models.ernie.modeling_ernie55.hca_attention.__all__#

[‘ERNIE55_ATTN_SINK_INIT_STD’, ‘ERNIE55_HCA_COMPRESS_RATIO’, ‘ERNIE55_HCA_ROPE_TYPES’, ‘Ernie55HCACo…

bridge.models.ernie.modeling_ernie55.hca_attention.ERNIE55_HCA_COMPRESS_RATIO#

128

Compression ratio of every ERNIE 5.5 H layer (Hugging Face compress_ratios entries == 128).

bridge.models.ernie.modeling_ernie55.hca_attention.ERNIE55_HCA_ROPE_TYPES#

(‘rope’, ‘yarn’)

Supported H-layer RoPE types (ernie_hca_rope_type, Hugging Face hca_rope_type): plain RoPE and Megatron-Core’s YaRN.

bridge.models.ernie.modeling_ernie55.hca_attention.ERNIE55_ATTN_SINK_INIT_STD#

0.1

Standard deviation of the H-layer attention sink drawn at initialization (the reference implementation’s N(0, 0.1) seed).

bridge.models.ernie.modeling_ernie55.hca_attention._SUPPORTED_DSA_KERNEL_BACKENDS#

(‘cudnn’, ‘none’)

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

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

Supported: Megatron-Core’s DSv4 hybrid attention variant with TP = 1, BF16 (no FP8/FP4, no Kitchen quantization), no CUDA graphs and no delayed weight gradients, RMSNorm q/kv/compressor norms, no linear biases, a q latent (q_lora_rank, the gate input), a positive ernie_vha_rank, RoPE on every positional channel (rotary_percent == 1) and dsa_kernel_backend "cudnn" (with a fused attention_backend) or "none".

Context parallelism (CP > 1) is Megatron-Core’s: DSv4 runs it in the contiguous partition on packed THD input (it exchanges the CP-boundary rows the window and the compressor need and gathers the compressed keys). The ERNIE additions are per row (VHA, gate) or per layer (plain RoPE or YaRN, see :meth:Ernie55HCASelfAttention._use_plain_rope). The CP envelope is shared with the D layer (:func:~megatron.bridge.models.ernie.modeling_ernie55.context_parallel.validate_ernie55_context_parallel_config): a Megatron-Core build with the CP partition converter (dev; main is not validated and raises) and static CP. Megatron-Core’s DSv4 CP path builds its compressor layout with CuTe DSL kernels, so H layers at CP > 1 run on GPUs only.

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.

bridge.models.ernie.modeling_ernie55.hca_attention.rotary_embedding_references(
root: torch.nn.Module,
) → list[tuple[str, megatron.core.models.common.embeddings.RotaryEmbedding]]#

Return every rotary embedding reachable from root with its attribute path.

Covers registered submodules and plain attributes of every submodule, including the items of a list, tuple, set or dict attribute and the arguments of a functools.partial attribute. Shared objects are reported once per path.

Parameters:

root – Module to search.

Returns:

(path, embedding) pairs; YarnRotaryEmbedding is a RotaryEmbedding too.

bridge.models.ernie.modeling_ernie55.hca_attention._seed_zero_attention_sink_(attn_sink: torch.Tensor) → None#

Draw an all-zero sink from N(0, ERNIE55_ATTN_SINK_INIT_STD) in place (the reference’s init).

class bridge.models.ernie.modeling_ernie55.hca_attention.Ernie55HCACoreAttention(
config: megatron.core.transformer.transformer_config.TransformerConfig,
*args,
**kwargs,
)#

Bases: megatron.core.transformer.experimental_attention_variant.csa.CompressedSparseAttention

CompressedSparseAttention at ratio 128 followed by the ERNIE VHA head mix.

Construction and the attention itself are Megatron-Core’s (window plus every complete compressed block, fp32 sink, fused or reference kernels by dsa_kernel_backend). This subclass adds:

  • vha_postmix_u / vha_postmix_v: [heads, ernie_vha_rank] fp32 parameters, marked keep_in_fp32. U takes init_method when perform_initialization is set; V starts at zero, so the mix starts as the identity.

  • attn_sink seeding: the all-zero sink is drawn from N(0, 0.1) at construction when perform_initialization is set (never in forward).

  • forward returns vha_postmix(core_output), computed out of place (ernie_vha_bf16_mix selects the bf16 or the fp32 contract).

The constructor forwards every argument to CompressedSparseAttention unchanged. Megatron-Core’s Attention.__init__ first builds a throwaway core without compress_ratio (a window-only layer) before DSv4HybridAttention builds the real one. The H-layer geometry is therefore checked by

Class:

Ernie55HCASelfAttention, not here, and only a ratio-128 core draws U and the sink: the throwaway core allocates the VHA factors but draws no random numbers, so each H layer consumes the initialization random streams once.

Raises:

ValueError – If ernie_vha_rank is not a positive integer.

Initialization

forward(*args, **kwargs) → torch.Tensor#

Run Megatron-Core’s core attention, then mix its heads with I + V U^T (out of place).

Returns:

[s, b, heads * v_head_dim], or [t, 1, heads * v_head_dim] for packed THD input.

Return type:

Same shape as the Megatron-Core core output

class bridge.models.ernie.modeling_ernie55.hca_attention.Ernie55HCASelfAttentionSubmodules#

Bases: megatron.core.transformer.experimental_attention_variant.deepseek_v4_hybrid_attention.DSv4HybridSelfAttentionSubmodules

DSv4HybridSelfAttentionSubmodules plus the ERNIE output gate.

Parameters:

linear_output_gate – Linear q_lora_rank -> output_projection_groups * output_projection_lora_rank for the q-latent gate, built like the compressor linears (parallel_mode="duplicated", no bias).

linear_output_gate: megatron.core.transformer.spec_utils.ModuleSpec | type | None#

None

class bridge.models.ernie.modeling_ernie55.hca_attention.Ernie55HCASelfAttention(
config: megatron.core.transformer.transformer_config.TransformerConfig,
submodules: bridge.models.ernie.modeling_ernie55.hca_attention.Ernie55HCASelfAttentionSubmodules,
layer_number: int,
*args,
**kwargs,
)#

Bases: megatron.core.transformer.experimental_attention_variant.deepseek_v4_hybrid_attention.DSv4HybridSelfAttention

DSv4HybridSelfAttention for ERNIE 5.5 H layers: plain RoPE or YaRN, and a q-latent output gate.

Only the constructor and the _post_o_group_proj hook differ from Megatron-Core; forward is inherited. The constructor validates the config (:func:validate_ernie55_hca_config), builds the DSv4 layer, swaps in plain RoPE (ernie_hca_rope_type="rope") or checks the YaRN holders ("yarn"), keeps the compressor eager, builds linear_output_gate and checks the spec: ratio 128, an

Class:

Ernie55HCACoreAttention core and explicit q/kv latent norms.

Parameters added on top of Megatron-Core (names are pinned by the checkpoint mappings): linear_output_gate.weight [output_projection_groups * output_projection_lora_rank, q_lora_rank] in params_dtype, and the core’s attn_sink / vha_postmix_u / vha_postmix_v.

Arguments after submodules and layer_number are passed through to Megatron-Core.

Raises:
  • RuntimeError – If Megatron-Core’s DSv4HybridAttention has no _post_o_group_proj hook.

  • TypeError – If the core is not an :class:Ernie55HCACoreAttention.

  • ValueError – If the config is outside the H envelope, the layer’s compression ratio is not 128, the core has an indexer or no compressor, a latent norm is missing (IdentityOp) or the spec has no output gate.

Initialization

_use_plain_rope() → None#

Replace Megatron-Core’s YaRN rotary embedding with plain RoPE at the same base, everywhere.

Megatron-Core builds one YarnRotaryEmbedding per compressed layer and hands it to the core (dev) and the compressor, which keep their own references. Every holder of a rotary embedding is rebound to one RotaryEmbedding(qk_pos_emb_head_dim, rotary_base=csa_compress_rotary_base, cp_group=<the layer's CP group>), so the forward, the compressor and the core’s inverse RoPE all read the same plain table. The context-parallel path reads the same holders: it applies the table at the rows’ global contiguous positions (cp_utils.apply_thd_cp_local_rope_*), the compressor rotates its blocks with its own rotary_pos_emb and the core’s inverse RoPE (_OutputInverseRope) reads the core’s.

Afterwards no rotary embedding other than the plain one may be reachable from the layer, as a registered submodule or as a plain attribute (also inside a list, tuple, dict or partial), so a Megatron-Core change that adds another holder raises here instead of silently keeping YaRN.

Raises:

RuntimeError – If another rotary embedding is still reachable after the rebinding.

_check_rope_holders(
rope: megatron.core.models.common.embeddings.RotaryEmbedding,
) → None#

Raise RuntimeError if a rotary embedding other than rope is reachable from the layer.

_use_eager_compressor() → None#

Keep the compressor’s fp32 pooling eager, as the reference implementation does.

Megatron-Core dev gates cudnn-frontend’s fused Compressor kernels (cudnn.csa.compressor, which cudnn-frontend 1.29.1 ships) with use_fused_dsa_kernels(config). That is the same switch that selects the fused FlashMLA/cuDNN attention, so dsa_kernel_backend="cudnn" would also replace the eager pooling on SM100+ GPUs. The fused ratio-128 gradients match the eager pooling only within a tolerance, and the fused ape gradient is accumulated with atomics.

_post_o_group_proj(
attn_out: torch.Tensor,
q_compressed: torch.Tensor,
) → torch.Tensor#

Gate the grouped wo_a output with the q latent: attn_out * sigmoid(c_q W_g^T).

ernie_output_gate_fp32 (Hugging Face sigmoid_gate_fusion) runs the sigmoid and the product in fp32 with one rounding; otherwise both run in the activation dtype. The result is a new tensor, and nothing saved for backward aliases it (the hook’s offload contract).

Parameters:
  • attn_out – [s, b, groups * o_lora_rank] ([t, 1, ...] for packed THD input).

  • q_compressed – q_layernorm output with the leading dims of attn_out.

Returns:

Gated tensor with the shape and dtype of attn_out.

backward_dw() → None#

Compute the deferred weight gradients of Megatron-Core’s linears and of the output gate.

bridge.models.ernie.modeling_ernie55.hca_attention.check_ernie55_attention_layers(
model: torch.nn.Module,
) → dict[str, int]#

Check that every attention module of an ERNIE 5.5 model is an ERNIE H or D layer.

Megatron-Core picks the module of a hybrid C/H/W layer from several spec slots (hca_layer on dev takes precedence over csa_qk_layernorm_layer), so a spec that sets a slot :func:~megatron.bridge.models.ernie.modeling_ernie55.ernie55_hybrid_stack_spec does not know about would silently build a layer without the ERNIE gate, VHA and sink. The ERNIE 5.5 model builder must call this on the built model; it walks every submodule, including the nested MTP stack and hyper-connection wrappers.

Parameters:

model – Built model, stack or layer.

Returns:

{"H": number of H layers, "D": number of D layers}.

Raises:

TypeError –

If a Megatron-Core attention module is neither an

class:

Ernie55HCASelfAttention nor an Ernie55LatentMQASelfAttention.