flashinfer.mla.trtllm_batch_decode_with_kv_cache_mla¶
- flashinfer.mla.trtllm_batch_decode_with_kv_cache_mla(query: Tensor, kv_cache: Tensor, workspace_buffer: Tensor, qk_nope_head_dim: int, kv_lora_rank: int, qk_rope_head_dim: int, block_tables: Tensor, seq_lens: Tensor | None, max_seq_len: int, sparse_mla_top_k: int = 0, out: Tensor | None = None, bmm1_scale: float | Tensor = 1.0, bmm2_scale: float | Tensor = 1.0, sinks: List[Tensor] | None = None, skip_softmax_threshold_scale_factor: float | None = None, enable_pdl: bool | None = None, backend: str = 'auto', is_var_seq: bool = True, uses_shared_paged_kv_idx: bool = True, lse: Tensor | None = None, return_lse: bool = False, cute_dsl_impl: str = 'auto', kv_scale_format: str = 'auto', cum_seq_lens_q: Tensor | None = None, max_q_len: int | None = None, multi_ctas_kv_counter_buffer: Tensor | None = None, sparse_mla_top_k_lens: Tensor | None = None, enable_dcp: bool = False, cp_world: int = 1, cp_rank: int = 0, causal_seqlens_kv_global: Tensor | None = None, use_fp16_softmax: bool | None = None, return_lse_base: Literal['basee', 'base2'] | None = None) Tensor | Tuple[Tensor, Tensor]¶
Execute MLA decode or prefill through the selected backend: TRTLLM-GEN, CuteDSL, XQA, Cake, or SM120/SM121 sparse kernels.
With
backend="auto", SM100/SM103 devices use TRTLLM-GEN for sparse MLA whensparse_mla_top_k > 0. SM120/SM121 devices use the packed sparse backend forsparse_mla_top_k > 0and XQA for dense decode.- Parameters:
query (torch.Tensor) – Query tensor with shape
[batch_size, q_len_per_request, num_heads, head_dim_qk]wherehead_dim_qk = kv_lora_rank + qk_rope_head_dim. Whencum_seq_lens_qis provided, TRTLLM-GEN and monolithic CuTeDSL instead accept compact[total_q, num_heads, head_dim_qk]input. For the SM120/SM121 sparse backend, this must be BF16 withhead_dim_qk == 576for v32/GLM_NSA or512for GLM-5.3 NoPE.kv_cache (torch.Tensor) – For TRTLLM-GEN, CuteDSL, and XQA, the paged KV cache is
[num_pages, page_size, kv_lora_rank + qk_rope_head_dim]or[num_pages, 1, page_size, kv_lora_rank + qk_rope_head_dim]and uses the query-compatible dense dtype. For the SM120/SM121 v32/GLM sparse backend, this is a packed uint8 cache with 656 bytes per token, shaped[num_pages, page_size, 656]or[num_pages, 1, page_size, 656]; for GLM-5.3 NoPE the payload is 528 bytes per token and padded rows (any last dim >= 528, including a legacy 656 pool) are accepted.workspace_buffer (torch.Tensor) – Pre-allocated workspace buffer. Must be zero-initialized on first use by kernels that use semaphore state.
qk_nope_head_dim (int) – Non-RoPE query dimension before absorption. SM100/SM103 TRTLLM-GEN sparse MLA supports
64withkv_lora_rank=512andqk_rope_head_dim=64. The SM120/SM121 sparse v32/GLM backend validates it together withquery.shape[-1]. GLM-5.3 uses the nativeqk_rope_head_dim=0/query.shape[-1]=512geometry.kv_lora_rank (int) – Latent KV rank. TRTLLM-GEN and SM120/SM121 sparse v32/GLM use
512.qk_rope_head_dim (int) – RoPE head dimension. Sparse MLA paths use
64; the native no-RoPE TRTLLM-GEN path (kv_lora_rank=512) uses0.block_tables (torch.Tensor) – Page table for dense MLA backends when
sparse_mla_top_k == 0. For SM100/SM103 TRTLLM-GEN sparse MLA it is the usual paged block table. Whencum_seq_lens_qis provided with sparse MLA, pass compact sparse rows in flattened query-token order with shape[total_q, sparse_mla_top_k]. For SM120/SM121 sparse v32/GLM, it is the sparse index matrix and must have shape[batch_size, q_len_per_request, sparse_mla_top_k]with int32 physical token indices. Withbackend="trtllm-gen", the final dimension may use its native width and does not need padding to a multiple of128 / page_size.seq_lens (Optional[torch.Tensor]) – Per-request physical KV sequence lengths for dense and TRTLLM-GEN paths. With DCP these are rank-local lengths and continue to control paging, memory bounds, and split-KV. For SM120/SM121 sparse v32/GLM, pass
[batch_size, q_len_per_request]or flattened[batch_size * q_len_per_request]active top-k lengths; ifNone, every column inblock_tablesis active.max_seq_len (int) – Maximum physical KV sequence length used for dense/TRTLLM-GEN scheduling. With DCP this is the maximum rank-local length. Ignored by the SM120/SM121 sparse v32/GLM backend.
sparse_mla_top_k (int) – Enables sparse MLA when greater than zero. On SM100/SM103 this selects the TRTLLM-GEN sparse page-table path. On SM120/SM121 with
backend="auto"orbackend="sparse", this is the width of the packed v32/GLM sparse index matrix. The TRTLLM-GEN backend supports dense query input or flattened query input pluscum_seq_lens_q.out (Optional[torch.Tensor]) – Output tensor. If not provided, it is allocated internally.
bmm1_scale (Union[float, torch.Tensor]) – Fused scale for MLA BMM1. TRTLLM-GEN accepts a FP32 tensor or float. Blackwell, CuteDSL, XQA, and SM120/SM121 sparse v32/GLM require a float.
bmm2_scale (Union[float, torch.Tensor]) – Fused scale for MLA BMM2. TRTLLM-GEN accepts a FP32 tensor or float. Blackwell, CuteDSL, and XQA require a float. SM120/SM121 sparse v32/GLM requires
1.0.sinks (Optional[List[torch.Tensor]]) – Additional value per head in the denominator of the softmax. Supported by
cake,trtllm-gen,cute-dsl, andsparse. Oncute-dslthis requires the modular implementation;cute_dsl_impl="auto"(the default) promotes to modular automatically, andcute_dsl_impl="monolithic"with sinks set raisesValueError.skip_softmax_threshold_scale_factor (threshold scale factor for skipping softmax operations.) – Providing a value for this parameter enables skip-softmax sparsity as described in: https://arxiv.org/abs/2512.12087 If no value is provided, then standard attention is used. Setting the threshold to a higher value generally increases kernel performance at the cost of accuracy degradation. The actual threshold value equals the provided threshold_scale_factor divided by the context length.
enable_pdl (Optional[bool]) – Programmatic Dependent Launch toggle. When
None(default), auto-detects support from the query device. Honoured by thetrtllm-genandxqabackends; ignored bycute-dsl.backend (str = "auto") – Implementation backend. Valid values are
"auto","xqa","cake","trtllm-gen","cute-dsl", and"sparse"."cake"explicitly selects the source-level Blackwell semantic dispatcher. It covers its qualified BF16/FP8 dense, sparse, compact-Q, sink, LSE, and caller-owned-output envelope. An untuned"auto"call never selects it; underflashinfer.autotune(True)its dense Blackwell route can win a uniform-Q"auto"request (see Autotune below)."auto"chooses"trtllm-gen"for SM100/SM103 sparse MLA and chooses"sparse"for SM120/SM121 whensparse_mla_top_k > 0; otherwise SM120/SM121 dense decode uses"xqa". For compact variable Q on SM100/SM103,"auto"keeps TRTLLM-GEN when it supports the call and uses monolithic CuTeDSL for TRT gaps or LSE output. Thecute-dslbackend has monolithic and modular implementations with a common fixed-Q shape/dtype envelope. Compact variable Q is monolithic-only, while features such assinksare modular-only; selection is controlled by thecute_dsl_implkwarg below.is_var_seq (bool) – Whether the sequence length is variable. If True, the sequence length is variable. Otherwise,the sequence length is fixed for all the requests in the batch.
uses_shared_paged_kv_idx (bool = True) – Whether K and V page indices are shared as a unified index. True (default) uses vLLM/FlashInfer layout with a 2D page table. False uses TRT-LLM layout with a 3D page table
[batch_size, 2, max_num_pages_per_seq]. False is only supported for trtllm-gen backend.use_fp16_softmax (Optional[bool]) – Select the trtllm-gen
Fp16Softmaxcubin variant. MLA decode is the primary consumer of this flag — Fp16Softmax generation cubins are only shipped for MLA head dims (head_dim_qk/v ∈ {576/512, 320/256}). WhenNone(default) orFalsethe standard FP32-accumulator softmax cubin is used. Only supported bybackend="trtllm-gen"; passingTrueto other backends raisesValueError.lse (Optional[torch.Tensor] = None) –
Optional pre-allocated buffer for Log-Sum-Exp values. Supported by
cake,trtllm-gen,cute-dsl, andsparsebackends. Must have dtypetorch.float32. Accepted shapes:[batch_size * q_len_per_request, num_qo_heads](TRTLLM-GEN native; accepted by sparse), or[batch_size, q_len_per_request, num_qo_heads](cute-dsl native; also accepted by cute-dsl), or[total_q, num_qo_heads]for compact variable Q with monolithic CuTeDSL.
If
return_lseis True and this is None, a buffer will be allocated by the backend.return_lse (bool = False) – Whether to return LSE values. Supported by
cake,trtllm-gen,cute-dsl, andsparsebackends. When True, the function returns(out, lse). With compact variable Q, LSE is currently supported by monolithic CuTeDSL and by thecakeKimi-K3 FP8 route.return_lse_base (Optional[Literal["basee", "base2"]] = None) – Logarithm base of LSE values, including values written to a supplied
lsebuffer. Supported bytrtllm-gen,cute-dsl,sparseand thecakeKimi-K3 FP8 route."basee"selects natural-log units and"base2"selects base-2 units.Nonepreserves each backend’s historical default: base-2 fortrtllm-genandsparse, and natural-log for monolithiccute-dsland thecakeKimi-K3 route. Select an explicit base for stable units underbackend="auto". This option does not enable LSE output; usereturn_lse=Trueto request it. Other values raiseValueError.cute_dsl_impl (str = "auto") –
Which cute-dsl implementation to use. Honored when
backend="cute-dsl"and whenbackend="auto"considers the cute-dsl candidate; ignored for non-cute-dsl backends."auto"(default) — picks monolithic by default, automatically promoted to modular when the call uses a feature monolithic doesn’t support (currentlysinks), and keeps compact variable Q on monolithic."modular"— strict. Always run the modular kernels."monolithic"— strict. Always run the monolithic kernels; raiseValueErrorif the call uses any modular-only feature (e.g.sinks).
kv_scale_format (str = "auto") – Scale semantics for the SM120/SM121 packed v32/GLM sparse backend.
"auto"and"pow2_fp32"select DSv3.2 power-of-2 FP32 inline scales;"arbitrary_fp32"selects GLM-style arbitrary FP32 inline scales. Ignored by thetrtllm-gen,xqa, andcute-dslbackends.cum_seq_lens_q (Optional[torch.Tensor] = None) – Cumulative query sequence lengths for variable-length query support, shape
[batch_size + 1], dtypetorch.int32. Must be a 1D tensor with at least two entries. Whenmax_q_lenis not provided, this function validates that it starts with 0, ends atquery.size(0), and is monotonically non-decreasing. Supported by Blackwell, TRTLLM-GEN, and the monolithic CuTeDSL implementation. When provided,querymust have shape[total_q, num_heads, head_dim_qk]. For best performance, providemax_q_lentogether withcum_seq_lens_qto avoid host-side metadata validation.max_q_len (Optional[int] = None) – Maximum query sequence length across all requests when using
cum_seq_lens_q. Provide withcum_seq_lens_qto avoid host-side metadata validation. Must be greater than or equal to the maximum segment length represented bycum_seq_lens_q. Over-estimation is safe but may waste work; under-estimation is invalid and may produce incorrect output.multi_ctas_kv_counter_buffer (Optional[torch.Tensor] = None) – Optional caller-owned counter buffer for the
trtllm-genbackend. It must be contiguous, remain alive for every launch or CUDA graph replay that uses it, and be zero-initialized once. Allocate at least the number of bytes returned byget_trtllm_gen_multi_ctas_kv_counter_bytesfor the current batch size, query-head count, and device SM count; a contiguoustorch.uint8tensor created withtorch.zerosis recommended. Reuse is safe only for ordered, non-overlapping launches; use a distinct buffer for each concurrently executing CUDA stream or graph. Autotune profiling uses runner-owned internal storage; the caller buffer is used only for the final request.sparse_mla_top_k_lens (Optional[torch.Tensor] = None) – Flattened active sparse top-k lengths, one INT32 value per query token. Required by the native
kv_lora_rank=512, qk_rope_head_dim=0TRTLLM-GEN kernel. Sparse indices must be packed before any-1padding. Zero-length rows are unsupported; padded query rows should contain one valid dummy index and use length 1.enable_dcp (bool = False) – Statically enable cyclic decode context parallelism in the monolithic CuTeDSL MLA kernel (
backend="cute-dsl"or"auto") or in thebackend="cake"Kimi-K3 FP8 route (power-of-twocp_world). DCP returns a rank-local output/LSE state, soreturn_lse=Trueis required and the caller must merge rank states. Both fixed-Q input and compact variable-Q input described bycum_seq_lens_qare supported.cp_world (int = 1) – Compile-time context-parallel world size. Rank
rstores global KV positions whose token index modulocp_worldequalsr.cp_rank (int = 0) – Runtime-uniform context-parallel rank.
causal_seqlens_kv_global (Optional[torch.Tensor] = None) – Contiguous CUDA int32 tensor
[batch_size]containing the global exclusive causal bound for the newest query token. Required with DCP.
Note
In MLA, the actual BMM1 and BMM2 scales applied would be fused as: bmm1_scale = q_scale * k_scale * sm_scale / (head_dim_qk ** 0.5) bmm2_scale = v_scale * o_scale or, bmm1_scale = torch.Tensor([q_scale * k_scale * sm_scale / (head_dim_qk ** 0.5)) bmm2_scale = torch.Tensor([v_scale * o_scale])
The two scale factors should be static constant for cuda graph capture. Either (bmm1_scale, bmm2_scale) or (bmm1_scale_log2_tensor, bmm2_scale_tensor) should be provided.
- For static constant scale factors, the scale factors should be provided as float.
(bmm1_scale, bmm2_scale)
- For on-device fused scale tensors, which could dynamically change, the scale factors should be provided as torch.Tensor.
(bmm1_scale_log2_tensor, bmm2_scale_tensor)
Currently, only fp8 tensor core operation supports this mode.
When both are provided, the dynamic scale factor tensors will be used.
On SM100/SM103/SM107 dense MLA, calling under
flashinfer.autotune(True)withbackend="auto"profiles bothtrtllm-genandcute-dslwhen DCP is disabled. DCP profiles only its required monolithic CuTeDSL runner. Both modes use a bucketed batch sweep up to each runner’s kernel/workspace cap and cache the winning tactic per shape signature. Subsequent calls underautotune(False)use the cached choice; any batch outside the tuned range falls back to the runner’s default tactic with a one-time warning. On SM100a/SM103a, Cake’s generated Blackwell route (the onebackend="cake"takes for its dimension tuples) can winbackend="auto"in a second selection stage. The first stage is the selection above, unchanged: the same op ("trtllm_batch_decode_mla"), runners, buckets, cache entries and replay records as without Cake, tuned and looked up first, so every bucket holds its TRTLLM-GEN / CuTe DSL winner and every lookup selects what it selects without Cake (a repeated lookup-only call of a listed batch reuses that result, see below). The second stage, the op"trtllm_batch_decode_mla_cake_margin", compares that winner with Cake per tuning bucket, under the sameautotune()settings, and (outsideautotune_v2contexts) keeps Cake unless the first-stage winner measures faster by more thantie_toleranceor by a tie of about 2.6 us (1.25 steps of the timer’s resolution) at the first stage’s time of the winner, whichever is wider (a relative tolerance, so it scales with the second stage’s measurement of the winner); it profiles Cake only against a first-stage winner, and a Cake result is valid only while the first stage keeps the winner Cake beat or tied. The second stage runs only for the units the device’s offer table (_CAKE_MLA_AUTO_OFFERS: device, dtype, page size,q_len,max_seq_lenbucket and batch range) lists, where Cake measured faster than the other candidates; elsewhere, and on devices the table does not list, Cake is never offered. Requests with sinks are not offered. Outside tuning the second stage runs only while the tuner holds a Cake result, and tuning underflashinfer.autotuner.set_autotune_process_groupskips it. Cake is eligible only for dense requests its aligned programs serve with the same semantics: BF16 query and cache with page size 32 or 64, or FP8 E4M3 query and cache with page size 64 and no sink; 128 heads of a generated dimension tuple, host float scales, shared K/V page indices and contiguous tensors; never with sparse MLA,sparse_mla_top_k_lens, skip-softmax,use_fp16_softmax, DCP, amulti_ctas_kv_counter_bufferor LSE output. Its generic tail program and the Kimi-K3 FP8 Cake route never join. Cake serves at most 512 query rows (batch * q_len; FP8 128) and is offered for a tuning bucket only when every batch the bucket serves is listed and launches the programs of the profiled batch, so never for the largest bucket. An untuned call never selects Cake. Every Cake miss runs the first stage’s selection: a cached Cake choice that cannot launch for the actual batch, whose first-stage winner changed, or whose program is not yet loaded during CUDA-graph capture, a failure while tuning Cake, and every request or setting that leaves Cake out, includingFLASHINFER_DISABLE_CAKE_AUTO_CANDIDATES=1.autotune_v2replay diagnostics record the first stage only; under strict replay a missing second-stage entry runs the first stage’s selection. Explicitbackend="cake"is unaffected. Unlike explicitbackend="cake", the candidate never readsseq_lenson the host and keeps no per-input plan or cached scratch, so in-place input updates and CUDA-graph replay with updated inputs stay correct; it never takes Cake’s exact-length programs. Its FP8 page-64 route allocates its split-K scratch (about 256 KiB per query row) on every call. Padded rows (seq_lens0, or a query row with no causal KV token) output zeros. Tuning measures GPU time under CUDA-graph replay; an eager caller also pays the host dispatch. Outside tuning, a batch no listed unit covers skips the second stage, and for a listed batch the decision of both stages (also the first stage’s alone, where Cake is left out because the tuner holds no Cake result (nor, withFLASHINFER_AUTOTUNER_LOAD_FROM_FILE=1, the bundled configs) or it is switched off) is reused for repeated calls with the same arguments and tensor sizes while the tuner, the offer table, every tuner’s winners and loaded configs, theautotune()overrides,skip_ops,FLASHINFER_AUTOTUNER_LOAD_FROM_FILEandFLASHINFER_DISABLE_CAKE_AUTO_CANDIDATESare unchanged (not while tuning, with anautotune_v2store or context, under replay diagnostics or with a measurement policy): such a call neither checks whether Cake joins, nor builds the tuning config, nor looks up, and builds only the selected runner; a reused Cake decision checks the contiguity of the tensors and that its programs are loaded, and launches the programs it resolved for those sizes. Amax_seq_lencounts as the same argument while its power-of-two bucket, its 128-token KV tile count and whether it reaches the device’s split-KV range are the same (the decision reads nothing else of it). A call with new arguments under the same tuner state (such as amax_seq_lenof another bucket) selects, but reuses the last check of whether Cake joins. Uniform explicit CuTeDSL requests use the same tuner with one candidate. Explicit TRTLLM-GEN requests enter the tuner only during tuning; inference directly executes its sole tactic. Compact variable-Q requests select an eligible backend directly and do not enter the autotuner. The internalautotuneexecution route does not introduce a public functionalbackend="autotune"option.The autotune bucket range and cache key do not depend on
kv_cache.shape[0](the number of pages in the pool), so reallocating the pool between tuning and inference does not invalidate cached choices. However, the page-aliasing ratio during profiling does depend on the pool size: syntheticblock_tablesare filled by uniform random sampling into[0, kv_cache.shape[0]), so a small pool produces high aliasing (L2-resident reads) and a large pool produces low aliasing (HBM-bound reads). For best profile fidelity, autotune with akv_cachewhose size reflects the production page-sharing pattern of your workload (e.g., heavily shared prefix → smaller pool; independent contexts → larger pool).