"""Grouped GEMMs. Imported only on CUDA; CPU uses the reference path. Weights are [expert, output, input]. A single FP8 copy services both forward and transposed input-gradient GEMMs. Ampere uses INT8 storage with BF16 tile dequantization and BF16 tensor cores. No full expert dequantization is used. """ import torch import triton import triton.language as tl @triton.jit def _row_quant(X, Q, S, K: tl.constexpr, LIMIT: tl.constexpr, BLOCK: tl.constexpr): row = tl.program_id(0) col = tl.arange(0, BLOCK) x = tl.load(X + row*K + col, col < K, 0).to(tl.float32) scale = tl.maximum(tl.max(tl.abs(x), 0)/LIMIT, 1.e-12) tl.store(S + row, scale) tl.store(Q + row*K + col, tl.minimum(tl.maximum(x/scale, -LIMIT), LIMIT), col < K) def row_quantize(x, backward=False): x = x.contiguous() dtype = torch.float8_e5m2 if backward else torch.float8_e4m3fn q = torch.empty_like(x, dtype=dtype) scales = torch.empty(x.shape[0], device=x.device, dtype=torch.float32) _row_quant[(x.shape[0],)](x, q, scales, x.shape[1], 57344. if backward else 448., triton.next_power_of_2(x.shape[1])) return q, scales @triton.jit def _grouped(X, W, Y, OFF, TILES, MAP, XS, WS, N: tl.constexpr, K: tl.constexpr, WN: tl.constexpr, WK: tl.constexpr, E: tl.constexpr, EP: tl.constexpr, TRANSPOSE: tl.constexpr, ADAPTER: tl.constexpr, FP8: tl.constexpr, INT8: tl.constexpr, PACKED: tl.constexpr, BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr): tile = tl.program_id(0) es = tl.arange(0, EP) ends = tl.load(TILES + es, es < E, 0) expert = tl.sum(((es < E) & (tile >= ends)).to(tl.int32), 0) if expert < E: prev_tile = tl.load(TILES + expert - 1, expert > 0, 0) start = tl.load(OFF + expert - 1, expert > 0, 0) end = tl.load(OFF + expert) wi = tl.load(MAP + expert) if ADAPTER else expert rows = start + (tile-prev_tile)*BM + tl.arange(0, BM) cols = tl.program_id(1)*BN + tl.arange(0, BN) ks = tl.arange(0, BK) acc = tl.full((BM, BN), 0, tl.float32) if wi >= 0: if INT8: wscale = tl.load(WS + expert) for part in range(tl.cdiv(K, BK)): kk = part*BK + ks a = tl.load(X + rows[:, None]*K + kk[None, :], (rows[:, None] < end) & (kk[None, :] < K), 0.) if TRANSPOSE: ptr = W + wi*WN*WK + kk[:, None]*WK + cols[None, :] else: ptr = W + wi*WN*WK + cols[None, :]*WK + kk[:, None] b = tl.load(ptr, (kk[:, None] < K) & (cols[None, :] < N), 0.) if PACKED: bits = b.to(tl.uint16) exponent = (bits >> 3) & 15 mantissa = bits & 7 normal = (((exponent + 8) << 10) | (mantissa << 7)).to(tl.uint16).to(tl.float16, bitcast=True) magnitude = tl.where(exponent == 0, mantissa.to(tl.float32) / 512., normal.to(tl.float32)) b = tl.where((bits & 128) != 0, -magnitude, magnitude) if not FP8: a = a.to(tl.bfloat16) b = (b.to(tl.float32)*wscale).to(tl.bfloat16) if INT8 else b.to(tl.bfloat16) acc += tl.dot(a, b) if PACKED: acc *= tl.load(WS + expert) if FP8: xscale = tl.load(XS + rows, rows < end, 0) wscale = tl.load(WS + expert) acc *= xscale[:, None]*wscale tl.store(Y + rows[:, None]*N + cols[None, :], acc, (rows[:, None] < end) & (cols[None, :] < N)) def grouped(x, weight, offsets, mapping=None, transpose=False, scales=None, backward=False): m, k = x.shape e = offsets.numel() wn, wk = weight.shape[1:] n = wk if transpose else wn assert k == (wn if transpose else wk) bm, bn, bk = 32, 64, 64 starts = torch.cat([offsets.new_zeros(1), offsets[:-1]]) tiles = ((offsets-starts+bm-1)//bm).cumsum(0).to(torch.int32) y = torch.empty((m, n), device=x.device, dtype=torch.bfloat16) xscale = None fp8 = scales is not None and weight.dtype == torch.float8_e4m3fn int8 = scales is not None and weight.dtype == torch.int8 packed = scales is not None and weight.dtype == torch.uint8 if scales is not None and not (fp8 or int8 or packed): raise ValueError(f"Unsupported quantized expert dtype: {weight.dtype}") if fp8: x, xscale = row_quantize(x, backward=backward) else: x = x.contiguous() # No CPU synchronization for the exact tile count. Upper bound adds at most E inactive tiles. _grouped[(triton.cdiv(m, bm)+e, triton.cdiv(n, bn))]( x, weight, y, offsets, tiles, mapping, xscale, scales, n, k, wn, wk, e, triton.next_power_of_2(e), transpose, mapping is not None, fp8, int8, packed, bm, bn, bk, num_warps=4) return y @triton.jit def _wgrad(X, DY, DW, OFF, SELECTED, N: tl.constexpr, K: tl.constexpr, BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr): si = tl.program_id(0) expert = tl.load(SELECTED + si) start = tl.load(OFF + expert - 1, expert > 0, 0) end = tl.load(OFF + expert) ns = tl.program_id(1)*BN + tl.arange(0, BN) ks = tl.program_id(2)*BK + tl.arange(0, BK) rr = tl.arange(0, BM) acc = tl.full((BN, BK), 0, tl.float32) for pos in range(start, end, BM): rows = pos + rr dy = tl.load(DY + rows[None, :]*N + ns[:, None], (rows[None, :] < end) & (ns[:, None] < N), 0).to(tl.bfloat16) x = tl.load(X + rows[:, None]*K + ks[None, :], (rows[:, None] < end) & (ks[None, :] < K), 0).to(tl.bfloat16) acc += tl.dot(dy, x) tl.store(DW + si*N*K + ns[:, None]*K + ks[None, :], acc, (ns[:, None] < N) & (ks[None, :] < K)) def weight_gradient(x, dy, weight, offsets, selected): x, dy = x.contiguous(), dy.contiguous() s, n, k = weight.shape result = torch.empty_like(weight, dtype=torch.float32) _wgrad[(s, triton.cdiv(n, 32), triton.cdiv(k, 64))]( x, dy, result, offsets, selected, n, k, 32, 32, 64, num_warps=4) return result