bridge.models.ernie.modeling_ernie55.latent_mqa_core#
Core attention of the ERNIE 5.5 D layer (compress_ratio == -2).
The module sits in the core_attention slot of Megatron-Core’s
AbsorbedMLASelfAttention. It receives the absorbed query [q_nope W_UK | q_pe], the
single-head latent key [c_kv | k_pe], the q latent qr (the q_layernorm output),
the layer input x and the per-head V up-projection, and returns the gated, projected
attention output [..., heads * v_head_dim]; AbsorbedMLA then applies linear_proj.
Per query row t of a document starting at d(t):
The Megatron-Core
DSAIndexerscores the remote keys[d(t), t - W]and keeps the topKof them (W = csa_window_size,K = dsa_indexer_topk).Latent MQA attends over
top-k ∪ [max(d(t), t - W + 1), t](disjoint sets) with a per-head learnable sink in the softmax denominator. The value is the firstkv_lora_ranklatent channels.V up-projection, then the VHA head mix
I + V U^T, thenout * sigmoid(W_g qr).In training, the indexer learns from a KL loss against a top-k-only attention teacher (Megatron-Core’s sparse DSA teacher). The loss only reaches the indexer parameters and is scaled per micro-batch by
DSAIndexerLossAutoScaler. Rows without remote candidates contribute exactly zero. The reduction follows the loss mode:calculate_per_token_loss=False(reference-implementation parity):coeff * sum_t KL_t / (b * s)over every row of the micro-batch, padding rows of a pack included; the schedule then averages over micro-batches. Under context parallelismsis the length of the whole pack, not the rank’s share (see below).calculate_per_token_loss=True(required by Bridge’s runtime THD packing): Megatron-Core’s convention, the rawcoeff * sum_t KL_t;finalize_model_gradsthen divides every gradient by the global loss-token count. The indexer gradient differs from the reference byrows / loss tokens, so the core warns once. Use per-row loss for parity checks.
Context parallelism (CP > 1, packed THD only). The attention module hands the core its rows in
the zigzag partition (rank r holds chunks r and 2 * CP - 1 - r of every document; see
- mod:
~megatron.bridge.models.ernie.modeling_ernie55.context_parallel), with AbsorbedMLA’s RoPE and the indexer’s RoPE already applied at the rows’ true document positions. The core then
takes the global packed position of every local row from the zigzag geometry (built on the host from the micro-batch’s prebuilt
cu_seqlens, cached per micro-batch);all-gathers the 576-wide latent key and the indexer key over the CP group and puts them in global packed order (the backward reduce-scatters the key gradients to their owners);
evaluates the document bounds
[d(t), t - W], the window and the placeholder candidate (see- func:
~megatron.bridge.models.ernie.modeling_ernie55.ops.ernie55_kernel_selection_ends) in global coordinates, so the indices address the gathered keys;
runs the fused scorer as Megatron-Core’s zigzag
PACKED_THD_GENERALcuDNN plan: it passes the packed layout with one tensor as both the query and the keycu_seqlens(the plan’s same-view requirement) andpacked_thd_single_sequence=False, because the single-sequence plan picks wrong top-k with cuDNN frontend >= 1.26 (Megatron-Core #8534). The plan scores each document causally from its start, and the top-k keeps only the firstend - startcolumns, so the lagging ERNIE endt - Wis honored. Both top-k hooks get these arguments: the loss hook in a training forward or a full-recompute replay, and the plain top-k hook in a forward without the loss (evaluation, or the no-grad forward of full recompute). :attr:requested_indexer_scoring_planrecords the plan the arguments each hook received select;normalizes the per-row indexer loss by the rows of the whole pack, as the reference does: it passes
coeff / CP, so rankr’s loss iscoeff * sum_{t on r} KL_t / (b * s_pack). The schedule scales the indexer gradient byCP / micro-batchesand DDP averages it over DP x CP, so the gradient is that ofcoeff * sum_t KL_t / (b * s_pack)over the whole pack. Megatron-Core DSA’s per-row convention normalizes by the local rows instead, which makes its indexer gradient CP times too large; it is not inherited here. The tracker averages the loss over the CP group, the reference’s logging convention (1 / CPof the pack’s row mean). Per-token loss keeps Megatron-Core’s convention, which is already CP-consistent.
Two backends are selected by use_fused_dsa_kernels(config): the fused path (cuDNN DSA
indexer and loss hooks, FlashMLA sparse forward, cuDNN sparse backward; CUDA, bf16, SM90+)
and the PyTorch reference path, which is exact but materializes O(heads * T^2) fp32
tensors and is meant for CPU tests, oracles and short sequences. The reference attention
gathers the latent key in fp32, so its key gradient is summed over query rows in fp32 and
rounded once.
Indexer scores follow the reference implementation’s convention on every path: the indexer
weights w = weights_proj(x) * H^-0.5 * d^-0.5 (bf16) are multiplied by d^0.5 in bf16
before scoring, and the score sum_h relu(q_h . k) * w_h is multiplied by d^-0.5 in fp32
after the head reduction (d = dsa_indexer_head_dim). Megatron-Core’s convention scores
with the pre-scaled weights instead; the math is the same, but the extra bf16 rounding of the
reference moves every score by about 3e-4 of the row’s largest score, and near-tied keys at the
top-k boundary swap. The cuDNN hooks read their score scale from
dsa_cudnn_kernels._INDEXER_SOFTMAX_SCALE (scores, the KL inputs and the indexer backward), so
the core sets it to d^-0.5 around each hook call. Gradients reach w through the bf16
multiplication.
The fused attention’s selection and key lists:
At CP = 1 the attention’s top-k is the reference implementation’s own: its cuDNN
indexer_forward_wrappercall on 512-row chunks (withq_causal_offsets), the remote bounds as a-infmask andtorch.topk, which leaves the keys in descending score order. FlashMLA gets[top-k | window]rows without their all-invalid 128-key blocks (:func:~megatron.bridge.models.ernie.modeling_ernie55.ops.drop_invalid_key_blocks) plus the kept lengths. FlashMLA’s output depends on the key order and on which keys share a block, and this list reproduces the reference’s output bitwise while skipping its empty blocks. In training the indexer loss still comes from Megatron-Core’s loss hook, which selects the same keys (PACKED_THD_GENERALfor packed THD rows,UNFUSED_BOUNDSotherwise); its top-k only feeds the loss. (A pack with tail rows pastcu_seqlens[-1], which only hand-built inputs have, keepsUNFUSED_BOUNDS, because the packed plan would leave the tail rows out of the last document.)At CP > 1 the hooks’ top-k (sorted by key id) goes to FlashMLA in compacted
[top-k | window]lists with per-row lengths, the format Megatron-Core DSA uses atd_qk = 576.
Megatron-Core issue worked around on the fused path: for an SBHD batch
(b > 1), the cuDNN sparse indexer loss (dsa_cudnn_kernels._compute_sparse_indexer_loss_and_grads)
gives no indexer gradient to the samples after the first. For the indexer backward it offsets the
top-k indices by sample * s, but it passes the indexer key per sample ([b, s, d]), and
cuDNN’s indexer_backward_wrapper reads local per-sample indices. The KL value and the top-k are
right. The core therefore calls the loss hook once per sample when b > 1; THD packs have
b = 1 and take one call.
Known performance cliffs on the fused path (measure them with
examples/models/ernie55/benchmark_d_layer_indexer.py):
Indexer scoring of SBHD batches. Without packed metadata, ERNIE’s remote bounds are neither causal nor reconstructible, so the loss hook scores them with Megatron-Core’s generic
UNFUSED_BOUNDSplan: fp32 per-head score chunks over the fulls x srectangle, with no causal skipping and no tensor cores, about2 * s^2 * n_heads * head_dimFLOPs per layer forward. Packed THD rows (every training step of the ERNIE recipes) usePACKED_THD_GENERALat every CP size, and the CP-1 attention top-k uses the causal cuDNN score kernel.Indexer loss. The teacher log-sum-exp comes from an extra FlashMLA pass (sink
-inf) over the top-k columns, which adds roughly one attention forward on steps with the loss.
Expected numerical differences from the reference implementation (not bugs):
attn_sinkis an fp32 parameter used as is; the reference stores a bf16 parameter and upcasts it at use. The forward is identical for bf16-representable sinks; training trajectories differ by the bf16 rounding of the sink.Rows past
cu_seqlens[-1](tail padding) extend the last document here; the reference assumes packs without such rows. Keep tail rows out of parity checks.
Module Contents#
Classes#
FlashMLA sparse forward with a sink, cuDNN backward with an analytic sink gradient. |
|
Submodules of :class: |
|
ERNIE 5.5 D-layer core: indexer top-k, windowed sparse latent MQA with a sink, V-up, VHA, gate. |
Functions#
Log |
|
cuDNN’s |
|
Whether a CP-1 pack’s boundaries end at its last row, i.e. it has no tail rows past |
|
Set Megatron-Core’s cuDNN indexer score scale ( |
|
Scoring plan the packed-layout arguments of one fused top-k hook call select in Megatron-Core’s cuDNN backend. |
|
Return the indexer-loss tracker slot of a D layer. |
|
Device for parameters this module allocates itself, chosen like Megatron-Core’s TE modules. |
|
Raise if the D-layer geometry cannot run on FlashMLA and the cuDNN DSA kernels. |
|
Raise unless the fused sparse attention can take |
Data#
Most query rows ( |
|
Megatron-Core’s |
|
Megatron-Core’s |
|
The core’s own CP-1 selection: the reference implementation’s cuDNN indexer score call on 512-row chunks
and |
|
API#
- bridge.models.ernie.modeling_ernie55.latent_mqa_core.logger#
‘getLogger(…)’
- bridge.models.ernie.modeling_ernie55.latent_mqa_core.__all__#
[‘INDEXER_SCORING_PACKED_THD_GENERAL’, ‘INDEXER_SCORING_REFERENCE_ORDER’, ‘INDEXER_SCORING_UNFUSED_B…
- bridge.models.ernie.modeling_ernie55.latent_mqa_core.REFERENCE_FALLBACK_MAX_TOKENS#
4096
Most query rows (
b * s, the whole pack under context parallelism) for which a declined fused top-k hook may fall back to the reference path.The reference top-k and loss materialize
[b, s, s]scores and a[b, heads, s, s]teacher in fp32, so a silent fallback at production lengths would run out of memory far from the cause. Above this size a declined hook raises instead.
- bridge.models.ernie.modeling_ernie55.latent_mqa_core.INDEXER_SCORING_UNFUSED_BOUNDS#
‘unfused_bounds’
Megatron-Core’s
IndexerScoringPlan.UNFUSED_BOUNDS: fp32 per-head score chunks over every key.
- bridge.models.ernie.modeling_ernie55.latent_mqa_core.INDEXER_SCORING_PACKED_THD_GENERAL#
‘packed_thd_general’
Megatron-Core’s
IndexerScoringPlan.PACKED_THD_GENERAL: cuDNN causal scoring per packed document.
- bridge.models.ernie.modeling_ernie55.latent_mqa_core.INDEXER_SCORING_REFERENCE_ORDER#
‘reference_order’
The core’s own CP-1 selection: the reference implementation’s cuDNN indexer score call on 512-row chunks and
torch.topk, which keeps the reference’s top-k keys and their score order.
- bridge.models.ernie.modeling_ernie55.latent_mqa_core._INDEXER_SCORING_PACKED_SINGLE_SEGMENTS#
‘packed_single_segments’
- bridge.models.ernie.modeling_ernie55.latent_mqa_core._FUSED_TOPK_BLOCK_SIZE#
8192
- bridge.models.ernie.modeling_ernie55.latent_mqa_core._FLASH_MLA_KV_LORA_RANK#
512
- bridge.models.ernie.modeling_ernie55.latent_mqa_core._FLASH_MLA_ROPE_DIM#
64
- bridge.models.ernie.modeling_ernie55.latent_mqa_core._FLASH_MLA_HEAD_COUNTS#
(64, 128)
- bridge.models.ernie.modeling_ernie55.latent_mqa_core._CUDNN_INDEXER_HEAD_DIM#
128
- bridge.models.ernie.modeling_ernie55.latent_mqa_core._CUDNN_INDEXER_HEAD_COUNTS#
(32, 64)
- bridge.models.ernie.modeling_ernie55.latent_mqa_core._DSA_FLASH_MLA_TOPK_ALIGNMENT#
512
- bridge.models.ernie.modeling_ernie55.latent_mqa_core._FLASH_MLA_KEY_BLOCK#
128
- bridge.models.ernie.modeling_ernie55.latent_mqa_core._REFERENCE_SCORE_CHUNK_ROWS#
512
- bridge.models.ernie.modeling_ernie55.latent_mqa_core._WARNED: set[str]#
‘set(…)’
- bridge.models.ernie.modeling_ernie55.latent_mqa_core._warn_once(
- key: str,
- message: str,
- level: int = logging.WARNING,
Log
messageonce per process, on the default logging rank only.
- bridge.models.ernie.modeling_ernie55.latent_mqa_core._REFERENCE_INDEXER_SCORER: collections.abc.Callable | None#
None
- bridge.models.ernie.modeling_ernie55.latent_mqa_core._REFERENCE_INDEXER_SCORER_PROBED#
False
- bridge.models.ernie.modeling_ernie55.latent_mqa_core._reference_indexer_scorer(
- q: torch.Tensor,
cuDNN’s
indexer_forward_wrapperwhen it can scoreqas the reference implementation does, else None.It needs a bf16 CUDA query and a cuDNN frontend whose wrapper takes
q_causal_offsets(1.26+), the per-chunk causal offset the reference passes for every chunk after the first.
- bridge.models.ernie.modeling_ernie55.latent_mqa_core._pack_covers_rows(
- packed_seq_params: megatron.core.packed_seq_params.PackedSeqParams,
- rows: int,
Whether a CP-1 pack’s boundaries end at its last row, i.e. it has no tail rows past
cu_seqlens[-1].Megatron-Core’s
PACKED_THD_GENERALplan scores only the rows itscu_seqlenscover, while the core treats tail rows as part of the last document, so the plan may only be requested for packs without them (every ERNIE 5.5 training batch). The last boundary comes from :func:pack_end: the host value the ERNIE 5.5 batch builder notes, or one device read per micro-batch for metadata built elsewhere.
- bridge.models.ernie.modeling_ernie55.latent_mqa_core._cudnn_indexer_score_scale(
- scale: float | None,
Set Megatron-Core’s cuDNN indexer score scale (
dsa_cudnn_kernels._INDEXER_SOFTMAX_SCALE) for a block.The cuDNN DSA hooks read it at call time for the top-k scores, the KL inputs and the indexer backward.
Noneleaves it alone.
- bridge.models.ernie.modeling_ernie55.latent_mqa_core._requested_indexer_scoring_plan(hook_kwargs: dict) str#
Scoring plan the packed-layout arguments of one fused top-k hook call select in Megatron-Core’s cuDNN backend.
Without packed metadata (SBHD batches) ERNIE’s lagging bounds are not causal, so the backend resolves
UNFUSED_BOUNDS. With it (packed THD rows:use_local_indexer_varlen=True, identity key positions, onecu_seqlenstensor for queries and keys,sk = CP * sq) it resolvesPACKED_THD_GENERAL, unlesssingle_packed_thd_sequence=Trueselects the single-sequence segment scorer. Megatron-Core still falls back toUNFUSED_BOUNDSwhen the installed cuDNN frontend lacks the per-segment query offsetsPACKED_THD_GENERALneeds at CP > 1, and then logs that itself; the GPU tests pin the executor that actually runs.- Parameters:
hook_kwargs – The keyword arguments the hook was called with.
- bridge.models.ernie.modeling_ernie55.latent_mqa_core.indexer_loss_layer_number(
- config: megatron.core.transformer.transformer_config.TransformerConfig,
- layer_number: int,
- is_mtp_layer: bool,
Return the indexer-loss tracker slot of a D layer.
Decoder layers log at their hybrid position; MTP layers are shifted past the decoder by
config.num_layers, the Megatron-Core DSA convention. Every MTP depth’s inner stack restarts at layer 1, so withmtp_num_layers >= 2the depths share their slots (also the Megatron-Core convention).- Parameters:
config – Layer config (
num_layersis the decoder’s hybrid layer count).layer_number – 1-based hybrid position of the layer in its stack.
is_mtp_layer – Whether the layer belongs to a multi-token-prediction stack.
- Returns:
1-based tracker slot.
- bridge.models.ernie.modeling_ernie55.latent_mqa_core._param_device(
- config: megatron.core.transformer.transformer_config.TransformerConfig,
Device for parameters this module allocates itself, chosen like Megatron-Core’s TE modules.
- bridge.models.ernie.modeling_ernie55.latent_mqa_core._check_fused_geometry(
- config: megatron.core.transformer.transformer_config.TransformerConfig,
Raise if the D-layer geometry cannot run on FlashMLA and the cuDNN DSA kernels.
- bridge.models.ernie.modeling_ernie55.latent_mqa_core._check_fused_attention_inputs(
- query: torch.Tensor,
- key: torch.Tensor,
Raise unless the fused sparse attention can take
queryandkey(bf16 CUDA tensors).
- class bridge.models.ernie.modeling_ernie55.latent_mqa_core._FlashMLASinkGradFallback#
Bases:
torch.autograd.FunctionFlashMLA sparse forward with a sink, cuDNN backward with an analytic sink gradient.
Megatron-Core’s native path (
csa_sparse_attn) lets the cuDNN backward differentiate the sink, which Megatron-Core has only run atd_qk = 512; ERNIE runsd_qk = 576. This function instead mirrors Megatron-Core DSA’sd_qk = 576sparse attention: index lists with per-row lengths (topk_length), the list width padded with-1to a multiple of 512 for FlashMLA, the ignored suffix replaced by non-negative placeholders before the backward, and the cuDNN backward run with the sink disabled (-inf). Invalid slots inside a row’s length (the CP-1 lists keep the-1holes of their key blocks) stay-1. The only additions are the finite sink in the FlashMLA forward and the sink folded into the log-sum-exp the backward receives (lse_full = logaddexp(lse, sink)), plus the analyticd_sink = -sum_rows exp(sink - lse_full) * rowsum(O * dO). It runs withernie_native_sink_grad=False. The native gradient is the default: it matched this function and an autograd reference on GB300 (test_sink_gradient).Inputs and outputs use the flat FlashMLA layout:
q [rows, H, 576],kv [rows_kv, 576],topk_idxs [rows, M]flat-global int32 indices (-1for an invalid slot),topk_length [rows]int32 lengths (slots past them are ignored), output[rows, H, d_v].With Megatron-Core dev, a deterministic backward is requested through Megatron-Core’s
_deterministic_sparse_bwd_kwargs(deterministic_modeortorch.use_deterministic_algorithms); it raises at the first backward when the GPU, the cuDNN frontend (>= 1.28) or the head count cannot provide one.- static forward(
- ctx,
- q: torch.Tensor,
- kv: torch.Tensor,
- attn_sink: torch.Tensor,
- topk_idxs: torch.Tensor,
- topk_length: torch.Tensor,
- softmax_scale: float,
- d_v: int,
- deterministic: bool,
Run FlashMLA with the sink in the denominator; save tensors for backward.
- static backward(ctx, grad_out: torch.Tensor)#
cuDNN sparse backward with
lse_fulland a disabled sink, plus analyticd_sink.
- class bridge.models.ernie.modeling_ernie55.latent_mqa_core.Ernie55LatentMQACoreSubmodules#
Submodules of :class:
Ernie55LatentMQACoreAttention.- Parameters:
indexer – Megatron-Core
DSAIndexerspec (linear_wq_b,linear_wk,k_norm,linear_weights_proj).linear_output_gate – Linear
q_lora_rank -> heads * v_head_dimfor the output gate. Built like the indexer linears (parallel_mode="duplicated", no bias).
- indexer: megatron.core.transformer.spec_utils.ModuleSpec | type | None#
None
- linear_output_gate: megatron.core.transformer.spec_utils.ModuleSpec | type | None#
None
- class bridge.models.ernie.modeling_ernie55.latent_mqa_core.Ernie55LatentMQACoreAttention(
- config: megatron.core.transformer.transformer_config.TransformerConfig,
- submodules: bridge.models.ernie.modeling_ernie55.latent_mqa_core.Ernie55LatentMQACoreSubmodules,
- layer_number: int,
- attn_mask_type: megatron.core.transformer.enums.AttnMaskType,
- attention_type: str,
- attention_dropout: float | None = None,
- softmax_scale: float | None = None,
- k_channels: int | None = None,
- v_channels: int | None = None,
- cp_comm_type: str | None = 'p2p',
- pg_collection: megatron.core.process_groups_config.ProcessGroupCollection | None = None,
- is_mtp_layer: bool = False,
Bases:
megatron.core.transformer.module.MegatronModuleERNIE 5.5 D-layer core: indexer top-k, windowed sparse latent MQA with a sink, V-up, VHA, gate.
The constructor mirrors Megatron-Core
DSAttentionbecauseAttention.__init__builds the core once withoutk_channels/v_channels/is_mtp_layerandAbsorbedMLASelfAttentionthen rebuilds it with them.Parameters owned by the module (names are pinned by the checkpoint mappings):
attn_sink[H]fp32, zero init: per-head sink logit (denominator only).vha_postmix_u[H, R]fp32,init_methodinit: VHA input-head factor.vha_postmix_v[H, R]fp32, zero init: VHA output-head factor (identity at init).linear_output_gate.weight[H * v_head_dim, q_lora_rank].indexer.{linear_wq_b, linear_wk, k_norm, linear_weights_proj}(Megatron-Core names). Thek_normweight and bias are stored in fp32, like the reference implementation;DSAIndexerapplies them with fp32 math (dsa_indexer_k_norm_fp32).
Hisnum_attention_headsandRisernie_vha_rank. The fp32 parameters are markedkeep_in_fp32soFloat16Moduleleaves them in fp32.deterministic_modeon the fused path: the sparse attention backward is deterministic, and raises at the first backward when the GPU (SM100 family), the cuDNN frontend (>= 1.28) or the head count cannot provide it. A Megatron-Core build without the deterministic backward only warns and falls back to atomics. The cuDNN indexer backward always accumulates with atomics.- Parameters:
config – D-layer config (see
ernie55_d_layer_config).submodules – Indexer and output-gate specs.
layer_number – 1-based hybrid position of the layer.
attn_mask_type – Must be
AttnMaskType.causal.attention_type – Must be
"self".attention_dropout – Must be
Noneor 0; the D layer has no attention dropout.softmax_scale – Attention logit scale; defaults to
1 / sqrt(k_channels).k_channels – Query/key width (
kv_lora_rank + qk_pos_emb_head_dim).v_channels – Latent value width (
kv_lora_rank).cp_comm_type – Unused; context parallelism always all-gathers the keys.
pg_collection – Process groups;
tpmust have size 1. Acpgroup of size > 1 needs Megatron-Core’s CP partition converter (dev) and zigzag packed THD input.is_mtp_layer – Shift the indexer-loss tracker slot past the decoder layers.
.. attribute:: requested_indexer_scoring_plan
How the last fused forward selected the attention’s top-k:
- Data:
INDEXER_SCORING_REFERENCE_ORDER(the core’s own CP-1 scorer), or the Megatron-Core plan that the arguments of the last top-k hook call select (:data:INDEXER_SCORING_PACKED_THD_GENERALfor packed THD rows,- data:
INDEXER_SCORING_UNFUSED_BOUNDSfor SBHD batches);Nonebefore the first call. Megatron-Core can still runUNFUSED_BOUNDSinstead ofPACKED_THD_GENERAL(a cuDNN frontend without per-segment query offsets), which it logs itself.
.. attribute:: requested_indexer_loss_scoring_plan
The Megatron-Core plan that the arguments of the last loss-hook call select, or
Nonebefore the first one.Initialization
- consumes_absorbed_v_up_projection#
True
- requires_dsa_inputs#
True
- logs_dsa_indexer_loss#
True
- _keep_indexer_k_norm_in_fp32() None#
Store the indexer key-norm weight and bias in fp32 (
keep_in_fp32), as the reference does.DSAIndexerappliesk_normwith fp32 math on.float()copies of its parameters (dsa_indexer_k_norm_fp32), so only the stored precision changes: checkpoint values and optimizer updates are no longer rounded to the activation dtype.
- _check_parallel_sizes() None#
Reject tensor parallelism, and context parallelism on Megatron-Core builds without the CP converter.
- _indexer_loss_coeff(cp_size: int) float#
Coefficient handed to the loss kernels:
coeff / CPfor per-row loss under context parallelism.Each rank’s per-row loss is then normalized by the rows of the whole pack, not by its own rows (see the module docstring).
- backward_dw() None#
Run deferred weight-gradient computation of the indexer and the output gate.
- forward(
- query: torch.Tensor,
- key: torch.Tensor,
- value: torch.Tensor | None,
- attention_mask: torch.Tensor | None,
- x: torch.Tensor,
- qr: torch.Tensor,
- position_ids: torch.Tensor | None = None,
- attn_mask_type: megatron.core.transformer.enums.AttnMaskType | None = None,
- attention_bias: torch.Tensor | None = None,
- packed_seq_params: megatron.core.packed_seq_params.PackedSeqParams | None = None,
- up_v_weight: torch.Tensor | None = None,
Run the D-layer core.
attention_maskandposition_idsare ignored: the layer is causal within each document, and the documents come frompacked_seq_params(one per sample without THD packing).Under context parallelism the inputs are this rank’s rows of a packed THD micro-batch in the zigzag partition (
packed_seq_params.cp_partition_mode == "zigzag"); the keys of the whole pack are gathered over the CP group (see the module docstring).- Parameters:
query – Absorbed query
[s, b, H, kv_lora + rope]or packed[T, H, kv_lora + rope].key – Latent key
[s, b, 1, kv_lora + rope]or packed[T, 1, kv_lora + rope].value – Must be
None(the value is the latent key’s firstkv_lora_rankchannels).attention_mask – Ignored.
x – Layer input
[s, b, hidden]([T, 1, hidden]for THD), used by the indexer.qr – q latent
[s, b, q_lora]or packed[T, q_lora].position_ids – Ignored.
attn_mask_type –
NoneorAttnMaskType.causal.attention_bias – Must be
None.packed_seq_params – THD document boundaries, or
Nonefor SBHD.up_v_weight – Per-head V up-projection
[H, v_head_dim, kv_lora_rank].
- Returns:
[s, b, H * v_head_dim]([T, 1, H * v_head_dim]for THD, the local rows under context parallelism).
- static _normalize_layout(
- query: torch.Tensor,
- key: torch.Tensor,
- qr: torch.Tensor,
Return
query [s, b, H, D],key [s, b, D],key [s, b, 1, D]andqr [s, b, q_lora].A packed THD pack is treated as SBHD with
b = 1, so local key indices equal packed row indices.
- _select_topk(
- q_indexer: torch.Tensor,
- k_indexer: torch.Tensor,
- w_indexer: torch.Tensor,
- query: torch.Tensor,
- key_heads: torch.Tensor,
- starts: torch.Tensor,
- kernel_ends: torch.Tensor,
- use_indexer_loss: bool,
- *,
- packed_seq_params: megatron.core.packed_seq_params.PackedSeqParams | None = None,
- geometry: megatron.bridge.models.ernie.modeling_ernie55.context_parallel.ZigzagCpGeometry | None = None,
Select the top-k remote keys and, in training, compute the indexer KL loss.
Under context parallelism (
geometrygiven) the queries are the local rows and the keys (k_indexer,key_heads) and the bounds are those of the whole pack. Scores use the reference implementation’s convention on every path (see the module docstring).- Returns:
int32
[b, s, K](-1padded) and the scalar loss, orNonewhen the loss is inactive.- Return type:
(topk, loss)
- static _packed_cp_hook_kwargs(
- packed_seq_params: megatron.core.packed_seq_params.PackedSeqParams,
- geometry: megatron.bridge.models.ernie.modeling_ernie55.context_parallel.ZigzagCpGeometry | None,
- local_rows: int,
Arguments that select Megatron-Core’s
PACKED_THD_GENERALscorer for a packed THD pack.At CP > 1 (
geometrygiven) the zigzag plan; at CP = 1 (geometryisNone) the same plan with one rank holding every row. The scorer accepts the packed layout only when the query and keycu_seqlensare one tensor (or one view), so the hook gets metadata whose fourcu_seqlensfields are the padded query boundaries; the layer is self attention and the boundaries were checked to be identical.single_packed_thd_sequencestaysFalseeven for one-document packs: Megatron-Core’s single-sequence segment scorer picks wrong top-k with cuDNN frontend >= 1.26 (Megatron-Core #8534) and ignores per-row ends.
- _run_topk_hook(hook, *args, **hook_kwargs)#
Call a Megatron-Core fused top-k hook and record the scoring plan its keyword arguments select.
Both hooks go through here, so :attr:
requested_indexer_scoring_plandescribes the arguments the hook that ran actually received. The cuDNN hooks run with the reference’s score scaled^-0.5(their weights arew * d^0.5); see the module docstring.- Returns:
The hook’s result,
Nonewhen it declines.
- _record_scoring_plan(plan: str) None#
Record the scoring plan of the last fused top-k call and log it once per plan.
- _fused_topk(
- q_indexer: torch.Tensor,
- k_indexer: torch.Tensor,
- w_indexer: torch.Tensor,
- query: torch.Tensor,
- key_heads: torch.Tensor,
- starts: torch.Tensor,
- kernel_ends: torch.Tensor,
- use_indexer_loss: bool,
- *,
- packed_seq_params: megatron.core.packed_seq_params.PackedSeqParams | None = None,
- geometry: megatron.bridge.models.ernie.modeling_ernie55.context_parallel.ZigzagCpGeometry | None = None,
- w_reference: torch.Tensor | None = None,
Top-k (and loss) on the fused path;
Nonewhen a hook declines.At CP = 1 the attention’s top-k comes from :meth:
_reference_order_topk(when cuDNN can score the inputs); the loss hook still runs for the loss, and its top-k, the same keys in key-id order, is discarded. Otherwise the hooks’ top-k is the attention’s.w_indexerare the weights the hooks take,w_referencethe reference-convention weights (w * d^0.5).
- _reference_order_topk(
- q_indexer: torch.Tensor,
- k_indexer: torch.Tensor,
- w_indexer: torch.Tensor,
- starts: torch.Tensor,
- ends: torch.Tensor,
The reference implementation’s top-k at CP = 1: its keys, in its order.
Step for step the reference implementation’s selection, so every call has the reference’s shapes: for each chunk of 512 query rows, cuDNN’s
indexer_forward_wrapperscores every key (ratio=1,sm_scale=d^-0.5, the chunk’s first row asq_causal_offsetsafter the first chunk), the keys outside[starts, ends)are set to-inf, andtorch.topkkeeps theKbest in descending score order; non-finite picks become-1. A row whose range holds only the placeholder candidate selects it, and the caller’s :func:mask_topk_beyond_endremoves it.- Parameters:
q_indexer –
[s, b, H, d]indexer queries.k_indexer –
[s, b, d]indexer keys.w_indexer –
[s, b, H]weights in the reference convention (w * d^0.5).starts – int32
[s]candidate starts.ends – int32
[s]candidate ends (exclusive).
- Returns:
int32
[b, s, K](-1padded), orNonewhen cuDNN cannot score the inputs.
- _fused_topk_with_loss(
- q_indexer: torch.Tensor,
- k_indexer: torch.Tensor,
- w_indexer: torch.Tensor,
- query: torch.Tensor,
- key_heads: torch.Tensor,
- starts: torch.Tensor,
- kernel_ends: torch.Tensor,
- cp_size: int,
- cp_kwargs: dict,
Top-k and indexer KL through the cuDNN loss hook, one call per sample when
b > 1.Megatron-Core’s batched hook drops the indexer gradient of every sample after the first (see the module docstring). Each per-sample call reduces over its own
srows, so the per-sample losses combine like the batched loss: their mean iscoeff * sum KL / (b * s)(per-row loss) and their sum is the rawcoeff * sum KL(per-token loss). Autograd scales each call’s precomputed indexer gradients by the same factor. Packed THD micro-batches (b = 1) pass the packed hook argumentscp_kwargs; context parallelism also passescoeff / CP(per-row loss).- Returns:
(topk [b, s, K], loss), orNonewhen the hook declines.
- _reference_topk(
- q_indexer: torch.Tensor,
- k_indexer: torch.Tensor,
- w_indexer: torch.Tensor,
- query: torch.Tensor,
- key_heads: torch.Tensor,
- starts: torch.Tensor,
- kernel_ends: torch.Tensor,
- use_indexer_loss: bool,
- cp_size: int = 1,
Top-k (and loss) with Megatron-Core’s PyTorch DSA reference, called by keyword.
Under context parallelism the queries are the local rows, the keys and bounds those of the whole pack, and the loss coefficient
coeff / CP(per-row loss).w_indexerare the reference-convention weights (w * d^0.5); the scores the loss reads are scaled byd^-0.5after the head reduction, as cuDNN’s kernel does (the top-k does not depend on it).
- _sparse_attention(
- query: torch.Tensor,
- key_mqa: torch.Tensor,
- indices: torch.Tensor,
- *,
- block_layout: bool = False,
Sparse latent MQA with the sink over per-sample
indices [b, s, K + W]intokey_mqa.key_mqais[s_kv, b, D]: the sample’s keys, or the gathered keys of the whole pack under context parallelism (b = 1), sos_kvmay exceed thesquery rows.On the fused path
block_layout(CP = 1) hands FlashMLA the rows without their all-invalid key blocks (:func:drop_invalid_key_blocks), keeping every other block’s keys and slots; otherwise (CP > 1) the valid keys are compacted to the front of each row.- Returns:
[s, b, H, kv_lora_rank]in the activation dtype.
- _save_indexer_loss(loss: torch.Tensor) None#
Log the indexer loss with Megatron-Core’s DSA tracker.
Under context parallelism the tracker averages the per-row loss over the CP group (the reference’s convention; each rank’s value is already normalized by the whole pack, so the logged value is
1 / CPof the pack’s row mean) and sums the per-token loss.