fl2va_int8_convrot/hyperflow_h3_flash_int8.py
19.4 KB · 411 lines · python Raw
1 # Copyright 2026 The HyperFlow authors. Licensed under the Apache License, Version 2.0.
2 """INT8 W8A8 linears with a Hadamard-rotated input dimension.
3
4 A dense ``y = x @ W^T`` is stored as ``qweight = round(W R / wscale)`` (int8, one fp32 scale per output channel), where
5 ``R`` is a block-diagonal regular Hadamard of size ``group``. ``R`` is orthonormal, so ``y = (x R) @ (W R)^T``: at run
6 time the activation is rotated and quantized per token, multiplied in int8 with an exact int32 accumulator, and
7 rescaled. The rotation spreads outlier channels across the group, which is what makes per-token int8 activations work.
8
9 On CUDA the rotation + quantization and the GEMM are Triton kernels (compiled on first use). Every kernel fits the
10 99 KiB of shared memory per block of Ampere, Ada and consumer Blackwell GPUs. The int8 GEMM runs as a Triton kernel or
11 as cuBLASLt (``torch._int_mm``) plus a Triton epilogue; both use the same int32 accumulator and the same fp32 multiply
12 order, so they give bitwise identical outputs. cuBLASLt is faster from compute capability 10 on, Triton on Hopper.
13 The B300 (compute capability 10.3) has INT8 tensor cores at about 1/20 of the B200's, so there the int8 codes are
14 multiplied on bf16 tensor cores into an fp32 accumulator: products are exact, and the sum matches the int32 one while
15 it stays below 2**24, which the rotated activations keep well clear of.
16 Elsewhere a plain torch implementation of the same scheme runs.
17
18 `KERNEL_OPTIONS` (set by `load_pipeline`, no weight change) picks the kernels at run time:
19
20 * ``int8_gemm``: ``"auto"`` (the choice above), ``"triton"``, ``"cublas"``, ``"bf16"``, or ``"sgl"``: CUTLASS
21 ``sgl_kernel.int8_scaled_mm`` with the scales in its epilogue, within 1 ulp of Triton and 1.25 to 1.45x faster on
22 H200 (Triton when sgl_kernel is missing).
23 * ``rotate_quant``: ``"dense"`` (the kernel above) or ``"factored"``: a 256-channel group rotated as ``H16 X H16``, two
24 K = 16 dots in 8.5 KiB of shared memory, 1.6 to 2.0x faster on H200; it rounds the rotated activation like the dense
25 kernel up to rare one-code differences.
26 """
27
28 from __future__ import annotations
29
30 import functools
31 from types import SimpleNamespace
32 from typing import Any, ClassVar
33
34 import torch
35 from torch import Tensor, nn
36
37 #: Run-time kernel choices.
38 INT8_GEMMS = ("auto", "triton", "cublas", "sgl", "bf16")
39 ROTATE_QUANTS = ("dense", "factored")
40
41 #: Rows below this go through the torch path: `torch._int_mm` needs more than 16 rows, and so few rows are not worth
42 #: a kernel launch.
43 _MIN_KERNEL_ROWS = 17
44
45 #: Run-time kernel choices for every `Int8RotLinear`; `load_pipeline` sets them.
46 KERNEL_OPTIONS: dict[str, Any] = {"int8_gemm": "auto", "rotate_quant": "dense"}
47
48
49 def set_kernel_options(*, int8_gemm: str | None = None, rotate_quant: str | None = None) -> None:
50 if int8_gemm is not None:
51 if int8_gemm not in INT8_GEMMS:
52 raise ValueError(f"int8_gemm must be one of {INT8_GEMMS}, got {int8_gemm!r}")
53 KERNEL_OPTIONS["int8_gemm"] = int8_gemm
54 if rotate_quant is not None:
55 if rotate_quant not in ROTATE_QUANTS:
56 raise ValueError(f"rotate_quant must be one of {ROTATE_QUANTS}, got {rotate_quant!r}")
57 KERNEL_OPTIONS["rotate_quant"] = rotate_quant
58
59
60 @functools.cache
61 def _sgl_int8_scaled_mm():
62 """sgl_kernel's ``int8_scaled_mm``, or None when sgl_kernel is not importable."""
63 try:
64 from sgl_kernel import int8_scaled_mm
65 except ImportError:
66 return None
67 return int8_scaled_mm
68
69
70 def _has_bf16_mm() -> bool:
71 # `torch.mm(..., out_dtype=)` is PyTorch 2.8+.
72 return tuple(int(v) for v in torch.__version__.split(".")[:2]) >= (2, 8)
73
74
75 @functools.cache
76 def _auto_int8_gemm(device: torch.device) -> str:
77 capability = torch.cuda.get_device_capability(device)
78 if capability == (10, 3) and _has_bf16_mm():
79 return "bf16"
80 if hasattr(torch, "_int_mm") and capability[0] >= 10:
81 return "cublas"
82 return "triton"
83
84
85 def resolve_int8_gemm(device: torch.device) -> str:
86 """The GEMM ``KERNEL_OPTIONS["int8_gemm"]`` runs as on ``device``: ``"triton"``, ``"cublas"``, ``"bf16"`` or
87 ``"sgl"``."""
88 choice = KERNEL_OPTIONS["int8_gemm"]
89 if choice == "auto":
90 return _auto_int8_gemm(device)
91 if (
92 (choice == "sgl" and _sgl_int8_scaled_mm() is None)
93 or (choice == "cublas" and not hasattr(torch, "_int_mm"))
94 or (choice == "bf16" and not _has_bf16_mm())
95 ):
96 return "triton"
97 return choice
98
99
100 @functools.cache
101 def regular_hadamard(group: int) -> Tensor:
102 """``kron(H4 / 2, ..., H4 / 2)`` of size ``group`` (a power of 4): orthonormal, symmetric, rows sum to one."""
103 h4 = torch.tensor([[1, 1, 1, -1], [1, 1, -1, 1], [1, -1, 1, 1], [-1, 1, 1, 1]], dtype=torch.float64) / 2
104 h, n = torch.ones(1, 1, dtype=torch.float64), 1
105 while n < group:
106 h, n = torch.kron(h, h4), n * 4
107 if n != group:
108 raise ValueError(f"Hadamard group {group} is not a power of 4")
109 return h.float()
110
111
112 def hadamard_factors(group: int) -> tuple[int, int] | None:
113 """``(GA, GB)`` with ``regular_hadamard(group) == kron(regular_hadamard(GA), regular_hadamard(GB))``, both at
114 least 16 (the smallest bf16 ``tl.dot`` K); None when ``group`` cannot be split that way."""
115 n = group.bit_length() - 1
116 if group < 256 or group != 1 << n or n % 2:
117 return None
118 ga = 4 ** (n // 4)
119 return ga, group // ga
120
121
122 @functools.cache
123 def _rotation(group: int, device: torch.device) -> Tensor:
124 return regular_hadamard(group).to(device=device, dtype=torch.bfloat16)
125
126
127 class Int8RotLinear(nn.Module):
128 """Bias-free W8A8 linear: ``y = (q(x R) @ qweight^T) * s_x * wscale``, ``R = blockdiag(regular Hadamard)``.
129
130 Linears that read one input (``to_q``, ``to_k``, ``to_v``) quantize it once: a layer with ``keep_input = True``
131 leaves its quantized input for the next layer, which reuses it if it receives the exact same, unmodified tensor.
132 Any other layer clears it, so nothing outlives the projections.
133 """
134
135 _last_input: ClassVar[dict[str, Any]] = {}
136
137 def __init__(self, in_features: int, out_features: int, group: int) -> None:
138 super().__init__()
139 if in_features % group:
140 raise ValueError(f"in_features {in_features} is not a multiple of the Hadamard group {group}")
141 self.in_features, self.out_features, self.group = in_features, out_features, group
142 self.keep_input = False
143 # Parameters, not buffers: diffusers' streamed group offloading moves module buffers on but never back off.
144 self.qweight = nn.Parameter(torch.zeros(out_features, in_features, dtype=torch.int8), requires_grad=False)
145 self.wscale = nn.Parameter(torch.ones(out_features, dtype=torch.float32), requires_grad=False)
146
147 def extra_repr(self) -> str:
148 return f"in_features={self.in_features}, out_features={self.out_features}, group={self.group}"
149
150 def _quantize(self, x: Tensor, x2: Tensor, kernels: SimpleNamespace) -> tuple[Tensor, Tensor]:
151 cache = Int8RotLinear._last_input
152 # Inference tensors (`torch.inference_mode`) have no version counter.
153 version = None if x.is_inference() else x._version
154 hit = cache.get("x") is x and cache.get("version") == version and cache.get("group") == self.group
155 quantized = cache["value"] if hit else kernels.rotate_quant(x2, self.group)
156 cache.clear()
157 if self.keep_input:
158 cache.update(x=x, version=version, group=self.group, value=quantized)
159 return quantized
160
161 def forward(self, x: Tensor) -> Tensor:
162 shape = x.shape
163 x2 = x.reshape(-1, self.in_features).to(torch.bfloat16).contiguous()
164 kernels = _kernels() if x2.is_cuda and x2.shape[0] >= _MIN_KERNEL_ROWS else None
165 if kernels is None:
166 Int8RotLinear._last_input.clear()
167 y = self._forward_torch(x2, _rotation(self.group, x2.device))
168 else:
169 xq, sx = self._quantize(x, x2, kernels)
170 y = kernels.int8_matmul(xq, self.qweight, sx, self.wscale)
171 return y.reshape(*shape[:-1], self.out_features).to(x.dtype)
172
173 def _forward_torch(self, x2: Tensor, rot: Tensor) -> Tensor:
174 """The same scheme in plain torch; the rotated activation is rounded to bf16 before quantization."""
175 g = self.group
176 xr = (x2.reshape(-1, self.in_features // g, g) @ rot).reshape(x2.shape).float()
177 sx = xr.abs().amax(1, keepdim=True).clamp_min(1e-12) / 127.0
178 xq = (xr / sx).round().clamp(-127, 127)
179 return ((xq @ self.qweight.float().t()) * sx * self.wscale[None, :]).to(torch.bfloat16)
180
181
182 @functools.cache
183 def _kernels() -> SimpleNamespace | None:
184 """``rotate_quant`` and ``int8_matmul`` as Triton kernels; ``None`` when Triton is not installed."""
185 try:
186 import triton
187 import triton.language as tl
188 except ImportError:
189 return None
190
191 ROTATE_BM = 64
192 FACTORED_BM = 16
193
194 @triton.jit
195 def rotate_quant_kernel(
196 x_ptr, h_ptr, q_ptr, s_ptr, M, K, stride_xm, stride_qm,
197 G: tl.constexpr, BM: tl.constexpr, BN: tl.constexpr,
198 ): # fmt: skip
199 # Two passes over the row block: the per-token scale needs the absmax of the whole rotated row first.
200 # The Hadamard streams through in G x BN column tiles, so shared memory is (BM * G + G * BN) * 2 bytes.
201 rows = tl.program_id(0) * BM + tl.arange(0, BM)
202 rows64 = rows.to(tl.int64)
203 cols = tl.arange(0, G)
204 tile = tl.arange(0, BN)
205 rmask = rows < M
206 amax = tl.zeros((BM,), dtype=tl.float32)
207 for g in range(0, K, G):
208 x = tl.load(x_ptr + rows64[:, None] * stride_xm + (g + cols)[None, :], mask=rmask[:, None], other=0.0)
209 for n in range(0, G, BN):
210 h = tl.load(h_ptr + cols[:, None] * G + (n + tile)[None, :])
211 amax = tl.maximum(amax, tl.max(tl.abs(tl.dot(x, h)), axis=1))
212 scale = tl.maximum(amax, 1e-12) / 127.0
213 tl.store(s_ptr + rows, scale, mask=rmask)
214 inv = 1.0 / scale
215 for g in range(0, K, G):
216 x = tl.load(x_ptr + rows64[:, None] * stride_xm + (g + cols)[None, :], mask=rmask[:, None], other=0.0)
217 for n in range(0, G, BN):
218 h = tl.load(h_ptr + cols[:, None] * G + (n + tile)[None, :])
219 q = tl.extra.cuda.libdevice.rint(tl.dot(x, h) * inv[:, None])
220 q = tl.minimum(tl.maximum(q, -127.0), 127.0).to(tl.int8)
221 tl.store(q_ptr + rows64[:, None] * stride_qm + (g + n + tile)[None, :], q, mask=rmask[:, None])
222
223 @triton.jit
224 def rotate_quant_factored_kernel(
225 x_ptr, ha_ptr, hb_ptr, q_ptr, s_ptr, M, K, stride_xm, stride_qm,
226 GA: tl.constexpr, GB: tl.constexpr, BM: tl.constexpr,
227 ): # fmt: skip
228 # Channel g + a * GB + b of a group is X[a, b]; the rotated group is H_GA X H_GB. Pass 0 takes the row absmax,
229 # pass 1 rotates again and writes int8. The fp32 input of the second dot is split into three bf16 terms
230 # (8 + 8 + 8 significand bits), so it is exact; a tf32 dot or a two-term split rounds it measurably.
231 # The second dot is batched per row, so its result is already in channel order.
232 G: tl.constexpr = GA * GB
233 rows = tl.program_id(0) * BM + tl.arange(0, BM)
234 rows64 = rows.to(tl.int64)
235 cols = tl.arange(0, G)
236 rmask = rows < M
237 ia = tl.arange(0, GA)
238 ib = tl.arange(0, GB)
239 ha = tl.broadcast_to(tl.load(ha_ptr + ia[:, None] * GA + ia[None, :])[None, :, :], (BM, GA, GA))
240 hb = tl.load(hb_ptr + ib[:, None] * GB + ib[None, :])
241 amax = tl.zeros((BM,), dtype=tl.float32)
242 inv = tl.zeros((BM,), dtype=tl.float32)
243 for p in tl.static_range(2):
244 for g in range(0, K, G):
245 x = tl.load(x_ptr + rows64[:, None] * stride_xm + (g + cols)[None, :], mask=rmask[:, None], other=0.0)
246 z = tl.reshape(tl.dot(tl.reshape(x, (BM * GA, GB)), hb), (BM, GA, GB))
247 z_hi = z.to(tl.bfloat16)
248 z = z - z_hi.to(tl.float32)
249 z_mid = z.to(tl.bfloat16)
250 z_lo = (z - z_mid.to(tl.float32)).to(tl.bfloat16)
251 y = tl.dot(ha, z_lo, acc=tl.dot(ha, z_mid, acc=tl.dot(ha, z_hi)))
252 y = tl.reshape(y, (BM, G))
253 if p == 0:
254 amax = tl.maximum(amax, tl.max(tl.abs(y), axis=1))
255 else:
256 q = tl.extra.cuda.libdevice.rint(y * inv[:, None])
257 q = tl.minimum(tl.maximum(q, -127.0), 127.0).to(tl.int8)
258 tl.store(q_ptr + rows64[:, None] * stride_qm + (g + cols)[None, :], q, mask=rmask[:, None])
259 if p == 0:
260 scale = tl.maximum(amax, 1e-12) / 127.0
261 tl.store(s_ptr + rows, scale, mask=rmask)
262 inv = 1.0 / scale
263
264 @functools.cache
265 def rotate_tile(device_index: int, group: int) -> int:
266 # At group 256, 128 columns take 96 KiB: that fits every GPU from Ampere on (99 KiB per block).
267 shared = triton.runtime.driver.active.utils.get_device_properties(device_index)["max_shared_mem"]
268 tile = 128 if (ROTATE_BM * group + group * 128) * 2 <= shared else 64
269 return min(tile, group)
270
271 configs = [
272 triton.Config({"BM": bm, "BN": bn, "BK": bk, "GROUP_M": 8}, num_stages=stages, num_warps=warps)
273 for bm, bn, bk, stages, warps in [
274 (128, 256, 128, 3, 8),
275 (256, 128, 128, 3, 8),
276 (128, 128, 128, 4, 8),
277 (128, 256, 64, 4, 8),
278 (256, 128, 64, 4, 8),
279 (128, 128, 64, 5, 4),
280 ]
281 ]
282
283 @triton.autotune(configs=configs, key=["M_BUCKET", "N", "K"])
284 @triton.jit
285 def int8_mm_kernel(
286 a_ptr, b_ptr, c_ptr, sa_ptr, sb_ptr, M, N, K, M_BUCKET, stride_am, stride_bn, stride_cm,
287 BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr, GROUP_M: tl.constexpr,
288 ): # fmt: skip
289 pid = tl.program_id(0)
290 num_m = tl.cdiv(M, BM)
291 num_n = tl.cdiv(N, BN)
292 group = GROUP_M * num_n
293 first_m = (pid // group) * GROUP_M
294 size_m = tl.minimum(num_m - first_m, GROUP_M)
295 pid_m = first_m + (pid % group) % size_m
296 pid_n = (pid % group) // size_m
297 rm = pid_m * BM + tl.arange(0, BM)
298 rn = pid_n * BN + tl.arange(0, BN)
299 rk = tl.arange(0, BK)
300 a_ptrs = a_ptr + rm.to(tl.int64)[:, None] * stride_am + rk[None, :]
301 b_ptrs = b_ptr + rn.to(tl.int64)[None, :] * stride_bn + rk[:, None]
302 acc = tl.zeros((BM, BN), dtype=tl.int32)
303 for k in range(0, K, BK):
304 a = tl.load(a_ptrs, mask=(rm[:, None] < M) & (k + rk[None, :] < K), other=0)
305 b = tl.load(b_ptrs, mask=(rn[None, :] < N) & (k + rk[:, None] < K), other=0)
306 acc += tl.dot(a, b, out_dtype=tl.int32)
307 a_ptrs += BK
308 b_ptrs += BK
309 sa = tl.load(sa_ptr + rm, mask=rm < M, other=0.0)
310 sb = tl.load(sb_ptr + rn, mask=rn < N, other=0.0)
311 c = (acc.to(tl.float32) * sa[:, None] * sb[None, :]).to(tl.bfloat16)
312 mask = (rm[:, None] < M) & (rn[None, :] < N)
313 tl.store(c_ptr + rm.to(tl.int64)[:, None] * stride_cm + rn[None, :], c, mask=mask)
314
315 @triton.jit
316 def rescale_kernel(acc_ptr, sa_ptr, sb_ptr, c_ptr, M, N, BM: tl.constexpr, BN: tl.constexpr):
317 rm = tl.program_id(0) * BM + tl.arange(0, BM)
318 rn = tl.program_id(1) * BN + tl.arange(0, BN)
319 mask = (rm[:, None] < M) & (rn[None, :] < N)
320 offsets = rm.to(tl.int64)[:, None] * N + rn[None, :]
321 acc = tl.load(acc_ptr + offsets, mask=mask, other=0)
322 sa = tl.load(sa_ptr + rm, mask=rm < M, other=0.0)
323 sb = tl.load(sb_ptr + rn, mask=rn < N, other=0.0)
324 tl.store(c_ptr + offsets, (acc.to(tl.float32) * sa[:, None] * sb[None, :]).to(tl.bfloat16), mask=mask)
325
326 def rotate_quant(x: Tensor, group: int) -> tuple[Tensor, Tensor]:
327 M, K = x.shape
328 q = torch.empty(M, K, device=x.device, dtype=torch.int8)
329 s = torch.empty(M, device=x.device, dtype=torch.float32)
330 factors = hadamard_factors(group) if KERNEL_OPTIONS["rotate_quant"] == "factored" else None
331 if factors is not None:
332 ga, gb = factors
333 ha, hb = _rotation(ga, x.device), _rotation(gb, x.device)
334 rotate_quant_factored_kernel[(triton.cdiv(M, FACTORED_BM),)](
335 x, ha, hb, q, s, M, K, x.stride(0), q.stride(0), GA=ga, GB=gb, BM=FACTORED_BM, num_warps=4,
336 num_stages=4,
337 ) # fmt: skip
338 return q, s
339 BN = rotate_tile(x.device.index, group)
340 rotate_quant_kernel[(triton.cdiv(M, ROTATE_BM),)](
341 x, _rotation(group, x.device), q, s, M, K, x.stride(0), q.stride(0), G=group, BM=ROTATE_BM, BN=BN,
342 num_warps=8, num_stages=1,
343 ) # fmt: skip
344 return q, s
345
346 def matmul_triton(a: Tensor, b: Tensor, sa: Tensor, sb: Tensor, c: Tensor) -> None:
347 M, K = a.shape
348 N = b.shape[0]
349 grid = lambda meta: (triton.cdiv(M, meta["BM"]) * triton.cdiv(N, meta["BN"]),) # noqa: E731
350 m_bucket = 1 << max(M - 1, 1).bit_length()
351 int8_mm_kernel[grid](a, b, c, sa, sb, M, N, K, m_bucket, a.stride(0), b.stride(0), c.stride(0))
352
353 def matmul_cublas(a: Tensor, b: Tensor, sa: Tensor, sb: Tensor, c: Tensor) -> None:
354 # Row chunks keep the int32 accumulator near 1 GiB.
355 M, N = a.shape[0], b.shape[0]
356 chunk = max(128, ((1 << 28) // N) // 128 * 128)
357 for start in range(0, M, chunk):
358 stop = min(M, start + chunk)
359 if stop - start < _MIN_KERNEL_ROWS:
360 matmul_triton(a[start:stop], b, sa[start:stop], sb, c[start:stop])
361 continue
362 acc = torch._int_mm(a[start:stop], b.t())
363 grid = (triton.cdiv(stop - start, 64), triton.cdiv(N, 128))
364 rescale_kernel[grid](acc, sa[start:stop], sb, c[start:stop], stop - start, N, BM=64, BN=128, num_warps=8)
365
366 def matmul_bf16(a: Tensor, b: Tensor, sa: Tensor, sb: Tensor, c: Tensor) -> None:
367 M, N = a.shape[0], b.shape[0]
368 weight = b.to(torch.bfloat16)
369 chunk = max(128, ((1 << 28) // N) // 128 * 128)
370 for start in range(0, M, chunk):
371 stop = min(M, start + chunk)
372 acc = torch.mm(a[start:stop].to(torch.bfloat16), weight.t(), out_dtype=torch.float32)
373 grid = (triton.cdiv(stop - start, 64), triton.cdiv(N, 128))
374 rescale_kernel[grid](acc, sa[start:stop], sb, c[start:stop], stop - start, N, BM=64, BN=128, num_warps=8)
375
376 def int8_matmul(a: Tensor, b: Tensor, sa: Tensor, sb: Tensor) -> Tensor:
377 M, K = a.shape
378 N = b.shape[0]
379 gemm = resolve_int8_gemm(a.device)
380 if gemm == "sgl" and K % 16 == 0 and N % 16 == 0:
381 # b is the [N, K] row-major qweight; its transpose is the column-major [K, N] operand CUTLASS expects.
382 return _sgl_int8_scaled_mm()(a, b.t(), sa, sb, torch.bfloat16)
383 c = torch.empty(M, N, device=a.device, dtype=torch.bfloat16)
384 if gemm == "bf16":
385 matmul_bf16(a, b, sa, sb, c)
386 elif gemm == "cublas" and K % 8 == 0 and N % 8 == 0:
387 matmul_cublas(a, b, sa, sb, c)
388 else:
389 matmul_triton(a, b, sa, sb, c)
390 return c
391
392 jit = SimpleNamespace(
393 rotate_quant=rotate_quant_kernel,
394 rotate_quant_factored=rotate_quant_factored_kernel,
395 int8_mm=int8_mm_kernel,
396 rescale=rescale_kernel,
397 )
398 return SimpleNamespace(rotate_quant=rotate_quant, int8_matmul=int8_matmul, jit=jit, rotate_tile=rotate_tile)
399
400
401 __all__ = [
402 "INT8_GEMMS",
403 "KERNEL_OPTIONS",
404 "ROTATE_QUANTS",
405 "Int8RotLinear",
406 "hadamard_factors",
407 "regular_hadamard",
408 "resolve_int8_gemm",
409 "set_kernel_options",
410 ]
411