Skip to content
11 changes: 7 additions & 4 deletions python/sglang/kernels/ops/attention/fla/fused_norm_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import triton
import triton.language as tl

from sglang.kernels.jit.utils import is_arch_support_pdl
from sglang.kernels.jit.utils import get_jit_cuda_arch, is_arch_support_pdl
from sglang.srt.utils import (
cdiv,
cpu_has_amx_support,
Expand Down Expand Up @@ -223,10 +223,13 @@ def layer_norm_gated_fwd(
# heuristics for number of warps

if D <= 512:
use_pdl = is_arch_support_pdl()
BT = 32
pdl_kwargs = (
{"USE_GDC": True, "launch_pdl": True} if is_arch_support_pdl() else {}
)
if use_pdl and (T, D, x.dtype) == (64, 128, torch.bfloat16):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Why is BT=8 restricted to exactly (64, 128, bfloat16)? Please document the reason, or use a workload-based rule if the gain also applies to nearby shapes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

tested nearby shapes and expanded bt8 to 8–256 rows for sigmoid rmsnorm on sm103, with bf16 and d=128

arch = get_jit_cuda_arch()
if (arch.major, arch.minor) == (10, 3):
BT = 8
pdl_kwargs = {"USE_GDC": True, "launch_pdl": True} if use_pdl else {}
layer_norm_gated_fwd_kernel[(cdiv(T, BT),)](
x=x,
g=g,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import triton
import triton.language as tl

from sglang.kernels.jit.utils import is_arch_support_pdl
from sglang.kernels.jit.utils import get_jit_cuda_arch, is_arch_support_pdl
from sglang.srt.utils import is_gfx95_supported, is_hip, is_sm90_supported

_is_hip = is_hip()
Expand Down Expand Up @@ -182,6 +182,7 @@ def fused_sigmoid_gating_delta_rule_update_kernel(
USE_GDC: tl.constexpr = False,
MATCH_CUTEDSL_DECODE: tl.constexpr = False,
ROUND_STATE_TO_BF16: tl.constexpr = False,
ROUND_STATE_PRODUCT: tl.constexpr = False,
):
"""
Fused kernel that combines sigmoid gating computation with recurrent delta rule update.
Expand Down Expand Up @@ -444,6 +445,16 @@ def fused_sigmoid_gating_delta_rule_update_kernel(
# Update hidden state: h += k[:, None] * v[None, :]
if MATCH_CUTEDSL_DECODE:
b_h = tl.fma(b_k[:, None], b_v[None, :], b_h)
elif ROUND_STATE_PRODUCT:
# Round the FP32 product and addition separately, without FMA contraction.
b_h = tl.inline_asm_elementwise(
"add.rn.f32 $0, $1, $2;",
constraints="=f,f,f",
args=[b_h, b_k[:, None] * b_v[None, :]],
dtype=tl.float32,
is_pure=True,
pack=1,
)
else:
b_h += b_k[:, None] * b_v[None, :]

Expand Down Expand Up @@ -566,6 +577,19 @@ def fused_sigmoid_gating_delta_rule_update(
BV, num_warps = _select_recurrent_launch_config(
N, H, HV, K, V, is_kda, target_verify=intermediate_states_buffer is not None
)
use_pdl = is_arch_support_pdl()
round_state_product = False
if (
is_kda
and disable_state_update
and not match_cutedsl_decode
and (N, H, HV, K, V, cache_steps) == (1, 8, 8, 128, 128, 8)
and use_pdl
):
arch = get_jit_cuda_arch()
if (arch.major, arch.minor) == (10, 3):
BV = 4

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Please move this SM103 rule into _select_recurrent_launch_config instead of overriding its result here. Keep the rounding requirement tied to the selected configuration and explain why this exact shape needs it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

moved into _select_recurrent_launch_config(). the narrow kda tile keeps separate fp32 multiply/add rounding to preserve parity

round_state_product = True
BK = triton.next_power_of_2(K)
NK, NV = triton.cdiv(K, BK), triton.cdiv(V, BV)
assert NK == 1, "NK > 1 is not supported yet"
Expand Down Expand Up @@ -626,7 +650,7 @@ def fused_sigmoid_gating_delta_rule_update(
# PDL (sm90+): chain this kernel behind its producer conv1d_update, which
# already launches dependents. Bit-exact (scheduling only) — benefits both
# KDA and GDN recurrent paths.
pdl_kwargs = {"USE_GDC": True, "launch_pdl": True} if is_arch_support_pdl() else {}
pdl_kwargs = {"USE_GDC": True, "launch_pdl": True} if use_pdl else {}

# CuTeDSL specializes on the persisted state dtype. Its BF16 decode path
# writes BF16 after every token and reloads FP32 for the next recurrence;
Expand Down Expand Up @@ -698,6 +722,7 @@ def fused_sigmoid_gating_delta_rule_update(
SPLIT_N_HV_GRID=split_n_hv_grid,
MATCH_CUTEDSL_DECODE=match_cutedsl_decode,
ROUND_STATE_TO_BF16=round_state_to_bf16,
ROUND_STATE_PRODUCT=round_state_product,
num_warps=num_warps,
num_stages=num_stages,
**pdl_kwargs,
Expand Down
1 change: 1 addition & 0 deletions python/sglang/srt/environ.py
Original file line number Diff line number Diff line change
Expand Up @@ -1100,6 +1100,7 @@ class Envs:
SGLANG_TRTLLM_MOE_PDL_MAX_TOKENS = EnvInt(8192)
# Use FlashInfer's fused atomic CUTLASS/CuTe DSL MoE finalize.
SGLANG_FLASHINFER_MOE_FUSED_FINALIZE = EnvBool(False)
SGLANG_FLASHINFER_FP8_MOE_BLOCK_LAYOUT = EnvBool(False)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Can we avoid adding another environment variable and enable this layout conversion automatically on SM100 when using FlashInfer FP8 MoE with block_size=[128, 128]?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

removed the flag. the separate moe branch enables this automatically for supported sm100-family fp8 configurations

# Master switch for the experimental TRT-LLM LoRA fast path; when OFF (default) every
# fine-grained opt switch reads False, keeping non-experimental paths byte-identical.
SGLANG_EXPERIMENTAL_LORA_OPTI = EnvBool(False)
Expand Down
76 changes: 37 additions & 39 deletions python/sglang/srt/layers/attention/dsa/dsa_backend_kpool.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,16 +102,17 @@ def _init_kpool_metadata(
full_seqlens_expanded=kpool_inputs.full_seqlens_expanded,
)

metadata = init_pooled_paged_mqa_metadata(
metadata,
metadata.cache_seqlens_int32,
forward_mode,
pool_size=self.dsa_index_kpool,
real_page_size=self.real_page_size,
slots_per_page=slots_per_page,
build_schedule_metadata=build_schedule_metadata,
)

if forward_mode.is_decode_or_idle():
metadata = init_pooled_paged_mqa_metadata(
metadata,
metadata.cache_seqlens_int32,
forward_mode,
pool_size=self.dsa_index_kpool,
real_page_size=self.real_page_size,
slots_per_page=slots_per_page,
build_schedule_metadata=build_schedule_metadata,
)
return init_kpool_write_plan(
metadata,
forward_batch,
Expand Down Expand Up @@ -170,16 +171,15 @@ def _init_kpool_metadata_capture(

slots_per_page = self._kpool_slots_per_page()
build_schedule_metadata = self._build_kpool_paged_mqa_schedule_metadata()
if forward_mode.is_decode_or_idle():
metadata = init_pooled_paged_mqa_metadata(
metadata,
metadata.cache_seqlens_int32,
forward_mode,
pool_size=self.dsa_index_kpool,
real_page_size=self.real_page_size,
slots_per_page=slots_per_page,
build_schedule_metadata=build_schedule_metadata,
)
metadata = init_pooled_paged_mqa_metadata(
metadata,
metadata.cache_seqlens_int32,
forward_mode,
pool_size=self.dsa_index_kpool,
real_page_size=self.real_page_size,
slots_per_page=slots_per_page,
build_schedule_metadata=build_schedule_metadata,
)

if (
forward_mode.is_decode_or_idle()
Expand Down Expand Up @@ -218,16 +218,15 @@ def _update_kpool_metadata_replay(

slots_per_page = self._kpool_slots_per_page()
build_schedule_metadata = self._build_kpool_paged_mqa_schedule_metadata()
if forward_mode.is_decode_or_idle():
update_pooled_paged_mqa_metadata(
metadata,
metadata.cache_seqlens_int32,
forward_mode,
pool_size=self.dsa_index_kpool,
real_page_size=self.real_page_size,
slots_per_page=slots_per_page,
build_schedule_metadata=build_schedule_metadata,
)
update_pooled_paged_mqa_metadata(
metadata,
metadata.cache_seqlens_int32,
forward_mode,
pool_size=self.dsa_index_kpool,
real_page_size=self.real_page_size,
slots_per_page=slots_per_page,
build_schedule_metadata=build_schedule_metadata,
)

if not (
forward_mode.is_decode_or_idle()
Expand Down Expand Up @@ -270,16 +269,15 @@ def _update_kpool_metadata_from_precomputed(

slots_per_page = self._kpool_slots_per_page()
build_schedule_metadata = self._build_kpool_paged_mqa_schedule_metadata()
if forward_mode.is_decode_or_idle():
update_pooled_paged_mqa_metadata(
metadata,
precomputed.cache_seqlens,
forward_mode,
pool_size=self.dsa_index_kpool,
real_page_size=self.real_page_size,
slots_per_page=slots_per_page,
build_schedule_metadata=build_schedule_metadata,
)
update_pooled_paged_mqa_metadata(
metadata,
precomputed.cache_seqlens,
forward_mode,
pool_size=self.dsa_index_kpool,
real_page_size=self.real_page_size,
slots_per_page=slots_per_page,
build_schedule_metadata=build_schedule_metadata,
)

if not (forward_mode.is_decode_or_idle() or forward_mode.is_target_verify()):
return
Expand Down
11 changes: 8 additions & 3 deletions python/sglang/srt/layers/attention/dsa/dsa_indexer_kpool.py
Original file line number Diff line number Diff line change
Expand Up @@ -805,9 +805,14 @@ def _get_kpool_decode_metadata(
if plan is not None and plan.pool_seqlens_per_q is not None:
pool_seqlens = plan.pool_seqlens_per_q[: seqlens_32.shape[0]]
pool_context_lens = pool_seqlens.contiguous().view(-1, 1)
pool_block_tables = build_pooled_page_table_64(
block_tables, self.index_kpool
).contiguous()
pool_block_tables = attn_metadata.pooled_real_page_table
if (
pool_block_tables is None
or attn_metadata.pooled_index_kpool != self.index_kpool
):
pool_block_tables = build_pooled_page_table_64(
block_tables, self.index_kpool
).contiguous()
pool_schedule_metadata = plan.pool_schedule_metadata
if pool_schedule_metadata is None and build_schedule_metadata:
pool_schedule_metadata = deep_gemm.get_paged_mqa_logits_metadata(
Expand Down
21 changes: 16 additions & 5 deletions python/sglang/srt/layers/attention/dsa/kpool_plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -584,16 +584,23 @@ def init_pooled_paged_mqa_metadata(
if (
not _is_kpool_layout_enabled(pool_size, real_page_size)
or not is_cuda()
or not forward_mode.is_decode_or_idle()
or not (forward_mode.is_decode_or_idle() or forward_mode.is_target_verify())
Comment thread
BBuf marked this conversation as resolved.
Resolved
):
return metadata

pool_seqlens = torch.div(seqlens_32, pool_size, rounding_mode="floor").to(
torch.int32
)
pooled_page_table = build_pooled_page_table_64(
metadata.real_page_table, pool_size
).contiguous()
if forward_mode.is_target_verify():
return dataclasses.replace(
metadata,
pooled_index_kpool=pool_size,
pooled_real_page_table=pooled_page_table,
)

pool_seqlens = torch.div(seqlens_32, pool_size, rounding_mode="floor").to(
torch.int32
)
schedule = (
_compute_pool_schedule_metadata(
pool_seqlens,
Expand Down Expand Up @@ -624,10 +631,14 @@ def update_pooled_paged_mqa_metadata(
if (
not _is_kpool_layout_enabled(pool_size, real_page_size)
or not is_cuda()
or not forward_mode.is_decode_or_idle()
or not (forward_mode.is_decode_or_idle() or forward_mode.is_target_verify())
):
return

if forward_mode.is_target_verify():
metadata.pooled_real_page_table.copy_(metadata.real_page_table[:, ::pool_size])
return

if (
metadata.pooled_index_kpool != pool_size
or metadata.pooled_cache_seqlens_int32 is None
Expand Down
42 changes: 40 additions & 2 deletions python/sglang/srt/layers/moe/moe_runner/flashinfer_trtllm.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
)

_TRTLLM_MOE_PDL_MAX_TOKENS = envs.SGLANG_TRTLLM_MOE_PDL_MAX_TOKENS.get()
_FP8_MOE_BLOCK_K = 128


def trtllm_moe_enable_pdl(num_tokens: int) -> bool:
Expand Down Expand Up @@ -228,6 +229,38 @@ def _align_fp8_moe_weights(
return padded_w13, padded_w2, padded_intermediate


def prepare_fp8_moe_block_layout(layer: Module, *, cache_views: bool = True) -> None:
from flashinfer import shuffle_matrix_a
from flashinfer.fused_moe import WeightLayout, convert_to_block_layout

epilogue_tile_m = 64
# Keep logical shapes and Parameter objects for the checkpoint weight loader.
for weight in (layer.w13_weight, layer.w2_weight):
for expert in weight:
shuffled = shuffle_matrix_a(expert.view(torch.uint8), epilogue_tile_m)
blocked = convert_to_block_layout(shuffled, _FP8_MOE_BLOCK_K)
expert.view(torch.uint8).copy_(blocked.reshape_as(expert))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

On a partial weight update, end_weight_update() postprocesses every layer, so weights that weren't reloaded get shuffled a second time. Please undo the packing in restore_weights_before_loading(), or only repack weights that were actually reloaded. The zero-filled view test won't catch this; check that untouched weights stay unchanged.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

moved moe to a separate branch. it now restores the original layout before reload; nonzero-weight tests confirm untouched weights stay unchanged.

layer._flashinfer_weight_layout = int(WeightLayout.BlockMajorK)
layer._flashinfer_moe_weights = None
if cache_views:
layer._flashinfer_moe_weights = get_fp8_moe_weights(layer)


def get_fp8_moe_weights(layer: Module) -> tuple[torch.Tensor, torch.Tensor]:
weights = (layer.w13_weight, layer.w2_weight)
cached = getattr(layer, "_flashinfer_moe_weights", weights)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Do we need to cache these views? view() doesn't copy data, and CUDA graph replay won't repeat this Python code. Creating the view from the current parameters would remove the cache_views option and offload checks, and avoid having to refresh aliases after reload.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

removed the cache and offload checks. views now come directly from the current parameters

if cached is not None:
return cached
# Offload substitutes live parameters through functional_call.
block_k = _FP8_MOE_BLOCK_K
return tuple(
weight.view(
weight.shape[0], weight.shape[2] // block_k, weight.shape[1], block_k
)
for weight in weights
)


def align_fp8_moe_weights_for_flashinfer_trtllm(
layer: Module, swap_w13_halves: bool = False
) -> None:
Expand Down Expand Up @@ -705,6 +738,7 @@ class FlashInferTrtllmFp8MoeQuantInfo(MoeQuantInfo):
# Block-quant path
block_quant: bool
use_mxfp8: bool = False
weight_layout: int = 0
weight_block_k: int | None = None
w13_weight_scale_inv: torch.Tensor | None = None
w2_weight_scale_inv: torch.Tensor | None = None
Expand All @@ -729,7 +763,7 @@ def fused_experts_none_to_flashinfer_trtllm_fp8(
runner_config: MoeRunnerConfig,
use_routed_topk: bool = False,
) -> StandardCombineInput:
from flashinfer.fused_moe import Fp8QuantizationType
from flashinfer.fused_moe import Fp8QuantizationType, WeightLayout

from sglang.srt.layers.moe.token_dispatcher.flashinfer import (
FlashinferDispatchOutput,
Expand Down Expand Up @@ -767,7 +801,9 @@ def fused_experts_none_to_flashinfer_trtllm_fp8(
if quant_info.use_mxfp8
else Fp8QuantizationType.DeepSeekFp8
)
use_shuffled_weight = quant_info.use_mxfp8
use_shuffled_weight = (
quant_info.use_mxfp8 or quant_info.weight_layout == WeightLayout.BlockMajorK
)
defer_finalize = _deferred_finalize_enabled.get()
if defer_finalize and (
not quant_info.block_quant
Expand Down Expand Up @@ -869,6 +905,7 @@ def fused_experts_none_to_flashinfer_trtllm_fp8(
else routing_method_type
),
use_shuffled_weight=use_shuffled_weight,
weight_layout=quant_info.weight_layout,
output=symm_output,
tune_max_num_tokens=next_power_of_2(a_q.shape[0]),
fp8_quantization_type=int(fp8_quantization_type),
Expand Down Expand Up @@ -903,6 +940,7 @@ def fused_experts_none_to_flashinfer_trtllm_fp8(
),
routing_method_type=routing_method_type,
use_shuffled_weight=use_shuffled_weight,
weight_layout=quant_info.weight_layout,
tune_max_num_tokens=next_power_of_2(a_q.shape[0]),
)
if defer_finalize:
Expand Down
Loading
Loading