class SdsaAttentionImpl(AttentionImpl):
"""MQA over each query's selected tokens. K and V are views of the cache's
[K | V] rows as page-size-1 pages, so there is no paging and no plan.
Each phase's core (SdsaConfig) attends in one of three ways. "token": a
token runs FlashInfer's trtllm-gen head-dim-256 static token-sparse kernel
as one or more requests, each with an equal share of its heads, whose page
list is its selected slots, as vLLM's FlashInfer sparse MLA backend
(FlashInferMLASparseImpl) gives that kernel its selections. "fa4": a token
is a FlashAttention 4 batch over its selected slots. "union": a group of
consecutive prefill tokens is an FA4 batch over the union of their
selections (SdsaPrefillPlan.run), each token's bitmask over it its mask,
the group's heads in one tile (PackGQA).
K/V are BF16, FP8 E4M3 or packed NVFP4 with the layer's per-tensor scales;
for FP8 and NVFP4 the query arrives quantized to FP8 by Attention with the
layer's q scale, as in vLLM's FlashInfer backend. NVFP4 K/V take the token
core: each launch first gathers its tokens' selected K/V to FP8 scratch
(FlashInfer's gather_nvfp4_kv_cache), divided by 6 to fit E4M3's range,
which the BMM scales restore.
"""
supports_quant_query_input = True
def __init__(
self,
num_heads: int,
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: float | None = None,
attn_type: str = AttentionType.DECODER,
kv_sharing_target_layer_name: str | None = None,
sinks: torch.Tensor | None = None,
*,
topk_indices_buffer: torch.Tensor,
valid_counts_buffer: torch.Tensor,
indexer_name: str,
sdsa_config: SdsaConfig,
) -> None:
if num_kv_heads != 1:
raise ValueError("SDSA requires one KV head")
if head_size != SDSA_CORE_HEAD_SIZE:
raise NotImplementedError("SDSA core attention serves head size 256")
# trtllm_fmha_kernel_launcher.cu: num_qo_heads / num_kv_heads <= 128.
if num_heads > 128:
raise NotImplementedError("SDSA core attention serves at most 128 heads")
if kv_cache_dtype not in SdsaAttentionBackend.supported_kv_cache_dtypes:
raise NotImplementedError(
f"SDSA core does not support {kv_cache_dtype} K/V"
)
if alibi_slopes is not None or sliding_window is not None or sinks is not None:
raise NotImplementedError(
"SDSA does not support ALiBi, sliding window, or sinks"
)
if logits_soft_cap:
raise NotImplementedError("SDSA does not support logits soft cap")
if attn_type != AttentionType.DECODER:
raise NotImplementedError("SDSA supports decoder self-attention only")
if kv_sharing_target_layer_name is not None:
raise NotImplementedError("SDSA does not support KV sharing")
self.num_heads = num_heads
# The fewest core requests per token that each fit the Q64 tile.
self.requests_per_token = next(
n
for n in range(1, num_heads + 1)
if num_heads % n == 0 and num_heads // n <= _CORE_HEADS_PER_REQUEST
)
self.head_size = head_size
self.scale = float(scale)
self.num_kv_heads = 1
self.kv_cache_dtype = kv_cache_dtype
self.attn_type = attn_type
# The core attends in FP8 for FP8 and NVFP4 caches alike (NVFP4 K/V are
# gathered to FP8); nvfp4_kv adds the packed layout and the gather.
self.fp8_kv = is_quantized_kv_cache(kv_cache_dtype)
self.nvfp4_kv = kv_cache_dtype == "nvfp4"
if self.nvfp4_kv and not has_nvfp4_kv_gather():
raise NotImplementedError(
"SDSA with NVFP4 K/V needs FlashInfer's "
"flashinfer.sdsa.token_sparse.gather_nvfp4_kv_cache"
)
self.topk_indices_buffer = topk_indices_buffer
self.valid_counts_buffer = valid_counts_buffer
self.indexer_name = indexer_name
self.counter_bytes: int | None = None # needs the device, known in forward
drafts = get_current_vllm_config().num_speculative_tokens
self.decode_core = sdsa_config.decode(
heads=num_heads, drafts=drafts, kv_cache_dtype=kv_cache_dtype
)
def do_kv_cache_update(
self,
layer: torch.nn.Module,
key: torch.Tensor,
value: torch.Tensor,
kv_cache: torch.Tensor,
slot_mapping: torch.Tensor,
) -> None:
# (B, 1, N, 2*D) -> ((B, N, 1, D), (B, N, 1, D)), as FlashAttention's;
# NVFP4 (B, 2, N, C) -> K and V head slots.
if self.nvfp4_kv:
key_cache, value_cache = kv_cache.transpose(1, 2).chunk(2, dim=-2)
else:
key_cache, value_cache = kv_cache.transpose(1, 2).split(
self.head_size, dim=-1
)
ops.reshape_and_cache_flash(
key,
value,
key_cache,
value_cache,
slot_mapping,
self.kv_cache_dtype,
layer._k_scale,
layer._v_scale,
)
def forward(
self,
layer: torch.nn.Module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
kv_cache: torch.Tensor,
attn_metadata: SdsaPagesMetadata | None,
output: torch.Tensor,
output_scale: torch.Tensor | None = None,
output_block_scale: torch.Tensor | None = None,
) -> torch.Tensor:
if output_scale is not None or output_block_scale is not None:
raise NotImplementedError("SDSA does not support fused output quantization")
from flashinfer.decode import trtllm_batch_decode_with_kv_cache
from flashinfer.token_sparse import token_sparse_kv_indices
from vllm.models.nemotron_shortcut.nvidia.sdsa.mask import sdsa_mask_mod
from vllm.vllm_flash_attn.cute.interface import _flash_attn_fwd
# Requested before the profiling run returns, so their memory is counted.
manager = current_workspace_manager()
workspace = manager.get_persistent(
"sdsa_core_workspace", (_CORE_WORKSPACE_BYTES,), torch.uint8, zero_init=True
)
# Zeroed once; the kernel leaves its split-KV semaphores zeroed.
if self.counter_bytes is None:
from flashinfer.utils import get_trtllm_gen_multi_ctas_kv_counter_bytes
self.counter_bytes = get_trtllm_gen_multi_ctas_kv_counter_bytes(
_CORE_MAX_ROWS, self.num_heads, num_compute_units(query.device.index)
)
counters = manager.get_persistent(
("sdsa_core_counters", self.num_heads),
(self.counter_bytes,),
torch.uint8,
zero_init=True,
)
# The kernel reads a K and a V slot list per request; ours are one list
# per token, repeated for each of its requests.
max_tokens, top_k = self.topk_indices_buffer.shape
layout = [((max_tokens, 2, top_k), torch.int32), ((max_tokens,), torch.int32)]
nvfp4_decode_requests = min(max_tokens, _NVFP4_MAX_REQUESTS)
nvfp4_prefill_requests = min(
max_tokens,
_CORE_MAX_ROWS,
_NVFP4_PREFILL_WORKSPACE_BYTES // (2 * top_k * self.head_size),
)
if self.nvfp4_kv:
# The gathered FP8 [K | V] rows and their requests' slot lists.
nvfp4_requests = max(nvfp4_decode_requests, nvfp4_prefill_requests)
layout += [
(
(nvfp4_requests * top_k, 1, 1, 2 * self.head_size),
torch.float8_e4m3fn,
),
((nvfp4_requests, 2, top_k), torch.int32),
]
scratch = manager.get_simultaneous(*layout)
block_tables, counts = scratch[:2]
if self.nvfp4_kv:
gathered, local_tables = scratch[2:]
if attn_metadata is None:
return output.zero_()
num_tokens = attn_metadata.num_actual_tokens
metadata = get_forward_context().attn_metadata
assert isinstance(metadata, dict)
indexer = metadata[self.indexer_name]
assert isinstance(indexer, SdsaIndexerMetadata)
decode_tokens = min(indexer.num_decodes * indexer.decode_rows, num_tokens)
prefill = indexer.prefill
block_scales = None
if self.nvfp4_kv:
# (B, 2, N, C): the K and V head slots, values then block scales.
key_cache, value_cache = kv_cache.chunk(2, dim=1)
key_cache, key_scales = nvfp4_split_data_scale(key_cache)
value_cache, value_scales = nvfp4_split_data_scale(value_cache)
block_scales = (key_scales, value_scales)
kv_dtype = torch.float8_e4m3fn
else:
# (B, 1, N, 2*D) -> token rows [K | V]; K and V as (B*N, 1, 1, D).
kv_cache = kv_cache.transpose(1, 2)
if kv_cache.stride(0) != kv_cache.shape[1] * kv_cache.stride(1):
raise RuntimeError("SDSA core attention requires contiguous KV pages")
rows = kv_cache.reshape(-1, 1, 1, 2 * self.head_size)
if self.fp8_kv:
rows = rows.view(torch.float8_e4m3fn)
kv_dtype = rows.dtype
key_cache, value_cache = rows.split(self.head_size, dim=-1)
if query.dtype != kv_dtype:
raise TypeError("SDSA core attention needs the query in the K/V dtype")
bmm1_scale, bmm2_scale = self.scale, 1.0
if self.fp8_kv:
bmm1_scale *= layer._q_scale_float * layer._k_scale_float
bmm2_scale = layer._v_scale_float
if self.nvfp4_kv:
# NVFP4's range is 6 * 448: the gather divides by 6 to fit E4M3.
bmm1_scale *= 6.0
bmm2_scale *= 6.0
def flash(q, out, page_table, lengths, **kwargs) -> None:
# A 0-dim scale expands to stride 0 everywhere; for one row PyTorch
# calls that contiguous, so FA4 passes it on and CuTe rejects the 0
# last stride.
v_descale = (
layer._v_scale.reshape(1, 1).expand(len(lengths), 1)
if self.fp8_kv
else None
)
_flash_attn_fwd(
q,
key_cache,
value_cache,
page_table=page_table,
seqused_k=lengths,
softmax_scale=bmm1_scale,
v_descale=v_descale,
out=out,
**kwargs,
)
def per_token(core, tokens, slots, lengths) -> None:
"""Each of `tokens` attends to its lengths[t] slots: as an FA4 batch
whose page table is slots[t] ("fa4"), or as trtllm-gen requests of
an equal share of its heads, whose K and V lists are slots[r]
("token")."""
q = query[tokens].reshape(len(lengths), -1, self.head_size)
out = output[tokens].view_as(q)
keys, values = key_cache, value_cache
if self.nvfp4_kv:
from flashinfer.sdsa.token_sparse import gather_nvfp4_kv_cache
selected = gathered[: len(lengths) * top_k]
gather_nvfp4_kv_cache(
(key_cache, value_cache),
block_scales,
slots,
lengths,
out=selected,
block_tables=local_tables[: len(lengths)],
)
keys, values = selected.chunk(2, dim=-1)
slots = local_tables[: len(lengths)]
if core == "fa4":
flash(q[:, None], out[:, None], slots, lengths, num_splits=0)
return
trtllm_batch_decode_with_kv_cache(
q,
(keys, values),
workspace,
slots,
lengths,
top_k,
bmm1_scale=bmm1_scale,
bmm2_scale=bmm2_scale,
out=out,
backend="trtllm-gen",
uses_shared_paged_kv_idx=False,
multi_ctas_kv_counter_buffer=counters,
sparse_top_k=top_k,
)
# Each decode token is `split` core requests. The token core splits a
# token's heads to fit its Q64 tile, only while the split grid has at
# most one request per SM and fits the table.
split = self.requests_per_token if self.decode_core == "token" else 1
if decode_tokens * split > min(
num_compute_units(query.device.index), max_tokens
):
split = 1
tokens_per_launch = min(max_tokens, _CORE_MAX_ROWS) // split
if self.nvfp4_kv:
tokens_per_launch = min(tokens_per_launch, nvfp4_decode_requests // split)
for start in range(0, decode_tokens, tokens_per_launch):
stop = min(start + tokens_per_launch, decode_tokens)
num_rows = (stop - start) * split
token_sparse_kv_indices(
self.topk_indices_buffer[start:stop],
indexer.token_requests[start:stop],
indexer.block_table,
block_tables=block_tables,
seq_lens=counts,
requests_per_token=split,
)
slots = block_tables[:num_rows]
if self.decode_core == "fa4":
slots = slots[:, 0]
per_token(self.decode_core, slice(start, stop), slots, counts[:num_rows])
if prefill is not None:
tokens, unions = slice(decode_tokens, num_tokens), prefill.unions
sizes = self.valid_counts_buffer[: len(unions)]
if prefill.core == "union":
flash(
query[tokens].view(-1, self.num_heads, self.head_size),
output[tokens].view(-1, self.num_heads, self.head_size),
unions,
sizes,
cu_seqlens_q=prefill.batch_starts,
max_seqlen_q=prefill.group,
mask_mod=sdsa_mask_mod,
aux_tensors=[prefill.mask],
)
else: # each one-token group's union is its token's slots
chunk = nvfp4_prefill_requests if self.nvfp4_kv else _CORE_MAX_ROWS
for start in range(0, len(unions), chunk):
part = slice(start, start + chunk)
slots, first = unions[part], decode_tokens + start
if prefill.core == "token": # as the K and the V list
slots = block_tables[: len(slots)]
slots.copy_(unions[part, None, :top_k])
tokens = slice(first, first + len(slots))
per_token(prefill.core, tokens, slots, sizes[part])
return output[:num_tokens]