bridge.models.ernie.modeling_ernie55.ops#

Pure tensor helpers for the ERNIE 5.5 D layer.

Nothing here launches a fused kernel, so every helper runs on CPU. The helpers cover the computation Megatron-Core lacks:

  • Index geometry. For query row t of a document that starts at d(t), the indexer may select among the remote keys [d(t), t - W] (W is csa_window_size) and the row always attends to its window [max(d(t), t - W + 1), t]. The two sets are disjoint and their union is every causal key of the document. Under context parallelism t and d(t) are global packed positions (the helpers take the local rows’ positions).

  • The VHA post-mix out'_k = sum_h (I + V U^T)[k, h] out_h on the head axis.

  • The sigmoid output gate out * sigmoid(gate_logits).

  • The analytic gradient of a softmax sink that only enters the denominator.

  • The FlashMLA key list of the reference implementation without its all-invalid key blocks.

All index tensors use -1 for an invalid slot and int32 storage, the convention of the Megatron-Core sparse-attention kernels.

Module Contents#

Functions#

_row_positions

int64 key coordinate of every query row: positions when given, else 0 .. num_rows - 1.

ernie55_document_starts

Return the first row of the document that owns each query row.

record_pack_end

Note on packed_seq_params the host value of its last boundary, so no layer has to read it from the device.

pack_end

The last boundary of a pack’s (padded) cu_seqlens on the host.

ernie55_selection_bounds

Return the indexer’s remote-candidate bounds [start, end) for every row.

ernie55_kernel_selection_ends

Widen empty candidate ranges to one key so no kernel ever sees an empty row.

mask_topk_beyond_end

Invalidate selected indices at or past the true candidate end.

ernie55_window_indices

Return each row’s sliding-window keys [max(doc_start, t - W + 1), t].

pad_topk

Right-pad selected indices with -1 to a fixed width.

vha_postmix

Mix attention heads with the low-rank-plus-identity matrix M = I + V U^T.

sigmoid_output_gate

Return out * sigmoid(gate_logits) element-wise.

lse_with_sink

Add a per-head sink to a log-sum-exp that excludes it.

attention_sink_grad

Analytic gradient of a softmax sink that enters only the denominator.

drop_invalid_key_blocks

Remove the key blocks that hold no valid index from FlashMLA key lists, keeping every other block as is.

Data#

API#

bridge.models.ernie.modeling_ernie55.ops.__all__#

[‘attention_sink_grad’, ‘drop_invalid_key_blocks’, ‘ernie55_document_starts’, ‘ernie55_kernel_select…

bridge.models.ernie.modeling_ernie55.ops._row_positions(
num_rows: int,
positions: torch.Tensor | None,
device: torch.device | str,
) → torch.Tensor#

int64 key coordinate of every query row: positions when given, else 0 .. num_rows - 1.

bridge.models.ernie.modeling_ernie55.ops.ernie55_document_starts(
packed_seq_params: megatron.core.packed_seq_params.PackedSeqParams | None,
seqlen: int,
device: torch.device | str,
*,
positions: torch.Tensor | None = None,
) → torch.Tensor#

Return the first row of the document that owns each query row.

Packed THD inputs take their document boundaries from

Func:

~megatron.core.transformer.experimental_attention_variant.dsa_layout.get_packed_qk_cu_seqlens, which prefers the padded cu_seqlens (the same boundaries the D-layer RoPE uses). Rows at or past cu_seqlens[-1] (tail padding) belong to the last document. The reference implementation assumes packs without such rows, so they are outside parity checks. Without THD packing (packed_seq_params is None or not "thd") every sample is a single document, so every start is 0.

Under context parallelism a rank holds only some rows of the pack; positions then gives the global packed position of each local row, and the starts are global packed positions too.

Parameters:
  • packed_seq_params – Packed-sequence metadata, or None for SBHD inputs.

  • seqlen – Number of query rows s (T for a THD pack, the local row count under context parallelism).

  • device – Device of the returned tensor.

  • positions – Optional int64 [s] global packed position of every row; None means row t is at position t.

Returns:

int64 tensor [s] with the document start of every row.

bridge.models.ernie.modeling_ernie55.ops._PACK_END_ATTR#

‘_ernie55_pack_end’

bridge.models.ernie.modeling_ernie55.ops.record_pack_end(
packed_seq_params: megatron.core.packed_seq_params.PackedSeqParams,
end: int,
) → None#

Note on packed_seq_params the host value of its last boundary, so no layer has to read it from the device.

The batch builder knows it when it builds the cu_seqlens. :func:pack_end returns it while the metadata still holds the same boundary tensor.

Parameters:
  • packed_seq_params – Packed THD metadata.

  • end – Its last boundary (cu_seqlens[-1] of the padded boundaries).

bridge.models.ernie.modeling_ernie55.ops.pack_end(
packed_seq_params: megatron.core.packed_seq_params.PackedSeqParams,
) → int#

The last boundary of a pack’s (padded) cu_seqlens on the host.

It is the value :func:record_pack_end noted for the current boundary tensor; otherwise it is read from the device (one synchronization) and noted the same way, so each micro-batch reads it at most once.

Parameters:

packed_seq_params – Packed THD metadata.

Returns:

cu_seqlens[-1] as a Python int.

bridge.models.ernie.modeling_ernie55.ops.ernie55_selection_bounds(
doc_start: torch.Tensor,
window_size: int,
*,
positions: torch.Tensor | None = None,
) → tuple[torch.Tensor, torch.Tensor]#

Return the indexer’s remote-candidate bounds [start, end) for every row.

Row t may select keys s with doc_start[t] <= s <= t - window_size, i.e. start = doc_start and end = max(doc_start, t - window_size + 1). The first window_size rows of every document have an empty range (start == end); see

Func:

ernie55_kernel_selection_ends before handing these bounds to a kernel.

With positions (context parallelism), t is the row’s global packed position and the bounds index the globally ordered keys.

Parameters:
  • doc_start – int64 [s] from :func:ernie55_document_starts.

  • window_size – Sliding-window width W (csa_window_size), at least 1.

  • positions – Optional int64 [s] global packed position of every row; None means row t is at position t.

Returns:

(starts, ends), both int32 [s], end exclusive.

bridge.models.ernie.modeling_ernie55.ops.ernie55_kernel_selection_ends(
*,
starts: torch.Tensor,
ends: torch.Tensor,
) → torch.Tensor#

Widen empty candidate ranges to one key so no kernel ever sees an empty row.

Megatron-Core’s top-k and indexer-loss kernels have only been exercised with causal bounds, where every row contains at least itself. An ERNIE row without remote candidates instead gets the single placeholder candidate start (its document start, which the window already covers). A one-candidate row has a KL of exactly 0 and no indexer gradient, so the loss is unchanged; :func:mask_topk_beyond_end removes the placeholder from the attention index list afterwards.

Parameters:
  • starts – int32 [s] candidate starts.

  • ends – int32 [s] true candidate ends (exclusive).

Returns:

int32 [s] kernel ends, max(ends, starts + 1).

bridge.models.ernie.modeling_ernie55.ops.mask_topk_beyond_end(
topk: torch.Tensor,
*,
ends: torch.Tensor,
) → torch.Tensor#

Invalidate selected indices at or past the true candidate end.

Only the placeholder added by :func:ernie55_kernel_selection_ends can lie past the true end, so this restores the exact ERNIE candidate set [start, end).

Parameters:
  • topk – [b, s, K] selected key indices, -1 for an empty slot.

  • ends – [s] true candidate ends (exclusive), shared by every sample.

Returns:

int32 [b, s, K] with every index >= ends[t] replaced by -1.

bridge.models.ernie.modeling_ernie55.ops.ernie55_window_indices(
doc_start: torch.Tensor,
*,
window_size: int,
batch_size: int,
positions: torch.Tensor | None = None,
) → torch.Tensor#

Return each row’s sliding-window keys [max(doc_start, t - W + 1), t].

Every row’s window contains the row itself, so no attention row is ever empty. Slot j holds max(doc_start[t], t - W + 1) + j, or -1 when that key lies after t; valid keys therefore come first and in ascending order.

With positions (context parallelism), t is the row’s global packed position and the window indexes the globally ordered keys.

Parameters:
  • doc_start – int64 [s] from :func:ernie55_document_starts.

  • window_size – Sliding-window width W.

  • batch_size – Number of samples b; every sample shares the same geometry.

  • positions – Optional int64 [s] global packed position of every row; None means row t is at position t.

Returns:

int32 [b, s, W] per-sample key indices.

bridge.models.ernie.modeling_ernie55.ops.pad_topk(topk: torch.Tensor, width: int) → torch.Tensor#

Right-pad selected indices with -1 to a fixed width.

PyTorch’s topk returns min(K, num_keys) columns; the attention index list [top-k | window] needs exactly K columns before the window.

Parameters:
  • topk – [b, s, k] indices with k <= width.

  • width – Target width K.

Returns:

int32 [b, s, width].

bridge.models.ernie.modeling_ernie55.ops.vha_postmix(
out: torch.Tensor,
*,
u: torch.Tensor,
v: torch.Tensor,
bf16_mix: bool,
) → torch.Tensor#

Mix attention heads with the low-rank-plus-identity matrix M = I + V U^T.

out'[..., k, :] = sum_h M[k, h] * out[..., h, :], so V indexes the output head and U the input head. V = 0 gives the identity.

Parameters:
  • out – [..., H, D] per-head attention output; the head axis is -2.

  • u – [H, R] input-head factor (an fp32 parameter in the model).

  • v – [H, R] output-head factor (an fp32 parameter in the model).

  • bf16_mix – When True, M is formed by one GEMM in the activation dtype (addmm(I, V, U^T)) and applied by a second GEMM in that dtype, which is the bf16 contract of the reference implementation. When False, M - I = V U^T is formed and the mix is accumulated in fp32 (or out.dtype if wider), and the result is rounded to out.dtype once.

Returns:

Tensor with the shape and dtype of out.

bridge.models.ernie.modeling_ernie55.ops.sigmoid_output_gate(
out: torch.Tensor,
*,
gate_logits: torch.Tensor,
fp32: bool,
) → torch.Tensor#

Return out * sigmoid(gate_logits) element-wise.

Parameters:
  • out – Attention output, flattened to [..., H * D] with index h * D + d.

  • gate_logits – Gate projection of the same shape and layout.

  • fp32 – When True, the sigmoid and the product run in fp32 (or out.dtype if wider) and the result is rounded to out.dtype once; otherwise both run in the activation dtype.

Returns:

Tensor with the shape and dtype of out.

bridge.models.ernie.modeling_ernie55.ops.lse_with_sink(
lse: torch.Tensor,
*,
attn_sink: torch.Tensor,
) → torch.Tensor#

Add a per-head sink to a log-sum-exp that excludes it.

Parameters:
  • lse – [rows, H] natural-log LSE over the selected keys only (FlashMLA’s lse).

  • attn_sink – [H] sink logits.

Returns:

[rows, H] logaddexp(lse, sink) in fp32 (or lse.dtype if wider).

bridge.models.ernie.modeling_ernie55.ops.attention_sink_grad(
*,
attn_sink: torch.Tensor,
lse: torch.Tensor,
out: torch.Tensor,
d_out: torch.Tensor,
) → torch.Tensor#

Analytic gradient of a softmax sink that enters only the denominator.

With o = sum_j e^{s_j} v_j / (sum_j e^{s_j} + e^{sigma}) per row and head, dL/dsigma = -e^{sigma - lse_full} * <o, dL/do>, where lse_full includes the sink. Summing over rows gives the per-head gradient.

Parameters:
  • attn_sink – [H] sink logits sigma.

  • lse – [rows, H] LSE over the selected keys, excluding the sink.

  • out – [rows, H, d_v] attention output.

  • d_out – [rows, H, d_v] gradient of the loss with respect to out.

Returns:

[H] gradient with respect to attn_sink, in fp32 (or lse.dtype if wider).

bridge.models.ernie.modeling_ernie55.ops.drop_invalid_key_blocks(
flat_idxs: torch.Tensor,
*,
block: int,
) → tuple[torch.Tensor, torch.Tensor]#

Remove the key blocks that hold no valid index from FlashMLA key lists, keeping every other block as is.

FlashMLA’s sparse forward reads a row’s list in blocks of keys (64 per block on SM100 at 64 heads, 128 at 128 heads) and folds each block into its online softmax as a unit; a block of -1 entries is an exact no-op. Which keys share a block, and the order of the blocks, decide the output bits. This keeps the content and the order of every block that holds a valid key, moves the blocks without one to the end and returns the kept length, so FlashMLA (with topk_length) computes exactly what it computes for the full list, while reading only the kept blocks. -1 entries inside a kept block stay where they are.

The reference implementation hands FlashMLA [top-k | window] rows of a fixed width, the top-k in score order followed by -1 padding and then the window: most of its blocks are empty for short documents. Applied to such rows with block 64 or 128, the result reproduces its FlashMLA output bitwise.

Parameters:
  • flat_idxs – [rows, width] flat key indices, -1 for an invalid slot.

  • block – Block granularity; a multiple of FlashMLA’s key block (on SM100, 64 at 64 heads and 128 at 128 heads; 128 on SM90).

Returns:

int32 [rows, ceil(width / block) * block] (padded with -1) and int32 [rows] kept lengths, a multiple of block (0 for a row without valid keys).

Return type:

(indices, topk_length)