Skip to content

vllm.v1.attention.ops.rocm_aiter_mla_sparse

Functions:

_aiter_wo_a_bmm(a, a_scale, weight_preshuffled, weight_scale, n_groups, rank)

wo_a on AITER's tuned batched GEMMs and the preshuffled weight; [T, G * R].

_apply_candidate_mask_strided(logits, row_ks, row_ke, candidate_blocks, block_size, row_repeat=1)

ROCm decode variant of apply_candidate_mask.

Same masking semantics over [0, end), but the grid is sized by a fixed program count rather than by the logits width. Only worth using where the width is the max_model_len workspace and the live context is far shorter, i.e. the paged decode path below; the prefill chunks pass chunk-sized logits and stay on the shared kernel.

On gfx942 and gfx950 the candidate flags are built by the masking programs themselves, each over only its own live tiles, so the whole mask is a single launch and the flags past each row's end are never cleared.

_can_use_aiter_pa_prefill_sparse(q, kv)

Cheap gate. The AITER import runs only after this passes.

_decode_num_splits(num_queries, heads_blocks, avg_main_len=0.0, avg_extra_len=0.0, block_k=32)

Pick a flash-decode split count to keep the GPU busy across batch sizes.

Decode launches only num_queries * heads_blocks workgroups otherwise, which severely under-fills the device for the low-concurrency regime that dominates latency. Splitting the KV sequence adds parallelism.

We model the relative partial-kernel latency for a given split count s as waves * (1/s + mu) where waves = ceil(base * s / CU) and mu is a small per-wave overhead penalty:

  • waves / s captures the partial compute: each wave walks roughly total_tokens / s tokens and there are waves of them, so dividing by s makes more splits cheaper until they spill into extra waves.
  • mu * waves charges per-wave launch/tail overhead so we do not over-split into many mostly-idle waves (e.g. batch 224 on 256 CUs is best left at 1 split rather than 8 splits across 7 waves).

The minimiser naturally prefers split counts that pack the device into full waves (base * s near a multiple of CU) and falls back to 1 split once the batch already fills the device. Ties favour the smaller split count (less reduce work).

Finally we "snap down" the chosen split count to the smallest value that yields the same wave count and the same per-workgroup BLOCK_K iteration count. Because latency tracks iteration count (not raw token count), extra splits that do not lower the iteration count add only reduce/HBM overhead for no parallelism gain (e.g. batch 24: s8 and s10 both walk 4 extra iters in one wave, so s8 is strictly better). Snapping needs the average segment lengths, which the caller derives sync-free from the ragged index sizes.

_decode_partial_iters(avg_main_len, avg_extra_len, splits, block_k)

BLOCK_K iterations one partial workgroup walks for splits splits.

Each split processes ceil(seg_len / splits) tokens of a segment, walked BLOCK_K at a time, and the main/extra segments are handled separately.

_fused_inverse_rope_gptj(o, positions, cos_sin_cache, rope_head_dim, out=None)

bf16 inverse GPT-J RoPE via a single fused Triton kernel.

out may alias o: the rotation is a per-row bijection whose kernel reads both lanes of a pair before storing either.

_get_cached_wo_a_bf16(wo_a, n_local_groups, o_lora_rank, hidden_dim)

Dequantize wo_a to bf16 once and cache it on the module.

wo_a weights are static, so the fp8 -> fp32 -> (* block scale) -> bf16 dequant only needs to run once. Recomputing it every decode step shows up in the profile as the largest copy/mul kernels (direct_copy float ~55us and MulFunctor float ~31us per two layers). SGLang / ATOM keep wo_a in bf16 and feed a plain bf16 GEMM; this mirrors that.

_indexer_k_is_c4a_block_flat(compress_ratio)

V4.0 C4A is block-flat (NORMAL). Ratio 1 and 2 are 16×16 SHUFFLE.

_inverse_rope_gptj_kernel(o_ptr, out_ptr, pos_ptr, cos_sin_ptr, s_t, s_h, os_t, os_h, cs_stride, NOPE, HALF, BLOCK_NOPE, BLOCK_HALF)

Fused inverse GPT-J RoPE on the trailing rope_dim of each (token, head).

Mirrors DeepseekV4ScalingRotaryEmbedding.forward_native(inverse=True) for the GPT-J (non-neox) layout, writing bf16 directly. Replaces the clone + index_select + repeat_interleave + neg + stack + cat + cast chain (~10 small kernels) with a single launch.

_max_decode_logits_rows(num_batched_tokens)

Upper bound on decode rows the paged-MQA logits buffer can ever hold.

rocm_fp8_paged_mqa_logits sizes its workspace as (batch_size * next_n, max_model_len). batch_size is bounded by max_num_seqs and next_n by 1 + num_speculative_tokens, which is far tighter than max_num_batched_tokens -- 192 vs 16384 for a typical 32-seq DSpark-5 deployment. The loose bound is harmless at short contexts but scales with max_model_len, so at the model's full context it asks for tens of TiB and the engine cannot start. Take whichever valid bound is smaller; the workspace is locked after profiling, so it must not be under- estimated.

_mxfp8_quantize_rows(x, ROWS, COLS)

MXFP8-quantize x [ROWS, COLS] in registers, one scale per 32 lanes.

Returns the rescaled fp32 values (to be cast to e4m3 on store) and the [ROWS, COLS // 32] biased E8M0 exponents.

_mxfp8_scale_bits(amax)

Biased E8M0 exponent that puts amax at the top of the e4m3 range.

Same rounding as mxfp8_e4m3_quantize, so the output is bit-identical to quantizing the tensor there.

_mxfp8_wo_a_bmm_config(num_tokens, n_groups)

(BLOCK_M, BLOCK_N, BLOCK_K, num_warps, num_stages) for gfx950.

Tuned under HIP graphs with a cold weight at G = 4 and 2, over every decode shape of conc 1-128 x 0-5 spec tokens plus prefill chunks up to 8K tokens. The best tile tracks the total work T * G, so the tiers are keyed on it.

This will be replaced after new GEMM kernel from AITER with proper 32x32 scale shape GEMM fp8 enabled.

_rocm_sparse_attn_decode_ragged_bf16_triton(q, kv, indices, indptr, scale, attn_sink, nope_head_dim, rope_head_dim, num_splits, out=None, is_mxfp4=False)

Split-K decode over an bf16 ragged KV cache.

Partitions each query's selected tokens across different workgroups and combines the partials through reduction.

Parameters:

  • q

    (Tensor) –

    Queries laid out as [sq, h, d].

  • kv

    (Tensor) –

    Unquantized KV rows laid out as [skv, d].

  • indices

    (Tensor) –

    Flattened per-query KV slots.

  • indptr

    (Tensor) –

    Segment offsets into indices, [sq + 1].

  • scale

    (float) –

    Softmax scale.

  • attn_sink

    (Tensor | None) –

    Optional per-head sink logits.

  • nope_head_dim

    (int) –

    NoPE width of d.

  • rope_head_dim

    (int) –

    RoPE width of d.

  • num_splits

    (int) –

    Number of KV splits per query.

  • out

    (Tensor | None, default: None ) –

    Optional destination with d trailing elements.

  • is_mxfp4

    (bool, default: False ) –

    kv holds packed mxfp4_mla rows instead of bf16.

Returns:

  • Tensor –

    The attention output, out when provided.

_rocm_sparse_attn_decode_ragged_triton(q, main_cache, main_indices, main_indptr, scale, attn_sink, nope_head_dim, rope_head_dim, extra_cache=None, extra_indices=None, extra_indptr=None, out=None, extra_cache_nan_free=False, adaptive_splits=False, inv_rope_positions=None, inv_rope_cos_sin_cache=None, out_mxfp8=None)

Split-K sparse decode; returns the attention output.

With out_mxfp8 = (data, scale) the reduce writes MXFP8 instead of bf16: data is [b, h * d] e4m3 and scale [b, h * d // 32] E8M0, and data viewed as [b, h, d] is returned.

_rocm_sparse_attn_prefill_aiter(pa_prefill_sparse, q, kv, indices, indptr, scale, attn_sink, output)

gfx942 path. One KV pool; the extend sources stay unset.

_unshuffle_indexer_k_values(values, block_size, dim)

[..., block_size * dim] FP8 bytes in 16x16 SHUFFLE tile order ([blk/16, dim/16, 16, 16]) -> flat rows ([blk, dim]).

build_prefill_topk_ragged_indices(topk_indices, token_to_req_indices, query_start_loc, seq_lens, is_valid_token, block_table, block_size, compress_ratio, num_compressed, token_offset, num_rows=-1)

Map prefill top-k rows to a ragged stream of compressed-cache slots.

topk_indices holds local compressed positions for the prefill tokens, which sit at token_offset in the batch; token_to_req_indices, query_start_loc, seq_lens and block_table are batch-wide. block_size is the compressed cache's, i.e. already divided by the ratio.

exchange_shardq_topk(k_cache_prefix, prefill_metadata, topk_buffer, width)

Each TP rank scored only its ShardQ slice of the prefill tokens, written compactly after the decode rows; for layers with gather_shardq_topk, gather every rank's rows back into token order.

fp8_mqa_logits_torch(q, kv, weights, cu_seqlen_ks, cu_seqlen_ke)

Compute FP8 MQA logits for a single sequence without KV paging.

Parameters:

  • q

    (Tensor) –

    Query tensor of shape [M, H, D]. Casted to torch.float8_e4m3fn by caller.

  • kv

    (tuple[Tensor, Tensor]) –

    Tuple (k_fp8, k_scales) where k_fp8 has shape [N, D] with dtype torch.float8_e4m3fn and k_scales has shape [N] (or [N, 1]) with dtype torch.float32.

  • weights

    (Tensor) –

    weights of shape [M, H], dtype torch.float32.

  • cu_seqlen_ks

    (Tensor) –

    Start indices (inclusive) for valid K per query position, shape [M], dtype int32.

  • cu_seqlen_ke

    (Tensor) –

    End indices (exclusive) for valid K per query position, shape [M], dtype int32.

Returns:

  • Tensor –

    Logits tensor of shape [M, N], dtype torch.float32.

indexer_k_cache_is_shuffled(block_size)

Value layout of the ROCm FP8 indexer-K cache (ratio 1 / 2): 16x16 SHUFFLE tiles when a block holds more than one token, flat rows otherwise.

The one rule shared by the insert, the prefill gather and the paged-logits readers (and by fused writers, through their cache object), so a writer and its readers cannot disagree on the layout.

reserve_shardq_exchange(k_cache_prefix, *gathered)

Profiling run: the layer's ShardQ gathers, live together.

rocm_fp8_mqa_logits(q, kv, weights, cu_seqlen_ks, cu_seqlen_ke)

Compute FP8 MQA logits for a single sequence without KV paging.

Parameters:

  • q

    (Tensor) –

    Query tensor of shape [M, H, D]. Casted to torch.float8_e4m3fn by caller.

  • kv

    (tuple[Tensor, Tensor]) –

    Tuple (k_fp8, k_scales) where k_fp8 has shape [N, D] with dtype torch.float8_e4m3fn and k_scales has shape [N] (or [N, 1]) with dtype torch.float32.

  • weights

    (Tensor) –

    weights of shape [M, H], dtype torch.float32.

  • cu_seqlen_ks

    (Tensor) –

    Start indices (inclusive) for valid K per query position, shape [M], dtype int32.

  • cu_seqlen_ke

    (Tensor) –

    End indices (exclusive) for valid K per query position, shape [M], dtype int32.

Returns:

  • Tensor –

    Logits tensor of shape [M, N], dtype torch.float32.

rocm_fp8_paged_mqa_logits(q_fp8, kv_cache_fp8, weights, context_lens, block_tables, schedule_metadata, max_model_len, *, compress_ratio=1, cache_layout=None)

Compute FP8 MQA logits using paged KV-cache.

Parameters:

  • q_fp8

    (Tensor) –

    Query tensor of shape [B, next_n, H, D]. Casted to torch.float8_e4m3fn by caller.

  • kv_cache_fp8

    (Tensor) –

    Paged KV-cache in packed FP8+scale layout with shape [num_blocks, block_size, 1, D+4], dtype torch.uint8.

  • weights

    (Tensor) –

    Tensor of shape [B * next_n, H], dtype torch.float32.

  • context_lens

    (Tensor) –

    Tensor of shape [B] or [B, next_n], dtype int32; effective context length for each batch element, or for each of its Q rows.

  • block_tables

    (Tensor) –

    Tensor of shape [B, max_blocks], dtype int32; maps logical block indices to physical blocks in the paged cache.

  • schedule_metadata

    (Tensor) –

    Returned by get_paged_mqa_logits_metadata; used to distribute work across SMs.

  • max_model_len

    (int) –

    Maximum sequence length used to size the logits output.

  • compress_ratio

    (int, default: 1 ) –

    C4A (4) takes block-flat Triton; 1 and 2 stay on AITER.

  • cache_layout

    (str | None, default: None ) –

    Explicit cache layout override; "NORMAL" (block-flat) also takes the Triton path.

Returns:

  • Tensor –

    Logits tensor of shape [B * next_n, max_model_len], dtype

  • Tensor –

    torch.float32.

rocm_fp8_paged_mqa_logits_triton(q_fp8, kv_cache_fp8, weights, context_lens, block_tables, max_model_len)

Triton paged MQA-logits for decode and MTP; matches the torch ref but has no host sync, so it is safe to capture under a full CUDA graph.

rocm_inv_rope_einsum(rotary_emb, o, positions, rope_head_dim, n_local_groups, o_lora_rank, wo_a, inverse_rope=True)

Inverse-RoPE + WO_A bmm path used on ROCm.

Fuses the inverse GPT-J RoPE into one Triton kernel and caches the bf16 wo_a weight so the per-step dequant disappears. Callers whose attention already rotated every row pass inverse_rope=False; that is a property of the attention backend, not of the batch, so it stays constant across steps and is safe to read from compiled code.

rocm_inverse_rope_mxfp8_rows(o, positions, cos_sin_cache, rope_head_dim, out_data, out_scale)

Inverse-RoPE bf16 attention rows and MXFP8-quantize them for wo_a.

The counterpart of rocm_inverse_rope_rows_ for layers whose attention output is MXFP8: rows the decode reduce did not emit (prefill) go through here. o is [T, H, D]; out_data [T, H * D] e4m3 and out_scale [T, H * D // 32] E8M0, the layout the reduce epilogue writes.

rocm_inverse_rope_rows_(o, positions, cos_sin_cache, rope_head_dim)

Inverse-RoPE attention output rows in place.

For rows no attention kernel rotated in its epilogue. Call it from the eager attention segment: which rows still owe a rotation depends on the prefill/decode split, and the o_proj that used to do this runs inside the compiled region, where a batch-dependent Python value would be frozen at trace time.

rocm_mxfp8_wo_a_bmm(a, a_scale, wo_a, n_groups, o_lora_rank)

Grouped MXFP8 wo_a: out[t, g, :] = a[t, g, :] @ W[g].T, bf16 out.

a is the [T, G * K] e4m3 attention output and a_scale its [T, G * K // 32] E8M0 scales, as the sparse decode reduce writes them. The weight is the checkpoint's MXFP8 wo_a as loaded, [G * R, K] with either [G * R // 32, K // 32] block scales or [G * R, K // 32] per-row scales, so there is no dequantized copy to keep. A weight_preshuffled the linear kernel set (possibly the weight itself) runs AITER's GEMMs. Returns [T, G * R].

rocm_sparse_attn_decode(q, kv_cache, swa_k_cache, swa_only, topk_indices, topk_lens, swa_indices, swa_lens, swa_ragged_indices, swa_ragged_indptr, topk_ragged_indices, topk_ragged_indptr, attn_sink, scale, head_dim, nope_head_dim, rope_head_dim, output, extra_cache_nan_free=False, adaptive_splits=False, inv_rope_positions=None, inv_rope_cos_sin_cache=None, output_mxfp8=None)

Run sparse MLA decode into output.

Passing inv_rope_positions folds the inverse RoPE into the reduce epilogue. Returns how many leading rows of output came back rotated, so a caller mixing in a decode path that does not fuse still knows what it owes the standalone pass. Read it from the eager attention segment only.

output_mxfp8 = (data, scale) replaces output: the reduce also MXFP8-quantizes the rotated rows for the FP8 wo_a (see _rocm_sparse_attn_decode_ragged_triton). It needs gfx950 and the fused inverse RoPE, and always covers every row.

rocm_sparse_attn_decode_bf16(q, kv, scale, head_dim, nope_head_dim, rope_head_dim, attn_sink, output, ragged_indices, ragged_indptr, num_splits, kv_cache_dtype='auto')

Run split-K sparse attention over decode rows using an unquantized KV cache.

Parameters:

  • q

    (Tensor) –

    Decode queries laid out as [sq, h, d].

  • kv

    (Tensor) –

    KV cache laid out as [skv, 1, d].

  • scale

    (float) –

    Softmax scale.

  • head_dim

    (int) –

    Post-absorption head width.

  • nope_head_dim

    (int) –

    NoPE width of head_dim.

  • rope_head_dim

    (int) –

    RoPE width of head_dim.

  • attn_sink

    (Tensor | None) –

    Optional per-head sink logits.

  • output

    (Tensor) –

    Destination, written in place.

  • ragged_indices

    (Tensor) –

    Flattened per-query KV slots.

  • ragged_indptr

    (Tensor) –

    Segment offsets into ragged_indices, [sq + 1].

  • num_splits

    (int) –

    KV splits per query, from rocm_sparse_decode_bf16_num_splits.

  • kv_cache_dtype

    (str, default: 'auto' ) –

    "mxfp4_mla" reads kv as packed rows.

rocm_sparse_decode_bf16_num_splits(num_queries, num_heads, sparse_len)

Number or kv splits in splitK for the sparse bf16 decode, or 1 for single-pass.

Parameters:

  • num_queries

    (int) –

    Decode rows in the batch.

  • num_heads

    (int) –

    Query heads per row.

  • sparse_len

    (int) –

    Longest selected KV run any decode row can walk.

Returns:

  • int –

    The split count, or 1 when the caller should use the single-pass kernel.