Skip to content
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
7991319
Integrate TRT-LLM DSv4 sparse attention kernels.
akhilg-nv Jul 10, 2026
3730db3
Re-enable in-graph metadata prep on trtllm backend
akhilg-nv Aug 4, 2026
3f4fd44
Build trtllm metadata more efficiently
akhilg-nv Aug 5, 2026
0490d97
Enable MTP (EAGLE specdec) on the trtllm backend
akhilg-nv Jul 16, 2026
e8330ee
Merge branch 'main' into dsv4_fp8_trtllm_gen
b8zhong Aug 10, 2026
a090cac
ci: register the DSv4 trtllm backend test on a suite that actually runs
b8zhong Aug 10, 2026
c2b6798
test: run the per-commit B200 DSv4-Flash recipes on the trtllm attent…
b8zhong Aug 10, 2026
bc12ba2
fix: classify the trtllm prefill metadata fields in DSV4AttnMetadata.…
b8zhong Aug 10, 2026
b2cd983
Fix breakable cuda graphs, use host-side prep for MTP accuracy
akhilg-nv Aug 11, 2026
ec497fc
Merge branch 'main' into dsv4_fp8_trtllm_gen
b8zhong Aug 11, 2026
a6bc903
re-enable in-graph metadata prep for MTP, improve comments
akhilg-nv Aug 12, 2026
5f8078a
Fix for balanced MTP + DP
akhilg-nv Aug 12, 2026
2d77c92
Fix lint: strip trailing whitespace in deepseek_v4_backend comment
Aug 13, 2026
5c468f3
Avoid dummy extend for prefill BCG on DP with idle rank
akhilg-nv Aug 13, 2026
7a083d7
Merge remote-tracking branch 'fork/main' into dsv4_fp8_trtllm_gen
akhilg-nv Aug 13, 2026
562249d
Make trtllm default DSv4 attention backend for fp8 kv
akhilg-nv Aug 15, 2026
c588d47
Fix trtllm DSv4 kernel memory-safety under spec decoding + DP overlap
akhilg-nv Aug 15, 2026
9acd565
Disable overlap scheduler for trtllm DSv4 + spec + DP
akhilg-nv Aug 15, 2026
f79d774
Merge main into dsv4_fp8_trtllm_gen
YAMY1234 Aug 17, 2026
6a4ddd5
Fix DSV4 TRT-LLM prefill padding and backend guards
YAMY1234 Aug 17, 2026
07f527f
Fix DSV4 TRT-LLM speculative stability
YAMY1234 Aug 17, 2026
4aaeae5
Stabilize DSV4 disaggregation graph capture
YAMY1234 Aug 17, 2026
906e230
Merge main into dsv4_fp8_trtllm_gen
YAMY1234 Aug 18, 2026
507d0eb
Address review, make the trtllm DSV4 backend opt-in and self-contained
akhilg-nv Aug 21, 2026
74eb6f1
Merge remote-tracking branch 'fork/main' into dsv4_fp8_trtllm_gen
akhilg-nv Aug 21, 2026
f3bb0cc
Merge branch 'main' into dsv4_fp8_trtllm_gen
akhilg-nv Sep 1, 2026
3dfd842
Merge branch 'main' into dsv4_fp8_trtllm_gen
akhilg-nv Sep 3, 2026
39bc7db
style: format DSV4 compressor
YAMY1234 Sep 3, 2026
ebf0145
[DSv4] trtllm backend: drop unneeded shared-path changes, keep MTP, s…
YAMY1234 Sep 3, 2026
6865a90
Merge main into dsv4_fp8_trtllm_gen
YAMY1234 Sep 3, 2026
3666e12
style: trim DSV4 trtllm comments
YAMY1234 Sep 3, 2026
a47aa31
[DSv4] trtllm backend: fail closed on PD disaggregation and disabled …
YAMY1234 Sep 3, 2026
6c0337d
Merge branch 'main' into dsv4_fp8_trtllm_gen
nvpohanh Sep 4, 2026
4708f64
[DSv4] trtllm backend: point the PD disaggregation guard at tracking …
YAMY1234 Sep 4, 2026
44e9376
Merge branch 'main' into dsv4_fp8_trtllm_gen
YAMY1234 Sep 8, 2026
f432ba0
[DSv4] Move the trtllm backend test under test/registered/e2e/dsv4 pe…
YAMY1234 Sep 8, 2026
1ed93d9
[DSv4] trtllm hook: drop the removed CP V1 flags from the context-par…
YAMY1234 Sep 8, 2026
4021365
Merge branch 'main' into dsv4_fp8_trtllm_gen
nvpohanh Sep 9, 2026
1d82b50
[DSv4] trtllm BCG test: use --cuda-graph-max-bs-prefill (piecewise fl…
YAMY1234 Sep 9, 2026
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
20 changes: 20 additions & 0 deletions python/sglang/srt/arg_groups/deepseek_v4_hook.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,26 @@ def apply_deepseek_v4_defaults(server_args: ServerArgs, model_arch: str) -> None

run_post_process_pass(server_args, _deepseek_v4_kv_cache_dtype)

if server_args.dsv4_attn_backend == "trtllm":
from sglang.srt.utils.common import is_sm100_supported

assert (
server_args.device == "cuda" and is_sm100_supported()
), "--dsv4-attn-backend trtllm requires an SM100/SM103 (Blackwell) GPU."
# "auto" is declared-but-unmaterialized here; the resolution pipeline
# (_deepseek_v4_kv_cache_dtype above) turns it into fp8_e4m3 on cuda.
assert server_args.kv_cache_dtype in ("auto", "fp8_e4m3"), (
"--dsv4-attn-backend trtllm requires kv_cache_dtype=fp8_e4m3, "
Comment thread
akhilg-nv marked this conversation as resolved.
Resolved
f"got {server_args.kv_cache_dtype}."
)
assert (
not server_args.enable_hisparse
), "--dsv4-attn-backend trtllm does not support enable_hisparse."
logger.info(
"DeepSeek V4 attention: trtllm backend enabled "
"(uniform-FP8 KV pool, decode + sparse prefill)."
)

if server_args.max_running_requests is None:
server_args.max_running_requests = 256
logger.warning(
Expand Down
486 changes: 481 additions & 5 deletions python/sglang/srt/layers/attention/deepseek_v4_backend.py

Large diffs are not rendered by default.

132 changes: 92 additions & 40 deletions python/sglang/srt/layers/attention/dsv4/compressor_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,17 @@ def forward_unified(
compressor=compressor,
layer_id=layer_id,
)
elif token_to_kv_pool.uniform_fp8 and not compressor.is_in_indexer:
# The fused JIT epilogue only writes the packed layout; the
# uniform-FP8 pool goes through the unfused pipeline. The indexer
# compressor keeps its own (blockwise-FP8) path above.
self._forward_compress_uniform_fp8(
token_to_kv_pool=token_to_kv_pool,
kv_score_input=kv_score_input,
state_pool=state_pool,
compressor=compressor,
layer_id=layer_id,
)
else:
out_loc = self._get_out_loc(compressor.ratio)
use_fp4_indexer = (
Expand Down Expand Up @@ -280,36 +291,35 @@ def forward_unified(
or forward_batch.forward_mode,
)

def _forward_unified_hip(
def _compress_norm_rope_unfused(
self,
token_to_kv_pool: DeepSeekV4TokenToKVPool,
*,
kv_score_input: torch.Tensor,
state_pool,
compressor: Compressor,
layer_id: int,
) -> None:
"""HIP-specific forward path using PyTorch/Triton fallbacks."""
):
"""Shared unfused compress pipeline: compress_forward, decode
boundary zeroing, out_loc resolution, then norm + RoPE.

Returns ``(kv_compressed, out_loc_to_store)`` ready for a
pool-specific store, or ``None`` when there is nothing to compress.
The compression math is the same JIT kernel as the fused path; only
the epilogue is left to the caller.
"""
from sglang.kernels.ops.attention.deepseek_v4_rope import (
fused_norm_rope_inplace_triton,
)
from sglang.kernels.ops.attention.dsv4.quant_k_cache import (
quant_to_nope_fp8_rope_bf16_pack_triton,
)
from sglang.srt.layers.attention.nsa.nsa_indexer import rotate_activation
from sglang.srt.layers.attention.nsa.triton_kernel import act_quant

compress_ratio = compressor.ratio
head_dim = compressor.head_dim
is_indexer = compressor.is_in_indexer

plan = self._get_paged_compress_metadata(compress_ratio)
out_loc = self._get_out_loc(compress_ratio)

# Step 1: compress_forward (always use JIT for both C4 and C128)
coff = 2 if is_overlap_compress(compress_ratio) else 1
last_dim = 2 * head_dim * coff
kv_score_buffer = state_pool.kv_score_buffer.kv_score
kv_score_buffer = kv_score_buffer.view(-1, compress_ratio, last_dim)
kv_score_buffer = state_pool.kv_score_buffer.kv_score.view(
-1, compress_ratio, 2 * head_dim * coff
)

kv_compressed = compress_forward(
kv_score_buffer=kv_score_buffer,
Expand All @@ -320,49 +330,59 @@ def _forward_unified_hip(
head_dim=head_dim,
is_online=False,
)

if kv_compressed.shape[0] == 0:
return
return None

# For decode: zero out non-boundary tokens to prevent corrupting kvcache loc 0.
plan_raw = plan[1].view(torch.int32)
if plan.is_decode:
plan_raw = plan[1].view(torch.int32)
# Zero out non-boundary tokens to prevent corrupting kvcache loc 0.
seq_lens_plan = plan_raw[:, 0].to(torch.int32)
is_boundary = (seq_lens_plan % compress_ratio == 0).unsqueeze(-1)
kv_compressed = torch.where(
is_boundary, kv_compressed, torch.zeros_like(kv_compressed)
)
out_loc_to_store = out_loc
else:
ragged_ids = plan_raw[:, 1].to(torch.int32) & 0xFFFF
out_loc_to_store = out_loc[ragged_ids.long()]

# Step 2: norm + rope (Triton fallback for precision parity with V1)
positions = _extract_positions_from_plan(plan, compress_ratio)
positions_safe = positions.clamp(min=0)

positions = _extract_positions_from_plan(plan, compress_ratio).clamp(min=0)
fused_norm_rope_inplace_triton(
kv_compressed,
compressor.norm.weight,
compressor.norm.variance_epsilon,
compressor.freqs_cis,
positions=positions_safe,
positions=positions,
)
return kv_compressed, out_loc_to_store

# Step 3: optional Hadamard rotation for indexer
if compressor.rotate:
kv_compressed = rotate_activation(kv_compressed)

# Step 4: store to kvcache
# For decode: store ALL tokens. Non-boundary tokens have out_loc=0 (safe).
# For prefill: plan_c already only contains valid entries.
if plan.is_decode:
kv_to_store = kv_compressed
out_loc_to_store = out_loc
else:
kv_to_store = kv_compressed
plan_raw = plan[1].view(torch.int32)
ragged_ids = plan_raw[:, 1].to(torch.int32) & 0xFFFF
out_loc_to_store = out_loc[ragged_ids.long()]
def _forward_unified_hip(
self,
token_to_kv_pool: DeepSeekV4TokenToKVPool,
kv_score_input: torch.Tensor,
state_pool,
compressor: Compressor,
layer_id: int,
) -> None:
"""HIP-specific forward path: the shared unfused pipeline + HIP stores."""
from sglang.srt.layers.attention.dsv4.quant_k_cache import (
quant_to_nope_fp8_rope_bf16_pack_triton,
)
from sglang.srt.layers.attention.nsa.nsa_indexer import rotate_activation
from sglang.srt.layers.attention.nsa.triton_kernel import act_quant

if kv_to_store.shape[0] == 0:
result = self._compress_norm_rope_unfused(
kv_score_input=kv_score_input,
state_pool=state_pool,
compressor=compressor,
)
if result is None:
return
kv_to_store, out_loc_to_store = result

is_indexer = compressor.is_in_indexer
if compressor.rotate:
kv_to_store = rotate_activation(kv_to_store)

if envs.SGLANG_OPT_USE_FUSED_STORE_CACHE.get():
# fused kernel: BF16 in -> FP8 quant + paged scatter in one launch
Expand Down Expand Up @@ -391,6 +411,38 @@ def _forward_unified_hip(
pack = quant_to_nope_fp8_rope_bf16_pack_triton(kv_to_store.bfloat16())
token_to_kv_pool.set_extra_key_buffer(layer_id, out_loc_to_store, pack)

def _forward_compress_uniform_fp8(
self,
*,
token_to_kv_pool: DeepSeekV4TokenToKVPool,
kv_score_input: torch.Tensor,
state_pool,
compressor: Compressor,
layer_id: int,
) -> None:
"""Uniform-FP8 pool: the shared unfused pipeline + e4m3 cast store."""
assert not compressor.is_in_indexer
assert compressor.head_dim == 512, f"{compressor.head_dim=}"
assert not _use_online_compress(compressor.ratio), (
"SGLANG_OPT_USE_ONLINE_COMPRESS is not supported with the "
"uniform-FP8 KV layout yet."
)

result = self._compress_norm_rope_unfused(
kv_score_input=kv_score_input,
state_pool=state_pool,
compressor=compressor,
)
if result is None:
return
kv_compressed, out_loc_to_store = result

token_to_kv_pool.set_extra_key_buffer_fused(
layer_id=layer_id,
loc=out_loc_to_store,
cache_k=kv_compressed,
)

# NOTE: alias for backward compatibility
forward_indexer_compressor = forward_unified
forward_core_compressor = forward_unified
Expand Down
100 changes: 99 additions & 1 deletion python/sglang/srt/mem_cache/deepseek_v4_memory_pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,67 @@ def get_kv_buffer(self, layer_id: int) -> Tuple[torch.Tensor, torch.Tensor]:
raise NotImplementedError("Use get_key_buffer instead.")


class DeepSeekV4UniformFP8KVPool(DeepSeekV4SingleKVPool):
"""Uniform 512-dim FP8 (e4m3) variant of the DSv4 single-KV pool.

Layout required by the trtllm-gen sparse MLA kernel: every token is 512
contiguous e4m3 values (448 nope + 64 rope, both FP8), with no in-cache
scales and no per-page padding -- the kernel addresses the cache at token
granularity as ``flat_index * 512`` bytes. The per-tensor dequant scale
is delivered externally via the kernel's bmm scales.
"""

def get_bytes_per_token(self) -> int:
return self.qk_nope_head_dim + self.qk_rope_head_dim

def create_buffer(self, *, num_pages: int):
bytes_per_token = self.get_bytes_per_token()
assert bytes_per_token == 512, (
"DSV4 uniform-FP8 KV layout: qk_nope_head_dim (448) + "
"qk_rope_head_dim (64), all e4m3 = 512 bytes/token"
)
self.kv_cache_total_dim = bytes_per_token
self.bytes_per_page_padded = self.page_size * bytes_per_token

return torch.zeros(
num_pages,
self.page_size * bytes_per_token,
dtype=torch.float8_e4m3fn,
device=self.device,
)

def get_key_buffer(self, layer_id: int):
return self.kv_buffer[layer_id - self.start_layer]

def set_key_buffer(
self,
layer_id: int,
loc: torch.Tensor,
cache_nope_fp8_rope_bf16_pack: NopeFp8RopeBf16Pack,
):
raise NotImplementedError(
"The packed NopeFp8RopeBf16Pack store does not apply to the "
"uniform-FP8 pool; use set_key_buffer_fused."
)

def set_key_buffer_fused(
self,
layer_id: int,
loc: torch.Tensor,
cache_k: torch.Tensor,
) -> None:
"""Store already-normed/roped rows as plain e4m3 with a fixed scale of
1.0 (the backend's bmm scales assume this - change both together).

Uses uint8 views to work around index_put not supporting fp8 dtypes.
"""

assert cache_k.dim() == 2 and cache_k.shape[1] == self.kv_cache_total_dim
self.kv_buffer[layer_id].view(torch.uint8).view(-1, self.kv_cache_total_dim)[
loc.long()
] = cache_k.to(torch.float8_e4m3fn).view(torch.uint8)


class HiSparseC4DevicePool(DeepSeekV4SingleKVPool):

def __init__(
Expand Down Expand Up @@ -578,6 +639,10 @@ def __init__(
)

self._unified_kv = is_unified_kv_triton()
# Uniform 512-dim e4m3 layout for the trtllm attention backend
self.uniform_fp8 = (
not self._unified_kv
) and get_exec().kernel.dsv4_attn_backend == "trtllm"

if self._unified_kv:
self.swa_kv_pool = None
Expand Down Expand Up @@ -606,6 +671,13 @@ def __init__(
self.unified_swa_pages = self.unified_kv_pool.swa_pages
else:
self.unified_kv_pool = None
kv_pool_cls: type = DeepSeekV4SingleKVPool
if self.uniform_fp8:
assert dtype == torch.float8_e4m3fn, (
"--dsv4-attn-backend trtllm requires "
f"kv_cache_dtype=fp8_e4m3, got {dtype}"
)
kv_pool_cls = DeepSeekV4UniformFP8KVPool
self.swa_kv_pool = self._make_kv_pool(
size=swa_size,
page_size=swa_page_size,
Expand All @@ -614,10 +686,15 @@ def __init__(
device=device,
enable_memory_saver=enable_memory_saver,
global_page_size=swa_page_size,
cls=kv_pool_cls,
)

c4_kv_pool_type = DeepSeekV4SingleKVPool
c4_kv_pool_type = kv_pool_cls
if enable_hisparse:
assert not self.uniform_fp8, (
"enable_hisparse is not supported with "
"--dsv4-attn-backend trtllm."
)
c4_kv_pool_type = HiSparseC4DevicePool
self.c4_kv_pool = self._make_kv_pool(
size=c4_size,
Expand All @@ -638,6 +715,7 @@ def __init__(
device=device,
enable_memory_saver=enable_memory_saver,
global_page_size=page_size,
cls=kv_pool_cls,
)

indexer_size = self.c4_logical_size
Expand Down Expand Up @@ -1187,6 +1265,26 @@ def set_swa_key_buffer_radix_fused_norm_rope(
freqs_cis: torch.Tensor,
positions: torch.Tensor,
) -> None:
if self.uniform_fp8:
# Uniform-FP8 (trtllm-gen) layout: norm + RoPE with the existing
# Triton kernel (in-place on kv; safe -- kv is not read again),
# then a plain e4m3 cast + scatter in the pool setter (per-tensor
# scale 1.0). Fusing the store is deferred to the perf phase.
from sglang.kernels.ops.attention.deepseek_v4_rope import (
fused_norm_rope_inplace_triton,
)

fused_norm_rope_inplace_triton(
kv,
kv_weight,
eps,
freqs_cis,
positions=positions,
)
self.swa_kv_pool.set_key_buffer_fused(
self._swa_local_layer_id(layer_id), swa_loc, kv
)
return
fused_k_norm_rope_flashmla(
kv=kv,
kv_weight=kv_weight,
Expand Down
14 changes: 14 additions & 0 deletions python/sglang/srt/server_args.py
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,8 @@ def resolve_encoder_transfer_backend(
]
NSA_CHOICES = DSA_CHOICES # deprecated alias

DSV4_ATTN_BACKEND_CHOICES = ["auto", "flashmla", "trtllm"]

DSA_TOPK_BACKEND_CHOICES = ["sgl-kernel", "torch", "flashinfer"]

DSA_PAGED_MQA_LOGITS_BACKEND_CHOICES = ["auto", "deepgemm", "cutedsl", "aiter"]
Expand Down Expand Up @@ -1793,6 +1795,18 @@ class ServerArgs:
),
NS("exec.kernel"),
] = "sgl-kernel"
dsv4_attn_backend: A[
Comment thread
akhilg-nv marked this conversation as resolved.
Resolved
str,
Arg(
help="DeepSeek V4 attention backend. 'auto' (default) resolves to "
"'flashmla'. 'trtllm' (SM100/SM103 Blackwell only) switches the "
"SWA/compressed KV pools to a uniform 512-dim FP8 layout and runs "
"decode and sparse prefill through the flashinfer trtllm-gen "
"sparse MLA kernel. The backend choice is shared by prefill and decode.",
choices=DSV4_ATTN_BACKEND_CHOICES,
),
NS("exec.kernel"),
] = "auto"
disable_flashinfer_autotune: A[
bool, "Disable FlashInfer autotuning.", NS("exec.kernel")
] = False
Expand Down
Loading
Loading