diff --git a/python/sglang/kernels/ops/attention/minimax_sparse/decode/topk_sparse.py b/python/sglang/kernels/ops/attention/minimax_sparse/decode/topk_sparse.py index 6ff0673161..1c18846e55 100644 --- a/python/sglang/kernels/ops/attention/minimax_sparse/decode/topk_sparse.py +++ b/python/sglang/kernels/ops/attention/minimax_sparse/decode/topk_sparse.py @@ -88,6 +88,7 @@ def _gqa_share_sparse_decode_kernel( BATCH_SIZE_BUCKET: tl.constexpr, BLOCK_SIZE_H: tl.constexpr, BLOCK_SIZE_N: tl.constexpr, + PAGED_CONTIG: tl.constexpr, BLOCK_SIZE_D: tl.constexpr, BLOCK_SIZE_T: tl.constexpr, NUM_TOPK_CHUNKS: tl.constexpr, @@ -184,13 +185,22 @@ def _gqa_share_sparse_decode_kernel( other=0, ).to(tl.int64) hisparse_topk_counter = hisparse_topk_counter + 1 + slots = (slots + max_slots) % max_slots # safety against negative + elif PAGED_CONTIG: + # A block lies inside one page, and slots are contiguous within a page, + # so the block's first slot fixes the whole tile. + base_slot = tl.load( + req_to_token_ptr + sid * stride_r2t_b + c, mask=c < seq_len, other=0 + ).to(tl.int64) + base_slot = (base_slot + max_slots) % max_slots + slots = base_slot + off_n.to(tl.int64) else: slots = tl.load( req_to_token_ptr + sid * stride_r2t_b + pos, mask=pos_mask, other=0, ).to(tl.int64) - slots = (slots + max_slots) % max_slots # safety against negative + slots = (slots + max_slots) % max_slots # safety against negative # load K as (head_dim, BLOCK_SIZE_N) via indirect addressing k_off = ( slots[None, :] * stride_k_s @@ -335,6 +345,7 @@ def flash_decode_with_gqa_share_sparse( topk_idx: torch.Tensor, # [num_kv_heads, batch_size, topk] sm_scale: Optional[float] = None, use_tma: bool = True, + page_size: int = 0, q_scale: Optional[float] = None, k_scale: Optional[float] = None, v_scale: Optional[float] = None, @@ -353,6 +364,9 @@ def flash_decode_with_gqa_share_sparse( f"block_size must be a power of 2, but got {block_size}" ) # assert slot_ids.max() < max_slots, f"get slot_ids {slot_ids}, but kv_cache shape is {kv_cache.shape}" + # A selected block cannot straddle a page boundary under this condition, so its + # slots are contiguous. page_size == 0 means unknown: keep the gather. + paged_contig = page_size >= block_size and page_size % block_size == 0 max_kv_len = req_to_token.shape[1] # gqa assert num_q_heads % num_kv_heads == 0 @@ -439,6 +453,7 @@ def flash_decode_with_gqa_share_sparse( lse_partial.stride(1), lse_partial.stride(2), BLOCK_SIZE_N=block_size, + PAGED_CONTIG=paged_contig, NUM_TOPK_CHUNKS=NUM_TOPK_CHUNKS, IS_FP8=is_fp8, ) diff --git a/python/sglang/srt/layers/attention/minimax_sparse_ops/minimax_sparse.py b/python/sglang/srt/layers/attention/minimax_sparse_ops/minimax_sparse.py index d63342b407..018a38e329 100644 --- a/python/sglang/srt/layers/attention/minimax_sparse_ops/minimax_sparse.py +++ b/python/sglang/srt/layers/attention/minimax_sparse_ops/minimax_sparse.py @@ -454,6 +454,7 @@ def minimax_sparse_decode( block_size=block_size_k, topk_idx=topk_idx, sm_scale=sm_scale, + page_size=page_size, q_scale=q_scale, k_scale=k_scale, v_scale=v_scale, @@ -471,6 +472,7 @@ def minimax_sparse_decode( block_size=block_size_k, topk_idx=topk_idx, sm_scale=sm_scale, + page_size=page_size, q_scale=q_scale, k_scale=k_scale, v_scale=v_scale, diff --git a/python/sglang/srt/models/minimax_m3.py b/python/sglang/srt/models/minimax_m3.py index c9109ed330..36494c9782 100644 --- a/python/sglang/srt/models/minimax_m3.py +++ b/python/sglang/srt/models/minimax_m3.py @@ -87,6 +87,7 @@ from sglang.srt.model_loader.weight_utils import ( default_weight_loader, maybe_remap_kv_scale_name, ) +from sglang.srt.models.deepseek_common.utils import tiny_router_gemm_max_tokens from sglang.srt.models.minimax_m2 import MiniMaxM2RMSNormTP from sglang.srt.models.utils import WeightsMapper from sglang.srt.runtime_context import get_exec, get_parallel, get_stream @@ -116,6 +117,12 @@ if _is_gfx95_supported: else: router_gemv = router_gemv_supported = None +# Import-time CUDA kernels would block processor imports on CPU CI. +if _is_cuda: + from sglang.kernels.ops.gemm.tiny_gemm import tiny_gemm_bf16 +else: + tiny_gemm_bf16 = None + _FP8_KV_DTYPES = ( torch.float8_e4m3fn, torch.float8_e5m2, @@ -418,6 +425,11 @@ class MiniMaxM3MoE(nn.Module): quant_config=None, prefix=add_prefix("gate", prefix), ) + self.tiny_router_gemm_max_tokens = tiny_router_gemm_max_tokens( + num_experts=config.num_local_experts, + hidden_size=config.hidden_size, + weight_dtype=self.gate.weight.dtype, + ) self.layer_id = layer_id @@ -520,6 +532,18 @@ class MiniMaxM3MoE(nn.Module): if _is_npu: # NPU lacks aten::mm.dtype; bf16 mm then cast keeps topk semantics. return torch.mm(hidden_states, self.gate.weight.t()).float() + if ( + not get_exec().deterministic.enable_deterministic_inference + and hidden_states.shape[0] <= self.tiny_router_gemm_max_tokens + ): + # N is num_local_experts, so cuBLAS splits K and runs the + # projection as two launches; the tiny GEMM does it in one. + return tiny_gemm_bf16( + hidden_states, + self.gate.weight, + out_dtype=torch.float32, + max_m=self.tiny_router_gemm_max_tokens, + ) return torch.mm( hidden_states, self.gate.weight.t(), out_dtype=torch.float32 ) diff --git a/test/registered/kernels/ops/attention/test_minimax_sparse_decode_paged_tile.py b/test/registered/kernels/ops/attention/test_minimax_sparse_decode_paged_tile.py new file mode 100644 index 0000000000..317e0c2c85 --- /dev/null +++ b/test/registered/kernels/ops/attention/test_minimax_sparse_decode_paged_tile.py @@ -0,0 +1,126 @@ +"""MiniMax-M3 sparse decode: a block inside one page loads from its first slot. + +These cases pin that this matches the slot gather on the allocator's page layout, +that pages smaller than a block keep the gather, and that HiSparse slots win. +""" + +import sys + +import pytest +import torch + +from sglang.kernels.ops.attention.minimax_sparse.decode.topk_sparse import ( + flash_decode_with_gqa_share_sparse, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=45, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=45, stage="base-b-kernel-unit", runner_config="4-gpu-b200") + +BS, NQH, NKH, HD, BLK, TOPK = 4, 64, 1, 128, 128, 16 +SEQ_LEN = 1024 # req_to_token width; each request's seq_len stops short of it +NUM_SLOTS = BS * SEQ_LEN + + +def _inputs(page_size=None): + q = torch.randn(BS, NQH, HD, dtype=torch.bfloat16, device="cuda") + # BLK spare rows: a one-tile read on a layout that breaks the precondition + # may run up to a block past the last slot. + k_cache = torch.randn(NUM_SLOTS + BLK, NKH, HD, dtype=torch.bfloat16, device="cuda") + v_cache = torch.randn_like(k_cache) + req_to_token = torch.empty(BS, SEQ_LEN, dtype=torch.int32, device="cuda") + for b in range(BS): + if page_size is None: + # A bare slot permutation: blocks no longer sit inside one page. + slots = torch.randperm(SEQ_LEN, device="cuda") + b * SEQ_LEN + else: + # PagedTokenToKVPoolAllocator: page * page_size + offset, pages shuffled. + npages = SEQ_LEN // page_size + pages = torch.randperm(npages, device="cuda") + b * npages + slots = pages[:, None] * page_size + torch.arange(page_size, device="cuda") + req_to_token[b] = slots.reshape(-1).to(torch.int32) + # Decode always reads the local block, which is usually partial; + # on the tile path only pos_mask keeps its tail lanes off unwritten slots. + seq_lens = SEQ_LEN - torch.randint(1, BLK, (BS,), dtype=torch.int32, device="cuda") + for b in range(BS): + # Unwritten slots hold garbage; NaN there makes any read of them show. + unwritten = req_to_token[b, int(seq_lens[b]) :].long() + k_cache[unwritten] = float("nan") + v_cache[unwritten] = float("nan") + slot_ids = torch.arange(BS, dtype=torch.int64, device="cuda") + topk_idx = torch.full((NKH, BS, TOPK), -1, dtype=torch.int32, device="cuda") + for b in range(BS): + num_blocks = (int(seq_lens[b]) + BLK - 1) // BLK + chosen = torch.randperm(num_blocks, device="cuda")[:TOPK] + topk_idx[0, b, : chosen.numel()] = chosen.to(torch.int32) + return q, k_cache, v_cache, req_to_token, seq_lens, slot_ids, topk_idx + + +def _decode(inputs, page_size, hisparse_slots=None): + q, k_cache, v_cache, req_to_token, seq_lens, slot_ids, topk_idx = inputs + return flash_decode_with_gqa_share_sparse( + q=q, + sink=None, + k_cache=k_cache, + v_cache=v_cache, + req_to_token=req_to_token, + seq_lens=seq_lens, + slot_ids=slot_ids, + block_size=BLK, + topk_idx=topk_idx, + page_size=page_size, + hisparse_slots=hisparse_slots, + ) + + +@pytest.mark.parametrize("page_size,engages", [(128, True), (256, True), (64, False)]) +def test_paged_tile_matches_slot_gather(page_size, engages): + """A block read as one tile matches the slot gather; small pages fall back.""" + torch.manual_seed(0) + inputs = _inputs(page_size) + gather = _decode(inputs, page_size=0) + assert torch.equal(gather, _decode(inputs, page_size=page_size)) + if not engages: + # These pages split every block, so a one-tile read differs; + # the equality above therefore means the gather ran. + assert not torch.equal(gather, _decode(inputs, page_size=BLK)) + else: + # On a layout that breaks the precondition the tile must diverge, + # else the equality above does not prove the tile ran. + scattered = _inputs() + assert not torch.equal( + _decode(scattered, page_size=0), _decode(scattered, page_size=page_size) + ) + + +def test_hisparse_slots_override_paged_tile(): + """Pre-resolved HiSparse slots win over the paged tile.""" + torch.manual_seed(0) + inputs = _inputs(BLK) + _, _, _, req_to_token, seq_lens, _, topk_idx = inputs + # Resolve every selected block through a permutation of the written slots, + # laid out like the coordinator's output: [1, batch, topk * block] int32. + written = torch.cat([req_to_token[b, : int(seq_lens[b])] for b in range(BS)]) + written = written.long() + remap = torch.full((NUM_SLOTS,), -1, dtype=torch.int32, device="cuda") + shuffled = written[torch.randperm(written.numel(), device="cuda")] + remap[written] = shuffled.to(torch.int32) + hisparse_slots = torch.full( + (1, BS, TOPK * BLK), -1, dtype=torch.int32, device="cuda" + ) + for b in range(BS): + for t, block in enumerate(topk_idx[0, b].tolist()): + if block >= 0: + tokens = req_to_token[b, block * BLK : (block + 1) * BLK].long() + hisparse_slots[0, b, t * BLK : (t + 1) * BLK] = remap[tokens] + expected = _decode(inputs, page_size=0, hisparse_slots=hisparse_slots) + assert torch.equal( + expected, _decode(inputs, page_size=BLK, hisparse_slots=hisparse_slots) + ) + # The remapped slots change the result, + # else a tile that ignored them would pass the assertion above. + assert not torch.equal(expected, _decode(inputs, page_size=BLK)) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v", "-s"]))