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
tof a document that starts atd(t), the indexer may select among the remote keys[d(t), t - W](Wiscsa_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 parallelismtandd(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_hon 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#
int64 key coordinate of every query row: |
|
Return the first row of the document that owns each query row. |
|
Note on |
|
The last boundary of a pack’s (padded) |
|
Return the indexer’s remote-candidate bounds |
|
Widen empty candidate ranges to one key so no kernel ever sees an empty row. |
|
Invalidate selected indices at or past the true candidate end. |
|
Return each row’s sliding-window keys |
|
Right-pad selected indices with |
|
Mix attention heads with the low-rank-plus-identity matrix |
|
Return |
|
Add a per-head sink to a log-sum-exp that excludes it. |
|
Analytic gradient of a softmax sink that enters only the denominator. |
|
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,
int64 key coordinate of every query row:
positionswhen given, else0 .. 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,
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 paddedcu_seqlens(the same boundaries the D-layer RoPE uses). Rows at or pastcu_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_paramsisNoneor 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;
positionsthen 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
Nonefor SBHD inputs.seqlen – Number of query rows
s(Tfor 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;Nonemeans rowtis at positiont.
- 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,
Note on
packed_seq_paramsthe 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_endreturns 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,
The last boundary of a pack’s (padded)
cu_seqlenson the host.It is the value :func:
record_pack_endnoted 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,
Return the indexer’s remote-candidate bounds
[start, end)for every row.Row
tmay select keysswithdoc_start[t] <= s <= t - window_size, i.e.start = doc_startandend = max(doc_start, t - window_size + 1). The firstwindow_sizerows of every document have an empty range (start == end); see- Func:
ernie55_kernel_selection_endsbefore handing these bounds to a kernel.
With
positions(context parallelism),tis 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;Nonemeans rowtis at positiont.
- Returns:
(starts, ends), both int32[s], end exclusive.
- bridge.models.ernie.modeling_ernie55.ops.ernie55_kernel_selection_ends(
- *,
- starts: torch.Tensor,
- ends: 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_endremoves 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,
Invalidate selected indices at or past the true candidate end.
Only the placeholder added by :func:
ernie55_kernel_selection_endscan lie past the true end, so this restores the exact ERNIE candidate set[start, end).- Parameters:
topk –
[b, s, K]selected key indices,-1for 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,
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
jholdsmax(doc_start[t], t - W + 1) + j, or-1when that key lies aftert; valid keys therefore come first and in ascending order.With
positions(context parallelism),tis 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;Nonemeans rowtis at positiont.
- 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
-1to a fixed width.PyTorch’s
topkreturnsmin(K, num_keys)columns; the attention index list[top-k | window]needs exactlyKcolumns before the window.- Parameters:
topk –
[b, s, k]indices withk <= 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,
Mix attention heads with the low-rank-plus-identity matrix
M = I + V U^T.out'[..., k, :] = sum_h M[k, h] * out[..., h, :], soVindexes the output head andUthe input head.V = 0gives 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,
Mis 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^Tis formed and the mix is accumulated in fp32 (orout.dtypeif wider), and the result is rounded toout.dtypeonce.
- 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,
Return
out * sigmoid(gate_logits)element-wise.- Parameters:
out – Attention output, flattened to
[..., H * D]with indexh * 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.dtypeif wider) and the result is rounded toout.dtypeonce; 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,
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’slse).attn_sink –
[H]sink logits.
- Returns:
[rows, H]logaddexp(lse, sink)in fp32 (orlse.dtypeif wider).
- bridge.models.ernie.modeling_ernie55.ops.attention_sink_grad(
- *,
- attn_sink: torch.Tensor,
- lse: torch.Tensor,
- out: torch.Tensor,
- d_out: 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>, wherelse_fullincludes the sink. Summing over rows gives the per-head gradient.- Parameters:
attn_sink –
[H]sink logitssigma.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 toout.
- Returns:
[H]gradient with respect toattn_sink, in fp32 (orlse.dtypeif wider).
- bridge.models.ernie.modeling_ernie55.ops.drop_invalid_key_blocks(
- flat_idxs: torch.Tensor,
- *,
- block: int,
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
-1entries 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 (withtopk_length) computes exactly what it computes for the full list, while reading only the kept blocks.-1entries 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-1padding and then the window: most of its blocks are empty for short documents. Applied to such rows withblock64 or 128, the result reproduces its FlashMLA output bitwise.- Parameters:
flat_idxs –
[rows, width]flat key indices,-1for 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 ofblock(0 for a row without valid keys).- Return type:
(indices, topk_length)