Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 20 additions & 4 deletions python/sglang/kernels/ops/attention/dsa/tilelang_kernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,13 @@ def fast_round_scale(amax, fp8_max_inv):
return fast_pow2(fast_log2_ceil(amax * fp8_max_inv))


@lru_cache(maxsize=1)
def _cuda_sm_count() -> int:
return torch.cuda.get_device_properties(
torch.cuda.current_device()
).multi_processor_count


@lru_cache(maxsize=8)
def _pick_inner_iter(seq: int, ni: int, cu: int, block_per_cu: int) -> int:
"""
Expand Down Expand Up @@ -1360,13 +1367,22 @@ def tilelang_sparse_fwd(
topk = indices.shape[-1]
assert topk % 64 == 0, "topk must be padded to a multiple of 64"

if _is_hip:
assert not return_lse, "tilelang HIP sparse fwd does not return LSE"
is_fp8_kv = kv.dtype in (torch.float8_e4m3fn, torch.float8_e4m3fnuz)
is_fp8_kv = kv.dtype in (torch.float8_e4m3fn, torch.float8_e4m3fnuz)
if _is_hip or is_fp8_kv:
assert (
not return_lse
), "tilelang partial+combine sparse fwd does not return LSE"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Support or reject DCP before routing CUDA FP8

With --dcp-size > 1, both DSA forward paths request LSE during decode and target verification via _should_return_dsa_dcp_lse, but CUDA FP8 now enters this partial-and-combine branch and immediately asserts that return_lse is false. Consequently, an otherwise accepted CUDA TileLang FP8 configuration aborts on its first DCP decode or verify step. The FP8 path must return LSE for cross-rank reduction, or argument validation must reject TileLang FP8 with DCP.

Useful? React with 👍 / 👎.

if is_fp8_kv:
if q.dtype != kv.dtype:
q = q.to(kv.dtype)
if _is_gfx95_supported:
if not _is_hip:
# CUDA: the fp8 partial kernel is generic TileLang (no HIP
# intrinsics). Tiles sized for the ~100 KB dynamic-smem class
# (SM12x): fp8 K tiles are half the bytes of bf16, so
# block_I=32/threads=128 uses ~25 KB smem and block_I=64
# would use ~42 KB; 32/128 is the shape validated on GB10.
block_I, threads, block_per_cu, cu = 32, 128, 1, _cuda_sm_count()
elif _is_gfx95_supported:
block_I, threads, block_per_cu, cu = 64, 256, 2, 256
else:
block_I, threads, block_per_cu, cu = 64, 256, 1, 304
Expand Down
40 changes: 31 additions & 9 deletions python/sglang/srt/arg_groups/overrides.py
Original file line number Diff line number Diff line change
Expand Up @@ -1919,20 +1919,42 @@ def _check_tilelang_dsa_fp8_kv(
*,
hip: bool,
) -> None:
"""tilelang's fp8 KV path is ROCm-only; the CUDA kernel hardcodes bfloat16.
Reject here instead of crashing at decode CUDA-graph capture."""
"""tilelang's fp8 KV path stores the raw MLA layout (nope + rope cast to
fp8_e4m3, no per-tile scales). On ROCm/HIP it is the default DSA path. On
CUDA the same generic TileLang fp8 kernel is used, but it requires fp8
tensor-core MMA (SM89+) and BOTH DSA backends to be tilelang, because every
other CUDA fp8 backend expects the scaled pool layout
(nope_fp8 + per-tile scales + bf16 rope). Reject unsupported combinations
here instead of crashing at decode CUDA-graph capture."""
if (
not hip
and kv_cache_dtype == "fp8_e4m3"
and "tilelang" in {prefill_backend, decode_backend}
hip
or kv_cache_dtype != "fp8_e4m3"
or "tilelang" not in {prefill_backend, decode_backend}
):
return
if prefill_backend != decode_backend:
raise ValueError(
"On CUDA, an fp8_e4m3 KV cache with a tilelang DSA backend requires "
"BOTH --dsa-prefill-backend and --dsa-decode-backend to be tilelang: "
"tilelang consumes the raw fp8 MLA KV layout, while the other CUDA "
"backends expect the scaled (nope_fp8 + scales + bf16 rope) layout "
f"(got prefill={prefill_backend}, decode={decode_backend})."
)
import torch

major, minor = torch.cuda.get_device_capability()
if major * 10 + minor < 89:
raise ValueError(
"The tilelang DSA prefill/decode kernels only support an fp8_e4m3 KV "
"cache on ROCm/HIP; on CUDA they require a bfloat16 KV cache. Use "
"--kv-cache-dtype bfloat16 with the tilelang backend, or keep "
"--kv-cache-dtype fp8_e4m3 and pick an fp8-capable DSA backend "
"The tilelang DSA fp8_e4m3 KV path on CUDA requires fp8 tensor-core "
f"MMA (SM89+); got sm_{major}{minor}. Use --kv-cache-dtype bfloat16 "
"with the tilelang backend, or pick an fp8-capable DSA backend "
"(flashmla_kv on Hopper, trtllm on Blackwell)."
)
logger.warning(
"Enabling the tilelang DSA fp8_e4m3 KV cache on CUDA: KV is stored as "
"raw fp8 (no per-tile scales), matching the ROCm tilelang path. Expect "
"a small accuracy delta vs a bfloat16 KV cache."
)


@register_post_process
Expand Down
10 changes: 10 additions & 0 deletions python/sglang/srt/layers/attention/dsa_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -535,6 +535,16 @@ def __init__(
self.supports_mha_one_shot: bool = True
self.dsa_prefill_impl: _DSA_IMPL_T = get_exec().kernel.dsa_prefill_backend
self.dsa_decode_impl: _DSA_IMPL_T = get_exec().kernel.dsa_decode_backend
if (
not _is_hip
and self.token_to_kv_pool.dtype == torch.float8_e4m3fn
and not self.dsa_kv_cache_store_fp8
and "tilelang" in (self.dsa_prefill_impl, self.dsa_decode_impl)
):
# CUDA TileLang fp8 path stores the raw (unscaled) MLA KV layout;
# the MHA_ONE_SHOT fp8 dequant helpers assume the scaled layout,
# so keep the one-shot MHA fast path off.
self.supports_mha_one_shot = False
self.dsa_topk_backend: DSATopKBackend = DSATopKBackend.resolve(model_runner)
if self.num_q_heads <= 64:
self.flashmla_kv_num_q_heads = 64
Expand Down
10 changes: 10 additions & 0 deletions python/sglang/srt/mem_cache/kv_cache_configurator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2291,6 +2291,16 @@ def calculate_mla_kv_cache_dim(
):
return kv_cache_dim

# On CUDA, the TileLang DSA kernels likewise consume the raw MLA KV layout
# when the KV cache is fp8. Arg validation (_check_tilelang_dsa_fp8_kv)
# guarantees prefill == decode == tilelang whenever tilelang is combined
# with an fp8_e4m3 KV cache on CUDA, so no mixed-layout consumer exists.
if not _is_hip and (
get_exec().kernel.dsa_prefill_backend == "tilelang"
and get_exec().kernel.dsa_decode_backend == "tilelang"
):
return kv_cache_dim

quant_block_size = DSATokenToKVPool.quant_block_size
rope_storage_dtype = DSATokenToKVPool.rope_storage_dtype
# Calculate override_kv_cache_dim for FP8 storage in backends that use scaled KV layout
Expand Down
13 changes: 11 additions & 2 deletions python/sglang/srt/mem_cache/memory_pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -4463,9 +4463,18 @@ def _write_mla_kv_buffer(
cache_k_nope: torch.Tensor,
cache_k_rope: torch.Tensor,
) -> None:
if _is_hip and self.use_dsa and self.dtype == fp8_dtype:
# HIP FP8 path uses raw MLA KV layout (nope + rope) without per-block scales.
if (
self.use_dsa
and self.dtype == fp8_dtype
and not self.dsa_kv_cache_store_fp8
):
# Raw MLA KV layout (nope + rope cast to fp8) without per-block
# scales: the HIP DSA kernels and the CUDA TileLang fp8 path.
# Fuse BF16/FP16 -> FP8 cast with paged KV write.
if cache_k_rope is None:
cache_k_rope = cache_k_nope.new_empty(
(*cache_k_nope.shape[:-1], 0)
)
set_mla_kv_buffer_triton_fp8_quant(
dst_buffer,
loc,
Comment on lines 4472 to 4474

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve DCP mapping in raw-FP8 cache writes

When CUDA TileLang FP8 is combined with --dcp-size > 1, loc contains widened logical token IDs, but set_mla_kv_buffer_triton_fp8_quant writes directly to dst_buffer[loc] without filtering by DCP ownership or dividing by the DCP world size. The normal MLA writer passes DCP_RANK/DCP_WORLD_SIZE and performs both operations, so this newly enabled branch can write the wrong row or access beyond the rank-local pool before attention runs. Add the same DCP mapping to the fused quant writer or reject this configuration.

Useful? React with 👍 / 👎.

Expand Down
97 changes: 97 additions & 0 deletions test/registered/attention/test_dsa_tilelang_fp8_kv_cuda.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
"""Execution test for the CUDA raw-fp8 tilelang DSA sparse path.

Ported from the probe validated on sm_121 (DGX Spark GB10); requires SM89+
for fp8 tensor-core MMA. Two properties, each of which has been observed to
fail when the path is broken:
1. one-hot: a single valid index per token makes softmax exactly 1.0 and
the fp8 prob-quant exact, so the kernel must return the gathered V row
nearly bit-exactly (decisive for gather/mask/normalize plumbing);
2. spread case vs an fp32 reference computed from the SAME quantized
inputs must sit inside the analytic fp8-prob-GEMM budget (0.04), and a
scrambled-index negative control must blow past it (proves the
comparator discriminates).
"""

import pytest
import torch

tilelang_kernel = pytest.importorskip(
"sglang.kernels.ops.attention.dsa.tilelang_kernel"
)

requires_fp8_cuda = pytest.mark.skipif(
not torch.cuda.is_available()
or torch.cuda.get_device_capability() < (8, 9),
reason="needs CUDA SM89+ for fp8 tensor-core MMA",
)

S, H, DV, TOPK, POOL = 4, 32, 512, 2112, 32768 # GLM-5.3-Flash NoPE geometry
SM_SCALE = DV**-0.5


def _rel_err(a, b):
return ((a.float() - b.float()).abs().max() / b.float().abs().max()).item()


def _make_inputs(seed):
g = torch.Generator(device="cuda").manual_seed(seed)
q = torch.randn(S, H, DV, device="cuda", dtype=torch.float32, generator=g) * 0.5
kv = torch.randn(POOL, 1, DV, device="cuda", dtype=torch.float32, generator=g) * 0.5
idx = torch.randint(1, POOL, (S, 1, TOPK), device="cuda", generator=g).to(
torch.int32
)
idx[:, :, -37:] = -1 # exercise the padded-tail mask path
return q.to(torch.bfloat16), kv.to(torch.bfloat16), idx


def _ref_attn_fp32(q32, kv32, idx):
out = torch.empty(S, H, DV, device="cuda", dtype=torch.float32)
kvf = kv32.squeeze(1)
for i in range(S):
ids = idx[i, 0].long()
m = ids >= 0
k = kvf[ids.clamp(min=0)]
logits = (q32[i] @ k.T) * SM_SCALE
logits[:, ~m] = float("-inf")
p = torch.softmax(logits, dim=-1)
out[i] = p @ k
return out


@requires_fp8_cuda
def test_fp8_one_hot_exact():
q, kv, _ = _make_inputs(0)
kv_fp8 = kv.to(torch.float8_e4m3fn)
idx_hot = torch.full((S, 1, TOPK), -1, device="cuda", dtype=torch.int32)
hot = torch.randint(1, POOL, (S,), device="cuda")
idx_hot[:, 0, 0] = hot.to(torch.int32)
out = tilelang_kernel.tilelang_sparse_fwd(q, kv_fp8, idx_hot, SM_SCALE, d_v=DV)
torch.cuda.synchronize()
expect = kv_fp8.float().squeeze(1)[hot.long()].unsqueeze(1).expand(S, H, DV)
rel = _rel_err(out.reshape(S, H, DV), expect)
assert rel < 1e-3, f"one-hot rel err {rel:.6f} exceeds 1e-3"


@requires_fp8_cuda
def test_fp8_spread_within_budget_and_negative_control_fails():
q, kv, idx = _make_inputs(1)
kv_fp8 = kv.to(torch.float8_e4m3fn)
out = tilelang_kernel.tilelang_sparse_fwd(q, kv_fp8, idx, SM_SCALE, d_v=DV)
torch.cuda.synchronize()
ref = _ref_attn_fp32(q.to(torch.float8_e4m3fn).float(), kv_fp8.float(), idx)
rel = _rel_err(out.reshape(S, H, DV), ref)
assert rel < 0.04, f"spread-case rel err {rel:.5f} exceeds fp8-prob budget"

idx_bad = idx.clone()
idx_bad[:, :, : TOPK // 2] = idx[:, :, TOPK // 2 : TOPK].flip(-1)[
:, :, : TOPK // 2
]
out_bad = tilelang_kernel.tilelang_sparse_fwd(
q, kv_fp8, idx_bad, SM_SCALE, d_v=DV
)
torch.cuda.synchronize()
rel_bad = _rel_err(out_bad.reshape(S, H, DV), ref)
assert rel_bad > 0.04, (
"scrambled indices still matched the reference — the comparator is "
f"not discriminating (rel err {rel_bad:.5f})"
)
Loading