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:
Q/KV (Megatron-Core):
q = rms(c_q W_qb^T)per head (weightless, over allv_head_dimchannels),kv = RMSNorm_kv(x W_kv^T), one latent head; RoPE on the lastqk_pos_emb_head_dimchannels ofqandkv, rotating adjacent channel pairs.Compressor (Megatron-Core): every complete block
jof 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 position128 j. TheL mod 128tail tokens of a document, and documents shorter than 128, have no block.Core (Megatron-Core): each head attends to the window
[max(0, p - W + 1), p]of its document and to every complete blockj < floor((p + 1) / 128), with a learnable per-head sink in the softmax denominator only and scalev_head_dim^-1/2; key = value = the latent row. The output is rotated back (inverse RoPE) atp.VHA (ERNIE, this module’s core):
o'_k = sum_h (I + V U^T)[k, h] o_hover the heads.Grouped
wo_a(Megatron-Core):z_g = o_g W_oa,g^Tforoutput_projection_groupsgroups of consecutive heads.Output gate (ERNIE, the
_post_o_group_projhook):z <- z * sigmoid(c_q W_g^T).linear_proj(Megatron-Core):y = z W_o^T.
ERNIE pieces, and where they live:
- class:
Ernie55HCACoreAttentionsubclassesCompressedSparseAttention. It owns the VHA factorsvha_postmix_u/vha_postmix_vand applies the head mix out of place to the core output, so the sparse-attentionFunctionkeeps its saved output intact. It also draws the all-zero attention sink fromN(0, 0.1)at construction whenperform_initializationis set. The reference implementation draws it unconditionally; checkpoint loading overwrites it either way.
- class:
Ernie55HCASelfAttentionsubclassesDSv4HybridSelfAttention. It overrides only the_post_o_group_proj(attn_out, q_compressed)hook, where it applies the q-latent sigmoid gatelinear_output_gate, and withernie_hca_rope_type="rope"it replaces the YaRN rotary embedding Megatron-Core builds for compressed layers with plain RoPE (see below).forwardis 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.YarnRotaryEmbeddingwithrotary_scaling_factor = 1equals plain RoPE only up to rounding: in the ramp band its blendinv * (1 - m) + inv * mcan moveinv_freqby one fp32 ulp, and the bf16 cos/sin table then differs in a handful of entries. The constructor therefore swaps in an exact plainRotaryEmbeddingand 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’sYarnRotaryEmbeddingfrom the stack’srotary_scaling_factor,original_max_position_embeddings,beta_fastandbeta_slow. DSv4 attention rotates withmscale=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#
|
|
|
|
|
Functions#
Raise |
|
Return every rotary embedding reachable from |
|
Draw an all-zero sink from |
|
Check that every attention module of an ERNIE 5.5 model is an ERNIE H or D layer. |
Data#
Compression ratio of every ERNIE 5.5 H layer (Hugging Face |
|
Supported H-layer RoPE types ( |
|
Standard deviation of the H-layer attention sink drawn at initialization (the reference implementation’s
|
|
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_ratiosentries == 128).
- bridge.models.ernie.modeling_ernie55.hca_attention.ERNIE55_HCA_ROPE_TYPES#
(‘rope’, ‘yarn’)
Supported H-layer RoPE types (
ernie_hca_rope_type, Hugging Facehca_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,
Raise
ValueErrorifconfigis 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 positiveernie_vha_rank, RoPE on every positional channel (rotary_percent == 1) anddsa_kernel_backend"cudnn"(with a fusedattention_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,
Return every rotary embedding reachable from
rootwith 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.partialattribute. Shared objects are reported once per path.- Parameters:
root – Module to search.
- Returns:
(path, embedding)pairs;YarnRotaryEmbeddingis aRotaryEmbeddingtoo.
- 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.CompressedSparseAttentionCompressedSparseAttentionat 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, markedkeep_in_fp32.Utakesinit_methodwhenperform_initializationis set;Vstarts at zero, so the mix starts as the identity.attn_sinkseeding: the all-zero sink is drawn fromN(0, 0.1)at construction whenperform_initializationis set (never inforward).forwardreturnsvha_postmix(core_output), computed out of place (ernie_vha_bf16_mixselects the bf16 or the fp32 contract).
The constructor forwards every argument to
CompressedSparseAttentionunchanged. Megatron-Core’sAttention.__init__first builds a throwaway core withoutcompress_ratio(a window-only layer) beforeDSv4HybridAttentionbuilds the real one. The H-layer geometry is therefore checked by- Class:
Ernie55HCASelfAttention, not here, and only a ratio-128 core drawsUand 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_rankis 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.DSv4HybridSelfAttentionSubmodulesDSv4HybridSelfAttentionSubmodulesplus the ERNIE output gate.- Parameters:
linear_output_gate – Linear
q_lora_rank -> output_projection_groups * output_projection_lora_rankfor 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.DSv4HybridSelfAttentionDSv4HybridSelfAttentionfor ERNIE 5.5 H layers: plain RoPE or YaRN, and a q-latent output gate.Only the constructor and the
_post_o_group_projhook differ from Megatron-Core;forwardis 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, buildslinear_output_gateand checks the spec: ratio 128, an- Class:
Ernie55HCACoreAttentioncore 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]inparams_dtype, and the core’sattn_sink/vha_postmix_u/vha_postmix_v.Arguments after
submodulesandlayer_numberare passed through to Megatron-Core.- Raises:
RuntimeError – If Megatron-Core’s
DSv4HybridAttentionhas no_post_o_group_projhook.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
YarnRotaryEmbeddingper 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 oneRotaryEmbedding(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 ownrotary_pos_emband 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,
Raise
RuntimeErrorif a rotary embedding other thanropeis 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
Compressorkernels (cudnn.csa.compressor, which cudnn-frontend 1.29.1 ships) withuse_fused_dsa_kernels(config). That is the same switch that selects the fused FlashMLA/cuDNN attention, sodsa_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 fusedapegradient is accumulated with atomics.
- _post_o_group_proj(
- attn_out: torch.Tensor,
- q_compressed: torch.Tensor,
Gate the grouped
wo_aoutput with the q latent:attn_out * sigmoid(c_q W_g^T).ernie_output_gate_fp32(Hugging Facesigmoid_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_layernormoutput with the leading dims ofattn_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,
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/Wlayer from several spec slots (hca_layeron dev takes precedence overcsa_qk_layernorm_layer), so a spec that sets a slot :func:~megatron.bridge.models.ernie.modeling_ernie55.ernie55_hybrid_stack_specdoes 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:
Ernie55HCASelfAttentionnor anErnie55LatentMQASelfAttention.