"""H100 int8_scaled_gemm. Adapted from public-trial gpt6-astra-h100-xhigh-c2-20261105, frozen submission c8aa92b105320f07846ed0b3be6f680a638f79b42dcab2a6fb5d3079c248f7b0.""" import torch import triton as tr import triton.language as tl from sgl_kernel import int8_scaled_mm as _native_mm @tr.jit def _gemv( A, B, AS, BS, C, K: tl.constexpr, N: tl.constexpr, BSTR: tl.constexpr, BSS: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr, ): cols = tl.program_id(0) * BN + tl.arange(0, BN) ks = tl.arange(0, BK) ap = A.to(tl.pointer_type(tl.int32)) bp = B.to(tl.pointer_type(tl.int32)) acc = tl.full((BN, BK), 0, tl.int32) for it in range(tr.cdiv(K // 4, BK)): kk = it * BK + ks av = tl.load(ap + kk, kk < K // 4, other=0) bv = tl.load( bp + cols[:, None] * (BSTR // 4) + kk[None, :], (cols[:, None] < N) & (kk[None, :] < K // 4), other=0, ) acc = tl.inline_asm_elementwise( "dp4a.s32.s32 $0, $1, $2, $3;", constraints="=r,r,r,r", args=[bv, av[None, :], acc], dtype=tl.int32, is_pure=True, pack=1, ) val = tl.sum(acc, 1).to(tl.float32) sa = tl.load(AS).to(tl.float32) sb = tl.load(BS + cols * BSS, cols < N, other=0).to(tl.float32) val = (val * sa) * sb tl.store(C + cols, val.to(tl.bfloat16), cols < N) @tr.jit def _mm( A, B, AS, BS, C, M: tl.constexpr, N: tl.constexpr, K: tl.constexpr, AM: tl.constexpr, AK: tl.constexpr, BKSTR: tl.constexpr, BNSTR: tl.constexpr, ASS: tl.constexpr, BSS: tl.constexpr, BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr, SPLIT: tl.constexpr, ): pm_count = tr.cdiv(M, BM) pid = tl.program_id(0) pm = pid % pm_count pn = pid // pm_count ps = tl.program_id(1) rm = pm * BM + tl.arange(0, BM) rn = pn * BN + tl.arange(0, BN) rk = tl.arange(0, BK) iterations: tl.constexpr = tr.cdiv(K, BK * SPLIT) kk = ps * iterations * BK + rk ap = A + rm[:, None] * AM + kk[None, :] * AK bp = B + kk[:, None] * BKSTR + rn[None, :] * BNSTR acc = tl.full((BM, BN), 0, tl.int32) for it in range(iterations): if K % (BK * SPLIT) == 0: av = tl.load(ap, rm[:, None] < M, other=0) bv = tl.load(bp, rn[None, :] < N, other=0) else: kval = kk + it * BK av = tl.load( ap, (rm[:, None] < M) & (kval[None, :] < K), other=0 ) bv = tl.load( bp, (kval[:, None] < K) & (rn[None, :] < N), other=0 ) acc = tl.dot(av, bv, acc, out_dtype=tl.int32) ap += BK * AK bp += BK * BKSTR offsets = rm[:, None] * N + rn[None, :] mask = (rm[:, None] < M) & (rn[None, :] < N) if SPLIT == 1: sa = tl.load(AS + rm * ASS, rm < M, other=0).to(tl.float32) sb = tl.load(BS + rn * BSS, rn < N, other=0).to(tl.float32) val = (acc.to(tl.float32) * sa[:, None]) * sb[None, :] tl.store(C + offsets, val.to(tl.bfloat16), mask) else: tl.store(C + ps * M * N + offsets, acc, mask) @tr.jit def _finish( P, AS, BS, C, M: tl.constexpr, N: tl.constexpr, ASS: tl.constexpr, BSS: tl.constexpr, SPLIT: tl.constexpr, BLOCK: tl.constexpr, ): x = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK) s = tl.arange(0, SPLIT) partial = tl.load( P + s[:, None] * (M * N) + x[None, :], x[None, :] < M * N, other=0, ) val = tl.sum(partial, axis=0).to(tl.float32) sa = tl.load(AS + (x // N) * ASS, x < M * N, other=0).to(tl.float32) sb = tl.load(BS + (x % N) * BSS, x < M * N, other=0).to(tl.float32) val = (val * sa) * sb tl.store(C + x, val.to(tl.bfloat16), x < M * N) def _config(mode, bm, bn, bk, split, warps, stages): return tr.Config( dict(MODE=mode, BM=bm, BN=bn, BK=bk, SPLIT=split), num_warps=warps, num_stages=stages, ) _native_config = _config(2, 32, 128, 128, 1, 4, 1) _gemv_default = _config(1, 1, 16, 256, 1, 4, 1) _configs = [_native_config] if _native_mm is not None else [] for bn, bk, nw in ( (8, 256, 4), (16, 128, 4), (16, 256, 4), (16, 512, 4), (32, 128, 4), (32, 256, 4), (32, 256, 8), (8, 1024, 4), ): _configs.append(_config(1, 1, bn, bk, 1, nw, 1)) for bm in (16, 32, 64, 128): nw = 8 if bm == 128 else 4 recipes = [ (64, 128, 4, 3), (128, 128, nw, 3), (64, 256, 4, 2), (128, 256, nw, 2), (128, 64, nw, 4), ] if bm <= 64: recipes.append((256, 128, 4 if bm <= 32 else 8, 3)) else: recipes.extend([(128, 128, 4, 3), (64, 128, 8, 3)]) for bn, bk, warps, stages in recipes: for split in (1, 2, 4, 8, 16): _configs.append(_config(0, bm, bn, bk, split, warps, stages)) def _prune(configs, named_args, **kwargs): p = dict(named_args) p.update(kwargs) m, n, k = p["M"], p["N"], p["K"] native_ok, gemv_ok = p["NATIVE_OK"], p["GEMV_OK"] if m <= 16: valid_bm = (16,) elif m <= 64: valid_bm = (32, 64) elif m <= 256: valid_bm = (64, 128) else: valid_bm = (128,) result = [] for cfg in configs: c = cfg.kwargs mode = c["MODE"] if mode == 2: if native_ok: result.append(cfg) continue if mode == 1: if gemv_ok: result.append(cfg) continue bm, bn, bk, split = c["BM"], c["BN"], c["BK"], c["SPLIT"] if bm not in valid_bm: continue if gemv_ok: if not ( bm == 16 and bn == 128 and bk == 128 and split in (4, 8) and cfg.num_stages == 3 ): continue if split > 1: if k < 2 * bk * split: continue blocks = tr.cdiv(m, bm) * tr.cdiv(n, bn) if blocks * split > 1056: continue if blocks * split < 96 and split < 8 and k >= 4096: continue result.append(cfg) return result class _GemmRunner: """A complete launch sequence, so tuning includes the split-K epilogue.""" arg_names = [ "A", "B", "AS", "BS", "C", "P", "M", "N", "K", "AM", "AK", "BKSTR", "BNSTR", "ASS", "BSS", "NATIVE_OK", "GEMV_OK", ] def __init__(self): self.fn = _mm def run( self, A, B, AS, BS, C, P, M, N, K, AM, AK, BKSTR, BNSTR, ASS, BSS, NATIVE_OK, GEMV_OK, **meta, ): mode = meta["MODE"] if mode == 2: return _native_mm(A, B, AS, BS, torch.bfloat16) bm, bn, bk = meta["BM"], meta["BN"], meta["BK"] warps, stages = meta["num_warps"], meta["num_stages"] if mode == 1: _gemv[(tr.cdiv(N, bn),)]( A, B, AS, BS, C, K, N, BNSTR, BSS, bn, bk, num_warps=warps, num_stages=1, ) return C split = meta["SPLIT"] dest = C if split == 1 else P _mm[(tr.cdiv(M, bm) * tr.cdiv(N, bn), split)]( A, B, AS, BS, dest, M, N, K, AM, AK, BKSTR, BNSTR, ASS, BSS, bm, bn, bk, split, num_warps=warps, num_stages=stages, ) if split != 1: _finish[(tr.cdiv(M * N, 1024),)]( P, AS, BS, C, M, N, ASS, BSS, split, 1024, num_warps=4, ) return C _runner = _GemmRunner() _tuned = tr.autotune( configs=_configs, key=[ "M", "N", "K", "AM", "AK", "BKSTR", "BNSTR", "ASS", "BSS", "NATIVE_OK", "GEMV_OK", ], prune_configs_by={"early_config_prune": _prune}, use_cuda_graph=True, rep=30, )(_runner) # Only launch configurations are retained; tensors and computed outputs are not. _selected = {} def _scale_stride(x): if x.numel() <= 1: return 0 if x.is_contiguous(): return 1 for d, sz in enumerate(x.shape): if sz > 1: return x.stride(d) return 0 def _basic_config(m, n, k): bm = min(128, max(16, tr.next_power_of_2(m))) blocks = tr.cdiv(m, bm) * tr.cdiv(n, 128) split = 1 target = 320 if m < 192 else 192 while blocks * split < target and split < 16 and k // split >= 1024: split *= 2 return _config(0, bm, 128, 128, split, 8 if bm == 128 else 4, 3) def int8_scaled_gemm(a, b, a_scale, b_scale): m, k = a.shape n = b.shape[1] if m == 0 or n == 0: return torch.empty((m, n), dtype=torch.bfloat16, device=a.device) am, ak = a.stride() bks, bns = b.stride() ass, bss = _scale_stride(a_scale), _scale_stride(b_scale) gemv_ok = ( m == 1 and k % 4 == 0 and ak == 1 and bks == 1 and bns % 4 == 0 and a.storage_offset() % 4 == 0 and b.storage_offset() % 4 == 0 ) native_ok = ( _native_mm is not None and k > 0 and k % 16 == 0 and n % 16 == 0 and am == k and ak == 1 and bks == 1 and bns == k and a.storage_offset() % 16 == 0 and b.storage_offset() % 16 == 0 and a_scale.dtype == torch.float32 and b_scale.dtype == torch.float32 and a_scale.is_contiguous() and b_scale.is_contiguous() and a_scale.numel() == m and b_scale.numel() == n ) parameters = ( m, n, k, am, ak, bks, bns, ass, bss, native_ok, gemv_ok ) key = parameters + ( a.device, a.dtype, b.dtype, a_scale.dtype, b_scale.dtype ) cfg = _selected.get(key) if cfg is None and not torch.cuda.is_current_stream_capturing(): out = torch.empty((m, n), dtype=torch.bfloat16, device=a.device) named = dict(zip(_runner.arg_names[6:], parameters)) active = _prune(_configs, named) max_split = max( (c.kwargs["SPLIT"] for c in active if c.kwargs["MODE"] == 0), default=1, ) scratch = ( torch.empty((max_split, m, n), dtype=torch.int32, device=a.device) if max_split > 1 else out ) result = _tuned.run(a, b, a_scale, b_scale, out, scratch, *parameters) _selected[key] = _tuned.best_config return result if cfg is None: if gemv_ok: cfg = _gemv_default elif native_ok: cfg = _native_config else: cfg = _basic_config(m, n, k) _selected[key] = cfg if cfg.kwargs["MODE"] == 2: return _native_mm(a, b, a_scale, b_scale, torch.bfloat16) out = torch.empty((m, n), dtype=torch.bfloat16, device=a.device) split = cfg.kwargs["SPLIT"] scratch = ( torch.empty((split, m, n), dtype=torch.int32, device=a.device) if cfg.kwargs["MODE"] == 0 and split > 1 else out ) return _runner.run( a, b, a_scale, b_scale, out, scratch, *parameters, **cfg.all_kwargs(), )