[Feat] lora: Add plan-driven dense and MoE LoRA engines (#45892)

This commit is contained in:
Yanbin Jiang
2026-10-22 13:40:56 -07:00
committed by GitHub
parent 154e29c1ec
commit 13999673ef
141 changed files with 33405 additions and 325 deletions
+95 -3
View File
@@ -1,8 +1,10 @@
"""LoRA adapter kernels that only the LoRA runtime calls: ``dense/`` SGMV GEMMs,
``moe/`` fused MoE-LoRA, and the experimental TRT-LLM LoRA path."""
"""LoRA kernels: shared routing/GEMMs, legacy dense adapters and MoE stages.
Runtime plans/providers select implementations; this package records lazy metadata.
"""
from sglang.kernels.registry import register_kernel
from sglang.kernels.spec import KernelBackend, KernelSpec
from sglang.kernels.spec import CapabilityRequirement, KernelBackend, KernelSpec
# Triton kernels registered for inventory. Import them from their modules.
_TRITON_KERNELS = [
@@ -31,4 +33,94 @@ for _mod, _fn in _TRITON_KERNELS:
)
del _mod, _fn
# Host launch APIs; importing this inventory does not import their implementations.
_ENGINE_TRITON_KERNELS = [
("common.routing", "build_route", "build_route"),
("common.lora_a", "grouped_lora_a", "grouped_lora_a"),
("common.lora_a", "per_row_lora_a", "per_row_lora_a"),
("common.lora_b", "grouped_lora_b", "grouped_lora_b"),
("common.lora_b", "per_row_lora_b", "per_row_lora_b"),
(
"dense.embedding_lora_a",
"embedding_lora_a_tokens_fwd",
"embedding_lora_a_tokens_fwd",
),
("moe.activation_delta", "act_delta", "act_delta"),
("moe.align_rows", "pair_to_row_map", "pair_to_row_map"),
("moe.align_rows", "moe_align_single_token", "moe_align_single_token"),
(
"moe.dispatch_contiguous",
"dispatch_layout_contiguous",
"dispatch_layout_contiguous",
),
(
"moe.dispatch_contiguous",
"dispatch_fill_rows_contiguous_bf16",
"dispatch_fill_rows_contiguous_bf16",
),
(
"moe.dispatch_contiguous",
"dispatch_fill_rows_contiguous_fp8",
"dispatch_fill_rows_contiguous_fp8",
),
("moe.dispatch_masked", "dispatch_fill_masked_bf16", "dispatch_fill_masked_bf16"),
("moe.dispatch_masked", "dispatch_fill_masked_fp8", "dispatch_fill_masked_fp8"),
("moe.dispatch_masked_small", "small_masked_prepare", "small_masked_prepare"),
(
"moe.finalize",
"invoke_shared_token_delta_reduce",
"invoke_shared_token_delta_reduce",
),
(
"moe.finalize",
"invoke_shared_token_delta_tail",
"invoke_shared_token_delta_tail",
),
("moe.finalize", "invoke_shared_one_pass", "invoke_shared_one_pass"),
("moe.finalize", "invoke_small_finalize", "invoke_small_finalize"),
("moe.fused_act", "fused_b_act", "fused_b_act"),
("moe.lora_b", "grouped_lora_b", "moe_grouped_lora_b"),
("moe.lora_b", "invoke_down_b_into_base", "invoke_down_b_into_base"),
(
"moe.cutedsl.schedule_builder",
"build_dual_stage_schedules_masked",
"build_dual_stage_schedules_masked",
),
(
"moe.cutedsl.schedule_builder",
"build_dual_stage_schedules_contiguous",
"build_dual_stage_schedules_contiguous",
),
]
for _mod, _fn, _op in _ENGINE_TRITON_KERNELS:
register_kernel(
KernelSpec(
op=f"lora.{_op}",
backend=KernelBackend.TRITON,
target=f"sglang.kernels.ops.lora.{_mod}:{_fn}",
capabilities=frozenset({CapabilityRequirement.CUDA}),
)
)
del _mod, _fn, _op
# CuTeDSL grouped GEMMs: each compiles once and returns the launchable kernel.
# Their kernel classes exist for SM90 (WGMMA) and SM100 (tcgen05) only.
_ENGINE_CUTE_DSL_KERNELS = (
"prepare_masked_bf16",
"prepare_contiguous_bf16",
"prepare_masked_fp8",
"prepare_contiguous_fp8",
)
for _fn in _ENGINE_CUTE_DSL_KERNELS:
register_kernel(
KernelSpec(
op=f"lora.{_fn}",
backend=KernelBackend.CUTE_DSL,
target=f"sglang.kernels.ops.lora.moe.cutedsl.api:{_fn}",
capabilities=frozenset({CapabilityRequirement.cuda(min_sm=(9, 0))}),
)
)
del _fn
__all__: list[str] = []
@@ -0,0 +1 @@
"""Shared LoRA routing, shrink and expand kernels."""
@@ -0,0 +1,399 @@
"""LoRA-A shrink over aligned groups or raw pairs.
Dense slots use ``lora_ranks`` to bound live width at rank * STACK;
MoE slots use the full N.
"""
from __future__ import annotations
from collections.abc import Mapping
import torch
import triton
import triton.language as tl
from sglang.kernels.ops.lora.common.route_view import RouteView
from sglang.kernels.ops.lora.common.routing import (
grouped_tile_coords,
route_bucket_ids,
)
@triton.jit(do_not_specialize=["num_input_rows", "num_pairs", "num_m_blocks"])
def _grouped_lora_a_kernel(
input_ptr,
weight_ptr,
output_ptr,
partial_ptr,
counter_ptr,
pair_to_row_ptr,
sorted_pair_ids_ptr,
block_bucket_ids_ptr,
num_pairs_post_padded_ptr,
lora_ranks_ptr,
num_input_rows,
num_pairs,
stride_im,
stride_ik,
stride_we,
stride_wn,
stride_wk,
stride_om,
stride_on,
stride_pp,
stride_pm,
stride_pn,
num_m_blocks,
WIDTH: tl.constexpr,
N: tl.constexpr,
K: tl.constexpr,
PAIR_INPUT: tl.constexpr,
STACK: tl.constexpr,
SPLIT_K: tl.constexpr,
SPLIT_MODE: tl.constexpr,
GROUPS_PER_SLOT: tl.constexpr,
WEIGHT_DIV: tl.constexpr,
BLOCK_SIZE_M: tl.constexpr,
BLOCK_SIZE_N: tl.constexpr,
BLOCK_SIZE_K: tl.constexpr,
GROUP_SIZE_M: tl.constexpr,
WINDOWED: tl.constexpr = False,
):
# WINDOWED tiles cannot straddle rank blocks or apply the live-rank prefix.
pid = tl.program_id(0)
pid_k = tl.program_id(1)
if WINDOWED:
N_BLOCK: tl.constexpr = N // STACK
TILES_PER_BLOCK: tl.constexpr = (N_BLOCK + BLOCK_SIZE_N - 1) // BLOCK_SIZE_N
num_pid_n = STACK * TILES_PER_BLOCK
else:
num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)
pid_m, pid_n = grouped_tile_coords(pid, num_pid_n, num_m_blocks, GROUP_SIZE_M)
if pid_m * BLOCK_SIZE_M >= tl.load(num_pairs_post_padded_ptr):
return
bucket_id = tl.load(block_bucket_ids_ptr + pid_m)
if bucket_id == -1:
return
if WINDOWED:
block = pid_n // TILES_PER_BLOCK
n_begin = block * N_BLOCK + (pid_n % TILES_PER_BLOCK) * BLOCK_SIZE_N
n_end = (block + 1) * N_BLOCK
k_base = (block * K).to(tl.int64)
else:
n_begin = pid_n * BLOCK_SIZE_N
n_end = N
k_base = 0
if lora_ranks_ptr is not None and not WINDOWED:
n_live = (
tl.load(lora_ranks_ptr + bucket_id // GROUPS_PER_SLOT).to(tl.int32) * STACK
)
if n_begin >= n_live:
return
else:
n_live = n_end
pair_slots = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M).to(tl.int64)
pair_ids = tl.load(sorted_pair_ids_ptr + pair_slots).to(tl.int64)
pair_mask = pair_ids < num_pairs
if pair_to_row_ptr is not None:
input_rows = tl.load(
pair_to_row_ptr + pair_ids,
mask=pair_mask,
other=-1,
).to(tl.int64)
elif PAIR_INPUT:
input_rows = pair_ids
else:
input_rows = pair_ids // WIDTH
input_mask = pair_mask & (input_rows >= 0) & (input_rows < num_input_rows)
n_offsets = n_begin + tl.arange(0, BLOCK_SIZE_N).to(tl.int64)
n_mask = n_offsets < n_live
plane = (bucket_id // WEIGHT_DIV).to(tl.int64)
K_PER_SPLIT: tl.constexpr = (K + SPLIT_K - 1) // SPLIT_K
if SPLIT_K == 1:
k_start = 0
k_end = K
else:
k_start = pid_k * K_PER_SPLIT
k_end = tl.minimum(k_start + K_PER_SPLIT, K)
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
for k_begin in range(k_start, k_end, BLOCK_SIZE_K):
k_offsets = k_begin + tl.arange(0, BLOCK_SIZE_K).to(tl.int64)
k_mask = k_offsets < k_end
lhs = tl.load(
input_ptr
+ input_rows[:, None] * stride_im
+ (k_base + k_offsets)[None, :] * stride_ik,
mask=input_mask[:, None] & k_mask[None, :],
other=0.0,
)
rhs = tl.load(
weight_ptr
+ plane * stride_we
+ n_offsets[None, :] * stride_wn
+ k_offsets[:, None] * stride_wk,
mask=n_mask[None, :] & k_mask[:, None],
other=0.0,
)
accumulator += tl.dot(lhs, rhs, out_dtype=tl.float32)
out_mask = pair_mask[:, None] & n_mask[None, :]
output_ptrs = (
output_ptr + pair_ids[:, None] * stride_om + n_offsets[None, :] * stride_on
)
if SPLIT_K == 1:
tl.store(
output_ptrs, accumulator.to(output_ptr.dtype.element_ty), mask=out_mask
)
else:
plane_ptrs = (
partial_ptr + pair_ids[:, None] * stride_pm + n_offsets[None, :] * stride_pn
)
tl.store(
plane_ptrs + pid_k.to(tl.int64) * stride_pp, accumulator, mask=out_mask
)
if SPLIT_MODE == "serial":
# The barrier orders this program's plane stores before its release;
# the last arrival's acquire makes every plane visible.
tl.debug_barrier()
tile = pid_m * num_pid_n + pid_n
arrived = tl.atomic_add(counter_ptr + tile, 1, sem="acq_rel", scope="gpu")
if arrived == SPLIT_K - 1:
total = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
for s in tl.static_range(SPLIT_K):
total += tl.load(
plane_ptrs + s * stride_pp, mask=out_mask, other=0.0
)
tl.store(
output_ptrs, total.to(output_ptr.dtype.element_ty), mask=out_mask
)
tl.atomic_xchg(counter_ptr + tile, 0, sem="release", scope="gpu")
def grouped_lora_a(
input: torch.Tensor,
weight: torch.Tensor,
output: torch.Tensor,
routing: RouteView,
*,
config: Mapping[str, int],
pair_input: bool = False,
pair_to_row: torch.Tensor | None = None,
lora_ranks: torch.Tensor | None = None,
stack: int = 1,
partial: torch.Tensor | None = None,
counters: torch.Tensor | None = None,
weight_div: int = 1,
windowed: bool = False,
) -> None:
"""Shrink aligned rows into a pair-major bridge.
``pair_to_row`` overrides pair/token input indexing; the weight plane is
bucket // weight_div. ``lora_ranks`` limits output to rank * stack.
``windowed`` block s reads input[:, s*K:(s+1)*K], ignoring ``lora_ranks``.
Split-K uses FP32 partial[split, row, N]; serial needs zeroed counters and
sums planes in a fixed order. Planes mode leaves reduction to B.
"""
num_pairs = routing.num_rows
if num_pairs == 0:
return
block_size_n, num_n_blocks = shrink_column_tiles(
int(config["BLOCK_SIZE_N"]), weight.shape[1], stack, windowed
)
split_k = int(config.get("SPLIT_K", 1))
split_mode = config.get("SPLIT_MODE", "serial")
num_m_blocks = triton.cdiv(routing.sorted_pair_ids.numel(), routing.block_size)
if split_k > 1:
if partial is None or (split_mode == "serial" and counters is None):
raise ValueError("a split-K shrink needs partial planes (and counters)")
if split_mode == "serial" and counters.numel() < num_m_blocks * num_n_blocks:
raise ValueError("split-K tile counters are smaller than the tile grid")
stride_pp, stride_pm, stride_pn = partial.stride()
else:
partial = counters = None
stride_pp = stride_pm = stride_pn = 0
_grouped_lora_a_kernel[(num_m_blocks * num_n_blocks, split_k)](
input,
weight,
output,
partial,
counters,
pair_to_row,
routing.sorted_pair_ids,
routing.block_bucket_ids,
routing.num_pairs_post_padded,
lora_ranks,
input.shape[0],
num_pairs,
input.stride(0),
input.stride(1),
weight.stride(0),
weight.stride(1),
weight.stride(2),
output.stride(0),
output.stride(1),
stride_pp,
stride_pm,
stride_pn,
num_m_blocks=num_m_blocks,
WIDTH=routing.width,
N=weight.shape[1],
K=weight.shape[2],
PAIR_INPUT=pair_input,
STACK=stack,
SPLIT_K=split_k,
SPLIT_MODE=split_mode,
GROUPS_PER_SLOT=routing.groups_per_slot,
WEIGHT_DIV=weight_div,
BLOCK_SIZE_M=routing.block_size,
BLOCK_SIZE_N=block_size_n,
BLOCK_SIZE_K=int(config["BLOCK_SIZE_K"]),
GROUP_SIZE_M=int(config["GROUP_SIZE_M"]),
WINDOWED=windowed,
num_warps=int(config["num_warps"]),
num_stages=int(config["num_stages"]),
)
def shrink_column_tiles(
block_size_n: int, n: int, stack: int, windowed: bool
) -> tuple[int, int]:
"""Return (tile width, tile count), keeping windowed rank blocks separate."""
if not windowed:
return block_size_n, triton.cdiv(n, block_size_n)
n_block = n // stack
block_size_n = max(16, min(block_size_n, triton.next_power_of_2(n_block)))
return block_size_n, stack * triton.cdiv(n_block, block_size_n)
@triton.jit
def _per_row_lora_a_kernel(
input_ptr,
weight_ptr,
group_ids_ptr,
token_slots_ptr,
output_ptr,
stride_im,
stride_ik,
stride_wg,
stride_wn,
stride_wk,
stride_om,
stride_on,
N: tl.constexpr,
K: tl.constexpr,
GROUPS_PER_SLOT: tl.constexpr,
MAX_LORAS: tl.constexpr,
WIDTH: tl.constexpr,
HAS_GROUPS: tl.constexpr,
PAIR_INPUT: tl.constexpr,
BLOCK_SIZE_N: tl.constexpr,
BLOCK_SIZE_K: tl.constexpr,
STACK: tl.constexpr = 1,
WINDOWED: tl.constexpr = False,
):
# One program per (row, column tile). WINDOWED uses the grouped contract.
pair_id = tl.program_id(0)
pid_n = tl.program_id(1)
bucket_id = route_bucket_ids(
group_ids_ptr,
token_slots_ptr,
pair_id,
pair_id >= 0,
GROUPS_PER_SLOT=GROUPS_PER_SLOT,
MAX_LORAS=MAX_LORAS,
WIDTH=WIDTH,
HAS_GROUPS=HAS_GROUPS,
)
if bucket_id == -1:
# B skips or zeroes these rows without reading the bridge.
return
bucket_id = bucket_id.to(tl.int64)
pair64 = pair_id.to(tl.int64)
input_row = pair64 if PAIR_INPUT else pair64 // WIDTH
if WINDOWED:
N_BLOCK: tl.constexpr = N // STACK
TILES_PER_BLOCK: tl.constexpr = (N_BLOCK + BLOCK_SIZE_N - 1) // BLOCK_SIZE_N
block = pid_n // TILES_PER_BLOCK
n_begin = block * N_BLOCK + (pid_n % TILES_PER_BLOCK) * BLOCK_SIZE_N
n_end = (block + 1) * N_BLOCK
k_base = (block * K).to(tl.int64)
else:
n_begin = pid_n * BLOCK_SIZE_N
n_end = N
k_base = 0
n_offsets = n_begin.to(tl.int64) + tl.arange(0, BLOCK_SIZE_N).to(tl.int64)
n_mask = n_offsets < n_end
accumulator = tl.zeros((BLOCK_SIZE_N,), dtype=tl.float32)
for k_begin in range(0, K, BLOCK_SIZE_K):
k_offsets = k_begin + tl.arange(0, BLOCK_SIZE_K).to(tl.int64)
k_mask = k_offsets < K
lhs = tl.load(
input_ptr + input_row * stride_im + (k_base + k_offsets) * stride_ik,
mask=k_mask,
other=0.0,
)
rhs = tl.load(
weight_ptr
+ bucket_id * stride_wg
+ n_offsets[:, None] * stride_wn
+ k_offsets[None, :] * stride_wk,
mask=n_mask[:, None] & k_mask[None, :],
other=0.0,
)
accumulator += tl.sum(rhs.to(tl.float32) * lhs[None, :].to(tl.float32), axis=1)
tl.store(
output_ptr + pair64 * stride_om + n_offsets * stride_on,
accumulator.to(output_ptr.dtype.element_ty),
mask=n_mask,
)
def per_row_lora_a(
input: torch.Tensor,
weight: torch.Tensor,
output: torch.Tensor,
routing: RouteView,
*,
config: Mapping[str, int],
pair_input: bool = False,
stack: int = 1,
windowed: bool = False,
) -> None:
num_pairs = routing.num_rows
if num_pairs == 0:
return
block_size_n, num_n_blocks = shrink_column_tiles(
int(config["BLOCK_SIZE_N"]), weight.shape[1], stack, windowed
)
_per_row_lora_a_kernel[(num_pairs, num_n_blocks)](
input,
weight,
routing.kernel_groups,
routing.token_slots,
output,
input.stride(0),
input.stride(1),
weight.stride(0),
weight.stride(1),
weight.stride(2),
output.stride(0),
output.stride(1),
N=weight.shape[1],
K=weight.shape[2],
GROUPS_PER_SLOT=routing.groups_per_slot,
MAX_LORAS=routing.max_loras,
WIDTH=routing.width,
HAS_GROUPS=routing.group_ids is not None,
PAIR_INPUT=pair_input,
BLOCK_SIZE_N=block_size_n,
BLOCK_SIZE_K=int(config["BLOCK_SIZE_K"]),
STACK=stack,
WINDOWED=windowed,
num_warps=int(config["num_warps"]),
num_stages=int(config["num_stages"]),
)
@@ -0,0 +1,710 @@
"""LoRA-B expands over aligned groups or individual raw-route pairs."""
from __future__ import annotations
from collections.abc import Mapping, Sequence
from typing import NamedTuple
import torch
import triton
import triton.language as tl
from sglang.kernels.ops.lora.common.route_view import RouteView
from sglang.kernels.ops.lora.common.routing import (
grouped_tile_coords,
route_bucket_ids,
)
@triton.jit
def _slice_of_tile(
slice_offsets_ptr, pid_n, NUM_SLICES: tl.constexpr, BLOCK_SIZE_N: tl.constexpr
):
"""Map a column tile to (slice, tile in slice, slice start, width);
-1 for a tile past the last slice."""
start = tl.zeros((), dtype=tl.int32)
slice_id = tl.full((), -1, tl.int32)
n_tile = tl.zeros((), dtype=tl.int32)
n_start = tl.zeros((), dtype=tl.int64)
width = tl.zeros((), dtype=tl.int64)
for s in tl.static_range(NUM_SLICES):
lo = tl.load(slice_offsets_ptr + s).to(tl.int64)
hi = tl.load(slice_offsets_ptr + s + 1).to(tl.int64)
tiles = ((hi - lo + BLOCK_SIZE_N - 1) // BLOCK_SIZE_N).to(tl.int32)
hit = (pid_n >= start) & (pid_n < start + tiles)
slice_id = tl.where(hit, s, slice_id)
n_tile = tl.where(hit, pid_n - start, n_tile)
n_start = tl.where(hit, lo, n_start)
width = tl.where(hit, hi - lo, width)
start += tiles
return slice_id, n_tile, n_start, width
class SliceGeometry(NamedTuple):
"""Map expand tiles to weight slices and destination columns.
Zero uniform_width/out_stride denotes irregular geometry. full_tiles means
every slice width is a multiple of the column tile.
"""
slice_offsets: torch.Tensor # [S + 1] int32, the weight rows of each slice
out_offsets: torch.Tensor # [S] int32, the destination column of each slice
num_slices: int
num_column_tiles: int
uniform_width: int
out_stride: int
full_tiles: bool
block_size_n: int
_GEOMETRY: dict[tuple, SliceGeometry] = {}
def _geometry_inputs(offsets, block_size_n, out_offsets):
if (
type(block_size_n) is not int
or block_size_n <= 0
or block_size_n & (block_size_n - 1)
):
raise ValueError("block_size_n must be a positive power of two")
try:
rows = tuple(offsets)
columns = rows[:-1] if out_offsets is None else tuple(out_offsets)
except TypeError:
raise ValueError("slice offsets must be integer sequences") from None
if len(rows) < 2 or any(type(o) is not int for o in rows) or rows[0] != 0:
raise ValueError("offsets must be increasing int32 prefixes starting at zero")
if out_offsets is not None and (
len(columns) != len(rows) - 1 or any(type(o) is not int for o in columns)
):
raise ValueError("out_offsets needs one nonnegative int32 entry per slice")
return rows, columns
def slice_geometry(
offsets: Sequence[int],
block_size_n: int,
device: torch.device,
out_offsets: Sequence[int] | None = None,
) -> SliceGeometry:
"""Cache weight slices ``offsets`` [S+1] and destination columns [S].
None out_offsets uses weight-row offsets. Entries are never evicted because
graphs retain their device tables. Blocking host-to-device initialization
must precede capture; a cache miss during capture raises.
"""
offsets, out_offsets = _geometry_inputs(offsets, block_size_n, out_offsets)
if device.type != "cuda":
raise ValueError(_NOT_CUDA)
# An index-less device may name a different current device on each call.
if device.index is None:
device = torch.device("cuda", torch.cuda.current_device())
key = (offsets, out_offsets, block_size_n, device)
geometry = _GEOMETRY.get(key)
if geometry is None:
geometry = _build_geometry(offsets, block_size_n, device, out_offsets)
_GEOMETRY[key] = geometry
return geometry
_NOT_CUDA = "the expand kernels read their offset tables from a CUDA device"
def _build_geometry(
rows: tuple[int, ...],
block_size_n: int,
device: torch.device,
columns: tuple[int, ...],
) -> SliceGeometry:
if any(o < 0 or o >= 2**31 for o in rows) or any(
lo >= hi for lo, hi in zip(rows, rows[1:])
):
raise ValueError("offsets must be increasing int32 prefixes starting at zero")
if any(o < 0 or o >= 2**31 for o in columns):
raise ValueError("out_offsets needs one nonnegative int32 entry per slice")
with torch.cuda.device(device):
if torch.cuda.is_current_stream_capturing():
raise RuntimeError(
f"slice geometry {(rows, columns, block_size_n, device)} was first "
"needed inside a CUDA graph capture; run the site eagerly once "
"before capturing"
)
widths = [hi - lo for lo, hi in zip(rows, rows[1:])]
uniform = widths[0] if len(set(widths)) == 1 else 0
stride = columns[1] if len(columns) > 1 else uniform
regular = stride > 0 and all(c == s * stride for s, c in enumerate(columns))
# Share an allocation for cache locality; align the columns to 16 bytes.
head = -(-len(rows) // 4) * 4
table = torch.tensor(
list(rows) + [0] * (head - len(rows)) + list(columns),
dtype=torch.int32,
device=device,
)
return SliceGeometry(
slice_offsets=table[: len(rows)],
out_offsets=table[head:],
num_slices=len(widths),
num_column_tiles=sum(triton.cdiv(w, block_size_n) for w in widths),
uniform_width=uniform,
out_stride=stride if regular else 0,
full_tiles=all(w % block_size_n == 0 for w in widths),
block_size_n=block_size_n,
)
@triton.jit(do_not_specialize=["num_pairs", "num_m_blocks", "sorted_capacity"])
def _grouped_lora_b_kernel(
bridge_ptr,
weight_ptr,
destination_ptr,
sorted_pair_ids_ptr,
block_bucket_ids_ptr,
num_pairs_post_padded_ptr,
lora_ranks_ptr,
scalings_ptr,
slice_offsets_ptr,
out_offsets_ptr,
num_pairs,
stride_bp,
stride_bm,
stride_bk,
stride_wg,
stride_wn,
stride_wk,
stride_dn,
stride_dt,
stride_dh,
num_m_blocks,
sorted_capacity,
num_pid_n: tl.constexpr,
WIDTH: tl.constexpr,
PAIR_BRIDGE: tl.constexpr,
RANK: tl.constexpr,
ADD_INPLACE: tl.constexpr,
ZERO_SENTINEL: tl.constexpr,
GROUPS_PER_SLOT: tl.constexpr,
WEIGHT_DIV: tl.constexpr,
NUM_SLICES: tl.constexpr,
UNIFORM_WIDTH: tl.constexpr,
OUT_STRIDE: tl.constexpr,
FULL_TILES: tl.constexpr,
BLOCK_SIZE_M: tl.constexpr,
BLOCK_SIZE_N: tl.constexpr,
BLOCK_SIZE_K: tl.constexpr,
GROUP_SIZE_M: tl.constexpr,
BRIDGE_SLICES: tl.constexpr,
PLANES: tl.constexpr = 1,
PAIR_HEADS: tl.constexpr = 1,
):
pid = tl.program_id(0)
if UNIFORM_WIDTH > 0:
tiles_per_slice: tl.constexpr = (
UNIFORM_WIDTH + BLOCK_SIZE_N - 1
) // BLOCK_SIZE_N
pid_m, pid_n = grouped_tile_coords(
pid, NUM_SLICES * tiles_per_slice, num_m_blocks, GROUP_SIZE_M
)
else:
pid_m, pid_n = grouped_tile_coords(pid, num_pid_n, num_m_blocks, GROUP_SIZE_M)
# Issue route loads together, but the JIT route's final block can be short.
num_pairs_post_padded = tl.load(num_pairs_post_padded_ptr)
bucket_id = tl.load(block_bucket_ids_ptr + pid_m)
pair_slots = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M).to(tl.int64)
pair_ids = tl.load(
sorted_pair_ids_ptr + pair_slots,
mask=pair_slots < sorted_capacity,
other=num_pairs,
).to(tl.int64)
if pid_m * BLOCK_SIZE_M >= num_pairs_post_padded:
return
if not ZERO_SENTINEL:
if bucket_id == -1:
return
slot = bucket_id // GROUPS_PER_SLOT
if UNIFORM_WIDTH > 0:
slice_id = pid_n // tiles_per_slice
n_tile = pid_n % tiles_per_slice
n_start = (slice_id * UNIFORM_WIDTH).to(tl.int64)
width = UNIFORM_WIDTH
else:
slice_id, n_tile, n_start, width = _slice_of_tile(
slice_offsets_ptr, pid_n, NUM_SLICES, BLOCK_SIZE_N
)
if slice_id < 0:
return
if OUT_STRIDE > 0:
out_start = (slice_id * OUT_STRIDE).to(tl.int64)
else:
out_start = tl.load(out_offsets_ptr + slice_id).to(tl.int64)
pair_mask = pair_ids < num_pairs
n_offsets = n_tile.to(tl.int64) * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N).to(
tl.int64
)
if FULL_TILES:
# Every slice is whole tiles wide: no column mask to carry.
n_mask = tl.full((BLOCK_SIZE_N,), 1, tl.int1)
else:
n_mask = n_offsets < width
row_offsets = (pair_ids // PAIR_HEADS) * stride_dt + (
pair_ids % PAIR_HEADS
) * stride_dh
destination_ptrs = (
destination_ptr
+ row_offsets[:, None]
+ (out_start + n_offsets)[None, :] * stride_dn
)
store_mask = pair_mask[:, None] & n_mask[None, :]
if ZERO_SENTINEL:
if bucket_id == -1:
# A fresh delta buffer must not keep stale graph memory.
zeros = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
tl.store(
destination_ptrs,
zeros.to(destination_ptr.dtype.element_ty),
mask=store_mask,
)
return
if lora_ranks_ptr is not None:
rank = tl.load(lora_ranks_ptr + slot).to(tl.int32)
else:
rank = RANK
if scalings_ptr is not None:
scaling = tl.load(scalings_ptr + slot).to(tl.float32)
plane = (bucket_id // WEIGHT_DIV).to(tl.int64)
if PAIR_BRIDGE:
bridge_rows = pair_ids
else:
bridge_rows = pair_ids // WIDTH
# Read the prior output before the dot so the load overlaps the operands.
if ADD_INPLACE:
prior = tl.load(destination_ptrs, mask=store_mask, other=0.0).to(tl.float32)
if lora_ranks_ptr is not None:
if rank == 0:
return
# A single slice starts at column 0; shared bridge blocks need modulo.
if NUM_SLICES == 1:
bridge_col0 = tl.zeros((), dtype=tl.int64)
elif BRIDGE_SLICES < NUM_SLICES:
bridge_col0 = (slice_id % BRIDGE_SLICES).to(tl.int64) * rank
else:
bridge_col0 = slice_id.to(tl.int64) * rank
# Load the first K block under the pool's static rank mask, then select
# the slot's live rank so these loads do not wait for the rank lookup.
K0: tl.constexpr = min(BLOCK_SIZE_K, RANK)
k_offsets = tl.arange(0, BLOCK_SIZE_K).to(tl.int64)
k_static = k_offsets < K0
weight_tile = (
weight_ptr
+ plane * stride_wg
+ (n_start + n_offsets)[None, :] * stride_wn
+ k_offsets[:, None] * stride_wk
)
rhs = tl.load(weight_tile, mask=n_mask[None, :] & k_static[:, None], other=0.0)
lhs_ptrs = (
bridge_ptr
+ bridge_rows[:, None] * stride_bm
+ (bridge_col0 + k_offsets)[None, :] * stride_bk
)
lhs_mask = pair_mask[:, None] & k_static[None, :]
lhs = tl.load(lhs_ptrs, mask=lhs_mask, other=0.0)
if PLANES > 1:
lhs = lhs.to(tl.float32)
for p in tl.static_range(1, PLANES):
lhs += tl.load(lhs_ptrs + p * stride_bp, mask=lhs_mask, other=0.0).to(
tl.float32
)
if lora_ranks_ptr is not None:
if rank < K0:
k_mask = k_offsets < rank
# Select, not multiply: the unselected lanes may hold anything.
lhs = tl.where(k_mask[None, :], lhs, 0.0)
rhs = tl.where(k_mask[:, None], rhs, 0.0)
# Match a locally materialized bridge's rounding before B; an intervening
# TP reduction can change that rounding order.
accumulator = tl.dot(lhs.to(weight_ptr.dtype.element_ty), rhs, out_dtype=tl.float32)
for k_begin in range(BLOCK_SIZE_K, RANK, BLOCK_SIZE_K):
k_offsets = k_begin + tl.arange(0, BLOCK_SIZE_K).to(tl.int64)
# Mask whole blocks, not lanes: a live-rank lane mask makes these loads
# scalar, and the compiler then converts the planes to the MMA layout
# one by one. A block the rank splits is trimmed after the loads.
k_block = (k_offsets < RANK) & (k_begin < rank)
lhs_ptrs = (
bridge_ptr
+ bridge_rows[:, None] * stride_bm
+ (bridge_col0 + k_offsets)[None, :] * stride_bk
)
lhs_mask = pair_mask[:, None] & k_block[None, :]
lhs = tl.load(lhs_ptrs, mask=lhs_mask, other=0.0)
if PLANES > 1:
lhs = lhs.to(tl.float32)
for p in tl.static_range(1, PLANES):
lhs += tl.load(lhs_ptrs + p * stride_bp, mask=lhs_mask, other=0.0).to(
tl.float32
)
rhs = tl.load(
weight_ptr
+ plane * stride_wg
+ (n_start + n_offsets)[None, :] * stride_wn
+ k_offsets[:, None] * stride_wk,
mask=n_mask[None, :] & k_block[:, None],
other=0.0,
)
if lora_ranks_ptr is not None:
if (rank > k_begin) & (rank < k_begin + BLOCK_SIZE_K):
k_mask = k_offsets < rank
lhs = tl.where(k_mask[None, :], lhs, 0.0)
rhs = tl.where(k_mask[:, None], rhs, 0.0)
accumulator += tl.dot(
lhs.to(weight_ptr.dtype.element_ty), rhs, out_dtype=tl.float32
)
if scalings_ptr is not None:
accumulator *= scaling
if ADD_INPLACE:
accumulator += prior
tl.store(
destination_ptrs,
accumulator.to(destination_ptr.dtype.element_ty),
mask=store_mask,
)
def _k_tile(block_k: int, rank: int) -> int:
"""Limit the configured tile to rounded-up rank, with MMA's minimum of 16."""
return max(16, min(block_k, triton.next_power_of_2(rank)))
def grouped_lora_b(
bridge: torch.Tensor,
weight: torch.Tensor,
destination: torch.Tensor,
routing: RouteView,
*,
geometry: SliceGeometry,
config: Mapping[str, int],
add_inplace: bool,
zero_sentinel: bool,
pair_bridge: bool = True,
lora_ranks: torch.Tensor | None = None,
scalings: torch.Tensor | None = None,
weight_div: int = 1,
planes: int = 1,
pair_heads: int = 0,
bridge_slices: int = 0,
) -> None:
"""Expand an aligned route with ``scaling * bridge @ weight.T`` per slice.
``geometry`` maps weight-row slices to destination columns, replaced unless
``add_inplace``. Bucket ``g`` selects adapter ``g // groups_per_slot`` and
weight plane ``g // weight_div``. ``lora_ranks`` gives the slot's live rank
``r``; None uses the pooled rank. Absent ``scalings`` means pre-scaled weights.
Slice ``s`` reads bridge columns ``[s*r, (s+1)*r)``; ``bridge_slices`` > 0
shares blocks via ``s % bridge_slices``. ``pair_bridge=False`` reads token
``pair // routing.width`` instead of the pair's bridge row. ``planes`` > 1
sums split-K FP32 ``[planes, rows, bridge_width]`` in plane order;
``bridge_width`` includes all stacked rank blocks.
Live rank-zero slots leave output untouched. Invalid pairs are cleared only with
``zero_sentinel``. ``pair_heads`` > 0 addresses a strided ``[tokens, heads,
width]`` destination at ``[pair // heads, pair % heads]``; otherwise it is 2D.
"""
if geometry.block_size_n != config["BLOCK_SIZE_N"]:
raise ValueError("expand BLOCK_SIZE_N must match its slice geometry")
num_pairs = routing.num_rows
if num_pairs == 0:
return
if bridge.dim() != 2 + (planes > 1):
raise ValueError(
"the grouped expand reads a [rows, rank] bridge (or [planes, rows, rank] "
"fp32 planes); an all_slots bridge (one plane per slot) needs the "
"per-row expand"
)
if pair_heads:
if destination.dim() != 3 or destination.shape[1] != pair_heads:
raise ValueError(
"a pair-addressed destination is [tokens, heads, width] with heads == pair_heads"
)
stride_dt, stride_dh, stride_dn = destination.stride()
else:
stride_dt, stride_dh, stride_dn = (
destination.stride(0),
0,
destination.stride(1),
)
num_m_blocks = triton.cdiv(routing.sorted_pair_ids.numel(), routing.block_size)
_grouped_lora_b_kernel[(num_m_blocks * geometry.num_column_tiles,)](
bridge,
weight,
destination,
routing.sorted_pair_ids,
routing.block_bucket_ids,
routing.num_pairs_post_padded,
lora_ranks,
scalings,
geometry.slice_offsets,
geometry.out_offsets,
num_pairs,
bridge.stride(0) if planes > 1 else 0,
bridge.stride(-2),
bridge.stride(-1),
weight.stride(0),
weight.stride(1),
weight.stride(2),
stride_dn,
stride_dt,
stride_dh,
num_m_blocks=num_m_blocks,
sorted_capacity=routing.sorted_pair_ids.numel(),
num_pid_n=geometry.num_column_tiles,
WIDTH=routing.width,
PAIR_BRIDGE=pair_bridge,
RANK=weight.shape[2],
ADD_INPLACE=add_inplace,
ZERO_SENTINEL=zero_sentinel,
GROUPS_PER_SLOT=routing.groups_per_slot,
WEIGHT_DIV=weight_div,
NUM_SLICES=geometry.num_slices,
UNIFORM_WIDTH=geometry.uniform_width,
OUT_STRIDE=geometry.out_stride,
FULL_TILES=geometry.full_tiles,
BLOCK_SIZE_M=routing.block_size,
BLOCK_SIZE_N=int(config["BLOCK_SIZE_N"]),
BLOCK_SIZE_K=_k_tile(int(config["BLOCK_SIZE_K"]), weight.shape[2]),
GROUP_SIZE_M=int(config["GROUP_SIZE_M"]),
BRIDGE_SLICES=int(bridge_slices) or geometry.num_slices,
PLANES=int(planes),
PAIR_HEADS=int(pair_heads) or 1,
num_warps=int(config["num_warps"]),
num_stages=int(config["num_stages"]),
)
@triton.jit
def _per_row_lora_b_kernel(
bridge_ptr,
weight_ptr,
destination_ptr,
group_ids_ptr,
token_slots_ptr,
lora_ranks_ptr,
scalings_ptr,
slice_offsets_ptr,
out_offsets_ptr,
# Keep the weight-stride pair 8-byte aligned for a single sm103 constant load.
stride_wg,
stride_wn,
stride_wk,
stride_bs,
stride_bp,
stride_bm,
stride_bk,
stride_dm,
stride_dn,
PAIR_BRIDGE: tl.constexpr,
RANK: tl.constexpr,
ADD_INPLACE: tl.constexpr,
ZERO_SENTINEL: tl.constexpr,
GROUPS_PER_SLOT: tl.constexpr,
MAX_LORAS: tl.constexpr,
WIDTH: tl.constexpr,
HAS_GROUPS: tl.constexpr,
NUM_SLICES: tl.constexpr,
UNIFORM_WIDTH: tl.constexpr,
OUT_STRIDE: tl.constexpr,
FULL_TILES: tl.constexpr,
BLOCK_SIZE_N: tl.constexpr,
BLOCK_SIZE_K: tl.constexpr,
BRIDGE_SLICES: tl.constexpr,
PLANES: tl.constexpr = 1,
):
# GEMV reduction order differs from grouped B's dot. The grid has no tail rows.
pair_id = tl.program_id(0)
pid_n = tl.program_id(1)
pair64 = pair_id.to(tl.int64)
bucket_id = route_bucket_ids(
group_ids_ptr,
token_slots_ptr,
pair_id,
pair_id >= 0,
GROUPS_PER_SLOT=GROUPS_PER_SLOT,
MAX_LORAS=MAX_LORAS,
WIDTH=WIDTH,
HAS_GROUPS=HAS_GROUPS,
)
if not ZERO_SENTINEL:
if bucket_id == -1:
return
safe_bucket_id = tl.maximum(bucket_id, 0).to(tl.int64)
slot = safe_bucket_id // GROUPS_PER_SLOT
if lora_ranks_ptr is not None:
rank = tl.load(lora_ranks_ptr + slot).to(tl.int32)
else:
rank = RANK
if UNIFORM_WIDTH > 0:
tiles_per_slice: tl.constexpr = (
UNIFORM_WIDTH + BLOCK_SIZE_N - 1
) // BLOCK_SIZE_N
slice_id = pid_n // tiles_per_slice
n_tile = pid_n % tiles_per_slice
n_start = (slice_id * UNIFORM_WIDTH).to(tl.int64)
width = UNIFORM_WIDTH
else:
slice_id, n_tile, n_start, width = _slice_of_tile(
slice_offsets_ptr, pid_n, NUM_SLICES, BLOCK_SIZE_N
)
if slice_id < 0:
return
if OUT_STRIDE > 0:
out_start = (slice_id * OUT_STRIDE).to(tl.int64)
else:
out_start = tl.load(out_offsets_ptr + slice_id).to(tl.int64)
n_offsets = n_tile.to(tl.int64) * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N).to(
tl.int64
)
if FULL_TILES:
n_mask = tl.full((BLOCK_SIZE_N,), 1, tl.int1)
else:
n_mask = n_offsets < width
destination_ptrs = (
destination_ptr + pair64 * stride_dm + (out_start + n_offsets) * stride_dn
)
if ZERO_SENTINEL:
if bucket_id == -1:
# A fresh delta buffer must not keep stale graph memory.
zeros = tl.zeros((BLOCK_SIZE_N,), dtype=tl.float32)
tl.store(
destination_ptrs,
zeros.to(destination_ptr.dtype.element_ty),
mask=n_mask,
)
return
if lora_ranks_ptr is not None:
if rank == 0:
return
if PAIR_BRIDGE:
bridge_row = bridge_ptr + slot * stride_bs + pair64 * stride_bm
else:
bridge_row = bridge_ptr + slot * stride_bs + (pair64 // WIDTH) * stride_bm
if ADD_INPLACE:
prior = tl.load(destination_ptrs, mask=n_mask, other=0.0).to(tl.float32)
if BRIDGE_SLICES < NUM_SLICES:
bridge_col0 = (slice_id % BRIDGE_SLICES).to(tl.int64) * rank
else:
bridge_col0 = slice_id.to(tl.int64) * rank
accumulator = tl.zeros((BLOCK_SIZE_N,), dtype=tl.float32)
for k_begin in range(0, RANK, BLOCK_SIZE_K):
k_offsets = k_begin + tl.arange(0, BLOCK_SIZE_K).to(tl.int64)
# Mask whole blocks, as grouped B does: a live-rank lane mask makes
# every load scalar. A block the rank splits is trimmed after the loads.
k_block = (k_offsets < RANK) & (k_begin < rank)
lhs_ptrs = bridge_row + (bridge_col0 + k_offsets) * stride_bk
lhs = tl.load(lhs_ptrs, mask=k_block, other=0.0)
if PLANES > 1:
lhs = lhs.to(tl.float32)
for p in tl.static_range(1, PLANES):
lhs += tl.load(lhs_ptrs + p * stride_bp, mask=k_block, other=0.0).to(
tl.float32
)
rhs = tl.load(
weight_ptr
+ safe_bucket_id * stride_wg
+ (n_start + n_offsets)[:, None] * stride_wn
+ k_offsets[None, :] * stride_wk,
mask=n_mask[:, None] & k_block[None, :],
other=0.0,
)
if lora_ranks_ptr is not None:
if (rank > k_begin) & (rank < k_begin + BLOCK_SIZE_K):
k_mask = k_offsets < rank
lhs = tl.where(k_mask, lhs, 0.0)
rhs = tl.where(k_mask[None, :], rhs, 0.0)
# Match grouped B's bridge cast before the FP32 multiply.
lhs = lhs.to(weight_ptr.dtype.element_ty).to(tl.float32)
accumulator += tl.sum(rhs.to(tl.float32) * lhs[None, :], axis=1)
if scalings_ptr is not None:
accumulator *= tl.load(scalings_ptr + slot).to(tl.float32)
if ADD_INPLACE:
accumulator += prior
tl.store(
destination_ptrs,
accumulator.to(destination_ptr.dtype.element_ty),
mask=n_mask,
)
def per_row_lora_b(
bridge: torch.Tensor,
weight: torch.Tensor,
destination: torch.Tensor,
routing: RouteView,
*,
geometry: SliceGeometry,
config: Mapping[str, int],
add_inplace: bool,
zero_sentinel: bool,
pair_bridge: bool = True,
lora_ranks: torch.Tensor | None = None,
scalings: torch.Tensor | None = None,
planes: int = 1,
slot_planes: bool = False,
bridge_slices: int = 0,
) -> None:
"""Use ``grouped_lora_b``'s contract over a raw route and 2D destination.
Weights have one plane per bucket. ``slot_planes`` reads a ``[slots, rows,
bridge_width]`` bridge instead of split-K planes; the modes cannot be combined.
"""
if geometry.block_size_n != config["BLOCK_SIZE_N"]:
raise ValueError("expand BLOCK_SIZE_N must match its slice geometry")
num_pairs = routing.num_rows
if num_pairs == 0:
return
if (slot_planes and planes > 1) or bridge.dim() != 2 + (slot_planes or planes > 1):
raise ValueError(
"the per-row expand reads a [rows, rank] bridge, [slots, rows, rank] "
"slot planes or [planes, rows, rank] fp32 split-K planes"
)
_per_row_lora_b_kernel[(num_pairs, geometry.num_column_tiles)](
bridge,
weight,
destination,
routing.kernel_groups,
routing.token_slots,
lora_ranks,
scalings,
geometry.slice_offsets,
geometry.out_offsets,
weight.stride(0),
weight.stride(1),
weight.stride(2),
bridge.stride(0) if slot_planes else 0,
bridge.stride(0) if planes > 1 else 0,
bridge.stride(-2),
bridge.stride(-1),
destination.stride(0),
destination.stride(1),
PAIR_BRIDGE=pair_bridge,
RANK=weight.shape[2],
ADD_INPLACE=add_inplace,
ZERO_SENTINEL=zero_sentinel,
GROUPS_PER_SLOT=routing.groups_per_slot,
MAX_LORAS=routing.max_loras,
WIDTH=routing.width,
HAS_GROUPS=routing.group_ids is not None,
NUM_SLICES=geometry.num_slices,
UNIFORM_WIDTH=geometry.uniform_width,
OUT_STRIDE=geometry.out_stride,
FULL_TILES=geometry.full_tiles,
BLOCK_SIZE_N=int(config["BLOCK_SIZE_N"]),
BLOCK_SIZE_K=_k_tile(int(config["BLOCK_SIZE_K"]), weight.shape[2]),
BRIDGE_SLICES=int(bridge_slices) or geometry.num_slices,
PLANES=int(planes),
num_warps=int(config["num_warps"]),
num_stages=int(config["num_stages"]),
)
@@ -0,0 +1,80 @@
from __future__ import annotations
from enum import Enum
import msgspec
import torch
class RouteViewKind(str, Enum):
RAW = "raw"
ALIGNED = "aligned"
class RouteView(msgspec.Struct, frozen=True, kw_only=True):
"""Token or (token, group) routes, optionally sorted and padded to blocks.
ALIGNED views group rows by adapter/group bucket. With groups_per_slot=1,
all nonnegative group IDs share their adapter's bucket.
"""
view: RouteViewKind
block_size: int
token_slots: torch.Tensor
group_ids: torch.Tensor | None
groups_per_slot: int
max_loras: int
maybe_sorted_pair_ids: torch.Tensor | None = None
maybe_block_bucket_ids: torch.Tensor | None = None
maybe_num_pairs_post_padded: torch.Tensor | None = None
@property
def num_tokens(self) -> int:
return self.token_slots.numel()
@property
def num_rows(self) -> int:
return (
self.token_slots.numel()
if self.group_ids is None
else self.group_ids.numel()
)
@property
def width(self) -> int:
return 1 if self.group_ids is None else self.group_ids.shape[1]
@property
def kernel_groups(self) -> torch.Tensor:
"""Group IDs, or an unread placeholder when HAS_GROUPS=False."""
return self.token_slots if self.group_ids is None else self.group_ids
def _require(self, value, field: str, needed: RouteViewKind):
if value is None:
raise ValueError(
f"route view {self.view.value!r} did not build {field}; the "
f"consumer must request view {needed.value!r} or derive it inline"
)
return value
@property
def sorted_pair_ids(self) -> torch.Tensor:
return self._require(
self.maybe_sorted_pair_ids, "sorted_pair_ids", RouteViewKind.ALIGNED
)
@property
def block_bucket_ids(self) -> torch.Tensor:
return self._require(
self.maybe_block_bucket_ids,
"block_bucket_ids",
RouteViewKind.ALIGNED,
)
@property
def num_pairs_post_padded(self) -> torch.Tensor:
return self._require(
self.maybe_num_pairs_post_padded,
"num_pairs_post_padded",
RouteViewKind.ALIGNED,
)
@@ -0,0 +1,812 @@
"""Build and index adapter/group routes for dense and MoE LoRA."""
from __future__ import annotations
from typing import TYPE_CHECKING
import torch
import triton
import triton.language as tl
from sglang.kernels.ops.lora.common.route_view import RouteView, RouteViewKind
from sglang.kernels.ops.lora.moe.virtual_experts import (
_align_block_size_jit,
)
if TYPE_CHECKING:
from sglang.srt.lora.workspace import LoraWorkspace
# Route-builder dispatch limits; CUDA alignment caps at 8192 buckets.
_LARGE_ROUTE_MIN_BUCKETS = 8192
_LARGE_ROUTE_MIN_PAIRS = 16384
_SMALL_ROUTE_MAX_PAIRS = 512
_SMALL_ROUTE_LOW_BUCKET_MAX_BUCKETS = 4
_SMALL_ROUTE_LOW_BUCKET_MAX_PAIRS = 768
_HIST_BLOCK = 512
_HIST_WARPS = 8
_EXPAND_BLOCK = 128
_EXPAND_WARPS = 4
_SCAN_CHUNK = 2048
_SCAN_WARPS = 4
# Use in-block histograms to reduce global atomics within these limits.
_COUNT_MAX_BINS = 512
_COUNT_MIN_PAIRS = 16384
_CLAIM_MIN_PAIRS_PER_BUCKET = 12288
@triton.jit
def route_bucket_ids(
group_ids_ptr,
token_slots_ptr,
pair_ids,
pair_mask,
GROUPS_PER_SLOT: tl.constexpr,
MAX_LORAS: tl.constexpr,
WIDTH: tl.constexpr,
HAS_GROUPS: tl.constexpr,
):
# Invalid slots/groups map to -1. With one group per slot, any nonnegative
# group folds into that slot; otherwise bound it to the bucket table.
token_ids = pair_ids // WIDTH
slots = tl.load(token_slots_ptr + token_ids, mask=pair_mask, other=-1).to(tl.int32)
live = (slots >= 0) & (slots < MAX_LORAS)
if HAS_GROUPS:
groups = tl.load(group_ids_ptr + pair_ids, mask=pair_mask, other=-1).to(
tl.int32
)
live = live & (groups >= 0)
if GROUPS_PER_SLOT == 1:
buckets = slots
else:
live = live & (groups < GROUPS_PER_SLOT)
buckets = slots * GROUPS_PER_SLOT + groups
else:
buckets = slots
return tl.where(live, buckets, -1)
@triton.jit
def grouped_tile_coords(
pid,
num_pid_n,
num_m_blocks,
GROUP_SIZE_M: tl.constexpr,
):
# Group M blocks for weight reuse; keep num_m_blocks runtime to avoid
# compiling a kernel per prefill size.
programs_per_group = GROUP_SIZE_M * num_pid_n
group_id = pid // programs_per_group
first_pid_m = group_id * GROUP_SIZE_M
group_size_m = tl.minimum(num_m_blocks - first_pid_m, GROUP_SIZE_M)
pid_m = first_pid_m + ((pid % programs_per_group) % group_size_m)
pid_n = (pid % programs_per_group) // group_size_m
return pid_m, pid_n
@triton.jit
def _add_counts(
counts_ptr,
bucket_ids,
mask,
NUM_BUCKETS: tl.constexpr,
BINS: tl.constexpr,
):
buckets = tl.where(bucket_ids < 0, NUM_BUCKETS - 1, bucket_ids)
if BINS == 0:
tl.atomic_add(counts_ptr + buckets, 1, mask=mask)
else:
mine = tl.histogram(tl.where(mask, buckets, BINS - 1), BINS)
bins = tl.arange(0, BINS)
tl.atomic_add(counts_ptr + bins, mine, mask=(bins < NUM_BUCKETS) & (mine > 0))
@triton.jit
def _route_histogram_kernel(
group_ids_ptr,
token_slots_ptr,
counts_ptr,
num_pairs,
NUM_BUCKETS: tl.constexpr,
GROUPS_PER_SLOT: tl.constexpr,
MAX_LORAS: tl.constexpr,
WIDTH: tl.constexpr,
HAS_GROUPS: tl.constexpr,
BLOCK: tl.constexpr,
BINS: tl.constexpr,
USE_PDL: tl.constexpr,
):
# The previous scan (or first allocation) cleared counts.
pair_ids = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK)
pair_mask = pair_ids < num_pairs
_add_counts(
counts_ptr,
route_bucket_ids(
group_ids_ptr,
token_slots_ptr,
pair_ids,
pair_mask,
GROUPS_PER_SLOT=GROUPS_PER_SLOT,
MAX_LORAS=MAX_LORAS,
WIDTH=WIDTH,
HAS_GROUPS=HAS_GROUPS,
),
pair_mask,
NUM_BUCKETS=NUM_BUCKETS,
BINS=BINS,
)
if USE_PDL:
tl.extra.cuda.gdc_launch_dependents()
@triton.jit
def _scan_one(
counts_ptr,
block_cumulative_ptr,
cursor_ptr,
bucket_end_ptr,
padded_pairs_ptr,
num_buckets,
BLOCK_SIZE_M: tl.constexpr,
CHUNK: tl.constexpr,
):
# Clear counts during the scan for the next replay.
running = 0
for base in range(0, num_buckets, CHUNK):
offsets = base + tl.arange(0, CHUNK)
mask = offsets < num_buckets
counts = tl.load(counts_ptr + offsets, mask=mask, other=0)
tl.store(counts_ptr + offsets, 0, mask=mask)
blocks = (counts + BLOCK_SIZE_M - 1) // BLOCK_SIZE_M
block_start = running + tl.cumsum(blocks) - blocks
tl.store(block_cumulative_ptr + offsets, block_start, mask=mask)
slot_start = block_start * BLOCK_SIZE_M
tl.store(cursor_ptr + offsets, slot_start, mask=mask)
tl.store(bucket_end_ptr + offsets, slot_start + counts, mask=mask)
running += tl.sum(blocks)
tl.store(block_cumulative_ptr + num_buckets, running)
tl.store(padded_pairs_ptr, running * BLOCK_SIZE_M)
@triton.jit
def _route_scan_kernel(
counts_ptr,
block_cumulative_ptr,
cursor_ptr,
bucket_end_ptr,
padded_pairs_ptr,
num_buckets,
BLOCK_SIZE_M: tl.constexpr,
CHUNK: tl.constexpr,
USE_PDL: tl.constexpr,
):
if USE_PDL:
tl.extra.cuda.gdc_wait()
# Both place paths wait before reading scan outputs.
tl.extra.cuda.gdc_launch_dependents()
_scan_one(
counts_ptr,
block_cumulative_ptr,
cursor_ptr,
bucket_end_ptr,
padded_pairs_ptr,
num_buckets,
BLOCK_SIZE_M=BLOCK_SIZE_M,
CHUNK=CHUNK,
)
@triton.jit
def _label_blocks(
pid,
block_cumulative_ptr,
bucket_end_ptr,
sorted_pair_ids_ptr,
block_bucket_ids_ptr,
num_blocks,
num_pairs,
NUM_BUCKETS: tl.constexpr,
NUM_ROUTE_BUCKETS: tl.constexpr,
BLOCK: tl.constexpr,
BLOCK_SIZE_M: tl.constexpr,
SEARCH_STEPS: tl.constexpr,
):
block_ids = pid * BLOCK + tl.arange(0, BLOCK)
block_mask = block_ids < num_blocks
low = tl.zeros(block_ids.shape, dtype=tl.int32)
high = tl.full(block_ids.shape, NUM_BUCKETS, dtype=tl.int32)
for _ in range(SEARCH_STEPS):
midpoint = (low + high) // 2
bound = tl.load(
block_cumulative_ptr + tl.minimum(midpoint + 1, NUM_BUCKETS),
mask=block_mask,
other=0,
)
take_upper = block_ids >= bound
low = tl.where(take_upper & (low < high), midpoint + 1, low)
high = tl.where(take_upper | (low >= high), high, midpoint)
owner = tl.minimum(low, NUM_BUCKETS - 1)
total_blocks = tl.load(block_cumulative_ptr + NUM_BUCKETS)
in_plan = block_mask & (block_ids < total_blocks)
tl.store(
block_bucket_ids_ptr + block_ids,
tl.where(in_plan & (owner < NUM_ROUTE_BUCKETS), owner, -1),
mask=block_mask,
)
# B reads sentinel blocks too, so initialize their padding slots.
real_end = tl.load(bucket_end_ptr + owner, mask=in_plan, other=0)
slots = block_ids[:, None] * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)[None, :]
tl.store(
sorted_pair_ids_ptr + slots,
num_pairs,
mask=in_plan[:, None] & (slots >= real_end[:, None]),
)
@triton.jit
def _claim_slots(
cursor_ptr,
bucket_ids,
mask,
NUM_BUCKETS: tl.constexpr,
PER_BLOCK: tl.constexpr,
):
# Per-block claims may reorder pairs within each bucket.
buckets = tl.where(bucket_ids < 0, NUM_BUCKETS - 1, bucket_ids)
if not PER_BLOCK:
return tl.atomic_add(cursor_ptr + buckets, 1, mask=mask)
slots = tl.zeros(buckets.shape, dtype=tl.int32)
for bucket in tl.static_range(NUM_BUCKETS):
mine = tl.where(mask & (buckets == bucket), 1, 0).to(tl.int32)
start = tl.atomic_add(cursor_ptr + bucket, tl.sum(mine))
slots = tl.where(mine == 1, start + tl.cumsum(mine) - mine, slots)
return slots
@triton.jit
def _route_place_kernel(
group_ids_ptr,
token_slots_ptr,
cursor_ptr,
bucket_end_ptr,
block_cumulative_ptr,
sorted_ptr,
block_bucket_ids_ptr,
num_blocks,
label_programs,
num_pairs,
NUM_BUCKETS: tl.constexpr,
NUM_ROUTE_BUCKETS: tl.constexpr,
GROUPS_PER_SLOT: tl.constexpr,
MAX_LORAS: tl.constexpr,
WIDTH: tl.constexpr,
HAS_GROUPS: tl.constexpr,
BLOCK: tl.constexpr,
BLOCK_SIZE_M: tl.constexpr,
SEARCH_STEPS: tl.constexpr,
CLAIM_PER_BLOCK: tl.constexpr,
USE_PDL: tl.constexpr,
):
# Low program IDs label blocks; the rest place pairs.
pid = tl.program_id(0)
if pid < label_programs:
if USE_PDL:
tl.extra.cuda.gdc_wait()
_label_blocks(
pid,
block_cumulative_ptr,
bucket_end_ptr,
sorted_ptr,
block_bucket_ids_ptr,
num_blocks,
num_pairs,
NUM_BUCKETS=NUM_BUCKETS,
NUM_ROUTE_BUCKETS=NUM_ROUTE_BUCKETS,
BLOCK=BLOCK,
BLOCK_SIZE_M=BLOCK_SIZE_M,
SEARCH_STEPS=SEARCH_STEPS,
)
return
# Recompute keys while the scan runs; this needs no scan output.
pair_ids = (pid - label_programs) * BLOCK + tl.arange(0, BLOCK)
pair_mask = pair_ids < num_pairs
bucket_ids = route_bucket_ids(
group_ids_ptr,
token_slots_ptr,
pair_ids,
pair_mask,
GROUPS_PER_SLOT=GROUPS_PER_SLOT,
MAX_LORAS=MAX_LORAS,
WIDTH=WIDTH,
HAS_GROUPS=HAS_GROUPS,
)
if USE_PDL:
# Cursors are this path's first scan dependency.
tl.extra.cuda.gdc_wait()
slots = _claim_slots(
cursor_ptr,
bucket_ids,
pair_mask,
NUM_BUCKETS=NUM_BUCKETS,
PER_BLOCK=CLAIM_PER_BLOCK,
)
tl.store(sorted_ptr + slots, pair_ids, mask=pair_mask)
@triton.jit
def _build_route_bucket_ids_kernel(
group_ids_ptr,
token_slots_ptr,
buckets_ptr,
num_pairs,
GROUPS_PER_SLOT: tl.constexpr,
MAX_LORAS: tl.constexpr,
WIDTH: tl.constexpr,
HAS_GROUPS: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
):
pair_ids = tl.program_id(0) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
pair_mask = pair_ids < num_pairs
buckets = route_bucket_ids(
group_ids_ptr,
token_slots_ptr,
pair_ids,
pair_mask,
GROUPS_PER_SLOT=GROUPS_PER_SLOT,
MAX_LORAS=MAX_LORAS,
WIDTH=WIDTH,
HAS_GROUPS=HAS_GROUPS,
)
tl.store(buckets_ptr + pair_ids, buckets, mask=pair_mask)
def _histogram_bins(num_buckets: int, num_pairs: int) -> int:
# 0 = one atomic per pair; otherwise in-block counting over 2^k bins.
if num_buckets >= _COUNT_MAX_BINS or num_pairs < _COUNT_MIN_PAIRS:
return 0
return 1 << num_buckets.bit_length() # the extra bin holds the masked-off lanes
def _aligned_route_capacity(
num_pairs: int,
block_size: int,
num_route_buckets: int,
) -> int:
"""Bound padded pairs, including the invalid-ID bucket."""
if num_pairs == 0:
return 0
max_nonempty_buckets = min(num_pairs, num_route_buckets + 1)
upper_bound = num_pairs + max_nonempty_buckets * (block_size - 1)
return triton.cdiv(triton.cdiv(upper_bound, block_size) * block_size, 4) * 4
def _aligned_route_scratch(
workspace: LoraWorkspace | None,
*,
prefix: str,
num_buckets: int,
capacity: int,
block_size: int,
device: torch.device,
) -> dict[str, torch.Tensor]:
def alloc(name: str, numel: int, zero: bool = False) -> torch.Tensor:
if workspace is None:
make = torch.zeros if zero else torch.empty
return make((numel,), dtype=torch.int32, device=device)
return workspace.tensor(
f"{prefix}:{name}",
(numel,),
dtype=torch.int32,
device=device,
zero_on_first_allocation=zero,
)
return {
"counts": alloc("counts", num_buckets, zero=True),
"block_cumulative": alloc("block_cumulative", num_buckets + 1),
"cursor": alloc("cursor", num_buckets),
"bucket_end": alloc("bucket_end", num_buckets),
"padded_pairs": alloc("padded_pairs", 1),
"sorted": alloc("sorted", capacity),
"block_bucket_ids": alloc("block_bucket_ids", capacity // block_size),
}
def _build_large_route(
token_slots: torch.Tensor,
group_ids: torch.Tensor | None,
*,
groups_per_slot: int,
max_loras: int,
block_size: int,
workspace: LoraWorkspace | None,
tensor_prefix: str | None,
capacity: int | None = None,
) -> RouteView:
from sglang.kernels.jit.utils import is_arch_support_pdl
groups = token_slots if group_ids is None else group_ids # placeholder pointer
num_pairs = groups.numel()
width = 1 if group_ids is None else group_ids.shape[1]
num_route_buckets = groups_per_slot * max_loras
num_buckets = num_route_buckets + 1
# Shared buffers may reserve more rows than this builder needs.
capacity = max(
_aligned_route_capacity(num_pairs, block_size, num_route_buckets), capacity or 0
)
capacity = triton.cdiv(capacity, block_size) * block_size
if num_route_buckets + 1 >= 2**31 or capacity >= 2**31:
raise ValueError(
f"aligned routes use int32 plan math: {tensor_prefix} needs "
f"{num_route_buckets + 1} buckets and {capacity} slots, both must be < 2**31"
)
# Scratch per bucket layout: one prefix may carry routes of different widths.
own = _aligned_route_scratch(
workspace,
prefix=f"{tensor_prefix}:groups{groups_per_slot}",
num_buckets=num_buckets,
capacity=capacity,
block_size=block_size,
device=token_slots.device,
)
use_pdl = is_arch_support_pdl()
pdl_kwargs = {"launch_pdl": True} if use_pdl else {}
_route_histogram_kernel[(triton.cdiv(max(num_pairs, 1), _HIST_BLOCK),)](
groups,
token_slots,
own["counts"],
num_pairs,
NUM_BUCKETS=num_buckets,
GROUPS_PER_SLOT=groups_per_slot,
MAX_LORAS=max_loras,
WIDTH=width,
HAS_GROUPS=group_ids is not None,
BLOCK=_HIST_BLOCK,
BINS=_histogram_bins(num_buckets, num_pairs),
USE_PDL=use_pdl,
num_warps=_HIST_WARPS,
)
_route_scan_kernel[(1,)](
own["counts"],
own["block_cumulative"],
own["cursor"],
own["bucket_end"],
own["padded_pairs"],
num_buckets,
BLOCK_SIZE_M=block_size,
CHUNK=_SCAN_CHUNK,
USE_PDL=use_pdl,
num_warps=_SCAN_WARPS,
**pdl_kwargs,
)
num_blocks = capacity // block_size
label_programs = triton.cdiv(max(num_blocks, 1), _EXPAND_BLOCK)
_route_place_kernel[
(label_programs + triton.cdiv(max(num_pairs, 1), _EXPAND_BLOCK),)
](
groups,
token_slots,
own["cursor"],
own["bucket_end"],
own["block_cumulative"],
own["sorted"],
own["block_bucket_ids"],
num_blocks,
label_programs,
num_pairs,
NUM_BUCKETS=num_buckets,
NUM_ROUTE_BUCKETS=num_buckets - 1,
GROUPS_PER_SLOT=groups_per_slot,
MAX_LORAS=max_loras,
WIDTH=width,
HAS_GROUPS=group_ids is not None,
BLOCK=_EXPAND_BLOCK,
BLOCK_SIZE_M=block_size,
# Include the sentinel in the binary-search depth.
SEARCH_STEPS=num_buckets.bit_length(),
CLAIM_PER_BLOCK=num_pairs >= _CLAIM_MIN_PAIRS_PER_BUCKET * num_buckets,
USE_PDL=use_pdl,
num_warps=_EXPAND_WARPS,
**pdl_kwargs,
)
return RouteView(
view=RouteViewKind.ALIGNED,
block_size=block_size,
token_slots=token_slots,
group_ids=group_ids,
groups_per_slot=groups_per_slot,
max_loras=max_loras,
maybe_sorted_pair_ids=own["sorted"],
maybe_block_bucket_ids=own["block_bucket_ids"],
maybe_num_pairs_post_padded=own["padded_pairs"],
)
def _build_route_bucket_ids(
token_slots: torch.Tensor,
group_ids: torch.Tensor | None,
*,
groups_per_slot: int,
max_loras: int,
out: torch.Tensor,
) -> torch.Tensor:
groups = token_slots if group_ids is None else group_ids # placeholder pointer
num_pairs = out.numel()
if num_pairs == 0:
return out
block_size = 1024
_build_route_bucket_ids_kernel[(triton.cdiv(num_pairs, block_size),)](
groups,
token_slots,
out,
num_pairs,
GROUPS_PER_SLOT=groups_per_slot,
MAX_LORAS=max_loras,
WIDTH=1 if group_ids is None else group_ids.shape[1],
HAS_GROUPS=group_ids is not None,
BLOCK_SIZE=block_size,
)
return out
# Like CUDA alignment, the small builder places the sentinel bucket first.
# Pair order within each bucket is arbitrary.
@triton.jit
def _build_small_route_kernel(
group_ids_ptr,
token_slots_ptr,
sorted_pair_ids_ptr,
block_bucket_ids_ptr,
num_pairs_post_padded_ptr,
scratch_ptr, # int32 [2 * NUM_BINS]: bucket counters, then padded bucket starts
num_pairs,
num_route_buckets,
capacity,
num_blocks,
GROUPS_PER_SLOT: tl.constexpr,
MAX_LORAS: tl.constexpr,
WIDTH: tl.constexpr,
HAS_GROUPS: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
LANES: tl.constexpr,
NUM_BINS: tl.constexpr,
FILL: tl.constexpr,
):
lane = tl.arange(0, LANES)
pair_mask = lane < num_pairs
bucket = route_bucket_ids(
group_ids_ptr,
token_slots_ptr,
lane,
pair_mask,
GROUPS_PER_SLOT=GROUPS_PER_SLOT,
MAX_LORAS=MAX_LORAS,
WIDTH=WIDTH,
HAS_GROUPS=HAS_GROUPS,
)
# Bin 0 is the sentinel bucket of the dead rows; bucket b is bin b + 1.
bin_id = tl.where(bucket >= 0, bucket + 1, 0)
# The counters are cleared here, so a graph replay is self-contained.
for off in range(0, NUM_BINS, FILL):
idx = off + tl.arange(0, FILL)
tl.store(
scratch_ptr + idx, tl.zeros([FILL], dtype=tl.int32), mask=idx < NUM_BINS
)
tl.debug_barrier()
rank = tl.atomic_add(scratch_ptr + bin_id, 1, mask=pair_mask)
tl.debug_barrier()
bins = tl.arange(0, NUM_BINS)
counts = tl.load(
scratch_ptr + bins,
mask=bins < num_route_buckets + 1,
other=0,
cache_modifier=".cg",
)
padded = (counts + BLOCK_SIZE - 1) // BLOCK_SIZE * BLOCK_SIZE
starts = tl.cumsum(padded, axis=0) - padded
tl.store(scratch_ptr + NUM_BINS + bins, starts)
total = tl.sum(padded, axis=0)
for off in range(0, capacity, FILL):
idx = off + tl.arange(0, FILL)
tl.store(
sorted_pair_ids_ptr + idx,
tl.zeros([FILL], dtype=tl.int32) + num_pairs,
mask=idx < capacity,
)
for off in range(0, num_blocks, FILL):
idx = off + tl.arange(0, FILL)
tl.store(
block_bucket_ids_ptr + idx,
tl.zeros([FILL], dtype=tl.int32) - 1,
mask=idx < num_blocks,
)
tl.debug_barrier()
pos = tl.load(scratch_ptr + NUM_BINS + bin_id, cache_modifier=".cg") + rank
tl.store(sorted_pair_ids_ptr + pos, lane, mask=pair_mask)
tl.store(block_bucket_ids_ptr + pos // BLOCK_SIZE, bin_id - 1, mask=pair_mask)
tl.store(num_pairs_post_padded_ptr, total)
def _build_small_route(
token_slots: torch.Tensor,
group_ids: torch.Tensor | None,
*,
groups_per_slot: int,
max_loras: int,
block_size: int,
workspace: LoraWorkspace | None,
tensor_prefix: str | None,
) -> RouteView:
groups = token_slots if group_ids is None else group_ids # placeholder pointer
shape = (token_slots.numel(), 1) if group_ids is None else tuple(group_ids.shape)
num_pairs = shape[0] * shape[1]
num_route_buckets = groups_per_slot * max_loras
# The CUDA builder's capacity, so consumers size their grids the same way.
if num_pairs < num_route_buckets + 1:
capacity = num_pairs * block_size
else:
capacity = num_pairs + (num_route_buckets + 1) * (block_size - 1)
capacity = (capacity + 3) & ~3
num_blocks = triton.cdiv(capacity, block_size)
lanes = max(16, triton.next_power_of_2(num_pairs))
num_bins = max(16, triton.next_power_of_2(num_route_buckets + 1))
device = token_slots.device
if workspace is not None:
prefix = f"{tensor_prefix}:small"
def alloc(name: str, numel: int) -> torch.Tensor:
return workspace.tensor(
f"{prefix}:{name}", (numel,), dtype=torch.int32, device=device
)
else:
def alloc(name: str, numel: int) -> torch.Tensor:
return torch.empty((numel,), dtype=torch.int32, device=device)
sorted_pair_ids = alloc("sorted", capacity)
block_bucket_ids = alloc("block_bucket_ids", num_blocks)
num_pairs_post_padded = alloc("num_post", 1)
scratch = alloc("scratch", 2 * num_bins)
_build_small_route_kernel[(1,)](
groups,
token_slots,
sorted_pair_ids,
block_bucket_ids,
num_pairs_post_padded,
scratch,
num_pairs,
num_route_buckets,
capacity,
num_blocks,
GROUPS_PER_SLOT=groups_per_slot,
MAX_LORAS=max_loras,
WIDTH=shape[1],
HAS_GROUPS=group_ids is not None,
BLOCK_SIZE=block_size,
LANES=lanes,
NUM_BINS=num_bins,
FILL=1024,
num_warps=8 if max(lanes, num_bins) >= 1024 else 4,
)
return RouteView(
view=RouteViewKind.ALIGNED,
block_size=block_size,
token_slots=token_slots,
group_ids=group_ids,
groups_per_slot=groups_per_slot,
max_loras=max_loras,
maybe_sorted_pair_ids=sorted_pair_ids,
maybe_block_bucket_ids=block_bucket_ids,
maybe_num_pairs_post_padded=num_pairs_post_padded,
)
def build_route(
token_slots: torch.Tensor,
*,
group_ids: torch.Tensor | None = None,
groups_per_slot: int = 1,
max_loras: int,
block_size: int,
view: RouteViewKind | str = RouteViewKind.ALIGNED,
workspace: LoraWorkspace | None = None,
tensor_prefix: str | None = None,
capacity: int | None = None,
) -> RouteView:
"""Route tokens, or flattened ``group_ids`` [tokens, width] pairs.
For ALIGNED views, ``capacity`` forces the large builder and reserves at
least that many rows, rounded up to a block.
"""
try:
view = RouteViewKind(view)
except (TypeError, ValueError):
raise ValueError(
f"unknown route view {view!r}; expected one of "
f"{tuple(kind.value for kind in RouteViewKind)}"
) from None
if type(block_size) is not int or block_size <= 0:
raise ValueError("block_size must be a positive integer")
if capacity is not None and (type(capacity) is not int or capacity < 0):
raise ValueError("capacity must be a non-negative integer")
if groups_per_slot > 1 and group_ids is None:
raise ValueError("a route with more than one group per slot needs group_ids")
common = {
"view": view,
"block_size": block_size,
"token_slots": token_slots,
"group_ids": group_ids,
"groups_per_slot": groups_per_slot,
"max_loras": max_loras,
}
if view is RouteViewKind.RAW:
return RouteView(**common)
shape = (token_slots.numel(), 1) if group_ids is None else tuple(group_ids.shape)
rows = shape[0] * shape[1]
num_route_buckets = groups_per_slot * max_loras
if (
capacity is not None
or num_route_buckets >= _LARGE_ROUTE_MIN_BUCKETS
or rows >= _LARGE_ROUTE_MIN_PAIRS
):
return _build_large_route(
token_slots,
group_ids,
groups_per_slot=groups_per_slot,
max_loras=max_loras,
block_size=block_size,
workspace=workspace,
tensor_prefix=tensor_prefix,
capacity=capacity,
)
small_max_pairs = _SMALL_ROUTE_MAX_PAIRS
if 0 < num_route_buckets <= _SMALL_ROUTE_LOW_BUCKET_MAX_BUCKETS:
small_max_pairs = _SMALL_ROUTE_LOW_BUCKET_MAX_PAIRS
if 0 < rows <= small_max_pairs:
return _build_small_route(
token_slots,
group_ids,
groups_per_slot=groups_per_slot,
max_loras=max_loras,
block_size=block_size,
workspace=workspace,
tensor_prefix=tensor_prefix,
)
# Use workspace storage to keep scratch out of the CUDA graph pool.
scratch = None
device = token_slots.device
if workspace is not None:
prefix = f"{tensor_prefix}:jit"
buckets_out = workspace.tensor(
f"{prefix}:bucket_ids", shape, dtype=torch.int32, device=device
)
scratch = lambda numel: workspace.tensor( # noqa: E731
f"{prefix}:scratch", (numel,), dtype=torch.int32, device=device
)
else:
buckets_out = torch.empty(shape, dtype=torch.int32, device=device)
buckets = _build_route_bucket_ids(
token_slots,
group_ids,
groups_per_slot=groups_per_slot,
max_loras=max_loras,
out=buckets_out,
)
sorted_pair_ids, block_bucket_ids, num_pairs_post_padded = _align_block_size_jit(
buckets, block_size, num_route_buckets, scratch=scratch
)
return RouteView(
**common,
maybe_sorted_pair_ids=sorted_pair_ids,
maybe_block_bucket_ids=block_bucket_ids,
maybe_num_pairs_post_padded=num_pairs_post_padded,
)
@@ -184,3 +184,112 @@ def embedding_lora_a_fwd(
)
return output
@triton.jit
def _embedding_lora_a_tokens_kernel(
input_ids,
weights,
output,
extra_embeddings,
token_lora_mapping, # int32 [S]: adapter slot per token, -1 = none
lora_ranks,
vocab_size,
rank,
w_stride_0,
w_stride_1,
w_stride_2,
output_stride_0,
output_stride_1,
extra_emb_stride_0,
extra_emb_stride_1,
extra_emb_stride_2,
BLOCK_RANK: tl.constexpr,
HAS_EXTRA_EMBEDDINGS: tl.constexpr,
):
"""One program per token; zero inactive rows and columns beyond live rank."""
token = tl.program_id(axis=0)
slot = tl.load(token_lora_mapping + token)
has_adapter = slot >= 0
w_index = tl.where(has_adapter, slot, 0)
rank_val = tl.where(has_adapter, tl.load(lora_ranks + w_index), 0)
token_id = tl.load(input_ids + token)
is_extra_token = token_id >= vocab_size
token_id_clamped = tl.minimum(token_id, vocab_size - 1)
extra_token_id = tl.maximum(token_id - vocab_size, 0)
for block_id in range(tl.cdiv(rank, BLOCK_RANK)):
rank_offset = tl.arange(0, BLOCK_RANK) + block_id * BLOCK_RANK
live = rank_offset < rank_val
if HAS_EXTRA_EMBEDDINGS and is_extra_token:
emb_values = tl.load(
extra_embeddings
+ w_index * extra_emb_stride_0
+ extra_token_id * extra_emb_stride_1
+ rank_offset * extra_emb_stride_2,
mask=live,
other=0.0,
)
else:
emb_values = tl.load(
weights
+ w_index * w_stride_0
+ rank_offset * w_stride_1
+ token_id_clamped * w_stride_2,
mask=live,
other=0.0,
)
tl.store(
output + token * output_stride_0 + rank_offset * output_stride_1,
emb_values,
mask=rank_offset < rank,
)
def embedding_lora_a_tokens_fwd(
input_ids: torch.Tensor,
weights: torch.Tensor,
token_lora_mapping: torch.Tensor,
lora_ranks: torch.Tensor,
vocab_size: int,
extra_embeddings: torch.Tensor = None,
) -> torch.Tensor:
"""Look up LoRA A by token slot (-1 = inactive), respecting per-slot ranks.
The grid follows token count, not request count, including graph padding.
"""
assert input_ids.is_contiguous() and weights.is_contiguous()
assert input_ids.dim() == 1 and weights.dim() == 3
S = input_ids.shape[0]
assert token_lora_mapping.shape[0] >= S, (token_lora_mapping.shape, S)
rank = weights.shape[1]
has_extra = extra_embeddings is not None
if has_extra:
assert extra_embeddings.is_contiguous()
extra_emb_stride = tuple(extra_embeddings.stride())
else:
extra_embeddings = weights
extra_emb_stride = (1, 1, 1)
output = torch.empty((S, rank), device=input_ids.device, dtype=weights.dtype)
if S == 0:
return output
_embedding_lora_a_tokens_kernel[(S,)](
input_ids,
weights,
output,
extra_embeddings,
token_lora_mapping,
lora_ranks,
vocab_size,
rank,
weights.stride(0),
weights.stride(1),
weights.stride(2),
output.stride(0),
output.stride(1),
extra_emb_stride[0],
extra_emb_stride[1],
extra_emb_stride[2],
BLOCK_RANK=128,
HAS_EXTRA_EMBEDDINGS=has_extra,
)
return output
@@ -1,2 +1,3 @@
"""Fused MoE-LoRA kernels: the fused shrink/expand Triton kernel, LoRA-aware
block alignment (JIT), and the merged virtual-expert path."""
"""MoE-LoRA kernels: the legacy fused shrink/expand kernel, LoRA-aware block
alignment and virtual-expert path, and the engine's dispatch, activation, B,
finalize stages and CuTeDSL grouped GEMMs."""
@@ -0,0 +1,17 @@
from __future__ import annotations
from enum import Enum
class ActivationFn(str, Enum):
SILU = "silu"
RELU2 = "relu2"
@classmethod
def parse(cls, name: str) -> ActivationFn:
try:
return cls(name)
except ValueError:
raise ValueError(
f"activation {name!r} is not one of {tuple(fn.value for fn in cls)}"
) from None
@@ -0,0 +1,174 @@
"""Add LoRA before activation and expose pair-major inputs for down-A.
pair_to_row addresses either base row layout; invalid pair outputs are zero.
"""
from __future__ import annotations
import torch
import triton
import triton.language as tl
from sglang.kernels.ops.lora.moe.activation import ActivationFn
from sglang.kernels.ops.lora.moe.fp8_quant import quantize_fp8_groups
@triton.jit
def apply_activation(x, ACTIVATION_TYPE: tl.constexpr):
if ACTIVATION_TYPE == "silu":
return x * tl.sigmoid(x)
elif ACTIVATION_TYPE == "relu2":
value = tl.maximum(x, 0.0)
return value * value
else:
raise ValueError(f"unsupported activation {ACTIVATION_TYPE}")
@triton.jit
def _act_delta_kernel(
gateup_ptr, # [rows, slices * inter] bf16, flat base rows
delta_ptr, # [num_tokens, top_k, slices * inter] [gate | up]
act_out_ptr, # [rows, inter] bf16, flat base rows
act_lora_in_ptr, # [num_tokens, top_k, inter] bf16
act_q_ptr, # [rows, inter] fp8e4m3 (QUANT_GROUP > 0 only)
act_s_ptr, # [rows, inter // QUANT_GROUP] fp32 row-major
pair_to_row_ptr, # [num_tokens * top_k] int32
topk_ids_ptr, # [num_tokens, top_k] (local ids; < 0 = invalid)
num_local_experts,
inter,
HAS_DELTA: tl.constexpr,
NUM_SLICES: tl.constexpr,
ACTIVATION_TYPE: tl.constexpr,
GATE_FIRST: tl.constexpr,
INTERLEAVED: tl.constexpr,
QUANT_GROUP: tl.constexpr, # 0 disables the additional FP8 output.
WHOLE_ROW: tl.constexpr, # Match upstream's whole-row rounding.
BLOCK_SIZE: tl.constexpr,
):
pair_idx_int32 = tl.program_id(0)
pair_idx = pair_idx_int32.to(tl.int64)
expert_id = tl.load(topk_ids_ptr + pair_idx)
valid = (expert_id >= 0) & (expert_id < num_local_experts)
dst_row = tl.load(pair_to_row_ptr + pair_idx, mask=valid, other=0).to(tl.int64)
total_inter = NUM_SLICES * inter
gateup_row = gateup_ptr + dst_row * total_inter
delta_row = delta_ptr + pair_idx * total_inter
act_out_row = act_out_ptr + dst_row * inter
lora_in_row = act_lora_in_ptr + pair_idx * inter
vec = tl.arange(0, BLOCK_SIZE)
for start in tl.range(0, inter, BLOCK_SIZE):
offs = start + vec
mask = offs < inter
if NUM_SLICES == 1:
gate_offs = offs
up_offs = offs
elif INTERLEAVED:
gate_offs = 2 * offs
up_offs = 2 * offs + 1
else:
gate_offs = offs
up_offs = inter + offs
if not GATE_FIRST:
gate_offs, up_offs = up_offs, gate_offs
g = tl.load(gateup_row + gate_offs, mask=mask & valid, other=0.0).to(tl.float32)
if HAS_DELTA:
# The delta is always contiguous [gate | up].
dg = tl.load(delta_row + offs, mask=mask & valid, other=0.0).to(tl.float32)
g += dg
act = apply_activation(g, ACTIVATION_TYPE)
if NUM_SLICES == 2:
u = tl.load(gateup_row + up_offs, mask=mask & valid, other=0.0).to(
tl.float32
)
if HAS_DELTA:
du = tl.load(
delta_row + inter + offs,
mask=mask & valid,
other=0.0,
).to(tl.float32)
u += du
act = act * u
act_bf16 = act.to(act_out_ptr.dtype.element_ty)
tl.store(act_out_row + offs, act_bf16, mask=mask & valid)
lora_in = tl.where(valid, act, 0.0)
tl.store(
lora_in_row + offs, lora_in.to(act_lora_in_ptr.dtype.element_ty), mask=mask
)
if QUANT_GROUP > 0:
# Quantize the BF16-rounded value, matching the unfused path.
# Admission ensures each quantization group is fully valid or masked.
QG: tl.constexpr = QUANT_GROUP if QUANT_GROUP > 0 else BLOCK_SIZE
grouped = tl.reshape(
tl.where(mask & valid, act_bf16.to(tl.float32), 0.0),
(BLOCK_SIZE // QG, QG),
)
q, scale = quantize_fp8_groups(grouped, WHOLE_ROW)
tl.store(
act_q_ptr + dst_row * inter + offs,
tl.reshape(q, (BLOCK_SIZE,)).to(act_q_ptr.dtype.element_ty),
mask=mask & valid,
)
gvec = tl.arange(0, BLOCK_SIZE // QG)
goffs = start // QG + gvec
n_groups = inter // QG
tl.store(
act_s_ptr + dst_row * n_groups + goffs,
scale,
mask=(goffs < n_groups) & valid,
)
def act_delta(
gateup_rows: torch.Tensor,
gate_up_delta: torch.Tensor | None, # [num_tokens, top_k, slices * inter]
act_out_rows: torch.Tensor,
activation_lora_input: torch.Tensor, # [num_tokens, top_k, inter] bf16
pair_to_row: torch.Tensor, # [num_tokens * top_k] int32
topk_ids: torch.Tensor, # [num_tokens, top_k]
*,
num_local_experts: int,
gate_first: bool = True,
interleaved: bool = False,
activation: str = "silu",
act_quant: tuple[torch.Tensor, torch.Tensor, int] | None = None,
) -> None:
"""Add pair-major LoRA deltas and activate either provider row layout."""
ActivationFn.parse(activation)
num_pairs = topk_ids.numel()
if num_pairs == 0:
return
gateup_rows = gateup_rows.view(-1, gateup_rows.shape[-1])
act_out_rows = act_out_rows.view(-1, act_out_rows.shape[-1])
inter = act_out_rows.shape[-1]
num_slices = gateup_rows.shape[-1] // inter
if act_quant is not None:
act_q, act_s, group = act_quant
assert inter % group == 0 and 512 % group == 0
else:
act_q, act_s, group = act_out_rows, act_out_rows, 0
_act_delta_kernel[(num_pairs,)](
gateup_rows,
gate_up_delta if gate_up_delta is not None else gateup_rows,
act_out_rows,
activation_lora_input,
act_q,
act_s,
pair_to_row,
topk_ids,
num_local_experts,
inter,
HAS_DELTA=gate_up_delta is not None,
NUM_SLICES=num_slices,
ACTIVATION_TYPE=activation,
GATE_FIRST=gate_first,
INTERLEAVED=interleaved,
QUANT_GROUP=group,
WHOLE_ROW=inter == group,
BLOCK_SIZE=512,
)
@@ -0,0 +1,99 @@
"""Align routed pairs for Triton and Marlin, dropping negative expert IDs.
Distinct top-k IDs allow a single-token fast path. pair_to_row maps pair p
to row p, or -1 for a pair without an expert.
"""
from __future__ import annotations
import torch
import triton
import triton.language as tl
@triton.jit
def _align_single_token_kernel(
topk_ids_ptr, # int32 [TOPK]
sorted_ids_ptr, # int32 [TOPK * BLOCK_SIZE]
expert_ids_ptr, # int32 [TOPK]
num_post_ptr, # int32 [1]
pair_to_row_ptr, # int32 [TOPK] out: pair p is row p, -1 without an expert
WRITE_PAIR_TO_ROW: tl.constexpr,
TOPK: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
LANES: tl.constexpr, # next pow2 >= TOPK
SLOTS: tl.constexpr, # next pow2 >= TOPK * BLOCK_SIZE
):
lane = tl.arange(0, LANES)
in_range = lane < TOPK
ids = tl.load(topk_ids_ptr + lane, mask=in_range, other=-1)
valid = ids >= 0
# Dropped lanes sort past every valid id; their ties break on lane.
key = tl.where(valid, ids, 2147483647)
before = (key[None, :] < key[:, None]) | (
(key[None, :] == key[:, None]) & (lane[None, :] < lane[:, None])
)
rank = tl.sum(before.to(tl.int32), axis=1)
n_valid = tl.sum(valid.to(tl.int32), axis=0)
# For one token, the lane is the flat pair index.
tl.store(expert_ids_ptr + rank, ids, mask=valid)
tl.store(sorted_ids_ptr + rank * BLOCK_SIZE, lane, mask=valid)
tl.store(
expert_ids_ptr + lane,
tl.full([LANES], -1, tl.int32),
mask=in_range & (lane >= n_valid),
)
# Padding uses numel (= TOPK), matching the general alignment path.
slot = tl.arange(0, SLOTS)
pad = (slot < TOPK * BLOCK_SIZE) & (
(slot % BLOCK_SIZE != 0) | (slot // BLOCK_SIZE >= n_valid)
)
tl.store(sorted_ids_ptr + slot, tl.full([SLOTS], TOPK, tl.int32), mask=pad)
tl.store(num_post_ptr, n_valid * BLOCK_SIZE)
if WRITE_PAIR_TO_ROW:
tl.store(pair_to_row_ptr + lane, tl.where(valid, lane, -1), mask=in_range)
def moe_align_single_token(
topk_ids: torch.Tensor, block_size: int, pair_to_row: torch.Tensor | None = None
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Align distinct top-k IDs for one token; accepts int32 [1, topk], topk <= 32."""
topk = topk_ids.shape[1]
device = topk_ids.device
sorted_ids = torch.empty((topk * block_size,), dtype=torch.int32, device=device)
expert_ids = torch.empty((topk,), dtype=torch.int32, device=device)
num_post = torch.empty((1,), dtype=torch.int32, device=device)
_align_single_token_kernel[(1,)](
topk_ids,
sorted_ids,
expert_ids,
num_post,
topk_ids if pair_to_row is None else pair_to_row,
WRITE_PAIR_TO_ROW=pair_to_row is not None,
TOPK=topk,
BLOCK_SIZE=block_size,
LANES=triton.next_power_of_2(topk),
SLOTS=triton.next_power_of_2(topk * block_size),
num_warps=1,
)
return sorted_ids, expert_ids, num_post
@triton.jit
def _pair_to_row_kernel(topk_ids_ptr, out_ptr, n, BLOCK: tl.constexpr):
offs = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK)
mask = offs < n
ids = tl.load(topk_ids_ptr + offs, mask=mask, other=-1)
tl.store(out_ptr + offs, tl.where(ids >= 0, offs, -1).to(tl.int32), mask=mask)
def pair_to_row_map(topk_ids: torch.Tensor, out: torch.Tensor) -> torch.Tensor:
"""Write out[p] = p for routed pairs, else -1; finalize gates on this map."""
flat = topk_ids.reshape(-1)
n = flat.numel()
block = 1024
_pair_to_row_kernel[(triton.cdiv(n, block),)](
flat, out, n, BLOCK=block, num_warps=4
)
return out
@@ -0,0 +1,4 @@
"""SM90/SM100 grouped GEMMs for BF16 and FP8, with masked or contiguous rows.
Mainloops derive from the CUTLASS dense persistent examples (NVIDIA BSD-3).
"""
@@ -0,0 +1,367 @@
# Copyright (c) 2025 - 2026 NVIDIA CORPORATION & AFFILIATES.
# SPDX-License-Identifier: BSD-3-Clause
"""Compile grouped GEMMs with dynamic row counts; providers cache the code."""
from typing import Any, Tuple
import cuda.bindings.driver as cuda
import cutlass
import cutlass.cute as cute
import cutlass.cute.testing as testing
import cutlass.utils as utils
import msgspec
import torch
from cutlass.cute.runtime import from_dlpack
from sglang.kernels.ops.lora.moe.cutedsl.kernel_sm100_bf16 import (
GroupedGemmKernelSm100Bf16,
)
@cute.jit
def _grouped_gemm_bf16_swap_ab(
gemm_op: cutlass.Constexpr,
a: cute.Tensor, # physical routed input (expert, m_max, k)
b: cute.Tensor, # physical weight (expert, n_out, k)
c: cute.Tensor, # physical output (expert, m_max, n_out)
group_m: cute.Tensor,
direct_schedule: cute.Tensor,
schedule_tiles: cute.Tensor,
max_active_clusters: cutlass.Constexpr,
stream: cuda.CUstream,
epilogue_op: cutlass.Constexpr = lambda x: x,
):
# W @ X.T puts tokens on N for 8-wide tiles; C uses the transposed layout.
weight_mke = cute.make_tensor(b.iterator, cute.select(b.layout, mode=[1, 2, 0]))
token_nke = cute.make_tensor(a.iterator, cute.select(a.layout, mode=[1, 2, 0]))
output_mne = cute.make_tensor(c.iterator, cute.select(c.layout, mode=[2, 1, 0]))
gemm_op(
weight_mke,
token_nke,
output_mne,
group_m,
direct_schedule,
schedule_tiles,
max_active_clusters,
stream,
epilogue_op,
)
def _bf16_kernel_class_for(device: torch.device):
major, _minor = torch.cuda.get_device_capability(device)
if major >= 10:
return GroupedGemmKernelSm100Bf16
if major == 9:
from sglang.kernels.ops.lora.moe.cutedsl.kernel_sm90_bf16 import (
GroupedGemmKernelSm90Bf16,
)
return GroupedGemmKernelSm90Bf16
raise NotImplementedError(
f"the BF16 grouped GEMM needs SM90+; device is sm{major}x"
)
@cute.jit
def _grouped_gemm_fp8_swap_ab(
gemm_op: cutlass.Constexpr,
a: cute.Tensor, # physical routed input (expert, m_max, k) e4m3
b: cute.Tensor, # physical weight (expert, n_out, k) e4m3
sf_tokens: cute.Tensor, # physical (expert, rows, k/128) fp32
sf_weights: cute.Tensor, # physical (expert, n/128, k/128) fp32
c: cute.Tensor, # physical output (expert, m_max, n_out) bf16
group_m: cute.Tensor,
direct_schedule: cute.Tensor,
schedule_tiles: cute.Tensor,
max_active_clusters: cutlass.Constexpr,
stream: cuda.CUstream,
epilogue_op: cutlass.Constexpr = lambda x: x,
):
# SFA follows weights (kernel A); SFB follows tokens (kernel B).
weight_mke = cute.make_tensor(b.iterator, cute.select(b.layout, mode=[1, 2, 0]))
token_nke = cute.make_tensor(a.iterator, cute.select(a.layout, mode=[1, 2, 0]))
output_mne = cute.make_tensor(c.iterator, cute.select(c.layout, mode=[2, 1, 0]))
sfa_weights = cute.make_tensor(
sf_weights.iterator, cute.select(sf_weights.layout, mode=[1, 2, 0])
)
sfb_tokens = cute.make_tensor(
sf_tokens.iterator, cute.select(sf_tokens.layout, mode=[1, 2, 0])
)
gemm_op(
weight_mke,
token_nke,
sfa_weights,
sfb_tokens,
output_mne,
group_m,
direct_schedule,
schedule_tiles,
max_active_clusters,
stream,
epilogue_op,
)
def _fp8_kernel_class_for(device: torch.device):
major, _minor = torch.cuda.get_device_capability(device)
if major >= 10:
from sglang.kernels.ops.lora.moe.cutedsl.kernel_sm100_fp8 import (
GroupedGemmKernelSm100Fp8,
)
return GroupedGemmKernelSm100Fp8
if major == 9:
from sglang.kernels.ops.lora.moe.cutedsl.kernel_sm90_fp8 import (
GroupedGemmKernelSm90Fp8,
)
return GroupedGemmKernelSm90Fp8
raise NotImplementedError(f"the FP8 grouped GEMM needs SM90+; device is sm{major}x")
class GroupedGemmConfig(msgspec.Struct, frozen=True, kw_only=True):
mma_tiler_mn: Tuple[int, int] = (64, 128)
cluster_shape_mn: Tuple[int, int] = (1, 1)
use_2cta_instrs: bool = False
occupancy: int = 1
mma_inst_tile_k: int = 4
persistent_clusters: int | None = None
class PreparedGroupedGemm(msgspec.Struct, kw_only=True):
"""Bound arguments retain the tensors backing their DLPack views."""
compiled_fn: Any
operand_args: tuple # the wrapper's tensor operands, in its order
group_m_arg: cute.Tensor
direct_schedule_arg: cute.Tensor
schedule_tiles_arg: cute.Tensor
direct_schedule_owner: torch.Tensor
schedule_tiles_owner: torch.Tensor
stream: cuda.CUstream
def launch(self) -> None:
self.compiled_fn(
*self.operand_args,
self.group_m_arg,
self.direct_schedule_arg,
self.schedule_tiles_arg,
self.stream,
)
def as_dynamic_cute_tensor(tensor: torch.Tensor, *, leading_dim: int) -> cute.Tensor:
"""Compile-time and runtime calls must use identical layout wrapping."""
return from_dlpack(tensor, assumed_align=16).mark_layout_dynamic(
leading_dim=leading_dim
)
def _compile_prepared(
*,
kernel_cls,
wrapper,
ab_dtype,
config: GroupedGemmConfig,
contiguous_segments: bool,
problem_shape: Tuple[int, int, int, int],
operand_args: tuple,
group_m_arg: cute.Tensor,
direct_schedule: torch.Tensor | None,
schedule_tiles: torch.Tensor | None,
device: torch.device,
) -> PreparedGroupedGemm:
if direct_schedule is None:
direct_schedule = torch.zeros((1,), device=device, dtype=torch.int64)
if schedule_tiles is None:
schedule_tiles = torch.zeros((1,), device=device, dtype=torch.int32)
direct_schedule_arg = as_dynamic_cute_tensor(direct_schedule, leading_dim=0)
schedule_tiles_arg = as_dynamic_cute_tensor(schedule_tiles, leading_dim=0)
kernel_kwargs = {}
if getattr(kernel_cls, "SUPPORTS_SINGLE_K_PIPELINE", False):
# Compile the rolling pipeline only for single-K tiles to save registers.
cta_tile_k = 32 * config.mma_inst_tile_k
kernel_kwargs["single_k_pipeline"] = problem_shape[2] <= cta_tile_k
gemm = kernel_cls(
acc_dtype=cutlass.Float32,
use_2cta_instrs=config.use_2cta_instrs,
mma_tiler_mn=config.mma_tiler_mn,
cluster_shape_mn=config.cluster_shape_mn,
mma_inst_tile_k=config.mma_inst_tile_k,
persistent_clusters=config.persistent_clusters,
swap_ab=True,
contiguous_segments=contiguous_segments,
**kernel_kwargs,
)
gemm.occupancy = config.occupancy
if not gemm.can_implement(
problem_shape, ab_dtype, ab_dtype, cutlass.BFloat16, "k", "k", "m"
):
raise testing.CantImplementError(
f"unsupported {getattr(ab_dtype, '__name__', ab_dtype)} "
f"config={config} for logical MNKL={problem_shape}"
)
max_active_clusters = utils.HardwareInfo().get_max_active_clusters(
config.cluster_shape_mn[0] * config.cluster_shape_mn[1]
)
stream = cuda.CUstream(torch.cuda.current_stream(device).cuda_stream)
compiled_fn = cute.compile(
wrapper,
gemm,
*operand_args,
group_m_arg,
direct_schedule_arg,
schedule_tiles_arg,
max_active_clusters,
stream,
lambda x: x,
)
return PreparedGroupedGemm(
compiled_fn=compiled_fn,
operand_args=operand_args,
group_m_arg=group_m_arg,
direct_schedule_arg=direct_schedule_arg,
schedule_tiles_arg=schedule_tiles_arg,
direct_schedule_owner=direct_schedule,
schedule_tiles_owner=schedule_tiles,
stream=stream,
)
def prepare_masked_bf16(
a: torch.Tensor,
b: torch.Tensor,
c: torch.Tensor,
masked_m: torch.Tensor,
*,
config: GroupedGemmConfig,
direct_schedule: torch.Tensor | None = None,
schedule_tiles: torch.Tensor | None = None,
) -> PreparedGroupedGemm:
experts, m_max, k = a.shape
n = b.shape[1]
return _compile_prepared(
kernel_cls=_bf16_kernel_class_for(a.device),
wrapper=_grouped_gemm_bf16_swap_ab,
ab_dtype=cutlass.BFloat16,
config=config,
contiguous_segments=False,
problem_shape=(n, m_max, k, experts),
operand_args=(
as_dynamic_cute_tensor(a, leading_dim=2),
as_dynamic_cute_tensor(b, leading_dim=2),
as_dynamic_cute_tensor(c, leading_dim=2),
),
group_m_arg=as_dynamic_cute_tensor(masked_m, leading_dim=0),
direct_schedule=direct_schedule,
schedule_tiles=schedule_tiles,
device=a.device,
)
def prepare_contiguous_bf16(
a: torch.Tensor,
b: torch.Tensor,
c: torch.Tensor,
seg_offsets: torch.Tensor,
*,
config: GroupedGemmConfig,
direct_schedule: torch.Tensor | None = None,
schedule_tiles: torch.Tensor | None = None,
) -> PreparedGroupedGemm:
"""Use seg_offsets in the group_m slot to address flat expert segments."""
m_ceil, k = a.shape
experts, n, _ = b.shape
return _compile_prepared(
kernel_cls=_bf16_kernel_class_for(a.device),
wrapper=_grouped_gemm_bf16_swap_ab,
ab_dtype=cutlass.BFloat16,
config=config,
contiguous_segments=True,
problem_shape=(n, m_ceil, k, experts),
operand_args=(
as_dynamic_cute_tensor(a.unsqueeze(0), leading_dim=2),
as_dynamic_cute_tensor(b, leading_dim=2),
as_dynamic_cute_tensor(c.unsqueeze(0), leading_dim=2),
),
group_m_arg=as_dynamic_cute_tensor(seg_offsets, leading_dim=0),
direct_schedule=direct_schedule,
schedule_tiles=schedule_tiles,
device=a.device,
)
def prepare_masked_fp8(
a: torch.Tensor,
b: torch.Tensor,
sf_tokens: torch.Tensor, # fp32 [E, m_max, K // 128]
sf_weights: torch.Tensor, # fp32 [E, N // 128, K // 128] (checkpoint form)
c: torch.Tensor,
masked_m: torch.Tensor,
*,
config: GroupedGemmConfig,
direct_schedule: torch.Tensor | None = None,
schedule_tiles: torch.Tensor | None = None,
) -> PreparedGroupedGemm:
assert sf_tokens.dtype == torch.float32 and sf_weights.dtype == torch.float32
experts, m_max, k = a.shape
n = b.shape[1]
return _compile_prepared(
kernel_cls=_fp8_kernel_class_for(a.device),
wrapper=_grouped_gemm_fp8_swap_ab,
ab_dtype=cutlass.Float8E4M3FN,
config=config,
contiguous_segments=False,
problem_shape=(n, m_max, k, experts),
operand_args=(
as_dynamic_cute_tensor(a, leading_dim=2),
as_dynamic_cute_tensor(b, leading_dim=2),
as_dynamic_cute_tensor(sf_tokens, leading_dim=2),
as_dynamic_cute_tensor(sf_weights, leading_dim=2),
as_dynamic_cute_tensor(c, leading_dim=2),
),
group_m_arg=as_dynamic_cute_tensor(masked_m, leading_dim=0),
direct_schedule=direct_schedule,
schedule_tiles=schedule_tiles,
device=a.device,
)
def prepare_contiguous_fp8(
a: torch.Tensor,
b: torch.Tensor,
sf_tokens: torch.Tensor, # fp32 [1, M, K // 128]
sf_weights: torch.Tensor, # fp32 [E, N // 128, K // 128] (checkpoint form)
c: torch.Tensor,
seg_offsets: torch.Tensor,
*,
config: GroupedGemmConfig,
direct_schedule: torch.Tensor | None = None,
schedule_tiles: torch.Tensor | None = None,
) -> PreparedGroupedGemm:
assert sf_tokens.dtype == torch.float32 and sf_weights.dtype == torch.float32
m_ceil, k = a.shape
experts, n, _ = b.shape
return _compile_prepared(
kernel_cls=_fp8_kernel_class_for(a.device),
wrapper=_grouped_gemm_fp8_swap_ab,
ab_dtype=cutlass.Float8E4M3FN,
config=config,
contiguous_segments=True,
problem_shape=(n, m_ceil, k, experts),
operand_args=(
as_dynamic_cute_tensor(a.unsqueeze(0), leading_dim=2),
as_dynamic_cute_tensor(b, leading_dim=2),
as_dynamic_cute_tensor(sf_tokens, leading_dim=2),
as_dynamic_cute_tensor(sf_weights, leading_dim=2),
as_dynamic_cute_tensor(c.unsqueeze(0), leading_dim=2),
),
group_m_arg=as_dynamic_cute_tensor(seg_offsets, leading_dim=0),
direct_schedule=direct_schedule,
schedule_tiles=schedule_tiles,
device=a.device,
)
@@ -0,0 +1,799 @@
# Copyright (c) 2025 - 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Persistent BF16 GEMM for masked slabs or aligned flat expert segments.
Physical tensors are A [E, M, K], B [E, N, K], and C [E, M, N]. Masked output
is defined only below group_m[e]; partial tiles may write padding, but none
starts beyond an expert's rows. For flat segments, group_m holds seg_offsets
and token tiles divide the segment alignment, keeping tails within their segment.
Mainloop and epilogue derive from CUTLASS v4.6.1
blackwell/kernel/dense_gemm/dense_gemm_persistent.py.
"""
from typing import Tuple, Type
import cuda.bindings.driver as cuda
import cutlass
import cutlass.cute as cute
import cutlass.cute.testing as testing
import cutlass.pipeline as pipeline
import cutlass.utils as utils
from cutlass.cute.nvgpu import cpasync, tcgen05
from cutlass.pipeline import pipeline_init_arrive, pipeline_init_wait
from sglang.kernels.ops.lora.moe.cutedsl.scheduler import (
MoESchedulerParams,
create_moe_tile_scheduler,
resolve_scheduler_params_and_grid,
)
class GroupedGemmKernelSm100Bf16:
def __init__(
self,
acc_dtype: Type[cutlass.Numeric],
use_2cta_instrs: bool,
mma_tiler_mn: Tuple[int, int],
cluster_shape_mn: Tuple[int, int],
mma_inst_tile_k: int = 4,
persistent_clusters: int | None = None,
swap_ab: bool = False,
contiguous_segments: bool = False,
):
self.acc_dtype: Type[cutlass.Numeric] = acc_dtype
self.use_2cta_instrs = use_2cta_instrs
self.cluster_shape_mn = cluster_shape_mn
# The K extent here is a placeholder. _setup_attributes computes it.
self.mma_tiler_mn = mma_tiler_mn
self.mma_tiler = (*mma_tiler_mn, 1)
self.mma_inst_tile_k = mma_inst_tile_k
self.persistent_clusters = persistent_clusters
self.swap_ab = swap_ab
self.contiguous_segments = contiguous_segments
if contiguous_segments and not swap_ab:
raise ValueError("contiguous_segments requires swap_ab")
if contiguous_segments and cluster_shape_mn != (1, 1):
raise ValueError("contiguous_segments requires a (1, 1) cluster")
self.arch = "sm_100"
self.cta_group = (
tcgen05.CtaGroup.TWO if use_2cta_instrs else tcgen05.CtaGroup.ONE
)
self.occupancy = 1
self.epilogue_warp_id = (0, 1, 2, 3)
self.mma_warp_id = 4
self.tma_warp_id = 5
self.threads_per_cta = 32 * len(
(self.mma_warp_id, self.tma_warp_id, *self.epilogue_warp_id)
)
self.epilog_sync_bar_id = 1
self.tmem_alloc_sync_bar_id = 2
def _create_tiled_mma(self):
return utils.sm100.make_trivial_tiled_mma(
self.a_dtype,
self.a_major_mode,
self.b_major_mode,
self.acc_dtype,
self.cta_group,
self.mma_tiler[:2],
)
def _setup_attributes(self):
tiled_mma = self._create_tiled_mma()
mma_inst_shape_k = cute.size(tiled_mma.shape_mnk, mode=[2])
self.mma_tiler = (
self.mma_tiler[0],
self.mma_tiler[1],
mma_inst_shape_k * self.mma_inst_tile_k,
)
self.cta_tile_shape_mnk = (
self.mma_tiler[0] // cute.size(tiled_mma.thr_id.shape),
self.mma_tiler[1],
self.mma_tiler[2],
)
self.cluster_layout_vmnk = cute.tiled_divide(
cute.make_layout((*self.cluster_shape_mn, 1)),
(tiled_mma.thr_id.shape,),
)
self.num_mcast_ctas_a = cute.size(self.cluster_layout_vmnk.shape[2])
self.num_mcast_ctas_b = cute.size(self.cluster_layout_vmnk.shape[1])
self.is_a_mcast = self.num_mcast_ctas_a > 1
self.is_b_mcast = self.num_mcast_ctas_b > 1
self.epi_tile = utils.sm100.compute_epilogue_tile_shape(
self.cta_tile_shape_mnk,
self.use_2cta_instrs,
self.c_layout,
self.c_dtype,
)
c_smem_layout = utils.sm100.make_smem_layout_epi(
self.c_dtype, self.c_layout, self.epi_tile, 1
)
self.smem_capacity = utils.get_smem_capacity_in_bytes()
self.num_acc_stage, self.num_ab_stage, self.num_c_stage = self._compute_stages(
tiled_mma,
self.mma_tiler,
self.a_dtype,
self.b_dtype,
self.c_dtype,
self.smem_capacity,
self.occupancy,
c_smem_layout,
)
self.a_smem_layout_staged = utils.sm100.make_smem_layout_a(
tiled_mma, self.mma_tiler, self.a_dtype, self.num_ab_stage
)
self.b_smem_layout_staged = utils.sm100.make_smem_layout_b(
tiled_mma, self.mma_tiler, self.b_dtype, self.num_ab_stage
)
self.c_smem_layout_staged = utils.sm100.make_smem_layout_epi(
self.c_dtype, self.c_layout, self.epi_tile, self.num_c_stage
)
acc_shape = tiled_mma.partition_shape_C(self.mma_tiler[:2])
tCtAcc_fake = tiled_mma.make_fragment_C(
cute.append(acc_shape, self.num_acc_stage)
)
self.num_tmem_alloc_cols = utils.get_num_tmem_alloc_cols(
tCtAcc_fake, arch=self.arch
)
@cute.jit
def __call__(
self,
a: cute.Tensor,
b: cute.Tensor,
c: cute.Tensor,
group_m: cute.Tensor,
direct_schedule: cute.Tensor,
schedule_tiles: cute.Tensor,
max_active_clusters: cutlass.Constexpr,
stream: cuda.CUstream,
epilogue_op: cutlass.Constexpr = lambda x: x,
):
self.a_dtype: Type[cutlass.Numeric] = a.element_type
self.b_dtype: Type[cutlass.Numeric] = b.element_type
self.c_dtype: Type[cutlass.Numeric] = c.element_type
self.a_major_mode = utils.LayoutEnum.from_tensor(a).mma_major_mode()
self.b_major_mode = utils.LayoutEnum.from_tensor(b).mma_major_mode()
self.c_layout = utils.LayoutEnum.from_tensor(c)
if cutlass.const_expr(self.a_dtype != self.b_dtype):
raise TypeError(f"Type must match: {self.a_dtype} != {self.b_dtype}")
tiled_mma = self._create_tiled_mma()
self._setup_attributes()
atom_thr_size = cute.size(tiled_mma.thr_id.shape)
a_op = utils.sm100.cluster_shape_to_tma_atom_A(
self.cluster_shape_mn, tiled_mma.thr_id
)
a_smem_layout = cute.slice_(self.a_smem_layout_staged, (None, None, None, 0))
tma_atom_a, tma_tensor_a = cute.nvgpu.make_tiled_tma_atom_A(
a_op,
a,
a_smem_layout,
self.mma_tiler,
tiled_mma,
self.cluster_layout_vmnk.shape,
internal_type=(
cutlass.TFloat32 if a.element_type is cutlass.Float32 else None
),
)
b_op = utils.sm100.cluster_shape_to_tma_atom_B(
self.cluster_shape_mn, tiled_mma.thr_id
)
b_smem_layout = cute.slice_(self.b_smem_layout_staged, (None, None, None, 0))
tma_atom_b, tma_tensor_b = cute.nvgpu.make_tiled_tma_atom_B(
b_op,
b,
b_smem_layout,
self.mma_tiler,
tiled_mma,
self.cluster_layout_vmnk.shape,
internal_type=(
cutlass.TFloat32 if b.element_type is cutlass.Float32 else None
),
)
a_copy_size = cute.size_in_bytes(self.a_dtype, a_smem_layout)
b_copy_size = cute.size_in_bytes(self.b_dtype, b_smem_layout)
self.num_tma_load_bytes = (a_copy_size + b_copy_size) * atom_thr_size
epi_smem_layout = cute.select(self.c_smem_layout_staged, mode=[0, 1])
tma_atom_c, tma_tensor_c = cpasync.make_tiled_tma_atom(
cpasync.CopyBulkTensorTileS2GOp(), c, epi_smem_layout, self.epi_tile
)
self.tile_sched_params, grid = resolve_scheduler_params_and_grid(
a=a,
cta_tile_k=self.cta_tile_shape_mnk[2],
cluster_shape_mn=self.cluster_shape_mn,
swap_ab=self.swap_ab,
persistent_clusters=self.persistent_clusters,
max_active_clusters=max_active_clusters,
)
self.kernel(
tiled_mma,
tma_atom_a,
tma_tensor_a,
tma_atom_b,
tma_tensor_b,
tma_atom_c,
tma_tensor_c,
group_m,
direct_schedule,
schedule_tiles,
self.cluster_layout_vmnk,
self.a_smem_layout_staged,
self.b_smem_layout_staged,
self.c_smem_layout_staged,
self.epi_tile,
self.tile_sched_params,
epilogue_op,
).launch(
grid=grid,
block=[self.threads_per_cta, 1, 1],
cluster=(*self.cluster_shape_mn, 1),
stream=stream,
)
return
@cute.kernel
def kernel(
self,
tiled_mma: cute.TiledMma,
tma_atom_a: cute.CopyAtom,
mA_mkl: cute.Tensor,
tma_atom_b: cute.CopyAtom,
mB_nkl: cute.Tensor,
tma_atom_c: cute.CopyAtom,
mC_mnl: cute.Tensor,
group_m: cute.Tensor,
direct_schedule: cute.Tensor,
schedule_tiles: cute.Tensor,
cluster_layout_vmnk: cute.Layout,
a_smem_layout_staged: cute.ComposedLayout,
b_smem_layout_staged: cute.ComposedLayout,
c_smem_layout_staged: cute.ComposedLayout,
epi_tile: cute.Tile,
tile_sched_params: MoESchedulerParams,
epilogue_op: cutlass.Constexpr,
):
warp_idx = cute.arch.warp_idx()
warp_idx = cute.arch.make_warp_uniform(warp_idx)
if warp_idx == self.tma_warp_id:
cpasync.prefetch_descriptor(tma_atom_a)
cpasync.prefetch_descriptor(tma_atom_b)
cpasync.prefetch_descriptor(tma_atom_c)
use_2cta_instrs = cute.size(tiled_mma.thr_id.shape) == 2
bidx, bidy, bidz = cute.arch.block_idx()
mma_tile_coord_v = bidx % cute.size(tiled_mma.thr_id.shape)
is_leader_cta = mma_tile_coord_v == 0
cta_rank_in_cluster = cute.arch.make_warp_uniform(
cute.arch.block_idx_in_cluster()
)
block_in_cluster_coord_vmnk = cluster_layout_vmnk.get_flat_coord(
cta_rank_in_cluster
)
tidx, _, _ = cute.arch.thread_idx()
@cute.struct
class SharedStorage:
ab_full_mbar_ptr: cute.struct.MemRange[cutlass.Int64, self.num_ab_stage * 2]
acc_full_mbar_ptr: cute.struct.MemRange[
cutlass.Int64, self.num_acc_stage * 2
]
tmem_dealloc_mbar: cutlass.Int64
tmem_holding_buf: cutlass.Int32
smem = utils.SmemAllocator()
storage = smem.allocate(SharedStorage)
ab_pipeline_producer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread)
num_tma_producer = self.num_mcast_ctas_a + self.num_mcast_ctas_b - 1
ab_pipeline_consumer_group = pipeline.CooperativeGroup(
pipeline.Agent.Thread, num_tma_producer
)
ab_producer, ab_consumer = pipeline.PipelineTmaUmma.create(
barrier_storage=storage.ab_full_mbar_ptr.data_ptr(),
num_stages=self.num_ab_stage,
producer_group=ab_pipeline_producer_group,
consumer_group=ab_pipeline_consumer_group,
tx_count=self.num_tma_load_bytes,
cta_layout_vmnk=cluster_layout_vmnk,
defer_sync=True,
).make_participants()
acc_pipeline_producer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread)
num_acc_consumer_threads = len(self.epilogue_warp_id) * (
2 if use_2cta_instrs else 1
)
acc_pipeline_consumer_group = pipeline.CooperativeGroup(
pipeline.Agent.Thread, num_acc_consumer_threads
)
acc_pipeline = pipeline.PipelineUmmaAsync.create(
barrier_storage=storage.acc_full_mbar_ptr.data_ptr(),
num_stages=self.num_acc_stage,
producer_group=acc_pipeline_producer_group,
consumer_group=acc_pipeline_consumer_group,
cta_layout_vmnk=cluster_layout_vmnk,
defer_sync=True,
)
tmem_alloc_barrier = pipeline.NamedBarrier(
barrier_id=self.tmem_alloc_sync_bar_id,
num_threads=32 * len((self.mma_warp_id, *self.epilogue_warp_id)),
)
tmem = utils.TmemAllocator(
storage.tmem_holding_buf.ptr,
barrier_for_retrieve=tmem_alloc_barrier,
allocator_warp_id=self.epilogue_warp_id[0],
is_two_cta=use_2cta_instrs,
two_cta_tmem_dealloc_mbar_ptr=storage.tmem_dealloc_mbar.ptr,
)
pipeline_init_arrive(cluster_shape_mn=cluster_layout_vmnk, is_relaxed=True)
# (MMA, MMA_M, MMA_K, STAGE)
sA = smem.allocate_tensor(
element_type=self.a_dtype,
layout=a_smem_layout_staged.outer,
byte_alignment=128,
swizzle=a_smem_layout_staged.inner,
)
# (MMA, MMA_N, MMA_K, STAGE)
sB = smem.allocate_tensor(
element_type=self.b_dtype,
layout=b_smem_layout_staged.outer,
byte_alignment=128,
swizzle=b_smem_layout_staged.inner,
)
a_full_mcast_mask = None
b_full_mcast_mask = None
if cutlass.const_expr(self.is_a_mcast or self.is_b_mcast or use_2cta_instrs):
a_full_mcast_mask = cpasync.create_tma_multicast_mask(
cluster_layout_vmnk, block_in_cluster_coord_vmnk, mcast_mode=2
)
b_full_mcast_mask = cpasync.create_tma_multicast_mask(
cluster_layout_vmnk, block_in_cluster_coord_vmnk, mcast_mode=1
)
# (bM, bK, RestM, RestK, RestL)
gA_mkl = cute.local_tile(
mA_mkl, cute.slice_(self.mma_tiler, (None, 0, None)), (None, None, None)
)
# (bN, bK, RestN, RestK, RestL)
gB_nkl = cute.local_tile(
mB_nkl, cute.slice_(self.mma_tiler, (0, None, None)), (None, None, None)
)
# (bM, bN, RestM, RestN, RestL)
gC_mnl = cute.local_tile(
mC_mnl, cute.slice_(self.mma_tiler, (None, None, 0)), (None, None, None)
)
thr_mma = tiled_mma.get_slice(mma_tile_coord_v)
# (MMA, MMA_M, MMA_K, RestM, RestK, RestL)
tCgA = thr_mma.partition_A(gA_mkl)
# (MMA, MMA_N, MMA_K, RestN, RestK, RestL)
tCgB = thr_mma.partition_B(gB_nkl)
# (MMA, MMA_M, MMA_N, RestM, RestN, RestL)
tCgC = thr_mma.partition_C(gC_mnl)
a_cta_layout = cute.make_layout(
cute.slice_(cluster_layout_vmnk, (0, 0, None, 0)).shape
)
# ((atom_v, rest_v), STAGE)
# ((atom_v, rest_v), RestM, RestK, RestL)
tAsA, tAgA = cpasync.tma_partition(
tma_atom_a,
block_in_cluster_coord_vmnk[2],
a_cta_layout,
cute.group_modes(sA, 0, 3),
cute.group_modes(tCgA, 0, 3),
)
b_cta_layout = cute.make_layout(
cute.slice_(cluster_layout_vmnk, (0, None, 0, 0)).shape
)
# ((atom_v, rest_v), STAGE)
# ((atom_v, rest_v), RestM, RestK, RestL)
tBsB, tBgB = cpasync.tma_partition(
tma_atom_b,
block_in_cluster_coord_vmnk[1],
b_cta_layout,
cute.group_modes(sB, 0, 3),
cute.group_modes(tCgB, 0, 3),
)
# (MMA, MMA_M, MMA_K, STAGE)
tCrA = tiled_mma.make_fragment_A(sA)
# (MMA, MMA_N, MMA_K, STAGE)
tCrB = tiled_mma.make_fragment_B(sB)
# (MMA, MMA_M, MMA_N)
acc_shape = tiled_mma.partition_shape_C(self.mma_tiler[:2])
# (MMA, MMA_M, MMA_N, STAGE)
tCtAcc_fake = tiled_mma.make_fragment_C(
cute.append(acc_shape, self.num_acc_stage)
)
pipeline_init_wait(cluster_shape_mn=cluster_layout_vmnk)
tile_sched = create_moe_tile_scheduler(
tile_sched_params=tile_sched_params,
direct_schedule=direct_schedule,
schedule_tiles=schedule_tiles,
swap_ab=self.swap_ab,
)
work_tile = tile_sched.initial_work_tile_info()
if warp_idx == self.tma_warp_id:
while work_tile.is_valid_tile:
mma_tile_coord_mnl = (
work_tile.tile_m_idx // cute.size(tiled_mma.thr_id.shape),
work_tile.tile_n_idx,
work_tile.expert_idx,
)
if cutlass.const_expr(self.swap_ab):
mma_tile_coord_mnl = (
work_tile.tile_n_idx // cute.size(tiled_mma.thr_id.shape),
work_tile.tile_m_idx,
work_tile.expert_idx,
)
a_rest_l_coord = mma_tile_coord_mnl[2]
if cutlass.const_expr(self.contiguous_segments):
# Flat rows use slot 0 plus seg_offsets; weights keep the expert.
seg_base_tile = (
group_m[work_tile.expert_idx] // self.cta_tile_shape_mnk[1]
)
mma_tile_coord_mnl = (
mma_tile_coord_mnl[0],
seg_base_tile + mma_tile_coord_mnl[1],
cutlass.Int32(0),
)
a_rest_l_coord = work_tile.expert_idx
# ((atom_v, rest_v), RestK)
tAgA_slice = tAgA[(None, mma_tile_coord_mnl[0], None, a_rest_l_coord)]
# ((atom_v, rest_v), RestK)
tBgB_slice = tBgB[
(None, mma_tile_coord_mnl[1], None, mma_tile_coord_mnl[2])
]
ab_producer.reset()
peek_ab_empty_status = ab_producer.try_acquire()
for k_tile in cutlass.range(0, work_tile.k_tile_cnt, 1, unroll=1):
handle = ab_producer.acquire_and_advance(peek_ab_empty_status)
cute.copy(
tma_atom_a,
tAgA_slice[(None, handle.count)],
tAsA[(None, handle.index)],
tma_bar_ptr=handle.barrier,
mcast_mask=a_full_mcast_mask,
)
cute.copy(
tma_atom_b,
tBgB_slice[(None, handle.count)],
tBsB[(None, handle.index)],
tma_bar_ptr=handle.barrier,
mcast_mask=b_full_mcast_mask,
)
peek_ab_empty_status = cutlass.Boolean(1)
if handle.count + 1 < work_tile.k_tile_cnt:
peek_ab_empty_status = ab_producer.try_acquire()
work_tile = tile_sched.advance_to_next_work()
ab_producer.tail()
if warp_idx == self.mma_warp_id:
tmem.wait_for_alloc()
tmem_ptr = tmem.retrieve_ptr(self.acc_dtype)
# (MMA, MMA_M, MMA_N, STAGE)
tCtAcc_base = cute.make_tensor(tmem_ptr, tCtAcc_fake.layout)
acc_producer_state = pipeline.make_pipeline_state(
pipeline.PipelineUserType.Producer, self.num_acc_stage
)
while work_tile.is_valid_tile:
# (MMA, MMA_M, MMA_N)
tCtAcc = tCtAcc_base[(None, None, None, acc_producer_state.index)]
ab_consumer.reset()
peek_ab_full_status = cutlass.Boolean(1)
if is_leader_cta:
peek_ab_full_status = ab_consumer.try_wait()
if is_leader_cta:
acc_pipeline.producer_acquire(acc_producer_state)
tiled_mma.set(tcgen05.Field.ACCUMULATE, False)
for k_tile in range(work_tile.k_tile_cnt):
if is_leader_cta:
handle = ab_consumer.wait_and_advance(peek_ab_full_status)
num_kblocks = cute.size(tCrA, mode=[2])
for kblk_idx in cutlass.range(num_kblocks, unroll_full=True):
kblk_crd = (None, None, kblk_idx, handle.index)
cute.gemm(
tiled_mma,
tCtAcc,
tCrA[kblk_crd],
tCrB[kblk_crd],
tCtAcc,
)
tiled_mma.set(tcgen05.Field.ACCUMULATE, True)
handle.release()
peek_ab_full_status = cutlass.Boolean(1)
if handle.count + 1 < work_tile.k_tile_cnt:
peek_ab_full_status = ab_consumer.try_wait()
if is_leader_cta:
acc_pipeline.producer_commit(acc_producer_state)
acc_producer_state.advance()
work_tile = tile_sched.advance_to_next_work()
acc_pipeline.producer_tail(acc_producer_state)
# (EPI_TILE_M, EPI_TILE_N, STAGE)
sC = smem.allocate_tensor(
element_type=self.c_dtype,
layout=c_smem_layout_staged.outer,
byte_alignment=128,
swizzle=c_smem_layout_staged.inner,
)
if warp_idx < self.mma_warp_id:
tmem.allocate(self.num_tmem_alloc_cols)
tmem.wait_for_alloc()
tmem_ptr = tmem.retrieve_ptr(self.acc_dtype)
# (MMA, MMA_M, MMA_N, STAGE)
tCtAcc_base = cute.make_tensor(tmem_ptr, tCtAcc_fake.layout)
acc_consumer_state = pipeline.make_pipeline_state(
pipeline.PipelineUserType.Consumer, self.num_acc_stage
)
c_producer_group = pipeline.CooperativeGroup(
pipeline.Agent.Thread,
32 * len(self.epilogue_warp_id),
)
c_pipeline = pipeline.PipelineTmaStore.create(
num_stages=self.num_c_stage, producer_group=c_producer_group
)
while work_tile.is_valid_tile:
mma_tile_coord_mnl = (
work_tile.tile_m_idx // cute.size(tiled_mma.thr_id.shape),
work_tile.tile_n_idx,
work_tile.expert_idx,
)
if cutlass.const_expr(self.swap_ab):
mma_tile_coord_mnl = (
work_tile.tile_n_idx // cute.size(tiled_mma.thr_id.shape),
work_tile.tile_m_idx,
work_tile.expert_idx,
)
if cutlass.const_expr(self.contiguous_segments):
# Same segment base as the TMA warp.
seg_base_tile = (
group_m[work_tile.expert_idx] // self.cta_tile_shape_mnk[1]
)
mma_tile_coord_mnl = (
mma_tile_coord_mnl[0],
seg_base_tile + mma_tile_coord_mnl[1],
cutlass.Int32(0),
)
work_tile = tile_sched.advance_to_next_work()
# Valid tiles only: pipeline count also counts executed tiles.
num_tiles_executed = acc_consumer_state.count
acc_consumer_state = utils.gemm.sm100.epilogue_tma_store(
self,
tidx,
warp_idx,
tma_atom_c,
tCtAcc_base,
sC,
tCgC,
epi_tile,
num_tiles_executed,
epilogue_op,
mma_tile_coord_mnl,
acc_consumer_state,
acc_pipeline,
c_pipeline,
)
c_pipeline.producer_tail()
tmem.relinquish_alloc_permit()
tmem.free(tmem_ptr)
@staticmethod
def _compute_stages(
tiled_mma: cute.TiledMma,
mma_tiler_mnk: Tuple[int, int, int],
a_dtype: Type[cutlass.Numeric],
b_dtype: Type[cutlass.Numeric],
c_dtype: Type[cutlass.Numeric],
smem_capacity: int,
occupancy: int,
c_smem_layout: cute.Layout,
) -> Tuple[int, int, int]:
num_acc_stage = 2
num_c_stage = 2
a_smem_layout_stage_one = utils.sm100.make_smem_layout_a(
tiled_mma, mma_tiler_mnk, a_dtype, 1
)
b_smem_layout_staged_one = utils.sm100.make_smem_layout_b(
tiled_mma, mma_tiler_mnk, b_dtype, 1
)
ab_bytes_per_stage = cute.size_in_bytes(
a_dtype, a_smem_layout_stage_one
) + cute.size_in_bytes(b_dtype, b_smem_layout_staged_one)
mbar_helpers_bytes = 1024
c_bytes_per_stage = cute.size_in_bytes(c_dtype, c_smem_layout)
c_bytes = c_bytes_per_stage * num_c_stage
num_ab_stage = (
smem_capacity // occupancy - (mbar_helpers_bytes + c_bytes)
) // ab_bytes_per_stage
num_c_stage += (
smem_capacity
- occupancy * ab_bytes_per_stage * num_ab_stage
- occupancy * (mbar_helpers_bytes + c_bytes)
) // (occupancy * c_bytes_per_stage)
return num_acc_stage, num_ab_stage, num_c_stage
def check_supported_dtypes(
self,
a_dtype: Type[cutlass.Numeric],
b_dtype: Type[cutlass.Numeric],
c_dtype: Type[cutlass.Numeric],
):
if a_dtype is not cutlass.BFloat16 or b_dtype is not cutlass.BFloat16:
raise testing.CantImplementError(
f"the BF16 grouped GEMM takes BF16 A/B; got {a_dtype}, {b_dtype}"
)
if c_dtype is not cutlass.BFloat16:
raise testing.CantImplementError(f"C must be BF16; got {c_dtype}")
if self.acc_dtype is not cutlass.Float32:
raise testing.CantImplementError(
f"the accumulator must be FP32; got {self.acc_dtype}"
)
def check_mma_tiler_and_cluster_shape(self):
if not (
(not self.use_2cta_instrs and self.mma_tiler_mn[0] in [64, 128])
or (self.use_2cta_instrs and self.mma_tiler_mn[0] in [128, 256])
):
raise testing.CantImplementError(
f"Invalid mma tiler & use_2cta_instrs: {self.mma_tiler_mn}, {self.use_2cta_instrs}"
)
valid_n_tiles = range(8, 257, 8) if self.swap_ab else range(32, 257, 32)
if self.mma_tiler_mn[1] not in valid_n_tiles:
raise testing.CantImplementError(
f"Invalid mma tiler N: {self.mma_tiler_mn[1]}"
)
if self.cluster_shape_mn[0] % (2 if self.use_2cta_instrs else 1) != 0:
raise testing.CantImplementError(
f"Invalid cluster shape M: {self.cluster_shape_mn[0]}"
)
is_power_of_2 = lambda x: x > 0 and (x & (x - 1)) == 0
if (
self.cluster_shape_mn[0] * self.cluster_shape_mn[1] > 16
or self.cluster_shape_mn[0] <= 0
or self.cluster_shape_mn[1] <= 0
or not is_power_of_2(self.cluster_shape_mn[0])
or not is_power_of_2(self.cluster_shape_mn[1])
):
raise testing.CantImplementError(
f"Invalid cluster shape: {self.cluster_shape_mn}"
)
def check_tensor_alignment(
self,
m: int,
n: int,
k: int,
l: int,
a_dtype: Type[cutlass.Numeric],
b_dtype: Type[cutlass.Numeric],
c_dtype: Type[cutlass.Numeric],
a_major: str,
b_major: str,
c_major: str,
):
def check_contiguous_16B_alignment(dtype, is_mode0_major, tensor_shape):
major_mode_idx = 0 if is_mode0_major else 1
num_major_elements = tensor_shape[major_mode_idx]
num_contiguous_elements = 16 * 8 // dtype.width
return num_major_elements % num_contiguous_elements == 0
if (
not check_contiguous_16B_alignment(a_dtype, a_major == "m", (m, k, l))
or not check_contiguous_16B_alignment(b_dtype, b_major == "n", (n, k, l))
or not check_contiguous_16B_alignment(c_dtype, c_major == "m", (m, n, l))
):
raise testing.CantImplementError(
f"Invalid tensor alignment: {m}, {n}, {k}, {l}, {a_dtype}, {b_dtype}, {c_dtype}, {a_major}, {b_major}, {c_major}"
)
def can_implement(
self,
mnkl: Tuple[int, int, int, int],
a_dtype: Type[cutlass.Numeric],
b_dtype: Type[cutlass.Numeric],
c_dtype: Type[cutlass.Numeric],
a_major: str,
b_major: str,
c_major: str,
) -> bool:
try:
self.check_supported_dtypes(a_dtype, b_dtype, c_dtype)
self.check_mma_tiler_and_cluster_shape()
m, n, k, l = mnkl
self.check_tensor_alignment(
m, n, k, l, a_dtype, b_dtype, c_dtype, a_major, b_major, c_major
)
except testing.CantImplementError:
return False
return True
@@ -0,0 +1,574 @@
# SPDX-License-Identifier: BSD-3-Clause
"""SM100 FP8 GEMM derived from kernel_sm100_bf16.py.
Each 128-element K partial is drained from tensor memory, scaled in FP32,
and accumulated in registers. Software scaling preserves checkpoint values
and permits 8-wide token tiles.
Scale layouts after swap_ab: weights [N/128, K/128, E], tokens [M, K/128, E|1].
"""
from typing import Type
import cuda.bindings.driver as cuda
import cutlass
import cutlass.cute as cute
import cutlass.cute.testing as testing
import cutlass.pipeline as pipeline
import cutlass.utils as utils
from cutlass.cute.nvgpu import cpasync, tcgen05
from cutlass.pipeline import pipeline_init_arrive, pipeline_init_wait
from sglang.kernels.ops.lora.moe.cutedsl.kernel_sm100_bf16 import (
GroupedGemmKernelSm100Bf16,
)
from sglang.kernels.ops.lora.moe.cutedsl.scheduler import (
create_moe_tile_scheduler,
resolve_scheduler_params_and_grid,
)
class GroupedGemmKernelSm100Fp8(GroupedGemmKernelSm100Bf16):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if not self.swap_ab:
raise ValueError("the software-scaled FP8 kernel ships swap_ab only")
if self.use_2cta_instrs or self.cluster_shape_mn != (1, 1):
raise ValueError(
"the software-scaled FP8 kernel ships (1, 1) single-CTA only"
)
if self.mma_tiler_mn[0] != 128 or self.mma_tiler_mn[1] > 128:
raise ValueError(
"the software-scaled FP8 kernel indexes weight scales per 128-wide "
"output tile and stages one column scale per epilogue thread, so "
f"mma_tiler_mn must be (128, <=128); got {self.mma_tiler_mn}"
)
def check_supported_dtypes(
self,
a_dtype: Type[cutlass.Numeric],
b_dtype: Type[cutlass.Numeric],
c_dtype: Type[cutlass.Numeric],
):
if a_dtype is not cutlass.Float8E4M3FN or b_dtype is not cutlass.Float8E4M3FN:
raise testing.CantImplementError(
f"the software-scaled GEMM takes e4m3 A/B; got {a_dtype}, {b_dtype}"
)
if c_dtype is not cutlass.BFloat16:
raise testing.CantImplementError(f"C must be BF16; got {c_dtype}")
if self.acc_dtype is not cutlass.Float32:
raise testing.CantImplementError(
f"the accumulator must be FP32; got {self.acc_dtype}"
)
@cute.jit
def __call__(
self,
a: cute.Tensor,
b: cute.Tensor,
sf_a: cute.Tensor, # weight scales [NT, KT, E] fp32
sf_b: cute.Tensor, # token scales [M, KT, E|1] fp32
c: cute.Tensor,
group_m: cute.Tensor,
direct_schedule: cute.Tensor,
schedule_tiles: cute.Tensor,
max_active_clusters: cutlass.Constexpr,
stream: cuda.CUstream,
epilogue_op: cutlass.Constexpr = lambda x: x,
):
self.a_dtype: Type[cutlass.Numeric] = a.element_type
self.b_dtype: Type[cutlass.Numeric] = b.element_type
self.c_dtype: Type[cutlass.Numeric] = c.element_type
self.a_major_mode = utils.LayoutEnum.from_tensor(a).mma_major_mode()
self.b_major_mode = utils.LayoutEnum.from_tensor(b).mma_major_mode()
self.c_layout = utils.LayoutEnum.from_tensor(c)
tiled_mma = self._create_tiled_mma()
self._setup_attributes()
# One k_tile must cover exactly one 128-element scale group.
if cutlass.const_expr(self.mma_tiler[2] != 128):
raise ValueError(
f"k_tile must equal the 128-element scale group; got "
f"{self.mma_tiler[2]} (mma_inst_tile_k={self.mma_inst_tile_k})"
)
a_op = utils.sm100.cluster_shape_to_tma_atom_A(
self.cluster_shape_mn, tiled_mma.thr_id
)
a_smem_layout = cute.slice_(self.a_smem_layout_staged, (None, None, None, 0))
tma_atom_a, tma_tensor_a = cute.nvgpu.make_tiled_tma_atom_A(
a_op,
a,
a_smem_layout,
self.mma_tiler,
tiled_mma,
self.cluster_layout_vmnk.shape,
)
b_op = utils.sm100.cluster_shape_to_tma_atom_B(
self.cluster_shape_mn, tiled_mma.thr_id
)
b_smem_layout = cute.slice_(self.b_smem_layout_staged, (None, None, None, 0))
tma_atom_b, tma_tensor_b = cute.nvgpu.make_tiled_tma_atom_B(
b_op,
b,
b_smem_layout,
self.mma_tiler,
tiled_mma,
self.cluster_layout_vmnk.shape,
)
a_copy_size = cute.size_in_bytes(self.a_dtype, a_smem_layout)
b_copy_size = cute.size_in_bytes(self.b_dtype, b_smem_layout)
self.num_tma_load_bytes = a_copy_size + b_copy_size
epi_smem_layout = cute.select(self.c_smem_layout_staged, mode=[0, 1])
tma_atom_c, tma_tensor_c = cpasync.make_tiled_tma_atom(
cpasync.CopyBulkTensorTileS2GOp(), c, epi_smem_layout, self.epi_tile
)
self.tile_sched_params, grid = resolve_scheduler_params_and_grid(
a=a,
cta_tile_k=self.cta_tile_shape_mnk[2],
cluster_shape_mn=self.cluster_shape_mn,
swap_ab=self.swap_ab,
persistent_clusters=self.persistent_clusters,
max_active_clusters=max_active_clusters,
)
self.kernel(
tiled_mma,
tma_atom_a,
tma_tensor_a,
tma_atom_b,
tma_tensor_b,
tma_atom_c,
tma_tensor_c,
sf_a,
sf_b,
group_m,
direct_schedule,
schedule_tiles,
self.cluster_layout_vmnk,
self.a_smem_layout_staged,
self.b_smem_layout_staged,
self.c_smem_layout_staged,
self.epi_tile,
self.tile_sched_params,
epilogue_op,
).launch(
grid=grid,
block=[self.threads_per_cta, 1, 1],
cluster=(*self.cluster_shape_mn, 1),
stream=stream,
)
return
@cute.kernel
def kernel(
self,
tiled_mma: cute.TiledMma,
tma_atom_a: cute.CopyAtom,
mA_mkl: cute.Tensor,
tma_atom_b: cute.CopyAtom,
mB_nkl: cute.Tensor,
tma_atom_c: cute.CopyAtom,
mC_mnl: cute.Tensor,
sf_a: cute.Tensor,
sf_b: cute.Tensor,
group_m: cute.Tensor,
direct_schedule: cute.Tensor,
schedule_tiles: cute.Tensor,
cluster_layout_vmnk: cute.Layout,
a_smem_layout_staged: cute.ComposedLayout,
b_smem_layout_staged: cute.ComposedLayout,
c_smem_layout_staged: cute.ComposedLayout,
epi_tile: cute.Tile,
tile_sched_params,
epilogue_op: cutlass.Constexpr,
):
warp_idx = cute.arch.warp_idx()
warp_idx = cute.arch.make_warp_uniform(warp_idx)
if warp_idx == self.tma_warp_id:
cpasync.prefetch_descriptor(tma_atom_a)
cpasync.prefetch_descriptor(tma_atom_b)
cpasync.prefetch_descriptor(tma_atom_c)
tidx, _, _ = cute.arch.thread_idx()
cta_n = self.cta_tile_shape_mnk[1]
@cute.struct
class SharedStorage:
ab_full_mbar_ptr: cute.struct.MemRange[cutlass.Int64, self.num_ab_stage * 2]
acc_full_mbar_ptr: cute.struct.MemRange[
cutlass.Int64, self.num_acc_stage * 2
]
col_scale: cute.struct.MemRange[cutlass.Float32, self.cta_tile_shape_mnk[1]]
tmem_dealloc_mbar: cutlass.Int64
tmem_holding_buf: cutlass.Int32
smem = utils.SmemAllocator()
storage = smem.allocate(SharedStorage)
ab_pipeline_producer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread)
ab_pipeline_consumer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread, 1)
ab_producer, ab_consumer = pipeline.PipelineTmaUmma.create(
barrier_storage=storage.ab_full_mbar_ptr.data_ptr(),
num_stages=self.num_ab_stage,
producer_group=ab_pipeline_producer_group,
consumer_group=ab_pipeline_consumer_group,
tx_count=self.num_tma_load_bytes,
cta_layout_vmnk=cluster_layout_vmnk,
defer_sync=True,
).make_participants()
acc_pipeline_producer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread)
acc_pipeline_consumer_group = pipeline.CooperativeGroup(
pipeline.Agent.Thread, len(self.epilogue_warp_id)
)
acc_pipeline = pipeline.PipelineUmmaAsync.create(
barrier_storage=storage.acc_full_mbar_ptr.data_ptr(),
num_stages=self.num_acc_stage,
producer_group=acc_pipeline_producer_group,
consumer_group=acc_pipeline_consumer_group,
cta_layout_vmnk=cluster_layout_vmnk,
defer_sync=True,
)
tmem_alloc_barrier = pipeline.NamedBarrier(
barrier_id=self.tmem_alloc_sync_bar_id,
num_threads=32 * len((self.mma_warp_id, *self.epilogue_warp_id)),
)
tmem = utils.TmemAllocator(
storage.tmem_holding_buf.ptr,
barrier_for_retrieve=tmem_alloc_barrier,
allocator_warp_id=self.epilogue_warp_id[0],
is_two_cta=False,
two_cta_tmem_dealloc_mbar_ptr=storage.tmem_dealloc_mbar.ptr,
)
pipeline_init_arrive(cluster_shape_mn=cluster_layout_vmnk, is_relaxed=True)
sA = smem.allocate_tensor(
element_type=self.a_dtype,
layout=a_smem_layout_staged.outer,
byte_alignment=128,
swizzle=a_smem_layout_staged.inner,
)
sB = smem.allocate_tensor(
element_type=self.b_dtype,
layout=b_smem_layout_staged.outer,
byte_alignment=128,
swizzle=b_smem_layout_staged.inner,
)
sColScale = cute.make_tensor(
storage.col_scale.data_ptr(), cute.make_layout(cta_n)
)
gA_mkl = cute.local_tile(
mA_mkl, cute.slice_(self.mma_tiler, (None, 0, None)), (None, None, None)
)
gB_nkl = cute.local_tile(
mB_nkl, cute.slice_(self.mma_tiler, (0, None, None)), (None, None, None)
)
gC_mnl = cute.local_tile(
mC_mnl, cute.slice_(self.mma_tiler, (None, None, 0)), (None, None, None)
)
thr_mma = tiled_mma.get_slice(0)
tCgA = thr_mma.partition_A(gA_mkl)
tCgB = thr_mma.partition_B(gB_nkl)
tCgC = thr_mma.partition_C(gC_mnl)
a_cta_layout = cute.make_layout(
cute.slice_(cluster_layout_vmnk, (0, 0, None, 0)).shape
)
tAsA, tAgA = cpasync.tma_partition(
tma_atom_a,
0,
a_cta_layout,
cute.group_modes(sA, 0, 3),
cute.group_modes(tCgA, 0, 3),
)
b_cta_layout = cute.make_layout(
cute.slice_(cluster_layout_vmnk, (0, None, 0, 0)).shape
)
tBsB, tBgB = cpasync.tma_partition(
tma_atom_b,
0,
b_cta_layout,
cute.group_modes(sB, 0, 3),
cute.group_modes(tCgB, 0, 3),
)
tCrA = tiled_mma.make_fragment_A(sA)
tCrB = tiled_mma.make_fragment_B(sB)
acc_shape = tiled_mma.partition_shape_C(self.mma_tiler[:2])
tCtAcc_fake = tiled_mma.make_fragment_C(
cute.append(acc_shape, self.num_acc_stage)
)
pipeline_init_wait(cluster_shape_mn=cluster_layout_vmnk)
tile_sched = create_moe_tile_scheduler(
tile_sched_params=tile_sched_params,
direct_schedule=direct_schedule,
schedule_tiles=schedule_tiles,
swap_ab=self.swap_ab,
)
work_tile = tile_sched.initial_work_tile_info()
if warp_idx == self.tma_warp_id:
while work_tile.is_valid_tile:
mma_tile_coord_mnl = (
work_tile.tile_n_idx,
work_tile.tile_m_idx,
work_tile.expert_idx,
)
a_rest_l_coord = mma_tile_coord_mnl[2]
if cutlass.const_expr(self.contiguous_segments):
seg_base_tile = (
group_m[work_tile.expert_idx] // self.cta_tile_shape_mnk[1]
)
mma_tile_coord_mnl = (
mma_tile_coord_mnl[0],
seg_base_tile + mma_tile_coord_mnl[1],
cutlass.Int32(0),
)
a_rest_l_coord = work_tile.expert_idx
tAgA_slice = tAgA[(None, mma_tile_coord_mnl[0], None, a_rest_l_coord)]
tBgB_slice = tBgB[
(None, mma_tile_coord_mnl[1], None, mma_tile_coord_mnl[2])
]
ab_producer.reset()
peek_ab_empty_status = ab_producer.try_acquire()
for k_tile in cutlass.range(0, work_tile.k_tile_cnt, 1, unroll=1):
handle = ab_producer.acquire_and_advance(peek_ab_empty_status)
cute.copy(
tma_atom_a,
tAgA_slice[(None, handle.count)],
tAsA[(None, handle.index)],
tma_bar_ptr=handle.barrier,
)
cute.copy(
tma_atom_b,
tBgB_slice[(None, handle.count)],
tBsB[(None, handle.index)],
tma_bar_ptr=handle.barrier,
)
peek_ab_empty_status = cutlass.Boolean(1)
if handle.count + 1 < work_tile.k_tile_cnt:
peek_ab_empty_status = ab_producer.try_acquire()
work_tile = tile_sched.advance_to_next_work()
ab_producer.tail()
if warp_idx == self.mma_warp_id:
tmem.wait_for_alloc()
tmem_ptr = tmem.retrieve_ptr(self.acc_dtype)
tCtAcc_base = cute.make_tensor(tmem_ptr, tCtAcc_fake.layout)
acc_producer_state = pipeline.make_pipeline_state(
pipeline.PipelineUserType.Producer, self.num_acc_stage
)
while work_tile.is_valid_tile:
ab_consumer.reset()
peek_ab_full_status = ab_consumer.try_wait()
# Hand each 128-K partial to the epilogue warps for scaling.
for k_tile in range(work_tile.k_tile_cnt):
tCtAcc = tCtAcc_base[(None, None, None, acc_producer_state.index)]
acc_pipeline.producer_acquire(acc_producer_state)
handle = ab_consumer.wait_and_advance(peek_ab_full_status)
tiled_mma.set(tcgen05.Field.ACCUMULATE, False)
num_kblocks = cute.size(tCrA, mode=[2])
for kblk_idx in cutlass.range(num_kblocks, unroll_full=True):
kblk_crd = (None, None, kblk_idx, handle.index)
cute.gemm(
tiled_mma,
tCtAcc,
tCrA[kblk_crd],
tCrB[kblk_crd],
tCtAcc,
)
tiled_mma.set(tcgen05.Field.ACCUMULATE, True)
handle.release()
peek_ab_full_status = cutlass.Boolean(1)
if handle.count + 1 < work_tile.k_tile_cnt:
peek_ab_full_status = ab_consumer.try_wait()
acc_pipeline.producer_commit(acc_producer_state)
acc_producer_state.advance()
work_tile = tile_sched.advance_to_next_work()
acc_pipeline.producer_tail(acc_producer_state)
sC = smem.allocate_tensor(
element_type=self.c_dtype,
layout=c_smem_layout_staged.outer,
byte_alignment=128,
swizzle=c_smem_layout_staged.inner,
)
if warp_idx < self.mma_warp_id:
tmem.allocate(self.num_tmem_alloc_cols)
tmem.wait_for_alloc()
tmem_ptr = tmem.retrieve_ptr(self.acc_dtype)
tCtAcc_base = cute.make_tensor(tmem_ptr, tCtAcc_fake.layout)
acc_consumer_state = pipeline.make_pipeline_state(
pipeline.PipelineUserType.Consumer, self.num_acc_stage
)
c_producer_group = pipeline.CooperativeGroup(
pipeline.Agent.Thread,
32 * len(self.epilogue_warp_id),
)
c_pipeline = pipeline.PipelineTmaStore.create(
num_stages=self.num_c_stage, producer_group=c_producer_group
)
epilog_sync_barrier = pipeline.NamedBarrier(
barrier_id=self.epilog_sync_bar_id,
num_threads=32 * len(self.epilogue_warp_id),
)
# Match accumulator elements to token columns for scale lookup.
tCgC_t = utils.gemm.sm100.transform_partitioned_tensor_layout(tCgC)
tCtAcc_t = utils.gemm.sm100.transform_partitioned_tensor_layout(tCtAcc_base)
tiled_copy_t2r, tTR_tAcc_base, tTR_rAcc = (
utils.gemm.sm100.epilogue_tmem_copy_and_partition(
self, tidx, tCtAcc_t, tCgC_t, epi_tile, False
)
)
thr_copy_t2r = tiled_copy_t2r.get_slice(tidx)
cC = cute.make_identity_tensor(
(self.cta_tile_shape_mnk[0], self.cta_tile_shape_mnk[1])
)
cC_epi = cute.flat_divide(cC, epi_tile)
tTR_cC_epi = thr_copy_t2r.partition_D(cC_epi)
# ((frag), (subtile)): linear element and subtile indices.
tTR_cC = cute.group_modes(
cute.group_modes(tTR_cC_epi, 3, cute.rank(tTR_cC_epi)), 0, 3
)
tTR_rC = cute.make_rmem_tensor(tTR_rAcc.shape, self.c_dtype)
tiled_copy_r2s, tRS_rC, tRS_sC = (
utils.gemm.sm100.epilogue_smem_copy_and_partition(
self, tiled_copy_t2r, tTR_rC, tidx, sC
)
)
tCgC_epi = cute.flat_divide(tCgC_t, epi_tile)
bSG_sC, bSG_gC_partitioned = cpasync.tma_partition(
tma_atom_c,
0,
cute.make_layout(1),
cute.group_modes(sC, 0, 2),
cute.group_modes(tCgC_epi, 0, 2),
)
subtile_cnt = cute.size(tTR_cC.shape, mode=[1])
frag_size = cute.size(tTR_rAcc.shape)
tTR_rAcc_flat = cute.group_modes(tTR_rAcc, 0, cute.rank(tTR_rAcc))
tTR_rTotal = cute.make_rmem_tensor(
cute.make_layout((frag_size, subtile_cnt)), cutlass.Float32
)
num_tiles_executed = cutlass.Int32(0)
while work_tile.is_valid_tile:
mma_tile_coord_mnl = (
work_tile.tile_n_idx,
work_tile.tile_m_idx,
work_tile.expert_idx,
)
weight_expert = work_tile.expert_idx
if cutlass.const_expr(self.contiguous_segments):
seg_base_tile = (
group_m[work_tile.expert_idx] // self.cta_tile_shape_mnk[1]
)
mma_tile_coord_mnl = (
mma_tile_coord_mnl[0],
seg_base_tile + mma_tile_coord_mnl[1],
cutlass.Int32(0),
)
k_tile_cnt = work_tile.k_tile_cnt
nt_idx = mma_tile_coord_mnl[0]
token_base = mma_tile_coord_mnl[1] * cta_n
token_rest_l = mma_tile_coord_mnl[2]
work_tile = tile_sched.advance_to_next_work()
for i in cutlass.range_constexpr(frag_size):
for st in cutlass.range_constexpr(subtile_cnt):
tTR_rTotal[(i, st)] = cutlass.Float32(0.0)
for k_tile in range(k_tile_cnt):
sw = sf_a[(nt_idx, k_tile, weight_expert)]
if tidx < cta_n:
sColScale[tidx] = (
sw * sf_b[(token_base + tidx, k_tile, token_rest_l)]
)
epilog_sync_barrier.arrive_and_wait()
acc_pipeline.consumer_wait(acc_consumer_state)
tTR_tAcc = tTR_tAcc_base[
(None, None, None, None, None, acc_consumer_state.index)
]
tTR_tAcc = cute.group_modes(tTR_tAcc, 3, cute.rank(tTR_tAcc))
for st in cutlass.range_constexpr(subtile_cnt):
cute.copy(
tiled_copy_t2r,
tTR_tAcc[(None, None, None, st)],
tTR_rAcc,
)
for i in cutlass.range_constexpr(frag_size):
col = tTR_cC[(i, st)][1]
tTR_rTotal[(i, st)] = (
tTR_rTotal[(i, st)] + tTR_rAcc_flat[i] * sColScale[col]
)
with cute.arch.elect_one():
acc_pipeline.consumer_release(acc_consumer_state)
acc_consumer_state.advance()
epilog_sync_barrier.arrive_and_wait()
num_prev_subtiles = num_tiles_executed * subtile_cnt
bSG_gC = bSG_gC_partitioned[(None, None, None, *mma_tile_coord_mnl)]
bSG_gC = cute.group_modes(bSG_gC, 1, cute.rank(bSG_gC))
for st in cutlass.range_constexpr(subtile_cnt):
for i in cutlass.range_constexpr(frag_size):
tTR_rAcc_flat[i] = tTR_rTotal[(i, st)]
acc_vec = tiled_copy_r2s.retile(tTR_rAcc).load()
acc_vec = epilogue_op(acc_vec.to(self.c_dtype))
tRS_rC.store(acc_vec)
c_buffer = (num_prev_subtiles + st) % self.num_c_stage
cute.copy(
tiled_copy_r2s,
tRS_rC,
tRS_sC[(None, None, None, c_buffer)],
)
cute.arch.fence_proxy("async.shared", space="cta")
epilog_sync_barrier.arrive_and_wait()
if warp_idx == self.epilogue_warp_id[0]:
cute.copy(
tma_atom_c,
bSG_sC[(None, c_buffer)],
bSG_gC[(None, st)],
)
c_pipeline.producer_commit()
c_pipeline.producer_acquire()
epilog_sync_barrier.arrive_and_wait()
num_tiles_executed = num_tiles_executed + 1
c_pipeline.producer_tail()
tmem.relinquish_alloc_permit()
tmem.free(tmem_ptr)
@@ -0,0 +1,802 @@
# Copyright (c) 2025 - 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import math
from typing import Optional, Tuple, Type
import cuda.bindings.driver as cuda
import cutlass
import cutlass.cute as cute
import cutlass.utils as utils
import cutlass.utils.hopper_helpers as sm90_utils
from cutlass import pipeline
from cutlass.pipeline import pipeline_init_arrive, pipeline_init_wait
from sglang.kernels.ops.lora.moe.cutedsl.scheduler import (
MoESchedulerParams,
create_moe_tile_scheduler,
resolve_scheduler_params_and_grid,
)
class GroupedGemmKernelSm90Bf16:
"""Hopper grouped GEMM with the same config interface as SM100."""
def __init__(
self,
acc_dtype: Type[cutlass.Numeric],
use_2cta_instrs: bool,
mma_tiler_mn: Tuple[int, int],
cluster_shape_mn: Tuple[int, int],
mma_inst_tile_k: int = 4,
persistent_clusters: Optional[int] = None,
swap_ab: bool = False,
contiguous_segments: bool = False,
):
if use_2cta_instrs:
raise ValueError("2-CTA MMA is a tcgen05 feature; SM90 has none")
self.acc_dtype = acc_dtype
self.cluster_shape_mn = cluster_shape_mn
self.mma_inst_tile_k = mma_inst_tile_k
self.persistent_clusters = persistent_clusters
self.swap_ab = swap_ab
self.contiguous_segments = contiguous_segments
if contiguous_segments and not swap_ab:
raise ValueError("contiguous_segments requires swap_ab")
if contiguous_segments and cluster_shape_mn != (1, 1):
raise ValueError("contiguous_segments requires a (1, 1) cluster")
# The K extent here is a placeholder. _setup_attributes computes it.
self.tile_shape_mnk = (*mma_tiler_mn, 1)
# Upstream uses a second math warp group only for large tiles.
self.atom_layout_mnk = (
(2, 1, 1)
if self.tile_shape_mnk[0] > 64 and self.tile_shape_mnk[1] > 128
else (1, 1, 1)
)
self.occupancy = 1
self.num_dma_warp_groups = 1
self.num_mma_warp_groups = math.prod(self.atom_layout_mnk)
self.num_threads_per_warp_group = 128
self.threads_per_cta = (
self.num_dma_warp_groups + self.num_mma_warp_groups
) * self.num_threads_per_warp_group
self.load_warp_id = 0
self.epi_store_warp_id = self.num_dma_warp_groups * 4
self.load_register_requirement = 40
self.mma_register_requirement = 232
self.smem_capacity = utils.get_smem_capacity_in_bytes("sm_90")
self.num_mma_threads = (
self.num_mma_warp_groups * self.num_threads_per_warp_group
)
self.epilog_sync_barrier = pipeline.NamedBarrier(
barrier_id=1, num_threads=self.num_mma_threads
)
self.buffer_align_bytes = 1024
self.tiled_mma = None
self.ab_stage = None
self.epi_stage = None
self.a_smem_layout_staged = None
self.b_smem_layout_staged = None
self.epi_smem_layout_staged = None
self.epi_tile = None
self.shared_storage = None
def _setup_attributes(self):
self.tiled_mma = sm90_utils.make_trivial_tiled_mma(
self.a_dtype,
self.b_dtype,
self.a_layout.sm90_mma_major_mode(),
self.b_layout.sm90_mma_major_mode(),
self.acc_dtype,
self.atom_layout_mnk,
tiler_mn=(64, self.tile_shape_mnk[1]),
)
mma_inst_shape_k = cute.size(self.tiled_mma.shape_mnk, mode=[2])
self.tile_shape_mnk = (
self.tile_shape_mnk[0],
self.tile_shape_mnk[1],
mma_inst_shape_k * self.mma_inst_tile_k,
)
self.cta_layout_mnk = cute.make_layout((*self.cluster_shape_mn, 1))
self.num_mcast_ctas_a = self.cluster_shape_mn[1]
self.num_mcast_ctas_b = self.cluster_shape_mn[0]
self.is_a_mcast = self.num_mcast_ctas_a > 1
self.is_b_mcast = self.num_mcast_ctas_b > 1
is_cooperative = self.atom_layout_mnk == (2, 1, 1)
self.epi_tile = (
min(128 if is_cooperative else 64, self.tile_shape_mnk[0]),
min(32, self.tile_shape_mnk[1]),
)
self.ab_stage, self.epi_stage = self._compute_stages(
self.tile_shape_mnk,
self.a_dtype,
self.b_dtype,
self.epi_tile,
self.c_dtype,
self.smem_capacity,
self.occupancy,
)
(
self.a_smem_layout_staged,
self.b_smem_layout_staged,
self.epi_smem_layout_staged,
) = self._make_smem_layouts(
self.tile_shape_mnk,
self.epi_tile,
self.a_dtype,
self.a_layout,
self.b_dtype,
self.b_layout,
self.ab_stage,
self.c_dtype,
self.c_layout,
self.epi_stage,
)
@cute.jit
def __call__(
self,
a: cute.Tensor,
b: cute.Tensor,
c: cute.Tensor,
group_m: cute.Tensor,
direct_schedule: cute.Tensor,
schedule_tiles: cute.Tensor,
max_active_clusters: cutlass.Constexpr,
stream: cuda.CUstream,
epilogue_op: cutlass.Constexpr = lambda x: x,
):
self.a_dtype = a.element_type
self.b_dtype = b.element_type
self.c_dtype = c.element_type
self.a_layout = utils.LayoutEnum.from_tensor(a)
self.b_layout = utils.LayoutEnum.from_tensor(b)
self.c_layout = utils.LayoutEnum.from_tensor(c)
if cutlass.const_expr(self.a_dtype != self.b_dtype):
raise TypeError(f"Type mismatch: {self.a_dtype} != {self.b_dtype}")
self._setup_attributes()
tma_atom_a, tma_tensor_a = self._make_tma_atoms_and_tensors(
a,
self.a_smem_layout_staged,
(self.tile_shape_mnk[0], self.tile_shape_mnk[2]),
self.cluster_shape_mn[1],
)
tma_atom_b, tma_tensor_b = self._make_tma_atoms_and_tensors(
b,
self.b_smem_layout_staged,
(self.tile_shape_mnk[1], self.tile_shape_mnk[2]),
self.cluster_shape_mn[0],
)
tma_atom_c, tma_tensor_c = self._make_tma_store_atoms_and_tensors(
c, self.epi_smem_layout_staged, self.epi_tile
)
self.tile_sched_params, grid = resolve_scheduler_params_and_grid(
a=a,
cta_tile_k=self.tile_shape_mnk[2],
cluster_shape_mn=self.cluster_shape_mn,
swap_ab=self.swap_ab,
persistent_clusters=self.persistent_clusters,
max_active_clusters=max_active_clusters,
)
@cute.struct
class SharedStorage:
mainloop_pipeline_array_ptr: cute.struct.MemRange[
cutlass.Int64, self.ab_stage * 2
]
sA: cute.struct.Align[
cute.struct.MemRange[
self.a_dtype, cute.cosize(self.a_smem_layout_staged)
],
self.buffer_align_bytes,
]
sB: cute.struct.Align[
cute.struct.MemRange[
self.b_dtype, cute.cosize(self.b_smem_layout_staged)
],
self.buffer_align_bytes,
]
sC: cute.struct.Align[
cute.struct.MemRange[
self.c_dtype, cute.cosize(self.epi_smem_layout_staged)
],
self.buffer_align_bytes,
]
self.shared_storage = SharedStorage
self.kernel(
tma_atom_a,
tma_tensor_a,
tma_atom_b,
tma_tensor_b,
tma_atom_c,
tma_tensor_c,
group_m,
direct_schedule,
schedule_tiles,
self.tiled_mma,
self.cta_layout_mnk,
self.a_smem_layout_staged,
self.b_smem_layout_staged,
self.epi_smem_layout_staged,
self.tile_sched_params,
epilogue_op,
).launch(
grid=grid,
block=[self.threads_per_cta, 1, 1],
cluster=(*self.cluster_shape_mn, 1),
min_blocks_per_mp=1,
stream=stream,
)
return
@cute.kernel
def kernel(
self,
tma_atom_a: cute.CopyAtom,
mA_mkl: cute.Tensor,
tma_atom_b: cute.CopyAtom,
mB_nkl: cute.Tensor,
tma_atom_c: cute.CopyAtom,
mC_mnl: cute.Tensor,
group_m: cute.Tensor,
direct_schedule: cute.Tensor,
schedule_tiles: cute.Tensor,
tiled_mma: cute.TiledMma,
cta_layout_mnk: cute.Layout,
a_smem_layout_staged: cute.ComposedLayout,
b_smem_layout_staged: cute.ComposedLayout,
epi_smem_layout_staged: cute.ComposedLayout,
tile_sched_params: MoESchedulerParams,
epilogue_op: cutlass.Constexpr,
):
tidx, _, _ = cute.arch.thread_idx()
warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx())
if warp_idx == 0:
cute.nvgpu.cpasync.prefetch_descriptor(tma_atom_a)
cute.nvgpu.cpasync.prefetch_descriptor(tma_atom_b)
cute.nvgpu.cpasync.prefetch_descriptor(tma_atom_c)
cta_rank_in_cluster = cute.arch.make_warp_uniform(
cute.arch.block_idx_in_cluster()
)
cluster_coord_mnk = cta_layout_mnk.get_flat_coord(cta_rank_in_cluster)
a_mcast_mask = cute.make_layout_image_mask(
cta_layout_mnk, cluster_coord_mnk, mode=1
)
b_mcast_mask = cute.make_layout_image_mask(
cta_layout_mnk, cluster_coord_mnk, mode=0
)
a_mcast_mask = a_mcast_mask if self.is_a_mcast else 0
b_mcast_mask = b_mcast_mask if self.is_b_mcast else 0
a_smem_layout = cute.slice_(a_smem_layout_staged, (None, None, 0))
b_smem_layout = cute.slice_(b_smem_layout_staged, (None, None, 0))
tma_copy_bytes = cute.size_in_bytes(
self.a_dtype, a_smem_layout
) + cute.size_in_bytes(self.b_dtype, b_smem_layout)
smem = utils.SmemAllocator()
storage = smem.allocate(self.shared_storage)
mainloop_pipeline_producer_group = pipeline.CooperativeGroup(
pipeline.Agent.Thread
)
mcast_size = self.num_mcast_ctas_a + self.num_mcast_ctas_b - 1
consumer_arrive_cnt = mcast_size * self.num_mma_warp_groups * 4
mainloop_pipeline_consumer_group = pipeline.CooperativeGroup(
pipeline.Agent.Thread, consumer_arrive_cnt
)
mainloop_pipeline = pipeline.PipelineTmaAsync.create(
barrier_storage=storage.mainloop_pipeline_array_ptr.data_ptr(),
num_stages=self.ab_stage,
producer_group=mainloop_pipeline_producer_group,
consumer_group=mainloop_pipeline_consumer_group,
tx_count=tma_copy_bytes,
cta_layout_vmnk=cute.make_layout((1, *cta_layout_mnk.shape)),
defer_sync=True,
)
pipeline_init_arrive(cluster_shape_mn=self.cluster_shape_mn, is_relaxed=True)
sA = storage.sA.get_tensor(
a_smem_layout_staged.outer, swizzle=a_smem_layout_staged.inner
)
sB = storage.sB.get_tensor(
b_smem_layout_staged.outer, swizzle=b_smem_layout_staged.inner
)
sC = storage.sC.get_tensor(
epi_smem_layout_staged.outer, swizzle=epi_smem_layout_staged.inner
)
# (bM, bK, RestM, RestK, RestL). The L mode is the expert index.
gA_mkl = cute.local_tile(
mA_mkl,
cute.slice_(self.tile_shape_mnk, (None, 0, None)),
(None, None, None),
)
gB_nkl = cute.local_tile(
mB_nkl,
cute.slice_(self.tile_shape_mnk, (0, None, None)),
(None, None, None),
)
gC_mnl = cute.local_tile(
mC_mnl,
cute.slice_(self.tile_shape_mnk, (None, None, 0)),
(None, None, None),
)
a_cta_layout = cute.make_layout(cute.slice_(cta_layout_mnk, (0, None, 0)).shape)
tAsA, tAgA = cute.nvgpu.cpasync.tma_partition(
tma_atom_a,
cluster_coord_mnk[1],
a_cta_layout,
cute.group_modes(sA, 0, 2),
cute.group_modes(gA_mkl, 0, 2),
)
b_cta_layout = cute.make_layout(cute.slice_(cta_layout_mnk, (None, 0, 0)).shape)
tBsB, tBgB = cute.nvgpu.cpasync.tma_partition(
tma_atom_b,
cluster_coord_mnk[0],
b_cta_layout,
cute.group_modes(sB, 0, 2),
cute.group_modes(gB_nkl, 0, 2),
)
warp_group_idx = cute.arch.make_warp_uniform(
tidx // self.num_threads_per_warp_group
)
mma_warp_group_thread_layout = cute.make_layout(
self.num_mma_warp_groups, stride=self.num_threads_per_warp_group
)
thr_mma = tiled_mma.get_slice(
mma_warp_group_thread_layout(warp_group_idx - self.num_dma_warp_groups)
)
tCsA = thr_mma.partition_A(sA)
tCsB = thr_mma.partition_B(sB)
tCrA = tiled_mma.make_fragment_A(tCsA)
tCrB = tiled_mma.make_fragment_B(tCsB)
tCgC = thr_mma.partition_C(gC_mnl)
accumulators = cute.make_rmem_tensor(tCgC.shape[:3], self.acc_dtype)
pipeline_init_wait(cluster_shape_mn=self.cluster_shape_mn)
tile_sched = create_moe_tile_scheduler(
tile_sched_params=tile_sched_params,
direct_schedule=direct_schedule,
schedule_tiles=schedule_tiles,
swap_ab=self.swap_ab,
)
work_tile = tile_sched.initial_work_tile_info()
is_dma_warp_group = warp_group_idx < self.num_dma_warp_groups
if is_dma_warp_group:
cute.arch.setmaxregister_decrease(self.load_register_requirement)
if warp_idx == self.load_warp_id:
mainloop_producer_state = pipeline.make_pipeline_state(
pipeline.PipelineUserType.Producer, self.ab_stage
)
while work_tile.is_valid_tile:
mma_tile_coord_mnl = (
work_tile.tile_m_idx,
work_tile.tile_n_idx,
work_tile.expert_idx,
)
if cutlass.const_expr(self.swap_ab):
mma_tile_coord_mnl = (
work_tile.tile_n_idx,
work_tile.tile_m_idx,
work_tile.expert_idx,
)
a_rest_l_coord = mma_tile_coord_mnl[2]
if cutlass.const_expr(self.contiguous_segments):
# Flat rows use slot 0 plus seg_offsets; weights keep the expert.
seg_base_tile = (
group_m[work_tile.expert_idx] // self.tile_shape_mnk[1]
)
mma_tile_coord_mnl = (
mma_tile_coord_mnl[0],
seg_base_tile + mma_tile_coord_mnl[1],
cutlass.Int32(0),
)
a_rest_l_coord = work_tile.expert_idx
tAgA_mkl = tAgA[(None, mma_tile_coord_mnl[0], None, a_rest_l_coord)]
tBgB_nkl = tBgB[
(None, mma_tile_coord_mnl[1], None, mma_tile_coord_mnl[2])
]
mainloop_producer_state.reset_count()
for k_tile in cutlass.range(0, work_tile.k_tile_cnt, 1, unroll=1):
mainloop_pipeline.producer_acquire(mainloop_producer_state)
cute.copy(
tma_atom_a,
tAgA_mkl[(None, mainloop_producer_state.count)],
tAsA[(None, mainloop_producer_state.index)],
tma_bar_ptr=mainloop_pipeline.producer_get_barrier(
mainloop_producer_state
),
mcast_mask=a_mcast_mask,
)
cute.copy(
tma_atom_b,
tBgB_nkl[(None, mainloop_producer_state.count)],
tBsB[(None, mainloop_producer_state.index)],
tma_bar_ptr=mainloop_pipeline.producer_get_barrier(
mainloop_producer_state
),
mcast_mask=b_mcast_mask,
)
mainloop_pipeline.producer_commit(mainloop_producer_state)
mainloop_producer_state.advance()
work_tile = tile_sched.advance_to_next_work()
mainloop_pipeline.producer_tail(mainloop_producer_state)
if not is_dma_warp_group:
cute.arch.setmaxregister_increase(self.mma_register_requirement)
mainloop_consumer_read_state = pipeline.make_pipeline_state(
pipeline.PipelineUserType.Consumer, self.ab_stage
)
mainloop_consumer_release_state = pipeline.make_pipeline_state(
pipeline.PipelineUserType.Consumer, self.ab_stage
)
num_k_blocks = cute.size(tCrA, mode=[2])
# N=8 has only four values/thread; the helper's fixed st.matrix x4
# needs eight. Scale the matrix count with the tile instead.
num_store_matrices = min(4, max(1, self.tile_shape_mnk[1] // 4))
if cutlass.const_expr(self.c_dtype.width == 16):
copy_atom_r2s = cute.make_copy_atom(
cute.nvgpu.warp.StMatrix8x8x16bOp(
self.c_layout.is_m_major_c(), num_store_matrices
),
self.c_dtype,
)
else:
copy_atom_r2s = sm90_utils.sm90_get_smem_store_op(
self.c_layout, elem_ty_d=self.c_dtype, elem_ty_acc=self.acc_dtype
)
copy_atom_C = cute.make_copy_atom(
cute.nvgpu.warp.StMatrix8x8x16bOp(
self.c_layout.is_m_major_c(), num_store_matrices
),
self.c_dtype,
)
tiled_copy_C_Atom = cute.make_tiled_copy_C_atom(copy_atom_C, tiled_mma)
tiled_copy_r2s = cute.make_tiled_copy_S(copy_atom_r2s, tiled_copy_C_Atom)
thr_copy_r2s = tiled_copy_r2s.get_slice(
tidx - self.num_dma_warp_groups * self.num_threads_per_warp_group
)
tRS_sD = thr_copy_r2s.partition_D(sC)
tRS_rAcc = tiled_copy_r2s.retile(accumulators)
rD_shape = cute.shape(thr_copy_r2s.partition_S(sC))
tRS_rD_layout = cute.make_layout(rD_shape[:3])
tRS_rD = cute.make_rmem_tensor(tRS_rD_layout.shape, self.acc_dtype)
tRS_rD_out = cute.make_rmem_tensor(tRS_rD_layout.shape, self.c_dtype)
size_tRS_rD = cute.size(tRS_rD)
tma_store_producer_group = pipeline.CooperativeGroup(
pipeline.Agent.Thread, self.num_mma_threads
)
tma_store_pipeline = pipeline.PipelineTmaStore.create(
num_stages=self.epi_stage,
producer_group=tma_store_producer_group,
)
# Rotate epilogue buffers by executed tiles, not global work index.
num_tiles_executed = cutlass.Int32(0)
while work_tile.is_valid_tile:
mma_tile_coord_mnl = (
work_tile.tile_m_idx,
work_tile.tile_n_idx,
work_tile.expert_idx,
)
if cutlass.const_expr(self.swap_ab):
mma_tile_coord_mnl = (
work_tile.tile_n_idx,
work_tile.tile_m_idx,
work_tile.expert_idx,
)
if cutlass.const_expr(self.contiguous_segments):
# Use the same flat segment offset as the DMA warp.
seg_base_tile = (
group_m[work_tile.expert_idx] // self.tile_shape_mnk[1]
)
mma_tile_coord_mnl = (
mma_tile_coord_mnl[0],
seg_base_tile + mma_tile_coord_mnl[1],
cutlass.Int32(0),
)
gC_mnl_slice = gC_mnl[(None, None, *mma_tile_coord_mnl)]
mainloop_consumer_read_state.reset_count()
mainloop_consumer_release_state.reset_count()
accumulators.fill(0.0)
tiled_mma.set(cute.nvgpu.warpgroup.Field.ACCUMULATE, True)
cute.nvgpu.warpgroup.fence()
# Positive, aligned K guarantees one prologue tile.
k_pipe_mmas = 1
for k_tile in cutlass.range(0, k_pipe_mmas, 1, unroll=1):
mainloop_pipeline.consumer_wait(mainloop_consumer_read_state)
for k_block_idx in cutlass.range_constexpr(num_k_blocks):
k_block_coord = (
None,
None,
k_block_idx,
mainloop_consumer_read_state.index,
)
cute.gemm(
tiled_mma,
accumulators,
tCrA[k_block_coord],
tCrB[k_block_coord],
accumulators,
)
cute.nvgpu.warpgroup.commit_group()
mainloop_consumer_read_state.advance()
for k_tile in cutlass.range(
k_pipe_mmas, work_tile.k_tile_cnt, 1, unroll=1
):
mainloop_pipeline.consumer_wait(mainloop_consumer_read_state)
for k_block_idx in cutlass.range_constexpr(num_k_blocks):
k_block_coord = (
None,
None,
k_block_idx,
mainloop_consumer_read_state.index,
)
cute.gemm(
tiled_mma,
accumulators,
tCrA[k_block_coord],
tCrB[k_block_coord],
accumulators,
)
cute.nvgpu.warpgroup.commit_group()
cute.nvgpu.warpgroup.wait_group(k_pipe_mmas)
mainloop_pipeline.consumer_release(mainloop_consumer_release_state)
mainloop_consumer_release_state.advance()
mainloop_consumer_read_state.advance()
cute.nvgpu.warpgroup.wait_group(0)
for k_tile in cutlass.range(0, k_pipe_mmas, 1, unroll=1):
mainloop_pipeline.consumer_release(mainloop_consumer_release_state)
mainloop_consumer_release_state.advance()
tCgC_for_tma_partition = cute.zipped_divide(gC_mnl_slice, self.epi_tile)
bSG_sD, bSG_gD = cute.nvgpu.cpasync.tma_partition(
tma_atom_c,
0,
cute.make_layout(1),
cute.group_modes(sC, 0, 2),
tCgC_for_tma_partition,
)
epi_tile_num = cute.size(tCgC_for_tma_partition, mode=[1])
epi_tile_shape = tCgC_for_tma_partition.shape[1]
epi_tile_layout = cute.make_layout(
epi_tile_shape, stride=(epi_tile_shape[1], 1)
)
num_prev_epi_tiles = num_tiles_executed * epi_tile_num
for epi_idx in cutlass.range_constexpr(epi_tile_num):
for epi_v in cutlass.range_constexpr(size_tRS_rD):
tRS_rD[epi_v] = tRS_rAcc[epi_idx * size_tRS_rD + epi_v]
acc_vec = epilogue_op(tRS_rD.load())
tRS_rD_out.store(acc_vec.to(self.c_dtype))
epi_buffer = (num_prev_epi_tiles + epi_idx) % cute.size(
tRS_sD, mode=[3]
)
cute.copy(
tiled_copy_r2s,
tRS_rD_out,
tRS_sD[(None, None, None, epi_buffer)],
)
cute.arch.fence_proxy("async.shared", space="cta")
self.epilog_sync_barrier.arrive_and_wait()
gmem_coord = epi_tile_layout.get_hier_coord(epi_idx)
if warp_idx == self.epi_store_warp_id:
cute.copy(
tma_atom_c,
bSG_sD[(None, epi_buffer)],
bSG_gD[(None, gmem_coord)],
)
tma_store_pipeline.producer_commit()
tma_store_pipeline.producer_acquire()
self.epilog_sync_barrier.arrive_and_wait()
num_tiles_executed += cutlass.Int32(1)
work_tile = tile_sched.advance_to_next_work()
tma_store_pipeline.producer_tail()
# The host helpers below come from the upstream Hopper persistent example.
@staticmethod
def _compute_stages(
tile_shape_mnk,
a_dtype,
b_dtype,
epi_tile,
c_dtype,
smem_capacity,
occupancy,
):
a_shape = cute.slice_(tile_shape_mnk, (None, 0, None))
b_shape = cute.slice_(tile_shape_mnk, (0, None, None))
ab_bytes_per_stage = (
cute.size(a_shape) * a_dtype.width // 8
+ cute.size(b_shape) * b_dtype.width // 8
)
c_bytes_per_stage = cute.size(epi_tile) * c_dtype.width // 8
epi_stage = 4
epi_bytes = c_bytes_per_stage * epi_stage
mbar_helpers_bytes = 1024
ab_stage = (
smem_capacity // occupancy - (mbar_helpers_bytes + epi_bytes)
) // ab_bytes_per_stage
return ab_stage, epi_stage
@staticmethod
def _make_smem_layouts(
tile_shape_mnk,
epi_tile,
a_dtype,
a_layout,
b_dtype,
b_layout,
ab_stage,
c_dtype,
c_layout,
epi_stage,
):
a_smem_shape = cute.slice_(tile_shape_mnk, (None, 0, None))
a_is_k_major = (
a_layout.sm90_mma_major_mode() == cute.nvgpu.warpgroup.OperandMajorMode.K
)
b_is_k_major = (
b_layout.sm90_mma_major_mode() == cute.nvgpu.warpgroup.OperandMajorMode.K
)
a_major_mode_size = tile_shape_mnk[2 if a_is_k_major else 0]
a_smem_layout_atom = cute.nvgpu.warpgroup.make_smem_layout_atom(
sm90_utils.get_smem_layout_atom(a_layout, a_dtype, a_major_mode_size),
a_dtype,
)
a_smem_layout_staged = cute.tile_to_shape(
a_smem_layout_atom,
cute.append(a_smem_shape, ab_stage),
order=(0, 1, 2) if a_is_k_major else (1, 0, 2),
)
b_smem_shape = cute.slice_(tile_shape_mnk, (0, None, None))
b_major_mode_size = tile_shape_mnk[2 if b_is_k_major else 1]
b_smem_layout_atom = cute.nvgpu.warpgroup.make_smem_layout_atom(
sm90_utils.get_smem_layout_atom(b_layout, b_dtype, b_major_mode_size),
b_dtype,
)
b_smem_layout_staged = cute.tile_to_shape(
b_smem_layout_atom,
cute.append(b_smem_shape, ab_stage),
order=(0, 1, 2) if b_is_k_major else (1, 0, 2),
)
c_smem_shape = epi_tile
c_major_mode_size = epi_tile[1] if c_layout.is_n_major_c() else epi_tile[0]
c_smem_layout_atom = cute.nvgpu.warpgroup.make_smem_layout_atom(
sm90_utils.get_smem_layout_atom(c_layout, c_dtype, c_major_mode_size),
c_dtype,
)
epi_smem_layout_staged = cute.tile_to_shape(
c_smem_layout_atom,
cute.append(c_smem_shape, epi_stage),
order=(1, 0, 2) if c_layout.is_m_major_c() else (0, 1, 2),
)
return a_smem_layout_staged, b_smem_layout_staged, epi_smem_layout_staged
@staticmethod
def _make_tma_store_atoms_and_tensors(tensor_c, epi_smem_layout_staged, epi_tile):
epi_smem_layout = cute.slice_(epi_smem_layout_staged, (None, None, 0))
return cute.nvgpu.cpasync.make_tiled_tma_atom(
cute.nvgpu.cpasync.CopyBulkTensorTileS2GOp(),
tensor_c,
epi_smem_layout,
epi_tile,
)
@staticmethod
def _make_tma_atoms_and_tensors(tensor, smem_layout_staged, smem_tile, mcast_dim):
op = (
cute.nvgpu.cpasync.CopyBulkTensorTileG2SOp()
if mcast_dim == 1
else cute.nvgpu.cpasync.CopyBulkTensorTileG2SMulticastOp()
)
smem_layout = cute.slice_(smem_layout_staged, (None, None, 0))
return cute.nvgpu.cpasync.make_tiled_tma_atom(
op, tensor, smem_layout, smem_tile, num_multicast=mcast_dim
)
def check_supported_dtypes(self, a_dtype, b_dtype, c_dtype):
if a_dtype not in (cutlass.Float16, cutlass.BFloat16):
raise TypeError(f"SM90 port supports F16/BF16 A/B; got {a_dtype}")
if a_dtype != b_dtype:
raise TypeError(f"A/B dtype mismatch: {a_dtype} vs {b_dtype}")
if c_dtype not in (cutlass.Float16, cutlass.BFloat16, cutlass.Float32):
raise TypeError(f"unsupported C dtype {c_dtype}")
def check_mma_tiler_and_cluster_shape(self):
if self.tile_shape_mnk[0] not in (64, 128):
raise ValueError("SM90 CTA tile M must be 64/128")
if self.tile_shape_mnk[1] not in (8, 16, 32, 64, 128, 256):
raise ValueError(
"this port validates CTA tile N in {8, 16, 32, 64, 128, "
"256}; WGMMA itself accepts 8..256 step 8 -- extend the "
"validated set before requesting other widths"
)
if math.prod(self.cluster_shape_mn) > 4:
raise ValueError("SM90 cluster size must be <= 4")
for extent in self.cluster_shape_mn:
if extent <= 0 or extent & (extent - 1):
raise ValueError(
"cluster extents must be positive powers of two; got "
f"{self.cluster_shape_mn}"
)
def check_tensor_alignment(self, problem_shape, a_major, b_major, c_major):
if a_major != "k" or b_major != "k":
raise ValueError("SM90 port requires K-major A and B")
m, n, k, _length = problem_shape
for extent, name in ((m, "M"), (n, "N"), (k, "K")):
if extent % 8:
raise ValueError(f"{name}={extent} breaks 16-byte TMA alignment")
def can_implement(
self, problem_shape, a_dtype, b_dtype, c_dtype, a_major, b_major, c_major
) -> bool:
try:
self.check_supported_dtypes(a_dtype, b_dtype, c_dtype)
self.check_mma_tiler_and_cluster_shape()
self.check_tensor_alignment(problem_shape, a_major, b_major, c_major)
except (TypeError, ValueError):
return False
return True
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,335 @@
"""Build both GEMM schedules from the dispatcher's row counts in one launch."""
from __future__ import annotations
import torch
import triton
import triton.language as tl
# Shared with scheduler.py: one signed int64 per tile, leaving bit 63 clear.
EXPERT_SHIFT = 0
EXPERT_BITS = 20
EXPERT_MASK = (1 << EXPERT_BITS) - 1
TOKEN_CLUSTER_SHIFT = EXPERT_SHIFT + EXPERT_BITS
TOKEN_CLUSTER_BITS = 22
TOKEN_CLUSTER_MASK = (1 << TOKEN_CLUSTER_BITS) - 1
OUTPUT_CLUSTER_SHIFT = TOKEN_CLUSTER_SHIFT + TOKEN_CLUSTER_BITS
OUTPUT_CLUSTER_BITS = 21
OUTPUT_CLUSTER_MASK = (1 << OUTPUT_CLUSTER_BITS) - 1
PACKED_BITS = OUTPUT_CLUSTER_SHIFT + OUTPUT_CLUSTER_BITS
assert PACKED_BITS == 63, PACKED_BITS
MAX_EXPERTS = 1 << EXPERT_BITS
MAX_TOKEN_CLUSTERS = 1 << TOKEN_CLUSTER_BITS
MAX_OUTPUT_CLUSTERS = 1 << OUTPUT_CLUSTER_BITS
@triton.jit
def _dual_schedule_kernel(
masked_m_ptr,
schedule1_ptr,
tiles1_ptr,
schedule2_ptr,
tiles2_ptr,
token_width,
out_clusters1,
out_clusters2,
EXPERTS: tl.constexpr,
BLOCK_EXPERTS: tl.constexpr,
ENTRY_BLOCK: tl.constexpr,
TOKEN_SHIFT: tl.constexpr,
OUTPUT_SHIFT: tl.constexpr,
):
expert = tl.program_id(0)
stage = tl.program_id(1)
out_clusters = tl.where(stage == 0, out_clusters1, out_clusters2)
offs = tl.arange(0, BLOCK_EXPERTS)
all_rows = tl.load(masked_m_ptr + offs, mask=offs < EXPERTS, other=0)
all_entries = tl.cdiv(all_rows, token_width) * out_clusters
begin = tl.sum(tl.where(offs < expert, all_entries, 0))
if expert == 0:
total = tl.sum(tl.where(offs < EXPERTS, all_entries, 0))
if stage == 0:
tl.store(tiles1_ptr, total)
else:
tl.store(tiles2_ptr, total)
rows = tl.load(masked_m_ptr + expert)
token_clusters = tl.cdiv(rows, token_width)
safe_tc = tl.maximum(token_clusters, 1)
entries = token_clusters * out_clusters
token_major = token_clusters > out_clusters
for base in range(0, entries, ENTRY_BLOCK):
local = base + tl.arange(0, ENTRY_BLOCK)
valid = local < entries
oc_a = local // safe_tc
tc_a = local - oc_a * safe_tc
tc_b = local // out_clusters
oc_b = local - tc_b * out_clusters
tc_i = tl.where(token_major, tc_b, tc_a)
oc_i = tl.where(token_major, oc_b, oc_a)
# Widen before shifting to preserve the upper fields.
packed = (
expert.to(tl.int64)
| (tc_i.to(tl.int64) << TOKEN_SHIFT)
| (oc_i.to(tl.int64) << OUTPUT_SHIFT)
)
if stage == 0:
tl.store(schedule1_ptr + begin + local, packed, mask=valid)
else:
tl.store(schedule2_ptr + begin + local, packed, mask=valid)
def dual_stage_schedule_capacities_masked(
*,
num_experts: int,
m_max: int,
token_width: int,
n_gemm1: int,
n_gemm2: int,
output_width: int,
cluster_shape_mn: tuple[int, int] = (1, 1),
use_2cta_instrs: bool = False,
) -> tuple[int, int]:
"""CTA-tile entries require 1x1 clusters and 1-CTA MMA."""
if tuple(cluster_shape_mn) != (1, 1) or use_2cta_instrs:
raise ValueError(
"packed schedules require a (1, 1) cluster and 1-CTA MMA; got "
f"cluster_shape_mn={tuple(cluster_shape_mn)}, "
f"use_2cta_instrs={use_2cta_instrs}"
)
out_clusters1 = (n_gemm1 + output_width - 1) // output_width
out_clusters2 = (n_gemm2 + output_width - 1) // output_width
max_token_clusters = (m_max + token_width - 1) // token_width
if num_experts > MAX_EXPERTS:
raise ValueError(
f"direct schedule packs expert INDICES in "
f"{MAX_EXPERTS.bit_length() - 1} bits (counts up to "
f"{MAX_EXPERTS}); got {num_experts}"
)
if max_token_clusters > MAX_TOKEN_CLUSTERS:
raise ValueError(
f"m_max={m_max} at token width {token_width} needs "
f"{max_token_clusters} token clusters; the packing holds "
f"{MAX_TOKEN_CLUSTERS}. Admission must pick a wider tile."
)
if max(out_clusters1, out_clusters2) > MAX_OUTPUT_CLUSTERS:
raise ValueError(
f"{max(out_clusters1, out_clusters2)} output clusters exceed the "
f"{MAX_OUTPUT_CLUSTERS} the non-negative-word config allows"
)
# Individually valid fields can still overflow the int32 prefix sum.
capacity = num_experts * max_token_clusters * max(out_clusters1, out_clusters2)
if capacity > 2**31 - 1:
raise ValueError(
f"worst-case schedule capacity {capacity} overflows the builder's "
"int32 prefix arithmetic"
)
return (
num_experts * max_token_clusters * out_clusters1,
num_experts * max_token_clusters * out_clusters2,
)
def validate_tile_geometry_contiguous(token_width: int, m_alignment: int) -> None:
"""Require exact segment-base division and keep partial tiles in bounds."""
if not isinstance(token_width, int) or token_width < 1:
raise ValueError(f"token_width must be a positive int, got {token_width!r}")
if not isinstance(m_alignment, int) or m_alignment < 1:
raise ValueError(f"m_alignment must be a positive int, got {m_alignment!r}")
if m_alignment % token_width:
raise ValueError(
f"token tile {token_width} does not divide the segment alignment "
f"{m_alignment}: a partial tile could cross into the next "
"expert's rows"
)
def dual_stage_schedule_capacities_contiguous(
*,
num_experts: int,
m_pad_ceiling: int,
max_expert_rows: int,
m_alignment: int,
token_width: int,
n_gemm1: int,
n_gemm2: int,
output_width: int,
cluster_shape_mn: tuple[int, int] = (1, 1),
use_2cta_instrs: bool = False,
) -> tuple[int, int]:
"""Bound capacity by total padded rows instead of per-expert slabs."""
dual_stage_schedule_capacities_masked(
num_experts=num_experts,
m_max=max_expert_rows,
token_width=token_width,
n_gemm1=n_gemm1,
n_gemm2=n_gemm2,
output_width=output_width,
cluster_shape_mn=cluster_shape_mn,
use_2cta_instrs=use_2cta_instrs,
)
validate_tile_geometry_contiguous(token_width, m_alignment)
if m_pad_ceiling < 0 or m_pad_ceiling % m_alignment:
raise ValueError(
f"m_pad_ceiling={m_pad_ceiling} must be a non-negative multiple "
f"of the segment alignment {m_alignment}"
)
total_clusters = m_pad_ceiling // token_width
out_clusters1 = (n_gemm1 + output_width - 1) // output_width
out_clusters2 = (n_gemm2 + output_width - 1) // output_width
capacity = total_clusters * max(out_clusters1, out_clusters2)
if capacity > 2**31 - 1:
raise ValueError(
f"worst-case contiguous schedule capacity {capacity} overflows "
"the builder's int32 prefix arithmetic"
)
return (
max(total_clusters * out_clusters1, 1),
max(total_clusters * out_clusters2, 1),
)
def build_dual_stage_schedules_contiguous(
seg_counts: torch.Tensor,
*,
m_pad_ceiling: int,
max_expert_rows: int,
m_alignment: int,
token_width: int,
n_gemm1: int,
n_gemm2: int,
output_width: int,
cluster_shape_mn: tuple[int, int] = (1, 1),
use_2cta_instrs: bool = False,
schedule1_out: torch.Tensor | None = None,
tiles1_out: torch.Tensor | None = None,
schedule2_out: torch.Tensor | None = None,
tiles2_out: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
capacities = dual_stage_schedule_capacities_contiguous(
num_experts=seg_counts.numel(),
m_pad_ceiling=m_pad_ceiling,
max_expert_rows=max_expert_rows,
m_alignment=m_alignment,
token_width=token_width,
n_gemm1=n_gemm1,
n_gemm2=n_gemm2,
output_width=output_width,
cluster_shape_mn=cluster_shape_mn,
use_2cta_instrs=use_2cta_instrs,
)
return _emit_dual_stage_schedules(
seg_counts,
capacities=capacities,
token_width=token_width,
n_gemm1=n_gemm1,
n_gemm2=n_gemm2,
output_width=output_width,
schedule1_out=schedule1_out,
tiles1_out=tiles1_out,
schedule2_out=schedule2_out,
tiles2_out=tiles2_out,
)
def _schedule_output(
output: torch.Tensor | None, *, elements: int, device: torch.device
) -> torch.Tensor:
if output is None:
return torch.empty(elements, dtype=torch.int64, device=device)
return output
def _tile_count_output(
output: torch.Tensor | None, *, device: torch.device
) -> torch.Tensor:
# int32: the device compares it to an Int32 work index.
if output is None:
return torch.empty(1, dtype=torch.int32, device=device)
return output
def build_dual_stage_schedules_masked(
masked_m: torch.Tensor,
*,
m_max: int,
token_width: int,
n_gemm1: int,
n_gemm2: int,
output_width: int,
cluster_shape_mn: tuple[int, int] = (1, 1),
use_2cta_instrs: bool = False,
schedule1_out: torch.Tensor | None = None,
tiles1_out: torch.Tensor | None = None,
schedule2_out: torch.Tensor | None = None,
tiles2_out: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
capacities = dual_stage_schedule_capacities_masked(
num_experts=masked_m.numel(),
m_max=m_max,
token_width=token_width,
n_gemm1=n_gemm1,
n_gemm2=n_gemm2,
output_width=output_width,
cluster_shape_mn=cluster_shape_mn,
use_2cta_instrs=use_2cta_instrs,
)
return _emit_dual_stage_schedules(
masked_m,
capacities=capacities,
token_width=token_width,
n_gemm1=n_gemm1,
n_gemm2=n_gemm2,
output_width=output_width,
schedule1_out=schedule1_out,
tiles1_out=tiles1_out,
schedule2_out=schedule2_out,
tiles2_out=tiles2_out,
)
def _emit_dual_stage_schedules(
row_counts: torch.Tensor,
*,
capacities: tuple[int, int],
token_width: int,
n_gemm1: int,
n_gemm2: int,
output_width: int,
schedule1_out: torch.Tensor | None,
tiles1_out: torch.Tensor | None,
schedule2_out: torch.Tensor | None,
tiles2_out: torch.Tensor | None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
capacity1, capacity2 = capacities
out_clusters1 = (n_gemm1 + output_width - 1) // output_width
out_clusters2 = (n_gemm2 + output_width - 1) // output_width
num_experts = row_counts.numel()
device = row_counts.device
schedule1 = _schedule_output(schedule1_out, elements=capacity1, device=device)
schedule2 = _schedule_output(schedule2_out, elements=capacity2, device=device)
tiles1 = _tile_count_output(tiles1_out, device=device)
tiles2 = _tile_count_output(tiles2_out, device=device)
_dual_schedule_kernel[(num_experts, 2)](
row_counts,
schedule1,
tiles1,
schedule2,
tiles2,
token_width,
out_clusters1,
out_clusters2,
EXPERTS=num_experts,
BLOCK_EXPERTS=max(triton.next_power_of_2(num_experts), 2),
ENTRY_BLOCK=128,
TOKEN_SHIFT=TOKEN_CLUSTER_SHIFT,
OUTPUT_SHIFT=OUTPUT_CLUSTER_SHIFT,
)
return schedule1, tiles1, schedule2, tiles2
@@ -0,0 +1,294 @@
# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Persistent scheduler for the packed work list from schedule_builder."""
from typing import List, Tuple
import cutlass.cute as cute
from cutlass._mlir import ir
from cutlass.cutlass_dsl import (
Boolean,
Int32,
Int64,
Integer,
dsl_user_op,
extract_mlir_values,
new_from_mlir_values,
)
from sglang.kernels.ops.lora.moe.cutedsl.schedule_builder import (
EXPERT_MASK,
OUTPUT_CLUSTER_MASK,
OUTPUT_CLUSTER_SHIFT,
TOKEN_CLUSTER_MASK,
TOKEN_CLUSTER_SHIFT,
)
class MoEWorkTileInfo:
def __init__(
self,
expert_idx: Int32, # -1 means invalid tile
tile_m_idx: Int32,
tile_n_idx: Int32,
k_tile_cnt: Int32,
):
self.expert_idx = expert_idx
self.tile_m_idx = tile_m_idx
self.tile_n_idx = tile_n_idx
self.k_tile_cnt = k_tile_cnt
@property
def is_valid_tile(self) -> Boolean:
return self.expert_idx >= Int32(0)
def __extract_mlir_values__(self) -> List[ir.Value]:
values = extract_mlir_values(self.expert_idx)
values.extend(extract_mlir_values(self.tile_m_idx))
values.extend(extract_mlir_values(self.tile_n_idx))
values.extend(extract_mlir_values(self.k_tile_cnt))
return values
def __new_from_mlir_values__(self, values: List[ir.Value]) -> "MoEWorkTileInfo":
assert len(values) == 4
return MoEWorkTileInfo(
expert_idx=new_from_mlir_values(self.expert_idx, [values[0]]),
tile_m_idx=new_from_mlir_values(self.tile_m_idx, [values[1]]),
tile_n_idx=new_from_mlir_values(self.tile_n_idx, [values[2]]),
k_tile_cnt=new_from_mlir_values(self.k_tile_cnt, [values[3]]),
)
class MoESchedulerParams:
def __init__(
self,
hidden: int | Int32,
cta_tile_k: int,
cluster_shape_mn: Tuple[int, int],
):
self.hidden = hidden if isinstance(hidden, Int32) else Int32(hidden)
self.cta_tile_k = cta_tile_k
self.cluster_shape_mn = cluster_shape_mn
def __extract_mlir_values__(self) -> List[ir.Value]:
return extract_mlir_values(self.hidden)
def __new_from_mlir_values__(self, values: List[ir.Value]) -> "MoESchedulerParams":
assert len(values) == 1
return MoESchedulerParams(
hidden=new_from_mlir_values(self.hidden, values),
cta_tile_k=self.cta_tile_k,
cluster_shape_mn=self.cluster_shape_mn,
)
class MoEDirectPersistentTileScheduler:
"""Decode (expert, cluster_m, cluster_n) from one int64 per tile."""
def __init__(
self,
params: MoESchedulerParams,
schedule: cute.Tensor,
schedule_tiles: cute.Tensor,
num_persistent_clusters: Int32,
current_work_linear_idx: Int32,
cta_id_in_cluster: cute.Coord,
):
self.params = params
self.schedule = schedule
self.schedule_tiles = schedule_tiles
self.num_persistent_clusters = num_persistent_clusters
self._current_work_linear_idx = current_work_linear_idx
self.cta_id_in_cluster = cta_id_in_cluster
def __extract_mlir_values__(self) -> List[ir.Value]:
values = []
values.extend(extract_mlir_values(self.params))
values.extend(extract_mlir_values(self.schedule))
values.extend(extract_mlir_values(self.schedule_tiles))
values.extend(extract_mlir_values(self.num_persistent_clusters))
values.extend(extract_mlir_values(self._current_work_linear_idx))
values.extend(extract_mlir_values(self.cta_id_in_cluster))
return values
def __new_from_mlir_values__(
self, values: List[ir.Value]
) -> "MoEDirectPersistentTileScheduler":
idx = 0
new_params = new_from_mlir_values(self.params, values[idx : idx + 1])
idx += 1
schedule_len = len(extract_mlir_values(self.schedule))
new_schedule = new_from_mlir_values(
self.schedule, values[idx : idx + schedule_len]
)
idx += schedule_len
tiles_len = len(extract_mlir_values(self.schedule_tiles))
new_schedule_tiles = new_from_mlir_values(
self.schedule_tiles, values[idx : idx + tiles_len]
)
idx += tiles_len
new_num_clusters = new_from_mlir_values(
self.num_persistent_clusters, [values[idx]]
)
idx += 1
new_work_idx = new_from_mlir_values(
self._current_work_linear_idx, [values[idx]]
)
idx += 1
new_cta_id = new_from_mlir_values(self.cta_id_in_cluster, values[idx : idx + 3])
return MoEDirectPersistentTileScheduler(
new_params,
new_schedule,
new_schedule_tiles,
new_num_clusters,
new_work_idx,
new_cta_id,
)
@staticmethod
@dsl_user_op
def create(
params: MoESchedulerParams,
schedule: cute.Tensor,
schedule_tiles: cute.Tensor,
block_idx: Tuple[Integer, Integer, Integer],
grid_dim: Tuple[Integer, Integer, Integer],
*,
loc=None,
ip=None,
) -> "MoEDirectPersistentTileScheduler":
num_persistent_clusters = cute.size(grid_dim, loc=loc, ip=ip) // cute.size(
params.cluster_shape_mn, loc=loc, ip=ip
)
bidx, bidy, bidz = block_idx
return MoEDirectPersistentTileScheduler(
params,
schedule,
schedule_tiles,
Int32(num_persistent_clusters),
Int32(bidz),
(
Int32(bidx % params.cluster_shape_mn[0]),
Int32(bidy % params.cluster_shape_mn[1]),
Int32(0),
),
)
@dsl_user_op
@cute.jit
def initial_work_tile_info(self, *, loc=None, ip=None) -> MoEWorkTileInfo:
return self._get_current_work(loc=loc, ip=ip)
@dsl_user_op
@cute.jit
def advance_to_next_work(self, *, loc=None, ip=None) -> MoEWorkTileInfo:
self._current_work_linear_idx += self.num_persistent_clusters
return self._get_current_work(loc=loc, ip=ip)
@dsl_user_op
@cute.jit
def _get_current_work(self, *, loc=None, ip=None) -> MoEWorkTileInfo:
work = MoEWorkTileInfo(Int32(-1), Int32(0), Int32(0), Int32(0))
if self._current_work_linear_idx < self.schedule_tiles[0]:
packed = Int64(self.schedule[self._current_work_linear_idx])
expert = Int32(packed & Int64(EXPERT_MASK))
cluster_m = Int32(
(packed >> Int64(TOKEN_CLUSTER_SHIFT)) & Int64(TOKEN_CLUSTER_MASK)
)
cluster_n = Int32(
(packed >> Int64(OUTPUT_CLUSTER_SHIFT)) & Int64(OUTPUT_CLUSTER_MASK)
)
tile_m = (
cluster_m * self.params.cluster_shape_mn[0] + self.cta_id_in_cluster[0] # type: ignore[index]
)
tile_n = (
cluster_n * self.params.cluster_shape_mn[1] + self.cta_id_in_cluster[1] # type: ignore[index]
)
k_tiles = (
self.params.hidden + self.params.cta_tile_k - 1
) // self.params.cta_tile_k
work = MoEWorkTileInfo(expert, tile_m, tile_n, Int32(k_tiles))
return work
def resolve_scheduler_params_and_grid(
*,
a: cute.Tensor,
cta_tile_k: int,
cluster_shape_mn,
swap_ab: bool,
persistent_clusters,
max_active_clusters,
):
"""Keep tokens on scheduler M, transposing cluster axes under swap_ab."""
# K can be hierarchical; the scheduler needs its scalar extent.
k = cute.size(a.shape[1])
cluster = cluster_shape_mn
if swap_ab:
cluster = (cluster_shape_mn[1], cluster_shape_mn[0])
params = MoESchedulerParams(
hidden=k,
cta_tile_k=cta_tile_k,
cluster_shape_mn=cluster,
)
launch_clusters = (
max_active_clusters if persistent_clusters is None else persistent_clusters
)
grid = (cluster_shape_mn[0], cluster_shape_mn[1], launch_clusters)
return params, grid
def create_moe_tile_scheduler(
*,
tile_sched_params,
direct_schedule: cute.Tensor,
schedule_tiles: cute.Tensor,
swap_ab: bool,
):
"""Restore scheduler axis order under swap_ab at trace time."""
scheduler_block_idx = cute.arch.block_idx()
scheduler_grid_dim = cute.arch.grid_dim()
if swap_ab:
scheduler_block_idx = (
scheduler_block_idx[1],
scheduler_block_idx[0],
scheduler_block_idx[2],
)
scheduler_grid_dim = (
scheduler_grid_dim[1],
scheduler_grid_dim[0],
scheduler_grid_dim[2],
)
return MoEDirectPersistentTileScheduler.create(
tile_sched_params,
direct_schedule,
schedule_tiles,
scheduler_block_idx,
scheduler_grid_dim,
)
@@ -0,0 +1,28 @@
"""Input contracts shared by the masked and contiguous row movers."""
from __future__ import annotations
import torch
def check_source_rows(
hidden_states: torch.Tensor, topk_ids: torch.Tensor, top_k: int
) -> None:
if hidden_states.dtype != torch.bfloat16:
raise ValueError("the row movers take BF16 [num_tokens, hidden] input")
if hidden_states.ndim != 2 or not hidden_states.is_contiguous():
raise ValueError("hidden_states must be contiguous [num_tokens, hidden]")
if not topk_ids.is_contiguous():
raise ValueError("topk_ids must be contiguous")
if topk_ids.numel() != hidden_states.size(0) * top_k:
raise ValueError(
f"topk_ids carries {topk_ids.numel()} pairs for "
f"{hidden_states.size(0)} tokens x top_k={top_k}"
)
def check_fp8_width(k: int) -> None:
if type(k) is not int or k <= 0 or k % 128:
raise ValueError(
f"the fp8 row movers need positive K divisible by 128, got {k}"
)
@@ -0,0 +1,249 @@
"""Dispatch rows into aligned expert segments, optionally quantizing to FP8.
Negative expert IDs map to pair_to_row == -1, which every consumer skips.
Atomic slot order may vary, so every stage must use the same pair_to_row map.
"""
from __future__ import annotations
import torch
import triton
import triton.language as tl
from sglang.kernels.ops.lora.moe.dispatch_checks import (
check_fp8_width,
check_source_rows,
)
from sglang.kernels.ops.lora.moe.fp8_quant import quantize_fp8_groups
PAIRS_PER_PROGRAM = 8
def contiguous_m_pad_ceiling(num_pairs: int, num_experts: int, alignment: int) -> int:
"""Bound padded rows by allowing alignment - 1 extra rows per expert."""
raw = num_pairs + num_experts * (alignment - 1)
return -(-raw // alignment) * alignment
@triton.jit
def _count_slots_contiguous_kernel(
topk_ids_ptr, # [num_pairs]; a value < 0 marks a pair with no expert
slot_out_ptr, # [num_pairs] int32 out: slot of the pair inside its expert
seg_counts_ptr, # [E_local] int32 count and cursor; the caller must zero it
num_pairs,
PAIRS_PER_PROGRAM: tl.constexpr,
):
pairs = tl.program_id(0).to(tl.int64) * PAIRS_PER_PROGRAM + tl.arange(
0, PAIRS_PER_PROGRAM
)
in_range = pairs < num_pairs
experts = tl.load(topk_ids_ptr + pairs, mask=in_range, other=-1)
valid = in_range & (experts >= 0)
slots = tl.atomic_add(seg_counts_ptr + experts, 1, mask=valid)
tl.store(slot_out_ptr + pairs, slots, mask=valid)
@triton.jit
def _seg_layout_contiguous_kernel(
seg_counts_ptr, # [E_local] int32 per-expert routed-pair counts
seg_offsets_ptr, # [E_local + 1] int32 out: first row of each segment
ALIGN: tl.constexpr,
EXPERTS: tl.constexpr,
BLOCK_EXPERTS: tl.constexpr,
):
offs = tl.arange(0, BLOCK_EXPERTS)
counts = tl.load(seg_counts_ptr + offs, mask=offs < EXPERTS, other=0)
aligned = ((counts + (ALIGN - 1)) // ALIGN) * ALIGN
inclusive = tl.cumsum(aligned, axis=0)
tl.store(seg_offsets_ptr + offs, inclusive - aligned, mask=offs < EXPERTS)
tl.store(seg_offsets_ptr + EXPERTS, tl.sum(aligned))
@triton.jit
def _fill_rows_contiguous_bf16_kernel(
input_ptr, # [num_tokens, hidden] bf16 source rows
compact_ptr, # [m_pad_ceiling, hidden] bf16, viewed flat
topk_ids_ptr, # [num_pairs]
pair_to_row_ptr, # [num_pairs] int32 finalized compact rows
hidden_size,
num_pairs,
TOPK: tl.constexpr,
PAIRS_PER_PROGRAM: tl.constexpr,
BLOCK_H: tl.constexpr,
):
# Row copying consumes the map finalized by the preceding launch.
lane = tl.arange(0, PAIRS_PER_PROGRAM)
base = tl.program_id(0).to(tl.int64) * PAIRS_PER_PROGRAM
pairs = base + lane
in_range = pairs < num_pairs
experts_vec = tl.load(topk_ids_ptr + pairs, mask=in_range, other=-1)
if tl.sum((experts_vec >= 0).to(tl.int32), axis=0) == 0:
return
vec = tl.arange(0, BLOCK_H)
for i in tl.static_range(PAIRS_PER_PROGRAM):
pair = base + i
if pair < num_pairs:
expert = tl.load(topk_ids_ptr + pair)
if expert >= 0:
dst = tl.load(pair_to_row_ptr + pair).to(tl.int64)
token = pair // TOPK
src = input_ptr + token * hidden_size
out = compact_ptr + dst * hidden_size
for off in tl.range(0, hidden_size, BLOCK_H):
mask = off + vec < hidden_size
tl.store(
out + off + vec,
tl.load(src + off + vec, mask=mask),
mask=mask,
)
@triton.jit
def _finalize_pair_to_row_contiguous_kernel(
topk_ids_ptr, # [num_pairs]; a value < 0 marks a pair with no expert
pair_to_row_ptr, # [num_pairs] int32: dense slots IN, compact rows OUT
seg_offsets_ptr, # [E_local + 1] int32 first row of each segment
num_pairs,
PAIRS_PER_PROGRAM: tl.constexpr,
):
base = tl.program_id(0).to(tl.int64) * PAIRS_PER_PROGRAM
for i in tl.static_range(PAIRS_PER_PROGRAM):
pair = base + i
if pair < num_pairs:
expert = tl.load(topk_ids_ptr + pair)
if expert >= 0:
slot = tl.load(pair_to_row_ptr + pair)
seg_base = tl.load(seg_offsets_ptr + expert)
tl.store(pair_to_row_ptr + pair, seg_base + slot)
else:
# Finalize gates on this map, so invalid pairs must read as -1.
tl.store(pair_to_row_ptr + pair, -1)
def dispatch_layout_contiguous(
hidden_states: torch.Tensor,
topk_ids: torch.Tensor,
num_local_experts: int,
top_k: int,
alignment: int,
*,
seg_counts_out: torch.Tensor,
seg_offsets_out: torch.Tensor,
pair_to_row_out: torch.Tensor,
) -> None:
"""Write compact row indices to pair_to_row; row copies run separately."""
check_source_rows(hidden_states, topk_ids, top_k)
num_pairs = topk_ids.numel()
pair_grid = (-(-num_pairs // PAIRS_PER_PROGRAM),)
# Clear atomic cursors on every forward, including graph replay.
seg_counts_out.zero_()
if num_pairs > 0:
_count_slots_contiguous_kernel[pair_grid](
topk_ids.view(-1),
pair_to_row_out,
seg_counts_out,
num_pairs,
PAIRS_PER_PROGRAM=PAIRS_PER_PROGRAM,
)
# Initialize offsets even for an empty batch.
_seg_layout_contiguous_kernel[(1,)](
seg_counts_out,
seg_offsets_out,
ALIGN=alignment,
EXPERTS=num_local_experts,
BLOCK_EXPERTS=max(triton.next_power_of_2(num_local_experts), 2),
)
if num_pairs > 0:
_finalize_pair_to_row_contiguous_kernel[pair_grid](
topk_ids.view(-1),
pair_to_row_out,
seg_offsets_out,
num_pairs,
PAIRS_PER_PROGRAM=PAIRS_PER_PROGRAM,
)
def dispatch_fill_rows_contiguous_bf16(
hidden_states: torch.Tensor,
topk_ids: torch.Tensor,
pair_to_row: torch.Tensor,
*,
hidden_compact_out: torch.Tensor,
) -> None:
num_tokens = hidden_states.size(0)
num_pairs = topk_ids.numel()
if num_pairs == 0:
return
check_source_rows(hidden_states, topk_ids, num_pairs // num_tokens)
_fill_rows_contiguous_bf16_kernel[(-(-num_pairs // PAIRS_PER_PROGRAM),)](
hidden_states,
hidden_compact_out,
topk_ids.view(-1),
pair_to_row,
hidden_states.size(1),
num_pairs,
TOPK=num_pairs // num_tokens,
PAIRS_PER_PROGRAM=PAIRS_PER_PROGRAM,
BLOCK_H=1024,
)
@triton.jit
def _fill_rows_contiguous_fp8_kernel(
input_ptr, # bf16 [num_tokens, K] source rows
out_ptr, # fp8e4m3 [m_pad_ceiling, K] contiguous
scale_ptr, # fp32 [m_pad_ceiling, K // 128] contiguous
topk_ids_ptr, # [num_pairs]; < 0 = padding or EP-unrouted
pair_to_row_ptr, # [num_pairs] int32 finalized compact rows
TOPK: tl.constexpr,
K: tl.constexpr,
GROUPS: tl.constexpr, # K // 128
BLOCK_K: tl.constexpr,
):
# Quantize each token once, then fan out to its routed destinations.
token = tl.program_id(0)
offs = tl.arange(0, BLOCK_K)
x = tl.load(input_ptr + token.to(tl.int64) * K + offs, mask=offs < K, other=0).to(
tl.float32
)
grouped = tl.reshape(x, (BLOCK_K // 128, 128))
q, scale = quantize_fp8_groups(grouped, GROUPS == 1)
qf = tl.reshape(q, (BLOCK_K,)).to(out_ptr.dtype.element_ty)
goffs = tl.arange(0, BLOCK_K // 128)
for j in range(TOPK):
pair = token * TOPK + j
expert = tl.load(topk_ids_ptr + pair)
if expert >= 0:
dst = tl.load(pair_to_row_ptr + pair).to(tl.int64)
tl.store(out_ptr + dst * K + offs, qf, mask=offs < K)
tl.store(scale_ptr + dst * GROUPS + goffs, scale, mask=goffs < GROUPS)
def dispatch_fill_rows_contiguous_fp8(
hidden_states: torch.Tensor,
topk_ids: torch.Tensor,
pair_to_row: torch.Tensor,
*,
rows_fp8_out: torch.Tensor,
scale_out: torch.Tensor,
) -> None:
"""Quantize and copy rows using the finalized pair_to_row map."""
num_tokens, k = hidden_states.shape
num_pairs = topk_ids.numel()
if num_pairs == 0:
return
check_source_rows(hidden_states, topk_ids, num_pairs // num_tokens)
check_fp8_width(k)
_fill_rows_contiguous_fp8_kernel[(num_tokens,)](
hidden_states,
rows_fp8_out,
scale_out,
topk_ids.view(-1),
pair_to_row,
TOPK=num_pairs // num_tokens,
K=k,
GROUPS=k // 128,
BLOCK_K=triton.next_power_of_2(k),
)
@@ -0,0 +1,146 @@
"""Dispatch rows into [expert, m_max, hidden] slabs, optionally quantizing to FP8.
Negative expert IDs write pair_to_row == -1; consumers must skip those rows.
"""
from __future__ import annotations
import torch
import triton
import triton.language as tl
from sglang.kernels.ops.lora.moe.dispatch_checks import (
check_fp8_width,
check_source_rows,
)
from sglang.kernels.ops.lora.moe.fp8_quant import quantize_fp8_groups
@triton.jit
def _dispatch_fill_masked_bf16_kernel(
input_ptr, # [num_tokens, hidden] bf16 source rows
gateup_input_ptr, # [E_local, m_max, hidden] bf16 rows, viewed flat
topk_ids_ptr, # [num_tokens * topk]; < 0 = padding or EP-unrouted
pair_to_row_ptr, # [num_tokens * topk] int32 out; -1 for pairs without an expert
masked_m_ptr, # [E_local] int32 count and atomic cursor; caller zeroes it
m_max,
hidden_size,
TOPK: tl.constexpr,
BLOCK_H: tl.constexpr,
):
t = tl.program_id(0)
k = tl.program_id(1)
pair = t * TOPK + k
expert = tl.load(topk_ids_ptr + pair)
if expert < 0:
# The finalize gates on the row map: no expert reads as -1.
tl.store(pair_to_row_ptr + pair, -1)
else:
slot = tl.atomic_add(masked_m_ptr + expert, 1)
dst = expert.to(tl.int64) * m_max + slot
tl.store(pair_to_row_ptr + pair, dst.to(tl.int32))
src = input_ptr + t.to(tl.int64) * hidden_size
out = gateup_input_ptr + dst * hidden_size
vec = tl.arange(0, BLOCK_H)
for off in tl.range(0, hidden_size, BLOCK_H):
mask = off + vec < hidden_size
tl.store(out + off + vec, tl.load(src + off + vec, mask=mask), mask=mask)
def dispatch_fill_masked_bf16(
hidden_states: torch.Tensor,
topk_ids: torch.Tensor,
top_k: int,
*,
masked_m_out: torch.Tensor,
pair_to_row_out: torch.Tensor,
rows_out: torch.Tensor,
) -> None:
check_source_rows(hidden_states, topk_ids, top_k)
num_tokens = hidden_states.size(0)
# Clear atomic cursors on every forward, including graph replay.
masked_m_out.zero_()
if num_tokens > 0:
_dispatch_fill_masked_bf16_kernel[(num_tokens, top_k)](
hidden_states,
rows_out,
topk_ids.view(-1),
pair_to_row_out,
masked_m_out,
rows_out.size(1),
hidden_states.size(1),
TOPK=top_k,
BLOCK_H=1024,
)
@triton.jit
def _dispatch_fill_masked_fp8_kernel(
input_ptr, # bf16 [num_tokens, K] source rows
out_ptr, # fp8e4m3 [E, m_max, K] contiguous
scale_ptr, # fp32 [E, m_max, K // 128] contiguous
topk_ids_ptr, # [num_tokens * top_k]; < 0 = padding or EP-unrouted
pair_to_row_ptr, # [num_tokens * top_k] int32 out; -1 for pairs without an expert
masked_m_ptr, # [E] int32 count and atomic cursor; caller zeroes it
m_max,
TOPK: tl.constexpr,
K: tl.constexpr,
GROUPS: tl.constexpr, # K // 128
BLOCK_K: tl.constexpr,
):
t = tl.program_id(0)
k = tl.program_id(1)
pair = t * TOPK + k
expert = tl.load(topk_ids_ptr + pair)
if expert < 0:
tl.store(pair_to_row_ptr + pair, -1)
return
slot = tl.atomic_add(masked_m_ptr + expert, 1)
dst = expert.to(tl.int64) * m_max + slot
tl.store(pair_to_row_ptr + pair, dst.to(tl.int32))
offs = tl.arange(0, BLOCK_K)
x = tl.load(input_ptr + t.to(tl.int64) * K + offs, mask=offs < K, other=0).to(
tl.float32
)
grouped = tl.reshape(x, (BLOCK_K // 128, 128))
q, scale = quantize_fp8_groups(grouped, GROUPS == 1)
tl.store(
out_ptr + dst * K + offs,
tl.reshape(q, (BLOCK_K,)).to(out_ptr.dtype.element_ty),
mask=offs < K,
)
groups = tl.arange(0, BLOCK_K // 128)
tl.store(scale_ptr + dst * GROUPS + groups, scale, mask=groups < GROUPS)
def dispatch_fill_masked_fp8(
hidden_states: torch.Tensor,
topk_ids: torch.Tensor,
top_k: int,
*,
masked_m_out: torch.Tensor,
pair_to_row_out: torch.Tensor,
rows_fp8_out: torch.Tensor,
scale_out: torch.Tensor,
) -> None:
"""Dispatch FP8 rows with FP32 scales per group of 128 values."""
check_source_rows(hidden_states, topk_ids, top_k)
num_tokens, k = hidden_states.shape
check_fp8_width(k)
masked_m_out.zero_()
if num_tokens > 0:
_dispatch_fill_masked_fp8_kernel[(num_tokens, top_k)](
hidden_states,
rows_fp8_out,
scale_out,
topk_ids.view(-1),
pair_to_row_out,
masked_m_out,
rows_fp8_out.size(1),
TOPK=top_k,
K=k,
GROUPS=k // 128,
BLOCK_K=triton.next_power_of_2(k),
num_warps=4 if k <= 4096 else 8,
)
@@ -0,0 +1,183 @@
"""Prepare masked rows, pair maps and both GEMM schedules in one launch.
Admission is limited to small BF16 batches with one token cluster per expert.
"""
from __future__ import annotations
import torch
import triton
import triton.language as tl
from sglang.kernels.ops.lora.moe.cutedsl.schedule_builder import (
OUTPUT_CLUSTER_SHIFT,
)
from sglang.kernels.ops.lora.moe.dispatch_checks import check_source_rows
_SMALL_PREPARE_MAX_PAIRS = 32
# The narrowest decode token tile: with at most this many tokens every expert
# fits one token cluster whatever tile the provider picks.
_SMALL_PREPARE_MAX_TOKENS = 8
# Pairs per program: the row-copy tile is [_PPP, BLOCK_H] with at most 8192 elements.
_PPP = 8
def small_masked_prepare_applies(num_tokens: int, num_pairs: int) -> bool:
return (
0 < num_pairs <= _SMALL_PREPARE_MAX_PAIRS
and num_tokens <= _SMALL_PREPARE_MAX_TOKENS
)
@triton.jit
def _small_masked_prepare_kernel(
input_ptr, # bf16 [num_tokens, hidden]
rows_ptr, # bf16 [E, m_max, hidden]
topk_ids_ptr, # int32 [num_tokens * TOPK]; < 0 = no expert
pair_to_row_ptr, # int32 [num_tokens * TOPK] out
masked_m_ptr, # int32 [E] out: the per-expert counts
scratch_ptr, # int32 [2 * E_P2]: the stage begins per expert
schedule1_ptr,
tiles1_ptr,
schedule2_ptr,
tiles2_ptr,
num_pairs,
m_max,
hidden,
token_width,
out_clusters1,
out_clusters2,
E: tl.constexpr,
E_P2: tl.constexpr,
PAIRS: tl.constexpr,
PPP: tl.constexpr, # pairs whose rows one program moves
TOPK: tl.constexpr,
OC_P2: tl.constexpr,
BLOCK_H: tl.constexpr,
OUTPUT_SHIFT: tl.constexpr,
):
# A pair's slot in its expert is its rank among the expert's pairs (stable
# by pair id), so every program derives the same placement without atomics.
pid = tl.program_id(0)
p = tl.arange(0, PAIRS)
pmask = p < num_pairs
expert = tl.load(topk_ids_ptr + p, mask=pmask, other=-1)
live = pmask & (expert >= 0)
if pid == 0:
same = (expert[None, :] == expert[:, None]) & live[None, :] & live[:, None]
rank = tl.sum((same & (p[None, :] < p[:, None])).to(tl.int32), axis=1)
count = tl.sum(same.to(tl.int32), axis=1)
head = live & (rank == 0)
e_safe = tl.where(live, expert, 0)
dst = e_safe.to(tl.int64) * m_max + rank
bins = tl.arange(0, E_P2)
tl.store(masked_m_ptr + bins, tl.zeros([E_P2], dtype=tl.int32), mask=bins < E)
tl.debug_barrier()
tl.store(masked_m_ptr + e_safe, count, mask=head)
tl.debug_barrier()
counts = tl.load(
masked_m_ptr + bins, mask=bins < E, other=0, cache_modifier=".cg"
)
clusters = (counts + token_width - 1) // token_width # one per touched expert
ent1 = clusters * out_clusters1
ent2 = clusters * out_clusters2
tl.store(scratch_ptr + bins, tl.cumsum(ent1, axis=0) - ent1)
tl.store(scratch_ptr + E_P2 + bins, tl.cumsum(ent2, axis=0) - ent2)
tl.store(tiles1_ptr, tl.sum(ent1, axis=0))
tl.store(tiles2_ptr, tl.sum(ent2, axis=0))
tl.debug_barrier()
tl.store(pair_to_row_ptr + p, tl.where(live, dst, -1).to(tl.int32), mask=pmask)
# The first row of each touched expert writes the expert's entries:
# one token cluster (index 0) times the stage's output clusters.
begin1 = tl.load(scratch_ptr + e_safe, cache_modifier=".cg")
begin2 = tl.load(scratch_ptr + E_P2 + e_safe, cache_modifier=".cg")
oc = tl.arange(0, OC_P2)
packed = (
expert.to(tl.int64)[:, None] | (oc.to(tl.int64) << OUTPUT_SHIFT)[None, :]
)
tl.store(
schedule1_ptr + begin1[:, None] + oc[None, :],
packed,
mask=head[:, None] & (oc < out_clusters1)[None, :],
)
tl.store(
schedule2_ptr + begin2[:, None] + oc[None, :],
packed,
mask=head[:, None] & (oc < out_clusters2)[None, :],
)
# Rows: this program moves pairs [pid * PPP, (pid + 1) * PPP) as one
# [PPP, BLOCK_H] tile per column chunk.
q = pid * PPP + tl.arange(0, PPP)
qmask = q < num_pairs
my_expert = tl.load(topk_ids_ptr + q, mask=qmask, other=-1)
my_live = qmask & (my_expert >= 0)
my_rank = tl.sum(
(
(expert[None, :] == my_expert[:, None])
& live[None, :]
& (p[None, :] < q[:, None])
).to(tl.int32),
axis=1,
)
my_dst = tl.where(my_live, my_expert, 0).to(tl.int64) * m_max + my_rank
src = input_ptr + (q // TOPK).to(tl.int64)[:, None] * hidden
out = rows_ptr + my_dst[:, None] * hidden
for off in tl.range(0, hidden, BLOCK_H):
cols = off + tl.arange(0, BLOCK_H)
m = my_live[:, None] & (cols < hidden)[None, :]
tl.store(out + cols[None, :], tl.load(src + cols[None, :], mask=m), mask=m)
def small_masked_prepare(
hidden_states: torch.Tensor,
topk_ids: torch.Tensor,
top_k: int,
*,
masked_m_out: torch.Tensor,
pair_to_row_out: torch.Tensor,
rows_out: torch.Tensor,
scratch: torch.Tensor,
token_width: int,
out_clusters1: int,
out_clusters2: int,
schedule1_out: torch.Tensor,
tiles1_out: torch.Tensor,
schedule2_out: torch.Tensor,
tiles2_out: torch.Tensor,
) -> None:
check_source_rows(hidden_states, topk_ids, top_k)
hidden = hidden_states.size(1)
num_pairs = topk_ids.numel()
num_experts = masked_m_out.numel()
e_p2 = max(16, triton.next_power_of_2(num_experts))
if scratch.numel() < 2 * e_p2:
raise ValueError("the small prepare needs a 2 x E_P2 int32 scratch")
pairs = max(16, triton.next_power_of_2(num_pairs))
block_h = max(128, triton.next_power_of_2(min(hidden, 8192 // _PPP)))
_small_masked_prepare_kernel[(triton.cdiv(num_pairs, _PPP),)](
hidden_states,
rows_out,
topk_ids.view(-1),
pair_to_row_out,
masked_m_out,
scratch,
schedule1_out,
tiles1_out,
schedule2_out,
tiles2_out,
num_pairs,
rows_out.size(1),
hidden,
token_width,
out_clusters1,
out_clusters2,
E=num_experts,
E_P2=e_p2,
PAIRS=pairs,
PPP=_PPP,
TOPK=top_k,
OC_P2=max(2, triton.next_power_of_2(max(out_clusters1, out_clusters2))),
BLOCK_H=block_h,
OUTPUT_SHIFT=OUTPUT_CLUSTER_SHIFT,
num_warps=8,
)
@@ -0,0 +1,423 @@
"""Materialized and shared-outer weighted finalizers.
The one-pass path keeps the rank sum and delta in FP32; the staged path rounds
them to buffer dtypes. Neither is bitwise equivalent to per-pair BF16 deltas.
"""
from __future__ import annotations
from collections.abc import Mapping
import torch
import triton
import triton.language as tl
from sglang.kernels.ops.lora.common.route_view import RouteView
@triton.jit
def _shared_token_delta_reduce_kernel(
bridge_ptr,
token_rank_ptr,
weights_ptr,
topk_ids_ptr,
token_lora_mapping_ptr,
num_tokens,
stride_xm,
stride_xk,
stride_tm,
stride_tk,
stride_wm,
stride_wk,
rank: tl.constexpr,
top_k: tl.constexpr,
max_loras: tl.constexpr,
local_expert_count: tl.constexpr,
block_t: tl.constexpr,
block_r: tl.constexpr,
):
tokens = tl.program_id(0) * block_t + tl.arange(0, block_t)
token_mask = tokens < num_tokens
tokens64 = tokens.to(tl.int64)
rank_offsets = tl.arange(0, block_r).to(tl.int64)
rank_mask = rank_offsets < rank
adapter = tl.load(token_lora_mapping_ptr + tokens, mask=token_mask, other=-1)
adapter_valid = (adapter >= 0) & (adapter < max_loras)
acc = tl.zeros((block_t, block_r), tl.float32)
for k in range(top_k):
pairs = tokens * top_k + k
expert = tl.load(topk_ids_ptr + pairs, mask=token_mask, other=-1)
valid = (
token_mask & adapter_valid & (expert >= 0) & (expert < local_expert_count)
)
weight = tl.load(
weights_ptr + tokens64 * stride_wm + k * stride_wk,
mask=valid,
other=0.0,
).to(tl.float32)
x = tl.load(
bridge_ptr
+ pairs.to(tl.int64)[:, None] * stride_xm
+ rank_offsets[None, :] * stride_xk,
mask=valid[:, None] & rank_mask[None, :],
other=0.0,
)
acc += weight[:, None] * x.to(tl.float32)
tl.store(
token_rank_ptr
+ tokens64[:, None] * stride_tm
+ rank_offsets[None, :] * stride_tk,
acc.to(token_rank_ptr.dtype.element_ty),
mask=token_mask[:, None] & rank_mask[None, :],
)
@triton.jit
def _shared_token_delta_tail_kernel(
down_ptr,
pair_to_row_ptr,
token_delta_ptr,
output_ptr,
weights_ptr,
topk_ids_ptr,
token_lora_mapping_ptr,
stride_dm,
stride_dh,
stride_om,
stride_oh,
stride_wm,
stride_wk,
stride_tdm,
stride_tdh,
routed_scaling,
num_local_experts: tl.constexpr,
hidden: tl.constexpr,
top_k: tl.constexpr,
max_loras: tl.constexpr,
block_h: tl.constexpr,
):
# Apply routed scaling once, after adding base and LoRA.
token = tl.program_id(0)
pid_h = tl.program_id(1)
token64 = token.to(tl.int64)
h_offsets = pid_h.to(tl.int64) * block_h + tl.arange(0, block_h).to(tl.int64)
h_mask = h_offsets < hidden
base_acc = tl.zeros((block_h,), tl.float32)
for k in range(top_k):
pair = token * top_k + k
expert = tl.load(topk_ids_ptr + pair)
valid = (expert >= 0) & (expert < num_local_experts)
dst = tl.load(pair_to_row_ptr + pair, mask=valid, other=0).to(tl.int64)
base = tl.load(
down_ptr + dst * stride_dm + h_offsets * stride_dh,
mask=valid & h_mask,
other=0.0,
).to(tl.float32)
weight = tl.load(
weights_ptr + token64 * stride_wm + k * stride_wk,
mask=valid,
other=0.0,
).to(tl.float32)
base_acc += weight * base
adapter = tl.load(token_lora_mapping_ptr + token)
adapter_valid = (adapter >= 0) & (adapter < max_loras)
delta = tl.load(
token_delta_ptr + token64 * stride_tdm + h_offsets * stride_tdh,
mask=adapter_valid & h_mask,
other=0.0,
).to(tl.float32)
tl.store(
output_ptr + token64 * stride_om + h_offsets * stride_oh,
(routed_scaling * (base_acc + tl.where(adapter_valid, delta, 0.0))).to(
output_ptr.dtype.element_ty
),
mask=h_mask,
)
@triton.jit
def _shared_one_pass_kernel(
down_ptr, # [rows, H] provider row order, unweighted
pair_to_row_ptr, # [M * top_k] raw pair -> provider row
bridge_ptr, # [M * top_k, R] raw pair order, unweighted
weights_ptr,
b_ptr, # [S, H, R]
topk_ids_ptr,
token_lora_mapping_ptr,
output_ptr,
stride_dm,
stride_dh,
stride_xm,
stride_xr,
stride_wm,
stride_wk,
stride_bs,
stride_bh,
stride_br,
stride_om,
stride_oh,
routed_scaling,
num_local_experts: tl.constexpr,
hidden: tl.constexpr,
rank: tl.constexpr,
top_k: tl.constexpr,
max_loras: tl.constexpr,
block_h: tl.constexpr,
block_r: tl.constexpr,
):
"""Weight and combine unweighted base and rank rows, then apply shared B."""
token = tl.program_id(0)
pid_h = tl.program_id(1)
token64 = token.to(tl.int64)
h_offsets = pid_h.to(tl.int64) * block_h + tl.arange(0, block_h).to(tl.int64)
h_mask = h_offsets < hidden
r_offsets = tl.arange(0, block_r).to(tl.int64)
r_mask = r_offsets < rank
base_acc = tl.zeros((block_h,), tl.float32)
rank_acc = tl.zeros((block_r,), tl.float32)
for k in tl.static_range(top_k):
pair = token64 * top_k + k
expert = tl.load(topk_ids_ptr + pair)
valid = (expert >= 0) & (expert < num_local_experts)
dst = tl.load(pair_to_row_ptr + pair, mask=valid, other=0).to(tl.int64)
weight = tl.load(
weights_ptr + token64 * stride_wm + k * stride_wk, mask=valid, other=0.0
).to(tl.float32)
base = tl.load(
down_ptr + dst * stride_dm + h_offsets * stride_dh,
mask=valid & h_mask,
other=0.0,
).to(tl.float32)
rank_row = tl.load(
bridge_ptr + pair * stride_xm + r_offsets * stride_xr,
mask=valid & r_mask,
other=0.0,
).to(tl.float32)
base_acc += weight * base
rank_acc += weight * rank_row
adapter = tl.load(token_lora_mapping_ptr + token)
adapter_valid = (adapter >= 0) & (adapter < max_loras)
safe_adapter = tl.maximum(adapter, 0).to(tl.int64)
b = tl.load(
b_ptr
+ safe_adapter * stride_bs
+ h_offsets[:, None] * stride_bh
+ r_offsets[None, :] * stride_br,
mask=adapter_valid & h_mask[:, None] & r_mask[None, :],
other=0.0,
)
delta = tl.sum(b.to(tl.float32) * rank_acc[None, :], axis=1)
tl.store(
output_ptr + token64 * stride_om + h_offsets * stride_oh,
(routed_scaling * (base_acc + tl.where(adapter_valid, delta, 0.0))).to(
output_ptr.dtype.element_ty
),
mask=h_mask,
)
def invoke_shared_token_delta_reduce(
*,
num_local_experts: int,
bridge: torch.Tensor,
routing: RouteView,
topk_weights: torch.Tensor,
token_rank: torch.Tensor,
config: Mapping[str, int],
) -> None:
num_tokens, top_k = routing.num_tokens, routing.width
if num_tokens == 0:
return
rank = bridge.shape[1]
block_t = int(config["BLOCK_SIZE_T"])
_shared_token_delta_reduce_kernel[(triton.cdiv(num_tokens, block_t),)](
bridge,
token_rank,
topk_weights,
routing.group_ids,
routing.token_slots,
num_tokens,
bridge.stride(0),
bridge.stride(1),
token_rank.stride(0),
token_rank.stride(1),
topk_weights.stride(0),
topk_weights.stride(1),
rank=rank,
top_k=top_k,
max_loras=routing.max_loras,
local_expert_count=num_local_experts,
block_t=block_t,
block_r=max(16, triton.next_power_of_2(rank)),
num_warps=int(config["num_warps"]),
num_stages=int(config["num_stages"]),
)
def invoke_shared_token_delta_tail(
*,
num_local_experts: int,
down_rows: torch.Tensor,
pair_to_row: torch.Tensor,
token_delta: torch.Tensor,
routing: RouteView,
topk_weights: torch.Tensor,
routed_scaling_factor: float | None,
output: torch.Tensor,
config: Mapping[str, int],
) -> None:
num_tokens = routing.num_tokens
if num_tokens == 0:
return
hidden = down_rows.shape[-1]
block_h = int(config["BLOCK_SIZE_H"])
_shared_token_delta_tail_kernel[(num_tokens, triton.cdiv(hidden, block_h))](
down_rows.view(-1, hidden),
pair_to_row,
token_delta,
output,
topk_weights,
routing.group_ids,
routing.token_slots,
down_rows.stride(-2),
down_rows.stride(-1),
output.stride(0),
output.stride(1),
topk_weights.stride(0),
topk_weights.stride(1),
token_delta.stride(0),
token_delta.stride(1),
1.0 if routed_scaling_factor is None else routed_scaling_factor,
num_local_experts=num_local_experts,
hidden=hidden,
top_k=routing.width,
max_loras=routing.max_loras,
block_h=block_h,
num_warps=int(config["num_warps"]),
num_stages=int(config["num_stages"]),
)
def invoke_shared_one_pass(
*,
num_local_experts: int,
down_rows: torch.Tensor,
pair_to_row: torch.Tensor,
bridge: torch.Tensor,
b_down: torch.Tensor,
routing: RouteView,
topk_weights: torch.Tensor,
routed_scaling_factor: float | None,
output: torch.Tensor,
config: Mapping[str, int],
) -> None:
num_tokens, top_k = routing.num_tokens, routing.width
if num_tokens == 0:
return
hidden = down_rows.shape[-1]
rank = bridge.shape[-1]
block_h = int(config["BLOCK_SIZE_H"])
_shared_one_pass_kernel[(num_tokens, triton.cdiv(hidden, block_h))](
down_rows.view(-1, hidden),
pair_to_row,
bridge,
topk_weights,
b_down,
routing.group_ids,
routing.token_slots,
output,
down_rows.stride(-2),
down_rows.stride(-1),
bridge.stride(0),
bridge.stride(1),
topk_weights.stride(0),
topk_weights.stride(1),
b_down.stride(0),
b_down.stride(1),
b_down.stride(2),
output.stride(0),
output.stride(1),
1.0 if routed_scaling_factor is None else routed_scaling_factor,
num_local_experts=num_local_experts,
hidden=hidden,
rank=rank,
top_k=top_k,
max_loras=routing.max_loras,
block_h=block_h,
block_r=max(16, triton.next_power_of_2(rank)),
num_warps=int(config["num_warps"]),
num_stages=int(config["num_stages"]),
)
# Vectorize index/weight loads, retaining the shared finalizer's top-k sum order.
@triton.jit
def _small_finalize_kernel(
down_ptr, # [rows, H] base down rows (pair_to_row indexes them)
delta_ptr, # [T * TOPK, H] unweighted LoRA delta per pair (or down_ptr when absent)
out_ptr, # [T, H]
pair_to_row_ptr, # [T * TOPK]; < 0 = no row for this pair
topk_weights_ptr, # [T * TOPK] fp32
hidden,
scaling,
TOPK: tl.constexpr,
TOPK_P2: tl.constexpr,
HAS_DELTA: tl.constexpr,
BLOCK_H: tl.constexpr,
):
t = tl.program_id(0).to(tl.int64)
cols = tl.program_id(1) * BLOCK_H + tl.arange(0, BLOCK_H)
cmask = cols < hidden
ks = tl.arange(0, TOPK_P2)
kmask = ks < TOPK
rows = tl.load(pair_to_row_ptr + t * TOPK + ks, mask=kmask, other=-1).to(tl.int64)
weights = tl.load(topk_weights_ptr + t * TOPK + ks, mask=kmask, other=0.0).to(
tl.float32
)
acc = tl.zeros([BLOCK_H], dtype=tl.float32)
for k in tl.static_range(TOPK):
pick = ks == k
row = tl.sum(tl.where(pick, rows, 0), axis=0)
weight = tl.sum(tl.where(pick, weights, 0.0), axis=0)
live = row >= 0
x = tl.load(down_ptr + row * hidden + cols, mask=cmask & live, other=0.0).to(
tl.float32
)
if HAS_DELTA:
x += tl.load(
delta_ptr + (t * TOPK + k) * hidden + cols, mask=cmask & live, other=0.0
).to(tl.float32)
acc += x * weight
acc *= scaling
tl.store(out_ptr + t * hidden + cols, acc.to(out_ptr.dtype.element_ty), mask=cmask)
def invoke_small_finalize(
down_rows: torch.Tensor,
output: torch.Tensor,
pair_to_row: torch.Tensor,
topk_weights: torch.Tensor,
routed_scaling_factor: float,
*,
lora_delta: torch.Tensor | None,
block_h: int = 512,
) -> None:
num_tokens, hidden = output.shape
topk = topk_weights.shape[1]
_small_finalize_kernel[(num_tokens, triton.cdiv(hidden, block_h))](
down_rows,
down_rows if lora_delta is None else lora_delta,
output,
pair_to_row,
topk_weights,
hidden,
float(routed_scaling_factor),
TOPK=topk,
TOPK_P2=triton.next_power_of_2(topk),
HAS_DELTA=lora_delta is not None,
BLOCK_H=block_h,
num_warps=4,
)
@@ -0,0 +1,34 @@
"""Match upstream FP8 scale arithmetic, with zero codes for zero-scale rows.
Whole-row division uses fast math only on SM90; group quantization always does.
"""
from __future__ import annotations
import torch
import triton
import triton.language as tl
from triton.language.extra.cuda import libdevice
_WHOLE_ROW_FAST_DIV = tl.constexpr(
torch.cuda.is_available() and torch.cuda.get_device_capability() == (9, 0)
)
@triton.jit
def quantize_fp8_groups(grouped, WHOLE_ROW: tl.constexpr):
"""Return FP32 codes and per-group scales for [groups, group_size] input."""
amax = tl.max(tl.abs(grouped), axis=1)
if WHOLE_ROW:
if _WHOLE_ROW_FAST_DIV:
scale = amax / 448.0
inv = tl.where(scale == 0.0, 0.0, 1.0 / scale)
else:
scale = libdevice.div_rn(amax, 448.0)
inv = tl.where(scale == 0.0, 0.0, libdevice.div_rn(1.0, scale))
q = grouped * inv[:, None]
else:
amax = tl.maximum(amax, 1e-10)
scale = amax * (1.0 / 448.0)
q = grouped * (448.0 / amax)[:, None]
return tl.clamp(q, -448.0, 448.0), scale
@@ -0,0 +1,295 @@
"""Fuse gate/up LoRA-B with activation in either base row layout.
The delta stays FP32 through activation, unlike a materialized BF16 delta.
The optional pair-major copy serves down-A kernels that cannot gather base rows.
"""
from __future__ import annotations
from collections.abc import Mapping
import torch
import triton
import triton.language as tl
from sglang.kernels.ops.lora.common.route_view import RouteView
from sglang.kernels.ops.lora.common.routing import grouped_tile_coords
from sglang.kernels.ops.lora.moe.activation import ActivationFn
from sglang.kernels.ops.lora.moe.activation_delta import (
apply_activation,
)
@triton.jit
def _base_columns(
offsets,
width: tl.constexpr,
num_slices: tl.constexpr,
gate_first: tl.constexpr,
interleaved: tl.constexpr,
):
if num_slices == 1:
return offsets, offsets
if interleaved:
gate_offsets = 2 * offsets
up_offsets = 2 * offsets + 1
else:
gate_offsets = offsets
up_offsets = width + offsets
if not gate_first:
gate_offsets, up_offsets = up_offsets, gate_offsets
return gate_offsets, up_offsets
@triton.jit
def _delta_slice(
bridge_ptr,
weight_bucket_ptr,
bridge_rows,
pair_mask,
w_offsets,
w_mask,
stride_xm,
stride_xk,
stride_wn,
stride_wk,
slice_id: tl.constexpr,
rank: tl.constexpr,
width: tl.constexpr,
block_m: tl.constexpr,
block_w: tl.constexpr,
block_k: tl.constexpr,
):
acc = tl.zeros((block_m, block_w), tl.float32)
for k_begin in range(0, rank, block_k):
k_offsets = k_begin + tl.arange(0, block_k).to(tl.int64)
k_mask = k_offsets < rank
lhs = tl.load(
bridge_ptr
+ bridge_rows[:, None] * stride_xm
+ (slice_id * rank + k_offsets)[None, :] * stride_xk,
mask=pair_mask[:, None] & k_mask[None, :],
other=0.0,
)
rhs = tl.load(
weight_bucket_ptr
+ (slice_id * width + w_offsets)[None, :] * stride_wn
+ k_offsets[:, None] * stride_wk,
mask=k_mask[:, None] & w_mask[None, :],
other=0.0,
)
acc += tl.dot(lhs, rhs, out_dtype=tl.float32)
return acc
@triton.jit(do_not_specialize=["num_pairs", "num_m_blocks"])
def _b_act_kernel(
bridge_ptr,
b_ptr,
base_ptr,
act_rows_ptr,
act_pairs_ptr,
pair_to_row_ptr,
topk_ids_ptr,
sorted_pairs_ptr,
block_bucket_ids_ptr,
pairs_post_padded_ptr,
num_pairs,
stride_xm,
stride_xk,
stride_bg,
stride_bn,
stride_bk,
stride_pm,
stride_pn,
stride_am,
stride_an,
stride_qm,
stride_qn,
num_m_blocks,
num_local_experts: tl.constexpr,
top_k: tl.constexpr,
width: tl.constexpr,
rank: tl.constexpr,
num_slices: tl.constexpr,
activation_type: tl.constexpr,
gate_first: tl.constexpr,
interleaved: tl.constexpr,
bridge_token_major: tl.constexpr,
block_m: tl.constexpr,
block_w: tl.constexpr,
block_k: tl.constexpr,
group_m: tl.constexpr,
store_pair_act: tl.constexpr,
):
pid = tl.program_id(0)
# Keep the tile count constexpr for grouped scheduling.
num_w_tiles: tl.constexpr = (width + block_w - 1) // block_w
pid_m, pid_w = grouped_tile_coords(pid, num_w_tiles, num_m_blocks, group_m)
if pid_m * block_m >= tl.load(pairs_post_padded_ptr):
return
slots = pid_m * block_m + tl.arange(0, block_m).to(tl.int64)
pair_ids = tl.load(sorted_pairs_ptr + slots).to(tl.int64)
pair_mask = pair_ids < num_pairs
expert = tl.load(topk_ids_ptr + pair_ids, mask=pair_mask, other=-1)
base_valid = pair_mask & (expert >= 0) & (expert < num_local_experts)
dst_rows = tl.load(pair_to_row_ptr + pair_ids, mask=base_valid, other=0).to(
tl.int64
)
bucket_id = tl.load(block_bucket_ids_ptr + pid_m).to(tl.int64)
w_offsets = pid_w * block_w + tl.arange(0, block_w).to(tl.int64)
w_mask = w_offsets < width
gate_cols, up_cols = _base_columns(
w_offsets,
width,
num_slices,
gate_first,
interleaved,
)
delta_gate = tl.zeros((block_m, block_w), tl.float32)
delta_up = tl.zeros((block_m, block_w), tl.float32)
if bucket_id != -1:
bridge_rows = pair_ids // top_k if bridge_token_major else pair_ids
weight_bucket_ptr = b_ptr + bucket_id * stride_bg
delta_gate += _delta_slice(
bridge_ptr,
weight_bucket_ptr,
bridge_rows,
pair_mask,
w_offsets,
w_mask,
stride_xm,
stride_xk,
stride_bn,
stride_bk,
slice_id=0,
rank=rank,
width=width,
block_m=block_m,
block_w=block_w,
block_k=block_k,
)
if num_slices == 2:
delta_up += _delta_slice(
bridge_ptr,
weight_bucket_ptr,
bridge_rows,
pair_mask,
w_offsets,
w_mask,
stride_xm,
stride_xk,
stride_bn,
stride_bk,
slice_id=1,
rank=rank,
width=width,
block_m=block_m,
block_w=block_w,
block_k=block_k,
)
base_gate = tl.load(
base_ptr + dst_rows[:, None] * stride_pm + gate_cols[None, :] * stride_pn,
mask=base_valid[:, None] & w_mask[None, :],
other=0.0,
).to(tl.float32)
act = apply_activation(base_gate + delta_gate, activation_type)
if num_slices == 2:
base_up = tl.load(
base_ptr + dst_rows[:, None] * stride_pm + up_cols[None, :] * stride_pn,
mask=base_valid[:, None] & w_mask[None, :],
other=0.0,
).to(tl.float32)
act = act * (base_up + delta_up)
value = act.to(act_rows_ptr.dtype.element_ty)
tl.store(
act_rows_ptr + dst_rows[:, None] * stride_am + w_offsets[None, :] * stride_an,
value,
mask=base_valid[:, None] & w_mask[None, :],
)
if store_pair_act:
# Invalid pairs must overwrite stale graph-buffer rows with zero.
tl.store(
act_pairs_ptr
+ pair_ids[:, None] * stride_qm
+ w_offsets[None, :] * stride_qn,
tl.where(base_valid[:, None], act, 0.0).to(act_pairs_ptr.dtype.element_ty),
mask=pair_mask[:, None] & w_mask[None, :],
)
def fused_b_act(
*,
activation: str,
base_gateup: torch.Tensor,
act_rows: torch.Tensor,
act_pairs: torch.Tensor | None, # [num_tokens, top_k, width] or None
pair_to_row: torch.Tensor, # [num_tokens * top_k] int32
routing: RouteView,
num_local_experts: int,
gate_first: bool,
interleaved: bool,
config: Mapping[str, int],
bridge_gateup: torch.Tensor,
b_gate_up: torch.Tensor,
bridge_top_k: int = 1,
) -> None:
"""Fuse LoRA-B and activation in either provider row layout."""
ActivationFn.parse(activation)
pairs = routing.num_rows
if pairs == 0:
return
base_rows = base_gateup.view(-1, base_gateup.shape[-1])
act_rows = act_rows.view(-1, act_rows.shape[-1])
width = act_rows.shape[1]
slices = base_rows.shape[1] // width
rank = b_gate_up.shape[2]
block_w = int(config["BLOCK_SIZE_W"])
num_m_blocks = triton.cdiv(routing.sorted_pair_ids.numel(), routing.block_size)
pair_target = act_pairs.view(-1, width) if act_pairs is not None else act_rows
num_w_tiles = triton.cdiv(width, block_w)
_b_act_kernel[(num_m_blocks * num_w_tiles,)](
bridge_gateup,
b_gate_up,
base_rows,
act_rows,
pair_target,
pair_to_row,
routing.group_ids,
routing.sorted_pair_ids,
routing.block_bucket_ids,
routing.num_pairs_post_padded,
pairs,
bridge_gateup.stride(0),
bridge_gateup.stride(1),
b_gate_up.stride(0),
b_gate_up.stride(1),
b_gate_up.stride(2),
base_rows.stride(0),
base_rows.stride(1),
act_rows.stride(0),
act_rows.stride(1),
pair_target.stride(0),
pair_target.stride(1),
num_m_blocks=num_m_blocks,
num_local_experts=num_local_experts,
top_k=routing.width,
width=width,
rank=rank,
num_slices=slices,
activation_type=activation,
gate_first=gate_first,
interleaved=interleaved,
bridge_token_major=bridge_top_k != 1,
block_m=routing.block_size,
block_w=block_w,
block_k=int(config["BLOCK_SIZE_K"]),
group_m=int(config["GROUP_SIZE_M"]),
store_pair_act=act_pairs is not None,
num_warps=int(config["num_warps"]),
num_stages=int(config["num_stages"]),
)
@@ -0,0 +1,229 @@
"""MoE LoRA-B dispatch over shared grouped/per-row expand kernels.
MoE slots are pre-scaled; every reachable delta cell is written. In-place
down-B uses the grouped kernel with provider row mappings.
"""
from __future__ import annotations
import functools
from collections.abc import Mapping, Sequence
from typing import TYPE_CHECKING
import torch
import triton
import triton.language as tl
from sglang.kernels.ops.lora.common import lora_b as shared
from sglang.kernels.ops.lora.common.route_view import RouteView
from sglang.kernels.ops.lora.common.routing import grouped_tile_coords
if TYPE_CHECKING:
from sglang.srt.lora.moe.plan import BSpec
@functools.lru_cache(maxsize=None)
def _rows(weight_rows: int, num_slices: int) -> tuple[int, ...]:
width = weight_rows // num_slices
return tuple(s * width for s in range(num_slices + 1))
def _geometry(
weight: torch.Tensor, destination_offsets: Sequence[int], config: Mapping[str, int]
) -> shared.SliceGeometry:
return shared.slice_geometry(
_rows(weight.shape[1], len(destination_offsets)),
config["BLOCK_SIZE_N"],
weight.device,
out_offsets=destination_offsets,
)
def grouped_lora_b(
bridge: torch.Tensor,
weight: torch.Tensor,
destination: torch.Tensor,
routing: RouteView,
*,
destination_offsets: Sequence[int],
config: Mapping[str, int],
pair_bridge: bool = True,
) -> None:
shared.grouped_lora_b(
bridge,
weight,
destination,
routing,
geometry=_geometry(weight, destination_offsets, config),
config=config,
add_inplace=False,
zero_sentinel=True,
pair_bridge=pair_bridge,
)
def run_lora_b(
spec: BSpec,
*,
bridge: torch.Tensor,
weight: torch.Tensor,
destination: torch.Tensor,
routing: RouteView,
destination_offsets: Sequence[int],
config: Mapping[str, int],
pair_bridge: bool = True,
slot_planes: bool = False,
) -> None:
"""``slot_planes``: ``bridge`` is [slots, tokens, N], one plane per
adapter slot (the token_dense shrink); only the per_row family reads it."""
family = spec.family.value
match family:
case "grouped":
grouped_lora_b(
bridge,
weight,
destination,
routing,
destination_offsets=destination_offsets,
config=config,
pair_bridge=pair_bridge,
)
case "per_row":
shared.per_row_lora_b(
bridge,
weight,
destination,
routing,
geometry=_geometry(weight, destination_offsets, config),
config=config,
add_inplace=False,
zero_sentinel=True,
pair_bridge=pair_bridge,
slot_planes=slot_planes,
)
case _:
raise NotImplementedError(f"no production LoRA-B executor for {family!r}")
@triton.jit(do_not_specialize=["num_pairs", "num_m_blocks"])
def _down_b_into_base_kernel(
bridge_ptr,
weight_ptr,
down_rows_ptr,
pair_to_row_ptr,
sorted_pair_ids_ptr,
block_bucket_ids_ptr,
num_pairs_post_padded_ptr,
num_pairs,
stride_bm,
stride_bk,
stride_wg,
stride_wn,
stride_wk,
stride_dm,
stride_dn,
num_m_blocks,
N_HIDDEN: tl.constexpr,
RANK: tl.constexpr,
BLOCK_SIZE_M: tl.constexpr,
BLOCK_SIZE_N: tl.constexpr,
BLOCK_SIZE_K: tl.constexpr,
GROUP_SIZE_M: tl.constexpr,
):
pid = tl.program_id(0)
num_pairs_post_padded = tl.load(num_pairs_post_padded_ptr)
num_pid_n: tl.constexpr = (N_HIDDEN + BLOCK_SIZE_N - 1) // BLOCK_SIZE_N
pid_m, pid_n = grouped_tile_coords(pid, num_pid_n, num_m_blocks, GROUP_SIZE_M)
if pid_m * BLOCK_SIZE_M >= num_pairs_post_padded:
return
bucket_id = tl.load(block_bucket_ids_ptr + pid_m).to(tl.int64)
if bucket_id == -1:
return
pair_slots = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M).to(tl.int64)
pair_ids = tl.load(sorted_pair_ids_ptr + pair_slots).to(tl.int64)
pair_mask = pair_ids < num_pairs
n_offsets = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N).to(tl.int64)
n_mask = n_offsets < N_HIDDEN
# Valid buckets exclude sentinel pairs whose pair_to_row was never written.
dest_rows = tl.load(pair_to_row_ptr + pair_ids, mask=pair_mask, other=0).to(
tl.int64
)
destination_ptrs = (
down_rows_ptr + dest_rows[:, None] * stride_dm + n_offsets[None, :] * stride_dn
)
store_mask = pair_mask[:, None] & n_mask[None, :]
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
for k_begin in range(0, RANK, BLOCK_SIZE_K):
k_offsets = k_begin + tl.arange(0, BLOCK_SIZE_K).to(tl.int64)
k_mask = k_offsets < RANK
lhs = tl.load(
bridge_ptr + pair_ids[:, None] * stride_bm + k_offsets[None, :] * stride_bk,
mask=pair_mask[:, None] & k_mask[None, :],
other=0.0,
)
rhs = tl.load(
weight_ptr
+ bucket_id * stride_wg
+ n_offsets[None, :] * stride_wn
+ k_offsets[:, None] * stride_wk,
mask=n_mask[None, :] & k_mask[:, None],
other=0.0,
)
accumulator += tl.dot(lhs, rhs, out_dtype=tl.float32)
base = tl.load(destination_ptrs, mask=store_mask, other=0.0).to(tl.float32)
tl.store(
destination_ptrs,
(base + accumulator).to(down_rows_ptr.dtype.element_ty),
mask=store_mask,
)
def invoke_down_b_into_base(
*,
down_rows: torch.Tensor,
pair_to_row: torch.Tensor,
bridge: torch.Tensor,
b_down: torch.Tensor,
routing: RouteView,
config: Mapping[str, int],
) -> None:
"""Add down-B into base rows addressed by pair_to_row."""
num_tokens, top_k = routing.num_tokens, routing.width
pairs = num_tokens * top_k
hidden = down_rows.shape[1]
rank = bridge.shape[1]
if pairs == 0:
return
block_size_n = int(config["BLOCK_SIZE_N"])
num_m_blocks = triton.cdiv(routing.sorted_pair_ids.numel(), routing.block_size)
num_pid_n = triton.cdiv(hidden, block_size_n)
_down_b_into_base_kernel[(num_m_blocks * num_pid_n,)](
bridge,
b_down,
down_rows,
pair_to_row,
routing.sorted_pair_ids,
routing.block_bucket_ids,
routing.num_pairs_post_padded,
pairs,
bridge.stride(0),
bridge.stride(1),
b_down.stride(0),
b_down.stride(1),
b_down.stride(2),
down_rows.stride(0),
down_rows.stride(1),
num_m_blocks=num_m_blocks,
N_HIDDEN=hidden,
RANK=rank,
BLOCK_SIZE_M=routing.block_size,
BLOCK_SIZE_N=block_size_n,
BLOCK_SIZE_K=int(config["BLOCK_SIZE_K"]),
GROUP_SIZE_M=int(config["GROUP_SIZE_M"]),
num_warps=int(config["num_warps"]),
num_stages=int(config["num_stages"]),
)
@@ -306,18 +306,16 @@ def _align_block_size_jit(
topk_ids: torch.Tensor,
block_size: int,
num_experts: int,
scratch=None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""CUDA JIT align_block_size for num_experts > 1024 (up to 8191).
Uses the v2 kernel from moe_align_kernel.cu which supports large expert
counts via per-thread multi-expert processing and a two-level warp scan,
replacing the previous pure-PyTorch fallback that had excessive CPU overhead
from 15+ individual kernel launches and torch.argsort.
The v2 kernel in moe_align_kernel.cu uses per-thread multi-expert processing
and a two-level warp scan. IDs are shifted by +1 so the EP sentinel (-1)
maps to bucket 0.
The JIT kernel uses a +1 offset convention: topk_ids are shifted by +1 so
that the EP sentinel value (-1) maps to bucket 0. The kernel internally
handles histogram, padded prefix-sum, expert_ids assignment, and token
scattering in just 2–3 CUDA kernel launches.
``scratch(numel)`` returns the int32 scratch buffer (default: a fresh
allocation); a caller under CUDA graphs passes a persistent buffer.
"""
assert num_experts <= 8191, (
f"_align_block_size_jit supports at most 8191 experts "
@@ -362,7 +360,11 @@ def _align_block_size_jit(
+ num_post_pad_size
+ cumsum_size
)
buf = torch.empty(total_buf, dtype=torch.int32, device=device)
buf = (
torch.empty(total_buf, dtype=torch.int32, device=device)
if scratch is None
else scratch(total_buf)
)
off = 0
sorted_token_ids = buf[off : off + max_num_tokens_padded]
off += max_num_tokens_padded
@@ -898,9 +898,22 @@ def post_reorder_for_cutlass_moe(
)
def _check_out_buffer(tensor, shape, device, name: str) -> None:
if (
tuple(tensor.shape) != tuple(shape)
or tensor.device != device
or not tensor.is_contiguous()
):
raise ValueError(
f"{name} must be contiguous {tuple(shape)} on {device}; got "
f"{tensor.dtype} {tuple(tensor.shape)} on {tensor.device}"
)
@triton.jit
def post_reorder_deepgemm_triton_kernel(
down_output_ptr,
lora_delta_ptr,
output_ptr,
src2dst_ptr,
topk_ids_ptr,
@@ -909,10 +922,13 @@ def post_reorder_deepgemm_triton_kernel(
num_tokens,
hidden_size,
routed_scaling_factor: float,
HAS_LORA_DELTA: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
NUM_STAGES: tl.constexpr,
):
"""Accumulate valid permuted rows; routed_scaling_factor is folded into the store."""
"""Sum weight * (base + delta) over valid pairs, then apply routed scaling.
Delta is unweighted and indexed by [token, top-k, hidden].
"""
OutDtype = output_ptr.dtype.element_ty
offset = BLOCK_SIZE * tl.program_id(1) + tl.arange(0, BLOCK_SIZE)
@@ -939,6 +955,10 @@ def post_reorder_deepgemm_triton_kernel(
weight_scale = tl.load(token_topk_weights_ptr + idx).to(tl.float32)
load_ptr_offs = down_output_ptr_offs + dst_idx * hidden_size
in_data = tl.load(load_ptr_offs, mask=mask).to(tl.float32)
if HAS_LORA_DELTA:
slot_idx = src_idx * topk + idx
delta_ptr_offs = lora_delta_ptr + slot_idx * hidden_size + offset
in_data += tl.load(delta_ptr_offs, mask=mask).to(tl.float32)
sum_vec += in_data * weight_scale
sum_vec *= routed_scaling_factor
store_ptr_offs = output_ptr_offs + src_idx * hidden_size
@@ -955,10 +975,19 @@ def post_reorder_deepgemm(
num_tokens,
hidden_size,
routed_scaling_factor: float,
lora_delta=None,
):
if lora_delta is not None:
_check_out_buffer(
lora_delta,
(num_tokens, topk, hidden_size),
down_output.device,
"lora_delta",
)
grid, block_dim = _get_launch_config_2d(down_output.device, num_tokens, hidden_size)
post_reorder_deepgemm_triton_kernel[grid](
down_output,
down_output if lora_delta is None else lora_delta,
output,
src2dst,
topk_ids,
@@ -967,6 +996,7 @@ def post_reorder_deepgemm(
num_tokens,
hidden_size,
float(routed_scaling_factor),
HAS_LORA_DELTA=lora_delta is not None,
BLOCK_SIZE=block_dim,
NUM_STAGES=3,
)
+3
View File
@@ -150,6 +150,9 @@ MOE_RUNNER_BACKEND_CHOICES = [
"marlin",
"humming",
"experimental_sgl_marlin",
"lora_cutedsl",
"lora_triton",
"lora_marlin",
"hpc_ops", # HPC-Ops (https://github.com/Tencent/hpc-ops), FP8 MoE on Hopper (SM90) only
"megamoe",
"intel_xpu",
+1 -1
View File
@@ -78,7 +78,7 @@ class Lora(msgspec.Struct):
str,
Arg(
help="Choose the kernel backend for multi-LoRA serving.",
choices=["triton", "csgmv", "ascend", "torch_native"],
choices=["triton", "csgmv", "ascend", "torch_native", "triton_v2"],
),
] = "csgmv"
max_lora_chunk_size: A[
+78
View File
@@ -12,10 +12,24 @@ from sglang.srt.arg_groups.overrides import (
)
from sglang.srt.environ import envs
from sglang.srt.lora.lora_registry import LoRARef
from sglang.srt.runtime_context import get_platform
logger = logging.getLogger(__name__)
def _check_v2_lora_modes(cfg: Any, option: str):
for unsupported, mode in (
(cfg.attn_dp_size > 1, "DP-attention with --attn-dp-size > 1"),
(cfg.enable_pdmux, "PD-multiplexing"),
(cfg.enable_two_batch_overlap, "two-batch overlap"),
# Both reach the legacy kv_b correction kernels with V2 batch metadata.
(envs.SGLANG_EXPERIMENTAL_LORA_OPTI.get(), "SGLANG_EXPERIMENTAL_LORA_OPTI"),
(get_platform().is_hip, "ROCm"),
):
if unsupported:
raise ValueError(f"{option} does not yet support {mode}")
def check_lora_server_args(server_args: Any):
cfg = resolving_view(server_args)
@@ -34,6 +48,11 @@ def check_lora_server_args(server_args: Any):
)
if cfg.enable_lora:
if cfg.lora_backend == "triton_v2" and not cfg.moe_runner_backend.startswith(
"lora"
):
_check_v2_lora_modes(cfg, "--lora-backend triton_v2")
if cfg.enable_lora_overlap_loading is None:
declare_resolution(
server_args, "check_lora_server_args", enable_lora_overlap_loading=False
@@ -158,6 +177,65 @@ def check_lora_server_args(server_args: Any):
"--lora-drain-wait-threshold must be non-negative."
)
check_lora_moe_runner_args(server_args)
def check_lora_moe_runner_args(server_args: Any):
"""Reject unsupported LoRA MoE configurations before layer attachment."""
cfg = resolving_view(server_args)
if (
cfg.speculative_algorithm is not None
and cfg.speculative_moe_runner_backend is not None
and cfg.speculative_moe_runner_backend.startswith("lora")
):
# Draft models have no LoRA adapters.
raise ValueError(
f"--speculative-moe-runner-backend {cfg.speculative_moe_runner_backend} "
"is not supported: the LoRA MoE runner serves adapter traffic on the "
"target model"
)
backend = cfg.moe_runner_backend
if not backend.startswith("lora"):
return
if not cfg.enable_lora:
raise ValueError(
f"--moe-runner-backend {backend} requires --enable-lora (or --lora-paths)"
)
if cfg.lora_backend != "triton_v2":
raise ValueError(
f"--moe-runner-backend {backend} requires --lora-backend triton_v2"
)
_check_v2_lora_modes(cfg, f"--moe-runner-backend {backend}")
# Layer attachment checks the specific weight layout within each scheme.
if cfg.quantization not in (None, "fp8", "modelopt_fp4"):
raise ValueError(
f"--moe-runner-backend {backend} supports unquantized BF16, 128-block "
f"FP8 and ModelOpt NVFP4 MoE, got --quantization {cfg.quantization}"
)
if cfg.quantization == "modelopt_fp4" and backend != "lora_marlin":
raise ValueError(
f"--moe-runner-backend {backend} cannot run ModelOpt NVFP4 MoE; "
"use --moe-runner-backend lora_marlin"
)
if cfg.moe_a2a_backend != "none":
raise ValueError(
f"--moe-runner-backend {backend} requires Standard dispatch, "
f"got --moe-a2a-backend {cfg.moe_a2a_backend}"
)
if cfg.ep_join_mode is not None:
raise ValueError(
f"--moe-runner-backend {backend} does not yet support elastic EP"
)
if (
cfg.enable_eplb
or cfg.init_expert_location != "trivial"
or cfg.ep_num_redundant_experts > 0
):
raise ValueError(
f"--moe-runner-backend {backend} currently requires trivial expert placement "
"without EPLB or redundant experts"
)
def check_lora_speculative_compatibility(server_args: Any):
"""Validate LoRA + speculative decoding combinations.
@@ -1532,6 +1532,9 @@ def _moe_runner_fusion_disable(view: Any) -> dict:
Runs before the deprecated cutlass environment override.
"""
runner = view.moe_runner_backend
if runner in ("lora_triton", "lora_cutedsl", "lora_marlin"):
logger.warning("LoRA MoE keeps shared experts separate for adapter attachment.")
return {"disable_shared_experts_fusion": True}
if runner == "flashinfer_cutedsl":
logger.warning(
"FlashInfer CuteDSL MoE is enabled. --disable-shared-experts-fusion is automatically set."
@@ -1639,11 +1642,16 @@ def _speculative_moe_runner_default(view: Any) -> dict:
with a quantized draft can set --speculative-moe-runner-backend explicitly.
(DeepGEMM megamoe is selected via the a2a backend and falls back per-layer
when its weights are not prepared, so it needs no override.)
A target-only lora_* runner defaults the draft to auto: the draft carries
no adapters, so it takes the regular runner chain.
"""
if view.speculative_moe_runner_backend is None:
default = view.moe_runner_backend
if default == "flashinfer_megamoe":
default = "flashinfer_trtllm"
elif default.startswith("lora_"):
default = "auto"
return {"speculative_moe_runner_backend": default}
return {}
+5
View File
@@ -1356,6 +1356,11 @@ class Envs:
# device only, matching how the nvcc path pins -gencode to this GPU.
SGLANG_SAIL_GPU_ARCH = EnvStr("native")
# Per-file overrides for packaged MoE LoRA plans, tiles, and base GEMM configs.
SGLANG_LORA_MOE_CONFIG_DIR = EnvStr(None)
# Per-file overrides for dense LoRA plan tables.
SGLANG_LORA_DENSE_CONFIG_DIR = EnvStr(None)
# ===================================================================
# Expert-parallel dispatch and MoE execution
# ===================================================================
@@ -107,7 +107,11 @@ def _fuses_routed_scaling_factor_in_topk(quant_method, runner_backend) -> bool:
getattr(quant_method, "fuse_routed_scaling_factor_in_topk", False)
or (
isinstance(quant_method, ModelOptNvFp4FusedMoEMethod)
and (runner_backend is None or not runner_backend.is_marlin())
# Marlin, or the LoRA MoE runner on its Marlin NVFP4 vendor.
and (
runner_backend is None
or not (runner_backend.is_marlin() or runner_backend.is_lora_marlin())
)
)
or (
runner_backend is not None
@@ -426,7 +430,11 @@ class FusedMoE(torch.nn.Module):
get_moe_runner_backend().is_flashinfer_trtllm()
or get_moe_runner_backend().is_flashinfer_trtllm_routed()
)
self.use_deep_gemm = get_moe_runner_backend().is_deep_gemm()
# Unquantized BF16 LoRA uses DeepGEMM's resident weight layout.
self.use_deep_gemm = (
get_moe_runner_backend().is_deep_gemm()
or get_moe_runner_backend().is_lora()
)
self.quant_config = quant_config
self.use_flashinfer_mxfp4_moe = get_moe_runner_backend().is_flashinfer_mxfp4()
+13
View File
@@ -171,6 +171,16 @@ class _MoeRunnerBackendPredicates:
def is_experimental_sgl_marlin(self):
return self.value == MoeRunnerBackend.EXPERIMENTAL_SGL_MARLIN.value
def is_lora(self):
return self.value in (
MoeRunnerBackend.LORA_CUTEDSL.value,
MoeRunnerBackend.LORA_TRITON.value,
MoeRunnerBackend.LORA_MARLIN.value,
)
def is_lora_marlin(self):
return self.value == MoeRunnerBackend.LORA_MARLIN.value
def is_humming(self):
return self.value == MoeRunnerBackend.HUMMING.value
@@ -198,6 +208,9 @@ class MoeRunnerBackend(_MoeRunnerBackendPredicates, Enum):
MARLIN = "marlin"
HUMMING = "humming"
EXPERIMENTAL_SGL_MARLIN = "experimental_sgl_marlin"
LORA_CUTEDSL = "lora_cutedsl"
LORA_TRITON = "lora_triton"
LORA_MARLIN = "lora_marlin"
AITER = "aiter"
HPC_OPS = "hpc_ops"
INTEL_XPU = "intel_xpu"
@@ -2369,7 +2369,12 @@ class ModelOptNvFp4FusedMoEMethod(FusedMoEMethodBase):
def __init__(self, quant_config: ModelOptFp4Config):
self.quant_config = quant_config
moe_runner_backend = get_moe_runner_backend()
if moe_runner_backend.is_auto() and is_cuda():
self._lora_marlin = moe_runner_backend.is_lora_marlin()
if moe_runner_backend.is_lora() and not self._lora_marlin:
raise ValueError(
"NVFP4 MoE LoRA requires --moe-runner-backend lora_marlin."
)
if (moe_runner_backend.is_auto() or moe_runner_backend.is_lora()) and is_cuda():
capability = get_device_capability()
use_marlin_fallback = (8, 0) <= capability < (10, 0)
else:
@@ -2727,6 +2732,8 @@ class ModelOptNvFp4FusedMoEMethod(FusedMoEMethodBase):
moe_runner_backend = getattr(
self, "_moe_runner_backend", get_moe_runner_backend()
)
if moe_runner_backend.is_lora_marlin():
moe_runner_backend = MoeRunnerBackend.MARLIN
use_nvfp4_dispatch = _use_nvfp4_dispatch()
if moe_runner_backend.is_marlin():
# Marlin supports only a single shared w1/w3 weight scale, so collapse
@@ -3122,6 +3129,10 @@ class ModelOptNvFp4FusedMoEMethod(FusedMoEMethodBase):
self.runner = None
return
if moe_runner_backend.is_lora():
self.runner = None
return
if moe_runner_backend.is_flashinfer_cutedsl():
import sglang.srt.layers.moe.moe_runner.flashinfer_cutedsl # noqa: F401 – triggers @register_fused_func
@@ -219,7 +219,7 @@ class AscendLoRABackend(BaseLoRABackend):
return output_tensor
def init_cuda_graph_batch_info(
def init_decode_cuda_graph_batch_info(
self,
max_bs_in_cuda_graph: int,
num_tokens_per_req: int,
+138 -47
View File
@@ -27,6 +27,8 @@ class BaseLoRABackend(LoRABackendLmHeadMixing):
supports_lora_a_overlap = False
skip_inactive_lora_batches = False
# Requires a separate "nolora" decode graph for batches without adapters.
skip_inactive_dense_lora = False
# Supporting backends implement init_prefill_cuda_graph_batch_info() and
# honor use_prefill_cuda_graph in prepare_lora_batch().
@@ -53,6 +55,8 @@ class BaseLoRABackend(LoRABackendLmHeadMixing):
self.prefill_moe_cg_buffers: dict | None = None
self._moe_cg_buffer_init_args: tuple[int, torch.dtype, object] | None = None
self._moe_cg_buffer_max_bs: int | None = None
# Sequential MoE layers share one workspace, including graph scratch.
self.lora_workspace = None
def reset_batch_state(self):
"""Idle-forward counterpart of prepare_lora_batch(): clears all
@@ -79,6 +83,15 @@ class BaseLoRABackend(LoRABackendLmHeadMixing):
"prepare_global_lora_batch() to support DP attention."
)
def reset_routing_cache(self) -> None:
"""Clear cached routes without changing batch metadata or storage.
Called before every warmup and capture forward so route-building launches
are recorded in the graph. Repeated calls must be safe.
"""
if self.lora_workspace is not None:
self.lora_workspace.routes.clear()
def validate_lora_targets(
self,
base_model: torch.nn.Module,
@@ -87,6 +100,35 @@ class BaseLoRABackend(LoRABackendLmHeadMixing):
"""Raise before wrapping when this backend cannot execute its targets."""
pass
def forward_with_base(
self,
layer,
x: torch.Tensor,
base_fn,
lora_a,
lora_b,
output_offset,
offsets,
*,
all_reduce=None,
kind="linear",
pruned_batch_info=None,
) -> torch.Tensor:
"""Run base + LoRA, retaining separate base/A reductions for legacy backends."""
if all_reduce is None:
return layer.apply_lora(base_fn(), x)
output = base_fn()
lora_a_output = self.run_lora_a_sgemm(x, lora_a)
output = all_reduce(output)
lora_a_output = all_reduce(lora_a_output)
return self.run_lora_b_sgemm(
x=lora_a_output,
weights=lora_b,
output_offset=output_offset,
output_offset_cpu=layer.output_offset_cpu,
base_output=output,
)
def run_lora_a_embedding(
self,
input_ids: torch.Tensor,
@@ -208,19 +250,10 @@ class BaseLoRABackend(LoRABackendLmHeadMixing):
"""
pass
def init_cuda_graph_batch_info(
self,
max_bs_in_cuda_graph: int,
num_tokens_per_req: int,
def init_decode_cuda_graph_batch_info(
self, max_bs_in_cuda_graph: int, num_tokens_per_req: int
):
"""Phase 2 of LoRA CUDA graph init: dense LoRA batch metadata.
Called during CudaGraphRunner.__init__(), after init_memory_pool().
Args:
max_bs_in_cuda_graph: maximum batch size for CUDA Graph mode
num_tokens_per_req: number of tokens per sequence (1 for decoding, >1 for target_verify)
"""
"""Allocate decode-runner metadata, including target verification."""
pass
def init_dp_attention_cuda_graph_batch_info(self, max_num_tokens: int) -> None:
@@ -231,7 +264,9 @@ class BaseLoRABackend(LoRABackendLmHeadMixing):
)
def init_prefill_cuda_graph_batch_info(
self, max_num_tokens: int, max_num_requests: Optional[int] = None
self,
max_num_tokens: int,
max_num_requests: Optional[int] = None,
):
"""Allocate static LoRA batch metadata for the prefill CUDA graph,
sized for the largest captured token bucket. Called before capture."""
@@ -266,7 +301,12 @@ class BaseLoRABackend(LoRABackendLmHeadMixing):
base = moe_layer.base_layer
top_k = base.top_k
device = moe_layer._quant_info.w13_weight.device
quant_info = moe_layer._quant_info
# Marlin quant info exposes packed weights as w13_qweight.
weight = getattr(quant_info, "w13_weight", None)
if weight is None:
weight = quant_info.w13_qweight
device = weight.device
num_experts = base.num_experts
block_size_m = 64
@@ -306,7 +346,6 @@ class BaseLoRABackend(LoRABackendLmHeadMixing):
(max_bs,), -1, dtype=torch.int32, device=device
),
}
if prefill:
self.prefill_moe_cg_buffers = buffers
else:
@@ -392,14 +431,10 @@ class BaseLoRABackend(LoRABackendLmHeadMixing):
weight_indices: list[int],
lora_ranks: list[int],
scalings: list[float],
use_cuda_graph: bool,
use_decode_cuda_graph: bool,
use_prefill_cuda_graph: bool = False,
):
"""Prepare the lora weights and batch info for current forward batch.
use_cuda_graph / use_prefill_cuda_graph select in-place updates of the
static decode / prefill CUDA graph batch info respectively.
"""
"""Bind eager metadata or update the selected graph family's static metadata."""
pass
def prepare_lora_token_segments(
@@ -424,11 +459,24 @@ def _compute_moe_lora_info_kernel(
weight_indices_ptr,
adapter_enabled_ptr,
token_lora_mapping_ptr,
num_segments,
max_len,
num_tokens,
bucket_len,
live_programs,
BLOCK_SIZE: tl.constexpr,
):
pid = tl.program_id(0)
if pid >= live_programs:
# A tile of the static bucket past the live tokens: no adapter.
offs = (
num_tokens + (pid - live_programs) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
)
tl.store(
token_lora_mapping_ptr + offs,
tl.full((BLOCK_SIZE,), -1, tl.int32),
mask=offs < bucket_len,
)
return
num_pid_m = tl.cdiv(max_len, BLOCK_SIZE)
pid_seg = pid // num_pid_m
@@ -441,12 +489,18 @@ def _compute_moe_lora_info_kernel(
valid = offs < seg_len
lora_id = tl.load(weight_indices_ptr + pid_seg)
lora_rank = tl.load(lora_ranks_ptr + lora_id)
adapter_is_enabled = lora_rank > 0
if adapter_enabled_ptr is not None:
tl.store(
adapter_enabled_ptr + lora_id,
adapter_is_enabled.to(tl.int32),
mask=pid_m == 0,
)
tl.store(
adapter_enabled_ptr + lora_id,
(lora_rank > 0).to(tl.int32),
mask=pid_m == 0,
token_lora_mapping_ptr + seg_start + offs,
tl.where(adapter_is_enabled, lora_id, -1),
mask=valid,
)
tl.store(token_lora_mapping_ptr + seg_start + offs, lora_id, mask=valid)
def _compute_moe_lora_info(
@@ -457,31 +511,60 @@ def _compute_moe_lora_info(
adapter_enabled: torch.Tensor | None,
token_lora_mapping: torch.Tensor | None,
max_len: int,
bucket_len: int | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Build token slots and the active-adapter mask for legacy backends."""
if adapter_enabled is None:
adapter_enabled = torch.empty(
len(lora_ranks), dtype=torch.int32, device=lora_ranks.device
)
else:
assert len(lora_ranks) <= adapter_enabled.shape[0], (
"lora_ranks must be less than or equal to the shape of adapter_enabled"
)
adapter_enabled.zero_()
token_lora_mapping = _compute_token_lora_mapping(
num_tokens,
seg_indptr,
lora_ranks,
weight_indices,
token_lora_mapping,
max_len,
bucket_len=bucket_len,
adapter_enabled=adapter_enabled,
)
return adapter_enabled, token_lora_mapping
def _compute_token_lora_mapping(
num_tokens: int,
seg_indptr: torch.Tensor,
lora_ranks: torch.Tensor,
weight_indices: torch.Tensor,
token_lora_mapping: torch.Tensor | None,
max_len: int,
bucket_len: int | None = None,
adapter_enabled: torch.Tensor | None = None,
) -> torch.Tensor:
"""Expand request slots, clearing graph padding in the same CUDA launch."""
tail_tiles = 0
full_mapping = token_lora_mapping
if token_lora_mapping is not None:
assert num_tokens <= token_lora_mapping.shape[0], (
"num_tokens must be less than or equal to the shape of token_lora_mapping"
)
# Clear padded replay rows left by a larger batch.
# Clear graph padding here unless the CUDA kernel will clear it.
if num_tokens < token_lora_mapping.shape[0]:
token_lora_mapping[num_tokens:].fill_(-1)
if bucket_len is not None and token_lora_mapping.device.type == "cuda":
tail_tiles = triton.cdiv(bucket_len - num_tokens, 256)
else:
token_lora_mapping[num_tokens:].fill_(-1)
token_lora_mapping = token_lora_mapping[:num_tokens]
else:
token_lora_mapping = torch.empty(
(num_tokens,), dtype=torch.int32, device=seg_indptr.device
)
if adapter_enabled is not None:
assert len(lora_ranks) <= adapter_enabled.shape[0], (
"lora_ranks must be less than or equal to the shape of adapter_enabled"
)
else:
adapter_enabled = torch.empty(
len(lora_ranks), dtype=torch.int32, device=lora_ranks.device
)
adapter_enabled.zero_()
has_segments = weight_indices.numel() != 0
needs_launch = num_tokens != 0 and has_segments
if needs_launch:
@@ -496,28 +579,32 @@ def _compute_moe_lora_info(
# Triton kernel on CUDA only; every other device (e.g. XPU) falls through to
# the native torch path below, which yields the same mapping.
if needs_launch and seg_indptr.device.type == "cuda":
_compute_moe_lora_info_kernel[(grid_size,)](
_compute_moe_lora_info_kernel[(grid_size + tail_tiles,)](
seg_indptr,
lora_ranks,
weight_indices,
adapter_enabled,
token_lora_mapping,
weight_indices.numel(),
max_len,
num_tokens,
bucket_len if tail_tiles else 0,
grid_size,
BLOCK_SIZE=block_size,
)
return adapter_enabled, token_lora_mapping
return token_lora_mapping
if tail_tiles:
full_mapping[num_tokens:bucket_len].fill_(-1)
if has_segments:
if has_segments and adapter_enabled is not None:
active_ranks = lora_ranks[weight_indices.long()]
adapter_enabled.scatter_(
0, weight_indices.long(), (active_ranks > 0).to(torch.int32)
)
if num_tokens == 0:
return adapter_enabled, token_lora_mapping
return token_lora_mapping
if not has_segments:
token_lora_mapping.fill_(-1)
return adapter_enabled, token_lora_mapping
return token_lora_mapping
token_positions = torch.arange(
num_tokens, device=seg_indptr.device, dtype=torch.int32
@@ -529,8 +616,12 @@ def _compute_moe_lora_info(
torch.searchsorted(seg_indptr.to(torch.int32), token_positions, right=True) - 1
)
token_lora_mapping = torch.index_select(
torch.index_select(
weight_indices.to(torch.int32), 0, req_indices, out=token_lora_mapping
)
token_lora_ranks = torch.index_select(
lora_ranks, 0, token_lora_mapping.to(torch.int64)
)
token_lora_mapping.masked_fill_(token_lora_ranks <= 0, -1)
return adapter_enabled, token_lora_mapping
return token_lora_mapping
@@ -219,7 +219,7 @@ class ChunkedSgmvLoRABackend(BaseLoRABackend):
torch.cumsum(seg_lens, dim=0, out=indptr[1:])
return indptr
def init_cuda_graph_batch_info(
def init_decode_cuda_graph_batch_info(
self,
max_bs_in_cuda_graph: int,
num_tokens_per_req: int,
@@ -30,6 +30,13 @@ def create_triton_csgmv_backend():
return ChunkedSgmvLoRABackend
@register_lora_backend("triton_v2")
def create_triton_v2_backend():
from sglang.srt.lora.backend.triton_v2_backend import TritonV2LoRABackend
return TritonV2LoRABackend
@register_lora_backend("ascend")
def create_ascend_backend():
from sglang.srt.lora.backend.ascend_backend import AscendLoRABackend
@@ -161,7 +161,7 @@ class TorchNativeLoRABackend(BaseLoRABackend):
return output_tensor
def init_cuda_graph_batch_info(
def init_decode_cuda_graph_batch_info(
self,
max_bs_in_cuda_graph: int,
num_tokens_per_req: int,
@@ -377,7 +377,7 @@ class TritonLoRABackend(BaseLoRABackend):
permutation=torch.zeros(max_tokens, dtype=torch.int32, device=self.device),
)
def init_cuda_graph_batch_info(
def init_decode_cuda_graph_batch_info(
self,
max_bs_in_cuda_graph: int,
num_tokens_per_req: int,
@@ -414,7 +414,7 @@ class TritonLoRABackend(BaseLoRABackend):
def init_dp_attention_cuda_graph_batch_info(self, max_num_tokens: int) -> None:
local_batch_info = getattr(self, "cuda_graph_batch_info", None)
assert local_batch_info is not None, (
"init_cuda_graph_batch_info must run before DP-attention graph init"
"init_decode_cuda_graph_batch_info must run before DP-attention graph init"
)
max_global_num_tokens = max_num_tokens * get_parallel().attn_dp_size
self.cuda_graph_global_batch_info = build_token_lora_batch_info(
@@ -0,0 +1,343 @@
"""Dense LoRA execution with request metadata shared by Linear and MoE layers."""
from __future__ import annotations
from dataclasses import dataclass
from typing import ClassVar
import torch
from sglang.kernels.ops.lora.dense.embedding_lora_a import embedding_lora_a_tokens_fwd
from sglang.srt.lora.backend.base_backend import (
BaseLoRABackend,
_compute_token_lora_mapping,
)
from sglang.srt.lora.dense.plan import DenseLoraKind
from sglang.srt.lora.dense.runner import DenseLoraRunner
from sglang.srt.lora.utils import (
Phase,
get_batch_token_counts,
get_lm_head_pruned_lens,
merge_and_chunk_segments,
)
from sglang.srt.lora.workspace import LoraWorkspace
from sglang.srt.model_executor.forward_batch_info import ForwardBatch
@dataclass
class _BatchInfo:
packed: torch.Tensor
lora_ranks: torch.Tensor
scalings: torch.Tensor
weight_indices: torch.Tensor
seg_indptr: torch.Tensor
token_slots: torch.Tensor
use_cuda_graph: bool # Static metadata for either graph family, including warmup.
num_tokens: int = 0
tokens_per_request: int = 0
has_active_lora: bool = False # Inkling's shared sink skips inactive eager batches.
is_prefill: bool = False # MoE plan phase; target verification uses decode.
@dataclass
class _LmHeadBatchInfo:
seg_indptr: torch.Tensor
weight_indices: torch.Tensor
expected_tokens: int
max_len: int
use_cuda_graph: ClassVar[bool] = False
class TritonV2LoRABackend(BaseLoRABackend):
name = "triton_v2"
supports_prefill_cuda_graph = True
skip_inactive_dense_lora = True
def __init__(self, max_loras_per_batch: int, device: torch.device, **kwargs):
super().__init__(max_loras_per_batch, device)
self.lora_workspace = LoraWorkspace()
self.runner = DenseLoraRunner(
self.lora_workspace, max_loras=max_loras_per_batch, device=device
)
self.lm_head_runner: DenseLoraRunner | None = None
self.decode_cuda_graph_batch_info: _BatchInfo | None = None
def validate_lora_targets(self, base_model, target_modules: set[str]) -> None:
if "lm_head" in target_modules and self.lm_head_runner is None:
# Pruned/chunked logits run outside the model graph on their own rows.
self.lm_head_runner = DenseLoraRunner(
LoraWorkspace(),
max_loras=self.max_loras_per_batch,
device=self.device,
architecture=self.runner.architecture,
)
def reset_batch_state(self):
super().reset_batch_state()
self.runner.reset()
if self.lm_head_runner is not None:
self.lm_head_runner.reset()
def reset_routing_cache(self) -> None:
self.runner.reset_routes()
if self.lm_head_runner is not None:
self.lm_head_runner.reset_routes()
def init_cuda_graph_moe_buffers(
self, max_bs, max_loras, compute_dtype, moe_layer, *, prefill=False
):
# V2 owns the metadata; the MoE workspace owns kernel scratch.
pass
def _new_batch(
self, requests: int, tokens: int, *, graph: bool = False
) -> _BatchInfo:
slots = self.max_loras_per_batch
head = 2 * slots
alloc = torch.zeros if graph else torch.empty
packed = alloc(head + 2 * requests + 1, dtype=torch.int32, device=self.device)
token_slots = torch.empty((tokens,), dtype=torch.int32, device=self.device)
if graph:
token_slots.fill_(-1)
return _BatchInfo(
packed=packed,
lora_ranks=packed[:slots],
scalings=packed[slots : 2 * slots].view(torch.float32),
weight_indices=packed[head : head + requests],
seg_indptr=packed[head + requests :],
token_slots=token_slots,
use_cuda_graph=graph,
)
def init_decode_cuda_graph_batch_info(
self, max_bs_in_cuda_graph: int, num_tokens_per_req: int
):
batch = self._new_batch(
max_bs_in_cuda_graph,
max_bs_in_cuda_graph * num_tokens_per_req,
graph=True,
)
batch.tokens_per_request = num_tokens_per_req
batch.seg_indptr.copy_(
torch.arange(
max_bs_in_cuda_graph + 1, dtype=torch.int32, device=self.device
)
* num_tokens_per_req
)
self.decode_cuda_graph_batch_info = batch
def init_prefill_cuda_graph_batch_info(
self, max_num_tokens: int, max_num_requests: int | None = None
):
requests = max_num_tokens if max_num_requests is None else max_num_requests
self.prefill_cuda_graph_batch_info = self._new_batch(
requests, max_num_tokens, graph=True
)
self.prefill_cuda_graph_max_bs = requests
self.prefill_cuda_graph_max_tokens = max_num_tokens
def _fill_batch(
self,
batch: _BatchInfo,
weight_indices: list[int],
lora_ranks: list[int],
scalings: list[float],
lengths: list[int] | None,
) -> None:
slots = self.max_loras_per_batch
requests = len(weight_indices)
if requests > batch.weight_indices.numel():
raise ValueError("LoRA requests exceed the graph metadata capacity")
indptr = []
if lengths is not None:
indptr = [0]
for length in lengths:
indptr.append(indptr[-1] + length)
head = 2 * slots + requests
host = torch.empty(head + len(indptr), dtype=torch.int32, pin_memory=True)
host[:slots] = torch.as_tensor(lora_ranks, dtype=torch.int32)
host[slots : 2 * slots].view(torch.float32).copy_(
torch.as_tensor(scalings, dtype=torch.float32)
)
host[2 * slots : head] = torch.as_tensor(weight_indices, dtype=torch.int32)
batch.packed[:head].copy_(host[:head], non_blocking=True)
if lengths is not None:
host[head:] = torch.as_tensor(indptr, dtype=torch.int32)
batch.seg_indptr[: requests + 1].copy_(host[head:], non_blocking=True)
def prepare_lora_batch(
self,
forward_batch: ForwardBatch,
weight_indices: list[int],
lora_ranks: list[int],
scalings: list[float],
use_decode_cuda_graph: bool,
use_prefill_cuda_graph: bool = False,
):
requests = forward_batch.batch_size
num_tokens, max_len = get_batch_token_counts(forward_batch)
if use_decode_cuda_graph:
batch = self.decode_cuda_graph_batch_info
if batch is None:
raise RuntimeError("LoRA decode graph metadata is not initialized")
if max_len != batch.tokens_per_request:
raise ValueError(
f"LoRA request width {max_len} does not match captured width "
f"{batch.tokens_per_request}"
)
lengths = None
else:
if use_prefill_cuda_graph:
batch = self.prefill_cuda_graph_batch_info
if batch is None:
raise RuntimeError("LoRA prefill graph metadata is not initialized")
else:
batch = self._new_batch(requests, num_tokens)
lengths = (
list(forward_batch.extend_seq_lens_cpu)
if forward_batch.forward_mode.is_extend_without_speculative()
else [max_len] * requests
)
if len(weight_indices) != requests:
raise ValueError("LoRA needs one adapter slot per request")
self._fill_batch(batch, weight_indices, lora_ranks, scalings, lengths)
request_indptr = batch.seg_indptr[: requests + 1]
request_slots = batch.weight_indices[:requests]
# Only live requests map tokens; the kernel also clears the padded tail.
_compute_token_lora_mapping(
num_tokens,
request_indptr,
batch.lora_ranks,
request_slots,
batch.token_slots,
max_len=max_len,
bucket_len=batch.token_slots.numel(),
)
batch.num_tokens = num_tokens
self.batch_info = batch
self.runner.begin_batch(
token_slots=batch.token_slots,
lora_ranks=batch.lora_ranks,
scalings=batch.scalings,
num_tokens=num_tokens,
phase=(
Phase.PREFILL
if forward_batch.forward_mode.is_extend()
else Phase.DECODE
),
graph_mode=batch.use_cuda_graph,
is_prefill_graph=use_prefill_cuda_graph,
)
if self.lm_head_runner is not None:
self.lm_head_batch_info, self.lm_head_pass_batch_infos = (
self._prepare_lm_head_batch_info(forward_batch, weight_indices)
)
self._lm_head_pass_idx = None
def _prepare_lm_head_batch_info(self, forward_batch, weight_indices):
pruned_lens = get_lm_head_pruned_lens(forward_batch)
if pruned_lens is None:
return None, None
pruned_total = sum(pruned_lens)
full_pruned_info = self._build_lm_head_batch_info(
merge_and_chunk_segments(weight_indices, pruned_lens, pruned_total)
)
pass_segments = self._get_lm_head_pass_segments(weight_indices, pruned_lens)
return full_pruned_info, (
[self._build_lm_head_batch_info(segments) for segments in pass_segments]
if pass_segments is not None
else None
)
def _build_lm_head_batch_info(self, segments) -> _LmHeadBatchInfo:
weight_indices, lengths = segments
indptr = [0]
for length in lengths:
indptr.append(indptr[-1] + length)
host = torch.tensor(indptr + weight_indices, dtype=torch.int32, pin_memory=True)
device = host.to(self.device, non_blocking=True)
return _LmHeadBatchInfo(
seg_indptr=device[: len(indptr)],
weight_indices=device[len(indptr) :],
expected_tokens=indptr[-1],
max_len=max(lengths, default=0),
)
def _runner_for(
self, pruned_batch_info: _LmHeadBatchInfo | None
) -> DenseLoraRunner:
if pruned_batch_info is None:
return self.runner
if self.lm_head_runner is None:
raise RuntimeError("lm_head LoRA was not enabled in the target modules")
batch = self.batch_info
token_slots = _compute_token_lora_mapping(
pruned_batch_info.expected_tokens,
pruned_batch_info.seg_indptr,
batch.lora_ranks,
pruned_batch_info.weight_indices,
None,
max_len=pruned_batch_info.max_len,
)
self.lm_head_runner.begin_batch(
token_slots=token_slots,
lora_ranks=batch.lora_ranks,
scalings=batch.scalings,
num_tokens=pruned_batch_info.expected_tokens,
phase=self.runner.phase,
graph_mode=False,
)
return self.lm_head_runner
def forward_with_base(
self,
layer,
x,
base_fn,
lora_a,
lora_b,
output_offset,
offsets,
*,
all_reduce=None,
kind: DenseLoraKind = DenseLoraKind.LINEAR,
pruned_batch_info: _LmHeadBatchInfo | None = None,
):
runner = self._runner_for(pruned_batch_info)
plan = runner.plan_for(
kind,
lora_b.shape[-1],
0 if kind is DenseLoraKind.EMBEDDING else lora_a.shape[-1],
offsets[-1],
num_tokens=x.shape[0],
)
a_fn = None
if kind is DenseLoraKind.EMBEDDING:
def a_fn():
return embedding_lora_a_tokens_fwd(
input_ids=x,
weights=lora_a,
token_lora_mapping=runner.token_slots,
lora_ranks=runner.lora_ranks,
vocab_size=layer.vocab_size,
extra_embeddings=layer.new_embeddings_buffer,
)
return runner.apply(
x,
base_fn,
plan,
a=lora_a,
b=lora_b,
offsets=offsets,
all_reduce=all_reduce,
a_fn=a_fn,
)
def run_qkv_lora(self, *args, **kwargs):
raise NotImplementedError("triton_v2 linear layers must use forward_with_base")
def run_gate_up_lora(self, *args, **kwargs):
raise NotImplementedError("triton_v2 linear layers must use forward_with_base")
@@ -0,0 +1,42 @@
# Dense LoRA execution plans
`<arch>.plans.json` selects kernels, routing tiles and overlap for
`--lora-backend triton_v2`. Capability major 9 selects `sm90`, major 10 or
above selects `sm100`, and other devices select `default`.
## Selection and overrides
Rows are tried in file order; the first compatible match wins. Selectors cover
phase, layer kind, token count, pool rank and input/output widths. Put narrow
rules before broad ones. A row name is only a label, not a selector. The
windowed Inkling sink-down site cannot use an all-slots shrink.
`SGLANG_LORA_DENSE_CONFIG_DIR` can supply an override file for an architecture.
Missing files or unmatched queries use the defaults in `../plan.py`. Tables
are cached within the process; use a fresh server to evaluate a changed file.
Malformed tables fail loading, including invalid rows that the current model
would not select.
Each plan contains:
- `a_family`: grouped, per-row or all-slots shrink;
- `b_family`: grouped or per-row expand;
- `overlap`: `none`, `a`, or `ab_delta`;
- `block_size`: aligned routing tile;
- `a_tiles` and `b_tiles`: complete launch configurations.
Grouped stages use aligned routes; per-row stages use raw routes. All-slots A
writes slot planes and requires per-row B. Split-K is grouped-A only, with
deterministic `serial` or `planes` reduction. These compatibility rules are
independent of which configuration is fastest.
## Tuning
Use the [dense tuner](../../../../../../benchmark/kernels/lora_dense/README.md)
for explicit resident shapes and devices. Independent validation of a kernel
candidate does not qualify an entire production selector region. Check every
affected kind/rank/geometry/phase, then measure model throughput with the actual
graphs and base backend before promoting a row.
Historical exploration and measurements remain in Git history; they are not
instructions for the maintained tuner or a current no-regression guarantee.
@@ -0,0 +1,433 @@
{
"rows": [
{
"name": "decode.vocab",
"kinds": [
"embedding",
"lm_head"
],
"phase": "decode",
"spec": {
"a_family": "grouped",
"b_family": "grouped",
"overlap": "none",
"block_size": 16,
"a_tiles": {
"BLOCK_SIZE_N": 64,
"BLOCK_SIZE_K": 128,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 3,
"SPLIT_K": 4
},
"b_tiles": {
"BLOCK_SIZE_N": 128,
"BLOCK_SIZE_K": 64,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 2
}
}
},
{
"name": "prefill.vocab",
"kinds": [
"embedding",
"lm_head"
],
"phase": "prefill",
"spec": {
"a_family": "grouped",
"b_family": "grouped",
"overlap": "none",
"block_size": 64,
"a_tiles": {
"BLOCK_SIZE_N": 64,
"BLOCK_SIZE_K": 128,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 3
},
"b_tiles": {
"BLOCK_SIZE_N": 64,
"BLOCK_SIZE_K": 64,
"GROUP_SIZE_M": 8,
"num_warps": 8,
"num_stages": 2
}
}
},
{
"name": "decode.tokens_le8.k_le1024",
"phase": "decode",
"max_in_features": 1024,
"max_tokens": 8,
"spec": {
"a_family": "all_slots",
"b_family": "per_row",
"overlap": "a",
"b_tiles": {
"BLOCK_SIZE_N": 128,
"BLOCK_SIZE_K": 64,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 2
}
}
},
{
"name": "decode.k_le1024",
"phase": "decode",
"max_in_features": 1024,
"spec": {
"a_family": "grouped",
"b_family": "grouped",
"overlap": "a",
"block_size": 16,
"a_tiles": {
"BLOCK_SIZE_N": 64,
"BLOCK_SIZE_K": 128,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 3
},
"b_tiles": {
"BLOCK_SIZE_N": 128,
"BLOCK_SIZE_K": 64,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 2
}
}
},
{
"name": "decode.n_le1024",
"phase": "decode",
"max_out_features": 1024,
"spec": {
"a_family": "all_slots",
"b_family": "per_row",
"overlap": "a",
"b_tiles": {
"BLOCK_SIZE_N": 128,
"BLOCK_SIZE_K": 64,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 2
}
}
},
{
"name": "decode.tokens_le1.n_ge8192",
"phase": "decode",
"max_tokens": 1,
"min_out_features": 8192,
"spec": {
"a_family": "grouped",
"b_family": "grouped",
"overlap": "a",
"block_size": 16,
"a_tiles": {
"BLOCK_SIZE_N": 64,
"BLOCK_SIZE_K": 128,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 3,
"SPLIT_K": 8
},
"b_tiles": {
"BLOCK_SIZE_N": 128,
"BLOCK_SIZE_K": 64,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 2
}
}
},
{
"name": "decode.tokens_le1",
"phase": "decode",
"max_tokens": 1,
"spec": {
"a_family": "grouped",
"b_family": "per_row",
"overlap": "a",
"block_size": 16,
"a_tiles": {
"BLOCK_SIZE_N": 64,
"BLOCK_SIZE_K": 128,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 3,
"SPLIT_K": 8
},
"b_tiles": {
"BLOCK_SIZE_N": 128,
"BLOCK_SIZE_K": 64,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 2
}
}
},
{
"name": "decode.tokens_le8.n_le4096",
"phase": "decode",
"max_tokens": 8,
"max_out_features": 4096,
"spec": {
"a_family": "all_slots",
"b_family": "per_row",
"overlap": "a",
"b_tiles": {
"BLOCK_SIZE_N": 128,
"BLOCK_SIZE_K": 64,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 2
}
}
},
{
"name": "decode.tokens_le16.n_le4096",
"phase": "decode",
"max_tokens": 16,
"max_out_features": 4096,
"spec": {
"a_family": "grouped",
"b_family": "grouped",
"overlap": "a",
"block_size": 16,
"a_tiles": {
"BLOCK_SIZE_N": 64,
"BLOCK_SIZE_K": 128,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 3,
"SPLIT_K": 8
},
"b_tiles": {
"BLOCK_SIZE_N": 128,
"BLOCK_SIZE_K": 64,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 2
}
}
},
{
"name": "decode.tokens_le16.n_le10240",
"phase": "decode",
"max_tokens": 16,
"max_out_features": 10240,
"spec": {
"a_family": "all_slots",
"b_family": "per_row",
"overlap": "none",
"b_tiles": {
"BLOCK_SIZE_N": 128,
"BLOCK_SIZE_K": 64,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 2
}
}
},
{
"name": "decode.tokens_le16",
"phase": "decode",
"max_tokens": 16,
"spec": {
"a_family": "grouped",
"b_family": "grouped",
"overlap": "a",
"block_size": 16,
"a_tiles": {
"BLOCK_SIZE_N": 64,
"BLOCK_SIZE_K": 128,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 3,
"SPLIT_K": 4
},
"b_tiles": {
"BLOCK_SIZE_N": 128,
"BLOCK_SIZE_K": 64,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 2
}
}
},
{
"name": "decode.n_le10240",
"phase": "decode",
"max_out_features": 10240,
"spec": {
"a_family": "grouped",
"b_family": "grouped",
"overlap": "a",
"block_size": 16,
"a_tiles": {
"BLOCK_SIZE_N": 64,
"BLOCK_SIZE_K": 128,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 3,
"SPLIT_K": 8
},
"b_tiles": {
"BLOCK_SIZE_N": 128,
"BLOCK_SIZE_K": 64,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 2
}
}
},
{
"name": "decode",
"phase": "decode",
"spec": {
"a_family": "grouped",
"b_family": "grouped",
"overlap": "a",
"block_size": 16,
"a_tiles": {
"BLOCK_SIZE_N": 64,
"BLOCK_SIZE_K": 128,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 3
},
"b_tiles": {
"BLOCK_SIZE_N": 128,
"BLOCK_SIZE_K": 64,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 2
}
}
},
{
"name": "prefill.tokens_le512.n_le4096",
"max_tokens": 512,
"max_out_features": 4096,
"phase": "prefill",
"spec": {
"a_family": "grouped",
"b_family": "grouped",
"block_size": 16,
"a_tiles": {
"BLOCK_SIZE_N": 64,
"BLOCK_SIZE_K": 128,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 3
},
"b_tiles": {
"BLOCK_SIZE_N": 32,
"BLOCK_SIZE_K": 64,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 2
}
}
},
{
"name": "prefill.tokens_le512",
"max_tokens": 512,
"phase": "prefill",
"spec": {
"a_family": "grouped",
"b_family": "grouped",
"block_size": 16,
"a_tiles": {
"BLOCK_SIZE_N": 64,
"BLOCK_SIZE_K": 128,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 3
},
"b_tiles": {
"BLOCK_SIZE_N": 64,
"BLOCK_SIZE_K": 64,
"GROUP_SIZE_M": 8,
"num_warps": 8,
"num_stages": 2
}
}
},
{
"name": "prefill.n_le4096",
"max_out_features": 4096,
"phase": "prefill",
"spec": {
"a_family": "grouped",
"b_family": "grouped",
"block_size": 32,
"a_tiles": {
"BLOCK_SIZE_N": 64,
"BLOCK_SIZE_K": 128,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 3
},
"b_tiles": {
"BLOCK_SIZE_N": 32,
"BLOCK_SIZE_K": 64,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 2
}
}
},
{
"name": "prefill.n_le10240",
"max_out_features": 10240,
"phase": "prefill",
"spec": {
"a_family": "grouped",
"b_family": "grouped",
"block_size": 64,
"a_tiles": {
"BLOCK_SIZE_N": 64,
"BLOCK_SIZE_K": 128,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 3
},
"b_tiles": {
"BLOCK_SIZE_N": 64,
"BLOCK_SIZE_K": 64,
"GROUP_SIZE_M": 8,
"num_warps": 8,
"num_stages": 2
}
}
},
{
"name": "prefill",
"phase": "prefill",
"spec": {
"a_family": "grouped",
"b_family": "grouped",
"block_size": 128,
"a_tiles": {
"BLOCK_SIZE_N": 64,
"BLOCK_SIZE_K": 128,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 3
},
"b_tiles": {
"BLOCK_SIZE_N": 64,
"BLOCK_SIZE_K": 64,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 1
}
}
}
]
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,138 @@
"""Absorbed MLA: Q += Q @ B_k @ A; V += attention @ A.T @ B_v.T.
Plans name the shrink/expand stages, not the original adapter A/B order.
Only B has per-head slices. Decode overlaps the grouped shrink with the base BMM.
"""
from __future__ import annotations
from contextlib import nullcontext
from dataclasses import dataclass
from functools import cache
import torch
from sglang.kernels.ops.lora.common.lora_a import grouped_lora_a
from sglang.kernels.ops.lora.common.lora_b import grouped_lora_b, slice_geometry
from sglang.kernels.ops.lora.common.route_view import RouteView
from sglang.srt.lora.dense.plan import DensePlan, Overlap
from sglang.srt.lora.utils import Phase
@cache
def _mla_plan(phase: Phase) -> DensePlan:
return DensePlan(
block_size=16 if phase is Phase.DECODE else 64,
overlap=Overlap.A if phase is Phase.DECODE else Overlap.NONE,
)
def _b_slice_per_head(b: torch.Tensor, heads: int, start: int, width: int):
slots, output_dim, rank = b.shape
return b.view(slots, heads, output_dim // heads, rank)[
:, :, start : start + width, :
].reshape(slots * heads, width, rank)
@dataclass(slots=True)
class _Prepared:
runner: object
input: torch.Tensor # Retain reshape copies until the side-stream join.
weight: torch.Tensor
route: RouteView
plan: DensePlan
heads: int
side: str
bridge: torch.Tensor
done: torch.cuda.Event | None = None
def _prepare(attn, x, side):
layer = attn.kv_b_proj
runner = layer.lora_backend.runner
a, b = layer.A_buffer, layer.B_buffer
tokens, heads, input_dim = x.shape
if side == "q":
shrink_weight = _b_slice_per_head(b, heads, 0, input_dim).transpose(1, 2)
expand_weight = a.transpose(1, 2)
else:
shrink_weight = a
expand_weight = _b_slice_per_head(
b, heads, attn.qk_nope_head_dim, attn.v_head_dim
)
plan = _mla_plan(runner.phase)
workspace = runner.workspace
# A reshape may copy; keep it before ready so side-stream reads are ordered.
flat_input = x.reshape(tokens * heads, input_dim)
done = None
# Build the route before forking so the side stream can start with shrink.
route = runner.pair_route(heads, plan.block_size, num_tokens=tokens)
if plan.overlap is Overlap.A:
current = torch.cuda.current_stream(x.device)
stream = workspace.side_stream(x.device)
ready = workspace.event(x.device, f"dense:mla_{side}:ready")
done = workspace.event(x.device, f"dense:mla_{side}:done")
ready.record(current)
stream.wait_event(ready)
context = torch.cuda.stream(stream)
else:
context = nullcontext()
with context:
bridge = workspace.tensor(
f"dense:mla_{side}:bridge",
(flat_input.shape[0], shrink_weight.shape[1]),
dtype=x.dtype,
device=x.device,
)
grouped_lora_a(
flat_input,
shrink_weight,
bridge,
route,
config=plan.a_tiles,
pair_input=True,
weight_div=1 if side == "q" else heads,
lora_ranks=runner.lora_ranks,
)
if done is not None:
done.record(stream)
return _Prepared(
runner, flat_input, expand_weight, route, plan, heads, side, bridge, done
)
def apply_correction(prepared, out):
if prepared.done is not None:
torch.cuda.current_stream(out.device).wait_event(prepared.done)
weight, runner = prepared.weight, prepared.runner
destination = (
out.view(-1, prepared.heads, weight.shape[1]) if out.ndim == 2 else out
)
grouped_lora_b(
prepared.bridge,
weight,
destination,
prepared.route,
pair_heads=prepared.heads,
geometry=slice_geometry(
(0, weight.shape[1]),
int(prepared.plan.b_tiles["BLOCK_SIZE_N"]),
weight.device,
),
config=prepared.plan.b_tiles,
add_inplace=True,
zero_sentinel=False,
lora_ranks=runner.lora_ranks,
scalings=runner.scalings,
weight_div=1 if prepared.side == "v" else prepared.heads,
)
return out
def prepare_q_correction(attn_module, q_nope):
"""Prepare before the base BMM; keep the result alive until apply."""
return _prepare(attn_module, q_nope, "q")
def prepare_v_correction(attn_module, attn_output):
return _prepare(attn_module, attn_output, "v")
+283
View File
@@ -0,0 +1,283 @@
"""Dense LoRA kernel, overlap, routing and tile selection.
``configs/<arch>.plans.json`` uses the first compatible matching row; order
narrow rules first. Missing tables or matches use the defaults below.
"""
from __future__ import annotations
import json
import logging
import os
from dataclasses import dataclass, field
from enum import Enum
from functools import cache
import pydantic
from sglang.srt.lora.utils import Phase
logger = logging.getLogger(__name__)
_CONFIG_DIR = os.path.join(os.path.dirname(__file__), "configs")
class AFamily(str, Enum):
GROUPED = "grouped" # aligned token route, one tile per (block, N tile)
PER_ROW = "per_row" # raw route, one program per route row: a GEMV
ALL_SLOTS = "all_slots" # one dense matmul over every slot's A
class BFamily(str, Enum):
GROUPED = "grouped"
PER_ROW = "per_row"
class DenseLoraKind(str, Enum):
LINEAR = "linear"
EMBEDDING = "embedding"
LM_HEAD = "lm_head"
SINK_GATE_UP = "sink_gate_up" # Inkling sink gate/up
SINK_DOWN = "sink_down" # Inkling per-expert sink down: the windowed shrink
class Overlap(str, Enum):
NONE = "none" # base GEMM, then A, then B into the base output
A = "a" # A on the side stream while the base GEMM runs; B after
AB_DELTA = "ab_delta" # A and B on the side stream into a delta; add after
def _a_tiles() -> dict[str, int]:
return {
"BLOCK_SIZE_N": 64,
"BLOCK_SIZE_K": 128,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 3,
}
def _b_tiles() -> dict[str, int]:
return {
"BLOCK_SIZE_N": 128,
"BLOCK_SIZE_K": 64,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 2,
}
@dataclass(frozen=True, slots=True)
class DensePlan:
a_family: AFamily = AFamily.GROUPED
b_family: BFamily = BFamily.GROUPED
overlap: Overlap = Overlap.NONE
block_size: int = 16
a_tiles: dict[str, int | str] = field(default_factory=_a_tiles)
b_tiles: dict[str, int] = field(default_factory=_b_tiles)
def __post_init__(self) -> None:
if self.block_size < 16 or self.block_size & (self.block_size - 1):
raise ValueError("block_size must be a power of two >= 16")
required = set(_a_tiles())
for name, config in (("a_tiles", self.a_tiles), ("b_tiles", self.b_tiles)):
allowed = required | (
{"SPLIT_K", "SPLIT_MODE"} if name == "a_tiles" else set()
)
if not required <= config.keys() or config.keys() - allowed:
raise ValueError(
f"{name} requires {sorted(required)}; unknown keys are not allowed"
)
for key, value in config.items():
if key == "SPLIT_MODE":
continue
if not isinstance(value, int) or isinstance(value, bool) or value <= 0:
raise ValueError(f"{name}.{key} must be a positive integer")
if key.startswith("BLOCK_SIZE_") and value & (value - 1):
raise ValueError(f"{name}.{key} must be a power of two")
dot_tiles = ()
if name == "a_tiles" and self.a_family is AFamily.GROUPED:
dot_tiles = ("BLOCK_SIZE_N", "BLOCK_SIZE_K")
elif name == "b_tiles" and self.b_family is BFamily.GROUPED:
dot_tiles = ("BLOCK_SIZE_N",)
for key in dot_tiles:
if config[key] < 16:
raise ValueError(
f"{name}.{key} must be at least 16 for grouped GEMM"
)
if config["num_warps"] not in (1, 2, 4, 8, 16, 32):
raise ValueError(f"{name}.num_warps must be a supported power of two")
if self.a_family is AFamily.ALL_SLOTS and self.b_family is not BFamily.PER_ROW:
raise ValueError(
"all_slots A writes one bridge plane per slot; only per_row B reads planes"
)
if (
int(self.a_tiles.get("SPLIT_K", 1)) > 1
and self.a_family is not AFamily.GROUPED
):
raise ValueError("SPLIT_K is a grouped-A tile key")
if self.a_tiles.get("SPLIT_MODE", "serial") not in ("serial", "planes"):
raise ValueError("SPLIT_MODE is 'serial' or 'planes'")
@property
def needs_aligned_route(self) -> bool:
return self.a_family is AFamily.GROUPED or self.b_family is BFamily.GROUPED
def _decode_default() -> DensePlan:
return DensePlan(
block_size=16,
a_tiles={**_a_tiles(), "SPLIT_K": 4},
)
def _prefill_default() -> DensePlan:
return DensePlan(
block_size=64,
b_tiles={**_b_tiles(), "BLOCK_SIZE_N": 64, "num_warps": 8},
)
class _PlanSpecModel(pydantic.BaseModel):
model_config = pydantic.ConfigDict(extra="forbid")
a_family: AFamily = AFamily.GROUPED
b_family: BFamily = BFamily.GROUPED
overlap: Overlap = Overlap.NONE
block_size: int = 16
a_tiles: dict[str, int | str] = pydantic.Field(default_factory=_a_tiles)
b_tiles: dict[str, int] = pydantic.Field(default_factory=_b_tiles)
class _PlanRowModel(pydantic.BaseModel):
model_config = pydantic.ConfigDict(extra="forbid")
name: str
phase: Phase | None = None
kinds: list[DenseLoraKind] | None = None
max_tokens: int | None = None
max_rank: int | None = None
# Geometry bands: shrink input width and total output width across slices.
min_in_features: int | None = None
max_in_features: int | None = None
min_out_features: int | None = None
max_out_features: int | None = None
spec: _PlanSpecModel = pydantic.Field(default_factory=_PlanSpecModel)
@pydantic.model_validator(mode="after")
def _kinds_can_run_the_plan(self) -> _PlanRowModel:
if (
self.kinds
and DenseLoraKind.SINK_DOWN in self.kinds
and self.spec.a_family is AFamily.ALL_SLOTS
):
raise ValueError(
f"row {self.name!r}: an all_slots shrink cannot serve sink_down "
"(the windowed shrink is not one dense matmul)"
)
return self
class _PlansFileModel(pydantic.BaseModel):
model_config = pydantic.ConfigDict(extra="forbid")
rows: list[_PlanRowModel]
def _read_table(name: str) -> dict | None:
from sglang.srt.environ import envs
override_dir = envs.SGLANG_LORA_DENSE_CONFIG_DIR.get()
for directory in filter(None, (override_dir, _CONFIG_DIR)):
path = os.path.join(directory, name)
if os.path.isfile(path):
if directory == override_dir:
logger.info(
"dense LoRA table %r loaded from override dir %s", name, directory
)
with open(path) as handle:
return json.load(handle)
return None
@cache
def load_plans(architecture: str) -> _PlansFileModel | None:
raw = _read_table(f"{architecture}.plans.json")
if raw is None:
return None
table = _PlansFileModel.model_validate(raw)
for row in table.rows:
try:
DensePlan(**row.spec.model_dump())
except ValueError as exc:
raise ValueError(f"dense LoRA row {row.name!r}: {exc}") from exc
return table
class DensePlanTable:
"""Select and cache the first compatible plan row."""
def __init__(self, architecture: str, max_rank: int) -> None:
table = load_plans(architecture)
self._rows = table.rows if table is not None else []
self._max_rank = max_rank
self._bounds = sorted(
{row.max_tokens for row in self._rows if row.max_tokens is not None}
)
self._cache: dict[tuple[DenseLoraKind, Phase, int, int, int], DensePlan] = {}
def plan_for(
self,
kind: DenseLoraKind,
phase: Phase,
num_tokens: int,
in_features: int = 0,
out_features: int = 0,
) -> DensePlan:
# Token counts bucket to the row bounds, so the cache stays small.
key = (kind, phase, self._bucket(num_tokens), in_features, out_features)
plan = self._cache.get(key)
if plan is None:
plan = self._resolve(kind, phase, num_tokens, in_features, out_features)
self._cache[key] = plan
return plan
def _bucket(self, num_tokens: int) -> int:
for bound in self._bounds:
if num_tokens <= bound:
return bound
return 1 << 30
def _resolve(
self,
kind: DenseLoraKind,
phase: Phase,
num_tokens: int,
in_features: int,
out_features: int,
) -> DensePlan:
for row in self._rows:
if row.phase is not None and row.phase is not phase:
continue
if row.kinds is not None and kind not in row.kinds:
continue
# Windowed shrink cannot use an all-slots GEMM.
if (
kind is DenseLoraKind.SINK_DOWN
and row.spec.a_family is AFamily.ALL_SLOTS
):
continue
if row.max_tokens is not None and num_tokens > row.max_tokens:
continue
if row.max_rank is not None and self._max_rank > row.max_rank:
continue
if row.min_in_features is not None and in_features < row.min_in_features:
continue
if row.max_in_features is not None and in_features > row.max_in_features:
continue
if row.min_out_features is not None and out_features < row.min_out_features:
continue
if row.max_out_features is not None and out_features > row.max_out_features:
continue
return DensePlan(**row.spec.model_dump())
return _decode_default() if phase is Phase.DECODE else _prefill_default()
+468
View File
@@ -0,0 +1,468 @@
"""Plan-driven dense LoRA with shared routing, scratch and base-GEMM overlap."""
from __future__ import annotations
from collections.abc import Callable
from typing import NamedTuple
import torch
import triton
from sglang.kernels.ops.lora.common.lora_a import (
grouped_lora_a,
per_row_lora_a,
shrink_column_tiles,
)
from sglang.kernels.ops.lora.common.lora_b import (
grouped_lora_b,
per_row_lora_b,
slice_geometry,
)
from sglang.kernels.ops.lora.common.route_view import RouteView, RouteViewKind
from sglang.kernels.ops.lora.common.routing import build_route
from sglang.srt.lora.dense.plan import (
AFamily,
BFamily,
DenseLoraKind,
DensePlan,
DensePlanTable,
Overlap,
load_plans,
)
from sglang.srt.lora.utils import Phase, architecture_for_capability
from sglang.srt.lora.workspace import LoraWorkspace
class Bridge(NamedTuple):
"""Shrink output, normally [rows, bridge_width]. Split-K uses FP32
[planes, rows, bridge_width], summed by expand; ``slot_planes`` uses
[slots, rows, bridge_width], indexed by adapter slot.
"""
tensor: torch.Tensor
planes: int = 1
slot_planes: bool = False
class DenseLoraRunner:
def __init__(
self,
workspace: LoraWorkspace,
*,
max_loras: int,
device: torch.device,
architecture: str | None = None,
) -> None:
self.workspace = workspace
self.max_loras = max_loras
if architecture is None:
if device.type == "cuda":
major, _ = torch.cuda.get_device_capability(device)
architecture = architecture_for_capability(major)
else:
architecture = "default"
self.architecture = architecture
# Validate the architecture's plan table (and any override) at startup.
load_plans(architecture)
self._plan_tables: dict[int, DensePlanTable] = {}
self.reset()
def reset(self) -> None:
self.phase = Phase.DECODE
self.num_tokens = 0
self._token_slots: torch.Tensor | None = None
self.token_slots: torch.Tensor | None = None
self.lora_ranks: torch.Tensor | None = None
self.scalings: torch.Tensor | None = None
self.reset_routes()
def reset_routes(self) -> None:
"""Start a forward without dropping bound metadata or workspace storage."""
self._raw_route: RouteView | None = None
self.workspace.routes.clear()
def begin_batch(
self,
*,
token_slots: torch.Tensor,
lora_ranks: torch.Tensor,
scalings: torch.Tensor,
num_tokens: int,
phase: Phase,
graph_mode: bool,
is_prefill_graph: bool = False,
) -> None:
"""Bind the token-to-adapter metadata for this batch."""
self.reset()
self.phase = phase
self.num_tokens = num_tokens
self._token_slots = token_slots
self.token_slots = token_slots[:num_tokens]
self.lora_ranks = lora_ranks
self.scalings = scalings
# Target verify uses prefill plans inside a decode graph.
self.workspace.begin_forward(
graph_mode=graph_mode, is_prefill_graph=is_prefill_graph
)
def set_num_tokens(self, num_tokens: int) -> None:
"""Use the forward's input shape, including graph padding."""
if not 0 <= num_tokens <= self._token_slots.numel():
raise ValueError("dense LoRA input exceeds its token-to-adapter buffer")
if num_tokens != self.num_tokens:
self.reset_routes()
self.num_tokens = num_tokens
self.token_slots = self._token_slots[:num_tokens]
def plan_for(
self,
kind: DenseLoraKind,
max_rank: int,
in_features: int = 0,
out_features: int = 0,
*,
num_tokens: int,
) -> DensePlan:
self.set_num_tokens(num_tokens)
table = self._plan_tables.get(max_rank)
if table is None:
table = DensePlanTable(self.architecture, max_rank)
self._plan_tables[max_rank] = table
return table.plan_for(kind, self.phase, num_tokens, in_features, out_features)
def route(self, block_size: int) -> RouteView:
"""Return the adapter-aligned route, cached per forward and block size."""
return self._cached_route(("sorted", block_size))
def _cached_route(self, key: tuple) -> RouteView:
return self.workspace.route(
self.token_slots, (*key, self.max_loras), lambda: self._build_route(key)
)
def _build_route(self, key: tuple) -> RouteView:
if key[0] == "pair":
return self._build_pair_route(*key[1:])
block_size = key[1]
return build_route(
self.token_slots,
max_loras=self.max_loras,
block_size=block_size,
view=RouteViewKind.ALIGNED,
workspace=self.workspace,
tensor_prefix=f"dense:sorted:{block_size}",
)
def pair_route(
self, num_heads: int, block_size: int, *, num_tokens: int
) -> RouteView:
"""Sort (token, head) pairs by slot*H + head, once per forward."""
self.set_num_tokens(num_tokens)
return self._cached_route(("pair", block_size, num_heads))
def _build_pair_route(self, block_size: int, num_heads: int) -> RouteView:
rows = self.num_tokens * num_heads
device = self.token_slots.device
head_ids = self.workspace.tensor(
f"dense:pairs:{num_heads}:heads",
(rows, 1),
dtype=torch.int32,
device=device,
)
# Refresh assignments on every graph replay.
head_ids.copy_(
torch.arange(num_heads, dtype=torch.int32, device=device)
.expand(self.num_tokens, num_heads)
.reshape(rows, 1)
)
row_slots = self.workspace.tensor(
f"dense:pairs:{num_heads}:slots",
(rows,),
dtype=torch.int32,
device=device,
)
row_slots.copy_(
self.token_slots[:, None].expand(self.num_tokens, num_heads).reshape(rows)
)
route = build_route(
row_slots,
group_ids=head_ids,
groups_per_slot=num_heads,
max_loras=self.max_loras,
block_size=block_size,
view=RouteViewKind.ALIGNED,
workspace=self.workspace,
tensor_prefix=f"dense:pairs:{num_heads}:{block_size}",
)
return route
def raw_route(self) -> RouteView:
if self._raw_route is None:
self._raw_route = RouteView(
view=RouteViewKind.RAW,
block_size=1,
token_slots=self.token_slots,
group_ids=None,
groups_per_slot=1,
max_loras=self.max_loras,
)
return self._raw_route
def run_a(
self,
x: torch.Tensor,
a: torch.Tensor,
*,
stack: int,
plan: DensePlan,
lora_ranks: torch.Tensor | None = None,
windowed: bool = False,
) -> Bridge:
"""Shrink into a bridge of width ``stack * rank_max`` (see ``Bridge``).
A rank-r slot packs slice s at [s*r, (s+1)*r). With ``windowed``,
block s reads input columns [s*K, (s+1)*K) at full rank width,
ignoring per-slot ranks.
"""
num_tokens = x.shape[0]
slots, n_max, k = a.shape
# A caller with max-rank-spaced, zero-filled slots (the MoE-layout
# pool buffers) passes constant ranks; the batch's ranks otherwise.
ranks = lora_ranks if lora_ranks is not None else self.lora_ranks
match plan.a_family:
case AFamily.GROUPED:
split_k = int(plan.a_tiles.get("SPLIT_K", 1))
mode = str(plan.a_tiles.get("SPLIT_MODE", "serial"))
bridge = self.workspace.tensor(
"dense:bridge",
(num_tokens, n_max),
dtype=x.dtype,
device=x.device,
)
partial = counters = None
if split_k > 1:
partial = self.workspace.tensor(
"dense:bridge_partial",
(split_k, num_tokens, n_max),
dtype=torch.float32,
device=x.device,
)
if mode == "serial":
route = self.route(plan.block_size)
tiles = (
triton.cdiv(route.sorted_pair_ids.numel(), route.block_size)
* shrink_column_tiles(
int(plan.a_tiles["BLOCK_SIZE_N"]),
n_max,
stack,
windowed,
)[1]
)
# Zero at rest; the last-arriving program resets its tile.
counters = self.workspace.tensor(
"dense:splitk_counters",
(tiles,),
dtype=torch.int32,
device=x.device,
zero_on_first_allocation=True,
)
grouped_lora_a(
x,
a,
bridge,
self.route(plan.block_size),
config=plan.a_tiles,
pair_input=True,
lora_ranks=ranks,
stack=stack,
partial=partial,
counters=counters,
windowed=windowed,
)
if split_k > 1 and mode == "planes":
return Bridge(partial, planes=split_k)
return Bridge(bridge)
case AFamily.PER_ROW:
bridge = self.workspace.tensor(
"dense:bridge",
(num_tokens, n_max),
dtype=x.dtype,
device=x.device,
)
per_row_lora_a(
x,
a,
bridge,
self.raw_route(),
config=plan.a_tiles,
stack=stack,
windowed=windowed,
)
return Bridge(bridge)
case AFamily.ALL_SLOTS:
if windowed: # plan_for never pairs them: a forced plan did
raise NotImplementedError(
"the all-slots GEMM cannot window per rank block"
)
flat = self.workspace.tensor(
"dense:bridge_all",
(num_tokens, slots * n_max),
dtype=x.dtype,
device=x.device,
)
torch.matmul(x, a.reshape(slots * n_max, k).t(), out=flat)
return Bridge(
flat.view(num_tokens, slots, n_max).transpose(0, 1),
slot_planes=True,
)
case _:
raise NotImplementedError(
f"no engine executor for A family {plan.a_family.value!r}"
)
def run_b(
self,
bridge: Bridge,
b: torch.Tensor,
out: torch.Tensor,
*,
offsets: tuple[int, ...],
plan: DensePlan,
add_inplace: bool = True,
lora_ranks: torch.Tensor | None = None,
scalings: torch.Tensor | None = None,
bridge_slices: int = 0,
) -> torch.Tensor:
"""Expand into output columns delimited by the host ``offsets``.
``bridge_slices`` > 0 maps slice s to bridge block s % bridge_slices.
Optional ranks/scalings override the batch's for MoE-layout buffers.
"""
ranks = lora_ranks if lora_ranks is not None else self.lora_ranks
scales = scalings if scalings is not None else self.scalings
b_tiles = plan.b_tiles
geometry = slice_geometry(offsets, int(b_tiles["BLOCK_SIZE_N"]), b.device)
match plan.b_family:
case BFamily.GROUPED:
grouped_lora_b(
bridge.tensor,
b,
out,
self.route(plan.block_size),
geometry=geometry,
config=b_tiles,
add_inplace=add_inplace,
zero_sentinel=False,
lora_ranks=ranks,
scalings=scales,
planes=bridge.planes,
bridge_slices=bridge_slices,
)
case BFamily.PER_ROW:
per_row_lora_b(
bridge.tensor,
b,
out,
self.raw_route(),
geometry=geometry,
config=b_tiles,
add_inplace=add_inplace,
zero_sentinel=False,
lora_ranks=ranks,
scalings=scales,
planes=bridge.planes,
slot_planes=bridge.slot_planes,
bridge_slices=bridge_slices,
)
case _:
raise NotImplementedError(
f"no engine executor for B family {plan.b_family.value!r}"
)
return out
def apply(
self,
x: torch.Tensor,
base_fn: Callable[[], torch.Tensor],
plan: DensePlan,
*,
a: torch.Tensor,
b: torch.Tensor,
offsets: tuple[int, ...],
all_reduce: Callable[[torch.Tensor], torch.Tensor] | None = None,
lora_ranks: torch.Tensor | None = None,
scalings: torch.Tensor | None = None,
bridge_slices: int = 0,
a_blocks: int | None = None,
a_windowed: bool = False,
a_fn: Callable[[], torch.Tensor] | None = None,
) -> torch.Tensor:
"""Add LoRA to ``base_fn()`` with the plan's overlap strategy.
A is [slots, a_blocks*rank, K]; B is [slots, offsets[-1], rank].
``a_blocks`` defaults to len(offsets)-1; windowing and bridge mapping
follow ``run_a``/``run_b``. ``all_reduce`` reduces base + LoRA once
with B replicated across TP ranks.
"""
self.set_num_tokens(x.shape[0])
stack = len(offsets) - 1 if a_blocks is None else a_blocks
def run_a() -> Bridge:
if a_fn is not None:
return Bridge(a_fn()) # the embedding shrink: one plain bridge
return self.run_a(
x,
a,
stack=stack,
plan=plan,
lora_ranks=lora_ranks,
windowed=a_windowed,
)
def run_b(bridge: Bridge, out: torch.Tensor, add_inplace: bool) -> None:
self.run_b(
bridge,
b,
out,
offsets=offsets,
plan=plan,
add_inplace=add_inplace,
lora_ranks=lora_ranks,
scalings=scalings,
bridge_slices=bridge_slices,
)
if plan.overlap is Overlap.AB_DELTA:
# The delta covers the output columns the LoRA slices reach.
out_end = offsets[-1]
delta = self.workspace.tensor(
"dense:delta",
(x.shape[0], out_end),
# Embedding inputs are integer token IDs, not activations.
dtype=b.dtype if a_fn is not None else x.dtype,
device=x.device,
)
delta.zero_()
base = self.workspace.run_parallel(
name="dense",
device=x.device,
compute=base_fn,
side=lambda: run_b(run_a(), delta, False),
)
base[:, :out_end].add_(delta)
return all_reduce(base) if all_reduce is not None else base
if plan.overlap is Overlap.A:
side_result: list[Bridge] = []
base = self.workspace.run_parallel(
name="dense",
device=x.device,
compute=base_fn,
side=lambda: side_result.append(run_a()),
)
bridge = side_result[0]
else:
base = base_fn()
bridge = run_a()
run_b(bridge, base, True)
return all_reduce(base) if all_reduce is not None else base
+194 -97
View File
@@ -26,7 +26,12 @@ from sglang.srt.layers.vocab_parallel_embedding import (
VocabParallelEmbedding,
)
from sglang.srt.lora.backend.base_backend import BaseLoRABackend
from sglang.srt.lora.utils import LoRABatchInfo, get_lm_head_lora_b_shard_size
from sglang.srt.lora.dense.plan import DenseLoraKind
from sglang.srt.lora.utils import (
LoRABatchInfo,
capturing_lora_graph,
get_lm_head_lora_b_shard_size,
)
from sglang.srt.runtime_context import LoRABatchLayout, get_forward, get_parallel
_SGLANG_EXPERIMENTAL_LORA_OPTI = envs.SGLANG_EXPERIMENTAL_LORA_OPTI.get()
@@ -63,19 +68,22 @@ class BaseLayerWithLoRA(nn.Module):
@property
def lora_active(self) -> bool:
"""True when this layer has LoRA buffers set AND the current forward
has LoRA batch metadata. batch_info is None on DP-attention idle
forwards (see LoRAManager.prepare_lora_batch), so idle forwards take
the base path."""
"""Whether this forward must execute LoRA kernels.
DP-attention idle forwards have no batch metadata. Inactive batches
may still need LoRA kernels when capturing an adapter-capable graph.
"""
batch_info = self.lora_backend.get_batch_info()
return (
self.set_lora
and batch_info is not None
and (
not self.lora_backend.skip_inactive_lora_batches
or batch_info.has_active_lora
)
)
if not self.set_lora or batch_info is None:
return False
backend = self.lora_backend
if not (backend.skip_inactive_lora_batches or backend.skip_inactive_dense_lora):
return True
if batch_info.has_active_lora:
return True
if backend.skip_inactive_lora_batches:
return False
return capturing_lora_graph()
def set_lora_info(self, *args):
pass
@@ -124,6 +132,7 @@ class VocabParallelEmbeddingWithLoRA(BaseLayerWithLoRA):
"VocabParallelEmbeddingWithLoRA with TP > 1 under input_scattered mode (e.g., DeepSeek-v2 MLA with --enable-attn-tp-input-scattered) is not fully supported and may produce incorrect results. Consider disabling input_scattered or removing embed_tokens from LoRA target modules."
)
offsets = [0, self.embed_dim]
self.lora_offsets = tuple(offsets)
self.output_offset = torch.tensor(
offsets,
dtype=torch.int32,
@@ -149,7 +158,7 @@ class VocabParallelEmbeddingWithLoRA(BaseLayerWithLoRA):
self.embedding_B_buffer = embedding_B_buffer # (num_loras, embed_dim, rank)
def apply_lora(
self, base_output: torch.Tensor, input_: torch.Tensor, batch_info
self, base_output: torch.Tensor, input_: torch.Tensor, batch_info=None
) -> torch.Tensor:
"""
Apply LoRA to base embedding output.
@@ -170,7 +179,7 @@ class VocabParallelEmbeddingWithLoRA(BaseLayerWithLoRA):
return lora_output
def run_lora_a_embedding(
self, input_: torch.Tensor, batch_info: LoRABatchInfo
self, input_: torch.Tensor, batch_info: LoRABatchInfo | None = None
) -> torch.Tensor:
"""
Apply LoRA A weights using efficient embedding lookup with CUDA graph support.
@@ -218,37 +227,28 @@ class VocabParallelEmbeddingWithLoRA(BaseLayerWithLoRA):
)
def forward(self, input_: torch.Tensor):
"""
Forward pass with LoRA support and CUDA graph compatibility.
def base_fn():
# Mask only the base lookup; LoRA still sees the original token IDs.
base = self.base_layer.forward(
input_.masked_fill(input_ >= self.vocab_size, 0)
)
if getattr(self, "new_embeddings_buffer", None) is not None:
base = self.extra_token_embedding(input_, base)
return base
Extra tokens (tokens >= vocab_size) are now handled efficiently
in the backend's run_lora_a_embedding method.
"""
batch_info = self.lora_backend.get_batch_info(LoRABatchLayout.DP_LOCAL)
# Get base embedding output
# For tokens >= vocab_size, base_layer will clamp or handle them
# We mask them to 0 to avoid out-of-bounds access
added_tokens_mask = input_ > self.vocab_size - 1
base_output = self.base_layer.forward(input_.masked_fill(added_tokens_mask, 0))
# [TODO] SGLang did not support extra/added token process; thus, self.extra_token_embedding only return original input_ now
# Extra tokens - It will replace extra token embedding with self.new_embeddings_buffer's emb (Default is 0)
if (
hasattr(self, "new_embeddings_buffer")
and self.new_embeddings_buffer is not None
):
base_output = self.extra_token_embedding(input_, base_output)
# Apply LoRA if configured; DP-attention idle forwards take the base
# path (see lora_active).
with get_forward().scoped(lora_batch_layout=LoRABatchLayout.DP_LOCAL):
if self.lora_active:
# The backend's run_lora_a_embedding now handles both regular
# and extra tokens efficiently with CUDA graph support
base_output = self.apply_lora(base_output, input_, batch_info)
return base_output
return self.lora_backend.forward_with_base(
self,
input_,
base_fn,
self.embedding_A_buffer,
self.embedding_B_buffer,
self.output_offset,
self.lora_offsets,
kind=DenseLoraKind.EMBEDDING,
)
return base_fn()
def slice_lora_a_weights(self, A: torch.Tensor):
# LoRA A weights (rank, vocab_size) are kept unsharded.
@@ -311,6 +311,7 @@ class ParallelLMHeadWithLoRA(BaseLayerWithLoRA):
)
offsets = [0, self.shard_vocab_size]
self.lora_offsets = tuple(offsets)
self.output_offset = torch.tensor(
offsets,
dtype=torch.int32,
@@ -354,9 +355,8 @@ class ParallelLMHeadWithLoRA(BaseLayerWithLoRA):
if batch_info is not None:
if batch_info.use_cuda_graph:
raise RuntimeError(
"lm_head LoRA with pruned batch info is not supported "
"under CUDA graph. lm_head pruning should only occur "
"during extend, which does not use CUDA graph."
"Pruned lm_head LoRA metadata is eager-only and must run "
"outside the captured model graph."
)
if num_tokens != batch_info.expected_tokens:
raise RuntimeError(
@@ -403,15 +403,24 @@ class ParallelLMHeadWithLoRA(BaseLayerWithLoRA):
return lora_output
def forward(self, hidden_states: torch.Tensor):
# Apply base linear transformation
base_output = F.linear(
hidden_states, self.weight, bias=getattr(self.base_layer, "bias", None)
)
def base_fn():
return F.linear(
hidden_states, self.weight, bias=getattr(self.base_layer, "bias", None)
)
if self.lora_active:
base_output = self.apply_lora(base_output, hidden_states)
return base_output
return self.lora_backend.forward_with_base(
self,
hidden_states,
base_fn,
self.lm_head_A_buffer,
self.lm_head_B_buffer,
self.output_offset,
self.lora_offsets,
kind=DenseLoraKind.LM_HEAD,
pruned_batch_info=self._get_lm_head_batch_info(hidden_states.shape[0]),
)
return base_fn()
# ------------------------------------------------------------------
# Multi-pass lm_head support (chunked logprobs)
@@ -478,6 +487,8 @@ class ColumnParallelLinearWithLoRA(BaseLayerWithLoRA):
self.set_lora = True
self.A_buffer = A_buffer
self.B_buffer = B_buffer
self.lora_a, self.lora_b = A_buffer, B_buffer
self.lora_offsets = tuple(self.output_offset_cpu.tolist())
def apply_lora(self, base_output: torch.Tensor, x: torch.Tensor) -> torch.Tensor:
lora_a_output = self.lora_backend.run_lora_a_sgemm(x, self.A_buffer)
@@ -501,12 +512,22 @@ class ColumnParallelLinearWithLoRA(BaseLayerWithLoRA):
self.start_lora_a_overlap(input_)
bias = self.base_layer.bias if not self.base_layer.skip_bias_add else None
output_parallel = self.base_layer.quant_method.apply(
self.base_layer, input_, bias
)
def base_fn():
return self.base_layer.quant_method.apply(self.base_layer, input_, bias)
if lora_active:
output_parallel = self.apply_lora(output_parallel, input_)
output_parallel = self.lora_backend.forward_with_base(
self,
input_,
base_fn,
self.lora_a,
self.lora_b,
self.output_offset,
self.lora_offsets,
)
else:
output_parallel = base_fn()
if self.base_layer.gather_output:
output = tensor_model_parallel_all_gather(output_parallel)
@@ -575,6 +596,8 @@ class MergedColumnParallelLinearWithLoRA(ColumnParallelLinearWithLoRA):
self.use_gate_up_lora = (
lora_n_slices == 2 and partition_sizes[0] == partition_sizes[1]
)
self.lora_a, self.lora_b = A_buffer, B_buffer
self.lora_offsets = tuple(offsets)
def _get_lora_n_slices(self) -> int:
"""Actual number of LoRA slices from the buffer shapes.
@@ -711,6 +734,8 @@ class QKVParallelLinearWithLoRA(ColumnParallelLinearWithLoRA):
self.set_lora = True
self.A_buffer_qkv = A_buffer_qkv
self.B_buffer_qkv = B_buffer_qkv
self.lora_a, self.lora_b = A_buffer_qkv, B_buffer_qkv
self.lora_offsets = tuple(self.output_offset_cpu.tolist())
def apply_lora(self, base_output: torch.Tensor, x: torch.Tensor) -> torch.Tensor:
lora_output = self.lora_backend.run_qkv_lora(
@@ -788,6 +813,8 @@ class RowParallelLinearWithLoRA(BaseLayerWithLoRA):
device="cpu",
pin_memory=True,
)
self.lora_a, self.lora_b = A_buffer, B_buffer
self.lora_offsets = tuple(offsets)
def apply_lora(self, base_output: torch.Tensor, x: torch.Tensor) -> torch.Tensor:
lora_a_output = self.lora_backend.run_lora_a_sgemm(x, self.A_buffer)
@@ -821,9 +848,11 @@ class RowParallelLinearWithLoRA(BaseLayerWithLoRA):
if (tp_rank > 0 or self.base_layer.skip_bias_add)
else self.base_layer.bias
)
output_parallel = self.base_layer.quant_method.apply(
self.base_layer, input_parallel, bias=bias_
)
def base_fn():
return self.base_layer.quant_method.apply(
self.base_layer, input_parallel, bias=bias_
)
should_reduce = (
self.base_layer.reduce_results
@@ -839,26 +868,21 @@ class RowParallelLinearWithLoRA(BaseLayerWithLoRA):
all_reduce = get_parallel().attn_tp_group.all_reduce
else:
all_reduce = tensor_model_parallel_all_reduce
if lora_active and should_reduce:
lora_a_output = self.lora_backend.run_lora_a_sgemm(
input_parallel, self.A_buffer
)
output_ = all_reduce(output_parallel)
lora_a_output = all_reduce(lora_a_output)
output_ = self.lora_backend.run_lora_b_sgemm(
x=lora_a_output,
weights=self.B_buffer,
output_offset=self.output_offset,
output_offset_cpu=self.output_offset_cpu,
base_output=output_,
if lora_active:
output_ = self.lora_backend.forward_with_base(
self,
input_parallel,
base_fn,
self.lora_a,
self.lora_b,
self.output_offset,
self.lora_offsets,
all_reduce=all_reduce if should_reduce else None,
)
elif should_reduce:
output_ = all_reduce(base_fn())
else:
if lora_active:
output_parallel = self.apply_lora(output_parallel, input_parallel)
if should_reduce:
output_ = all_reduce(output_parallel)
else:
output_ = output_parallel
output_ = base_fn()
output_bias = self.base_layer.bias if self.base_layer.skip_bias_add else None
return output_, output_bias
@@ -920,6 +944,8 @@ class ReplicatedLinearWithLoRA(BaseLayerWithLoRA):
dtype=torch.int32,
device=B_buffer.device,
)
self.lora_a, self.lora_b = A_buffer, B_buffer
self.lora_offsets = tuple(self._output_offset.tolist())
def apply_lora(self, base_output: torch.Tensor, x: torch.Tensor) -> torch.Tensor:
first_dim = self.first_output_dim
@@ -952,9 +978,22 @@ class ReplicatedLinearWithLoRA(BaseLayerWithLoRA):
def forward(self, x: torch.Tensor):
bias = self.base_layer.bias if not self.base_layer.skip_bias_add else None
output = self.base_layer.quant_method.apply(self.base_layer, x, bias)
def base_fn():
return self.base_layer.quant_method.apply(self.base_layer, x, bias)
if self.lora_active:
output = self.apply_lora(output, x)
output = self.lora_backend.forward_with_base(
self,
x,
base_fn,
self.lora_a,
self.lora_b,
self._output_offset,
self.lora_offsets,
)
else:
output = base_fn()
output_bias = self.base_layer.bias if self.base_layer.skip_bias_add else None
return output, output_bias
@@ -981,13 +1020,17 @@ class FusedMoEWithLoRA(BaseLayerWithLoRA):
self,
base_layer: FusedMoE,
lora_backend: BaseLoRABackend,
*,
experts_shared_outer_loras: bool = False,
max_lora_rank: Optional[int] = None,
):
# initializes FusedMoE with its own moe_runner for base path
super().__init__(base_layer, lora_backend)
lora_backend.is_moe_lora = True
self.experts_shared_outer_loras: bool = False
# Match the factor layout and physical rank allocated by the memory pool.
self.experts_shared_outer_loras: bool = experts_shared_outer_loras
self.lora_use_virtual_experts: bool = False
self.quant_method = base_layer.quant_method
self.moe_runner_config = base_layer.moe_runner_config
@@ -1012,15 +1055,19 @@ class FusedMoEWithLoRA(BaseLayerWithLoRA):
base_layer.moe_runner_config.gemm1_alpha is not None
)
# Initialize triton_lora moe runner for batches with lora enabled
from sglang.srt.layers.moe import MoeRunnerBackend
from sglang.srt.layers.moe.moe_runner.runner import MoeRunner
from sglang.srt.layers.moe.utils import get_moe_runner_backend
# Use the runner selected by the quant method so per-format backend resolution
# stays identical between base and LoRA forwards.
# Explicit LoRA engines take precedence over the base layer's vendor runner.
global_backend = get_moe_runner_backend()
if base_layer.runner is not None:
if (
global_backend.is_lora()
or global_backend.is_experimental_sgl_trtllm()
or global_backend.is_experimental_sgl_marlin()
):
runner_backend = global_backend
elif base_layer.runner is not None:
runner_backend = base_layer.runner.runner_backend
elif not global_backend.is_auto():
runner_backend = global_backend
@@ -1038,8 +1085,27 @@ class FusedMoEWithLoRA(BaseLayerWithLoRA):
if isinstance(base_layer.quant_method, UnquantizedFusedMoEMethod):
runner_backend = MoeRunnerBackend.TRITON
# ===== TO BE REFACTORED ====
self._lora_runner_backend = runner_backend
if (lora_backend.name == "triton_v2") != runner_backend.is_lora():
raise ValueError(
"Routed MoE LoRA must pair --lora-backend triton_v2 with "
"--moe-runner-backend lora_cutedsl, lora_triton, or lora_marlin; "
"mixing new and legacy LoRA backends is unsupported"
)
if runner_backend.is_lora():
from sglang.srt.lora.moe.runner import MoeLoraRunner
self._moe_lora_runner = MoeLoraRunner.from_layer(
base_layer,
workspace=lora_backend.lora_workspace,
is_shared_outer=experts_shared_outer_loras,
physical_rank=max_lora_rank,
)
# Keep dispatch, combine, and distributed reduction in the base layer.
self._base_run_moe_core = base_layer.run_moe_core
base_layer.run_moe_core = self._run_moe_core_with_lora
return
if runner_backend.is_experimental_sgl_trtllm():
from sglang.srt.lora.trtllm_lora_temp.lora_layer import (
init_experimental_sgl_trtllm_lora,
@@ -1102,7 +1168,7 @@ class FusedMoEWithLoRA(BaseLayerWithLoRA):
self.down_lora_b_weights = down_lora_b_weights
def _get_lora_info(self):
"""Build LoRAInfo for the current batch."""
"""Build the legacy engine's batch payload."""
from sglang.srt.lora.lora_moe_runners import LoRAInfo
batch_info = self.lora_backend.get_batch_info(LoRABatchLayout.TP_GLOBAL)
@@ -1159,8 +1225,11 @@ class FusedMoEWithLoRA(BaseLayerWithLoRA):
1. After gate_up projection, before activation
2. After down projection, before final reduction
"""
# DP-attention idle forward: no batch_info, run the base MoE path.
if self.lora_backend.get_batch_info(LoRABatchLayout.TP_GLOBAL) is None:
# The lora_* path replaces run_moe_core inside the base forward.
if (
self.lora_backend.get_batch_info(LoRABatchLayout.TP_GLOBAL) is None
or self._lora_runner_backend.is_lora()
):
return self.base_layer.forward(hidden_states, topk_output, **kwargs)
# Build LoRA info for this batch
@@ -1169,6 +1238,25 @@ class FusedMoEWithLoRA(BaseLayerWithLoRA):
# run lora moe_runner
return self._forward_with_lora(hidden_states, topk_output, lora_info, **kwargs)
def _run_moe_core_with_lora(self, dispatch_output):
batch_info = self.lora_backend.get_batch_info(LoRABatchLayout.TP_GLOBAL)
if batch_info is None:
return self._base_run_moe_core(dispatch_output=dispatch_output)
from sglang.srt.lora.moe.runner import MoeLoraBatch
return self._moe_lora_runner.run(
dispatch_output,
MoeLoraBatch(
gate_up_lora_a=self.gate_up_lora_a_weights,
gate_up_lora_b=self.gate_up_lora_b_weights,
down_lora_a=self.down_lora_a_weights,
down_lora_b=self.down_lora_b_weights,
token_lora_mapping=batch_info.token_slots[: batch_info.num_tokens],
use_cuda_graph=batch_info.use_cuda_graph,
is_prefill=batch_info.is_prefill,
),
)
def _forward_with_lora(
self,
hidden_states: torch.Tensor,
@@ -1328,11 +1416,25 @@ class FusedMoEWithLoRA(BaseLayerWithLoRA):
def get_lora_layer(
layer: nn.Module, lora_backend: BaseLoRABackend
layer: nn.Module,
lora_backend: BaseLoRABackend,
*,
experts_shared_outer_loras: bool = False,
max_lora_rank: Optional[int] = None,
) -> BaseLayerWithLoRA:
if isinstance(layer, FusedMoE):
return FusedMoEWithLoRA(
layer,
lora_backend,
experts_shared_outer_loras=experts_shared_outer_loras,
max_lora_rank=max_lora_rank,
)
# Inkling QKVR needs custom LoRA-B slicing despite being a merged linear.
if getattr(layer, "is_inkling_qkvr", False):
return InklingQKVRLinearWithLoRA(layer, lora_backend)
supported_layer_types = {
# the order matters
FusedMoE: FusedMoEWithLoRA,
ParallelLMHead: ParallelLMHeadWithLoRA,
VocabParallelEmbedding: VocabParallelEmbeddingWithLoRA,
ReplicatedLinear: ReplicatedLinearWithLoRA,
@@ -1341,14 +1443,9 @@ def get_lora_layer(
ColumnParallelLinear: ColumnParallelLinearWithLoRA,
RowParallelLinear: RowParallelLinearWithLoRA,
}
# Inkling's fused qkvr needs replication-aware LoRA-B slicing (see InklingQKVRLinear);
# it IS a MergedColumnParallelLinear, so this must precede the isinstance loop.
if getattr(layer, "is_inkling_qkvr", False):
return InklingQKVRLinearWithLoRA(layer, lora_backend)
for src_layer_type, lora_layer_type in supported_layer_types.items():
if isinstance(layer, src_layer_type): # pylint: disable=unidiomatic-typecheck
ret = lora_layer_type(layer, lora_backend)
return ret
return lora_layer_type(layer, lora_backend)
raise Exception(f"No corresponding LoRA layer supported for {type(layer)}.")
+85 -51
View File
@@ -122,6 +122,9 @@ class LoRAManager:
self._experts_shared_outer_override: Optional[bool] = (
get_lora().experts_shared_outer_loras
)
from sglang.srt.layers.moe.utils import get_moe_runner_backend
self.moe_lora_runner_backend = get_moe_runner_backend()
self.lora_use_virtual_experts: bool = get_lora().lora_use_virtual_experts
self.lora_strict_loading: bool = get_lora().lora_strict_loading
self.speculative_algorithm: Optional[str] = get_spec().speculative_algorithm
@@ -146,16 +149,12 @@ class LoRAManager:
lora_paths=lora_paths,
)
def init_cuda_graph_batch_info(
def init_decode_cuda_graph_batch_info(
self, max_bs_in_cuda_graph: int, num_tokens_per_req: int
):
"""Phase 2 of LoRA CUDA graph init: dense LoRA batch metadata.
Called during CudaGraphRunner.__init__(), after init_memory_pool().
Phase 1 (MoE buffers) is handled earlier via init_cuda_graph_moe_buffers().
"""
self.max_bs_in_cuda_graph = max_bs_in_cuda_graph
self.lora_backend.init_cuda_graph_batch_info(
"""Initialize decode-runner metadata after model memory-pool setup."""
self.max_bs_in_decode_cuda_graph = max_bs_in_cuda_graph
self.lora_backend.init_decode_cuda_graph_batch_info(
max_bs_in_cuda_graph=max_bs_in_cuda_graph,
num_tokens_per_req=num_tokens_per_req,
)
@@ -247,12 +246,16 @@ class LoRAManager:
)
def init_cuda_graph_moe_buffers(
self, max_bs: int, max_loras: int, compute_dtype, moe_layer
self,
max_bs: int,
max_loras: int,
compute_dtype,
moe_layer,
):
"""Phase 1 of LoRA CUDA graph init: MoE intermediate buffers.
Called before init_memory_pool() so memory profiling accounts for them.
Phase 2 (dense batch metadata) is handled later via init_cuda_graph_batch_info().
Phase 2 (dense batch metadata) uses init_decode_cuda_graph_batch_info().
"""
self.lora_backend.init_cuda_graph_moe_buffers(
max_bs=max_bs,
@@ -322,6 +325,15 @@ class LoRAManager:
return self.create_lora_update_result(success=True)
def _validate_replicated_q_targets(self, target_modules):
# q_proj adapter targets normalize to qkv_proj.
unsupported = set(target_modules) & {"q_b_proj", "qkv_proj", "kv_b_proj"}
if unsupported and get_parallel().dcp_replicate_q_proj:
raise ValueError(
f"Replicated-Q decode is incompatible with LoRA targets {sorted(unsupported)}; "
"pass --no-dcp-replicate-q-proj to use the local-head Q path."
)
def validate_new_adapter(self, lora_config: LoRAConfig, lora_ref: LoRARef):
"""
Validate if an adapter can be loaded into the current LoRA memory pool and generate error if it is incompatible.
@@ -479,6 +491,9 @@ class LoRAManager:
metadata."""
self.lora_backend.reset_batch_state()
def reset_routing_cache(self) -> None:
self.lora_backend.reset_routing_cache()
def prepare_lora_batch(self, forward_batch: ForwardBatch):
# Some internal-only backends (currently UNO) use explicit token-row
# routing for their adapted forwards and want all-base batches to run
@@ -491,11 +506,11 @@ class LoRAManager:
return
# set up batch info shared by all lora modules
use_cuda_graph = self._use_cuda_graph_batch(forward_batch)
use_decode_cuda_graph = self._use_cuda_graph_batch(forward_batch)
# Eligible extend batches refresh the static prefill batch info in
# place so captured kernels read current values at replay.
use_prefill_cuda_graph = not use_cuda_graph and self.can_use_prefill_cuda_graph(
forward_batch
use_prefill_cuda_graph = (
not use_decode_cuda_graph and self.can_use_prefill_cuda_graph(forward_batch)
)
active_lora_ids = set(forward_batch.lora_ids)
@@ -534,16 +549,20 @@ class LoRAManager:
# Do in-place updates when CUDA graph is enabled and the batch forward mode
# could use CUDA graph.
self.lora_backend.prepare_lora_batch(
forward_batch=forward_batch,
weight_indices=weight_indices,
lora_ranks=lora_ranks,
scalings=scalings,
use_cuda_graph=use_cuda_graph,
forward_batch,
weight_indices,
lora_ranks,
scalings,
use_decode_cuda_graph,
use_prefill_cuda_graph=use_prefill_cuda_graph,
)
self.lora_backend.batch_info.has_active_lora = any(
lora_ranks[wi] > 0 for wi in weight_indices
)
self.lora_backend.batch_info.is_prefill = (
forward_batch.forward_mode.is_extend()
and not forward_batch.forward_mode.is_cuda_graph()
)
if self.attn_dp_enabled:
self.lora_backend.prepare_global_lora_batch(forward_batch)
if forward_batch.forward_mode.is_idle():
@@ -553,8 +572,8 @@ class LoRAManager:
def _use_cuda_graph_batch(self, forward_batch: ForwardBatch) -> bool:
return (
hasattr(self, "max_bs_in_cuda_graph")
and forward_batch.batch_size <= self.max_bs_in_cuda_graph
hasattr(self, "max_bs_in_decode_cuda_graph")
and forward_batch.batch_size <= self.max_bs_in_decode_cuda_graph
and forward_batch.forward_mode.is_cuda_graph()
and (not self.attn_dp_enabled or forward_batch.can_run_decode_cuda_graph)
)
@@ -705,6 +724,7 @@ class LoRAManager:
base_model=self.base_model,
target_modules=self.target_modules,
)
self._validate_replicated_q_targets(self.target_modules)
if self._experts_shared_outer_override is not None:
self.experts_shared_outer_loras = self._experts_shared_outer_override
@@ -858,19 +878,18 @@ class LoRAManager:
# Fusion folds wk + weights_proj into wk_weights_proj, so the modules
# LoRA wraps are absent and an indexer-targeted adapter is silently dropped.
# Each Indexer decides fusion when it is built (CUDA, env, RoPE style).
indexer_targets = self.target_modules & DSA_INDEXER_LORA_NAMES
if indexer_targets:
from sglang.srt.layers.attention.dsa.dsa_indexer import (
_use_dsa_indexer_fusion,
if indexer_targets and any(
getattr(module, "use_dsa_indexer_fusion", False)
for _, module in self.base_model.named_modules()
):
raise ValueError(
f"LoRA targets the DSA indexer ({sorted(indexer_targets)}), which is "
"incompatible with DSA indexer Q/K fusion. Set "
"SGLANG_DISABLE_DSA_INDEXER_FUSION=1 to disable fusion and use indexer LoRA."
)
if _use_dsa_indexer_fusion:
raise ValueError(
f"LoRA targets the DSA indexer ({sorted(indexer_targets)}), which is "
"incompatible with DSA indexer Q/K fusion. Set "
"SGLANG_DISABLE_DSA_INDEXER_FUSION=1 to disable fusion and use indexer LoRA."
)
if max_lora_rank is not None:
self.max_lora_rank = max_lora_rank
else:
@@ -1013,9 +1032,9 @@ class LoRAManager:
# Initializing memory pool with base model
self.fetch_new_loras({None})
def set_lora_module(self, module_name, module):
def set_lora_module(self, module_name, module, **kwargs):
"""Wrap any module (standard or MoE) with LoRA support."""
lora_module = get_lora_layer(module, self.lora_backend)
lora_module = get_lora_layer(module, self.lora_backend, **kwargs)
replace_submodule(self.base_model, module_name, lora_module)
return lora_module
@@ -1148,21 +1167,37 @@ class LoRAManager:
# `self.lora_modules` with `None`.
continue
if isinstance(module, InklingBatchDenseMLP):
from sglang.srt.models.inkling_common.lora import (
InklingBatchDenseMLPWithLoRA,
)
module.__class__ = InklingBatchDenseMLPWithLoRA
module.initialize_lora(self.lora_backend)
logger.info_once(
"Inkling shared-sink LoRA: %s on the %s backend",
type(module).__name__,
self.lora_backend.name,
)
lora_module = module
else:
lora_module = self.set_lora_module(module_name, module)
lora_module.experts_shared_outer_loras = (
self.experts_shared_outer_loras
lora_module = self.set_lora_module(
module_name,
module,
experts_shared_outer_loras=self.experts_shared_outer_loras,
max_lora_rank=self.max_lora_rank,
)
lora_module.lora_use_virtual_experts = self.lora_use_virtual_experts
self.lora_modules[layer_id][module_name] = lora_module
# lora_* quant methods leave execution to the LoRA wrapper; reject
# target sets that leave every MoE layer without one.
backend = getattr(self, "moe_lora_runner_backend", None)
if backend is not None and backend.is_lora():
modules = list(self.base_model.modules())
if any(isinstance(module, FusedMoE) for module in modules) and not any(
isinstance(module, FusedMoEWithLoRA) for module in modules
):
raise ValueError(
f"--moe-runner-backend {backend.value} requires "
"the LoRA target modules to include gate_up_proj and down_proj; "
"this adapter leaves the MoE experts without a runner"
)
def init_lora_cuda_graph_moe_buffers(
*,
@@ -1170,18 +1205,14 @@ def init_lora_cuda_graph_moe_buffers(
lora_manager: LoRAManager,
dtype: torch.dtype,
):
"""Phase 1 of LoRA CUDA graph init: pre-allocate MoE intermediate buffers.
"""Allocate legacy MoE buffers before init_memory_pool() sizes the KV cache.
Must be called before init_memory_pool() so that memory profiling
sees the reduced available memory and sizes KV cache correctly.
All MoE LoRA layers share one set of buffers (managed by the
lora_backend) since they execute sequentially during forward.
Phase 2 (dense LoRA batch metadata) is handled later in
CudaGraphRunner.__init__() via lora_manager.init_cuda_graph_batch_info(),
because it needs capture-time parameters (max_bs, num_tokens_per_req)
that are only available at that stage.
Sequential MoE layers reuse these buffers. Dense batch metadata is allocated
later by DecodeCudaGraphRunner, which owns the capture-time batch sizes.
"""
if lora_manager.lora_backend.name == "triton_v2":
logger.debug("V2 MoE scratch is allocated during warmup, not reserved here")
return
from sglang.srt.lora.layers import FusedMoEWithLoRA
max_bs = get_exec().graph.cuda_graph_config.decode.max_bs
@@ -1201,7 +1232,10 @@ def init_lora_cuda_graph_moe_buffers(
for module in model.modules():
if isinstance(module, FusedMoEWithLoRA):
lora_manager.init_cuda_graph_moe_buffers(
max_tokens, max_loras, dtype, module
max_tokens,
max_loras,
dtype,
module,
)
logger.info(
f"Pre-allocated shared MoE LoRA CUDA graph buffers "
+8 -3
View File
@@ -350,9 +350,7 @@ class LoRAMemoryPool:
return any(isinstance(m, FusedMoE) for m in base_model.modules())
def _get_num_local_experts(self, base_model: torch.nn.Module) -> int:
"""Experts owned by this rank. Equals the global count when EP is
off, the runner keeps global IDs, or the split isn't even (all
three cases fold into `moe_use_local_expert_ids == False`)."""
"""Resident factor count; new MoE LoRA providers use EP-local factors."""
total = self._get_num_experts(base_model)
if not self.moe_use_local_expert_ids:
return total
@@ -1015,6 +1013,13 @@ class LoRAMemoryPool:
else:
temp_B_buffer[target_module] = weights
temp_B_cache_keys[target_module] = name
elif is_shared_expert and expert_match:
# Without a shared-MoE destination, "shared_experts.<id>."
# would match "experts.<id>." and overwrite routed weights.
raise ValueError(
f"Cannot load LoRA weight {name!r}: layer {layer_id} has no "
"matching target for indexed shared-expert weights."
)
elif expert_match:
# Per-expert MoE weight — 2D tensors, one per expert
target_module = target_module + "_moe"
+1
View File
@@ -0,0 +1 @@
"""MoE LoRA execution plans, runner, and base-GEMM providers."""
@@ -0,0 +1,85 @@
"""Lazy selection of base-MoE providers."""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from sglang.srt.lora.moe.base_gemm_provider.base import MoeBaseProvider
logger = logging.getLogger(__name__)
# The first vendor is the default for each weight family.
VENDORS = {
"bf16": ("cutedsl", "triton"),
"fp8": ("cutedsl", "triton"),
"nvfp4": ("marlin",),
}
def select_provider_cls(
base_gemm_rows: str, family: str, vendor: str | None = None
) -> type[MoeBaseProvider]:
"""Use the family default when the requested vendor cannot serve it.
Triton and Marlin use route-major rows for either requested row order.
"""
if base_gemm_rows not in ("expert_major", "route_major"):
raise ValueError(
f"unknown MoE LoRA base-GEMM row order {base_gemm_rows!r}; "
"expected 'expert_major' or 'route_major'"
)
vendors = VENDORS[family]
if vendor not in vendors:
if vendor is not None:
logger.info(
"MoE LoRA base-GEMM vendor %r serves no %s layers; this layer "
"family uses its default vendor %r",
vendor,
family,
vendors[0],
)
vendor = vendors[0]
expert_major = base_gemm_rows == "expert_major"
match vendor, family:
case "cutedsl", "bf16":
from sglang.srt.lora.moe.base_gemm_provider.cutedsl_bf16 import (
CuteDslBf16ContiguousProvider,
CuteDslBf16MaskedProvider,
)
return (
CuteDslBf16MaskedProvider
if expert_major
else CuteDslBf16ContiguousProvider
)
case "cutedsl", "fp8":
from sglang.srt.lora.moe.base_gemm_provider.cutedsl_fp8 import (
CuteDslFp8ContiguousProvider,
CuteDslFp8MaskedProvider,
)
return (
CuteDslFp8MaskedProvider
if expert_major
else CuteDslFp8ContiguousProvider
)
case "triton", "bf16":
from sglang.srt.lora.moe.base_gemm_provider.triton_bf16 import (
TritonBf16ContiguousProvider,
)
return TritonBf16ContiguousProvider
case "triton", "fp8":
from sglang.srt.lora.moe.base_gemm_provider.triton_fp8 import (
TritonFp8ContiguousProvider,
)
return TritonFp8ContiguousProvider
case "marlin", "nvfp4":
from sglang.srt.lora.moe.base_gemm_provider.marlin_nvfp4 import (
MarlinNvFp4ContiguousProvider,
)
return MarlinNvFp4ContiguousProvider
@@ -0,0 +1,305 @@
"""Base MoE stages with insertion points for LoRA."""
from __future__ import annotations
from collections.abc import Mapping
from typing import TYPE_CHECKING
import msgspec
import torch
if TYPE_CHECKING:
from sglang.kernels.ops.lora.common.route_view import RouteView
from sglang.srt.lora.moe.plan import FinalizeFamily, MoeLoraLaunchConfig
from sglang.srt.lora.workspace import LoraWorkspace
# Token-count cutoff for the vectorized top-k gather.
_SMALL_FINALIZE_MAX_TOKENS = 64
class MoeBaseProviderContract(msgspec.Struct, frozen=True, kw_only=True):
key: str
quant_info_cls: type
# Base output order; the LoRA delta is always [gate | up].
gate_first: bool
interleaved: bool
gate_up_output_dtype: torch.dtype
lora_delta_dtype: torch.dtype
lora_activation_dtype: torch.dtype
# Fuse FP8 quantization into activation for the down GEMM.
act_quant_group: int | None = None
def expected_rows_per_expert(num_pairs: int, num_experts: int) -> int:
"""Rounded-up mean rows per expert; use one for an empty batch."""
return (num_pairs - 1) // num_experts + 1 if num_pairs else 1
def prepare_buffer(workspace, name: str, shape, *, dtype, device) -> torch.Tensor:
if workspace is not None:
return workspace.tensor(name, shape, dtype=dtype, device=device)
return torch.empty(shape, dtype=dtype, device=device)
def admit_weight_layout(quant_info) -> int:
"""Validate [E, S*I, H] / [E, H, I] weights and return S."""
if quant_info.intermediate_size <= 0:
raise ValueError("intermediate_size must be positive")
expected_w2 = (
quant_info.num_local_experts,
quant_info.hidden_size,
quant_info.intermediate_size,
)
if quant_info.w2_weight.shape != expected_w2:
raise ValueError(
f"w2_weight must be {expected_w2}, got {tuple(quant_info.w2_weight.shape)}"
)
if (
quant_info.w13_weight.ndim != 3
or quant_info.w13_weight.shape[0] != quant_info.num_local_experts
or quant_info.w13_weight.shape[2] != quant_info.hidden_size
):
raise ValueError(
"w13_weight must be [num_local_experts, slices*intermediate, hidden]"
)
gateup_width = quant_info.w13_weight.shape[1]
if gateup_width % quant_info.intermediate_size:
raise ValueError(
"w13 output width must be an integer multiple of intermediate_size"
)
gate_up_slices = gateup_width // quant_info.intermediate_size
if gate_up_slices not in (1, 2):
raise ValueError(
"the base providers support one non-gated slice or two gated "
f"gate/up slices, got {gate_up_slices}"
)
return gate_up_slices
class MoeBaseProvider:
"""One provider per layer; logical sizes come from quant_info."""
contract: MoeBaseProviderContract
@property
def num_local_experts(self) -> int:
return self.quant_info.num_local_experts
@property
def intermediate_size(self) -> int:
"""Logical intermediate width of one TP shard."""
return self.quant_info.intermediate_size
@property
def hidden_size(self) -> int:
return self.quant_info.hidden_size
@property
def gate_up_slices(self) -> int:
return self._gate_up_slices
def prepare(
self,
hidden_states: torch.Tensor,
topk_ids: torch.Tensor,
top_k: int,
workspace: LoraWorkspace | None = None,
):
"""Prepare rows with graph-stable buffers when a workspace is supplied."""
raise NotImplementedError
def gateup(self, row_state, out: torch.Tensor) -> None:
raise NotImplementedError
def release_prepared_inputs(self, row_state) -> None:
raise NotImplementedError
def act_with_delta(
self,
row_state,
gateup_out: torch.Tensor,
gate_up_delta: torch.Tensor | None,
topk_ids: torch.Tensor,
act_out: torch.Tensor,
activation_lora_input: torch.Tensor,
*,
activation: str = "silu",
) -> None:
raise NotImplementedError
def fused_act(
self,
row_state,
*,
activation: str,
base_gateup: torch.Tensor,
act_rows: torch.Tensor,
act_pairs: torch.Tensor | None,
routing: RouteView,
config: Mapping[str, int],
bridge_gateup: torch.Tensor | None = None,
b_gate_up: torch.Tensor | None = None,
bridge_top_k: int = 1,
) -> None:
raise NotImplementedError(
f"{self.contract.key} has no fused-act implementation"
)
def down(
self,
row_state,
act_out: torch.Tensor,
out: torch.Tensor,
) -> None:
raise NotImplementedError
def down_output(self, row_state, workspace: LoraWorkspace) -> torch.Tensor:
return workspace.tensor(
"base:down",
self.down_out_shape(row_state),
dtype=torch.bfloat16,
device=row_state.pair_to_row.device,
)
def finalize(
self,
row_state,
down_out: torch.Tensor,
topk_ids: torch.Tensor,
topk_weights: torch.Tensor,
routed_scaling_factor: float | None,
output: torch.Tensor,
*,
lora_delta: torch.Tensor | None = None,
) -> None:
"""Weight base + unweighted LoRA delta [T, K, H], then scale once."""
from sglang.kernels.ops.lora.moe.finalize import invoke_small_finalize
from sglang.kernels.ops.moe.ep_moe_kernels import post_reorder_deepgemm
num_tokens, hidden = output.shape
scaling = routed_scaling_factor if routed_scaling_factor is not None else 1.0
if num_tokens <= _SMALL_FINALIZE_MAX_TOKENS and topk_weights.is_contiguous():
# Gather top-k rows together instead of issuing dependent row loads.
invoke_small_finalize(
down_out.view(-1, hidden),
output,
row_state.pair_to_row,
topk_weights,
scaling,
lora_delta=lora_delta,
)
return
post_reorder_deepgemm(
down_out.view(-1, hidden),
output,
row_state.pair_to_row,
topk_ids,
topk_weights.contiguous(),
topk_ids.shape[1],
num_tokens,
hidden,
scaling,
lora_delta=lora_delta,
)
def shared_outer_finalize(
self,
row_state,
*,
down_rows: torch.Tensor,
bridge: torch.Tensor,
b_down: torch.Tensor,
routing: RouteView,
topk_weights: torch.Tensor,
routed_scaling_factor: float | None,
output: torch.Tensor,
family: FinalizeFamily,
launch_config: MoeLoraLaunchConfig,
workspace: LoraWorkspace,
token_route: RouteView | None,
) -> None:
"""Apply shared down-B with the plan's fused or staged finalize."""
from sglang.srt.lora.moe.plan import FinalizeFamily, Site
if topk_weights.dtype != torch.float32:
raise TypeError(
"topk_weights must stay FP32 until the finalize applies them"
)
if family is FinalizeFamily.SHARED_ONE_PASS:
from sglang.kernels.ops.lora.moe.finalize import invoke_shared_one_pass
invoke_shared_one_pass(
num_local_experts=self.num_local_experts,
down_rows=down_rows,
pair_to_row=row_state.pair_to_row,
bridge=bridge,
b_down=b_down,
routing=routing,
topk_weights=topk_weights,
routed_scaling_factor=routed_scaling_factor,
output=output,
config=launch_config.shared_one_pass,
)
return
if family is not FinalizeFamily.SHARED_TOKEN_DELTA:
raise ValueError(f"not a shared-outer finalize family: {family}")
if token_route is None:
raise ValueError("shared token route was not constructed")
num_tokens = output.shape[0]
token_rank = workspace.tensor(
"finalize:shared_token_rank",
(num_tokens, bridge.shape[1]),
dtype=bridge.dtype,
device=bridge.device,
)
token_delta = workspace.tensor(
"finalize:shared_token_delta",
(num_tokens, self.hidden_size),
dtype=self.contract.lora_delta_dtype,
device=bridge.device,
)
from sglang.kernels.ops.lora.moe.finalize import (
invoke_shared_token_delta_reduce,
invoke_shared_token_delta_tail,
)
from sglang.kernels.ops.lora.moe.lora_b import grouped_lora_b
invoke_shared_token_delta_reduce(
num_local_experts=self.num_local_experts,
bridge=bridge,
routing=routing,
topk_weights=topk_weights,
token_rank=token_rank,
config=launch_config.shared_token_delta["reduce"],
)
grouped_lora_b(
token_rank,
b_down,
token_delta,
token_route,
destination_offsets=(0,),
config=launch_config.for_b(Site.DOWN),
pair_bridge=True,
)
invoke_shared_token_delta_tail(
num_local_experts=self.num_local_experts,
down_rows=down_rows,
pair_to_row=row_state.pair_to_row,
token_delta=token_delta,
routing=routing,
topk_weights=topk_weights,
routed_scaling_factor=routed_scaling_factor,
output=output,
config=launch_config.shared_token_delta["tail"],
)
def gateup_out_shape(self, row_state) -> tuple[int, ...]:
raise NotImplementedError
def act_out_shape(self, row_state) -> tuple[int, ...]:
raise NotImplementedError
def down_out_shape(self, row_state) -> tuple[int, ...]:
raise NotImplementedError
@@ -0,0 +1,212 @@
"""Routed rows packed into aligned, contiguous expert segments."""
from __future__ import annotations
from collections.abc import Mapping
from typing import TYPE_CHECKING
import msgspec
import torch
from sglang.kernels.ops.lora.moe.activation_delta import act_delta
from sglang.kernels.ops.lora.moe.dispatch_contiguous import (
contiguous_m_pad_ceiling,
dispatch_fill_rows_contiguous_bf16,
dispatch_layout_contiguous,
)
from sglang.kernels.ops.lora.moe.fused_act import fused_b_act
from sglang.srt.lora.moe.base_gemm_provider.base import (
MoeBaseProvider,
admit_weight_layout,
prepare_buffer,
)
from sglang.srt.lora.moe.quant_info import StandardLayoutQuantInfo
if TYPE_CHECKING:
from sglang.kernels.ops.lora.common.route_view import RouteView
from sglang.srt.lora.workspace import LoraWorkspace
class ContiguousRowState(msgspec.Struct, kw_only=True):
hidden_compact: torch.Tensor | None # [m_pad_ceiling, hidden], the GEMM input dtype
seg_counts: torch.Tensor # [E_local] int32
seg_offsets: torch.Tensor # [E_local + 1] int32 first row of each segment
pair_to_row: torch.Tensor # [num_tokens * top_k] int32 compact rows
m_pad_ceiling: int
input_buffer_reuse: bool
# Quantized activation and scales for the down GEMM.
act_quant: tuple[torch.Tensor, torch.Tensor] | None = None
class ContiguousRowDomainProvider(MoeBaseProvider):
def __init__(self, quant_info: StandardLayoutQuantInfo, *, m_alignment: int):
self.quant_info = quant_info
if not isinstance(m_alignment, int) or m_alignment < 1:
raise ValueError(f"m_alignment must be a positive int, got {m_alignment!r}")
self._m_alignment = m_alignment
self._gate_up_slices = admit_weight_layout(quant_info)
def prepare(
self,
hidden_states: torch.Tensor,
topk_ids: torch.Tensor,
top_k: int,
workspace: LoraWorkspace | None = None,
*,
fill_rows: bool = True,
) -> ContiguousRowState:
num_pairs = topk_ids.numel()
num_experts = self.quant_info.num_local_experts
m_pad_ceiling = contiguous_m_pad_ceiling(
num_pairs, num_experts, self._m_alignment
)
device = hidden_states.device
prefix = f"contiguous:a{self._m_alignment}"
seg_counts = prepare_buffer(
workspace,
f"{prefix}:seg_counts",
(num_experts,),
dtype=torch.int32,
device=device,
)
seg_offsets = prepare_buffer(
workspace,
f"{prefix}:seg_offsets",
(num_experts + 1,),
dtype=torch.int32,
device=device,
)
pair_to_row = prepare_buffer(
workspace,
f"{prefix}:pair_to_row",
(num_pairs,),
dtype=torch.int32,
device=device,
)
if workspace is not None:
# Padding outputs are ignored, so reused padding needs no reset.
hidden_compact = (
None
if not fill_rows
else workspace.tensor(
f"{prefix}:hidden_compact",
(m_pad_ceiling, hidden_states.size(1)),
dtype=torch.bfloat16,
device=device,
zero_on_first_allocation=True,
)
)
else:
hidden_compact = (
None
if not fill_rows
else torch.zeros(
(m_pad_ceiling, hidden_states.size(1)),
dtype=torch.bfloat16,
device=device,
)
)
dispatch_layout_contiguous(
hidden_states,
topk_ids,
num_experts,
top_k,
self._m_alignment,
seg_counts_out=seg_counts,
seg_offsets_out=seg_offsets,
pair_to_row_out=pair_to_row,
)
if hidden_compact is not None:
dispatch_fill_rows_contiguous_bf16(
hidden_states, topk_ids, pair_to_row, hidden_compact_out=hidden_compact
)
return ContiguousRowState(
hidden_compact=hidden_compact,
seg_counts=seg_counts,
seg_offsets=seg_offsets,
pair_to_row=pair_to_row,
m_pad_ceiling=m_pad_ceiling,
input_buffer_reuse=workspace is not None,
)
def release_prepared_inputs(self, row_state: ContiguousRowState) -> None:
# Workspace buffers retain their addresses for graph replay.
if row_state.input_buffer_reuse or row_state.hidden_compact is None:
return
from sglang.srt.utils import dispose_tensor
dispose_tensor(row_state.hidden_compact)
def act_with_delta(
self,
row_state: ContiguousRowState,
gateup_out: torch.Tensor,
gate_up_delta: torch.Tensor | None,
topk_ids: torch.Tensor,
act_out: torch.Tensor,
activation_lora_input: torch.Tensor,
*,
activation: str = "silu",
act_quant: tuple[torch.Tensor, torch.Tensor] | None = None,
) -> None:
if act_quant is not None:
row_state.act_quant = act_quant
act_delta(
gateup_out,
gate_up_delta,
act_out,
activation_lora_input,
row_state.pair_to_row,
topk_ids,
num_local_experts=self.num_local_experts,
gate_first=self.contract.gate_first,
interleaved=self.contract.interleaved,
activation=activation,
act_quant=(
(*act_quant, self.contract.act_quant_group)
if act_quant is not None
else None
),
)
def fused_act(
self,
row_state: ContiguousRowState,
*,
activation: str,
base_gateup: torch.Tensor,
act_rows: torch.Tensor,
act_pairs: torch.Tensor | None,
routing: RouteView,
config: Mapping[str, int],
bridge_gateup: torch.Tensor | None = None,
b_gate_up: torch.Tensor | None = None,
bridge_top_k: int = 1,
) -> None:
fused_b_act(
activation=activation,
base_gateup=base_gateup,
act_rows=act_rows,
act_pairs=act_pairs,
pair_to_row=row_state.pair_to_row,
routing=routing,
num_local_experts=self.num_local_experts,
gate_first=self.contract.gate_first,
interleaved=self.contract.interleaved,
config=config,
bridge_gateup=bridge_gateup,
b_gate_up=b_gate_up,
bridge_top_k=bridge_top_k,
)
def gateup_out_shape(self, row_state: ContiguousRowState) -> tuple[int, ...]:
return (
row_state.m_pad_ceiling,
self.gate_up_slices * self.quant_info.intermediate_size,
)
def act_out_shape(self, row_state: ContiguousRowState) -> tuple[int, ...]:
return (row_state.m_pad_ceiling, self.quant_info.intermediate_size)
def down_out_shape(self, row_state: ContiguousRowState) -> tuple[int, ...]:
return (row_state.m_pad_ceiling, self.quant_info.hidden_size)
@@ -0,0 +1,383 @@
from __future__ import annotations
from typing import TYPE_CHECKING
import torch
from sglang.kernels.ops.lora.moe.dispatch_masked_small import (
small_masked_prepare,
small_masked_prepare_applies,
)
from sglang.srt.lora.moe.base_gemm_provider.base import (
MoeBaseProviderContract,
expected_rows_per_expert,
)
from sglang.srt.lora.moe.base_gemm_provider.contiguous_row_domain import (
ContiguousRowDomainProvider,
ContiguousRowState,
)
from sglang.srt.lora.moe.base_gemm_provider.cutedsl_common import CuteDslTileMixin
from sglang.srt.lora.moe.base_gemm_provider.masked_row_domain import (
MaskedRowDomainProvider,
MaskedRowState,
masked_m_max,
prepare_buffer,
)
from sglang.srt.lora.moe.quant_info import MoeLoraBf16QuantInfo
if TYPE_CHECKING:
from sglang.srt.lora.workspace import LoraWorkspace
class _CuteDslBf16Mixin(CuteDslTileMixin):
_DTYPE_TAG = "bf16"
WIDE_EXPECTED_M_THRESHOLD = 16
def _launch(
self,
stage: str,
a: torch.Tensor,
c: torch.Tensor,
row_state,
schedule: torch.Tensor,
tiles: torch.Tensor,
) -> None:
call = self._compiled[row_state.token_width][stage]
# Runtime wrapping must match the compiled argument's MLIR type.
dyn = self._as_dynamic_cute_tensor
call.compiled_fn(
dyn(self._rows_arg(a), leading_dim=2),
call.b_arg,
dyn(self._rows_arg(c), leading_dim=2),
dyn(self._group_arg(row_state), leading_dim=0),
dyn(schedule, leading_dim=0),
dyn(tiles, leading_dim=0),
self._stream(a.device),
)
def gateup(self, row_state, out: torch.Tensor) -> None:
self._launch(
"gemm1",
self._input_rows(row_state),
out,
row_state,
row_state.gemm1_schedule,
row_state.gemm1_tiles,
)
def down(self, row_state, act_out: torch.Tensor, out: torch.Tensor) -> None:
self._launch(
"gemm2",
act_out,
out,
row_state,
row_state.gemm2_schedule,
row_state.gemm2_tiles,
)
def down_output(self, row_state, workspace: LoraWorkspace) -> torch.Tensor:
# Gate/up has finished reading the prepared rows before down starts.
if row_state.input_buffer_reuse:
return self._input_rows(row_state)
return super().down_output(row_state, workspace)
class CuteDslBf16MaskedRowState(MaskedRowState, kw_only=True):
token_width: int
gemm1_schedule: torch.Tensor
gemm1_tiles: torch.Tensor
gemm2_schedule: torch.Tensor
gemm2_tiles: torch.Tensor
class CuteDslBf16MaskedProvider(_CuteDslBf16Mixin, MaskedRowDomainProvider):
contract = MoeBaseProviderContract(
key="cutedsl_bf16_masked",
quant_info_cls=MoeLoraBf16QuantInfo,
gate_first=True,
interleaved=False,
gate_up_output_dtype=torch.bfloat16,
lora_delta_dtype=torch.bfloat16,
lora_activation_dtype=torch.bfloat16,
)
_ROW_MODE = "masked"
def __init__(self, quant_info: MoeLoraBf16QuantInfo):
super().__init__(quant_info)
from sglang.kernels.ops.lora.moe.cutedsl.api import prepare_masked_bf16
from sglang.kernels.ops.lora.moe.cutedsl.schedule_builder import (
build_dual_stage_schedules_masked,
dual_stage_schedule_capacities_masked,
)
self._prepare_masked_gemm = prepare_masked_bf16
self._build_schedules = build_dual_stage_schedules_masked
self._schedule_capacities = dual_stage_schedule_capacities_masked
self._init_tiles(quant_info)
def _prepare_dummy(self, stage: str, config):
weight = self._stage_weight(stage)
device = weight.device
experts, n, k = weight.shape
# Compile the layout with a dynamic M extent.
dummy_a = torch.zeros((experts, 256, k), dtype=torch.bfloat16, device=device)
dummy_c = torch.empty((experts, 256, n), dtype=torch.bfloat16, device=device)
dummy_masked = torch.zeros(experts, dtype=torch.int32, device=device)
return self._prepare_masked_gemm(
dummy_a,
weight,
dummy_c,
dummy_masked,
config=config,
)
@staticmethod
def _rows_arg(tensor: torch.Tensor) -> torch.Tensor:
return tensor
@staticmethod
def _input_rows(row_state: CuteDslBf16MaskedRowState) -> torch.Tensor:
return row_state.hidden_permuted
@staticmethod
def _group_arg(row_state: CuteDslBf16MaskedRowState) -> torch.Tensor:
return row_state.masked_m
def _masked_geometry(self, token_width: int) -> dict:
return dict(
token_width=token_width,
n_gemm1=self.gate_up_slices * self.quant_info.intermediate_size,
n_gemm2=self.quant_info.hidden_size,
output_width=self.OUTPUT_WIDTH,
cluster_shape_mn=self.CLUSTER_SHAPE_MN,
use_2cta_instrs=self.USE_2CTA_INSTRS,
)
def prepare(
self,
hidden_states: torch.Tensor,
topk_ids: torch.Tensor,
top_k: int,
workspace: LoraWorkspace | None = None,
) -> CuteDslBf16MaskedRowState:
num_pairs = topk_ids.numel()
if small_masked_prepare_applies(hidden_states.size(0), num_pairs):
# Prepare rows, pair map and both schedules in one launch.
num_experts = self.quant_info.num_local_experts
m_max = masked_m_max(hidden_states.size(0))
expected_m = expected_rows_per_expert(num_pairs, num_experts)
token_width = self._token_width_for(m_max, expected_m)
geometry = self._masked_geometry(token_width)
device = hidden_states.device
masked_m = prepare_buffer(
workspace,
"masked:masked_m",
(num_experts,),
dtype=torch.int32,
device=device,
)
pair_to_row = prepare_buffer(
workspace,
"masked:pair_to_row",
(num_pairs,),
dtype=torch.int32,
device=device,
)
hidden_permuted = prepare_buffer(
workspace,
"masked:hidden_permuted",
(num_experts, m_max, hidden_states.size(1)),
dtype=torch.bfloat16,
device=device,
)
outputs = self._small_prepare_outputs(
workspace,
f"cutedsl_masked:tw{token_width}",
self._schedule_capacities(
num_experts=num_experts, m_max=m_max, **geometry
),
num_experts,
device,
)
small_masked_prepare(
hidden_states,
topk_ids,
top_k,
masked_m_out=masked_m,
pair_to_row_out=pair_to_row,
rows_out=hidden_permuted,
token_width=token_width,
out_clusters1=self._output_clusters(geometry["n_gemm1"]),
out_clusters2=self._output_clusters(geometry["n_gemm2"]),
**outputs,
)
return CuteDslBf16MaskedRowState(
hidden_permuted=hidden_permuted,
masked_m=masked_m,
expected_m=expected_m,
pair_to_row=pair_to_row,
m_max=m_max,
input_buffer_reuse=workspace is not None,
token_width=token_width,
gemm1_schedule=outputs["schedule1_out"],
gemm1_tiles=outputs["tiles1_out"],
gemm2_schedule=outputs["schedule2_out"],
gemm2_tiles=outputs["tiles2_out"],
)
base = super().prepare(hidden_states, topk_ids, top_k, workspace)
token_width = self._token_width_for(base.m_max, base.expected_m)
geometry = self._masked_geometry(token_width)
schedule_outputs = {}
if workspace is not None:
schedule_outputs = self._schedule_buffers(
workspace,
f"cutedsl_masked:tw{token_width}",
self._schedule_capacities(
num_experts=base.masked_m.numel(), m_max=base.m_max, **geometry
),
hidden_states.device,
)
schedule1, tiles1, schedule2, tiles2 = self._build_schedules(
base.masked_m, m_max=base.m_max, **geometry, **schedule_outputs
)
return CuteDslBf16MaskedRowState(
hidden_permuted=base.hidden_permuted,
masked_m=base.masked_m,
expected_m=base.expected_m,
pair_to_row=base.pair_to_row,
m_max=base.m_max,
input_buffer_reuse=base.input_buffer_reuse,
token_width=token_width,
gemm1_schedule=schedule1,
gemm1_tiles=tiles1,
gemm2_schedule=schedule2,
gemm2_tiles=tiles2,
)
class CuteDslBf16ContiguousRowState(ContiguousRowState, kw_only=True):
token_width: int
gemm1_schedule: torch.Tensor
gemm1_tiles: torch.Tensor
gemm2_schedule: torch.Tensor
gemm2_tiles: torch.Tensor
class CuteDslBf16ContiguousProvider(_CuteDslBf16Mixin, ContiguousRowDomainProvider):
contract = MoeBaseProviderContract(
key="cutedsl_bf16_contiguous",
quant_info_cls=MoeLoraBf16QuantInfo,
gate_first=True,
interleaved=False,
gate_up_output_dtype=torch.bfloat16,
lora_delta_dtype=torch.bfloat16,
lora_activation_dtype=torch.bfloat16,
)
# Every compiled token width divides 128.
M_ALIGNMENT = 128
_ROW_MODE = "contiguous"
def __init__(self, quant_info: MoeLoraBf16QuantInfo):
super().__init__(quant_info, m_alignment=self.M_ALIGNMENT)
from sglang.kernels.ops.lora.moe.cutedsl.api import prepare_contiguous_bf16
from sglang.kernels.ops.lora.moe.cutedsl.schedule_builder import (
build_dual_stage_schedules_contiguous,
dual_stage_schedule_capacities_contiguous,
validate_tile_geometry_contiguous,
)
self._prepare_contiguous_gemm = prepare_contiguous_bf16
self._validate_tile_geometry = validate_tile_geometry_contiguous
self._build_schedules_contiguous = build_dual_stage_schedules_contiguous
self._schedule_capacities = dual_stage_schedule_capacities_contiguous
# Hopper prefill uses wide tiles.
device_capability = torch.cuda.get_device_capability(
quant_info.w13_weight.device
)
self._init_tiles(quant_info, drop_narrow_tile=device_capability < (10, 0))
def _admit_tile_width(self, token_width: int) -> None:
self._validate_tile_geometry(token_width, self._m_alignment)
def _prepare_dummy(self, stage: str, config):
weight = self._stage_weight(stage)
device = weight.device
num_experts, n, k = weight.shape
# Compile the layout with a dynamic M extent.
dummy_a = torch.zeros((256, k), dtype=torch.bfloat16, device=device)
dummy_c = torch.empty((256, n), dtype=torch.bfloat16, device=device)
dummy_seg = torch.zeros(num_experts + 1, dtype=torch.int32, device=device)
return self._prepare_contiguous_gemm(
dummy_a,
weight,
dummy_c,
dummy_seg,
config=config,
)
@staticmethod
def _rows_arg(tensor: torch.Tensor) -> torch.Tensor:
# Flat rows occupy one expert slot in the swap_ab wrapper.
return tensor.unsqueeze(0)
@staticmethod
def _input_rows(row_state: CuteDslBf16ContiguousRowState) -> torch.Tensor:
return row_state.hidden_compact
@staticmethod
def _group_arg(row_state: CuteDslBf16ContiguousRowState) -> torch.Tensor:
return row_state.seg_offsets
def prepare(
self,
hidden_states: torch.Tensor,
topk_ids: torch.Tensor,
top_k: int,
workspace: LoraWorkspace | None = None,
) -> CuteDslBf16ContiguousRowState:
base = super().prepare(hidden_states, topk_ids, top_k, workspace)
num_experts = self.quant_info.num_local_experts
# Distinct top-k experts bound each expert to one row per token.
max_expert_rows = max(int(hidden_states.size(0)), 1)
expected_m = expected_rows_per_expert(topk_ids.numel(), num_experts)
token_width = self._token_width_for(max_expert_rows, expected_m)
geometry = dict(
m_pad_ceiling=base.m_pad_ceiling,
max_expert_rows=max_expert_rows,
m_alignment=self._m_alignment,
token_width=token_width,
n_gemm1=self.gate_up_slices * self.quant_info.intermediate_size,
n_gemm2=self.quant_info.hidden_size,
output_width=self.OUTPUT_WIDTH,
cluster_shape_mn=self.CLUSTER_SHAPE_MN,
use_2cta_instrs=self.USE_2CTA_INSTRS,
)
schedule_outputs = {}
if workspace is not None:
schedule_outputs = self._schedule_buffers(
workspace,
f"cutedsl_contiguous:a{self._m_alignment}:tw{token_width}",
self._schedule_capacities(num_experts=num_experts, **geometry),
hidden_states.device,
)
schedule1, tiles1, schedule2, tiles2 = self._build_schedules_contiguous(
base.seg_counts, **geometry, **schedule_outputs
)
return CuteDslBf16ContiguousRowState(
hidden_compact=base.hidden_compact,
seg_counts=base.seg_counts,
seg_offsets=base.seg_offsets,
pair_to_row=base.pair_to_row,
m_pad_ceiling=base.m_pad_ceiling,
input_buffer_reuse=base.input_buffer_reuse,
token_width=token_width,
gemm1_schedule=schedule1,
gemm1_tiles=tiles1,
gemm2_schedule=schedule2,
gemm2_tiles=tiles2,
)
@@ -0,0 +1,282 @@
"""Shared compilation, tile selection, and launch buffers for CuTeDSL."""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
import msgspec
import torch
from sglang.srt.lora.moe.base_gemm_provider.base import prepare_buffer
if TYPE_CHECKING:
from sglang.srt.lora.moe.quant_info import StandardLayoutQuantInfo
from sglang.srt.lora.workspace import LoraWorkspace
logger = logging.getLogger(__name__)
# Cache code only: caching bound arguments would retain layer weights.
_COMPILE_CACHE: dict[tuple, object] = {}
class CuteDslStageCall(msgspec.Struct, frozen=True):
compiled_fn: object
b_arg: object
sf_weights: torch.Tensor | None = None
class CuteDslTileMixin:
NARROW_TOKEN_WIDTH = 8
NARROW_PERSISTENT_CLUSTERS = 128
WIDE_TOKEN_WIDTH = 64
WIDE_PERSISTENT_CLUSTERS = 128
XWIDE_TOKEN_WIDTH = 128
XWIDE_PERSISTENT_CLUSTERS = 128
# The packed schedule supports only 1x1 clusters and 1-CTA MMA.
CLUSTER_SHAPE_MN = (1, 1)
USE_2CTA_INSTRS = False
OCCUPANCY = 1
MMA_INST_TILE_K = 4
WIDE_EXPECTED_M_THRESHOLD: int
XWIDE_EXPECTED_M_THRESHOLD = 96
OUTPUT_WIDTH = 128
_ROW_MODE: str
_DTYPE_TAG: str
def _init_tiles(
self, quant_info: StandardLayoutQuantInfo, *, drop_narrow_tile: bool = False
) -> None:
import cuda.bindings.driver as cuda_driver
from sglang.kernels.ops.lora.moe.cutedsl.api import (
GroupedGemmConfig,
as_dynamic_cute_tensor,
)
from sglang.kernels.ops.lora.moe.cutedsl.schedule_builder import (
MAX_EXPERTS,
MAX_TOKEN_CLUSTERS,
)
from sglang.srt.lora.moe.base_gemm_provider.gemm_config_store import (
cutedsl_version,
load_config_table,
)
self._as_dynamic_cute_tensor = as_dynamic_cute_tensor
self._cu_stream = cuda_driver.CUstream
if quant_info.num_local_experts > MAX_EXPERTS:
raise ValueError(
f"{quant_info.num_local_experts} local experts exceed the "
f"direct schedule's {MAX_EXPERTS}-expert packing"
)
self._max_token_clusters = MAX_TOKEN_CLUSTERS
self._bind_weights(quant_info)
device = quant_info.w13_weight.device
# Keep the SM90 FP8 heuristic at 64-wide tiles; tables may override it.
self._xwide_by_heuristic = not (
self._DTYPE_TAG == "fp8"
and torch.cuda.get_device_capability(device) < (10, 0)
)
# Use one persistent cluster per SM on 152-SM Blackwell devices.
xwide_clusters = self.XWIDE_PERSISTENT_CLUSTERS
if (
torch.cuda.get_device_capability(device) >= (10, 0)
and torch.cuda.get_device_properties(device).multi_processor_count == 152
):
xwide_clusters = 152
tile_set = (
(self.NARROW_TOKEN_WIDTH, self.NARROW_PERSISTENT_CLUSTERS),
(self.WIDE_TOKEN_WIDTH, self.WIDE_PERSISTENT_CLUSTERS),
(self.XWIDE_TOKEN_WIDTH, xwide_clusters),
)
if drop_narrow_tile:
tile_set = tile_set[1:]
version = cutedsl_version()
self._config_table = load_config_table(
self.contract.key,
num_local_experts=quant_info.num_local_experts,
n_gemm1=self._gate_up_slices * quant_info.intermediate_size,
n_gemm2=quant_info.hidden_size,
k=quant_info.hidden_size,
installed_versions={"cutedsl": version} if version else None,
)
tile_set = self._merge_table_tiles(tile_set)
self._compiled: dict[int, dict[str, CuteDslStageCall]] = {}
for token_width, persistent_clusters in tile_set:
self._admit_tile_width(token_width)
config = GroupedGemmConfig(
mma_tiler_mn=(self.OUTPUT_WIDTH, token_width),
cluster_shape_mn=self.CLUSTER_SHAPE_MN,
use_2cta_instrs=self.USE_2CTA_INSTRS,
occupancy=self.OCCUPANCY,
mma_inst_tile_k=self.MMA_INST_TILE_K,
persistent_clusters=persistent_clusters,
)
self._compiled[token_width] = {}
self._compile_stage(token_width, "gemm1", config)
self._compile_stage(token_width, "gemm2", config)
torch.cuda.synchronize(device)
def _merge_table_tiles(
self, tile_set: tuple[tuple[int, int], ...]
) -> tuple[tuple[int, int], ...]:
"""Add the table's tiles; drop a table whose buckets pick uncompiled widths."""
if self._config_table is None:
return tile_set
widths = dict(tile_set)
widths.update(
(tile.token_width, tile.persistent_clusters)
for tile in self._config_table.tiles
)
undeclared = {
payload["token_width"] for payload in self._config_table.buckets.values()
} - set(widths)
if undeclared:
logger.warning(
"Ignoring the %s GEMM config: buckets select token widths %s that "
"no tile declares",
self.contract.key,
sorted(undeclared),
)
self._config_table = None
return tile_set
return tuple(sorted(widths.items()))
def _bind_weights(self, quant_info: StandardLayoutQuantInfo) -> None:
"""Optional hook for dtype-specific weight preparation."""
def _admit_tile_width(self, token_width: int) -> None:
"""Optional hook for row-layout constraints."""
def _stage_weight(self, stage: str) -> torch.Tensor:
if stage == "gemm1":
return self.quant_info.w13_weight
if stage == "gemm2":
return self.quant_info.w2_weight
raise ValueError(f"unknown CuTeDSL base stage {stage!r}")
def _stage_scale(self, stage: str) -> torch.Tensor | None:
return None
def _compile_stage(self, token_width: int, stage: str, config) -> None:
weight = self._stage_weight(stage)
device = weight.device
key = (
device.type,
device.index,
config,
self._ROW_MODE,
self._DTYPE_TAG,
self.quant_info.num_local_experts,
weight.shape[1],
weight.shape[2],
)
compiled_fn = _COMPILE_CACHE.get(key)
if compiled_fn is None:
prepared = self._prepare_dummy(stage, config)
# Load the module before graph capture with a zero-tile launch.
prepared.launch()
compiled_fn = prepared.compiled_fn
_COMPILE_CACHE[key] = compiled_fn
self._compiled[token_width][stage] = CuteDslStageCall(
compiled_fn=compiled_fn,
b_arg=self._as_dynamic_cute_tensor(weight, leading_dim=2),
sf_weights=self._stage_scale(stage),
)
def _token_width_for(self, max_expert_rows: int, expected_m: int) -> int:
"""Widen the tuned choice if needed to fit the packed schedule."""
if self._config_table is not None:
performance_width = self._config_table.pick(expected_m)["token_width"]
elif expected_m >= self.XWIDE_EXPECTED_M_THRESHOLD and self._xwide_by_heuristic:
performance_width = self.XWIDE_TOKEN_WIDTH
elif (
expected_m >= self.WIDE_EXPECTED_M_THRESHOLD
or self.NARROW_TOKEN_WIDTH not in self._compiled
):
performance_width = self.WIDE_TOKEN_WIDTH
else:
performance_width = self.NARROW_TOKEN_WIDTH
for width in sorted(self._compiled):
if (
width >= performance_width
and max_expert_rows <= width * self._max_token_clusters
):
return width
widest = max(self._compiled)
raise ValueError(
f"max_expert_rows={max_expert_rows} exceeds the widest compiled "
f"tile's schedule packing ({widest * self._max_token_clusters})"
)
def _stream(self, device: torch.device):
return self._cu_stream(torch.cuda.current_stream(device).cuda_stream)
@staticmethod
def _output_clusters(n: int) -> int:
return (n + CuteDslTileMixin.OUTPUT_WIDTH - 1) // CuteDslTileMixin.OUTPUT_WIDTH
def _small_prepare_outputs(
self,
workspace: LoraWorkspace | None,
prefix: str,
capacities: tuple[int, int],
num_experts: int,
device: torch.device,
) -> dict[str, torch.Tensor]:
"""Schedule buffers plus the small prepare's stage-begin scratch."""
import triton
scratch_len = 2 * max(16, triton.next_power_of_2(num_experts))
outputs = self._schedule_buffers(workspace, prefix, capacities, device)
outputs["scratch"] = prepare_buffer(
workspace,
f"{prefix}:small_scratch",
(scratch_len,),
dtype=torch.int32,
device=device,
)
return outputs
@staticmethod
def _schedule_buffers(
workspace: LoraWorkspace | None,
prefix: str,
capacities: tuple[int, int],
device: torch.device,
) -> dict[str, torch.Tensor]:
capacity1, capacity2 = capacities
return {
"schedule1_out": prepare_buffer(
workspace,
f"{prefix}:gemm1_schedule",
(capacity1,),
dtype=torch.int64,
device=device,
),
"tiles1_out": prepare_buffer(
workspace,
f"{prefix}:gemm1_tiles",
(1,),
dtype=torch.int32,
device=device,
),
"schedule2_out": prepare_buffer(
workspace,
f"{prefix}:gemm2_schedule",
(capacity2,),
dtype=torch.int64,
device=device,
),
"tiles2_out": prepare_buffer(
workspace,
f"{prefix}:gemm2_tiles",
(1,),
dtype=torch.int32,
device=device,
),
}
@@ -0,0 +1,446 @@
"""CuTeDSL GEMMs using checkpoint FP8 values and FP32 block scales.
Activations use group-128 quantization; GEMM outputs remain BF16 for LoRA.
"""
from __future__ import annotations
import torch
from sglang.kernels.ops.lora.moe.dispatch_contiguous import (
dispatch_fill_rows_contiguous_fp8,
)
from sglang.kernels.ops.lora.moe.dispatch_masked import dispatch_fill_masked_fp8
from sglang.kernels.ops.quantization.fp8_kernel import (
sglang_per_token_group_quant_fp8,
)
from sglang.srt.lora.moe.base_gemm_provider.base import (
MoeBaseProviderContract,
expected_rows_per_expert,
prepare_buffer,
)
from sglang.srt.lora.moe.base_gemm_provider.contiguous_row_domain import (
ContiguousRowDomainProvider,
ContiguousRowState,
)
from sglang.srt.lora.moe.base_gemm_provider.cutedsl_common import CuteDslTileMixin
from sglang.srt.lora.moe.base_gemm_provider.masked_row_domain import (
MaskedRowDomainProvider,
MaskedRowState,
masked_m_max,
)
from sglang.srt.lora.moe.quant_info import MoeLoraFp8QuantInfo
QUANT_GROUP = 128
class _CuteDslFp8Mixin(CuteDslTileMixin):
_DTYPE_TAG = "fp8"
WIDE_EXPECTED_M_THRESHOLD = 32
@staticmethod
def _prepare_input_rows(workspace, shape, device):
if workspace is None:
return torch.empty(shape, dtype=torch.float8_e4m3fn, device=device)
output = workspace.tensor(
"base:down", shape, dtype=torch.bfloat16, device=device
)
# Gate/up consumes the packed FP8 prefix before down overwrites the BF16 slab.
return output.view(torch.float8_e4m3fn).flatten()[: output.numel()].view(shape)
def _bind_weights(self, quant_info: MoeLoraFp8QuantInfo) -> None:
self._sf_w13 = quant_info.w13_scale.contiguous()
self._sf_w2 = quant_info.w2_scale.contiguous()
def _stage_scale(self, stage: str) -> torch.Tensor:
return self._sf_w13 if stage == "gemm1" else self._sf_w2
def _launch(
self,
stage: str,
a_fp8: torch.Tensor,
sf_tokens: torch.Tensor,
c: torch.Tensor,
row_state,
schedule: torch.Tensor,
tiles: torch.Tensor,
) -> None:
call = self._compiled[row_state.token_width][stage]
# Runtime wrapping must match the compiled argument's MLIR type.
dyn = self._as_dynamic_cute_tensor
a_rows = self._rows_arg(a_fp8)
call.compiled_fn(
dyn(a_rows, leading_dim=2),
call.b_arg,
dyn(sf_tokens.view(*a_rows.shape[:2], -1), leading_dim=2),
dyn(call.sf_weights, leading_dim=2),
dyn(self._rows_arg(c), leading_dim=2),
dyn(self._group_arg(row_state), leading_dim=0),
dyn(schedule, leading_dim=0),
dyn(tiles, leading_dim=0),
self._stream(a_fp8.device),
)
def gateup(self, row_state, out: torch.Tensor) -> None:
self._launch(
"gemm1",
self._input_rows(row_state),
row_state.sf_rows,
out,
row_state,
row_state.gemm1_schedule,
row_state.gemm1_tiles,
)
def down(self, row_state, act_out: torch.Tensor, out: torch.Tensor) -> None:
act_fp8, sf_act = self._down_operands(row_state, act_out)
self._launch(
"gemm2",
act_fp8,
sf_act,
out,
row_state,
row_state.gemm2_schedule,
row_state.gemm2_tiles,
)
class CuteDslFp8MaskedRowState(MaskedRowState, kw_only=True):
token_width: int
sf_rows: torch.Tensor # [E_local, m_max, hidden // 128] fp32 group scales
gemm1_schedule: torch.Tensor
gemm1_tiles: torch.Tensor
gemm2_schedule: torch.Tensor
gemm2_tiles: torch.Tensor
# Only materialized activation fills these; fused-B activation stays BF16.
act_fp8: torch.Tensor
act_scale: torch.Tensor
act_quant_ready: bool = False
class CuteDslFp8MaskedProvider(_CuteDslFp8Mixin, MaskedRowDomainProvider):
contract = MoeBaseProviderContract(
key="cutedsl_fp8_masked",
quant_info_cls=MoeLoraFp8QuantInfo,
gate_first=True,
interleaved=False,
gate_up_output_dtype=torch.bfloat16,
lora_delta_dtype=torch.bfloat16,
lora_activation_dtype=torch.bfloat16,
)
_ROW_MODE = "masked"
def __init__(self, quant_info: MoeLoraFp8QuantInfo):
super().__init__(quant_info)
from sglang.kernels.ops.lora.moe.cutedsl.api import prepare_masked_fp8
from sglang.kernels.ops.lora.moe.cutedsl.schedule_builder import (
build_dual_stage_schedules_masked,
dual_stage_schedule_capacities_masked,
)
self._prepare_masked_gemm = prepare_masked_fp8
self._build_schedules = build_dual_stage_schedules_masked
self._schedule_capacities = dual_stage_schedule_capacities_masked
self._init_tiles(quant_info)
def _prepare_dummy(self, stage: str, config):
weight, weight_sf = self._stage_weight(stage), self._stage_scale(stage)
device = weight.device
experts, n, k = weight.shape
dummy_a = torch.zeros(
(experts, 256, k), dtype=torch.float8_e4m3fn, device=device
)
dummy_sf = torch.zeros(
(experts, 256, k // QUANT_GROUP), dtype=torch.float32, device=device
)
dummy_c = torch.empty((experts, 256, n), dtype=torch.bfloat16, device=device)
dummy_masked = torch.zeros(experts, dtype=torch.int32, device=device)
return self._prepare_masked_gemm(
dummy_a,
weight,
dummy_sf,
weight_sf,
dummy_c,
dummy_masked,
config=config,
)
@staticmethod
def _rows_arg(tensor: torch.Tensor) -> torch.Tensor:
return tensor
@staticmethod
def _input_rows(row_state: CuteDslFp8MaskedRowState) -> torch.Tensor:
return row_state.hidden_permuted
@staticmethod
def _group_arg(row_state: CuteDslFp8MaskedRowState) -> torch.Tensor:
return row_state.masked_m
def prepare(
self,
hidden_states: torch.Tensor,
topk_ids: torch.Tensor,
top_k: int,
workspace=None,
) -> CuteDslFp8MaskedRowState:
experts = self.quant_info.num_local_experts
k = hidden_states.size(1)
inter = self.quant_info.intermediate_size
expected_m = expected_rows_per_expert(topk_ids.numel(), experts)
token_width = self._token_width_for(hidden_states.size(0), expected_m)
# FP8 scale loads are unpredicated across the whole selected token tile.
m_max = masked_m_max(hidden_states.size(0), token_width)
device = hidden_states.device
def _buf(name, shape, dtype):
return prepare_buffer(workspace, name, shape, dtype=dtype, device=device)
masked_m = _buf("masked:masked_m", (experts,), torch.int32)
pair_to_row = _buf("masked:pair_to_row", (topk_ids.numel(),), torch.int32)
rows_fp8 = self._prepare_input_rows(workspace, (experts, m_max, k), device)
sf_rows = _buf(
"masked:sf_rows", (experts, m_max, k // QUANT_GROUP), torch.float32
)
act_fp8 = _buf("masked:act_fp8", (experts, m_max, inter), torch.float8_e4m3fn)
act_scale = _buf(
"masked:act_scale", (experts, m_max, inter // QUANT_GROUP), torch.float32
)
geometry = dict(
token_width=token_width,
n_gemm1=self.gate_up_slices * inter,
n_gemm2=self.quant_info.hidden_size,
output_width=self.OUTPUT_WIDTH,
cluster_shape_mn=self.CLUSTER_SHAPE_MN,
use_2cta_instrs=self.USE_2CTA_INSTRS,
)
capacities = self._schedule_capacities(
num_experts=experts, m_max=m_max, **geometry
)
dispatch_fill_masked_fp8(
hidden_states,
topk_ids,
top_k,
masked_m_out=masked_m,
pair_to_row_out=pair_to_row,
rows_fp8_out=rows_fp8,
scale_out=sf_rows,
)
schedule_outputs = {}
if workspace is not None:
schedule_outputs = self._schedule_buffers(
workspace, f"cutedsl_masked:tw{token_width}", capacities, device
)
schedule1, tiles1, schedule2, tiles2 = self._build_schedules(
masked_m, m_max=m_max, **geometry, **schedule_outputs
)
return CuteDslFp8MaskedRowState(
hidden_permuted=rows_fp8,
masked_m=masked_m,
expected_m=expected_m,
pair_to_row=pair_to_row,
m_max=m_max,
input_buffer_reuse=workspace is not None,
token_width=token_width,
sf_rows=sf_rows,
gemm1_schedule=schedule1,
gemm1_tiles=tiles1,
gemm2_schedule=schedule2,
gemm2_tiles=tiles2,
act_fp8=act_fp8,
act_scale=act_scale,
)
def act_with_delta(
self,
row_state: CuteDslFp8MaskedRowState,
gateup_out: torch.Tensor,
gate_up_delta: torch.Tensor | None,
topk_ids: torch.Tensor,
act_out: torch.Tensor,
activation_lora_input: torch.Tensor,
*,
activation: str = "silu",
) -> None:
self._act_kernel(
gateup_out,
gate_up_delta,
act_out,
activation_lora_input,
row_state.pair_to_row,
topk_ids,
num_local_experts=self.num_local_experts,
gate_first=self.contract.gate_first,
interleaved=self.contract.interleaved,
activation=activation,
act_quant=(row_state.act_fp8, row_state.act_scale, QUANT_GROUP),
)
row_state.act_quant_ready = True
@staticmethod
def _down_operands(
row_state: CuteDslFp8MaskedRowState, act_out: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
if row_state.act_quant_ready:
return row_state.act_fp8, row_state.act_scale
# Fused-B activation needs separate quantization.
return sglang_per_token_group_quant_fp8(
act_out, QUANT_GROUP, masked_m=row_state.masked_m
)
class CuteDslFp8ContiguousRowState(ContiguousRowState, kw_only=True):
token_width: int
sf_rows: torch.Tensor # [m_pad_ceiling, hidden // 128] fp32 group scales
gemm1_schedule: torch.Tensor
gemm1_tiles: torch.Tensor
gemm2_schedule: torch.Tensor
gemm2_tiles: torch.Tensor
class CuteDslFp8ContiguousProvider(_CuteDslFp8Mixin, ContiguousRowDomainProvider):
contract = MoeBaseProviderContract(
key="cutedsl_fp8_contiguous",
quant_info_cls=MoeLoraFp8QuantInfo,
gate_first=True,
interleaved=False,
gate_up_output_dtype=torch.bfloat16,
lora_delta_dtype=torch.bfloat16,
lora_activation_dtype=torch.bfloat16,
)
M_ALIGNMENT = 128
_ROW_MODE = "contiguous"
def __init__(self, quant_info: MoeLoraFp8QuantInfo):
super().__init__(quant_info, m_alignment=self.M_ALIGNMENT)
from sglang.kernels.ops.lora.moe.cutedsl.api import prepare_contiguous_fp8
from sglang.kernels.ops.lora.moe.cutedsl.schedule_builder import (
build_dual_stage_schedules_contiguous,
dual_stage_schedule_capacities_contiguous,
validate_tile_geometry_contiguous,
)
self._prepare_contiguous_gemm = prepare_contiguous_fp8
self._validate_tile_geometry = validate_tile_geometry_contiguous
self._build_schedules_contiguous = build_dual_stage_schedules_contiguous
self._schedule_capacities = dual_stage_schedule_capacities_contiguous
self._init_tiles(quant_info)
def _admit_tile_width(self, token_width: int) -> None:
self._validate_tile_geometry(token_width, self._m_alignment)
def _prepare_dummy(self, stage: str, config):
weight, weight_sf = self._stage_weight(stage), self._stage_scale(stage)
device = weight.device
num_experts, n, k = weight.shape
dummy_a = torch.zeros((256, k), dtype=torch.float8_e4m3fn, device=device)
dummy_sf = torch.zeros(
(1, 256, k // QUANT_GROUP), dtype=torch.float32, device=device
)
dummy_c = torch.empty((256, n), dtype=torch.bfloat16, device=device)
dummy_seg = torch.zeros(num_experts + 1, dtype=torch.int32, device=device)
return self._prepare_contiguous_gemm(
dummy_a,
weight,
dummy_sf,
weight_sf,
dummy_c,
dummy_seg,
config=config,
)
@staticmethod
def _rows_arg(tensor: torch.Tensor) -> torch.Tensor:
# Flat rows occupy one expert slot in the swap_ab wrapper.
return tensor.unsqueeze(0)
@staticmethod
def _input_rows(row_state: CuteDslFp8ContiguousRowState) -> torch.Tensor:
return row_state.hidden_compact
@staticmethod
def _group_arg(row_state: CuteDslFp8ContiguousRowState) -> torch.Tensor:
return row_state.seg_offsets
def prepare(
self,
hidden_states: torch.Tensor,
topk_ids: torch.Tensor,
top_k: int,
workspace=None,
) -> CuteDslFp8ContiguousRowState:
base = super().prepare(
hidden_states, topk_ids, top_k, workspace, fill_rows=False
)
num_experts = self.quant_info.num_local_experts
hidden = hidden_states.size(1)
device = hidden_states.device
prefix = f"contiguous:a{self._m_alignment}"
rows_fp8 = self._prepare_input_rows(
workspace,
(base.m_pad_ceiling, hidden),
device,
)
sf_rows = prepare_buffer(
workspace,
f"{prefix}:sf_rows",
(base.m_pad_ceiling, hidden // QUANT_GROUP),
dtype=torch.float32,
device=device,
)
dispatch_fill_rows_contiguous_fp8(
hidden_states,
topk_ids,
base.pair_to_row,
rows_fp8_out=rows_fp8,
scale_out=sf_rows,
)
# Distinct top-k experts bound each expert to one row per token.
max_expert_rows = max(int(hidden_states.size(0)), 1)
expected_m = expected_rows_per_expert(topk_ids.numel(), num_experts)
token_width = self._token_width_for(max_expert_rows, expected_m)
geometry = dict(
m_pad_ceiling=base.m_pad_ceiling,
max_expert_rows=max_expert_rows,
m_alignment=self._m_alignment,
token_width=token_width,
n_gemm1=self.gate_up_slices * self.quant_info.intermediate_size,
n_gemm2=self.quant_info.hidden_size,
output_width=self.OUTPUT_WIDTH,
cluster_shape_mn=self.CLUSTER_SHAPE_MN,
use_2cta_instrs=self.USE_2CTA_INSTRS,
)
schedule_outputs = {}
if workspace is not None:
schedule_outputs = self._schedule_buffers(
workspace,
f"cutedsl_contiguous:a{self._m_alignment}:tw{token_width}",
self._schedule_capacities(num_experts=num_experts, **geometry),
device,
)
schedule1, tiles1, schedule2, tiles2 = self._build_schedules_contiguous(
base.seg_counts, **geometry, **schedule_outputs
)
return CuteDslFp8ContiguousRowState(
hidden_compact=rows_fp8,
seg_counts=base.seg_counts,
seg_offsets=base.seg_offsets,
pair_to_row=base.pair_to_row,
m_pad_ceiling=base.m_pad_ceiling,
input_buffer_reuse=base.input_buffer_reuse,
token_width=token_width,
sf_rows=sf_rows,
gemm1_schedule=schedule1,
gemm1_tiles=tiles1,
gemm2_schedule=schedule2,
gemm2_tiles=tiles2,
)
@staticmethod
def _down_operands(
row_state: CuteDslFp8ContiguousRowState, act_out: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
return sglang_per_token_group_quant_fp8(act_out, QUANT_GROUP)
@@ -0,0 +1,142 @@
"""GEMM configs keyed by provider, geometry, device, and nearest expected M."""
from __future__ import annotations
import functools
import logging
import os
from collections.abc import Mapping
import msgspec
from sglang.srt.environ import envs
logger = logging.getLogger(__name__)
_PACKAGE_CONFIG_DIR = os.path.join(
os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "configs"
)
class GemmTile(msgspec.Struct, frozen=True, kw_only=True, forbid_unknown_fields=True):
token_width: int
persistent_clusters: int
class GemmConfigTable(msgspec.Struct, kw_only=True, forbid_unknown_fields=True):
buckets: dict[int, dict[str, int]]
tiles: tuple[GemmTile, ...] = ()
version: dict[str, str] = {}
def pick(self, expected_m: int) -> dict[str, int]:
return self.buckets[min(self.buckets, key=lambda m: abs(m - expected_m))]
def _validate(table: GemmConfigTable) -> None:
if not table.buckets:
raise ValueError("buckets must be non-empty")
for bucket_m, payload in table.buckets.items():
if bucket_m <= 0:
raise ValueError(f"bucket key {bucket_m} must be positive")
if set(payload) != {"token_width"}:
raise ValueError(f"bucket {bucket_m} must contain only token_width")
width = payload["token_width"]
if width <= 0 or width & (width - 1):
raise ValueError(
f"bucket {bucket_m} token_width must be a positive power of two"
)
widths = [tile.token_width for tile in table.tiles]
if len(set(widths)) != len(widths):
raise ValueError("tiles must declare one persistent_clusters per token_width")
for tile in table.tiles:
if tile.token_width <= 0 or tile.token_width & (tile.token_width - 1):
raise ValueError("tile token_width must be a positive power of two")
if tile.persistent_clusters <= 0:
raise ValueError("persistent_clusters must be positive")
def config_file_name(
provider_key: str,
*,
num_local_experts: int,
n_gemm1: int,
n_gemm2: int,
k: int,
device_name: str,
) -> str:
device = device_name.replace(" ", "_")
return (
f"provider={provider_key},E={num_local_experts},N1={n_gemm1},"
f"N2={n_gemm2},K={k},device_name={device}.json"
)
@functools.lru_cache(maxsize=None)
def _load(
path: str, installed_versions: tuple[tuple[str, str], ...]
) -> GemmConfigTable | None:
if not os.path.exists(path):
return None
try:
with open(path, "rb") as f:
table = msgspec.json.decode(f.read(), type=GemmConfigTable)
_validate(table)
except (msgspec.DecodeError, ValueError) as exc:
logger.warning("Ignoring malformed MoE LoRA GEMM config %s: %s", path, exc)
return None
# The recorded version is tuning provenance. A table tuned with another
# release is still used: its tiles are compiled and checked before use,
# but their speed on this release has not been re-validated here.
for name, installed in installed_versions:
recorded = table.version.get(name)
if recorded is not None and recorded != installed:
logger.warning(
"MoE LoRA GEMM config %s was tuned with %s %s; installed %s. "
"The table is used, but its tile choices were not re-validated "
"on this release.",
path,
name,
recorded,
installed,
)
logger.info("Using MoE LoRA GEMM config from %s.", path)
return table
def load_config_table(
provider_key: str,
*,
num_local_experts: int,
n_gemm1: int,
n_gemm2: int,
k: int,
device_name: str | None = None,
installed_versions: Mapping[str, str] | None = None,
) -> GemmConfigTable | None:
if device_name is None:
from sglang.srt.utils import get_device_name
device_name = get_device_name()
name = config_file_name(
provider_key,
num_local_experts=num_local_experts,
n_gemm1=n_gemm1,
n_gemm2=n_gemm2,
k=k,
device_name=device_name,
)
versions = tuple(sorted((installed_versions or {}).items()))
roots = (envs.SGLANG_LORA_MOE_CONFIG_DIR.get(), _PACKAGE_CONFIG_DIR)
for root in filter(None, roots):
path = os.path.join(root, "base_gemm", name)
if os.path.isfile(path):
return _load(path, versions)
return None
def cutedsl_version() -> str | None:
try:
import cutlass
except ImportError:
return None
return getattr(cutlass, "__version__", None)
@@ -0,0 +1,38 @@
"""Select the single-token or upstream general expert-row alignment."""
from __future__ import annotations
import torch
from sglang.kernels.ops.lora.moe.align_rows import (
moe_align_single_token,
pair_to_row_map,
)
def align_rows(
topk_ids: torch.Tensor,
block_size: int,
num_experts: int,
*,
pair_to_row_out: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Align pairs, optionally filling pair_to_row_out [tokens * topk].
The single-token path fills the row map in its alignment launch.
"""
if (
topk_ids.shape[0] == 1
and topk_ids.shape[1] <= 32
and topk_ids.dtype == torch.int32
):
return moe_align_single_token(topk_ids, block_size, pair_to_row_out)
if pair_to_row_out is not None:
pair_to_row_map(topk_ids, pair_to_row_out)
from sglang.srt.layers.moe.moe_runner.triton_utils.moe_align_block_size import (
moe_align_block_size,
)
return moe_align_block_size(
topk_ids, block_size, num_experts, ignore_invalid_expert=True
)
@@ -0,0 +1,216 @@
"""Marlin W4A16 GEMMs with BF16 activations in raw pair order."""
from __future__ import annotations
import msgspec
import torch
from sglang.srt.lora.moe.base_gemm_provider.base import (
MoeBaseProviderContract,
prepare_buffer,
)
from sglang.srt.lora.moe.base_gemm_provider.contiguous_row_domain import (
ContiguousRowDomainProvider,
)
from sglang.srt.lora.moe.quant_info import MoeLoraNvFp4MarlinQuantInfo
class MarlinNvFp4RowState(msgspec.Struct, kw_only=True):
hidden_states: torch.Tensor # [num_tokens, hidden] bf16, borrowed
sorted_token_ids: torch.Tensor
expert_ids: torch.Tensor
num_tokens_post_padded: torch.Tensor
# Per-forward locks prevent aliasing across CUDA graph pools.
lock_workspace: torch.Tensor
pair_to_row: torch.Tensor # [num_pairs] int32 identity
num_pairs: int
top_k: int
block_size_m: int
padded_intermediate: torch.Tensor | None = None
class MarlinNvFp4ContiguousProvider(ContiguousRowDomainProvider):
contract = MoeBaseProviderContract(
key="marlin_nvfp4_contiguous",
quant_info_cls=MoeLoraNvFp4MarlinQuantInfo,
gate_first=True,
interleaved=False,
gate_up_output_dtype=torch.bfloat16,
lora_delta_dtype=torch.bfloat16,
lora_activation_dtype=torch.bfloat16,
)
def __init__(self, quant_info: MoeLoraNvFp4MarlinQuantInfo):
# Packed weights use explicit logical sizes instead of shape admission.
self.quant_info = quant_info
self._gate_up_slices = quant_info.gate_up_slices
self._padded_intermediate_size = quant_info.w2_qweight.shape[1] * 16
from sglang.srt.layers.moe.fused_moe_triton.fused_marlin_moe import (
get_scalar_type,
)
self._scalar_type_w13 = get_scalar_type(
4, False, quant_info.w13_scales, quant_info.w13_global_scale
)
self._scalar_type_w2 = get_scalar_type(
4, False, quant_info.w2_scales, quant_info.w2_global_scale
)
# Finalize owns router weights; the dummy is unread when mul_topk_weights=False.
self._unused_topk_weights = torch.zeros(
(1, 1), dtype=torch.float32, device=quant_info.w13_qweight.device
)
def prepare(
self,
hidden_states: torch.Tensor,
topk_ids: torch.Tensor,
top_k: int,
workspace=None,
) -> MarlinNvFp4RowState:
from sglang.srt.layers.quantization.marlin_utils import marlin_make_workspace
from sglang.srt.lora.moe.base_gemm_provider.input_alignment import align_rows
num_tokens = hidden_states.shape[0]
num_experts = self.quant_info.num_local_experts
# fused_marlin_moe's M block size rule.
for block_size_m in (8, 16, 32, 48, 64):
if num_tokens * top_k / num_experts / block_size_m < 0.9:
break
num_pairs = topk_ids.numel()
device = hidden_states.device
pair_to_row = prepare_buffer(
workspace, "pair_to_row", (num_pairs,), dtype=torch.int32, device=device
)
# Finalize uses pair_to_row, with -1 for pairs without an expert.
sorted_token_ids, expert_ids, num_tokens_post_padded = align_rows(
topk_ids, block_size_m, num_experts, pair_to_row_out=pair_to_row
)
return MarlinNvFp4RowState(
hidden_states=hidden_states,
sorted_token_ids=sorted_token_ids,
expert_ids=expert_ids,
num_tokens_post_padded=num_tokens_post_padded,
lock_workspace=marlin_make_workspace(device, max_blocks_per_sm=4),
pair_to_row=pair_to_row,
num_pairs=num_pairs,
top_k=top_k,
block_size_m=block_size_m,
padded_intermediate=(
prepare_buffer(
workspace,
"marlin:padded_intermediate",
(num_pairs, self._padded_intermediate_size),
dtype=hidden_states.dtype,
device=device,
)
if self._padded_intermediate_size != self.intermediate_size
else None
),
)
def release_prepared_inputs(self, row_state: MarlinNvFp4RowState) -> None:
pass
def _invoke(
self,
a: torch.Tensor,
out: torch.Tensor,
row_state: MarlinNvFp4RowState,
*,
qweight: torch.Tensor,
scales: torch.Tensor,
global_scale: torch.Tensor,
scalar_type,
top_k: int,
size_m: int,
size_n: int,
size_k: int,
) -> None:
from sglang.kernels.ops.moe.moe_wna16_marlin import moe_wna16_marlin_gemm
moe_wna16_marlin_gemm(
a,
out,
qweight,
None,
scales,
global_scale,
None,
None,
None,
row_state.lock_workspace,
row_state.sorted_token_ids,
row_state.expert_ids,
row_state.num_tokens_post_padded,
self._unused_topk_weights,
moe_block_size=row_state.block_size_m,
top_k=top_k,
mul_topk_weights=False,
is_ep=False,
b_q_type=scalar_type,
size_m=size_m,
size_n=size_n,
size_k=size_k,
is_k_full=True, # NVFP4 has no GPTQ act-order; K is never permuted
use_atomic_add=True,
use_fp32_reduce=True,
is_zp_float=False,
)
def gateup(self, row_state: MarlinNvFp4RowState, out: torch.Tensor) -> None:
qi = self.quant_info
padded = row_state.padded_intermediate
self._invoke(
row_state.hidden_states,
out if padded is None else padded,
row_state,
qweight=qi.w13_qweight,
scales=qi.w13_scales,
global_scale=qi.w13_global_scale,
scalar_type=self._scalar_type_w13,
top_k=row_state.top_k,
size_m=row_state.hidden_states.shape[0],
size_n=self._gate_up_slices * self._padded_intermediate_size,
size_k=qi.hidden_size,
)
if padded is not None:
out.copy_(padded[:, : qi.intermediate_size])
def down(
self,
row_state: MarlinNvFp4RowState,
act_out: torch.Tensor,
out: torch.Tensor,
) -> None:
qi = self.quant_info
padded = row_state.padded_intermediate
if padded is not None:
padded[:, : qi.intermediate_size].copy_(act_out)
# Gateup reused this buffer; clear its tail on every replay.
padded[:, qi.intermediate_size :].zero_()
act_out = padded
self._invoke(
act_out,
out,
row_state,
qweight=qi.w2_qweight,
scales=qi.w2_scales,
global_scale=qi.w2_global_scale,
scalar_type=self._scalar_type_w2,
top_k=1,
size_m=row_state.num_pairs,
size_n=qi.hidden_size,
size_k=self._padded_intermediate_size,
)
def gateup_out_shape(self, row_state: MarlinNvFp4RowState) -> tuple[int, ...]:
return (
row_state.num_pairs,
self._gate_up_slices * self.quant_info.intermediate_size,
)
def act_out_shape(self, row_state: MarlinNvFp4RowState) -> tuple[int, ...]:
return (row_state.num_pairs, self.quant_info.intermediate_size)
def down_out_shape(self, row_state: MarlinNvFp4RowState) -> tuple[int, ...]:
return (row_state.num_pairs, self.quant_info.hidden_size)
@@ -0,0 +1,189 @@
"""Expert slabs [E_local, m_max, ...] with valid counts and pair mappings."""
from __future__ import annotations
from collections.abc import Mapping
from typing import TYPE_CHECKING
import msgspec
import torch
from sglang.srt.lora.moe.base_gemm_provider.base import (
MoeBaseProvider,
admit_weight_layout,
expected_rows_per_expert,
prepare_buffer,
)
from sglang.srt.lora.moe.quant_info import StandardLayoutQuantInfo
if TYPE_CHECKING:
from sglang.kernels.ops.lora.common.route_view import RouteView
from sglang.srt.lora.workspace import LoraWorkspace
def masked_m_max(num_tokens: int, alignment: int = 8) -> int:
"""Fit all input rows in one expert, with a nonzero aligned slab extent."""
return max(alignment, (num_tokens + alignment - 1) // alignment * alignment)
class MaskedRowState(msgspec.Struct, kw_only=True):
"""``pair_to_row[t * top_k + k]`` is ``expert * m_max + offset``; a pair is
valid only when ``topk_ids[t, k] >= 0``.
"""
hidden_permuted: torch.Tensor # [E_local, m_max, hidden], the GEMM input dtype
masked_m: torch.Tensor # [E_local] int32
expected_m: int
pair_to_row: torch.Tensor # [num_tokens * top_k] int32
m_max: int
input_buffer_reuse: bool
class MaskedRowDomainProvider(MoeBaseProvider):
def __init__(self, quant_info: StandardLayoutQuantInfo):
self.quant_info = quant_info
self._gate_up_slices = admit_weight_layout(quant_info)
from sglang.kernels.ops.lora.moe.activation_delta import act_delta
from sglang.kernels.ops.lora.moe.dispatch_masked import (
dispatch_fill_masked_bf16,
)
self._preprocess = dispatch_fill_masked_bf16
self._act_kernel = act_delta
from sglang.kernels.ops.lora.moe.fused_act import fused_b_act
self._fused_act = fused_b_act
def prepare(
self,
hidden_states: torch.Tensor,
topk_ids: torch.Tensor,
top_k: int,
workspace: LoraWorkspace | None = None,
) -> MaskedRowState:
num_experts = self.quant_info.num_local_experts
num_pairs = topk_ids.numel()
m_max = masked_m_max(hidden_states.size(0))
device = hidden_states.device
masked_m = prepare_buffer(
workspace,
"masked:masked_m",
(num_experts,),
dtype=torch.int32,
device=device,
)
pair_to_row = prepare_buffer(
workspace,
"masked:pair_to_row",
(num_pairs,),
dtype=torch.int32,
device=device,
)
hidden_permuted = prepare_buffer(
workspace,
"masked:hidden_permuted",
(num_experts, m_max, hidden_states.size(1)),
dtype=torch.bfloat16,
device=device,
)
self._preprocess(
hidden_states,
topk_ids,
top_k,
masked_m_out=masked_m,
pair_to_row_out=pair_to_row,
rows_out=hidden_permuted,
)
return MaskedRowState(
hidden_permuted=hidden_permuted,
masked_m=masked_m,
expected_m=expected_rows_per_expert(num_pairs, num_experts),
pair_to_row=pair_to_row,
m_max=m_max,
input_buffer_reuse=workspace is not None,
)
def release_prepared_inputs(self, row_state: MaskedRowState) -> None:
# Workspace buffers retain their addresses for graph replay.
if row_state.input_buffer_reuse:
return
from sglang.srt.utils import dispose_tensor
dispose_tensor(row_state.hidden_permuted)
def act_with_delta(
self,
row_state: MaskedRowState,
gateup_out: torch.Tensor,
gate_up_delta: torch.Tensor | None,
topk_ids: torch.Tensor,
act_out: torch.Tensor,
activation_lora_input: torch.Tensor,
*,
activation: str = "silu",
) -> None:
self._act_kernel(
gateup_out,
gate_up_delta,
act_out,
activation_lora_input,
row_state.pair_to_row,
topk_ids,
num_local_experts=self.num_local_experts,
gate_first=self.contract.gate_first,
interleaved=self.contract.interleaved,
activation=activation,
)
def fused_act(
self,
row_state: MaskedRowState,
*,
activation: str,
base_gateup: torch.Tensor,
act_rows: torch.Tensor,
act_pairs: torch.Tensor | None,
routing: RouteView,
config: Mapping[str, int],
bridge_gateup: torch.Tensor | None = None,
b_gate_up: torch.Tensor | None = None,
bridge_top_k: int = 1,
) -> None:
self._fused_act(
activation=activation,
base_gateup=base_gateup,
act_rows=act_rows,
act_pairs=act_pairs,
pair_to_row=row_state.pair_to_row,
routing=routing,
num_local_experts=self.num_local_experts,
gate_first=self.contract.gate_first,
interleaved=self.contract.interleaved,
config=config,
bridge_gateup=bridge_gateup,
b_gate_up=b_gate_up,
bridge_top_k=bridge_top_k,
)
def gateup_out_shape(self, row_state: MaskedRowState) -> tuple[int, ...]:
return (
self.quant_info.num_local_experts,
row_state.m_max,
self.gate_up_slices * self.quant_info.intermediate_size,
)
def act_out_shape(self, row_state: MaskedRowState) -> tuple[int, ...]:
return (
self.quant_info.num_local_experts,
row_state.m_max,
self.quant_info.intermediate_size,
)
def down_out_shape(self, row_state: MaskedRowState) -> tuple[int, ...]:
return (
self.quant_info.num_local_experts,
row_state.m_max,
self.quant_info.hidden_size,
)
@@ -0,0 +1,202 @@
"""Triton GEMMs gather sorted token IDs and scatter into raw pair order."""
from __future__ import annotations
import msgspec
import torch
from sglang.srt.lora.moe.base_gemm_provider.base import (
MoeBaseProviderContract,
prepare_buffer,
)
from sglang.srt.lora.moe.base_gemm_provider.contiguous_row_domain import (
ContiguousRowDomainProvider,
)
from sglang.srt.lora.moe.quant_info import MoeLoraBf16QuantInfo
class TritonRowState(msgspec.Struct, kw_only=True):
hidden_states: torch.Tensor # [num_tokens, hidden] bf16, borrowed
topk_ids: torch.Tensor # [num_tokens, top_k] borrowed
sorted_token_ids: torch.Tensor # [em_ceiling] int32 route ids, pad = numel
expert_ids: torch.Tensor # [em_ceiling / block_m] int32 per-block expert
num_tokens_post_padded: torch.Tensor # [1] int32 device scalar
pair_to_row: torch.Tensor # [num_pairs] int32 pair index, or -1 when dropped
num_pairs: int
top_k: int
config: dict
down_config: dict | None
# Quantized activation and scales for the down GEMM.
act_quant: tuple[torch.Tensor, torch.Tensor] | None = None
class TritonBf16ContiguousProvider(ContiguousRowDomainProvider):
contract = MoeBaseProviderContract(
key="triton_bf16_contiguous",
quant_info_cls=MoeLoraBf16QuantInfo,
gate_first=True,
interleaved=False,
gate_up_output_dtype=torch.bfloat16,
lora_delta_dtype=torch.bfloat16,
lora_activation_dtype=torch.bfloat16,
)
def __init__(self, quant_info: MoeLoraBf16QuantInfo):
# prepare() replaces parent compaction with the tuned BLOCK_SIZE_M.
super().__init__(quant_info, m_alignment=1)
# Finalize applies router weights; the launcher only checks this stride.
self._unused_topk_weights = torch.zeros(
(1, 1), dtype=torch.float32, device=quant_info.w2_weight.device
)
self._configs: dict[int, tuple[dict, dict | None]] = {}
_config_dtype_tag: str | None = None
_config_block_shape: list[int] | None = None
def _config_for(self, num_tokens: int, top_k: int) -> tuple[dict, dict | None]:
cached = self._configs.get(num_tokens)
if cached is not None:
return cached
from sglang.srt.layers.moe.moe_runner.triton_utils.fused_moe_triton_config import (
try_get_optimal_moe_config,
)
config, (down_config, _max_block_m) = try_get_optimal_moe_config(
tuple(self.quant_info.w13_weight.shape),
tuple(self.quant_info.w2_weight.shape),
top_k,
self._config_dtype_tag,
num_tokens,
return_down_config=True,
block_shape=self._config_block_shape,
)
# Both GEMMs share a sort; upstream makes their BLOCK_SIZE_M equal.
resolved = (dict(config), dict(down_config) if down_config else None)
for stage_config in resolved:
if stage_config is None:
continue
# Classic Triton kernels do not accept the TMA launcher's flag.
stage_config.pop("USE_TMA", None)
if self._config_block_shape is not None:
# One dot tile must not span independently scaled K groups.
stage_config["BLOCK_SIZE_K"] = min(
stage_config["BLOCK_SIZE_K"], self._config_block_shape[1]
)
self._configs[num_tokens] = resolved
return resolved
def prepare(
self,
hidden_states: torch.Tensor,
topk_ids: torch.Tensor,
top_k: int,
workspace=None,
) -> TritonRowState:
from sglang.srt.lora.moe.base_gemm_provider.input_alignment import align_rows
config, down_config = self._config_for(hidden_states.shape[0], top_k)
num_pairs = topk_ids.numel()
device = hidden_states.device
pair_to_row = prepare_buffer(
workspace, "pair_to_row", (num_pairs,), dtype=torch.int32, device=device
)
# Finalize uses pair_to_row, with -1 for pairs without an expert.
sorted_token_ids, expert_ids, num_tokens_post_padded = align_rows(
topk_ids,
int(config["BLOCK_SIZE_M"]),
self.quant_info.num_local_experts,
pair_to_row_out=pair_to_row,
)
return TritonRowState(
hidden_states=hidden_states,
topk_ids=topk_ids,
sorted_token_ids=sorted_token_ids,
expert_ids=expert_ids,
num_tokens_post_padded=num_tokens_post_padded,
pair_to_row=pair_to_row,
num_pairs=num_pairs,
top_k=top_k,
config=config,
down_config=down_config,
)
def release_prepared_inputs(self, row_state: TritonRowState) -> None:
pass
def _invoke(
self,
a: torch.Tensor,
b: torch.Tensor,
out: torch.Tensor,
row_state: TritonRowState,
*,
top_k: int,
config: dict,
) -> None:
import triton.language as tl
from sglang.kernels.ops.moe.fused_moe_triton_kernels import (
invoke_fused_moe_kernel,
)
invoke_fused_moe_kernel(
a,
b,
None,
out,
None,
None,
None,
self._unused_topk_weights,
row_state.topk_ids,
row_state.sorted_token_ids,
row_state.expert_ids,
row_state.num_tokens_post_padded,
False,
top_k,
config,
compute_type=tl.bfloat16,
use_fp8_w8a8=False,
use_int8_w8a8=False,
use_int8_w8a16=False,
use_int4_w4a16=False,
per_channel_quant=False,
)
def gateup(self, row_state: TritonRowState, out: torch.Tensor) -> None:
# GEMM1 gathers token row pair_id // top_k.
self._invoke(
row_state.hidden_states,
self.quant_info.w13_weight,
out,
row_state,
top_k=row_state.top_k,
config=row_state.config,
)
def down(
self,
row_state: TritonRowState,
act_out: torch.Tensor,
out: torch.Tensor,
) -> None:
self._invoke(
act_out,
self.quant_info.w2_weight,
out,
row_state,
top_k=1,
config=row_state.down_config or row_state.config,
)
def gateup_out_shape(self, row_state: TritonRowState) -> tuple[int, ...]:
return (
row_state.num_pairs,
self.gate_up_slices * self.quant_info.intermediate_size,
)
def act_out_shape(self, row_state: TritonRowState) -> tuple[int, ...]:
return (row_state.num_pairs, self.quant_info.intermediate_size)
def down_out_shape(self, row_state: TritonRowState) -> tuple[int, ...]:
return (row_state.num_pairs, self.quant_info.hidden_size)
@@ -0,0 +1,106 @@
"""Triton FP8 GEMMs with 128-block scales and BF16 LoRA inputs/outputs."""
from __future__ import annotations
import torch
from sglang.srt.lora.moe.base_gemm_provider.base import MoeBaseProviderContract
from sglang.srt.lora.moe.base_gemm_provider.triton_bf16 import (
TritonBf16ContiguousProvider,
TritonRowState,
)
from sglang.srt.lora.moe.quant_info import MoeLoraFp8QuantInfo
class TritonFp8ContiguousProvider(TritonBf16ContiguousProvider):
contract = MoeBaseProviderContract(
key="triton_fp8_contiguous",
quant_info_cls=MoeLoraFp8QuantInfo,
gate_first=True,
interleaved=False,
gate_up_output_dtype=torch.bfloat16,
lora_delta_dtype=torch.bfloat16,
lora_activation_dtype=torch.bfloat16,
act_quant_group=128,
)
_config_dtype_tag = "fp8_w8a8"
def __init__(self, quant_info: MoeLoraFp8QuantInfo):
super().__init__(quant_info)
self._config_block_shape = list(quant_info.block_shape)
def _invoke_fp8(
self,
a: torch.Tensor,
b: torch.Tensor,
b_scale: torch.Tensor,
out: torch.Tensor,
row_state: TritonRowState,
*,
top_k: int,
config: dict,
a_scale: torch.Tensor | None = None,
) -> None:
import triton.language as tl
from sglang.kernels.ops.moe.fused_moe_triton_kernels import (
invoke_fused_moe_kernel,
)
invoke_fused_moe_kernel(
a,
b,
None,
out,
# Pre-quantized activations carry their matching scales.
a_scale,
b_scale,
None,
self._unused_topk_weights,
row_state.topk_ids,
row_state.sorted_token_ids,
row_state.expert_ids,
row_state.num_tokens_post_padded,
False,
top_k,
config,
compute_type=tl.bfloat16,
use_fp8_w8a8=True,
use_int8_w8a8=False,
use_int8_w8a16=False,
use_int4_w4a16=False,
per_channel_quant=False,
block_shape=self._config_block_shape,
)
def gateup(self, row_state: TritonRowState, out: torch.Tensor) -> None:
self._invoke_fp8(
row_state.hidden_states,
self.quant_info.w13_weight,
self.quant_info.w13_scale,
out,
row_state,
top_k=row_state.top_k,
config=row_state.config,
)
def down(
self,
row_state: TritonRowState,
act_out: torch.Tensor,
out: torch.Tensor,
) -> None:
a, a_scale = act_out, None
if row_state.act_quant is not None:
a, a_scale = row_state.act_quant
self._invoke_fp8(
a,
self.quant_info.w2_weight,
self.quant_info.w2_scale,
out,
row_state,
top_k=1,
config=row_state.down_config or row_state.config,
a_scale=a_scale,
)
@@ -0,0 +1,56 @@
# MoE LoRA execution plans
`<arch>.plans.json` selects the base row layout and LoRA execution stages for
`lora_triton`, `lora_cutedsl` and `lora_marlin`. Supported capability majors
9 and 10 select `sm90` and `sm100`, respectively. Other architectures,
including SM120, are unsupported. A missing table uses `default.plans.json`.
## Selection and overrides
`SGLANG_LORA_MOE_CONFIG_DIR` supplies override files before packaged files.
Tables are process-cached; use a fresh server to evaluate an override.
The file contains a tuned `domain`, ordered `scenarios`, and conservative
`fallback` rows. Scenario selection matches adapter layout, phase, pool rank,
resident expert count and quantization. Shapes outside the tuned domain use
fallback rows. Row names are labels, not selectors.
Each row declares:
- `base_gemm_rows`: `expert_major` or `route_major`;
- `plan`: A/B, activation and finalization families plus overlap and routing;
- `tiles`: ordered rank/token rules containing per-site launch configurations.
Rank filters are applied before the first matching token bound is selected.
An unbounded token rule ends that rank's ladder. `{ "sites": {} }` or no
surviving rank rule uses launch defaults; a supplied site section must be
complete. Invalid keys, tiles or shadowed ladders fail at loading, even in an
unselected row.
The plan determines which route views and buffers are consumed. Per-expert
adapters have factors for each resident expert; shared-outer adapters share
the gate/up A and down B factors across experts. Raw views retain token/expert
pairs. Aligned views bucket and pad pairs for grouped kernels. Shared-token
plans instead group one row per token. Route construction must not create
views the selected stages do not need.
Runtime orchestration remains in `srt/lora`: MoE plans, runner and base-GEMM
providers under `srt/lora/moe`, the shared workspace in `srt/lora/workspace.py`.
Device kernels live in `kernels/ops/lora/common` for
shared routing/A/B operations and `kernels/ops/lora/moe` for MoE stages and
CuTeDSL kernels. Existing upstream LoRA registry and dense token kernels keep
their paths.
## Tuning and evidence
Search bounded launch tiles while retaining plan families and base-GEMM
configurations. Whole-runner fixture timings are not model TPS. Base-GEMM
tables have a separate schema and admission policy.
New production rows need numerical checks, independent locked validation and
model-level target/control measurements on their exact device and affected
selector regions. Do not copy isolated kernel winners into broader rules or
treat aggregate gains as proof that every cell is regression-free.
Historical exploration and measurements remain in Git history; private
campaign paths and retired tools are not part of the public tuning contract.
@@ -0,0 +1,39 @@
# MoE LoRA base-GEMM launch-config store
M-bucketed JSON tables consumed by `gemm_config_store.load_config_table`.
One file per (provider, geometry, device); the provider key names the
weight dtype, so the file name carries no separate dtype field:
```
provider={cutedsl_bf16_masked|cutedsl_bf16_contiguous|cutedsl_fp8_masked|cutedsl_fp8_contiguous},E={E_local},N1={gate_up_slices*I},N2={H},K={H},device_name={NVIDIA_...}.json
```
Payload keys are `expected_m` buckets (nearest-M lookup); each bucket payload
carries `token_width`. The optional `tiles` list declares the tile set to
compile at attach — one `persistent_clusters` per `token_width`. The
optional `version` map (e.g. `{"cutedsl": "..."}`) records the package
release the table was tuned with. It is provenance, not a guarantee: with a
different installed release the table is still used (its tiles are compiled
and checked before use) and a warning names the table and both releases,
because the tile choices have not been re-validated on that release.
When the pinned compiler release changes:
1. List the tables whose recorded release differs (the startup warnings).
2. For each affected provider, geometry and device you can run, check the
numerics against the FP32 reference and compare the table with the
built-in heuristics on a representative serving shape.
3. Re-tune only where that evidence calls for it, and record the new release
in `version`. Keep a note of the scopes you could not test.
Missing or malformed files use the provider's built-in heuristics.
`SGLANG_LORA_MOE_CONFIG_DIR` names an override config root at load time;
tables are read from its `base_gemm/` subdirectory.
The [maintained LoRA tuner](../../../../../../../benchmark/kernels/lora_moe/README.md)
currently searches LoRA launch tiles while retaining these base configurations.
It does not emit base-GEMM tables. The old partial-GEMM sweep is historical
screening evidence, not a complete-runner correctness or performance gate.
New tables need numerical checks and complete-runner validation on their exact
device/geometry; do not populate this directory from isolated stage timings.
@@ -0,0 +1,34 @@
{
"version": {
"generated_on": "NVIDIA H200",
"cutedsl": "4.6.0"
},
"buckets": {
"8": {
"token_width": 8
},
"16": {
"token_width": 32
},
"32": {
"token_width": 32
},
"48": {
"token_width": 64
}
},
"tiles": [
{
"token_width": 8,
"persistent_clusters": 128
},
{
"token_width": 32,
"persistent_clusters": 128
},
{
"token_width": 64,
"persistent_clusters": 128
}
]
}
@@ -0,0 +1,41 @@
{
"version": {
"generated_on": "NVIDIA B200",
"cutedsl": "4.8.0"
},
"buckets": {
"16": {
"token_width": 16
},
"24": {
"token_width": 32
},
"32": {
"token_width": 64
},
"64": {
"token_width": 64
},
"80": {
"token_width": 128
}
},
"tiles": [
{
"token_width": 16,
"persistent_clusters": 148
},
{
"token_width": 32,
"persistent_clusters": 148
},
{
"token_width": 64,
"persistent_clusters": 148
},
{
"token_width": 128,
"persistent_clusters": 148
}
]
}
@@ -0,0 +1,31 @@
{
"version": {
"generated_on": "NVIDIA H200",
"cutedsl": "4.8.0"
},
"buckets": {
"16": {
"token_width": 16
},
"32": {
"token_width": 32
},
"96": {
"token_width": 64
}
},
"tiles": [
{
"token_width": 16,
"persistent_clusters": 132
},
{
"token_width": 32,
"persistent_clusters": 132
},
{
"token_width": 64,
"persistent_clusters": 128
}
]
}
@@ -0,0 +1,31 @@
{
"version": {
"generated_on": "NVIDIA B200",
"cutedsl": "4.6.2"
},
"buckets": {
"16": {
"token_width": 16
},
"32": {
"token_width": 32
},
"160": {
"token_width": 64
}
},
"tiles": [
{
"token_width": 16,
"persistent_clusters": 148
},
{
"token_width": 32,
"persistent_clusters": 148
},
{
"token_width": 64,
"persistent_clusters": 128
}
]
}
@@ -0,0 +1,31 @@
{
"version": {
"generated_on": "NVIDIA H200",
"cutedsl": "4.8.0"
},
"buckets": {
"16": {
"token_width": 16
},
"32": {
"token_width": 32
},
"96": {
"token_width": 64
}
},
"tiles": [
{
"token_width": 16,
"persistent_clusters": 132
},
{
"token_width": 32,
"persistent_clusters": 132
},
{
"token_width": 64,
"persistent_clusters": 128
}
]
}
@@ -0,0 +1,46 @@
{
"version": {
"generated_on": "NVIDIA B200",
"cutedsl": "4.6.2"
},
"buckets": {
"8": {
"token_width": 8
},
"10": {
"token_width": 64
},
"64": {
"token_width": 64
},
"80": {
"token_width": 128
},
"128": {
"token_width": 128
},
"160": {
"token_width": 64
},
"192": {
"token_width": 64
},
"256": {
"token_width": 128
}
},
"tiles": [
{
"token_width": 8,
"persistent_clusters": 128
},
{
"token_width": 64,
"persistent_clusters": 128
},
{
"token_width": 128,
"persistent_clusters": 128
}
]
}
@@ -0,0 +1,34 @@
{
"version": {
"generated_on": "NVIDIA GB300",
"cutedsl": "4.6.2"
},
"buckets": {
"8": {
"token_width": 8
},
"10": {
"token_width": 64
},
"64": {
"token_width": 64
},
"80": {
"token_width": 128
}
},
"tiles": [
{
"token_width": 8,
"persistent_clusters": 128
},
{
"token_width": 64,
"persistent_clusters": 128
},
{
"token_width": 128,
"persistent_clusters": 152
}
]
}
@@ -0,0 +1,45 @@
{
"version": {
"generated_on": "NVIDIA B200",
"cutedsl": "4.6.2"
},
"buckets": {
"2": {
"token_width": 8
},
"8": {
"token_width": 16
},
"32": {
"token_width": 32
},
"64": {
"token_width": 64
},
"128": {
"token_width": 128
}
},
"tiles": [
{
"token_width": 8,
"persistent_clusters": 148
},
{
"token_width": 16,
"persistent_clusters": 148
},
{
"token_width": 32,
"persistent_clusters": 148
},
{
"token_width": 64,
"persistent_clusters": 148
},
{
"token_width": 128,
"persistent_clusters": 148
}
]
}
@@ -0,0 +1,45 @@
{
"version": {
"generated_on": "NVIDIA GB300",
"cutedsl": "4.6.2"
},
"buckets": {
"2": {
"token_width": 8
},
"8": {
"token_width": 16
},
"32": {
"token_width": 32
},
"64": {
"token_width": 64
},
"128": {
"token_width": 128
}
},
"tiles": [
{
"token_width": 8,
"persistent_clusters": 152
},
{
"token_width": 16,
"persistent_clusters": 152
},
{
"token_width": 32,
"persistent_clusters": 152
},
{
"token_width": 64,
"persistent_clusters": 152
},
{
"token_width": 128,
"persistent_clusters": 152
}
]
}
@@ -0,0 +1,38 @@
{
"version": {
"generated_on": "NVIDIA H200",
"cutedsl": "4.6.0"
},
"buckets": {
"8": {
"token_width": 8
},
"16": {
"token_width": 16
},
"32": {
"token_width": 32
},
"96": {
"token_width": 64
}
},
"tiles": [
{
"token_width": 8,
"persistent_clusters": 128
},
{
"token_width": 16,
"persistent_clusters": 128
},
{
"token_width": 32,
"persistent_clusters": 128
},
{
"token_width": 64,
"persistent_clusters": 128
}
]
}
@@ -0,0 +1,41 @@
{
"version": {
"generated_on": "NVIDIA B200",
"cutedsl": "4.6.2"
},
"buckets": {
"2": {
"token_width": 8
},
"8": {
"token_width": 16
},
"32": {
"token_width": 64
},
"64": {
"token_width": 64
},
"128": {
"token_width": 128
}
},
"tiles": [
{
"token_width": 8,
"persistent_clusters": 148
},
{
"token_width": 16,
"persistent_clusters": 148
},
{
"token_width": 64,
"persistent_clusters": 148
},
{
"token_width": 128,
"persistent_clusters": 148
}
]
}
@@ -0,0 +1,38 @@
{
"version": {
"generated_on": "NVIDIA H200",
"cutedsl": "4.6.0"
},
"buckets": {
"8": {
"token_width": 8
},
"16": {
"token_width": 16
},
"32": {
"token_width": 32
},
"96": {
"token_width": 64
}
},
"tiles": [
{
"token_width": 8,
"persistent_clusters": 128
},
{
"token_width": 16,
"persistent_clusters": 128
},
{
"token_width": 32,
"persistent_clusters": 128
},
{
"token_width": 64,
"persistent_clusters": 128
}
]
}
@@ -0,0 +1,41 @@
{
"version": {
"generated_on": "NVIDIA GB300",
"cutedsl": "4.6.2"
},
"buckets": {
"2": {
"token_width": 8
},
"8": {
"token_width": 16
},
"32": {
"token_width": 64
},
"64": {
"token_width": 64
},
"128": {
"token_width": 128
}
},
"tiles": [
{
"token_width": 8,
"persistent_clusters": 152
},
{
"token_width": 16,
"persistent_clusters": 152
},
{
"token_width": 64,
"persistent_clusters": 152
},
{
"token_width": 128,
"persistent_clusters": 152
}
]
}
@@ -0,0 +1,101 @@
{
"domain": {
"max_hidden": 0,
"max_local_experts": 0
},
"scenarios": [],
"fallback": [
{
"name": "fallback.decode.shared",
"layout": "shared",
"phase": "decode",
"base_gemm_rows": "expert_major",
"plan": {
"gate_up_a_family": "grouped",
"down_a_family": "grouped",
"gate_up_b_family": "grouped",
"act_family": "materialized",
"finalize_family": "shared_one_pass"
},
"tiles": [
{
"sites": {
"shared_one_pass": {
"BLOCK_SIZE_H": 128,
"num_stages": 3,
"num_warps": 4
}
}
}
]
},
{
"name": "fallback.decode",
"phase": "decode",
"base_gemm_rows": "expert_major",
"plan": {
"gate_up_a_family": "grouped",
"down_a_family": "grouped",
"gate_up_b_family": "grouped",
"down_b_family": "grouped",
"act_family": "materialized",
"finalize_family": "materialized"
},
"tiles": [
{
"sites": {}
}
]
},
{
"name": "fallback.prefill.per_expert",
"layout": "per_expert",
"phase": "prefill",
"base_gemm_rows": "route_major",
"plan": {
"gate_up_a_family": "grouped",
"down_a_family": "grouped",
"down_b_family": "grouped",
"act_family": "b_activation",
"finalize_family": "materialized",
"down_b_into_base": true
},
"tiles": [
{
"sites": {}
}
]
},
{
"name": "fallback.prefill.shared",
"layout": "shared",
"phase": "prefill",
"base_gemm_rows": "route_major",
"plan": {
"gate_up_a_family": "token_grouped",
"down_a_family": "grouped",
"act_family": "b_activation",
"finalize_family": "shared_token_delta",
"route_builder": "parallel_shared_outer"
},
"tiles": [
{
"sites": {
"shared_token_delta": {
"reduce": {
"BLOCK_SIZE_T": 32,
"num_stages": 2,
"num_warps": 4
},
"tail": {
"BLOCK_SIZE_H": 128,
"num_stages": 3,
"num_warps": 4
}
}
}
}
]
}
]
}
@@ -0,0 +1,974 @@
{
"domain": {
"max_hidden": 8192,
"max_local_experts": 512
},
"scenarios": [
{
"name": "decode.per_expert",
"layout": "per_expert",
"phase": "decode",
"base_gemm_rows": "expert_major",
"plan": {
"gate_up_a_family": "grouped",
"down_a_family": "grouped",
"gate_up_b_family": "per_row",
"down_b_family": "per_row",
"act_family": "materialized",
"finalize_family": "materialized",
"gate_up_overlap": "gate_up_a_b",
"down_overlap": "down_a_b"
},
"tiles": [
{
"max_rank": 16,
"max_tokens": 4,
"sites": {
"b_activation": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_W": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"down_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 16,
"GROUP_SIZE_M": 8,
"num_stages": 4,
"num_warps": 4
},
"down_b": {
"BLOCK_SIZE_K": 16,
"BLOCK_SIZE_N": 256,
"GROUP_SIZE_M": 1,
"num_stages": 2,
"num_warps": 8
},
"gate_up_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 16,
"GROUP_SIZE_M": 8,
"num_stages": 3,
"num_warps": 4,
"SPLIT_K": 8
},
"gate_up_b": {
"BLOCK_SIZE_K": 16,
"BLOCK_SIZE_N": 128,
"GROUP_SIZE_M": 4,
"num_stages": 2,
"num_warps": 4
},
"routing_block_size": 16
}
},
{
"max_rank": 16,
"max_tokens": 16,
"sites": {
"b_activation": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_W": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"down_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 16,
"GROUP_SIZE_M": 8,
"num_stages": 4,
"num_warps": 4
},
"down_b": {
"BLOCK_SIZE_K": 16,
"BLOCK_SIZE_N": 256,
"GROUP_SIZE_M": 1,
"num_stages": 2,
"num_warps": 8
},
"gate_up_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 16,
"GROUP_SIZE_M": 8,
"num_stages": 3,
"num_warps": 4,
"SPLIT_K": 4
},
"gate_up_b": {
"BLOCK_SIZE_K": 16,
"BLOCK_SIZE_N": 128,
"GROUP_SIZE_M": 4,
"num_stages": 2,
"num_warps": 4
},
"routing_block_size": 16
}
},
{
"max_rank": 16,
"sites": {
"b_activation": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_W": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"down_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 16,
"GROUP_SIZE_M": 8,
"num_stages": 4,
"num_warps": 4
},
"down_b": {
"BLOCK_SIZE_K": 16,
"BLOCK_SIZE_N": 256,
"GROUP_SIZE_M": 1,
"num_stages": 2,
"num_warps": 8
},
"gate_up_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 16,
"GROUP_SIZE_M": 8,
"num_stages": 3,
"num_warps": 4
},
"gate_up_b": {
"BLOCK_SIZE_K": 16,
"BLOCK_SIZE_N": 128,
"GROUP_SIZE_M": 4,
"num_stages": 2,
"num_warps": 4
},
"routing_block_size": 16
}
},
{
"max_tokens": 4,
"sites": {
"b_activation": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_W": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"down_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 16,
"GROUP_SIZE_M": 8,
"num_stages": 4,
"num_warps": 4
},
"down_b": {
"BLOCK_SIZE_K": 16,
"BLOCK_SIZE_N": 256,
"GROUP_SIZE_M": 1,
"num_stages": 2,
"num_warps": 8
},
"gate_up_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 16,
"GROUP_SIZE_M": 8,
"num_stages": 3,
"num_warps": 4
},
"gate_up_b": {
"BLOCK_SIZE_K": 16,
"BLOCK_SIZE_N": 128,
"GROUP_SIZE_M": 4,
"num_stages": 2,
"num_warps": 4
},
"routing_block_size": 16
}
},
{
"max_tokens": 16,
"sites": {
"b_activation": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_W": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"down_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 3,
"num_warps": 8
},
"down_b": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_N": 128,
"GROUP_SIZE_M": 1,
"num_stages": 2,
"num_warps": 4
},
"gate_up_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 4,
"num_warps": 4
},
"gate_up_b": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_N": 512,
"GROUP_SIZE_M": 4,
"num_stages": 2,
"num_warps": 4
},
"routing_block_size": 16
}
},
{
"max_rank": 32,
"sites": {
"b_activation": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_W": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"down_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 3,
"num_warps": 8
},
"down_b": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_N": 128,
"GROUP_SIZE_M": 1,
"num_stages": 2,
"num_warps": 4
},
"gate_up_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 4,
"num_warps": 4
},
"gate_up_b": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_N": 512,
"GROUP_SIZE_M": 4,
"num_stages": 2,
"num_warps": 4
},
"routing_block_size": 16
}
},
{
"sites": {
"b_activation": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_W": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"down_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 4,
"num_warps": 8
},
"down_b": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_N": 256,
"GROUP_SIZE_M": 4,
"num_stages": 2,
"num_warps": 8
},
"gate_up_a": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 4,
"num_warps": 4
},
"gate_up_b": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_N": 256,
"GROUP_SIZE_M": 16,
"num_stages": 2,
"num_warps": 4
},
"routing_block_size": 16
}
}
]
},
{
"name": "prefill.per_expert",
"layout": "per_expert",
"phase": "prefill",
"base_gemm_rows": "route_major",
"plan": {
"gate_up_a_family": "grouped",
"down_a_family": "grouped",
"down_b_family": "grouped",
"act_family": "b_activation",
"finalize_family": "materialized"
},
"tiles": [
{
"max_rank": 8,
"sites": {
"b_activation": {
"BLOCK_SIZE_K": 16,
"BLOCK_SIZE_W": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"down_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"down_b": {
"BLOCK_SIZE_K": 16,
"BLOCK_SIZE_N": 128,
"GROUP_SIZE_M": 16,
"num_stages": 2,
"num_warps": 2
},
"gate_up_a": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_N": 16,
"GROUP_SIZE_M": 8,
"num_stages": 3,
"num_warps": 2
},
"gate_up_b": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_N": 128,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"routing_block_size": 32
}
},
{
"max_rank": 16,
"sites": {
"b_activation": {
"BLOCK_SIZE_K": 16,
"BLOCK_SIZE_W": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"down_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 16,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"down_b": {
"BLOCK_SIZE_K": 16,
"BLOCK_SIZE_N": 128,
"GROUP_SIZE_M": 16,
"num_stages": 2,
"num_warps": 2
},
"gate_up_a": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_N": 32,
"GROUP_SIZE_M": 8,
"num_stages": 3,
"num_warps": 2
},
"gate_up_b": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_N": 128,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"routing_block_size": 32
}
},
{
"sites": {
"b_activation": {
"BLOCK_SIZE_K": 16,
"BLOCK_SIZE_W": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"down_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"down_b": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_N": 128,
"GROUP_SIZE_M": 16,
"num_stages": 2,
"num_warps": 2
},
"gate_up_a": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 3,
"num_warps": 1
},
"gate_up_b": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_N": 128,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"routing_block_size": 32
}
}
]
},
{
"name": "decode.shared.fp8.e_ge512",
"layout": "shared",
"phase": "decode",
"min_local_experts": 512,
"quant": [
"fp8"
],
"base_gemm_rows": "expert_major",
"plan": {
"gate_up_a_family": "grouped",
"down_a_family": "grouped",
"act_family": "b_activation",
"finalize_family": "shared_one_pass",
"gate_up_overlap": "gate_up_a",
"down_overlap": "down_a",
"route_builder": "parallel_shared_outer"
},
"tiles": [
{
"sites": {
"b_activation": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_W": 64,
"GROUP_SIZE_M": 1,
"num_stages": 2,
"num_warps": 4
},
"down_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 4,
"num_warps": 4
},
"down_b": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_M": 16,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"gate_up_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 4,
"num_warps": 4
},
"gate_up_b": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_M": 16,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"routing_block_size": 16,
"shared_one_pass": {
"BLOCK_SIZE_H": 128,
"num_stages": 3,
"num_warps": 4
}
}
}
]
},
{
"name": "decode.shared.nvfp4",
"layout": "shared",
"phase": "decode",
"quant": [
"nvfp4"
],
"base_gemm_rows": "expert_major",
"plan": {
"gate_up_a_family": "token_dense",
"gate_up_b_family": "per_row",
"down_a_family": "per_row",
"act_family": "materialized",
"finalize_family": "shared_one_pass",
"gate_up_overlap": "gate_up_a_b",
"down_overlap": "down_a",
"route_builder": "standard"
},
"tiles": [
{
"sites": {
"b_activation": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_W": 64,
"GROUP_SIZE_M": 1,
"num_stages": 2,
"num_warps": 4
},
"down_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 4,
"num_warps": 4
},
"down_b": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_M": 16,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"gate_up_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 4,
"num_warps": 4
},
"gate_up_b": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_M": 16,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"routing_block_size": 16,
"shared_one_pass": {
"BLOCK_SIZE_H": 128,
"num_stages": 2,
"num_warps": 4
}
}
}
]
},
{
"name": "decode.shared",
"layout": "shared",
"phase": "decode",
"base_gemm_rows": "expert_major",
"plan": {
"gate_up_a_family": "grouped",
"down_a_family": "grouped",
"gate_up_b_family": "grouped",
"act_family": "materialized",
"finalize_family": "shared_one_pass",
"gate_up_overlap": "gate_up_a_b",
"down_overlap": "down_a",
"route_builder": "parallel_shared_outer"
},
"tiles": [
{
"sites": {
"b_activation": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_W": 64,
"GROUP_SIZE_M": 1,
"num_stages": 2,
"num_warps": 4
},
"down_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 4,
"num_warps": 4
},
"down_b": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_M": 16,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"gate_up_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 4,
"num_warps": 4
},
"gate_up_b": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_M": 16,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"routing_block_size": 16,
"shared_one_pass": {
"BLOCK_SIZE_H": 128,
"num_stages": 3,
"num_warps": 4
}
}
}
]
},
{
"name": "prefill.shared",
"layout": "shared",
"phase": "prefill",
"base_gemm_rows": "route_major",
"plan": {
"gate_up_a_family": "token_grouped",
"down_a_family": "grouped",
"act_family": "b_activation",
"finalize_family": "shared_token_delta",
"route_builder": "parallel_shared_outer"
},
"tiles": [
{
"sites": {
"b_activation": {
"BLOCK_SIZE_K": 16,
"BLOCK_SIZE_W": 128,
"GROUP_SIZE_M": 8,
"num_stages": 4,
"num_warps": 4
},
"down_a": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 3,
"num_warps": 4
},
"down_b": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_N": 256,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 2
},
"gate_up_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 4,
"num_warps": 4
},
"gate_up_b": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_M": 32,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"routing_block_size": 32,
"shared_token_delta": {
"reduce": {
"BLOCK_SIZE_T": 32,
"num_stages": 2,
"num_warps": 4
},
"tail": {
"BLOCK_SIZE_H": 1024,
"num_stages": 2,
"num_warps": 8
}
}
}
}
]
}
],
"fallback": [
{
"name": "fallback.decode.shared",
"layout": "shared",
"phase": "decode",
"base_gemm_rows": "expert_major",
"plan": {
"gate_up_a_family": "grouped",
"down_a_family": "grouped",
"gate_up_b_family": "grouped",
"act_family": "materialized",
"finalize_family": "shared_one_pass",
"gate_up_overlap": "gate_up_a_b",
"down_overlap": "down_a",
"route_builder": "parallel_shared_outer"
},
"tiles": [
{
"sites": {
"b_activation": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_W": 64,
"GROUP_SIZE_M": 1,
"num_stages": 2,
"num_warps": 4
},
"down_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 4,
"num_warps": 4
},
"down_b": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_M": 16,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"gate_up_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 4,
"num_warps": 4
},
"gate_up_b": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_M": 16,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"routing_block_size": 16,
"shared_one_pass": {
"BLOCK_SIZE_H": 128,
"num_stages": 3,
"num_warps": 4
}
}
}
]
},
{
"name": "fallback.decode",
"phase": "decode",
"base_gemm_rows": "expert_major",
"plan": {
"gate_up_a_family": "per_row",
"down_a_family": "grouped",
"gate_up_b_family": "grouped",
"down_b_family": "grouped",
"act_family": "materialized",
"finalize_family": "materialized",
"down_overlap": "down_a_b",
"gate_up_overlap": "gate_up_a_b"
},
"tiles": [
{
"sites": {
"b_activation": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_W": 64,
"GROUP_SIZE_M": 8,
"num_stages": 3,
"num_warps": 4
},
"down_a": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_N": 32,
"GROUP_SIZE_M": 8,
"num_stages": 4,
"num_warps": 4
},
"down_b": {
"BLOCK_SIZE_K": 16,
"BLOCK_SIZE_M": 16,
"BLOCK_SIZE_N": 128,
"GROUP_SIZE_M": 1,
"num_stages": 2,
"num_warps": 4
},
"gate_up_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 32,
"GROUP_SIZE_M": 8,
"num_stages": 4,
"num_warps": 4
},
"gate_up_b": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_M": 16,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"routing_block_size": 16
}
}
]
},
{
"name": "fallback.prefill.per_expert",
"layout": "per_expert",
"phase": "prefill",
"base_gemm_rows": "route_major",
"plan": {
"gate_up_a_family": "grouped",
"down_a_family": "grouped",
"down_b_family": "grouped",
"act_family": "b_activation",
"finalize_family": "materialized"
},
"tiles": [
{
"sites": {
"b_activation": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_W": 64,
"GROUP_SIZE_M": 8,
"num_stages": 3,
"num_warps": 4
},
"down_a": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_N": 32,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"down_b": {
"BLOCK_SIZE_K": 16,
"BLOCK_SIZE_M": 32,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"gate_up_a": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_N": 32,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"gate_up_b": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_M": 32,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"routing_block_size": 32
}
}
]
},
{
"name": "fallback.prefill.shared",
"layout": "shared",
"phase": "prefill",
"base_gemm_rows": "route_major",
"plan": {
"gate_up_a_family": "token_grouped",
"down_a_family": "grouped",
"act_family": "b_activation",
"finalize_family": "shared_token_delta",
"route_builder": "parallel_shared_outer"
},
"tiles": [
{
"sites": {
"b_activation": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_W": 64,
"GROUP_SIZE_M": 8,
"num_stages": 3,
"num_warps": 4
},
"down_a": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_N": 32,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"down_b": {
"BLOCK_SIZE_K": 16,
"BLOCK_SIZE_M": 32,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"gate_up_a": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_N": 32,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"gate_up_b": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_M": 32,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"routing_block_size": 32,
"shared_token_delta": {
"reduce": {
"BLOCK_SIZE_T": 32,
"num_stages": 2,
"num_warps": 4
},
"tail": {
"BLOCK_SIZE_H": 1024,
"num_stages": 2,
"num_warps": 8
}
}
}
}
]
}
]
}
@@ -0,0 +1,634 @@
{
"domain": {
"max_hidden": 4096,
"max_local_experts": 512
},
"scenarios": [
{
"name": "decode.per_expert",
"layout": "per_expert",
"phase": "decode",
"base_gemm_rows": "expert_major",
"plan": {
"gate_up_a_family": "grouped",
"down_a_family": "per_row",
"gate_up_b_family": "grouped",
"down_b_family": "grouped",
"act_family": "materialized",
"finalize_family": "materialized",
"gate_up_overlap": "gate_up_a_b",
"down_overlap": "down_a_b"
},
"tiles": [
{
"sites": {
"b_activation": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_W": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"down_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 16,
"num_stages": 2,
"num_warps": 8
},
"down_b": {
"BLOCK_SIZE_K": 16,
"BLOCK_SIZE_N": 128,
"GROUP_SIZE_M": 1,
"num_stages": 2,
"num_warps": 4
},
"gate_up_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 3,
"num_warps": 4
},
"gate_up_b": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_N": 128,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"routing_block_size": 16
}
}
]
},
{
"name": "prefill.per_expert.rank_le16",
"layout": "per_expert",
"phase": "prefill",
"base_gemm_rows": "route_major",
"plan": {
"gate_up_a_family": "grouped",
"down_a_family": "grouped",
"down_b_family": "grouped",
"act_family": "b_activation",
"finalize_family": "materialized",
"down_b_into_base": true,
"gate_up_overlap": "gate_up_a"
},
"max_rank": 16,
"tiles": [
{
"sites": {
"b_activation": {
"BLOCK_SIZE_K": 16,
"BLOCK_SIZE_W": 64,
"GROUP_SIZE_M": 16,
"num_stages": 2,
"num_warps": 4
},
"down_a": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_N": 16,
"GROUP_SIZE_M": 16,
"num_stages": 2,
"num_warps": 2
},
"down_b": {
"BLOCK_SIZE_K": 16,
"BLOCK_SIZE_N": 128,
"GROUP_SIZE_M": 1,
"num_stages": 2,
"num_warps": 4
},
"gate_up_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 32,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 2
},
"gate_up_b": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_M": 32,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"routing_block_size": 32
}
}
]
},
{
"name": "prefill.per_expert",
"layout": "per_expert",
"phase": "prefill",
"base_gemm_rows": "route_major",
"plan": {
"gate_up_a_family": "grouped",
"down_a_family": "grouped",
"down_b_family": "grouped",
"act_family": "b_activation",
"finalize_family": "materialized",
"down_b_into_base": true
},
"tiles": [
{
"sites": {
"b_activation": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_W": 256,
"GROUP_SIZE_M": 16,
"num_stages": 4,
"num_warps": 4
},
"down_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"down_b": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_N": 128,
"GROUP_SIZE_M": 1,
"num_stages": 2,
"num_warps": 4
},
"gate_up_a": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 3,
"num_warps": 4
},
"gate_up_b": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_M": 32,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"routing_block_size": 32
}
}
]
},
{
"name": "decode.shared",
"layout": "shared",
"phase": "decode",
"base_gemm_rows": "expert_major",
"plan": {
"gate_up_a_family": "grouped",
"down_a_family": "grouped",
"gate_up_b_family": "grouped",
"act_family": "materialized",
"finalize_family": "shared_one_pass",
"gate_up_overlap": "gate_up_a_b",
"down_overlap": "down_a",
"route_builder": "parallel_shared_outer"
},
"tiles": [
{
"sites": {
"b_activation": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_W": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"down_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 4,
"num_warps": 4
},
"down_b": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_N": 128,
"GROUP_SIZE_M": 1,
"num_stages": 2,
"num_warps": 4
},
"gate_up_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 32,
"GROUP_SIZE_M": 8,
"num_stages": 3,
"num_warps": 4
},
"gate_up_b": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_N": 256,
"GROUP_SIZE_M": 4,
"num_stages": 3,
"num_warps": 8
},
"routing_block_size": 16,
"shared_one_pass": {
"BLOCK_SIZE_H": 128,
"num_stages": 3,
"num_warps": 4
}
}
}
]
},
{
"name": "prefill.shared.rank_le16",
"layout": "shared",
"phase": "prefill",
"max_rank": 16,
"base_gemm_rows": "route_major",
"plan": {
"gate_up_a_family": "token_grouped",
"down_a_family": "grouped",
"act_family": "b_activation",
"finalize_family": "shared_token_delta",
"gate_up_overlap": "gate_up_a"
},
"tiles": [
{
"sites": {
"b_activation": {
"BLOCK_SIZE_K": 16,
"BLOCK_SIZE_W": 128,
"GROUP_SIZE_M": 1,
"num_stages": 4,
"num_warps": 4
},
"down_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 3,
"num_warps": 4
},
"down_b": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_M": 16,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"gate_up_a": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 3,
"num_warps": 4
},
"gate_up_b": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_M": 16,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"routing_block_size": 16,
"shared_token_delta": {
"reduce": {
"BLOCK_SIZE_T": 16,
"num_stages": 2,
"num_warps": 8
},
"tail": {
"BLOCK_SIZE_H": 1024,
"num_stages": 2,
"num_warps": 8
}
}
}
}
]
},
{
"name": "prefill.shared",
"layout": "shared",
"phase": "prefill",
"base_gemm_rows": "route_major",
"plan": {
"gate_up_a_family": "token_grouped",
"down_a_family": "grouped",
"act_family": "b_activation",
"finalize_family": "shared_token_delta",
"route_builder": "parallel_shared_outer"
},
"tiles": [
{
"sites": {
"b_activation": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_W": 64,
"GROUP_SIZE_M": 1,
"num_stages": 4,
"num_warps": 4
},
"down_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 3,
"num_warps": 4
},
"down_b": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_M": 64,
"BLOCK_SIZE_N": 128,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"gate_up_a": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 3,
"num_warps": 4
},
"gate_up_b": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_M": 64,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"routing_block_size": 64,
"shared_token_delta": {
"reduce": {
"BLOCK_SIZE_T": 16,
"num_stages": 2,
"num_warps": 8
},
"tail": {
"BLOCK_SIZE_H": 1024,
"num_stages": 2,
"num_warps": 8
}
}
}
}
]
}
],
"fallback": [
{
"name": "fallback.decode.shared",
"layout": "shared",
"phase": "decode",
"base_gemm_rows": "expert_major",
"plan": {
"gate_up_a_family": "grouped",
"down_a_family": "grouped",
"gate_up_b_family": "grouped",
"act_family": "materialized",
"finalize_family": "shared_one_pass",
"gate_up_overlap": "gate_up_a_b",
"down_overlap": "down_a",
"route_builder": "parallel_shared_outer"
},
"tiles": [
{
"sites": {
"b_activation": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_W": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"down_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 4,
"num_warps": 4
},
"down_b": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_N": 128,
"GROUP_SIZE_M": 1,
"num_stages": 2,
"num_warps": 4
},
"gate_up_a": {
"BLOCK_SIZE_K": 128,
"BLOCK_SIZE_N": 32,
"GROUP_SIZE_M": 8,
"num_stages": 3,
"num_warps": 4
},
"gate_up_b": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_N": 256,
"GROUP_SIZE_M": 4,
"num_stages": 3,
"num_warps": 8
},
"routing_block_size": 16,
"shared_one_pass": {
"BLOCK_SIZE_H": 128,
"num_stages": 3,
"num_warps": 4
}
}
}
]
},
{
"name": "fallback.decode",
"phase": "decode",
"base_gemm_rows": "expert_major",
"plan": {
"gate_up_a_family": "grouped",
"down_a_family": "grouped",
"gate_up_b_family": "grouped",
"down_b_family": "grouped",
"act_family": "materialized",
"finalize_family": "materialized",
"down_overlap": "down_a_b",
"gate_up_overlap": "gate_up_a_b"
},
"tiles": [
{
"sites": {
"b_activation": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_W": 64,
"GROUP_SIZE_M": 8,
"num_stages": 3,
"num_warps": 4
},
"down_a": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_N": 32,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"down_b": {
"BLOCK_SIZE_K": 16,
"BLOCK_SIZE_M": 16,
"BLOCK_SIZE_N": 128,
"GROUP_SIZE_M": 1,
"num_stages": 2,
"num_warps": 4
},
"gate_up_a": {
"BLOCK_SIZE_K": 256,
"BLOCK_SIZE_N": 32,
"GROUP_SIZE_M": 8,
"num_stages": 4,
"num_warps": 8
},
"gate_up_b": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_M": 16,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"routing_block_size": 16
}
}
]
},
{
"name": "fallback.prefill.per_expert",
"layout": "per_expert",
"phase": "prefill",
"base_gemm_rows": "route_major",
"plan": {
"gate_up_a_family": "grouped",
"down_a_family": "grouped",
"down_b_family": "grouped",
"act_family": "b_activation",
"finalize_family": "materialized",
"down_b_into_base": true
},
"tiles": [
{
"sites": {
"b_activation": {
"BLOCK_SIZE_K": 16,
"BLOCK_SIZE_W": 64,
"GROUP_SIZE_M": 8,
"num_stages": 3,
"num_warps": 8
},
"down_a": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_N": 32,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"down_b": {
"BLOCK_SIZE_K": 16,
"BLOCK_SIZE_M": 32,
"BLOCK_SIZE_N": 128,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"gate_up_a": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_N": 16,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 2
},
"gate_up_b": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_M": 32,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"routing_block_size": 32
}
}
]
},
{
"name": "fallback.prefill.shared",
"layout": "shared",
"phase": "prefill",
"base_gemm_rows": "route_major",
"plan": {
"gate_up_a_family": "token_grouped",
"down_a_family": "grouped",
"act_family": "b_activation",
"finalize_family": "shared_token_delta",
"route_builder": "parallel_shared_outer"
},
"tiles": [
{
"sites": {
"b_activation": {
"BLOCK_SIZE_K": 16,
"BLOCK_SIZE_W": 64,
"GROUP_SIZE_M": 8,
"num_stages": 3,
"num_warps": 8
},
"down_a": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_N": 32,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"down_b": {
"BLOCK_SIZE_K": 16,
"BLOCK_SIZE_M": 32,
"BLOCK_SIZE_N": 128,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"gate_up_a": {
"BLOCK_SIZE_K": 64,
"BLOCK_SIZE_N": 16,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 2
},
"gate_up_b": {
"BLOCK_SIZE_K": 32,
"BLOCK_SIZE_M": 32,
"BLOCK_SIZE_N": 64,
"GROUP_SIZE_M": 8,
"num_stages": 2,
"num_warps": 4
},
"routing_block_size": 32,
"shared_token_delta": {
"reduce": {
"BLOCK_SIZE_T": 32,
"num_stages": 2,
"num_warps": 4
},
"tail": {
"BLOCK_SIZE_H": 1024,
"num_stages": 2,
"num_warps": 8
}
}
}
}
]
}
]
}
+759
View File
@@ -0,0 +1,759 @@
"""Select and validate MoE LoRA plans and their launch tiles."""
from __future__ import annotations
import json
import logging
import os
from dataclasses import dataclass, field
from enum import Enum
from functools import cache
from typing import Any, Literal, Mapping
import pydantic
from pydantic.dataclasses import dataclass as pydantic_dataclass
from sglang.kernels.ops.lora.moe.activation import ActivationFn
from sglang.srt.lora.utils import Phase
logger = logging.getLogger(__name__)
_STRICT = pydantic.ConfigDict(strict=True, extra="forbid")
class Site(str, Enum):
GATE_UP = "gate_up"
DOWN = "down"
class BridgeLayout(str, Enum):
PAIR_MAJOR = "pair_major"
TOKEN_MAJOR = "token_major"
class RouteRequirement(str, Enum):
RAW_PER_EXPERT = "raw_per_expert"
RAW_SHARED_OUTER = "raw_shared_outer"
ALIGNED_PER_EXPERT = "aligned_per_expert"
ALIGNED_SHARED_OUTER = "aligned_shared_outer"
SHARED_TOKEN_PLAN = "shared_token_plan"
class RouteBuilderFamily(str, Enum):
STANDARD = "standard"
# Build the shared route on the workspace side stream.
PARALLEL_SHARED_OUTER = "parallel_shared_outer"
class AFamily(str, Enum):
GROUPED = "grouped"
PER_ROW = "per_row"
TOKEN_GROUPED = "token_grouped"
# Shared gate/up A writes one token-domain bridge plane per adapter slot.
TOKEN_DENSE = "token_dense"
class BFamily(str, Enum):
GROUPED = "grouped"
PER_ROW = "per_row"
class ActFamily(str, Enum):
MATERIALIZED = "materialized"
B_ACTIVATION = "b_activation"
class FinalizeFamily(str, Enum):
MATERIALIZED = "materialized"
# Reduce in rank space before expanding the shared B once per token.
SHARED_TOKEN_DELTA = "shared_token_delta"
# Fuse the rank reduction, B expansion, and base reduction.
SHARED_ONE_PASS = "shared_one_pass"
class GateUpOverlap(str, Enum):
NONE = "none"
GATE_UP_A = "gate_up_a"
GATE_UP_A_B = "gate_up_a_b"
class DownOverlap(str, Enum):
NONE = "none"
DOWN_A = "down_a"
DOWN_A_B = "down_a_b"
def _raw_requirement(is_shared_outer: bool) -> RouteRequirement:
if is_shared_outer:
return RouteRequirement.RAW_SHARED_OUTER
return RouteRequirement.RAW_PER_EXPERT
def _aligned_requirement(is_shared_outer: bool) -> RouteRequirement:
if is_shared_outer:
return RouteRequirement.ALIGNED_SHARED_OUTER
return RouteRequirement.ALIGNED_PER_EXPERT
def _check_down_bridge_layout(site: Site, layout: BridgeLayout) -> None:
if site is Site.DOWN and layout is BridgeLayout.TOKEN_MAJOR:
raise ValueError(
"the down bridge is inherently pair-major: each routed expert "
"produces a different activation"
)
@pydantic_dataclass(frozen=True, slots=True, config=_STRICT)
class ASpec:
site: Site
family: AFamily
is_shared_outer: bool = False
output_layout: BridgeLayout = BridgeLayout.PAIR_MAJOR
def __post_init__(self) -> None:
_check_down_bridge_layout(self.site, self.output_layout)
if self.family in (AFamily.GROUPED, AFamily.PER_ROW):
if self.output_layout is not BridgeLayout.PAIR_MAJOR:
raise ValueError(f"{self.family.value} A writes a pair-major bridge")
else:
if self.site is not Site.GATE_UP:
raise ValueError(f"{self.family.value} is a shared gate/up-A family")
if not self.is_shared_outer:
raise ValueError(
f"{self.family.value} requires shared-outer A ownership"
)
if self.output_layout is not BridgeLayout.TOKEN_MAJOR:
raise ValueError(f"{self.family.value} writes a token-major bridge")
def route_requirements(self) -> frozenset[RouteRequirement]:
if self.family in (
AFamily.PER_ROW,
AFamily.TOKEN_DENSE,
):
return frozenset((_raw_requirement(self.is_shared_outer),))
if self.family is AFamily.TOKEN_GROUPED:
return frozenset((RouteRequirement.SHARED_TOKEN_PLAN,))
return frozenset((_aligned_requirement(self.is_shared_outer),))
@pydantic_dataclass(frozen=True, slots=True, config=_STRICT)
class BSpec:
site: Site
family: BFamily
is_shared_outer: bool = False
input_layout: BridgeLayout = BridgeLayout.PAIR_MAJOR
def __post_init__(self) -> None:
_check_down_bridge_layout(self.site, self.input_layout)
def route_requirements(self) -> frozenset[RouteRequirement]:
if self.family is BFamily.PER_ROW:
return frozenset((_raw_requirement(self.is_shared_outer),))
return frozenset((_aligned_requirement(self.is_shared_outer),))
@pydantic_dataclass(frozen=True, slots=True, config=_STRICT)
class ActSpec:
"""B_ACTIVATION owns gate/up B and consumes the A bridge."""
family: ActFamily
activation: ActivationFn
def route_requirements(self) -> frozenset[RouteRequirement]:
if self.family is not ActFamily.B_ACTIVATION:
return frozenset()
return frozenset((_aligned_requirement(False),))
@pydantic_dataclass(frozen=True, slots=True, config=_STRICT)
class FinalizeSpec:
family: FinalizeFamily
is_shared_outer: bool = False
def __post_init__(self) -> None:
if (
self.family
in (FinalizeFamily.SHARED_TOKEN_DELTA, FinalizeFamily.SHARED_ONE_PASS)
and not self.is_shared_outer
):
raise ValueError(
f"{self.family.value} requires shared-outer down-B ownership"
)
def route_requirements(self) -> frozenset[RouteRequirement]:
if self.family is FinalizeFamily.MATERIALIZED:
return frozenset()
if self.family is FinalizeFamily.SHARED_TOKEN_DELTA:
return frozenset(
(
_raw_requirement(self.is_shared_outer),
RouteRequirement.SHARED_TOKEN_PLAN,
)
)
return frozenset((_raw_requirement(self.is_shared_outer),))
@pydantic_dataclass(frozen=True, slots=True, kw_only=True, config=_STRICT)
class MoePlan:
gate_up_a: ASpec
gate_up_b: BSpec | None = None
act: ActSpec
down_a: ASpec
down_b: BSpec | None = None
finalize: FinalizeSpec
gate_up_overlap: GateUpOverlap = GateUpOverlap.NONE
down_overlap: DownOverlap = DownOverlap.NONE
down_b_into_base: bool = False
route_builder: RouteBuilderFamily = RouteBuilderFamily.STANDARD
def __post_init__(self) -> None:
if self.gate_up_a.site is not Site.GATE_UP:
raise ValueError("gate_up_a must describe the gate/up site")
if self.gate_up_b is not None and self.gate_up_b.site is not Site.GATE_UP:
raise ValueError("gate_up_b must describe the gate/up site")
if self.down_a.site is not Site.DOWN:
raise ValueError("down_a must describe the down site")
if self.down_b is not None and self.down_b.site is not Site.DOWN:
raise ValueError("down_b must describe the down site")
gate_up_b_consumed = self.act.family is ActFamily.B_ACTIVATION
if gate_up_b_consumed == (self.gate_up_b is not None):
raise ValueError(
"gate/up B must have exactly one owner: standalone gate_up_b or the act stage"
)
down_b_consumed = self.finalize.family is not FinalizeFamily.MATERIALIZED
if down_b_consumed == (self.down_b is not None):
raise ValueError(
"down B must have exactly one owner: standalone down_b or finalize"
)
# Fused consumers inherit A's layout; standalone B must match it.
if (
self.gate_up_b is not None
and self.gate_up_a.output_layout is not self.gate_up_b.input_layout
):
raise ValueError(
"gate/up A output layout must match the gate/up B input layout"
)
if (
self.down_b is not None
and self.down_a.output_layout is not self.down_b.input_layout
):
raise ValueError("down A output layout must match the down B input layout")
if self.gate_up_a.family is AFamily.TOKEN_DENSE and (
self.gate_up_b is None or self.gate_up_b.family is not BFamily.PER_ROW
):
raise ValueError(
"token_dense A writes one bridge plane per adapter slot; only a "
"standalone per_row gate/up B selects planes"
)
if self.gate_up_overlap is GateUpOverlap.GATE_UP_A_B and self.gate_up_b is None:
raise ValueError(
"gate/up-A+B overlap requires standalone gate/up B; the act stage owns it"
)
if self.down_overlap is DownOverlap.DOWN_A_B and self.down_b is None:
raise ValueError(
f"{self.down_overlap.value} overlap requires standalone down B"
)
# In-place B must wait for the base down GEMM to finish writing.
if self.down_b_into_base and not (
self.down_b is not None
and self.down_overlap in (DownOverlap.NONE, DownOverlap.DOWN_A)
):
raise ValueError(
"down-B into-base requires a standalone down-B stage and no "
"late overlap window (it read-modify-writes the base down "
"output)"
)
def route_requirements(self) -> frozenset[RouteRequirement]:
requirements: set[RouteRequirement] = set()
for stage in (
self.gate_up_a,
self.gate_up_b,
self.act,
self.down_a,
self.finalize,
):
if stage is not None:
requirements.update(stage.route_requirements())
if self.down_b is not None:
# The in-place B kernel replaces the selected family with aligned rows.
if self.down_b_into_base:
requirements.add(_aligned_requirement(self.down_b.is_shared_outer))
else:
requirements.update(self.down_b.route_requirements())
return frozenset(requirements)
def _a_default() -> dict[str, int]:
return {
"BLOCK_SIZE_N": 32,
"BLOCK_SIZE_K": 64,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 2,
}
def _b_default() -> dict[str, int]:
return {
"BLOCK_SIZE_M": 16,
"BLOCK_SIZE_N": 64,
"BLOCK_SIZE_K": 32,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 2,
}
def _b_act_default() -> dict[str, int]:
return {
"BLOCK_SIZE_W": 64,
"BLOCK_SIZE_K": 32,
"GROUP_SIZE_M": 8,
"num_warps": 4,
"num_stages": 3,
}
def _shared_token_delta_default() -> dict[str, dict[str, int]]:
return {
"reduce": {"BLOCK_SIZE_T": 32, "num_warps": 4, "num_stages": 2},
"tail": {"BLOCK_SIZE_H": 128, "num_warps": 4, "num_stages": 3},
}
def _shared_one_pass_default() -> dict[str, int]:
return {"BLOCK_SIZE_H": 128, "num_warps": 4, "num_stages": 3}
def _is_power_of_two(value: int) -> bool:
return value > 0 and value & (value - 1) == 0
def _validate_flat_config(
name: str, config: Mapping[str, int], allowed: frozenset[str]
) -> None:
if not config:
raise ValueError(f"{name} must be a non-empty launch-config mapping")
unknown = set(config) - allowed
if unknown:
raise ValueError(f"{name} has unknown launch keys: {sorted(unknown)}")
required = allowed - {"GROUP_SIZE_M", "BLOCK_SIZE_M", "SPLIT_K"}
missing = required - set(config)
if missing:
raise ValueError(f"{name} is missing launch keys: {sorted(missing)}")
for key, value in config.items():
if value <= 0:
raise ValueError(f"{name}.{key} must be positive")
if (
key.startswith("BLOCK_SIZE_") or key in ("num_warps", "SPLIT_K")
) and not _is_power_of_two(value):
raise ValueError(f"{name}.{key} must be a power of two")
_GEMM_LAUNCH_KEYS = frozenset(
("BLOCK_SIZE_N", "BLOCK_SIZE_K", "GROUP_SIZE_M", "num_warps", "num_stages")
)
@pydantic_dataclass(frozen=True, slots=True, kw_only=True, config=_STRICT)
class MoeLoraLaunchConfig:
"""Per-site Triton launch configs of one plan row."""
# Shared row tile for aligned LoRA kernels; independent of base-GEMM tiles.
routing_block_size: int = 16
gate_up_a: dict[str, int] = field(default_factory=_a_default)
gate_up_b: dict[str, int] = field(default_factory=_b_default)
down_a: dict[str, int] = field(default_factory=_a_default)
down_b: dict[str, int] = field(default_factory=_b_default)
b_activation: dict[str, int] = field(default_factory=_b_act_default)
shared_token_delta: dict[str, dict[str, int]] = field(
default_factory=_shared_token_delta_default
)
shared_one_pass: dict[str, int] = field(default_factory=_shared_one_pass_default)
def __post_init__(self) -> None:
# tl.dot requires a power-of-two row tile of at least 16.
if (
not _is_power_of_two(self.routing_block_size)
or self.routing_block_size < 16
):
raise ValueError("routing_block_size must be a power of two >= 16")
# MoE consumes the combined shrink output, so split-K is serial.
for name in ("gate_up_a", "down_a"):
_validate_flat_config(
name, getattr(self, name), _GEMM_LAUNCH_KEYS | {"SPLIT_K"}
)
for name in ("gate_up_b", "down_b"):
_validate_flat_config(
name, getattr(self, name), _GEMM_LAUNCH_KEYS | {"BLOCK_SIZE_M"}
)
_validate_flat_config(
"b_activation",
self.b_activation,
(_GEMM_LAUNCH_KEYS - {"BLOCK_SIZE_N"}) | {"BLOCK_SIZE_W"},
)
# Grouped B takes its row tile from the route, not its config section.
for name in ("gate_up_b", "down_b"):
declared = getattr(self, name).get("BLOCK_SIZE_M")
if declared is not None and int(declared) != self.routing_block_size:
raise ValueError(
f"{name} declares BLOCK_SIZE_M={declared}, but the aligned "
f"route uses routing_block_size={self.routing_block_size}"
)
if set(self.shared_token_delta) != {"reduce", "tail"}:
raise ValueError(
"shared_token_delta must contain exactly 'reduce' and 'tail'"
)
for name, tile_key in (("reduce", "BLOCK_SIZE_T"), ("tail", "BLOCK_SIZE_H")):
_validate_flat_config(
f"shared_token_delta.{name}",
self.shared_token_delta[name],
frozenset((tile_key, "num_warps", "num_stages")),
)
_validate_flat_config(
"shared_one_pass",
self.shared_one_pass,
frozenset(("BLOCK_SIZE_H", "num_warps", "num_stages")),
)
def for_a(self, site: Site) -> Mapping[str, int]:
return self.gate_up_a if site is Site.GATE_UP else self.down_a
def for_b(self, site: Site) -> Mapping[str, int]:
return self.gate_up_b if site is Site.GATE_UP else self.down_b
def for_act(self, family: ActFamily) -> Mapping[str, int]:
if family is ActFamily.B_ACTIVATION:
return self.b_activation
raise ValueError(f"{family.value} has no fused-act launch config")
class TileTable:
"""Launch configs of one bound plan row, picked per forward by token count."""
def __init__(self, rules: list[tuple[int, MoeLoraLaunchConfig]]) -> None:
self._rules = rules
def config_for(self, num_tokens: int) -> MoeLoraLaunchConfig:
for bound, config in self._rules:
if num_tokens <= bound:
return config
return self._rules[-1][1]
def _validate_plan_launch_config(plan: MoePlan, config: MoeLoraLaunchConfig) -> None:
dot_sites = {}
for name, spec in (("gate_up_a", plan.gate_up_a), ("down_a", plan.down_a)):
if spec.family in (AFamily.GROUPED, AFamily.TOKEN_GROUPED):
dot_sites[name] = ("BLOCK_SIZE_N", "BLOCK_SIZE_K")
if (
spec.family is AFamily.TOKEN_GROUPED
and getattr(config, name).get("SPLIT_K", 1) > 1
):
raise ValueError(f"{name} token_grouped does not provide split-K scratch")
for name, spec in (("gate_up_b", plan.gate_up_b), ("down_b", plan.down_b)):
if spec is not None and spec.family is BFamily.GROUPED:
dot_sites[name] = ("BLOCK_SIZE_N",)
if plan.act.family is ActFamily.B_ACTIVATION:
dot_sites["b_activation"] = ("BLOCK_SIZE_W", "BLOCK_SIZE_K")
if plan.down_b_into_base:
dot_sites["down_b"] = ("BLOCK_SIZE_N", "BLOCK_SIZE_K")
elif plan.finalize.family is FinalizeFamily.SHARED_TOKEN_DELTA:
dot_sites["down_b"] = ("BLOCK_SIZE_N",)
for name, tile_keys in sorted(dot_sites.items()):
tiles = getattr(config, name)
if "GROUP_SIZE_M" not in tiles:
raise ValueError(f"{name} requires GROUP_SIZE_M for its selected consumer")
for key in tile_keys:
if tiles[key] < 16:
raise ValueError(
f"{name}.{key} must be at least 16 for its selected consumer"
)
class _PlanSpecModel(pydantic.BaseModel):
model_config = pydantic.ConfigDict(extra="forbid")
gate_up_a_family: AFamily = AFamily.GROUPED
down_a_family: AFamily = AFamily.GROUPED
gate_up_b_family: BFamily = BFamily.GROUPED
down_b_family: BFamily = BFamily.GROUPED
act_family: ActFamily = ActFamily.MATERIALIZED
finalize_family: FinalizeFamily = FinalizeFamily.MATERIALIZED
gate_up_overlap: GateUpOverlap = GateUpOverlap.NONE
down_overlap: DownOverlap = DownOverlap.NONE
route_builder: RouteBuilderFamily = RouteBuilderFamily.STANDARD
down_b_into_base: bool = False
class _TileRuleModel(pydantic.BaseModel):
model_config = pydantic.ConfigDict(extra="forbid")
max_rank: int | None = pydantic.Field(default=None, gt=0)
max_tokens: int | None = pydantic.Field(default=None, gt=0)
sites: dict[str, Any] = pydantic.Field(default_factory=dict)
class _PlanRowModel(pydantic.BaseModel):
model_config = pydantic.ConfigDict(extra="forbid")
name: str
layout: Literal["per_expert", "shared"] | None = None
phase: Phase | None = None
max_rank: int | None = None
min_local_experts: int | None = None
max_local_experts: int | None = None
quant: list[str] | None = None
base_gemm_rows: Literal["expert_major", "route_major"]
plan: _PlanSpecModel
# Rank rules precede token buckets; an unbounded rule ends the ladder.
# Tiles are required. Use {"sites": {}} to select defaults explicitly.
tiles: list[_TileRuleModel] = pydantic.Field(min_length=1)
class _DomainModel(pydantic.BaseModel):
"""Geometry covered by the tuned scenario rows."""
model_config = pydantic.ConfigDict(extra="forbid")
max_hidden: int | None = None
max_local_experts: int | None = None
def admits(self, *, hidden_size: int, num_local_experts: int) -> bool:
return (self.max_hidden is None or hidden_size <= self.max_hidden) and (
self.max_local_experts is None
or num_local_experts <= self.max_local_experts
)
class _PlansFileModel(pydantic.BaseModel):
model_config = pydantic.ConfigDict(extra="forbid")
domain: _DomainModel = pydantic.Field(default_factory=_DomainModel)
scenarios: list[_PlanRowModel] = pydantic.Field(default_factory=list)
fallback: list[_PlanRowModel]
_CONFIG_DIR = os.path.join(os.path.dirname(__file__), "configs")
def _validate_tile_ladder(rules: list[_TileRuleModel]) -> None:
ranks = {1} | {rule.max_rank + 1 for rule in rules if rule.max_rank is not None}
reachable = set()
for rank in ranks:
previous = 0
for index, rule in enumerate(rules):
if rule.max_rank is not None and rank > rule.max_rank:
continue
reachable.add(index)
if rule.max_tokens is None:
break
if rule.max_tokens <= previous:
raise ValueError(f"tile token bounds must increase for rank {rank}")
previous = rule.max_tokens
if len(reachable) != len(rules):
raise ValueError("tile rules must not be shadowed for every rank")
def _read_table(name: str) -> dict | None:
from sglang.srt.environ import envs
override_dir = envs.SGLANG_LORA_MOE_CONFIG_DIR.get()
for directory in filter(None, (override_dir, _CONFIG_DIR)):
path = os.path.join(directory, name)
if os.path.isfile(path):
if directory == override_dir:
logger.info(
"MoE LoRA table %r loaded from override dir %s", name, directory
)
with open(path) as handle:
return json.load(handle)
return None
@cache
def _load_plans(architecture: str) -> _PlansFileModel:
raw = _read_table(f"{architecture}.plans.json")
if raw is None:
logger.warning(
"no MoE LoRA plan table for architecture %s; serving the "
"conservative default plans",
architecture,
)
raw = _read_table("default.plans.json")
if raw is None:
raise RuntimeError("MoE LoRA plan tables are missing from the package")
table = _PlansFileModel.model_validate(raw)
for row in (*table.scenarios, *table.fallback):
layouts = (row.layout,) if row.layout is not None else ("per_expert", "shared")
plans = [
_build_plan(
row.plan,
activation=ActivationFn.SILU,
is_shared_outer=layout == "shared",
)
for layout in layouts
]
for rule in row.tiles:
config = MoeLoraLaunchConfig(**rule.sites)
for plan in plans:
_validate_plan_launch_config(plan, config)
_validate_tile_ladder(row.tiles)
return table
@dataclass(frozen=True, slots=True)
class SelectedPlan:
name: str
base_gemm_rows: str
plan: MoePlan
tiles: TileTable
def _tile_table(rules: list[_TileRuleModel], physical_rank: int) -> TileTable:
"""Drop the rules the bound rank excludes; keep the token bounds for each forward."""
resolved: list[tuple[int, MoeLoraLaunchConfig]] = []
for rule in rules:
if rule.max_rank is not None and physical_rank > rule.max_rank:
continue
bound = rule.max_tokens if rule.max_tokens is not None else 1 << 30
resolved.append((bound, MoeLoraLaunchConfig(**rule.sites)))
if rule.max_tokens is None:
break # An unbounded rule shadows all later rules.
if not resolved:
resolved.append((1 << 30, MoeLoraLaunchConfig()))
return TileTable(resolved)
def _build_plan(
spec: _PlanSpecModel,
*,
activation: ActivationFn,
is_shared_outer: bool,
) -> MoePlan:
gate_up_a_family = spec.gate_up_a_family
gate_up_layout = (
BridgeLayout.TOKEN_MAJOR
if gate_up_a_family in (AFamily.TOKEN_GROUPED, AFamily.TOKEN_DENSE)
else BridgeLayout.PAIR_MAJOR
)
act_family = spec.act_family
finalize_family = spec.finalize_family
consumes_gate_up_b = act_family is ActFamily.B_ACTIVATION
consumes_down_b = finalize_family is not FinalizeFamily.MATERIALIZED
plan = MoePlan(
gate_up_a=ASpec(
Site.GATE_UP, gate_up_a_family, is_shared_outer, gate_up_layout
),
gate_up_b=(
None
if consumes_gate_up_b
else BSpec(
Site.GATE_UP,
spec.gate_up_b_family,
False,
gate_up_layout,
)
),
act=ActSpec(act_family, activation),
down_a=ASpec(
Site.DOWN,
spec.down_a_family,
False,
BridgeLayout.PAIR_MAJOR,
),
down_b=(
None
if consumes_down_b
else BSpec(
Site.DOWN,
spec.down_b_family,
is_shared_outer,
BridgeLayout.PAIR_MAJOR,
)
),
finalize=FinalizeSpec(
finalize_family, is_shared_outer if consumes_down_b else False
),
gate_up_overlap=spec.gate_up_overlap,
down_overlap=spec.down_overlap,
route_builder=spec.route_builder,
down_b_into_base=spec.down_b_into_base,
)
return plan
@cache
def _warn_out_of_domain(
architecture: str, hidden_size: int, num_local_experts: int
) -> None:
logger.warning(
"MoE LoRA geometry (hidden=%d, local_experts=%d) is outside the tuned "
"domain of table %r; serving the fallback rows",
hidden_size,
num_local_experts,
architecture,
)
def resolve_plans(
*,
architecture: str,
is_shared_outer: bool,
physical_rank: int,
activation: ActivationFn,
hidden_size: int,
num_local_experts: int,
quant_family: str,
) -> dict[Phase, SelectedPlan]:
table = _load_plans(architecture)
layout_name = "shared" if is_shared_outer else "per_expert"
in_domain = table.domain.admits(
hidden_size=hidden_size, num_local_experts=num_local_experts
)
rows = table.scenarios if in_domain else []
if not in_domain:
_warn_out_of_domain(architecture, hidden_size, num_local_experts)
selected: dict[Phase, SelectedPlan] = {}
for phase in Phase:
# Earlier rows take precedence, including wildcard rows.
row = next(
(
candidate
for candidate in (*rows, *table.fallback)
if candidate.layout in (None, layout_name)
and candidate.phase in (None, phase)
and (candidate.max_rank is None or physical_rank <= candidate.max_rank)
and (
candidate.min_local_experts is None
or num_local_experts >= candidate.min_local_experts
)
and (
candidate.max_local_experts is None
or num_local_experts <= candidate.max_local_experts
)
and (candidate.quant is None or quant_family in candidate.quant)
),
None,
)
if row is None:
raise RuntimeError(
f"no MoE LoRA plan row matches ({layout_name}, {phase.value}) "
f"on {architecture}"
)
selected[phase] = SelectedPlan(
name=row.name,
base_gemm_rows=row.base_gemm_rows,
plan=_build_plan(
row.plan,
activation=activation,
is_shared_outer=is_shared_outer,
),
tiles=_tile_table(row.tiles, physical_rank),
)
return selected
+135
View File
@@ -0,0 +1,135 @@
from __future__ import annotations
from typing import TYPE_CHECKING
import msgspec
import torch
if TYPE_CHECKING:
from sglang.srt.layers.moe.fused_moe_triton.layer import FusedMoE
class MoeLoraBf16QuantInfo(msgspec.Struct, kw_only=True):
"""W13: [E, S*I, H], gate first when S=2. W2: [E, H, I]."""
w13_weight: torch.Tensor
w2_weight: torch.Tensor
num_local_experts: int
intermediate_size: int
hidden_size: int
@classmethod
def from_layer(cls, base_layer: FusedMoE) -> MoeLoraBf16QuantInfo:
return cls(
w13_weight=base_layer.w13_weight,
w2_weight=base_layer.w2_weight,
num_local_experts=int(base_layer.num_local_experts),
intermediate_size=int(base_layer.w2_weight.shape[2]),
hidden_size=int(base_layer.w2_weight.shape[1]),
)
class MoeLoraFp8QuantInfo(msgspec.Struct, kw_only=True):
"""FP8 weights in standard layout, with FP32 inverse block scales."""
w13_weight: torch.Tensor # [E_local, S * I, H] float8_e4m3fn
w13_scale: torch.Tensor # [E_local, ceil(S*I/block_n), ceil(H/block_k)]
w2_weight: torch.Tensor # [E_local, H, I] float8_e4m3fn
w2_scale: torch.Tensor # [E_local, ceil(H/block_n), ceil(I/block_k)]
block_shape: tuple[int, int]
num_local_experts: int
intermediate_size: int
hidden_size: int
@classmethod
def from_layer(cls, base_layer: FusedMoE) -> MoeLoraFp8QuantInfo:
quant_info = cls(
w13_weight=base_layer.w13_weight,
w13_scale=base_layer.w13_weight_scale_inv,
w2_weight=base_layer.w2_weight,
w2_scale=base_layer.w2_weight_scale_inv,
block_shape=tuple(base_layer.quant_method.weight_block_size),
num_local_experts=int(base_layer.num_local_experts),
intermediate_size=int(base_layer.w2_weight.shape[2]),
hidden_size=int(base_layer.w2_weight.shape[1]),
)
_admit_fp8_block_weights(quant_info)
return quant_info
def _admit_fp8_block_weights(quant_info: MoeLoraFp8QuantInfo) -> None:
"""Validate 128x128 weight blocks and scales once when binding weights."""
if tuple(quant_info.block_shape) != (128, 128):
raise NotImplementedError(
f"MoE LoRA FP8 supports [128, 128] weight blocks, got "
f"{list(quant_info.block_shape)}"
)
for name, value in (
("hidden_size", quant_info.hidden_size),
("intermediate_size", quant_info.intermediate_size),
):
if value % 128:
raise NotImplementedError(
f"MoE LoRA FP8 requires {name} % 128 == 0, got {value}"
)
for name, scale, rows, cols in (
(
"w13_scale",
quant_info.w13_scale,
quant_info.w13_weight.shape[1],
quant_info.hidden_size,
),
(
"w2_scale",
quant_info.w2_scale,
quant_info.hidden_size,
quant_info.intermediate_size,
),
):
expected = (quant_info.num_local_experts, -(-rows // 128), -(-cols // 128))
if scale.dtype != torch.float32 or tuple(scale.shape) != expected:
raise ValueError(
f"{name} must be fp32 {list(expected)}, got {scale.dtype} "
f"{tuple(scale.shape)}"
)
# Marlin's packed weights do not use the standard row-domain layout.
StandardLayoutQuantInfo = MoeLoraBf16QuantInfo | MoeLoraFp8QuantInfo
class MoeLoraNvFp4MarlinQuantInfo(msgspec.Struct, kw_only=True):
"""Prepared Marlin W4A16 for BF16 activations and global scales."""
w13_qweight: torch.Tensor
w2_qweight: torch.Tensor
w13_scales: torch.Tensor
w2_scales: torch.Tensor
w13_global_scale: torch.Tensor
w2_global_scale: torch.Tensor
num_local_experts: int
intermediate_size: int
hidden_size: int
gate_up_slices: int
@classmethod
def from_layer(cls, base_layer: FusedMoE) -> MoeLoraNvFp4MarlinQuantInfo:
if base_layer.params_dtype != torch.bfloat16:
raise NotImplementedError("NVFP4 MoE LoRA requires BF16 activations.")
for name in ("w13_weight", "w2_weight"):
if getattr(base_layer, name).dtype != torch.int32:
raise ValueError(
f"NVFP4 MoE LoRA requires already-prepared Marlin {name}."
)
return cls(
w13_qweight=base_layer.w13_weight,
w2_qweight=base_layer.w2_weight,
w13_scales=base_layer.w13_weight_scale,
w2_scales=base_layer.w2_weight_scale,
w13_global_scale=base_layer.w13_weight_scale_2,
w2_global_scale=base_layer.w2_weight_scale_2,
num_local_experts=int(base_layer.num_local_experts),
intermediate_size=int(base_layer.intermediate_size_per_partition),
hidden_size=int(base_layer.hidden_size),
gate_up_slices=2 if base_layer.moe_runner_config.is_gated else 1,
)
+132
View File
@@ -0,0 +1,132 @@
"""Build the route views required by a MoE LoRA plan."""
from __future__ import annotations
from dataclasses import dataclass
import torch
from sglang.kernels.ops.lora.common.route_view import RouteView, RouteViewKind
from sglang.kernels.ops.lora.common.routing import build_route
from sglang.srt.lora.moe.plan import (
MoePlan,
RouteBuilderFamily,
RouteRequirement,
)
from sglang.srt.lora.workspace import LoraWorkspace
@dataclass(frozen=True, slots=True)
class MoeLoraRoutes:
raw_per_expert: RouteView | None = None
raw_shared_outer: RouteView | None = None
aligned_per_expert: RouteView | None = None
aligned_shared_outer: RouteView | None = None
shared_token: RouteView | None = None
def raw(self, is_shared_outer: bool) -> RouteView:
if is_shared_outer:
return self._require(self.raw_shared_outer, "raw_shared_outer")
return self._require(self.raw_per_expert, "raw_per_expert")
def aligned(self, is_shared_outer: bool) -> RouteView:
if is_shared_outer:
return self._require(self.aligned_shared_outer, "aligned_shared_outer")
return self._require(self.aligned_per_expert, "aligned_per_expert")
@staticmethod
def _require(route: RouteView | None, field: str) -> RouteView:
if route is None:
raise ValueError(f"the execution plan did not request {field}")
return route
def build_moe_routes(
plan: MoePlan,
*,
topk_ids: torch.Tensor,
token_lora_mapping: torch.Tensor,
num_local_experts: int,
max_loras: int,
block_size: int,
workspace: LoraWorkspace,
) -> MoeLoraRoutes:
requirements = plan.route_requirements()
values: dict[str, RouteView] = {}
if RouteRequirement.RAW_PER_EXPERT in requirements:
values["raw_per_expert"] = build_route(
token_lora_mapping,
group_ids=topk_ids,
groups_per_slot=num_local_experts,
max_loras=max_loras,
block_size=block_size,
view=RouteViewKind.RAW,
)
if RouteRequirement.RAW_SHARED_OUTER in requirements:
values["raw_shared_outer"] = build_route(
token_lora_mapping,
group_ids=topk_ids,
groups_per_slot=1,
max_loras=max_loras,
block_size=block_size,
view=RouteViewKind.RAW,
)
def _build_per_expert() -> RouteView:
return build_route(
token_lora_mapping,
group_ids=topk_ids,
groups_per_slot=num_local_experts,
max_loras=max_loras,
block_size=block_size,
view=RouteViewKind.ALIGNED,
workspace=workspace,
tensor_prefix="route:aligned_per_expert",
)
def _build_shared() -> None:
values["aligned_shared_outer"] = build_route(
token_lora_mapping,
group_ids=topk_ids,
groups_per_slot=1,
max_loras=max_loras,
block_size=block_size,
view=RouteViewKind.ALIGNED,
workspace=workspace,
tensor_prefix="route:aligned_shared_outer",
)
if (
plan.route_builder is RouteBuilderFamily.PARALLEL_SHARED_OUTER
and RouteRequirement.ALIGNED_PER_EXPERT in requirements
and RouteRequirement.ALIGNED_SHARED_OUTER in requirements
):
values["aligned_per_expert"] = workspace.run_parallel(
name="route:parallel",
device=topk_ids.device,
compute=_build_per_expert,
side=_build_shared,
)
else:
if RouteRequirement.ALIGNED_PER_EXPERT in requirements:
values["aligned_per_expert"] = _build_per_expert()
if RouteRequirement.ALIGNED_SHARED_OUTER in requirements:
_build_shared()
if RouteRequirement.SHARED_TOKEN_PLAN in requirements:
def build_token_route():
# Shared experts use one row per token, grouped by adapter slot.
return build_route(
token_lora_mapping,
max_loras=max_loras,
block_size=block_size,
view=RouteViewKind.ALIGNED,
workspace=workspace,
tensor_prefix=f"route:shared_token:sorted:{block_size}",
)
values["shared_token"] = workspace.route(
token_lora_mapping, ("sorted", block_size, max_loras), build_token_route
)
return MoeLoraRoutes(**values)
+856
View File
@@ -0,0 +1,856 @@
"""Execute a bound MoE LoRA plan; base-only tokens use adapter slot -1."""
from __future__ import annotations
from collections.abc import Mapping
from dataclasses import dataclass
from typing import TYPE_CHECKING
import msgspec
import torch
import triton
from sglang.kernels.ops.lora.common.lora_a import (
grouped_lora_a,
per_row_lora_a,
shrink_column_tiles,
)
from sglang.kernels.ops.lora.moe.activation import ActivationFn
from sglang.kernels.ops.lora.moe.lora_b import invoke_down_b_into_base, run_lora_b
from sglang.srt.layers.moe.utils import get_moe_runner_backend
from sglang.srt.lora.moe.base_gemm_provider import select_provider_cls
from sglang.srt.lora.moe.base_gemm_provider.base import (
MoeBaseProvider,
)
from sglang.srt.lora.moe.plan import (
ActFamily,
AFamily,
ASpec,
BFamily,
BridgeLayout,
BSpec,
DownOverlap,
FinalizeFamily,
GateUpOverlap,
MoeLoraLaunchConfig,
MoePlan,
SelectedPlan,
Site,
resolve_plans,
)
from sglang.srt.lora.moe.routing import MoeLoraRoutes, build_moe_routes
from sglang.srt.lora.utils import Phase, architecture_for_capability
from sglang.srt.lora.workspace import LoraWorkspace
if TYPE_CHECKING:
from sglang.srt.layers.moe.fused_moe_triton.layer import FusedMoE
from sglang.srt.layers.moe.token_dispatcher.standard import (
StandardCombineInput,
StandardDispatchOutput,
)
@dataclass(slots=True)
class _LoraStageState:
rank: torch.Tensor | None = None
delta: torch.Tensor | None = None
class MoeLoraBatch(msgspec.Struct, kw_only=True):
gate_up_lora_a: torch.Tensor # [L_cap, E_f, slices*R_phys, H]
gate_up_lora_b: torch.Tensor # [L_cap, E_local, slices*I, R_phys]
down_lora_a: torch.Tensor # [L_cap, E_local, R_phys, I]
down_lora_b: torch.Tensor # [L_cap, E_f_down, H, R_phys]
token_lora_mapping: torch.Tensor # [T] int, adapter slot per token (-1 = base)
use_cuda_graph: bool = False # Graph-stable storage for either graph family.
is_prefill: bool = False # MoE plan phase; target verification uses decode.
@property
def max_loras(self) -> int:
return self.gate_up_lora_a.shape[0]
class MoeLoraRunner:
def __init__(
self,
*,
providers: Mapping[str, MoeBaseProvider],
top_k: int,
routed_scaling_factor: float | None,
activation: ActivationFn = ActivationFn.SILU,
is_gated: bool = True,
workspace: LoraWorkspace | None = None,
) -> None:
if not providers:
raise ValueError("a MoE LoRA runner needs at least one provider")
self.providers = dict(providers)
geometries = {
(
provider.hidden_size,
provider.intermediate_size,
provider.num_local_experts,
provider.gate_up_slices,
provider.contract.lora_delta_dtype,
)
for provider in self.providers.values()
}
if len(geometries) != 1:
raise ValueError("providers of one layer must share resident geometry")
(
self.hidden_size,
self.intermediate_size,
self.num_local_experts,
self.gate_up_slices,
self.lora_delta_dtype,
) = next(iter(geometries))
self.top_k = top_k
self.routed_scaling_factor = routed_scaling_factor
self.activation = activation
self.is_gated = is_gated
self.workspace = workspace if workspace is not None else LoraWorkspace()
self.plans: dict[Phase, SelectedPlan] = {}
@classmethod
def from_layer(
cls,
base_layer: FusedMoE,
*,
workspace: LoraWorkspace | None = None,
is_shared_outer: bool,
physical_rank: int,
) -> MoeLoraRunner:
family = cls._admit(base_layer)
weight_device = base_layer.w2_weight.device
if weight_device.type != "cuda":
raise NotImplementedError("MoE LoRA requires a CUDA layer")
major, _ = torch.cuda.get_device_capability(weight_device)
architecture = architecture_for_capability(major)
config = base_layer.moe_runner_config
activation = ActivationFn.parse(config.activation)
plans = resolve_plans(
architecture=architecture,
is_shared_outer=is_shared_outer,
physical_rank=physical_rank,
activation=activation,
hidden_size=int(base_layer.hidden_size),
num_local_experts=int(base_layer.num_local_experts),
quant_family=family,
)
# Shared finalizers hold the rank reduction in one tile, tested up to 256.
if physical_rank > 256 and any(
sel.plan.finalize.family is not FinalizeFamily.MATERIALIZED
for sel in plans.values()
):
raise ValueError(
f"the shared finalizes are capped at rank 256, got {physical_rank}"
)
vendor = get_moe_runner_backend().value.removeprefix("lora_")
runner = cls(
providers={
rows: cls._build_provider(
base_layer, base_gemm_rows=rows, vendor=vendor, family=family
)
for rows in dict.fromkeys(sel.base_gemm_rows for sel in plans.values())
},
top_k=int(config.top_k),
routed_scaling_factor=config.routed_scaling_factor,
activation=activation,
is_gated=bool(config.is_gated),
workspace=workspace,
)
for sel in plans.values():
runner.validate_plan(sel.plan, base_gemm_rows=sel.base_gemm_rows)
runner.plans = dict(plans)
return runner
@staticmethod
def _weight_family(base_layer: FusedMoE) -> str:
from sglang.srt.layers.quantization.unquant import UnquantizedFusedMoEMethod
quant_method = base_layer.quant_method
if isinstance(quant_method, UnquantizedFusedMoEMethod):
if (
base_layer.w13_weight.dtype != torch.bfloat16
or base_layer.w2_weight.dtype != torch.bfloat16
):
raise NotImplementedError(
"MoE LoRA on an unquantized layer requires resident BF16 weights"
)
return "bf16"
from sglang.srt.layers.quantization.fp8 import Fp8MoEMethod
if isinstance(quant_method, Fp8MoEMethod):
if base_layer.params_dtype != torch.bfloat16:
raise NotImplementedError("FP8 MoE LoRA requires BF16 activations.")
if not quant_method.block_quant or getattr(
quant_method, "use_mxfp8", False
):
raise NotImplementedError(
"MoE LoRA on FP8 requires 128-block weight quantization; "
"per-tensor and MXFP8 layers are unsupported"
)
if base_layer.w13_weight.dtype != torch.float8_e4m3fn:
raise NotImplementedError(
"MoE LoRA on FP8 requires resident float8_e4m3fn weights; "
"a Marlin-repacked FP8 layer is unsupported"
)
return "fp8"
from sglang.srt.layers.quantization.modelopt_quant import (
ModelOptNvFp4FusedMoEMethod,
)
if isinstance(quant_method, ModelOptNvFp4FusedMoEMethod):
return "nvfp4"
raise NotImplementedError(
"MoE LoRA supports unquantized BF16, 128-block FP8, and NVFP4 "
f"MoE; this layer's quant method is {type(quant_method).__name__}"
)
@classmethod
def _admit(cls, base_layer: FusedMoE) -> str:
from sglang.srt.layers.moe.token_dispatcher.standard import StandardDispatcher
family = cls._weight_family(base_layer)
if not isinstance(base_layer.dispatcher, StandardDispatcher):
raise NotImplementedError(
"MoE LoRA currently requires the Standard dispatcher"
)
major, minor = torch.cuda.get_device_capability()
if major not in (9, 10):
raise NotImplementedError(
f"MoE LoRA supports SM90 and SM100 only; this device is "
f"sm{major}{minor}. Its base GEMMs are WGMMA (SM90) and "
"tcgen05 (SM100) kernels, and no other architecture implements "
"either -- SM120 included, despite reporting a higher major."
)
if base_layer.dispatcher.skip_local_expert_mapping:
raise NotImplementedError(
"MoE LoRA requires EP-local expert IDs at the runner "
"boundary, but this dispatcher keeps global IDs"
)
if base_layer.should_fuse_routed_scaling_factor_in_topk:
raise NotImplementedError(
"MoE LoRA applies routed scaling exactly once in its own "
"finalize; this layer already folds it into the top-k weights. "
"Under a lora backend only ModelOpt NVFP4 does that, so those "
"experts need --moe-runner-backend lora_marlin"
)
if getattr(base_layer, "with_bias", False):
raise NotImplementedError(
"MoE LoRA providers carry no expert biases; this layer has them"
)
config = base_layer.moe_runner_config
# Membership by value: `str in Enum` raises TypeError before Python 3.12.
supported_activation = config.activation in {fn.value for fn in ActivationFn}
if (
not supported_activation
or config.gemm1_alpha is not None
or config.gemm1_clamp_limit is not None
or config.swiglu_limit is not None
or config.apply_router_weight_on_input
or config.no_combine
or config.num_fused_shared_experts
):
raise NotImplementedError(
"MoE LoRA supports SiLU or ReLU2 (gated or not) without "
"fused shared experts, with route weighting owned by finalize"
)
return family
@staticmethod
def _build_provider(
base_layer: FusedMoE,
*,
base_gemm_rows: str,
vendor: str,
family: str,
) -> MoeBaseProvider:
provider_cls = select_provider_cls(base_gemm_rows, family, vendor)
quant_info = provider_cls.contract.quant_info_cls.from_layer(base_layer)
return provider_cls(quant_info)
def validate_plan(self, plan: MoePlan, *, base_gemm_rows: str) -> None:
provider = self.providers[base_gemm_rows]
if plan.act.activation is not self.activation:
raise ValueError(
f"plan activation {plan.act.activation.value} does not match "
f"resident layer activation {self.activation.value}"
)
expected_slices = 2 if self.is_gated else 1
if provider.gate_up_slices != expected_slices:
raise ValueError(
f"provider exposes {provider.gate_up_slices} gate/up slices "
f"but is_gated={self.is_gated} needs {expected_slices}"
)
def run(
self,
dispatch_output: StandardDispatchOutput,
batch: MoeLoraBatch,
) -> StandardCombineInput:
from sglang.srt.layers.moe.token_dispatcher.standard import StandardCombineInput
from sglang.srt.layers.moe.topk import TopKOutputChecker
phase = Phase.PREFILL if batch.is_prefill else Phase.DECODE
selected = self.plans[phase]
launch_config = selected.tiles.config_for(
dispatch_output.hidden_states.shape[0]
)
provider = self.providers[selected.base_gemm_rows]
hidden_states = dispatch_output.hidden_states
topk_output = dispatch_output.topk_output
assert TopKOutputChecker.format_is_standard(topk_output)
topk_ids = topk_output.topk_ids
num_tokens = hidden_states.shape[0]
if (
batch.token_lora_mapping.ndim != 1
or batch.token_lora_mapping.shape[0] != num_tokens
):
raise RuntimeError(
"MoE LoRA token/adapter assignment does not match the MoE "
f"token domain: mapping has {batch.token_lora_mapping.shape[0]} rows "
f"but the runner received {num_tokens}. Gather/remap "
"assignments before MoE-DP execution."
)
self.workspace.begin_forward(
graph_mode=batch.use_cuda_graph, is_prefill_graph=batch.is_prefill
)
routes = build_moe_routes(
selected.plan,
topk_ids=topk_ids,
token_lora_mapping=batch.token_lora_mapping,
num_local_experts=self.num_local_experts,
max_loras=batch.max_loras,
block_size=launch_config.routing_block_size,
workspace=self.workspace,
)
gate_up, base_gemm_state, gateup_out = self._run_gate_up(
selected.plan,
launch_config,
provider,
routes,
hidden_states,
topk_ids,
batch,
num_tokens,
)
act_out, down_a_input, down_a_gather = self._run_act(
selected.plan,
launch_config,
provider,
routes,
base_gemm_state,
gateup_out,
gate_up,
topk_ids,
batch,
num_tokens,
)
output = self._allocate_output(
num_tokens=num_tokens,
dtype=hidden_states.dtype,
device=act_out.device,
)
down_out, down_rank, down_delta = self._run_down(
selected.plan,
launch_config,
provider,
routes,
base_gemm_state,
act_out,
down_a_input,
down_a_gather,
batch,
)
output = self._run_finalize(
selected.plan,
launch_config,
provider,
routes,
base_gemm_state,
output,
down_out,
down_rank,
down_delta,
topk_output,
batch,
num_tokens,
)
return StandardCombineInput(hidden_states=output)
def _run_a(
self,
launch_config: MoeLoraLaunchConfig,
spec: ASpec,
input: torch.Tensor,
weight: torch.Tensor,
routes: MoeLoraRoutes,
name: str,
*,
pair_to_row: torch.Tensor | None = None,
) -> torch.Tensor:
if spec.family is AFamily.TOKEN_GROUPED:
route = routes.shared_token
if route is None:
raise ValueError("shared token route was not constructed")
elif spec.family in (AFamily.PER_ROW, AFamily.TOKEN_DENSE):
route = routes.raw(spec.is_shared_outer)
else:
route = routes.aligned(spec.is_shared_outer)
num_output_rows = (
route.num_tokens
if spec.output_layout is BridgeLayout.TOKEN_MAJOR
else route.num_rows
)
shape: tuple[int, ...] = (num_output_rows, weight.shape[1])
if spec.family is AFamily.TOKEN_DENSE:
# One bridge plane per resident slot; per-row B indexes the planes.
shape = (route.max_loras, num_output_rows, weight.shape[1])
output = self.workspace.tensor(
f"{name}:output",
shape,
dtype=self.lora_delta_dtype,
device=input.device,
)
config = launch_config.for_a(spec.site)
pair_input = spec.site is Site.DOWN
match spec.family.value:
case "token_grouped":
grouped_lora_a(input, weight, output, route, config=config)
case "grouped":
partial = counters = None
split_k = int(config.get("SPLIT_K", 1))
if split_k > 1:
# Serial split-K: the last arrival sums the FP32 planes and
# resets its counter for the next graph replay.
partial = self.workspace.tensor(
f"{name}:partial",
(split_k, num_output_rows, weight.shape[1]),
dtype=torch.float32,
device=input.device,
)
tiles = (
triton.cdiv(route.sorted_pair_ids.numel(), route.block_size)
* shrink_column_tiles(
int(config["BLOCK_SIZE_N"]), weight.shape[1], 1, False
)[1]
)
counters = self.workspace.tensor(
f"{name}:splitk_counters",
(tiles,),
dtype=torch.int32,
device=input.device,
zero_on_first_allocation=True,
)
grouped_lora_a(
input,
weight,
output,
route,
config=config,
pair_input=pair_input,
pair_to_row=pair_to_row,
partial=partial,
counters=counters,
)
case "per_row":
per_row_lora_a(
input, weight, output, route, config=config, pair_input=pair_input
)
case "token_dense":
torch.matmul(
input,
weight.transpose(1, 2),
out=output.view(weight.shape[0], input.shape[0], weight.shape[1]),
)
case family:
raise NotImplementedError(f"no LoRA-A executor for {family!r}")
return output
def _run_b(
self,
launch_config: MoeLoraLaunchConfig,
spec: BSpec,
bridge: torch.Tensor,
weight: torch.Tensor,
destination: torch.Tensor,
routes: MoeLoraRoutes,
*,
slot_planes: bool = False,
) -> None:
route = (
routes.raw(spec.is_shared_outer)
if spec.family is BFamily.PER_ROW
else routes.aligned(spec.is_shared_outer)
)
config = launch_config.for_b(spec.site)
if spec.site is Site.GATE_UP:
width = weight.shape[1] // self.gate_up_slices
offsets = tuple(slice_id * width for slice_id in range(self.gate_up_slices))
else:
offsets = (0,)
run_lora_b(
spec,
bridge=bridge,
weight=weight,
destination=destination,
routing=route,
destination_offsets=offsets,
config=config,
pair_bridge=spec.input_layout is BridgeLayout.PAIR_MAJOR,
slot_planes=slot_planes,
)
def _run_gate_up(
self,
plan: MoePlan,
launch_config: MoeLoraLaunchConfig,
provider: MoeBaseProvider,
routes: MoeLoraRoutes,
hidden_states: torch.Tensor,
topk_ids: torch.Tensor,
batch: MoeLoraBatch,
num_tokens: int,
) -> tuple[_LoraStageState, object, torch.Tensor]:
state = _LoraStageState()
def gate_up_a() -> None:
state.rank = self._run_a(
launch_config,
plan.gate_up_a,
hidden_states,
batch.gate_up_lora_a.flatten(0, 1),
routes,
"gate_up_a",
)
def gate_up_b() -> None:
delta = self.workspace.tensor(
"gate_up_b:delta",
(
num_tokens * self.top_k,
self.gate_up_slices * self.intermediate_size,
),
dtype=self.lora_delta_dtype,
device=state.rank.device,
)
self._run_b(
launch_config,
plan.gate_up_b,
state.rank,
batch.gate_up_lora_b.flatten(0, 1),
delta,
routes,
slot_planes=plan.gate_up_a.family is AFamily.TOKEN_DENSE,
)
state.delta = delta
def base() -> tuple[object, torch.Tensor]:
base_gemm_state = provider.prepare(
hidden_states,
topk_ids,
self.top_k,
self.workspace,
)
gateup_out = self.workspace.tensor(
"base:gateup",
provider.gateup_out_shape(base_gemm_state),
dtype=provider.contract.gate_up_output_dtype,
device=hidden_states.device,
)
provider.gateup(base_gemm_state, gateup_out)
provider.release_prepared_inputs(base_gemm_state)
return base_gemm_state, gateup_out
if plan.gate_up_overlap is GateUpOverlap.NONE:
gate_up_a()
if plan.gate_up_b is not None:
gate_up_b()
base_gemm_state, gateup = base()
elif plan.gate_up_overlap is GateUpOverlap.GATE_UP_A:
base_gemm_state, gateup = self.workspace.run_parallel(
name=plan.gate_up_overlap.value,
device=hidden_states.device,
compute=base,
side=gate_up_a,
)
if plan.gate_up_b is not None:
gate_up_b()
else:
def gate_up_a_b() -> None:
gate_up_a()
gate_up_b()
base_gemm_state, gateup = self.workspace.run_parallel(
name=plan.gate_up_overlap.value,
device=hidden_states.device,
compute=base,
side=gate_up_a_b,
)
return state, base_gemm_state, gateup
def _run_act(
self,
plan: MoePlan,
launch_config: MoeLoraLaunchConfig,
provider: MoeBaseProvider,
routes: MoeLoraRoutes,
base_gemm_state,
gateup_out: torch.Tensor,
gate_up: _LoraStageState,
topk_ids: torch.Tensor,
batch: MoeLoraBatch,
num_tokens: int,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:
act_out = self.workspace.tensor(
"act:masked",
provider.act_out_shape(base_gemm_state),
dtype=provider.contract.lora_activation_dtype,
device=gateup_out.device,
)
provider_rows = act_out.view(-1, act_out.shape[-1])
pair_to_row = base_gemm_state.pair_to_row
# Fused B+activation can feed grouped down-A through the provider's row map.
exposes_pair_activation = not (
plan.act.family is ActFamily.B_ACTIVATION
and plan.down_a.family is AFamily.GROUPED
)
act_pairs = (
self.workspace.tensor(
"act:pairs",
(num_tokens, self.top_k, provider.intermediate_size),
dtype=provider.contract.lora_activation_dtype,
device=gateup_out.device,
)
if exposes_pair_activation
else None
)
if plan.act.family is ActFamily.MATERIALIZED:
quant_group = provider.contract.act_quant_group
act_quant = None
if quant_group is not None:
# Quantize during activation to avoid a separate down-GEMM input pass.
act_quant = (
self.workspace.tensor(
"act:quant_rows",
act_out.shape,
dtype=torch.float8_e4m3fn,
device=gateup_out.device,
),
self.workspace.tensor(
"act:quant_scales",
(act_out.shape[0], act_out.shape[1] // quant_group),
dtype=torch.float32,
device=gateup_out.device,
),
)
provider.act_with_delta(
base_gemm_state,
gateup_out,
gate_up.delta.view(
num_tokens,
self.top_k,
provider.gate_up_slices * provider.intermediate_size,
),
topk_ids,
act_out,
act_pairs,
activation=self.activation.value,
**({"act_quant": act_quant} if act_quant is not None else {}),
)
# Pair-major input needs no gather.
return act_out, act_pairs, None
provider.fused_act(
base_gemm_state,
activation=self.activation.value,
base_gateup=gateup_out,
act_rows=act_out,
act_pairs=act_pairs,
routing=routes.aligned(False),
config=launch_config.for_act(plan.act.family),
bridge_gateup=gate_up.rank,
b_gate_up=batch.gate_up_lora_b.flatten(0, 1),
bridge_top_k=(
self.top_k
if plan.gate_up_a.output_layout is BridgeLayout.TOKEN_MAJOR
else 1
),
)
if exposes_pair_activation:
return act_out, act_pairs, None
# Only provider-ordered input uses pair_to_row; pair-major input must not.
return act_out, provider_rows, pair_to_row
def _run_down(
self,
plan: MoePlan,
launch_config: MoeLoraLaunchConfig,
provider: MoeBaseProvider,
routes: MoeLoraRoutes,
base_gemm_state,
act_out: torch.Tensor,
down_a_input: torch.Tensor,
down_a_gather: torch.Tensor | None,
batch: MoeLoraBatch,
) -> tuple[
torch.Tensor,
torch.Tensor,
torch.Tensor | None,
]:
state = _LoraStageState()
def down_a() -> None:
state.rank = self._run_a(
launch_config,
plan.down_a,
down_a_input.view(-1, self.intermediate_size),
batch.down_lora_a.flatten(0, 1),
routes,
"down_a",
pair_to_row=down_a_gather,
)
def down_b() -> None:
delta = self.workspace.tensor(
"down_b:delta",
(state.rank.shape[0], self.hidden_size),
dtype=self.lora_delta_dtype,
device=state.rank.device,
)
self._run_b(
launch_config,
plan.down_b,
state.rank,
batch.down_lora_b.flatten(0, 1),
delta,
routes,
)
state.delta = delta
def down_b_into_base(down_out: torch.Tensor) -> None:
invoke_down_b_into_base(
down_rows=down_out.view(-1, provider.hidden_size),
pair_to_row=base_gemm_state.pair_to_row,
bridge=state.rank,
b_down=batch.down_lora_b.flatten(0, 1),
# In-place B requires aligned rows even when the selected family is raw.
routing=routes.aligned(plan.down_b.is_shared_outer),
config=launch_config.for_b(plan.down_b.site),
)
def base() -> torch.Tensor:
down_out = provider.down_output(base_gemm_state, self.workspace)
provider.down(base_gemm_state, act_out, down_out)
return down_out
if plan.down_overlap is DownOverlap.NONE:
down_a()
if plan.down_b_into_base:
down_out = base()
down_b_into_base(down_out)
else:
if plan.down_b is not None:
down_b()
down_out = base()
elif plan.down_overlap is DownOverlap.DOWN_A:
down_out = self.workspace.run_parallel(
name=plan.down_overlap.value,
device=act_out.device,
compute=base,
side=down_a,
)
if plan.down_b_into_base:
down_b_into_base(down_out)
elif plan.down_b is not None:
down_b()
else:
def down_a_b() -> None:
down_a()
down_b()
down_out = self.workspace.run_parallel(
name=plan.down_overlap.value,
device=act_out.device,
compute=base,
side=down_a_b,
)
return down_out, state.rank, state.delta
def _allocate_output(
self,
*,
num_tokens: int,
dtype: torch.dtype,
device: torch.device,
) -> torch.Tensor:
from sglang.srt.distributed.device_communicators.pynccl_allocator import (
use_symmetric_memory,
)
from sglang.srt.layers.dp_attention import is_allocation_symmetric
from sglang.srt.runtime_context import get_parallel
with use_symmetric_memory(
get_parallel().tp_group, disabled=not is_allocation_symmetric()
):
return torch.empty(
(num_tokens, self.hidden_size),
dtype=dtype,
device=device,
)
def _run_finalize(
self,
plan: MoePlan,
launch_config: MoeLoraLaunchConfig,
provider: MoeBaseProvider,
routes: MoeLoraRoutes,
base_gemm_state,
output: torch.Tensor,
down_out: torch.Tensor,
down_rank: torch.Tensor,
down_delta: torch.Tensor | None,
topk_output,
batch: MoeLoraBatch,
num_tokens: int,
) -> torch.Tensor:
if plan.finalize.family is FinalizeFamily.MATERIALIZED:
provider.finalize(
base_gemm_state,
down_out,
topk_output.topk_ids,
topk_output.topk_weights,
self.routed_scaling_factor,
output,
lora_delta=(
None
if plan.down_b_into_base
else down_delta.view(num_tokens, self.top_k, self.hidden_size)
),
)
return output
provider.shared_outer_finalize(
base_gemm_state,
down_rows=down_out,
bridge=down_rank,
b_down=batch.down_lora_b.flatten(0, 1),
routing=routes.raw(plan.finalize.is_shared_outer),
topk_weights=topk_output.topk_weights,
routed_scaling_factor=self.routed_scaling_factor,
output=output,
family=plan.finalize.family,
launch_config=launch_config,
workspace=self.workspace,
token_route=routes.shared_token,
)
return output
+37 -1
View File
@@ -78,7 +78,7 @@ class LoRABatchInfo:
seg_lens: Optional[torch.Tensor]
# The logical (re)ordering of input rows (tokens), in shape (num_tokens,)
permutation: Optional[torch.Tensor]
permutation: Optional[torch.Tensor] = None
# Total number of tokens this batch info expects (host-side int).
# Used by lm_head LoRA to validate input shape without GPU sync.
@@ -88,6 +88,8 @@ class LoRABatchInfo:
# Computed from Python lists in prepare_lora_batch to avoid GPU sync.
has_active_lora: bool = False
is_prefill: bool = False
# Per-request segment indptrs, shape (bs + 1,). Required by MoE virtual
# experts which map tokens to requests regardless of the dense-LoRA
# backend's internal segmentation. For the triton backend these are
@@ -107,6 +109,20 @@ class LoRAType(Enum):
LORA_B = 1
class Phase(str, Enum):
DECODE = "decode"
PREFILL = "prefill"
def architecture_for_capability(major: int) -> str:
"""Plan-table name for compute capability major: sm90, sm100 (>= 10) or default."""
if major == 9:
return "sm90"
if major >= 10:
return "sm100"
return "default"
def copy_weight_into_buffer(
buffer_view: torch.Tensor,
weight: torch.Tensor,
@@ -659,3 +675,23 @@ def build_lm_head_pass_segments(
result.append((seg_wi, seg_lens))
return result
def capturing_lora_graph() -> bool:
"""Whether capture is active, excluding the decode "nolora" variant."""
from sglang.srt.model_executor.runner_utils.capture_mode import (
get_capture_lora_variant,
get_is_capture_mode,
)
return get_is_capture_mode() and get_capture_lora_variant() != "nolora"
def kv_b_lora_correction(attn_module) -> str | None:
"""Select legacy or capture-aware v2 correction, or None."""
layer = getattr(attn_module, "kv_b_proj", None)
if not getattr(layer, "set_lora", False):
return None
if layer.lora_backend.name != "triton_v2":
return "legacy"
return "v2" if layer.lora_active else None
+180
View File
@@ -0,0 +1,180 @@
from __future__ import annotations
from collections.abc import Callable, Sequence
from typing import TYPE_CHECKING, TypeVar
import torch
if TYPE_CHECKING:
from sglang.kernels.ops.lora.common.route_view import RouteView
_raw_stream = getattr(torch._C, "_cuda_getCurrentRawStream", None)
_T = TypeVar("_T")
class LoraWorkspace:
"""Reusable, stream-local scratch for LoRA runners.
Warm up on the streams used during capture. Graph phases use separate
buffers; outgrown graph storage stays alive for existing captures.
"""
def __init__(self) -> None:
self._graph_storage: dict[
tuple[str, torch.dtype, torch.device, int, bool], torch.Tensor
] = {}
self._retired: list[torch.Tensor] = []
self._eager_buffers: dict[
tuple[str, torch.dtype, torch.device, int], torch.Tensor
] = {}
self._streams: dict[tuple[torch.device, int], torch.cuda.Stream] = {}
self._events: dict[tuple[torch.device, int, str], torch.cuda.Event] = {}
self._graph_mode = False
self._is_prefill_graph = False
self.routes: dict[tuple, dict[tuple, RouteView]] = {}
def route(
self, mapping: torch.Tensor, key: tuple, build: Callable[[], RouteView]
) -> RouteView:
stream = self._caller(mapping.device) if mapping.is_cuda else 0
routes = self.routes.setdefault((mapping.device, stream), {})
key = (
self._graph_mode,
self._is_prefill_graph if self._graph_mode else False,
mapping.dtype,
mapping.data_ptr(),
mapping.numel(),
mapping.stride(),
*key,
)
route = routes.get(key)
if route is None:
route = build()
routes[key] = route
return route
def begin_forward(
self, *, graph_mode: bool, is_prefill_graph: bool = False
) -> None:
self._graph_mode = bool(graph_mode)
self._is_prefill_graph = bool(is_prefill_graph)
@staticmethod
def _capturing(device: torch.device) -> bool:
return device.type == "cuda" and torch.cuda.is_current_stream_capturing()
def tensor(
self,
name: str,
shape: Sequence[int],
*,
dtype: torch.dtype,
device: torch.device | str,
zero_on_first_allocation: bool = False,
) -> torch.Tensor:
# Per-forward clears belong to the caller so graphs replay them.
resolved_device = torch.device(device)
resolved_shape = tuple(int(dim) for dim in shape)
elements = 1
for dimension in resolved_shape:
elements *= dimension
stream = self._caller(resolved_device) if resolved_device.type == "cuda" else 0
key = (name, dtype, resolved_device, stream)
if self._graph_mode:
key = (*key, self._is_prefill_graph)
storage = self._graph_storage.get(key)
if storage is None or storage.numel() < elements:
if self._capturing(resolved_device):
raise RuntimeError(
"MoE LoRA workspace was not warmed before CUDA capture: "
f"missing {name!r} {resolved_shape} {dtype} on "
f"{resolved_device}"
)
if storage is not None:
self._retired.append(storage)
factory = torch.zeros if zero_on_first_allocation else torch.empty
storage = factory((elements,), dtype=dtype, device=resolved_device)
self._graph_storage[key] = storage
tensor = storage[:elements].view(resolved_shape)
else:
storage = self._eager_buffers.get(key)
if storage is None or storage.numel() < elements:
if self._capturing(resolved_device):
raise RuntimeError(
"an eager MoE LoRA workspace cannot grow inside CUDA capture"
)
factory = torch.zeros if zero_on_first_allocation else torch.empty
storage = factory((elements,), dtype=dtype, device=resolved_device)
self._eager_buffers[key] = storage
tensor = storage[:elements].view(resolved_shape)
return tensor
@staticmethod
def _caller(device: torch.device) -> int:
# Read the raw handle without constructing a Python Stream wrapper.
if _raw_stream is not None and device.type == "cuda":
index = device.index
return _raw_stream(
index if index is not None else torch.cuda.current_device()
)
return torch.cuda.current_stream(device).cuda_stream
def side_stream(self, device: torch.device | str) -> torch.cuda.Stream:
resolved_device = torch.device(device)
caller = self._caller(resolved_device)
key = (resolved_device, caller)
stream = self._streams.get(key)
if stream is None:
# The stream pool can return the caller's stream, preventing overlap.
stream = torch.cuda.Stream(device=resolved_device)
while stream.cuda_stream == caller:
stream = torch.cuda.Stream(device=resolved_device)
self._streams[key] = stream
return stream
def event(self, device: torch.device | str, name: str) -> torch.cuda.Event:
resolved_device = torch.device(device)
key = (resolved_device, self._caller(resolved_device), name)
event = self._events.get(key)
if event is None:
event = torch.cuda.Event()
self._events[key] = event
return event
def run_parallel(
self,
*,
name: str,
device: torch.device,
compute: Callable[[], _T],
side: Callable[[], object],
) -> _T:
if device.type != "cuda":
side()
return compute()
current = torch.cuda.current_stream(device)
side_stream = self.side_stream(device)
ready = self.event(device, f"{name}:ready")
done = self.event(device, f"{name}:done")
ready.record(current)
side_stream.wait_event(ready)
caller_routes = self.routes.setdefault(
(current.device, current.cuda_stream), {}
)
side_routes = self.routes.setdefault(
(side_stream.device, side_stream.cuda_stream), {}
)
# Routes become visible across streams at the existing event waits.
side_routes.update(caller_routes)
with torch.cuda.stream(side_stream):
side()
done.record(side_stream)
completed_routes = side_routes.copy()
result = compute()
current.wait_event(done)
caller_routes.update(completed_routes)
return result
@@ -47,7 +47,6 @@ from sglang.srt.model_executor.runner_utils.buffers import ( # noqa: F401
_grouped_foreach_copy_,
)
from sglang.srt.model_executor.runner_utils.capture_mode import ( # noqa: F401
_set_capture_lora_variant,
compile_in_capture_mode,
get_capture_lora_variant,
get_is_capture_mode,
@@ -94,7 +94,7 @@ from sglang.srt.model_executor.runner_backend_utils import CUDA_GRAPH_CAPTURE_FA
from sglang.srt.model_executor.runner_utils.buffers import DecodeInputBuffers
from sglang.srt.model_executor.runner_utils.capture_mode import (
_set_capture_attention_variant,
_set_capture_lora_variant,
capture_lora_variant,
model_capture_mode,
)
from sglang.srt.model_executor.runner_utils.deepep_adapter import (
@@ -216,6 +216,11 @@ def build_replay_fb_view(
)
def _lora_backend_skips_inactive(model_runner) -> bool:
manager = model_runner.lora_manager
return manager is not None and manager.lora_backend.skip_inactive_dense_lora
class DecodeCudaGraphRunner(BaseCudaGraphRunner):
"""Decode-phase CUDA graph runner.
@@ -237,7 +242,10 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner):
record_nolora_graph: bool = False,
):
super().__init__(model_runner)
self.record_nolora_graph = record_nolora_graph
# Inactive dense LoRA batches replay a separate base-only graph.
self.record_nolora_graph = record_nolora_graph or _lora_backend_skips_inactive(
model_runner
)
# In-graph metadata prep: shared buffers -> in-graph private data
self.in_graph_metadata_prep_done: Optional[torch.cuda.Event] = None
@@ -394,7 +402,7 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner):
# Phase 2 of LoRA CUDA graph init: dense LoRA batch metadata.
# Phase 1 (MoE buffers) was handled earlier in ModelRunner via
# lora_manager.init_cuda_graph_moe_buffers().
self.model_runner.lora_manager.init_cuda_graph_batch_info(
self.model_runner.lora_manager.init_decode_cuda_graph_batch_info(
max_bs_in_cuda_graph=self.max_bs,
num_tokens_per_req=self.captured_req_width,
)
@@ -1187,11 +1195,7 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner):
if get_parallel().tp_rank == 0
else reversed(self.capture_bs)
)
lora_variants = (
[("lora", True), ("nolora", False)]
if self.record_nolora_graph
else [(None, None)]
)
lora_variants = ("lora", "nolora") if self.record_nolora_graph else (None,)
variants = self.attention_graph_variants
for bs in capture_range:
attention_variants = (
@@ -1207,26 +1211,26 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner):
f"Capturing batches ({bs=} {avail_mem=:.2f} GB)"
)
for variant_label, _variant_has_lora in lora_variants:
_set_capture_lora_variant(variant_label)
for attention_variant in attention_variants:
_set_capture_attention_variant(attention_variant)
self._set_profile_trace_tag(
bs, stream_idx, variant_label, attention_variant
)
with torch_compile_decoration.patch_model(
self.model_runner.model,
bs in self.compile_bs,
num_tokens=bs * self.captured_req_width,
tp_group=get_parallel().tp_group,
) as forward:
self.capture_one_shape(
bs,
forward,
stream_idx,
variant_label,
attention_variant,
for variant_label in lora_variants:
with capture_lora_variant(variant_label):
for attention_variant in attention_variants:
_set_capture_attention_variant(attention_variant)
self._set_profile_trace_tag(
bs, stream_idx, variant_label, attention_variant
)
with torch_compile_decoration.patch_model(
self.model_runner.model,
bs in self.compile_bs,
num_tokens=bs * self.captured_req_width,
tp_group=get_parallel().tp_group,
) as forward:
self.capture_one_shape(
bs,
forward,
stream_idx,
variant_label,
attention_variant,
)
_set_capture_attention_variant(None)
def capture_one_shape(
@@ -1269,6 +1273,8 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner):
ForwardContext(attn_backend=attn_backend),
forward_batch=forward_batch,
):
if forward_batch.lora_ids is not None:
self.model_runner.lora_manager.reset_routing_cache()
# Backends may gather live pool mappings into their static
# metadata here; these nodes run before any model KV reads.
attn_backend.init_forward_metadata_in_graph(forward_batch)
@@ -1785,6 +1785,8 @@ class PrefillCudaGraphRunner(BaseCudaGraphRunner):
self._init_forward_metadata_for_capture(forward_batch, shape_key)
def run_once():
if forward_batch.lora_ids is not None:
self.model_runner.lora_manager.reset_routing_cache()
# Record LoRA kernels even when capture uses base-model requests.
with (
model_capture_mode()
@@ -63,9 +63,19 @@ def get_capture_lora_variant() -> Optional[str]:
return _capture_lora_variant
def _set_capture_lora_variant(variant: Optional[str]) -> None:
@contextmanager
def capture_lora_variant(variant: Optional[str]):
"""Scope the "lora"/"nolora" label so later captures cannot inherit it.
None denotes a single graph serving both variants.
"""
global _capture_lora_variant
previous = _capture_lora_variant
_capture_lora_variant = variant
try:
yield
finally:
_capture_lora_variant = previous
def get_capture_attention_variant() -> Optional[str]:
@@ -24,15 +24,7 @@ from sglang.srt.layers.dcp import (
)
from sglang.srt.layers.layer_boundary import get_attn_tp_context
from sglang.srt.layers.logits_processor import get_in_autotune_dummy_run
from sglang.srt.lora.deepseek_mla_correction import (
apply_q_correction as apply_kv_b_lora_q_correction,
)
from sglang.srt.lora.deepseek_mla_correction import (
apply_v_correction as apply_kv_b_lora_v_correction,
)
from sglang.srt.lora.deepseek_mla_correction import (
is_kv_b_lora_active,
)
from sglang.srt.lora.utils import kv_b_lora_correction
from sglang.srt.model_executor.forward_batch_info import ForwardBatch
from sglang.srt.model_executor.forward_context import (
get_attn_backend,
@@ -72,6 +64,10 @@ if TYPE_CHECKING:
from sglang.srt.models.deepseek_v2 import DeepseekV2AttentionMLA
def is_kv_b_lora_active(attn_module: DeepseekV2AttentionMLA) -> bool:
return getattr(getattr(attn_module, "kv_b_proj", None), "set_lora", False)
@dataclass(frozen=True)
class MlaBmmFusionPlan:
q_nope_t: torch.Tensor
@@ -521,6 +517,7 @@ class DeepseekMLAForwardMixin:
# fp8 q directly into the q8kv8 backend buffer.
q_nope_out = None
else:
kv_b_lora = kv_b_lora_correction(self)
if _SGLANG_EXPERIMENTAL_LORA_OPTI:
# Fork the kv_b q-correction A-step onto the LoRA side stream to overlap the bmm.
from sglang.srt.lora.trtllm_lora_temp.deepseek_mla_correction import (
@@ -528,6 +525,10 @@ class DeepseekMLAForwardMixin:
)
_kvb_q = kv_b_lora_q_prepare(self, q_nope)
elif kv_b_lora == "v2":
from sglang.srt.lora.dense import mla_correction
_kvb_q = mla_correction.prepare_q_correction(self, q_nope)
if self.use_deep_gemm_bmm:
(
@@ -583,8 +584,14 @@ class DeepseekMLAForwardMixin:
)
q_nope_out = kv_b_lora_q_apply(self, q_nope, q_nope_out, _kvb_q)
elif is_kv_b_lora_active(self):
q_nope_out = apply_kv_b_lora_q_correction(self, q_nope, q_nope_out)
elif kv_b_lora == "v2":
q_nope_out = mla_correction.apply_correction(_kvb_q, q_nope_out)
elif kv_b_lora == "legacy":
from sglang.srt.lora import deepseek_mla_correction
q_nope_out = deepseek_mla_correction.apply_q_correction(
self, q_nope, q_nope_out
)
fuse_rope_for_trtllm_mla = self._fuse_rope_for_trtllm_mla(forward_batch)
if (
@@ -812,6 +819,7 @@ class DeepseekMLAForwardMixin:
attn_output = attn_output.view(-1, self.num_local_heads, self.kv_lora_rank)
_kvb_v = None
kv_b_lora = kv_b_lora_correction(self)
if _SGLANG_EXPERIMENTAL_LORA_OPTI:
# Fork the kv_b v-correction A-step onto the LoRA side stream to overlap the bmm.
from sglang.srt.lora.trtllm_lora_temp.deepseek_mla_correction import (
@@ -819,6 +827,10 @@ class DeepseekMLAForwardMixin:
)
_kvb_v = kv_b_lora_v_prepare(self, attn_output)
elif kv_b_lora == "v2":
from sglang.srt.lora.dense import mla_correction
_kvb_v = mla_correction.prepare_v_correction(self, attn_output)
if getattr(self, "_kimi_split_gguf_kv_b", False):
from sglang.srt.layers.quantization.gguf import fused_mul_mat_gguf
@@ -908,8 +920,12 @@ class DeepseekMLAForwardMixin:
attn_bmm_output = kv_b_lora_v_apply(
self, attn_output, attn_bmm_output, _kvb_v
)
elif is_kv_b_lora_active(self):
attn_bmm_output = apply_kv_b_lora_v_correction(
elif kv_b_lora == "v2":
attn_bmm_output = mla_correction.apply_correction(_kvb_v, attn_bmm_output)
elif kv_b_lora == "legacy":
from sglang.srt.lora import deepseek_mla_correction
attn_bmm_output = deepseek_mla_correction.apply_v_correction(
self, attn_output, attn_bmm_output
)
if attention_output_gate is not None:
@@ -16,10 +16,11 @@ from sglang.srt.models.inkling_common.kernels.comm import (
)
from sglang.srt.models.inkling_common.util import (
FusedMoELoadingMixin,
deinterleave_gate_up,
lora_compatible_layout_enabled,
)
from sglang.srt.models.llama import LlamaMLP
from sglang.srt.runtime_context import get_exec, get_model
from sglang.srt.runtime_context import get_exec, get_lora, get_model
logger = logging.getLogger(__name__)
@@ -150,6 +151,8 @@ def _sum_dim0(x: torch.Tensor) -> torch.Tensor:
class InklingBatchDenseMLP(nn.Module, FusedMoELoadingMixin):
_w13_gate_up_contiguous = False
def __init__(
self,
n_shared_experts: int,
@@ -247,6 +250,11 @@ class InklingBatchDenseMLP(nn.Module, FusedMoELoadingMixin):
else:
self.register_buffer("_w2_lin", None, persistent=False)
self._bf16_linearized_ready = False
self._w13_gate_up_contiguous = (
self._linearized_bf16_enabled
and lora_compatible_layout_enabled()
and get_lora().lora_backend == "triton_v2"
)
def weight_loader_fused(
self,
@@ -255,6 +263,15 @@ class InklingBatchDenseMLP(nn.Module, FusedMoELoadingMixin):
weight_name: str,
shard_id: str,
) -> None:
if self._w13_gate_up_contiguous and param is self.w13_weight:
n, two_f, d = loaded_weight.shape
# Keep each TP block intact: the fused loader shards after conversion.
loaded_weight = deinterleave_gate_up(
loaded_weight.reshape(
n, self.moe_tp_size, two_f // self.moe_tp_size, d
),
dim=2,
).reshape(n, two_f, d)
FusedMoELoadingMixin.weight_loader_fused(
self, param, loaded_weight, weight_name, shard_id
)
@@ -384,14 +401,21 @@ class InklingBatchDenseMLP(nn.Module, FusedMoELoadingMixin):
def _swiglu(self, y_st2f: torch.Tensor, gammas_st: torch.Tensor) -> torch.Tensor:
# Helion's kernel can produce NaNs for small shared-expert batches.
from sglang.kernels.ops.moe.inkling_moe import (
silu_and_mul,
silu_and_mul_triton,
)
assert self.inference_moe_w13_interleaved, (
"silu_and_mul_triton requires interleaved w13"
)
y_st_2f = y_st2f.view(-1, y_st2f.size(-1))
y_st_f = silu_and_mul_triton(y_st_2f, gammas_st.reshape(-1))
gammas = gammas_st.reshape(-1)
if self._w13_gate_up_contiguous:
# Same fp32 math and rounding as the interleaved kernel, reading
# the two contiguous halves of each row.
y_st_f = silu_and_mul(y_st_2f, gammas, use_interleaved=False)
else:
assert self.inference_moe_w13_interleaved, (
"silu_and_mul_triton requires interleaved w13"
)
y_st_f = silu_and_mul_triton(y_st_2f, gammas)
return y_st_f.view(*y_st2f.shape[:-1], y_st2f.size(-1) // 2)
# NVFP4 shared-expert serving uses the generic ModelOpt FP4 linears.
+169 -1
View File
@@ -3,13 +3,17 @@ from __future__ import annotations
import torch
from sglang.srt.lora.backend.base_backend import BaseLoRABackend
from sglang.srt.lora.dense.plan import DenseLoraKind
from sglang.srt.lora.utils import capturing_lora_graph
from sglang.srt.models.inkling_common.dense_mlp import InklingBatchDenseMLP
from sglang.srt.models.inkling_common.kernels.comm import symm_mem_all_reduce
class InklingBatchDenseMLPWithLoRA(InklingBatchDenseMLP):
"""LoRA layer for Inkling's dense shared-expert sink."""
is_shared_fused_moe = True
set_lora = False
is_shared_fused_moe = False
def initialize_lora(self, lora_backend: BaseLoRABackend) -> None:
problems = []
@@ -31,6 +35,7 @@ class InklingBatchDenseMLPWithLoRA(InklingBatchDenseMLP):
self.register_buffer("_w1_delta", None, persistent=False)
self.register_buffer("_a_cat", None, persistent=False)
self._lora_routing_cache = {}
self.is_shared_fused_moe = True
lora_backend.is_moe_lora = True
def set_lora_info(
@@ -241,3 +246,166 @@ class InklingBatchDenseMLPWithLoRA(InklingBatchDenseMLP):
linearized_weights,
use_reduce_scatter,
)
class InklingBatchDenseMLPWithLoRAV2(InklingBatchDenseMLP):
"""Dense-engine LoRA for Inkling's shared-expert sink."""
set_lora = False
is_shared_fused_moe = False
def initialize_lora(self, lora_backend: BaseLoRABackend) -> None:
if getattr(lora_backend, "runner", None) is None:
raise ValueError(
f"{type(self).__name__} needs a backend with the dense engine"
)
if not self._linearized_bf16_enabled:
raise ValueError(
f"{type(self).__name__} needs the linearized BF16 shared sink"
)
if not self._w13_gate_up_contiguous:
raise ValueError(
"The V2 shared sink must select contiguous W13 before loading"
)
self.lora_backend = lora_backend
self.set_lora = False
self.register_buffer("_down_cat", None, persistent=False)
self.is_shared_fused_moe = True
lora_backend.is_moe_lora = True
def set_lora_info(
self,
gate_up_lora_a_weights: torch.Tensor,
gate_up_lora_b_weights: torch.Tensor,
down_lora_a_weights: torch.Tensor,
down_lora_b_weights: torch.Tensor,
) -> None:
n = self.n_shared_experts
slots, outer, two_rank, _ = gate_up_lora_a_weights.shape
_, _, two_f, rank = gate_up_lora_b_weights.shape
hidden = down_lora_b_weights.shape[2]
if (
outer not in (1, n)
or down_lora_b_weights.shape[1] != outer
or gate_up_lora_b_weights.shape[1] != n
or down_lora_a_weights.shape[1] != n
or two_rank != 2 * rank
or down_lora_a_weights.shape[2] != rank
or down_lora_b_weights.shape[-1] != rank
):
raise ValueError(
"Inkling shared-sink LoRA pool buffers do not agree: expected gate-up A "
f"[slots, 1 or {n}, 2R, H], gate-up B [slots, {n}, 2F, R], down A "
f"[slots, {n}, R, F], down B [slots, 1 or {n}, H, R] with one layout"
)
shared = outer == 1
shape = (slots, rank, n * (two_f // 2)) if shared else (slots, hidden, n * rank)
down_cat = self._down_cat
if down_cat is None:
down_cat = down_lora_a_weights.new_empty(shape)
elif tuple(down_cat.shape) != shape:
raise RuntimeError(
"Shared-sink LoRA pool shape changed after initialization: "
f"{tuple(down_cat.shape)} -> {shape}"
)
device = gate_up_lora_b_weights.device
# Pool factors are max-rank padded and already scaled.
ranks = torch.full((slots,), rank, dtype=torch.int32, device=device)
scalings = torch.ones(slots, dtype=torch.float32, device=device)
gate_up = dict(
kind=DenseLoraKind.SINK_GATE_UP,
a=(
gate_up_lora_a_weights[:, 0]
if shared
else gate_up_lora_a_weights.reshape(slots, n * 2 * rank, -1)
),
b=gate_up_lora_b_weights.view(slots, n * two_f, rank),
offsets=tuple(range(0, n * two_f + 1, two_f // 2)),
lora_ranks=ranks,
scalings=scalings,
a_blocks=2 if shared else 2 * n,
bridge_slices=2 if shared else 0,
)
if shared:
down = dict(
kind=DenseLoraKind.LINEAR,
a=down_cat,
b=down_lora_b_weights[:, 0],
offsets=(0, hidden),
lora_ranks=ranks,
scalings=scalings,
)
else:
# Each A block reads one expert's activation window.
down = dict(
kind=DenseLoraKind.SINK_DOWN,
a=down_lora_a_weights.view(slots, n * rank, -1),
b=down_cat,
offsets=(0, hidden),
lora_ranks=ranks * n,
scalings=scalings,
a_blocks=n,
a_windowed=True,
)
source = (down_lora_a_weights if shared else down_lora_b_weights).permute(
0, 2, 1, 3
)
self._down_refresh = source, down_cat.view_as(source)
self._down_cat = down_cat
self._gate_up, self._down = gate_up, down
self.set_lora = True
self.on_lora_slots_updated()
def on_lora_slots_updated(self, slot_ids: set[int] | None = None) -> None:
if not self.set_lora:
return
source, target = self._down_refresh
# Keep the derived buffer's address stable across graph replays.
with torch.no_grad():
for slot in range(source.shape[0]) if slot_ids is None else slot_ids:
target[slot].copy_(source[slot])
# Both wrappers receive the same pool factors and TP slicing geometry.
slice_moe_lora_a_weights = InklingBatchDenseMLPWithLoRA.slice_moe_lora_a_weights
slice_moe_lora_b_weights = InklingBatchDenseMLPWithLoRA.slice_moe_lora_b_weights
_slice_down_lora_a = InklingBatchDenseMLPWithLoRA._slice_down_lora_a
_slice_gate_up_lora_b = InklingBatchDenseMLPWithLoRA._slice_gate_up_lora_b
def _forward_bf16_linearized(
self,
x_td: torch.Tensor,
gammas_ts: torch.Tensor,
linearized_weights: tuple[torch.Tensor, torch.Tensor],
use_reduce_scatter: bool,
) -> torch.Tensor:
# Capture LoRA even without an active adapter, for later replay batches
# (except the decode runner's LoRA-free "nolora" graph).
if not self.set_lora or not (
getattr(self.lora_backend.batch_info, "has_active_lora", False)
or capturing_lora_graph()
):
return super()._forward_bf16_linearized(
x_td, gammas_ts, linearized_weights, use_reduce_scatter
)
w13_lin, w2_lin = linearized_weights
t, n = x_td.shape[0], self.n_shared_experts
y = self._lora_gemm(x_td, lambda: torch.mm(x_td, w13_lin.T), **self._gate_up)
act_flat = self._swiglu(y.view(t, n, -1), gammas_ts).reshape(t, -1)
out_td = self._lora_gemm(
act_flat, lambda: torch.mm(act_flat, w2_lin), **self._down
)
if not use_reduce_scatter and self.tp_group is not None:
out_td = symm_mem_all_reduce(out_td, self.tp_group)
return out_td
def _lora_gemm(self, x: torch.Tensor, base_fn, *, kind, **site) -> torch.Tensor:
runner = self.lora_backend.runner
plan = runner.plan_for(
kind,
site["b"].shape[-1],
x.shape[-1],
site["offsets"][-1],
num_tokens=x.shape[0],
)
return runner.apply(x, base_fn, plan, **site)
+15 -3
View File
@@ -56,7 +56,7 @@ from sglang.srt.models.inkling_common.util import (
lora_compatible_layout_enabled,
use_inkling_shared_fused_moe,
)
from sglang.srt.runtime_context import get_exec, get_parallel
from sglang.srt.runtime_context import get_exec, get_lora, get_parallel
from sglang.srt.state_capturer.routed_experts import get_global_experts_capturer
from sglang.srt.utils import add_prefix, is_cuda, is_hip
@@ -748,7 +748,19 @@ def _build_inkling_shared_experts(
parallel_group="tp",
tp_group=get_parallel().tp_group,
)
return InklingBatchDenseMLP(
sink_cls = InklingBatchDenseMLP
if get_lora().enable_lora:
from sglang.srt.models.inkling_common.lora import (
InklingBatchDenseMLPWithLoRA,
InklingBatchDenseMLPWithLoRAV2,
)
sink_cls = (
InklingBatchDenseMLPWithLoRAV2
if get_lora().lora_backend == "triton_v2"
else InklingBatchDenseMLPWithLoRA
)
return sink_cls(
**dense_kwargs,
linearized_bf16=(
lora_compatible_layout_enabled()
@@ -1018,7 +1030,7 @@ class InklingMoE(nn.Module):
topk_weights, topk_ids, shared_gammas, packed_topk_ids = self.gate(x)
allow_lora_overlap = True
if lora_compatible_layout_enabled():
if lora_compatible_layout_enabled() and get_lora().lora_backend != "triton_v2":
# ===== TO BE REFACTORED ====
from sglang.srt.lora.trtllm_lora_temp.inkling_dense import (
allow_inkling_moe_two_stream,