Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
150 changes: 150 additions & 0 deletions benchmark/kernels/rocm_bf16_gemv/tune_rocm_bf16_gemv.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
"""Tune the gfx942 Triton skinny bf16 GEMM (sglang.kernels.ops.gemm.rocm_bf16_gemv).

Prints a "(N, K): {M bound: config}" entry to paste into _GFX942_CONFIGS in
rocm_bf16_gemv.py, plus per-bucket timings. Run one process per N on an idle GPU:

HIP_VISIBLE_DEVICES=2 python benchmark/kernels/rocm_bf16_gemv/tune_rocm_bf16_gemv.py \
--n 124160 --k 2560

Search is coarse-to-fine: tile shape first (BLOCK_N, BLOCK_K, num_warps) with neutral
knobs, then waves_per_eu / num_stages / cache_modifier on the best tiles.
All timings (candidates, hipBLASLt, shipped config) use triton.testing.do_bench.
Every candidate is checked against an fp32 reference before it is timed. Only add an
entry when the tuned config beats hipBLASLt in every bucket: listed shapes are the
only ones routed to these kernels.
"""

import argparse
import itertools
import json
import statistics

import torch
import triton

from sglang.kernels.ops.gemm.rocm_bf16_gemv import _GFX942_CONFIGS, _launch

M_BOUNDS = (1, 2, 4, 8, 16, 24, 32)


def _time_us(fn):
# Same settings as aiter's op_benchmarks (do_bench also flushes L2 between reps).
return triton.testing.do_bench(fn, warmup=25, rep=100) * 1000


def _tile_candidates(m, k):
if m == 1:
for bn, bk, warps in itertools.product(
(8, 16, 32, 64), (128, 256, 512), (1, 2, 4, 8)
):
if bn * bk <= 32768 and k % bk == 0:
yield dict(
BLOCK_SIZE_N=bn,
BLOCK_SIZE_K=bk,
num_warps=warps,
num_stages=2,
waves_per_eu=0,
cache_modifier=None,
)
return
block_m = 16 if m <= 16 else 32
for bn, bk, warps in itertools.product(
(16, 32, 64, 128, 256), (64, 128, 256, 512), (1, 2, 4, 8)
):
if block_m * bk + bn * bk <= 65536 and k % bk == 0:
yield dict(
BLOCK_SIZE_M=block_m,
BLOCK_SIZE_N=bn,
BLOCK_SIZE_K=bk,
num_warps=warps,
num_stages=1,
waves_per_eu=0,
matrix_instr_nonkdim=16,
kpack=2,
cache_modifier=None,
)


def _knob_candidates(tile):
for wpe, stages, cache in itertools.product((0, 1, 2, 3, 4), (1, 2), (None, ".cg")):
yield dict(tile, waves_per_eu=wpe, num_stages=stages, cache_modifier=cache)


def _screen(x, w, ref, tol, candidates):
timed = []
for cfg in candidates:
try:
out = _launch(x, w, cfg)
torch.cuda.synchronize()
except Exception: # compile failure (registers / LDS) rules the config out
continue
if (out.float() - ref).abs().max().item() > tol:
continue
timed.append((_time_us(lambda: _launch(x, w, cfg)), cfg))
timed.sort(key=lambda item: item[0])
return timed


def _final_time(fn, repeats=3):
return statistics.median(_time_us(fn) for _ in range(repeats))


def tune_bucket(w, m):
n, k = w.shape
x = torch.randn(m, k, dtype=torch.bfloat16, device="cuda")
ref = x.float() @ w.float().t()
blas_err = ((x @ w.t()).float() - ref).abs().max().item()
tol = max(blas_err * 2.0, 1e-2)

tiles = _screen(x, w, ref, tol, _tile_candidates(m, k))[:8]
knobs = [c for _, tile in tiles for c in _knob_candidates(tile)]
finalists = [cfg for _, cfg in _screen(x, w, ref, tol, knobs)[:5]]

t_blas = _final_time(lambda: torch.matmul(x, w.t()))
best = min(
((_final_time(lambda: _launch(x, w, cfg)), cfg) for cfg in finalists),
key=lambda item: item[0],
)
timing = dict(tuned_us=round(best[0], 1), hipblaslt_us=round(t_blas, 1))
# Compare with the shipped entry so a re-tune only replaces it when it wins.
current = _GFX942_CONFIGS.get((n, k))
if current is not None:
cfg = current[min(b for b in current if m <= b)]
timing["current_us"] = round(_final_time(lambda: _launch(x, w, cfg)), 1)
return best[1], timing


def _format_entry(n, k, configs):
lines = [f" ({n}, {k}): {{"]
for bound, c in configs.items():
knobs = (
f"{c['BLOCK_SIZE_N']}, {c['BLOCK_SIZE_K']}, {c['num_warps']}, "
f"{c['num_stages']}, {c['waves_per_eu']}, {c['cache_modifier']!r}"
)
if "BLOCK_SIZE_M" in c:
lines.append(f" {bound}: _mfma({c['BLOCK_SIZE_M']}, {knobs}),")
else:
lines.append(f" {bound}: _gemv({knobs}),")
lines.append(" },")
return "\n".join(lines)


def main():
parser = argparse.ArgumentParser()
parser.add_argument("--n", type=int, required=True)
parser.add_argument("--k", type=int, required=True)
parser.add_argument("--m-bounds", type=int, nargs="+", default=list(M_BOUNDS))
args = parser.parse_args()

torch.manual_seed(0)
w = torch.randn(args.n, args.k, dtype=torch.bfloat16, device="cuda") * 0.05
configs = {}
for bound in args.m_bounds:
cfg, timing = tune_bucket(w, bound)
configs[bound] = cfg
print(f"N={args.n} K={args.k} M<={bound}: {json.dumps(timing)}", flush=True)
print(_format_entry(args.n, args.k, configs))


if __name__ == "__main__":
main()
216 changes: 216 additions & 0 deletions python/sglang/kernels/ops/gemm/rocm_bf16_gemv.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
"""Skinny bf16 GEMM (``y = x @ w.T``) for weight-streaming shapes on gfx942."""

from __future__ import annotations

import functools

import torch
import triton
import triton.language as tl

_MAX_M = 32


@triton.jit
def _gemv_m1_kernel(
x_ptr,
w_ptr,
y_ptr,
N,
K,
stride_wn,
BLOCK_N: tl.constexpr,
BLOCK_K: tl.constexpr,
CACHE_MODIFIER: tl.constexpr,
):
pid = tl.program_id(0)
rn = pid * BLOCK_N + tl.arange(0, BLOCK_N)
rn_mask = rn < N
acc = tl.zeros((BLOCK_N,), dtype=tl.float32)
for k0 in range(0, K, BLOCK_K):
rk = k0 + tl.arange(0, BLOCK_K)
w = tl.load(
w_ptr + rn[:, None] * stride_wn + rk[None, :],
mask=rn_mask[:, None],
other=0.0,
cache_modifier=CACHE_MODIFIER,
)
x = tl.load(x_ptr + rk)
acc += tl.sum(w.to(tl.float32) * x.to(tl.float32)[None, :], axis=1)
tl.store(y_ptr + rn, acc.to(y_ptr.dtype.element_ty), mask=rn_mask)


@triton.jit
def _skinny_mfma_kernel(
x_ptr,
w_ptr,
y_ptr,
M,
N,
K,
stride_xm,
stride_wn,
stride_ym,
BLOCK_M: tl.constexpr,
BLOCK_N: tl.constexpr,
BLOCK_K: tl.constexpr,
CACHE_MODIFIER: tl.constexpr,
):
pid = tl.program_id(0)
rn = pid * BLOCK_N + tl.arange(0, BLOCK_N)
rm = tl.arange(0, BLOCK_M)
rn_mask = rn < N
rm_mask = rm < M
acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)
for k0 in range(0, K, BLOCK_K):
rk = k0 + tl.arange(0, BLOCK_K)
# Load W row-major ([BLOCK_N, BLOCK_K], contiguous along K) and
# transpose in registers; loading it pre-transposed halves bandwidth.
w = tl.load(
w_ptr + rn[:, None] * stride_wn + rk[None, :],
mask=rn_mask[:, None],
other=0.0,
cache_modifier=CACHE_MODIFIER,
)
x = tl.load(
x_ptr + rm[:, None] * stride_xm + rk[None, :],
mask=rm_mask[:, None],
other=0.0,
)
acc += tl.dot(x, tl.trans(w))
tl.store(
y_ptr + rm[:, None] * stride_ym + rn[None, :],
acc.to(y_ptr.dtype.element_ty),
mask=rm_mask[:, None] & rn_mask[None, :],
)


def _gemv(block_n, block_k, num_warps, num_stages, waves_per_eu, cache_modifier):
return dict(
BLOCK_SIZE_N=block_n,
BLOCK_SIZE_K=block_k,
num_warps=num_warps,
num_stages=num_stages,
waves_per_eu=waves_per_eu,
cache_modifier=cache_modifier,
)


def _mfma(
block_m, block_n, block_k, num_warps, num_stages, waves_per_eu, cache_modifier
):
return dict(
_gemv(block_n, block_k, num_warps, num_stages, waves_per_eu, cache_modifier),
BLOCK_SIZE_M=block_m,
matrix_instr_nonkdim=16,
kpack=2,
)


# {(N, K): {M upper bound: config}}. Only listed shapes use these kernels; untuned
# shapes measured slower than hipBLASLt for some M (N <= 24576, or K=5120).
# Tuned on MI308X with benchmark/kernels/rocm_bf16_gemv/tune_rocm_bf16_gemv.py
# for the Qwen3.8-Flash-Next lm_head shards (TP1/2/4/8).
_GFX942_CONFIGS = {
(248320, 2560): {
1: _gemv(8, 512, 1, 1, 0, ".cg"),
2: _mfma(16, 64, 256, 1, 1, 2, ".cg"),
4: _mfma(16, 64, 256, 1, 1, 2, ".cg"),
8: _mfma(16, 64, 256, 1, 1, 2, ".cg"),
16: _mfma(16, 64, 256, 1, 1, 2, ".cg"),
24: _mfma(32, 64, 256, 2, 1, 0, ".cg"),
32: _mfma(32, 64, 256, 2, 1, 2, ".cg"),
},
(124160, 2560): {
1: _gemv(32, 512, 8, 1, 1, ".cg"),
2: _mfma(16, 64, 256, 1, 1, 2, ".cg"),
4: _mfma(16, 64, 256, 1, 1, 2, ".cg"),
8: _mfma(16, 64, 256, 1, 1, 2, ".cg"),
16: _mfma(16, 64, 256, 1, 1, 2, ".cg"),
24: _mfma(32, 64, 256, 2, 1, 0, ".cg"),
32: _mfma(32, 64, 256, 2, 1, 3, ".cg"),
},
(62080, 2560): {
1: _gemv(16, 512, 4, 1, 0, ".cg"),
2: _mfma(16, 64, 256, 1, 1, 2, ".cg"),
4: _mfma(16, 64, 256, 1, 1, 2, ".cg"),
8: _mfma(16, 64, 256, 1, 1, 2, None),
16: _mfma(16, 64, 256, 1, 1, 2, None),
24: _mfma(32, 64, 256, 2, 1, 0, ".cg"),
32: _mfma(32, 64, 256, 2, 1, 0, ".cg"),
},
(31040, 2560): {
1: _gemv(8, 512, 1, 1, 0, None),
2: _mfma(16, 64, 256, 1, 1, 0, ".cg"),
4: _mfma(16, 32, 256, 1, 1, 2, ".cg"),
8: _mfma(16, 64, 256, 2, 1, 0, ".cg"),
16: _mfma(16, 64, 256, 1, 1, 0, ".cg"),
24: _mfma(32, 64, 128, 2, 1, 4, ".cg"),
32: _mfma(32, 128, 256, 4, 1, 3, ".cg"),
},
}


@functools.lru_cache(maxsize=None)
def _get_config(m: int, n: int, k: int) -> dict:
buckets = _GFX942_CONFIGS[(n, k)]
cfg = buckets[min(b for b in buckets if m <= b)]
assert k % cfg["BLOCK_SIZE_K"] == 0, (m, n, k, cfg) # K loop is unmasked
return cfg


def use_rocm_bf16_gemv(x: torch.Tensor, w: torch.Tensor) -> bool:
"""Whether ``rocm_bf16_gemv(x, w)`` applies; callers gate on gfx942."""
return (
x.dim() == 2
and w.dim() == 2
and x.dtype == torch.bfloat16
and w.dtype == torch.bfloat16
and x.is_cuda
and 1 <= x.shape[0] <= _MAX_M
and x.shape[1] == w.shape[1]
and (w.shape[0], w.shape[1]) in _GFX942_CONFIGS
and x.stride(1) == 1
and w.stride(1) == 1
)


def _launch(x: torch.Tensor, w: torch.Tensor, cfg: dict) -> torch.Tensor:
m, k = x.shape
n = w.shape[0]
y = torch.empty((m, n), dtype=x.dtype, device=x.device)
grid = (triton.cdiv(n, cfg["BLOCK_SIZE_N"]),)
launch_opts = dict(
BLOCK_N=cfg["BLOCK_SIZE_N"],
BLOCK_K=cfg["BLOCK_SIZE_K"],
CACHE_MODIFIER=cfg["cache_modifier"],
num_warps=cfg["num_warps"],
num_stages=cfg["num_stages"],
waves_per_eu=cfg["waves_per_eu"],
)
if m == 1:
_gemv_m1_kernel[grid](x, w, y, n, k, w.stride(0), **launch_opts)
else:
_skinny_mfma_kernel[grid](
x,
w,
y,
m,
n,
k,
x.stride(0),
w.stride(0),
y.stride(0),
BLOCK_M=cfg["BLOCK_SIZE_M"],
matrix_instr_nonkdim=cfg["matrix_instr_nonkdim"],
kpack=cfg["kpack"],
**launch_opts,
)
return y


def rocm_bf16_gemv(x: torch.Tensor, w: torch.Tensor) -> torch.Tensor:
"""y[M, N] = x[M, K] @ w[N, K]^T in bf16 with fp32 accumulation."""
m, k = x.shape
cfg = _get_config(m, w.shape[0], k)
Comment thread
apinge marked this conversation as resolved.
Resolved
return _launch(x, w, cfg)
3 changes: 3 additions & 0 deletions python/sglang/srt/environ.py
Original file line number Diff line number Diff line change
Expand Up @@ -1017,6 +1017,9 @@ class Envs:
SGLANG_HC_MIX_CUDA = EnvBool(True)
# Optional installed PyHIP GR read for BF16 Qwen HC mix on gfx942.
SGLANG_GR_READ_FLYDSL = EnvBool(False)
# Route M<=32 bf16 lm_head GEMMs on gfx942 to the Triton skinny GEMV
# instead of hipBLASLt.
SGLANG_ENABLE_ROCM_LM_HEAD_GEMV = EnvBool(True)
Comment thread
sammysun0711 marked this conversation as resolved.
Resolved
# Log each distinct (m, n, k) the BF16 GEMM dispatch sees (allowlist tuning).
SGLANG_BF16_GEMM_LOG_SHAPES = EnvBool(False)
# Split the HC combine gate dot across CTAs instead of one CTA per row.
Expand Down
Loading