From 26a718fd584fe04a41e298f8fe8c5ed4b60f6b36 Mon Sep 17 00:00:00 2001 From: Tairan Xu <34982739+Andrewxu313@users.noreply.github.com> Date: Thu, 3 Dec 2026 21:24:22 +0000 Subject: [PATCH 1/8] feat(kernel): add clamped SwiGLU, sparse-EP skip, and MLA return_lse Add optional swiglu_limit clamping and out-of-range expert slot skipping (-1) to fused_moe_bf16 and ResidentEPMoELayer so high-EP shards skip non-local tiles instead of piling onto expert 0, guard zero-weight loads in moe_weighted_sum, and expose return_lse on mla_paged_decode and sparse_mla_{decode,prefill} for per-head learnable softmax sinks. --- batchgen/attention/mla/paged_decode.py | 13 +- batchgen/attention/mla/sparse_dispatch.py | 34 +++- batchgen/moe/fused_moe_bf16_resident.py | 37 ++-- batchgen_kernels/triton/fused_moe_bf16.py | 89 ++++++-- batchgen_kernels/triton/moe_weighted_sum.py | 6 +- tests/test_hy4_kernel_primitives.py | 213 ++++++++++++++++++++ 6 files changed, 347 insertions(+), 45 deletions(-) create mode 100644 tests/test_hy4_kernel_primitives.py diff --git a/batchgen/attention/mla/paged_decode.py b/batchgen/attention/mla/paged_decode.py index a03afebee..259b616d3 100644 --- a/batchgen/attention/mla/paged_decode.py +++ b/batchgen/attention/mla/paged_decode.py @@ -149,7 +149,9 @@ def mla_paged_decode( head_dim_v: int, softmax_scale: float, schedule: Optional[DecodeSchedule] = None, -) -> torch.Tensor: + *, + return_lse: bool = False, +): batch, q_len, num_heads, head_dim = query.shape assert q_len == 1, "dense paged MLA decode takes one query token per sequence" if schedule is None: @@ -158,13 +160,18 @@ def mla_paged_decode( if _backend() == "flashmla": from flash_mla import flash_mla_with_kvcache - out, _ = flash_mla_with_kvcache( + out, lse = flash_mla_with_kvcache( query, blocked_k, block_table, cache_seqlens, head_dim_v, schedule.tile_scheduler_metadata, schedule.num_splits, softmax_scale, True, **flashmla_dense_kwargs(), ) - return out + return (out, lse) if return_lse else out + if return_lse: + raise NotImplementedError( + "mla_paged_decode(return_lse=True) is not implemented for backend " + f"{_backend()!r}" + ) return _trtllm_gen_dense( query, blocked_k, block_table, cache_seqlens, head_dim_v, softmax_scale ) diff --git a/batchgen/attention/mla/sparse_dispatch.py b/batchgen/attention/mla/sparse_dispatch.py index 904ed3867..ffe43fb0b 100644 --- a/batchgen/attention/mla/sparse_dispatch.py +++ b/batchgen/attention/mla/sparse_dispatch.py @@ -117,7 +117,9 @@ def _fa3_num_splits() -> int: return GLM5_SPARSE_FA3_NUM_SPLITS -def _fa3_sparse(q_pe, q_latent, flat_kv, token_rows, lengths, softmax_scale): +def _fa3_sparse( + q_pe, q_latent, flat_kv, token_rows, lengths, softmax_scale, *, return_lse: bool = False +): lora = q_latent.shape[-1] return _fa3_with_kvcache()( q=q_pe, @@ -129,7 +131,7 @@ def _fa3_sparse(q_pe, q_latent, flat_kv, token_rows, lengths, softmax_scale): softmax_scale=float(softmax_scale), causal=True, num_splits=_fa3_num_splits(), - return_softmax_lse=False, + return_softmax_lse=return_lse, ) @@ -220,12 +222,22 @@ def sparse_mla_decode( token_rows: torch.Tensor, lengths: torch.Tensor, softmax_scale: float, -) -> torch.Tensor: + *, + return_lse: bool = False, +): """Decode: one query token per row over the paged latent cache.""" _announce("decode", q_latent, token_rows) if _backend() == "fa3": flat_kv = blocked_k.view(-1, 1, 1, blocked_k.shape[-1]) - return _fa3_sparse(q_pe, q_latent, flat_kv, token_rows, lengths, softmax_scale) + return _fa3_sparse( + q_pe, q_latent, flat_kv, token_rows, lengths, softmax_scale, + return_lse=return_lse, + ) + if return_lse: + raise NotImplementedError( + "sparse_mla_decode(return_lse=True) is not implemented for backend " + f"{_backend()!r}" + ) return _trtllm_sparse_decode(q_pe, q_latent, blocked_k, token_rows, lengths, softmax_scale) @@ -236,10 +248,20 @@ def sparse_mla_prefill( token_rows: torch.Tensor, lengths: torch.Tensor, softmax_scale: float, -) -> torch.Tensor: + *, + return_lse: bool = False, +): """Prefill: every query token its own row over flat latent rows.""" _announce("prefill", q_latent, token_rows) if _backend() == "fa3": flat_kv = kv_rows.view(-1, 1, 1, kv_rows.shape[-1]) - return _fa3_sparse(q_pe, q_latent, flat_kv, token_rows, lengths, softmax_scale) + return _fa3_sparse( + q_pe, q_latent, flat_kv, token_rows, lengths, softmax_scale, + return_lse=return_lse, + ) + if return_lse: + raise NotImplementedError( + "sparse_mla_prefill(return_lse=True) is not implemented for backend " + f"{_backend()!r}" + ) return _flashmla_sparse_prefill(q_pe, q_latent, kv_rows, token_rows, lengths, softmax_scale) diff --git a/batchgen/moe/fused_moe_bf16_resident.py b/batchgen/moe/fused_moe_bf16_resident.py index d21e394c0..5f44a9eeb 100644 --- a/batchgen/moe/fused_moe_bf16_resident.py +++ b/batchgen/moe/fused_moe_bf16_resident.py @@ -72,23 +72,26 @@ def layer_shard_nbytes(num_local, hidden_size, intermediate_size, ) -def fill_layer_shard(w13, w2, get_tensor, layer_idx, expert_start): +def fill_layer_shard(w13, w2, get_tensor, layer_idx, expert_start, + weight_keys=("w1.weight", "w3.weight", "w2.weight")): """Copy one layer's local experts host->GPU into the stacked rows in place. The build and every refill of a kept shard write the same host tensors (``core_engine.get_tensor``, address-stable) to the same rows. """ + gate_key, up_key, down_key = weight_keys I = w2.shape[2] for i in range(w13.shape[0]): tensors = get_tensor(f"routed_expert_{layer_idx}_{expert_start + i}") - w13[i, :I].copy_(tensors["w1.weight"]) - w13[i, I:].copy_(tensors["w3.weight"]) - w2[i].copy_(tensors["w2.weight"]) + w13[i, :I].copy_(tensors[gate_key]) + w13[i, I:].copy_(tensors[up_key]) + w2[i].copy_(tensors[down_key]) def build_layer_shard(get_tensor, layer_idx, expert_start, num_local, hidden_size, intermediate_size, device, - dtype=torch.bfloat16, arena=None): + dtype=torch.bfloat16, arena=None, + weight_keys=("w1.weight", "w3.weight", "w2.weight")): """Materialize one MoE layer's local expert shard as stacked GPU tensors. Copies each local expert's BF16 weights host->GPU exactly once, straight @@ -125,7 +128,8 @@ def build_layer_shard(get_tensor, layer_idx, expert_start, num_local, else: w13 = torch.empty(w13_shape, dtype=dtype, device=device) w2 = torch.empty(w2_shape, dtype=dtype, device=device) - fill_layer_shard(w13, w2, get_tensor, layer_idx, expert_start) + fill_layer_shard(w13, w2, get_tensor, layer_idx, expert_start, + weight_keys=weight_keys) return w13, w2 @@ -144,7 +148,7 @@ class ResidentEPMoELayer: num_tokens_per_rank = None def __init__(self, layer_idx, w13, w2, comm, world_size, rank, - expert_start, arena=None): + expert_start, arena=None, swiglu_limit=None): self.layer_idx = layer_idx self.w13 = w13 self.w2 = w2 @@ -155,6 +159,7 @@ def __init__(self, layer_idx, w13, w2, comm, world_size, rank, self.num_local_experts = w13.shape[0] # The fixed-address arena the stacks are carved from, or None. self.arena = arena + self.swiglu_limit = swiglu_limit @classmethod def set_num_tokens_per_rank(cls, num_tokens_per_rank): @@ -213,18 +218,22 @@ def forward(self, x_local, gate): gate_out = gate(all_tokens.view(num_global, 1, H)) topk_idx, topk_weight = gate_out[0], gate_out[1] - # Mask routing to the local shard: non-local slots keep weight 0 and - # are pointed at local expert 0 — they contribute exactly 0 through - # the weighted top-k reduction, and the extra rows cost no additional - # weight traffic in the BW-bound decode regime (same experts read). + # Mask routing to the local shard: non-local slots carry sentinel -1 + # and weight 0 so fused_moe_bf16 skips them completely (zero wasted + # GEMM tiles on expert 0 under high EP such as EP-32). local_ids = topk_idx - self.expert_start local_mask = (local_ids >= 0) & (local_ids < self.num_local_experts) local_ids = torch.where(local_mask, local_ids, - torch.zeros_like(local_ids)) + torch.full_like(local_ids, -1)) masked_weight = topk_weight * local_mask.to(topk_weight.dtype) - partial = fused_moe_bf16(all_tokens, self.w13, self.w2, - masked_weight, local_ids) + if self.swiglu_limit is not None: + partial = fused_moe_bf16(all_tokens, self.w13, self.w2, + masked_weight, local_ids, + swiglu_limit=self.swiglu_limit) + else: + partial = fused_moe_bf16(all_tokens, self.w13, self.w2, + masked_weight, local_ids) # Combine expert shards: SUM over ranks in the global layout (BF16 # over NCCL, K2.5-class numerics; per-rank top-k accumulation above diff --git a/batchgen_kernels/triton/fused_moe_bf16.py b/batchgen_kernels/triton/fused_moe_bf16.py index ec4c9e599..cb9fd7aa5 100644 --- a/batchgen_kernels/triton/fused_moe_bf16.py +++ b/batchgen_kernels/triton/fused_moe_bf16.py @@ -121,29 +121,48 @@ def _fused_moe_gemm( def _silu_and_mul_kernel( x_ptr, y_ptr, + sorted_token_ids_ptr, + num_tokens_post_padded_ptr, N, + num_valid_tokens, stride_xm, stride_ym, BLOCK_N: tl.constexpr, + CLAMP_SWIGLU: tl.constexpr, + SWIGLU_LIMIT: tl.constexpr, ): - """y = silu(x[:, :N]) * x[:, N:] (fp32 internally), row-wise over (M, 2N).""" + """y[slot] = silu(x[slot, :N]) * x[slot, N:] (fp32 internally) over active sorted slots.""" pid_m = tl.program_id(0) + num_post = tl.load(num_tokens_post_padded_ptr) + if pid_m >= num_post: + return + tok_slot = tl.load(sorted_token_ids_ptr + pid_m).to(tl.int64) + if tok_slot >= num_valid_tokens: + return pid_n = tl.program_id(1) offs = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) mask = offs < N - g = tl.load(x_ptr + pid_m * stride_xm + offs, mask=mask, other=0.0).to(tl.float32) - u = tl.load(x_ptr + pid_m * stride_xm + N + offs, mask=mask, other=0.0).to(tl.float32) + g = tl.load(x_ptr + tok_slot * stride_xm + offs, mask=mask, other=0.0).to(tl.float32) + u = tl.load(x_ptr + tok_slot * stride_xm + N + offs, mask=mask, other=0.0).to(tl.float32) + if CLAMP_SWIGLU: + g = tl.minimum(g, SWIGLU_LIMIT) + u = tl.maximum(tl.minimum(u, SWIGLU_LIMIT), -SWIGLU_LIMIT) y = g / (1.0 + tl.exp(-g)) * u - tl.store(y_ptr + pid_m * stride_ym + offs, y.to(y_ptr.dtype.element_ty), mask=mask) + tl.store(y_ptr + tok_slot * stride_ym + offs, y.to(y_ptr.dtype.element_ty), mask=mask) def moe_align_block_size( topk_ids: torch.Tensor, block_size: int, num_experts: int ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: - """Sort token-slots by expert and pad segments to block_size (GPU-only). + """Sort active token-slots by expert and pad segments to block_size (GPU-only). + + Slots whose expert id is outside ``[0, num_experts)`` (e.g. ``-1`` for + non-local experts under resident EP) are skipped so they consume zero + grouped-GEMM blocks. Args: - topk_ids: (M, top_k) expert indices per token. + topk_ids: (M, top_k) expert indices per token (``-1`` or out-of-range + entries are ignored). block_size: GEMM M-tile the segments are padded to. num_experts: total routed experts E. @@ -154,24 +173,38 @@ def moe_align_block_size( num_tokens_post_padded: (1,) int32 total padded slots. """ device = topk_ids.device - top_k = topk_ids.shape[1] flat = topk_ids.flatten().to(torch.int64) numel = flat.numel() - counts = torch.bincount(flat, minlength=num_experts) + valid = (flat >= 0) & (flat < num_experts) + bucket = torch.where(valid, flat, torch.full_like(flat, num_experts)) + counts_all = torch.bincount(bucket, minlength=num_experts + 1) + counts = counts_all[:num_experts] padded = (counts + (block_size - 1)).div(block_size, rounding_mode="floor") * block_size padded_ends = torch.cumsum(padded, 0) padded_offsets = padded_ends - padded - counts_ends = torch.cumsum(counts, 0) - counts_offsets = counts_ends - counts + counts_ends = torch.cumsum(counts_all, 0) + counts_offsets = counts_ends - counts_all - order = torch.argsort(flat, stable=True) - sorted_experts = flat[order] - rank = torch.arange(numel, device=device) - counts_offsets[sorted_experts] + order = torch.argsort(bucket, stable=True) + sorted_buckets = bucket[order] + rank = torch.arange(numel, device=device) - counts_offsets[sorted_buckets] max_padded = numel + (num_experts + 1) * (block_size - 1) - sorted_ids = torch.full((max_padded,), numel, dtype=torch.int32, device=device) - sorted_ids[padded_offsets[sorted_experts] + rank] = order.to(torch.int32) + # Extra trailing sink slot absorbs invalid (bucket == num_experts) entries + # without host sync or dynamic slicing. + sorted_buf = torch.full((max_padded + 1,), numel, dtype=torch.int32, device=device) + is_valid_sorted = sorted_buckets < num_experts + clamped_experts = torch.where( + is_valid_sorted, sorted_buckets, torch.zeros_like(sorted_buckets) + ) + dest = torch.where( + is_valid_sorted, + padded_offsets[clamped_experts] + rank, + torch.full_like(rank, max_padded), + ) + sorted_buf[dest] = order.to(torch.int32) + sorted_ids = sorted_buf[:max_padded] max_blocks = triton.cdiv(max_padded, block_size) block_starts = torch.arange(max_blocks, device=device) * block_size @@ -224,6 +257,8 @@ def fused_moe_bf16( w2: torch.Tensor, topk_weights: torch.Tensor, topk_ids: torch.Tensor, + *, + swiglu_limit: float | None = None, ) -> torch.Tensor: """Fused BF16 MoE forward. @@ -232,8 +267,11 @@ def fused_moe_bf16( w13: (E, 2N, K) packed [gate; up] expert weights (gate first). w2: (E, H, N) down-projection expert weights. topk_weights: (M, top_k) fp32 routing weights (already renormalized - and scaled, as produced by KimiMoEGate). - topk_ids: (M, top_k) expert indices. + and scaled, as produced by KimiMoEGate / HyV4MoEGate). + topk_ids: (M, top_k) expert indices; entries outside ``[0, E)`` (e.g. + ``-1``) are skipped and their ``topk_weights`` must be 0. + swiglu_limit: optional HY4 clamped-SwiGLU bound (gate clamped to + ``<= limit``, up clamped to ``[-limit, limit]`` in fp32). Returns: (M, H) tensor in x.dtype: sum_k topk_weights[m, k] * expert(x[m]). @@ -245,6 +283,8 @@ def fused_moe_bf16( H = w2.shape[1] top_k = topk_ids.shape[1] assert w13.shape[2] == K and w2.shape[2] == N and w2.shape[0] == E + if swiglu_limit is not None and swiglu_limit <= 0: + raise ValueError(f"swiglu_limit must be positive, got {swiglu_limit!r}") config = _pick_config(M * top_k) block_m = config[0] @@ -254,9 +294,20 @@ def fused_moe_bf16( _stage_gemm(x, w13, c1, sorted_ids, expert_ids, num_post, top_k, M * top_k, config) c2 = torch.empty((M * top_k, N), device=x.device, dtype=x.dtype) - grid_act = (M * top_k, triton.cdiv(N, 1024)) + grid_act = (sorted_ids.numel(), triton.cdiv(N, 1024)) _silu_and_mul_kernel[grid_act]( - c1, c2, N, c1.stride(0), c2.stride(0), BLOCK_N=1024, num_warps=4 + c1, + c2, + sorted_ids, + num_post, + N, + M * top_k, + c1.stride(0), + c2.stride(0), + BLOCK_N=1024, + CLAMP_SWIGLU=(swiglu_limit is not None), + SWIGLU_LIMIT=(float(swiglu_limit) if swiglu_limit is not None else 0.0), + num_warps=4, ) c3 = torch.empty((M * top_k, H), device=x.device, dtype=x.dtype) diff --git a/batchgen_kernels/triton/moe_weighted_sum.py b/batchgen_kernels/triton/moe_weighted_sum.py index 38e46af02..132b0a7ad 100644 --- a/batchgen_kernels/triton/moe_weighted_sum.py +++ b/batchgen_kernels/triton/moe_weighted_sum.py @@ -59,7 +59,7 @@ def moe_weighted_sum_kernel( # Create 2D indices: [BLOCK_SIZE_TOKENS, BLOCK_SIZE_HIDDEN] load_indices = token_base_indices[:, None] + hidden_offsets[None, :] - load_mask = token_mask[:, None] & hidden_mask[None, :] + load_mask = token_mask[:, None] & hidden_mask[None, :] & (weights[:, None] != 0.0) # Load values for all tokens and hidden dims in this block values = tl.load( @@ -133,8 +133,8 @@ def moe_weighted_sum_kernel_optimized( token_base_ptrs = (token_offsets[:, None] * topk + expert_idx) * hidden_size result_ptrs = token_base_ptrs + hidden_offsets[None, :] - # Load values with proper masking - mask_2d = token_mask[:, None] & hidden_mask[None, :] + # Load values with proper masking (skip zero-weight non-local slots) + mask_2d = token_mask[:, None] & hidden_mask[None, :] & (weights != 0.0) values = tl.load( global_results_ptr + result_ptrs, mask=mask_2d, diff --git a/tests/test_hy4_kernel_primitives.py b/tests/test_hy4_kernel_primitives.py new file mode 100644 index 000000000..d24d37fb1 --- /dev/null +++ b/tests/test_hy4_kernel_primitives.py @@ -0,0 +1,213 @@ +"""Unit tests for HY4-required kernel primitives (CPU-safe, GPU-verified on H20). + +Covers: + - ``mla_paged_decode(..., return_lse=True)`` on FlashMLA and fail-fast on Blackwell + - ``sparse_mla_decode`` / ``sparse_mla_prefill(..., return_lse=True)`` on FA3 and + fail-fast on Blackwell + - ``ResidentEPMoELayer`` non-local ``-1`` masking, ``swiglu_limit`` forwarding, + and custom ``weight_keys`` in ``build_layer_shard`` +""" + +from __future__ import annotations + +import importlib.util +import sys +import types +from pathlib import Path + +import pytest +import torch + +from batchgen.attention.mla import paged_decode, sparse_dispatch + + +class _DummyComm: + def __init__(self): + self.calls = [] + + def change_state(self, enable=True): + import contextlib + + @contextlib.contextmanager + def _cm(): + yield + + return _cm() + + def all_gather(self, out, inp): + world = out.shape[0] // inp.shape[0] + out.copy_(inp.repeat(world, 1)) + + def all_reduce(self, tensor, op=None): + pass + + +def _load_resident_with_stub(): + mod_path = ( + Path(__file__).resolve().parents[1] + / "batchgen" + / "moe" + / "fused_moe_bf16_resident.py" + ) + pkg = types.ModuleType("batchgen_kernels") + triton_pkg = types.ModuleType("batchgen_kernels.triton") + kernel_mod = types.ModuleType("batchgen_kernels.triton.fused_moe_bf16") + kernel_mod.fused_moe_bf16 = lambda *a, **kw: None + triton_pkg.fused_moe_bf16 = kernel_mod + pkg.triton = triton_pkg + names = ( + "batchgen_kernels", + "batchgen_kernels.triton", + "batchgen_kernels.triton.fused_moe_bf16", + ) + saved = {n: sys.modules.get(n) for n in names} + sys.modules["batchgen_kernels"] = pkg + sys.modules["batchgen_kernels.triton"] = triton_pkg + sys.modules["batchgen_kernels.triton.fused_moe_bf16"] = kernel_mod + try: + spec = importlib.util.spec_from_file_location("_resident_hy4_test", mod_path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + finally: + for n, prev in saved.items(): + if prev is None: + sys.modules.pop(n, None) + else: + sys.modules[n] = prev + + +def test_mla_paged_decode_return_lse_flashmla(monkeypatch): + monkeypatch.setattr(paged_decode, "_BACKEND", "flashmla") + monkeypatch.setattr(paged_decode, "_FLASHMLA_DENSE_KWARGS", {}) + fake_out = torch.randn(2, 1, 8, 512, dtype=torch.bfloat16) + fake_lse = torch.randn(2, 8, 1, dtype=torch.float32) + + fake_fm = types.ModuleType("flash_mla") + fake_fm.flash_mla_with_kvcache = lambda *a, **kw: (fake_out, fake_lse) + fake_fm.get_mla_metadata = lambda *a, **kw: (torch.empty(1), torch.empty(1)) + monkeypatch.setitem(sys.modules, "flash_mla", fake_fm) + + q = torch.zeros(2, 1, 8, 576, dtype=torch.bfloat16) + k = torch.zeros(4, 64, 1, 576, dtype=torch.bfloat16) + bt = torch.zeros(2, 4, dtype=torch.int32) + sl = torch.tensor([10, 20], dtype=torch.int32) + + out_only = paged_decode.mla_paged_decode(q, k, bt, sl, 512, 0.0625) + assert out_only is fake_out + + out, lse = paged_decode.mla_paged_decode( + q, k, bt, sl, 512, 0.0625, return_lse=True + ) + assert out is fake_out + assert lse is fake_lse + + +def test_mla_paged_decode_return_lse_blackwell_fails_loud(monkeypatch): + monkeypatch.setattr(paged_decode, "_BACKEND", "flashinfer-trtllm-gen") + q = torch.zeros(2, 1, 8, 576, dtype=torch.bfloat16) + k = torch.zeros(4, 64, 1, 576, dtype=torch.bfloat16) + bt = torch.zeros(2, 4, dtype=torch.int32) + sl = torch.tensor([10, 20], dtype=torch.int32) + with pytest.raises(NotImplementedError, match="return_lse"): + paged_decode.mla_paged_decode(q, k, bt, sl, 512, 0.0625, return_lse=True) + + +def test_sparse_mla_return_lse_fa3_and_blackwell(monkeypatch): + monkeypatch.setattr(sparse_dispatch, "_BACKEND", "fa3") + monkeypatch.setattr(sparse_dispatch, "_fa3_num_splits", lambda: 1) + seen = [] + + def _fake_fa3(**kwargs): + seen.append(kwargs["return_softmax_lse"]) + out = torch.zeros(2, 1, 8, 512, dtype=torch.bfloat16) + lse = torch.zeros(2, 8, 1, dtype=torch.float32) + return (out, lse) if kwargs["return_softmax_lse"] else out + + monkeypatch.setattr(sparse_dispatch, "_fa3_with_kvcache", lambda: _fake_fa3) + q_pe = torch.zeros(2, 1, 8, 64, dtype=torch.bfloat16) + q_lat = torch.zeros(2, 1, 8, 512, dtype=torch.bfloat16) + bk = torch.zeros(4, 64, 1, 576, dtype=torch.bfloat16) + rows = torch.zeros(2, 16, dtype=torch.int32) + lens = torch.tensor([8, 8], dtype=torch.int32) + + out_d, lse_d = sparse_dispatch.sparse_mla_decode( + q_pe, q_lat, bk, rows, lens, 0.0625, return_lse=True + ) + assert out_d.shape == (2, 1, 8, 512) and lse_d.shape == (2, 8, 1) + out_p, lse_p = sparse_dispatch.sparse_mla_prefill( + q_pe, q_lat, bk.view(-1, 576), rows, lens, 0.0625, return_lse=True + ) + assert out_p.shape == (2, 1, 8, 512) and lse_p.shape == (2, 8, 1) + assert seen == [True, True] + + monkeypatch.setattr(sparse_dispatch, "_BACKEND", "blackwell") + with pytest.raises(NotImplementedError, match="return_lse"): + sparse_dispatch.sparse_mla_decode( + q_pe, q_lat, bk, rows, lens, 0.0625, return_lse=True + ) + with pytest.raises(NotImplementedError, match="return_lse"): + sparse_dispatch.sparse_mla_prefill( + q_pe, q_lat, bk.view(-1, 576), rows, lens, 0.0625, return_lse=True + ) + + +def test_resident_ep_nonlocal_sentinel_and_swiglu_limit(monkeypatch): + mod = _load_resident_with_stub() + captured = {} + + def _spy_kernel(all_tokens, w13, w2, masked_weight, local_ids, **kwargs): + captured["masked_weight"] = masked_weight.clone() + captured["local_ids"] = local_ids.clone() + captured["kwargs"] = dict(kwargs) + return all_tokens.clone() + + monkeypatch.setattr(mod, "fused_moe_bf16", _spy_kernel) + mod.ResidentEPMoELayer.set_num_tokens_per_rank(2) + try: + # Rank 1 owns experts [8, 16). + w13 = torch.zeros(8, 16, 4) + w2 = torch.zeros(8, 4, 8) + layer = mod.ResidentEPMoELayer( + layer_idx=1, w13=w13, w2=w2, comm=_DummyComm(), + world_size=2, rank=1, expert_start=8, swiglu_limit=10.0, + ) + + def _gate(x): + n = x.shape[0] + # Slot 0 is non-local (expert 3), slot 1 is local (expert 10 -> local 2). + idx = torch.tensor([[3, 10]] * n, dtype=torch.int64) + w = torch.tensor([[0.4, 0.6]] * n, dtype=torch.float32) + return idx, w + + x = torch.ones(2, 4) + out = layer.forward(x, _gate) + assert out.shape == (2, 4) + assert (captured["local_ids"][:, 0] == -1).all() + assert (captured["local_ids"][:, 1] == 2).all() + assert (captured["masked_weight"][:, 0] == 0.0).all() + assert torch.allclose(captured["masked_weight"][:, 1], torch.full((4,), 0.6)) + assert captured["kwargs"] == {"swiglu_limit": 10.0} + finally: + mod.ResidentEPMoELayer.num_tokens_per_rank = None + + +def test_build_layer_shard_custom_weight_keys(): + mod = _load_resident_with_stub() + + def _get(key): + idx = int(key.rsplit("_", 1)[-1]) + return { + "gate_proj.weight": torch.full((6, 4), float(idx + 1), dtype=torch.bfloat16), + "up_proj.weight": torch.full((6, 4), float(idx + 101), dtype=torch.bfloat16), + "down_proj.weight": torch.full((4, 6), float(idx + 201), dtype=torch.bfloat16), + } + + w13, w2 = mod.build_layer_shard( + _get, layer_idx=2, expert_start=8, num_local=2, + hidden_size=4, intermediate_size=6, device="cpu", + weight_keys=("gate_proj.weight", "up_proj.weight", "down_proj.weight"), + ) + assert torch.equal(w13[0, :6], torch.full((6, 4), 9.0, dtype=torch.bfloat16)) + assert torch.equal(w13[0, 6:], torch.full((6, 4), 109.0, dtype=torch.bfloat16)) + assert torch.equal(w2[1], torch.full((4, 6), 210.0, dtype=torch.bfloat16)) From 6f12ded6243af8f4c1a892a831dfe1870cbbf602 Mon Sep 17 00:00:00 2001 From: Tairan Xu <34982739+Andrewxu313@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:52:27 +0000 Subject: [PATCH 2/8] fix(kernel): unpack (out, softmax_lse) from FA3 kvcache tuple Upstream FA3 flash_attn_with_kvcache(return_softmax_lse=True) returns (out, softmax_lse, *rest); return exact 2-tuple (res[0], res[1]) from _fa3_sparse. --- batchgen/attention/mla/sparse_dispatch.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/batchgen/attention/mla/sparse_dispatch.py b/batchgen/attention/mla/sparse_dispatch.py index ffe43fb0b..f0b9cec7e 100644 --- a/batchgen/attention/mla/sparse_dispatch.py +++ b/batchgen/attention/mla/sparse_dispatch.py @@ -121,7 +121,7 @@ def _fa3_sparse( q_pe, q_latent, flat_kv, token_rows, lengths, softmax_scale, *, return_lse: bool = False ): lora = q_latent.shape[-1] - return _fa3_with_kvcache()( + res = _fa3_with_kvcache()( q=q_pe, k_cache=flat_kv[..., lora:], v_cache=flat_kv[..., :lora], @@ -133,6 +133,10 @@ def _fa3_sparse( num_splits=_fa3_num_splits(), return_softmax_lse=return_lse, ) + if return_lse: + # Upstream FA3 flash_attn_with_kvcache returns (out, softmax_lse, *rest). + return res[0], res[1] + return res # --------------------------------------------------------------------------- # From d45ae96519267b068cc7f5115dc058a6d8a06fe1 Mon Sep 17 00:00:00 2001 From: Tairan Xu <34982739+Andrewxu313@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:44:13 +0000 Subject: [PATCH 3/8] fix(kernels): make fused_moe_bf16 graph-safe and chunk large batches Replace torch.bincount with scatter_add_ in moe_align_block_size to remove host syncs during CUDA graph capture, release intermediate buffers early, and chunk batches above 16k tokens to bound peak HBM. --- batchgen_kernels/triton/fused_moe_bf16.py | 89 +++++++++++++++++------ 1 file changed, 65 insertions(+), 24 deletions(-) diff --git a/batchgen_kernels/triton/fused_moe_bf16.py b/batchgen_kernels/triton/fused_moe_bf16.py index cb9fd7aa5..37fc31df6 100644 --- a/batchgen_kernels/triton/fused_moe_bf16.py +++ b/batchgen_kernels/triton/fused_moe_bf16.py @@ -178,7 +178,9 @@ def moe_align_block_size( valid = (flat >= 0) & (flat < num_experts) bucket = torch.where(valid, flat, torch.full_like(flat, num_experts)) - counts_all = torch.bincount(bucket, minlength=num_experts + 1) + # scatter_add_ avoids torch.bincount's GPU->CPU sync and is CUDA-graph-capturable. + counts_all = torch.zeros(num_experts + 1, dtype=torch.int64, device=device) + counts_all.scatter_add_(0, bucket, torch.ones_like(bucket)) counts = counts_all[:num_experts] padded = (counts + (block_size - 1)).div(block_size, rounding_mode="floor") * block_size padded_ends = torch.cumsum(padded, 0) @@ -251,40 +253,23 @@ def _stage_gemm(a, b, c, sorted_ids, expert_ids, num_post, top_k, num_valid, con ) -def fused_moe_bf16( +_MAX_CHUNK_TOKENS = 16384 + + +def _fused_moe_bf16_chunk( x: torch.Tensor, w13: torch.Tensor, w2: torch.Tensor, topk_weights: torch.Tensor, topk_ids: torch.Tensor, *, - swiglu_limit: float | None = None, + swiglu_limit: float | None, ) -> torch.Tensor: - """Fused BF16 MoE forward. - - Args: - x: (M, K) bf16/fp16/fp32 hidden states. - w13: (E, 2N, K) packed [gate; up] expert weights (gate first). - w2: (E, H, N) down-projection expert weights. - topk_weights: (M, top_k) fp32 routing weights (already renormalized - and scaled, as produced by KimiMoEGate / HyV4MoEGate). - topk_ids: (M, top_k) expert indices; entries outside ``[0, E)`` (e.g. - ``-1``) are skipped and their ``topk_weights`` must be 0. - swiglu_limit: optional HY4 clamped-SwiGLU bound (gate clamped to - ``<= limit``, up clamped to ``[-limit, limit]`` in fp32). - - Returns: - (M, H) tensor in x.dtype: sum_k topk_weights[m, k] * expert(x[m]). - """ - assert x.dim() == 2 and w13.dim() == 3 and w2.dim() == 3 - M, K = x.shape + M = x.shape[0] E, N2, _ = w13.shape N = N2 // 2 H = w2.shape[1] top_k = topk_ids.shape[1] - assert w13.shape[2] == K and w2.shape[2] == N and w2.shape[0] == E - if swiglu_limit is not None and swiglu_limit <= 0: - raise ValueError(f"swiglu_limit must be positive, got {swiglu_limit!r}") config = _pick_config(M * top_k) block_m = config[0] @@ -309,11 +294,67 @@ def fused_moe_bf16( SWIGLU_LIMIT=(float(swiglu_limit) if swiglu_limit is not None else 0.0), num_warps=4, ) + del c1 c3 = torch.empty((M * top_k, H), device=x.device, dtype=x.dtype) _stage_gemm(c2, w2, c3, sorted_ids, expert_ids, num_post, 1, M * top_k, config) + del c2 out = moe_weighted_sum_triton( c3.view(M, top_k, H), topk_weights.to(torch.float32) ) + del c3 return out.to(x.dtype) + + +def fused_moe_bf16( + x: torch.Tensor, + w13: torch.Tensor, + w2: torch.Tensor, + topk_weights: torch.Tensor, + topk_ids: torch.Tensor, + *, + swiglu_limit: float | None = None, +) -> torch.Tensor: + """Fused BF16 MoE forward. + + Args: + x: (M, K) bf16/fp16/fp32 hidden states. + w13: (E, 2N, K) packed [gate; up] expert weights (gate first). + w2: (E, H, N) down-projection expert weights. + topk_weights: (M, top_k) fp32 routing weights (already renormalized + and scaled, as produced by KimiMoEGate / HyV4MoEGate). + topk_ids: (M, top_k) expert indices; entries outside ``[0, E)`` (e.g. + ``-1``) are skipped and their ``topk_weights`` must be 0. + swiglu_limit: optional HY4 clamped-SwiGLU bound (gate clamped to + ``<= limit``, up clamped to ``[-limit, limit]`` in fp32). + + Returns: + (M, H) tensor in x.dtype: sum_k topk_weights[m, k] * expert(x[m]). + """ + assert x.dim() == 2 and w13.dim() == 3 and w2.dim() == 3 + M, K = x.shape + E, N2, _ = w13.shape + N = N2 // 2 + H = w2.shape[1] + assert w13.shape[2] == K and w2.shape[2] == N and w2.shape[0] == E + if swiglu_limit is not None and swiglu_limit <= 0: + raise ValueError(f"swiglu_limit must be positive, got {swiglu_limit!r}") + if M <= _MAX_CHUNK_TOKENS: + return _fused_moe_bf16_chunk( + x, w13, w2, topk_weights, topk_ids, swiglu_limit=swiglu_limit + ) + out = torch.empty((M, H), device=x.device, dtype=x.dtype) + for start in range(0, M, _MAX_CHUNK_TOKENS): + end = min(start + _MAX_CHUNK_TOKENS, M) + out[start:end].copy_( + _fused_moe_bf16_chunk( + x[start:end], + w13, + w2, + topk_weights[start:end], + topk_ids[start:end], + swiglu_limit=swiglu_limit, + ) + ) + return out From b29bd98327e4c8c2e052319e0f1974e9fb3acbbc Mon Sep 17 00:00:00 2001 From: Tairan Xu <34982739+Andrewxu313@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:50:25 +0000 Subject: [PATCH 4/8] perf(kernel): bound BF16 MoE chunk size and small sparse-EP tiles Lower fused_moe_bf16 prefill chunk size to 4096 tokens to bound activation HBM under large packed batches, and select the small M tile when running sparse resident-EP shards with small local expert counts. --- batchgen_kernels/triton/fused_moe_bf16.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/batchgen_kernels/triton/fused_moe_bf16.py b/batchgen_kernels/triton/fused_moe_bf16.py index 37fc31df6..96bf7c753 100644 --- a/batchgen_kernels/triton/fused_moe_bf16.py +++ b/batchgen_kernels/triton/fused_moe_bf16.py @@ -215,8 +215,10 @@ def moe_align_block_size( return sorted_ids, expert_ids, num_tokens_post_padded -def _pick_config(m_slots: int): - return _CONFIG_SMALL if m_slots <= 1024 else _CONFIG_LARGE +def _pick_config(m_slots: int, num_experts: int = 256): + if m_slots <= 1024 or (num_experts <= 16 and m_slots <= 4096): + return _CONFIG_SMALL + return _CONFIG_LARGE def _stage_gemm(a, b, c, sorted_ids, expert_ids, num_post, top_k, num_valid, config): @@ -253,7 +255,7 @@ def _stage_gemm(a, b, c, sorted_ids, expert_ids, num_post, top_k, num_valid, con ) -_MAX_CHUNK_TOKENS = 16384 +_MAX_CHUNK_TOKENS = 4096 def _fused_moe_bf16_chunk( @@ -271,7 +273,7 @@ def _fused_moe_bf16_chunk( H = w2.shape[1] top_k = topk_ids.shape[1] - config = _pick_config(M * top_k) + config = _pick_config(M * top_k, E) block_m = config[0] sorted_ids, expert_ids, num_post = moe_align_block_size(topk_ids, block_m, E) From 5e83d678a33490662386a04fef47aec608d6e958 Mon Sep 17 00:00:00 2001 From: Tairan Xu <34982739+Andrewxu313@users.noreply.github.com> Date: Fri, 4 Dec 2026 01:40:57 +0000 Subject: [PATCH 5/8] perf(kernel): fuse Triton moe_align_block_size for small EP Replace multi-op PyTorch moe_align_block_size on small resident-EP shards with a single-CTA zero-atomic deterministic Triton kernel, and widen the small-batch BF16 MoE K/N tile configuration. --- batchgen_kernels/triton/fused_moe_bf16.py | 119 +++++++++++++++++++++- 1 file changed, 115 insertions(+), 4 deletions(-) diff --git a/batchgen_kernels/triton/fused_moe_bf16.py b/batchgen_kernels/triton/fused_moe_bf16.py index 96bf7c753..3628130b1 100644 --- a/batchgen_kernels/triton/fused_moe_bf16.py +++ b/batchgen_kernels/triton/fused_moe_bf16.py @@ -27,7 +27,88 @@ # (BLOCK_M, BLOCK_N, BLOCK_K, GROUP_M, num_warps, num_stages) _CONFIG_LARGE = (64, 64, 32, 8, 4, 3) -_CONFIG_SMALL = (16, 64, 32, 8, 4, 3) +_CONFIG_SMALL = (16, 128, 128, 8, 8, 3) +_ALIGN_TRITON_MAX_EXPERTS = 32 +_ALIGN_TRITON_MAX_SLOTS = 8192 + + +@triton.jit +def _moe_align_block_size_small_kernel( + topk_ids_ptr, + sorted_ids_ptr, + expert_ids_ptr, + num_tokens_post_padded_ptr, + numel, + max_padded, + max_blocks, + num_experts: tl.constexpr, + BLOCK_SIZE: tl.constexpr, + BLOCK_E: tl.constexpr, + BLOCK_T: tl.constexpr, +): + """Single-CTA zero-atomic moe_align_block_size for resident-EP decode.""" + e_offs = tl.arange(0, BLOCK_E) + e_mask = e_offs < num_experts + + # Pass 1: count valid slots per local expert in registers. + counts = tl.zeros((BLOCK_E,), dtype=tl.int32) + t_base = 0 + while t_base < numel: + t_offs = t_base + tl.arange(0, BLOCK_T) + t_mask = t_offs < numel + eids = tl.load(topk_ids_ptr + t_offs, mask=t_mask, other=-1).to(tl.int32) + match = ( + (eids[None, :] == e_offs[:, None]) + & e_mask[:, None] + & t_mask[None, :] + ) + counts += tl.sum(match.to(tl.int32), axis=1) + t_base += BLOCK_T + + padded = ((counts + BLOCK_SIZE - 1) // BLOCK_SIZE) * BLOCK_SIZE + padded = tl.where(e_mask, padded, 0) + padded_ends = tl.cumsum(padded, axis=0) + padded_offsets = padded_ends - padded + total_padded = tl.sum(padded, axis=0) + tl.store(num_tokens_post_padded_ptr, total_padded) + + # Fill expert_ids per BLOCK_SIZE segment (equivalent to searchsorted right=True). + b_base = 0 + while b_base < max_blocks: + b_offs = b_base + tl.arange(0, BLOCK_T) + b_mask = b_offs < max_blocks + b_starts = b_offs * BLOCK_SIZE + ge = (padded_ends[:, None] <= b_starts[None, :]) & e_mask[:, None] + e_for_b = tl.sum(ge.to(tl.int32), axis=0) + tl.store(expert_ids_ptr + b_offs, e_for_b, mask=b_mask) + b_base += BLOCK_T + + # Initialize padded sentinel slots to numel. + s_base = 0 + while s_base < max_padded: + s_offs = s_base + tl.arange(0, BLOCK_T) + tl.store(sorted_ids_ptr + s_offs, numel, mask=s_offs < max_padded) + s_base += BLOCK_T + + # Pass 2: deterministic stable scatter in slot order without atomics. + cur_offsets = padded_offsets + t_base = 0 + while t_base < numel: + t_offs = t_base + tl.arange(0, BLOCK_T) + t_mask = t_offs < numel + eids = tl.load(topk_ids_ptr + t_offs, mask=t_mask, other=-1).to(tl.int32) + match = ( + (eids[None, :] == e_offs[:, None]) + & e_mask[:, None] + & t_mask[None, :] + ).to(tl.int32) + rank_in_chunk = tl.cumsum(match, axis=1) - 1 + dest_2d = cur_offsets[:, None] + rank_in_chunk + dest_1d = tl.sum(dest_2d * match, axis=0) + valid_t = (eids >= 0) & (eids < num_experts) & t_mask + tl.store(sorted_ids_ptr + dest_1d, t_offs.to(tl.int32), mask=valid_t) + cur_offsets += tl.sum(match, axis=1) + t_base += BLOCK_T @triton.jit @@ -173,8 +254,40 @@ def moe_align_block_size( num_tokens_post_padded: (1,) int32 total padded slots. """ device = topk_ids.device - flat = topk_ids.flatten().to(torch.int64) + flat = topk_ids.reshape(-1) numel = flat.numel() + max_padded = numel + (num_experts + 1) * (block_size - 1) + max_blocks = triton.cdiv(max_padded, block_size) + + if ( + topk_ids.is_cuda + and num_experts > 0 + and num_experts <= _ALIGN_TRITON_MAX_EXPERTS + and numel <= _ALIGN_TRITON_MAX_SLOTS + ): + flat_c = flat.contiguous() + sorted_ids = torch.empty((max_padded,), dtype=torch.int32, device=device) + expert_ids = torch.empty((max_blocks,), dtype=torch.int32, device=device) + num_tokens_post_padded = torch.empty((1,), dtype=torch.int32, device=device) + block_e = max(2, triton.next_power_of_2(num_experts)) + block_t = 256 + _moe_align_block_size_small_kernel[(1,)]( + flat_c, + sorted_ids, + expert_ids, + num_tokens_post_padded, + numel, + max_padded, + max_blocks, + num_experts=num_experts, + BLOCK_SIZE=block_size, + BLOCK_E=block_e, + BLOCK_T=block_t, + num_warps=4, + ) + return sorted_ids, expert_ids, num_tokens_post_padded + + flat = flat.to(torch.int64) valid = (flat >= 0) & (flat < num_experts) bucket = torch.where(valid, flat, torch.full_like(flat, num_experts)) @@ -192,7 +305,6 @@ def moe_align_block_size( sorted_buckets = bucket[order] rank = torch.arange(numel, device=device) - counts_offsets[sorted_buckets] - max_padded = numel + (num_experts + 1) * (block_size - 1) # Extra trailing sink slot absorbs invalid (bucket == num_experts) entries # without host sync or dynamic slicing. sorted_buf = torch.full((max_padded + 1,), numel, dtype=torch.int32, device=device) @@ -208,7 +320,6 @@ def moe_align_block_size( sorted_buf[dest] = order.to(torch.int32) sorted_ids = sorted_buf[:max_padded] - max_blocks = triton.cdiv(max_padded, block_size) block_starts = torch.arange(max_blocks, device=device) * block_size expert_ids = torch.searchsorted(padded_ends, block_starts, right=True).to(torch.int32) num_tokens_post_padded = padded_ends[-1].to(torch.int32).reshape(1) From 83e98bc84da057756f6fa30fdd9e227dd911d6fe Mon Sep 17 00:00:00 2001 From: Tairan Xu <34982739+Andrewxu313@users.noreply.github.com> Date: Fri, 4 Dec 2026 02:30:28 +0000 Subject: [PATCH 6/8] perf(kernel): chunk large resident-EP batches and use reduce_scatter Bound global all_gather/reduce_scatter buffer memory in ResidentEPMoELayer.forward on large prepacked prefill waves and replace world all_reduce with reduce_scatter directly into each rank's local slice. --- batchgen/moe/fused_moe_bf16_resident.py | 101 ++++++++++++++---------- tests/test_hy4_kernel_primitives.py | 40 ++++++++++ 2 files changed, 101 insertions(+), 40 deletions(-) diff --git a/batchgen/moe/fused_moe_bf16_resident.py b/batchgen/moe/fused_moe_bf16_resident.py index 5f44a9eeb..85028f55d 100644 --- a/batchgen/moe/fused_moe_bf16_resident.py +++ b/batchgen/moe/fused_moe_bf16_resident.py @@ -133,6 +133,11 @@ def build_layer_shard(get_tensor, layer_idx, expert_start, num_local, return w13, w2 +# Cap the global all_gather/reduce_scatter buffer to avoid OOM on large +# prepacked prefill micro-batches while leaving decode single-shot. +_MAX_GLOBAL_TOKENS = 32768 + + class ResidentEPMoELayer: """Per-layer resident-EP decode MoE forward (thin: kernel + collectives). @@ -174,43 +179,14 @@ def require_resident(self, context): "access, so the decode activation must map and refill it first" ) - def forward(self, x_local, gate): - """Resident-EP decode MoE over DP-sharded tokens. - - Args: - x_local: (num_local_tokens, H) this rank's decode rows; may be - (0, H) on an empty rank — the collectives still run. - gate: router module; called on the gathered (num_global, 1, H) - tokens, returns (topk_idx, topk_weight[, ...]). - - Returns: - (num_local_tokens, H) summed routed-expert output for the local - rows (all 256 experts, combined across ranks). - """ - self.require_resident( - f"resident-EP BF16 MoE forward (layer {self.layer_idx})" - ) - ntp = ResidentEPMoELayer.num_tokens_per_rank - num_tokens, H = x_local.shape - assert ntp is not None and ntp > 0, ( - "resident-EP decode requires the worker rank-count sync " - "(PSM.set_num_tokens_per_rank) before the MoE forward" - ) - assert num_tokens <= ntp, ( - f"local decode rows {num_tokens} exceed synced ntp {ntp}" - ) - num_global = self.world_size * ntp - - # Fixed per-rank layout: zero-pad local rows to ntp, gather globally. - padded = x_local.new_zeros((ntp, H)) - if num_tokens > 0: - padded[:num_tokens].copy_(x_local) + def _forward_chunk(self, padded, gate): + """Run one all_gather -> gate -> fused_moe_bf16 -> reduce_scatter chunk.""" + chunk_ntp, H = padded.shape + num_global = self.world_size * chunk_ntp if self.world_size == 1: - # Degenerate collective schedule: the gather of one rank is the - # padded local rows themselves. all_tokens = padded else: - all_tokens = x_local.new_empty((num_global, H)) + all_tokens = padded.new_empty((num_global, H)) with self.comm.change_state(enable=True): self.comm.all_gather(all_tokens, padded) @@ -235,15 +211,60 @@ def forward(self, x_local, gate): partial = fused_moe_bf16(all_tokens, self.w13, self.w2, masked_weight, local_ids) - # Combine expert shards: SUM over ranks in the global layout (BF16 - # over NCCL, K2.5-class numerics; per-rank top-k accumulation above - # is fp32 inside moe_weighted_sum). if self.world_size > 1: + my_slice = partial.new_empty((chunk_ntp, H)) with self.comm.change_state(enable=True): - self.comm.all_reduce(partial, op=ReduceOp.SUM) + self.comm.reduce_scatter(my_slice, partial, op=ReduceOp.SUM) + return my_slice + return partial + + def forward(self, x_local, gate): + """Resident-EP MoE over DP-sharded tokens (decode and resident-EP prefill). + + Args: + x_local: (num_local_tokens, H) this rank's rows; may be + (0, H) on an empty rank — the collectives still run. + gate: router module; called on the gathered (num_global, 1, H) + tokens, returns (topk_idx, topk_weight[, ...]). + + Returns: + (num_local_tokens, H) summed routed-expert output for the local + rows (all experts, combined across ranks). + """ + self.require_resident( + f"resident-EP BF16 MoE forward (layer {self.layer_idx})" + ) + ntp = ResidentEPMoELayer.num_tokens_per_rank + num_tokens, H = x_local.shape + assert ntp is not None and ntp > 0, ( + "resident-EP decode requires the worker rank-count sync " + "(PSM.set_num_tokens_per_rank) before the MoE forward" + ) + assert num_tokens <= ntp, ( + f"local decode rows {num_tokens} exceed synced ntp {ntp}" + ) + num_global = self.world_size * ntp - start = self.rank * ntp - return partial[start:start + num_tokens] + if num_global <= _MAX_GLOBAL_TOKENS: + padded = x_local.new_zeros((ntp, H)) + if num_tokens > 0: + padded[:num_tokens].copy_(x_local) + out_padded = self._forward_chunk(padded, gate) + return out_padded[:num_tokens] + + chunk_ntp = max(1, _MAX_GLOBAL_TOKENS // self.world_size) + out = x_local.new_empty((num_tokens, H)) + for start in range(0, ntp, chunk_ntp): + end = min(start + chunk_ntp, ntp) + cur_ntp = end - start + padded = x_local.new_zeros((cur_ntp, H)) + valid_end = min(end, num_tokens) + if valid_end > start: + padded[:valid_end - start].copy_(x_local[start:valid_end]) + chunk_out = self._forward_chunk(padded, gate) + if valid_end > start: + out[start:valid_end].copy_(chunk_out[:valid_end - start]) + return out def _resident_moe_layers(model_layers): diff --git a/tests/test_hy4_kernel_primitives.py b/tests/test_hy4_kernel_primitives.py index d24d37fb1..711d6edc5 100644 --- a/tests/test_hy4_kernel_primitives.py +++ b/tests/test_hy4_kernel_primitives.py @@ -41,6 +41,10 @@ def all_gather(self, out, inp): def all_reduce(self, tensor, op=None): pass + def reduce_scatter(self, out, inp, op=None): + self.calls.append(("reduce_scatter", tuple(out.shape), tuple(inp.shape))) + out.copy_(inp[: out.shape[0]]) + def _load_resident_with_stub(): mod_path = ( @@ -192,6 +196,42 @@ def _gate(x): mod.ResidentEPMoELayer.num_tokens_per_rank = None +def test_resident_ep_chunks_large_global_batches(monkeypatch): + mod = _load_resident_with_stub() + chunk_sizes = [] + + def _spy_kernel(all_tokens, w13, w2, masked_weight, local_ids, **kwargs): + chunk_sizes.append(int(all_tokens.shape[0])) + return all_tokens * 2.0 + + monkeypatch.setattr(mod, "fused_moe_bf16", _spy_kernel) + monkeypatch.setattr(mod, "_MAX_GLOBAL_TOKENS", 8) + mod.ResidentEPMoELayer.set_num_tokens_per_rank(5) + try: + comm = _DummyComm() + layer = mod.ResidentEPMoELayer( + layer_idx=1, + w13=torch.zeros(4, 8, 4), + w2=torch.zeros(4, 4, 4), + comm=comm, + world_size=4, + rank=0, + expert_start=0, + ) + + def _gate(x): + n = x.shape[0] + return torch.zeros((n, 2), dtype=torch.int64), torch.ones((n, 2)) + + x = torch.arange(1, 21, dtype=torch.float32).view(5, 4) + out = layer.forward(x, _gate) + # chunk_ntp = 8 // 4 = 2 -> chunks of 2, 2, 1 local rows -> 8, 8, 4 global. + assert chunk_sizes == [8, 8, 4] + assert torch.equal(out, x * 2.0) + finally: + mod.ResidentEPMoELayer.num_tokens_per_rank = None + + def test_build_layer_shard_custom_weight_keys(): mod = _load_resident_with_stub() From f99b8535634f69e8ac3728370f51d97444642c6a Mon Sep 17 00:00:00 2001 From: Tairan Xu <34982739+Andrewxu313@users.noreply.github.com> Date: Fri, 4 Dec 2026 04:51:47 +0000 Subject: [PATCH 7/8] feat(kernel): add sparse_mla_decode num_splits and medium MoE tile Allow callers of sparse_mla_decode to override FA3 num_splits on Hopper while preserving the default policy when omitted, and add a BLOCK_M=32 MoE tile configuration for medium resident-EP slot counts. --- batchgen/attention/mla/sparse_dispatch.py | 15 +++++++++++++-- batchgen_kernels/triton/fused_moe_bf16.py | 5 ++++- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/batchgen/attention/mla/sparse_dispatch.py b/batchgen/attention/mla/sparse_dispatch.py index f0b9cec7e..3de00108f 100644 --- a/batchgen/attention/mla/sparse_dispatch.py +++ b/batchgen/attention/mla/sparse_dispatch.py @@ -118,9 +118,18 @@ def _fa3_num_splits() -> int: def _fa3_sparse( - q_pe, q_latent, flat_kv, token_rows, lengths, softmax_scale, *, return_lse: bool = False + q_pe, + q_latent, + flat_kv, + token_rows, + lengths, + softmax_scale, + *, + return_lse: bool = False, + num_splits: Optional[int] = None, ): lora = q_latent.shape[-1] + resolved_splits = _fa3_num_splits() if num_splits is None else int(num_splits) res = _fa3_with_kvcache()( q=q_pe, k_cache=flat_kv[..., lora:], @@ -130,7 +139,7 @@ def _fa3_sparse( cache_seqlens=lengths, softmax_scale=float(softmax_scale), causal=True, - num_splits=_fa3_num_splits(), + num_splits=resolved_splits, return_softmax_lse=return_lse, ) if return_lse: @@ -228,6 +237,7 @@ def sparse_mla_decode( softmax_scale: float, *, return_lse: bool = False, + num_splits: Optional[int] = None, ): """Decode: one query token per row over the paged latent cache.""" _announce("decode", q_latent, token_rows) @@ -236,6 +246,7 @@ def sparse_mla_decode( return _fa3_sparse( q_pe, q_latent, flat_kv, token_rows, lengths, softmax_scale, return_lse=return_lse, + num_splits=num_splits, ) if return_lse: raise NotImplementedError( diff --git a/batchgen_kernels/triton/fused_moe_bf16.py b/batchgen_kernels/triton/fused_moe_bf16.py index 3628130b1..7503eab2d 100644 --- a/batchgen_kernels/triton/fused_moe_bf16.py +++ b/batchgen_kernels/triton/fused_moe_bf16.py @@ -27,6 +27,7 @@ # (BLOCK_M, BLOCK_N, BLOCK_K, GROUP_M, num_warps, num_stages) _CONFIG_LARGE = (64, 64, 32, 8, 4, 3) +_CONFIG_MED = (32, 128, 128, 8, 8, 3) _CONFIG_SMALL = (16, 128, 128, 8, 8, 3) _ALIGN_TRITON_MAX_EXPERTS = 32 _ALIGN_TRITON_MAX_SLOTS = 8192 @@ -327,7 +328,9 @@ def moe_align_block_size( def _pick_config(m_slots: int, num_experts: int = 256): - if m_slots <= 1024 or (num_experts <= 16 and m_slots <= 4096): + if num_experts <= 16 and 2048 < m_slots <= 4096: + return _CONFIG_MED + if m_slots <= 1024 or (num_experts <= 16 and m_slots <= 2048): return _CONFIG_SMALL return _CONFIG_LARGE From 55a268a310ab44804bb801572dfa75db909208b8 Mon Sep 17 00:00:00 2001 From: Tairan Xu <34982739+Andrewxu313@users.noreply.github.com> Date: Fri, 4 Dec 2026 05:41:22 +0000 Subject: [PATCH 8/8] perf(kernel): retain BLOCK_M=16 tile for resident-EP BF16 MoE Drop the experimental (32, 128, 128) tile in fused_moe_bf16 so resident-EP batches up to 4096 slots stay on the higher-occupancy (16, 128, 128) schedule. --- batchgen_kernels/triton/fused_moe_bf16.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/batchgen_kernels/triton/fused_moe_bf16.py b/batchgen_kernels/triton/fused_moe_bf16.py index 7503eab2d..3628130b1 100644 --- a/batchgen_kernels/triton/fused_moe_bf16.py +++ b/batchgen_kernels/triton/fused_moe_bf16.py @@ -27,7 +27,6 @@ # (BLOCK_M, BLOCK_N, BLOCK_K, GROUP_M, num_warps, num_stages) _CONFIG_LARGE = (64, 64, 32, 8, 4, 3) -_CONFIG_MED = (32, 128, 128, 8, 8, 3) _CONFIG_SMALL = (16, 128, 128, 8, 8, 3) _ALIGN_TRITON_MAX_EXPERTS = 32 _ALIGN_TRITON_MAX_SLOTS = 8192 @@ -328,9 +327,7 @@ def moe_align_block_size( def _pick_config(m_slots: int, num_experts: int = 256): - if num_experts <= 16 and 2048 < m_slots <= 4096: - return _CONFIG_MED - if m_slots <= 1024 or (num_experts <= 16 and m_slots <= 2048): + if m_slots <= 1024 or (num_experts <= 16 and m_slots <= 4096): return _CONFIG_SMALL return _CONFIG_LARGE