Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio diffusion: cut the int8 ConvRot overhead (one rotation per shared input, SwiGLU fused into the down quant, factored rotation kernel) (#14982)

Daniel Han614305507d72
diff --git a/studio/backend/core/inference/diffusion_convrot_quant.py b/studio/backend/core/inference/diffusion_convrot_quant.py
index b2ccdd1d339..0e88ff4f60d 100644
--- a/studio/backend/core/inference/diffusion_convrot_quant.py
+++ b/studio/backend/core/inference/diffusion_convrot_quant.py
@@ -21,6 +21,15 @@ gives any other int8 consumer of a rotated activation the same codes.
Per-arch gate (``_ROTQ_CONFIG``): measured archs only; ``UNSLOTH_DIFFUSION_INT8_ROTQUANT=1`` (or
``UNSLOTH_DIFFUSION_INT8_GEMM=1``) also enables it on an unmeasured sm80+ part, still probe-gated. Kill switch
``UNSLOTH_DIFFUSION_INT8_ROTQUANT=0``; ``UNSLOTH_DIFFUSION_INT8_GEMM=0`` turns off the whole int8 Linear swap.
+
+H16 ROTATION (``rotq_h16``, default where ``rotq_i8`` passed): ``H256 = H16 (x) H16``, so a group rotates as
+``H16 . X . H16`` (one bf16 tensor-core dot, one fp32 dot): 32 multiply-adds per element instead of 256, bandwidth-bound
+everywhere. A different fp32 summation order: ~1 code in 10^6 differs by one step, scales equal; the probe gates it per
+device at that tolerance (``codes_close``). ``UNSLOTH_DIFFUSION_INT8_ROTQUANT_H16=0`` keeps the bit-identical dense kernel.
+
+SwiGLU PROLOGUE (``rotq_h16`` only): the down projection's codes come straight from the gate / value halves, the
+product computed in-kernel like the compiled stock MLP; the [M, hidden] HBM round trip was ConvRot's largest cost over
+plain int8 at Qwen-Image-2.1 1024px. Kill switch ``UNSLOTH_DIFFUSION_INT8_ROTQUANT_SWIGLU=0``.
"""
from __future__ import annotations
@@ -32,8 +41,11 @@ from typing import Any, Optional
from .rocm_bf16 import is_rocm_torch
INT8_ROTQUANT_ENV = "UNSLOTH_DIFFUSION_INT8_ROTQUANT"
+INT8_ROTQUANT_H16_ENV = "UNSLOTH_DIFFUSION_INT8_ROTQUANT_H16"
+INT8_ROTQUANT_SWIGLU_ENV = "UNSLOTH_DIFFUSION_INT8_ROTQUANT_SWIGLU"
_OP_NAMESPACE = "unsloth_studio"
_ROTQ_OP_NAME = "convrot_act_quant_int8"
+_SWIGLU_OP_NAME = "convrot_swiglu_act_quant_int8"
# (BLOCK_M group rows, BLOCK_K, num_warps, num_stages) per (major, minor); measured end to end. Absent = stock.
_ROTQ_CONFIG = {
@@ -62,6 +74,22 @@ _ROTQ_DEVICE_K: dict = {}
_ROTQ_CALLS = [0]
# Set once a device passed the probe; read by traced forwards (dynamo must not trace into the lru_cache'd registration).
_ROTQ_HANDLE: Any = None
+# device index -> passing rotq_h16 mode ("ieee" / "tf32x3"; falsy = dense rotq_i8) / SwiGLU probe result
+_H16_DEVICE: dict = {}
+_SWIGLU_DEVICE: dict = {}
+_H16_CALLS = [0]
+_SWIGLU_CALLS = [0]
+_SWIGLU_HANDLE: Any = None
+# 16 group rows per program: fastest (within 2%) on L4; 128 rows overflow 100 KB smem. One masked row per program at
+# K 12288 was 1.2x slower on A100 and spilled on B200.
+_H16_TILE_ROWS = 16
+_H16_WARPS = 4
+_H16_WARPS_TWO_PASS = 8
+# Second stage: tf32x3 (fp32-level error) where fp32 FMA rate is a fraction of tf32 (A100: 1.2x faster); sm89 / sm86 /
+# sm120 run fp32 FMAs at their tf32 rate, so they keep IEEE FMAs.
+_H16_TF32X3_ARCHS = ((8, 0), (9, 0), (10, 0), (10, 3))
+# max chunks per row to unroll (a longer unrolled row overflows sm100 TMEM)
+_H16_UNROLL_MAX = 4
def _env_mode(name: str) -> str:
@@ -78,6 +106,16 @@ def rotquant_enabled() -> bool:
return _env_mode(INT8_ROTQUANT_ENV) != "off"
+def rotquant_h16_enabled() -> bool:
+ """False only under ``UNSLOTH_DIFFUSION_INT8_ROTQUANT_H16=0`` (the dense, bit-identical ``rotq_i8``)."""
+ return _env_mode(INT8_ROTQUANT_H16_ENV) != "off"
+
+
+def rotquant_swiglu_enabled() -> bool:
+ """False only under ``UNSLOTH_DIFFUSION_INT8_ROTQUANT_SWIGLU=0``."""
+ return _env_mode(INT8_ROTQUANT_SWIGLU_ENV) != "off"
+
+
def rotquant_mode() -> str:
"""'off', 'force' or 'auto'. The int8 GEMM switch is the master: its ``0`` turns the whole swap off and its ``1``
forces this lever too."""
@@ -134,6 +172,13 @@ def _kernels() -> Optional[types.SimpleNamespace]:
def _rbf16(x):
return x.to(tl.bfloat16).to(tl.float32)
+ @triton.jit
+ def _swiglu_bf16(g, v):
+ # Inductor's silu(g) * v rounding. ATen's IEEE-divide form matched eager bitwise but was 1.5-2.3x slower on B200.
+ gf = g.to(tl.float32)
+ silu = _rbf16(gf * tl.sigmoid(gf))
+ return (silu * v.to(tl.float32)).to(tl.bfloat16)
+
@triton.jit
def rotq_i8(
x_ptr,
@@ -190,7 +235,207 @@ def _kernels() -> Optional[types.SimpleNamespace]:
srow = pid.to(tl.int64) * ROWS + j
tl.store(s_ptr + srow, s.to(s_ptr.dtype.element_ty), mask = (j < ROWS) & (srow < M))
- return types.SimpleNamespace(rotq_i8 = rotq_i8, triton = triton)
+ @triton.jit
+ def _h16_tile(
+ x_ptr,
+ v_ptr,
+ gidx,
+ live,
+ h,
+ h32,
+ TM: tl.constexpr,
+ SWIGLU: tl.constexpr,
+ TF32X3: tl.constexpr,
+ ):
+ # X[a, b] = x[16 a + b]; Y = X . H16 on tensor cores (H16 entries +-1/4: exact products), Z = H16 . Y in fp32.
+ offs = tl.arange(0, 256)
+ ptrs = gidx[:, None] * 256 + offs[None, :]
+ x = tl.load(x_ptr + ptrs, mask = live[:, None], other = 0.0)
+ if SWIGLU:
+ x = _swiglu_bf16(x, tl.load(v_ptr + ptrs, mask = live[:, None], other = 0.0))
+ y = tl.dot(tl.reshape(x, (TM * 16, 16)), h, out_dtype = tl.float32)
+ y = tl.reshape(tl.permute(tl.reshape(y, (TM, 16, 16)), (0, 2, 1)), (TM * 16, 16))
+ if TF32X3:
+ z = tl.dot(y, h32, input_precision = "tf32x3", out_dtype = tl.float32)
+ else:
+ z = tl.dot(y, h32, input_precision = "ieee", out_dtype = tl.float32)
+ z = tl.reshape(tl.permute(tl.reshape(z, (TM, 16, 16)), (0, 2, 1)), (TM, 256))
+ return _rbf16(z)
+
+ @triton.jit
+ def _h16_quant_store(
+ z,
+ inv_t,
+ q_ptr,
+ gidx,
+ live,
+ QMIN: tl.constexpr,
+ QMAX: tl.constexpr,
+ FP32_SCALE: tl.constexpr,
+ ):
+ offs = tl.arange(0, 256)
+ p = z * inv_t[:, None]
+ if not FP32_SCALE:
+ p = _rbf16(p)
+ p = libdevice.rint(p)
+ p = tl.minimum(tl.maximum(p, QMIN), QMAX)
+ tl.store(q_ptr + gidx[:, None] * 256 + offs[None, :], p.to(tl.int8), mask = live[:, None])
+
+ @triton.jit
+ def _h16_amax_chunk(
+ c,
+ amax,
+ x_ptr,
+ v_ptr,
+ row,
+ gl,
+ M,
+ NG,
+ h,
+ h32,
+ CG: tl.constexpr,
+ ROWS: tl.constexpr,
+ SWIGLU: tl.constexpr,
+ TF32X3: tl.constexpr,
+ ):
+ live = row < M
+ gidx = tl.where(live, row * NG + c * CG + gl, 0)
+ z = _h16_tile(x_ptr, v_ptr, gidx, live, h, h32, ROWS * CG, SWIGLU, TF32X3)
+ m = tl.where(live, tl.max(tl.abs(z), axis = 1), 0.0)
+ return tl.maximum(amax, tl.max(tl.reshape(m, (ROWS, CG)), axis = 1))
+
+ @triton.jit
+ def _h16_quant_chunk(
+ c,
+ inv_t,
+ x_ptr,
+ v_ptr,
+ q_ptr,
+ row,
+ gl,
+ M,
+ NG,
+ h,
+ h32,
+ CG: tl.constexpr,
+ ROWS: tl.constexpr,
+ SWIGLU: tl.constexpr,
+ TF32X3: tl.constexpr,
+ QMIN: tl.constexpr,
+ QMAX: tl.constexpr,
+ FP32_SCALE: tl.constexpr,
+ ):
+ live = row < M
+ gidx = tl.where(live, row * NG + c * CG + gl, 0)
+ z = _h16_tile(x_ptr, v_ptr, gidx, live, h, h32, ROWS * CG, SWIGLU, TF32X3)
+ _h16_quant_store(z, inv_t, q_ptr, gidx, live, QMIN, QMAX, FP32_SCALE)
+
+ @triton.jit
+ def rotq_h16(
+ x_ptr,
+ v_ptr,
+ h_ptr,
+ h32_ptr,
+ q_ptr,
+ s_ptr,
+ M,
+ NG,
+ NCH: tl.constexpr,
+ CG: tl.constexpr,
+ ROWS: tl.constexpr,
+ ONE_PASS: tl.constexpr,
+ UNROLL: tl.constexpr,
+ SWIGLU: tl.constexpr,
+ TF32X3: tl.constexpr,
+ QMIN: tl.constexpr,
+ QMAX: tl.constexpr,
+ DIV: tl.constexpr,
+ EPS: tl.constexpr,
+ FP32_SCALE: tl.constexpr,
+ ):
+ # ONE_PASS: rotate, amax, quantize from registers. Else an amax pass, then recompute + quant (row re-read from L2).
+ TM: tl.constexpr = ROWS * CG
+ pid = tl.program_id(0)
+ t = tl.arange(0, TM)
+ row = pid.to(tl.int64) * ROWS + t // CG
+ gl = t % CG
+ o16 = tl.arange(0, 16)
+ h = tl.load(h_ptr + o16[:, None] * 16 + o16[None, :])
+ h32 = tl.load(h32_ptr + o16[:, None] * 16 + o16[None, :])
+ if ONE_PASS:
+ live = row < M
+ gidx = tl.where(live, row * NG + gl, 0)
+ z = _h16_tile(x_ptr, v_ptr, gidx, live, h, h32, TM, SWIGLU, TF32X3)
+ m = tl.where(live, tl.max(tl.abs(z), axis = 1), 0.0)
+ amax = tl.max(tl.reshape(m, (ROWS, CG)), axis = 1)
+ else:
+ amax = tl.zeros((ROWS,), dtype = tl.float32)
+ if UNROLL:
+ for c in tl.static_range(NCH):
+ amax = _h16_amax_chunk(
+ c, amax, x_ptr, v_ptr, row, gl, M, NG, h, h32, CG, ROWS, SWIGLU, TF32X3
+ )
+ else:
+ for c in range(0, NCH):
+ amax = _h16_amax_chunk(
+ c, amax, x_ptr, v_ptr, row, gl, M, NG, h, h32, CG, ROWS, SWIGLU, TF32X3
+ )
+ # s = bf16(max(bf16(amax / DIV), EPS)), q = clamp(rint(bf16(z * bf16(1 / s)))), as rotq_i8
+ s = _rbf16(tl.maximum(_rbf16(libdevice.div_rn(amax, DIV)), EPS))
+ inv = libdevice.div_rn(tl.full((ROWS,), 1.0, tl.float32), s)
+ if not FP32_SCALE:
+ inv = _rbf16(inv)
+ inv_t = tl.reshape(tl.broadcast_to(inv[:, None], (ROWS, CG)), (TM,))
+ if ONE_PASS:
+ _h16_quant_store(z, inv_t, q_ptr, gidx, live, QMIN, QMAX, FP32_SCALE)
+ elif UNROLL:
+ for c in tl.static_range(NCH):
+ _h16_quant_chunk(
+ c,
+ inv_t,
+ x_ptr,
+ v_ptr,
+ q_ptr,
+ row,
+ gl,
+ M,
+ NG,
+ h,
+ h32,
+ CG,
+ ROWS,
+ SWIGLU,
+ TF32X3,
+ QMIN,
+ QMAX,
+ FP32_SCALE,
+ )
+ else:
+ for c in range(0, NCH):
+ _h16_quant_chunk(
+ c,
+ inv_t,
+ x_ptr,
+ v_ptr,
+ q_ptr,
+ row,
+ gl,
+ M,
+ NG,
+ h,
+ h32,
+ CG,
+ ROWS,
+ SWIGLU,
+ TF32X3,
+ QMIN,
+ QMAX,
+ FP32_SCALE,
+ )
+ srow = pid.to(tl.int64) * ROWS + tl.arange(0, ROWS)
+ tl.store(s_ptr + srow, s.to(s_ptr.dtype.element_ty), mask = srow < M)
+
+ return types.SimpleNamespace(rotq_i8 = rotq_i8, rotq_h16 = rotq_h16, triton = triton)
@lru_cache(maxsize = 1)
@@ -236,11 +481,25 @@ def act_quant_v1(x2d: Any) -> tuple:
return q, scale
-def rotquant_reference(x2d: Any, group: int, kind: str) -> tuple:
- """The stock path: ConvRotLinear.forward's rotation (bf16 GEMM), then torchao's activation quant. (int8, scale)."""
+def swiglu_reference(g2d: Any, v2d: Any) -> Any:
+ """The stock MLP's down-projection input: ``F.silu(gate) * value`` on bf16 (ATen, eager)."""
+ import torch.nn.functional as F
+ return F.silu(g2d) * v2d
+
+
+def rotquant_reference(
+ x2d: Any,
+ group: int,
+ kind: str,
+ v2d: Any = None,
+) -> tuple:
+ """The stock path: ConvRotLinear.forward's rotation (bf16 GEMM), then torchao's activation quant. (int8, scale).
+ ``v2d``: ``x2d`` is a SwiGLU gate and this the value; the rotated activation is ``swiglu_reference``'s product."""
import torch
from .diffusion_convrot import build_convrot_hadamard, rotate_convrot_activation
+ if v2d is not None:
+ x2d = swiglu_reference(x2d, v2d)
xr = rotate_convrot_activation(
x2d, build_convrot_hadamard(group, device = x2d.device, dtype = x2d.dtype), group
)
@@ -303,6 +562,75 @@ def _rotq_launch(x2d: Any, group: int, kind: str, cfg: tuple) -> tuple:
return q, s
+def _h16_plan(ng: int, tile_rows: int = _H16_TILE_ROWS) -> tuple:
+ """(groups per chunk CG, rows per program, chunks, one pass) for a row of ``ng`` 256-wide groups: CG the largest
+ power of two dividing ng (at most tile_rows), so every chunk is full and no lane is masked off on a live row; one
+ pass when CG == ng, else two (amax, then a recompute + quant)."""
+ cg = 1
+ while cg * 2 <= tile_rows and ng % (cg * 2) == 0:
+ cg *= 2
+ rows = max(1, tile_rows // cg)
+ return cg, rows, ng // cg, cg == ng
+
+
+def _h16_launch(
+ x2d: Any,
+ kind: str,
+ v2d: Any = None,
+ tile_rows: int = _H16_TILE_ROWS,
+ warps: Optional[int] = None,
+ tf32x3: Optional[bool] = None,
+) -> tuple:
+ """``rotq_h16`` on a contiguous bf16 ``[M, K]`` (K a multiple of 256): (int8 [M, K], scale [M]). ``v2d``: the
+ SwiGLU value half (``x2d`` the gate)."""
+ import torch
+ from .diffusion_convrot import build_convrot_hadamard
+
+ kern = _kernels()
+ m, k = x2d.shape
+ ng = k // 256
+ cg, rows, nch, one = _h16_plan(ng, tile_rows)
+ if tf32x3 is None:
+ tf32x3 = _H16_DEVICE.get(x2d.device.index) == "tf32x3"
+ if warps is None:
+ warps = _H16_WARPS if one else _H16_WARPS_TWO_PASS
+ qmin, qmax, div, eps = _ROTQ_QPARAMS[kind]
+ h = build_convrot_hadamard(16, device = x2d.device, dtype = torch.bfloat16)
+ h32 = build_convrot_hadamard(16, device = x2d.device, dtype = torch.float32)
+ fp32_scale = _rotq_scale_fp32(kind)
+ q = torch.empty((m, k), device = x2d.device, dtype = torch.int8)
+ s = torch.empty((m,), device = x2d.device, dtype = torch.float32 if fp32_scale else torch.bfloat16)
+ if m == 0:
+ return q, s
+ with torch.cuda.device(x2d.device):
+ kern.rotq_h16[(kern.triton.cdiv(m, rows),)](
+ x2d,
+ x2d if v2d is None else v2d,
+ h,
+ h32,
+ q,
+ s,
+ m,
+ ng,
+ nch,
+ CG = cg,
+ ROWS = rows,
+ ONE_PASS = one,
+ UNROLL = nch <= _H16_UNROLL_MAX,
+ SWIGLU = v2d is not None,
+ TF32X3 = bool(tf32x3),
+ QMIN = qmin,
+ QMAX = qmax,
+ DIV = div,
+ EPS = eps,
+ FP32_SCALE = fp32_scale,
+ num_warps = warps,
+ num_stages = 1,
+ enable_fp_fusion = False,
+ )
+ return q, s
+
+
def rotquant_supported(x2d: Any, group: int, cfg: Optional[tuple]) -> bool:
"""Shape / dtype / device / group gate of the fused kernel (anything else keeps the stock rotation + quant)."""
import torch
@@ -334,12 +662,50 @@ def rotq_tile_for(
return cfg
-def _rotq_run(x2d: Any, group: int, v2: bool) -> tuple:
- """Op body: the probed tile for this device and K, the stock rotation + quant if anything does not fit."""
+def _h16_ok(
+ x2d: Any,
+ group: int,
+ v2d: Any = None,
+) -> bool:
+ """``rotq_h16`` covers this call: its probe passed on the device (and the SwiGLU one for a gate / value pair)."""
+ import torch
+
+ index = x2d.device.index
+ return (
+ bool(_H16_DEVICE.get(index))
+ and (v2d is None or bool(_SWIGLU_DEVICE.get(index)))
+ and group == 256
+ and x2d.dim() == 2
+ and x2d.dtype == torch.bfloat16
+ and x2d.is_cuda
+ and x2d.shape[1] % 256 == 0
+ and x2d.shape[1] >= 256
+ )
+
+
+def _rotq_run(
+ x2d: Any,
+ group: int,
+ v2: bool,
+ v2d: Any = None,
+) -> tuple:
+ """Op body: ``rotq_h16`` where it passed its probe, else the probed dense tile for this device and K, else the stock
+ rotation + quant. ``v2d``: ``x2d`` is a SwiGLU gate and this its value half."""
_ROTQ_CALLS[0] += 1
kind = "v2" if v2 else "v1"
x2d = x2d if x2d.is_contiguous() else x2d.contiguous()
+ if v2d is not None:
+ v2d = v2d if v2d.is_contiguous() else v2d.contiguous()
+ _SWIGLU_CALLS[0] += 1
index = x2d.device.index
+ if _h16_ok(x2d, group, v2d):
+ try:
+ _H16_CALLS[0] += 1
+ return _h16_launch(x2d, kind, v2d)
+ except Exception: # noqa: BLE001 - a failed launch keeps the dense kernel / stock math
+ _H16_DEVICE[index] = False
+ if v2d is not None: # no dense SwiGLU kernel: the stock product, rotation and quant
+ return rotquant_reference(x2d, group, kind, v2d)
cfg = rotq_tile_for(index, x2d.shape[-1], group) if x2d.dim() == 2 else None
if rotquant_supported(x2d, group, cfg):
try:
@@ -349,7 +715,50 @@ def _rotq_run(x2d: Any, group: int, v2: bool) -> tuple:
_ROTQ_DEVICE_K[index] = () # drop the per-K tiles, keep the probed default
return _rotq_run(x2d, group, v2)
_ROTQ_DEVICE[index] = None
- return rotquant_reference(x2d, group, kind)
+ return rotquant_reference(x2d, group, kind, v2d)
+
+
+def _fake_quant(x: Any, v2: bool) -> tuple:
+ import torch
+ return (
+ x.new_empty((x.shape[0], x.shape[1]), dtype = torch.int8),
+ x.new_empty(
+ (x.shape[0],),
+ dtype = torch.float32 if _rotq_scale_fp32("v2" if v2 else "v1") else torch.bfloat16,
+ ),
+ )
+
+
+@lru_cache(maxsize = 1)
+def _swiglu_op() -> Any:
+ """``unsloth_studio::convrot_swiglu_act_quant_int8(gate, value, group, v2)``: the rotated, quantized
+ ``silu(gate) * value`` (opaque to Inductor), or None."""
+ try:
+ import torch
+ except Exception: # noqa: BLE001
+ return None
+ ns = getattr(torch.ops, _OP_NAMESPACE, None)
+ if ns is not None and hasattr(ns, _SWIGLU_OP_NAME):
+ return getattr(ns, _SWIGLU_OP_NAME)
+ custom_op = getattr(getattr(torch, "library", None), "custom_op", None)
+ if custom_op is None:
+ return None
+ try:
+
+ @custom_op(
+ f"{_OP_NAMESPACE}::{_SWIGLU_OP_NAME}",
+ mutates_args = (),
+ schema = "(Tensor gate, Tensor value, int group, bool v2) -> (Tensor, Tensor)",
+ )
+ def _convrot_swiglu_act_quant_int8(gate, value, group, v2):
+ return _rotq_run(gate, group, v2, value)
+
+ @_convrot_swiglu_act_quant_int8.register_fake
+ def _(gate, value, group, v2):
+ return _fake_quant(gate, v2)
+ except Exception: # noqa: BLE001
+ return None
+ return getattr(getattr(torch.ops, _OP_NAMESPACE), _SWIGLU_OP_NAME)
@lru_cache(maxsize = 1)
@@ -377,15 +786,7 @@ def _rotq_op() -> Any:
@_convrot_act_quant_int8.register_fake
def _(x, group, v2):
- return (
- x.new_empty((x.shape[0], x.shape[1]), dtype = torch.int8),
- x.new_empty(
- (x.shape[0],),
- dtype = torch.float32
- if _rotq_scale_fp32("v2" if v2 else "v1")
- else torch.bfloat16,
- ),
- )
+ return _fake_quant(x, v2)
except Exception: # noqa: BLE001
return None
return getattr(getattr(torch.ops, _OP_NAMESPACE), _ROTQ_OP_NAME)
@@ -393,8 +794,9 @@ def _rotq_op() -> Any:
def rotquant_device_config(index: int) -> Optional[tuple]:
"""Once per device: arch gate, then bit-exact codes and scales vs the stock path (v1, v2, outliers, zero row, ragged
- M). None = stock. A passing device also publishes the op handle the traced forwards call."""
- global _ROTQ_HANDLE
+ M). None = stock. A passing device also publishes the op handle the traced forwards call, and probes ``rotq_h16``
+ (tolerance, ``_h16_probe``) and the SwiGLU prologue on top of whichever rotation kernel will run."""
+ global _ROTQ_HANDLE, _SWIGLU_HANDLE
if index in _ROTQ_DEVICE:
return _ROTQ_DEVICE[index]
cfg = None
@@ -424,13 +826,35 @@ def rotquant_device_config(index: int) -> Optional[tuple]:
cfg = None
_ROTQ_DEVICE_K[index] = rules if cfg is not None else ()
_ROTQ_DEVICE[index] = cfg
+ h16 = sw = False
+ if cfg is not None:
+ try:
+ h16 = _h16_probe(index) if rotquant_h16_enabled() else False
+ if h16:
+ _H16_DEVICE[index] = h16 # the SwiGLU probe launches in this mode
+ if h16 and rotquant_swiglu_enabled() and _swiglu_op() is not None:
+ sw = _swiglu_probe(index)
+ except Exception: # noqa: BLE001 - the dense kernel stays, no SwiGLU prologue
+ h16 = sw = False
+ _H16_DEVICE[index] = h16
+ _SWIGLU_DEVICE[index] = sw
if cfg is not None:
_ROTQ_HANDLE = _rotq_op()
+ if sw:
+ _SWIGLU_HANDLE = _swiglu_op()
return cfg
# (M, K): ragged M, one-group rows, 21 groups (a ragged row count per tile), 56 and 128 groups (two rows / one row).
_ROTQ_PROBE_SHAPES = ((257, 256 * 3), (33, 256 * 21), (130, 256 * 56), (17, 256 * 128))
+# rotq_h16: the dense shapes and long rows (two-pass) plus 16 and 4 groups (K 4096 / 1024: the one-pass branch)
+_H16_PROBE_SHAPES = _ROTQ_PROBE_SHAPES + (
+ (19, 256 * 48),
+ (5, 256 * 160),
+ (65, 256 * 16),
+ (9, 256 * 4),
+)
+_SWIGLU_PROBE_SHAPES = ((257, 256 * 3), (130, 256 * 48), (33, 256 * 21), (65, 256 * 16))
def _rotq_probe(index: int, cfg: tuple) -> bool:
@@ -458,22 +882,138 @@ def _rotq_probe(index: int, cfg: tuple) -> bool:
return False
+def _probe_input(m: int, k: int, g: Any) -> Any:
+ import torch
+
+ x = torch.randn(m, k, generator = g) * (torch.rand(1, k, generator = g) * 4)
+ x[:, :3] *= 60
+ x[1] = 0
+ x[2, 11] = 3e4
+ return x.to(torch.bfloat16)
+
+
+def codes_close(q: Any, s: Any, rq: Any, rs: Any) -> bool:
+ """``rotq_h16`` vs stock codes: every code within two steps (v1's bf16 ``z / s`` has step 0.5 near 127); <= 1 in
+ 10^4 codes (and 8) off on scale-matched rows; <= 1% of rows (and 1) one bf16 step off in scale."""
+ import torch
+
+ if q.shape != rq.shape or q.dtype != rq.dtype or s.shape != rs.shape or s.dtype != rs.dtype:
+ return False
+ if not (bool(torch.isfinite(s).all()) and bool(torch.isfinite(rs).all())):
+ return False # NaN compares false against every tolerance below
+ dq = (q.to(torch.int16) - rq.to(torch.int16)).abs()
+ if q.numel() and int(dq.max()) > 2:
+ return False
+ same = s == rs
+ rows_off = int((~same).sum())
+ if rows_off > max(1, s.numel() // 100):
+ return False
+ if rows_off:
+ sf, rf = s.float(), rs.float()
+ if bool(((sf - rf).abs() > rf.abs() * 2.0**-7)[~same].any()):
+ return False
+ off = int(dq[same].ne(0).sum())
+ return off <= max(8, int(same.sum()) * q.shape[-1] // 10000)
+
+
+def _h16_probe(index: int) -> Any:
+ """``rotq_h16`` vs the stock rotation + quant on the dense probe's shapes and a long row (``codes_close``): the
+ second-stage mode that passed ("tf32x3" first on ``_H16_TF32X3_ARCHS``, else "ieee"), or False."""
+ import torch
+
+ dev = torch.device("cuda", index)
+ cap = tuple(torch.cuda.get_device_capability(index))
+ modes = ("tf32x3", "ieee") if cap in _H16_TF32X3_ARCHS else ("ieee",)
+ for mode in modes:
+ g = torch.Generator(device = "cpu").manual_seed(3)
+ try:
+ ok = True
+ for m, k in _H16_PROBE_SHAPES:
+ x = _probe_input(m, k, g).to(dev)
+ for kind in ("v1", "v2"):
+ q, s = _h16_launch(x, kind, tf32x3 = mode == "tf32x3")
+ rq, rs = rotquant_reference(x, 256, kind)
+ if not codes_close(q, s, rq, rs):
+ ok = False
+ break
+ if not ok:
+ break
+ torch.cuda.synchronize(dev)
+ if ok:
+ return mode
+ except Exception: # noqa: BLE001
+ continue
+ return False
+
+
+def _swiglu_probe(index: int) -> bool:
+ """``rotq_h16``'s SwiGLU prologue vs ``silu(gate) * value`` (ATen, eager) then the stock rotation + quant:
+ ``codes_close``. Gates span SiLU's saturated tails, zero and tiny magnitudes."""
+ import torch
+
+ dev = torch.device("cuda", index)
+ g = torch.Generator(device = "cpu").manual_seed(4)
+ try:
+ for m, k in _SWIGLU_PROBE_SHAPES:
+ gate = (_probe_input(m, k, g).float() * 0.05).to(torch.bfloat16).to(dev)
+ gate[0, :7] = torch.tensor([-90.0, -20.0, -1e-3, 0.0, 1e-3, 20.0, 90.0])
+ value = _probe_input(m, k, g).to(dev)
+ for kind in ("v1", "v2"):
+ rq, rs = rotquant_reference(gate, 256, kind, value)
+ q, s = _h16_launch(gate, kind, value)
+ if not codes_close(q, s, rq, rs):
+ return False
+ torch.cuda.synchronize(dev)
+ return True
+ except Exception: # noqa: BLE001
+ return False
+
+
def rotquant_call_count() -> int:
return _ROTQ_CALLS[0]
+def h16_call_count() -> int:
+ return _H16_CALLS[0]
+
+
+def swiglu_call_count() -> int:
+ return _SWIGLU_CALLS[0]
+
+
def convrot_act_quant(x2d: Any, group: int, v2: bool) -> Optional[tuple]:
"""``(int8 [M, K], scale [M])`` of ``x2d @ blockdiag(H_group)`` quantized like torchao (v2 = ``Int8Tensor``, else
the v1 per-token quant), from the fused kernel; None when this device / shape / group is not covered, so the caller
keeps its own rotation + quant. Safe inside a traced forward: no host sync, the probe ran at install time."""
import torch
- if (
- _ROTQ_HANDLE is None
- or x2d.dim() != 2
- or x2d.dtype != torch.bfloat16
- or not x2d.is_cuda
- or not rotquant_supported(x2d, group, rotq_tile_for(x2d.device.index, x2d.shape[-1], group))
+ if _ROTQ_HANDLE is None or x2d.dim() != 2 or x2d.dtype != torch.bfloat16 or not x2d.is_cuda:
+ return None
+ if not (
+ _h16_ok(x2d, group)
+ or rotquant_supported(x2d, group, rotq_tile_for(x2d.device.index, x2d.shape[-1], group))
):
return None
return _ROTQ_HANDLE(x2d, group, v2)
+
+
+def convrot_swiglu_act_quant(g2d: Any, v2d: Any, group: int, v2: bool) -> Optional[tuple]:
+ """``convrot_act_quant`` of ``silu(g2d) * v2d`` without the product ever reaching HBM: the down projection of a
+ rotated SwiGLU MLP. None when this device / shape / group is not covered (the caller keeps the stock product and
+ its own rotation + quant). Safe inside a traced forward: no host sync, the probe ran at install time."""
+ import torch
+
+ if (
+ _SWIGLU_HANDLE is None
+ or g2d.dim() != 2
+ or g2d.shape != v2d.shape
+ or g2d.dtype != torch.bfloat16
+ or v2d.dtype != torch.bfloat16
+ or not g2d.is_cuda
+ or g2d.device != v2d.device
+ or not _SWIGLU_DEVICE.get(g2d.device.index)
+ ):
+ return None
+ if not _h16_ok(g2d, group, v2d):
+ return None
+ return _SWIGLU_HANDLE(g2d, v2d, group, v2)
diff --git a/studio/backend/core/inference/diffusion_int8_gemm.py b/studio/backend/core/inference/diffusion_int8_gemm.py
index 28bc98308ef..a20df067592 100644
--- a/studio/backend/core/inference/diffusion_int8_gemm.py
+++ b/studio/backend/core/inference/diffusion_int8_gemm.py
@@ -28,9 +28,16 @@ ConvRot Linears (MiniMax-H3, Qwen-Image-2.1 ConvRot) run ``ConvRotLinear.forward
output stays bit-identical; kill switch ``UNSLOTH_DIFFUSION_INT8_GEMM_CONVROT=0``.
Rotated Linears on the archs ``diffusion_convrot_quant`` covers run the rotation and the act quant as ONE kernel
-(``rotq_i8``, codes and scales bit-identical, probed per device). Where the fused GEMM is off but that kernel is on
-(sm100), only the rotated Linears are swapped and their GEMM is cuBLAS ``_int_mm`` with torchao's epilogue, op for
-op. Kill switch ``UNSLOTH_DIFFUSION_INT8_ROTQUANT=0``.
+(``rotq_h16`` / ``rotq_i8``, probed per device). Where the fused GEMM is off but that kernel is on (sm100), only the
+rotated Linears are swapped and their GEMM is cuBLAS ``_int_mm`` with torchao's epilogue, op for op. Kill switch
+``UNSLOTH_DIFFUSION_INT8_ROTQUANT=0``.
+
+Rotated Linears that read the SAME activation (Q / K / V, a SwiGLU's gate / value) share one rotation + act quant
+(``shared_rotq_linears``): Inductor does not merge identical opaque custom-op calls in an inference graph (7 kernels
+per Qwen-Image-2.1 block for 4 distinct inputs). Outputs are bit-identical to the separate calls.
+
+A fully swapped Qwen-Image-2.1 SwiGLU MLP takes its down projection's codes straight from the gate / value halves
+(``convrot_swiglu_act_quant``); kill switch ``UNSLOTH_DIFFUSION_INT8_ROTQUANT_SWIGLU=0``.
A block-streamed denoiser installs against its onload device (``install(..., device = ...)``): group offload's
``swap_tensors`` keeps each Parameter's identity and the forward reads the payload off the live Parameter, so every
@@ -59,6 +66,9 @@ _OP_NAMESPACE = "unsloth_studio"
_OP_NAME = "int8_mm_dequant"
_REC = "_unsloth_i8_gemm"
_MARK = "_unsloth_i8_gemm_prev"
+# on a SwiGLU MLP whose down projection takes its codes from the gate / value halves
+_FF_MARK = "_unsloth_i8_gemm_swiglu_prev"
+_SWIGLU_FF_CLASSES = ("QwenImage21SwiGLUFeedForward",)
_NO_PREV = object()
_LOCK = threading.Lock()
_OP_HANDLE: Any = None
@@ -576,6 +586,14 @@ def stock_gemm(xq: Any, wq: Any, xs: Any, ws: Any, bias: Any) -> Any:
return y.to(torch.bfloat16)
+def _payload(kind: str, weight: Any) -> tuple:
+ """(int8 [N, K], scale [N]) off the live parameter, never a cached alias (a moved weight must not go stale)."""
+ if kind == "v1":
+ impl = weight.original_weight_tensor.tensor_impl
+ return impl.int_data, impl.scale.reshape(-1)
+ return weight.qdata, weight.scale.reshape(-1)
+
+
def _linear_forward(self: Any, x: Any) -> Any:
"""``nn.Linear.forward`` for a torchao int8 dynamic weight: torchao's activation quant (fused with the ConvRot
rotation where that kernel is on), then the fused-dequant GEMM, or cuBLAS + torchao's epilogue where it is not."""
@@ -587,12 +605,7 @@ def _linear_forward(self: Any, x: Any) -> Any:
kind, group, rotq, weight, fused = rec
if self.weight is not weight: # weight replaced since install (reload / LoRA bake): stock
return type(self).forward(self, x)
- # Payload off the live parameter, never a cached alias: a moved weight must not leave a stale device or pin a copy.
- if kind == "v1":
- impl = weight.original_weight_tensor.tensor_impl
- wq, ws = impl.int_data, impl.scale.reshape(-1)
- else:
- wq, ws = weight.qdata, weight.scale.reshape(-1)
+ wq, ws = _payload(kind, weight)
if wq.device != x.device:
return type(self).forward(self, x)
lead = x.shape[:-1]
@@ -625,6 +638,159 @@ def _linear_forward(self: Any, x: Any) -> Any:
return y.reshape(*lead, y.shape[-1])
+def _hooked(module: Any) -> bool:
+ """A forward (pre-)hook, own or global, or an instance ``forward``: a fused path skipping ``module`` would bypass it."""
+ import torch
+
+ d = module.__dict__
+ if "forward" in d or d.get("_forward_hooks") or d.get("_forward_pre_hooks"):
+ return True
+ nn_module = torch.nn.modules.module
+ return bool(nn_module._global_forward_hooks or nn_module._global_forward_pre_hooks)
+
+
+def _swapped_rec(module: Any) -> Optional[tuple]:
+ """Record of a Linear we swapped with its install-time weight and no offload / forward hook or override, else None:
+ the shared paths run the GEMM without calling the module, so any of those would be bypassed."""
+ import torch
+
+ d = module.__dict__
+ rec = d.get(_REC)
+ if rec is None or _MARK not in d or "_diffusers_hook" in d or "_hf_hook" in d:
+ return None
+ if getattr(d.get("forward"), "__func__", None) is not _linear_forward:
+ return None
+ if d.get("_forward_hooks") or d.get("_forward_pre_hooks"):
+ return None
+ nn_module = torch.nn.modules.module
+ if nn_module._global_forward_hooks or nn_module._global_forward_pre_hooks:
+ return None
+ if module.weight is not rec[3]:
+ return None
+ return rec
+
+
+def shared_rotq_linears(x: Any, linears: tuple) -> Optional[list]:
+ """``[m(x) for m in linears]`` with one shared rotation + act quant; None when any is not covered."""
+ import torch
+
+ if x.dtype != torch.bfloat16 or not x.is_cuda or x.numel() < _MIN_ROWS * x.shape[-1]:
+ return None
+ recs = [_swapped_rec(m) for m in linears]
+ if any(r is None or not r[2] for r in recs):
+ return None
+ kind, group = recs[0][0], recs[0][1]
+ if any(r[0] != kind or r[1] != group for r in recs):
+ return None
+ parts = [_payload(r[0], r[3]) for r in recs]
+ if any(wq.device != x.device for wq, _ in parts):
+ return None
+ from .diffusion_convrot_quant import convrot_act_quant
+
+ q = convrot_act_quant(x.reshape(-1, x.shape[-1]), group, kind == "v2")
+ if q is None:
+ return None
+ xq, xs = q
+ lead = x.shape[:-1]
+ outs = []
+ for m, r, (wq, ws) in zip(linears, recs, parts):
+ if r[4]:
+ y = _OP_HANDLE(xq, wq, xs.reshape(-1), ws, m.bias)
+ else:
+ y = stock_gemm(xq, wq, xs, ws, m.bias)
+ outs.append(y.reshape(*lead, y.shape[-1]))
+ return outs
+
+
+def _swiglu_down(down: Any, gate: Any, value: Any) -> Optional[Any]:
+ """``down(silu(gate) * value)`` via the fused SwiGLU rotation + quant, else None."""
+ import torch
+
+ rec = _swapped_rec(down)
+ if rec is None:
+ return None
+ kind, group, rotq, weight, fused = rec
+ if (
+ not rotq
+ or gate.dtype != torch.bfloat16
+ or value.dtype != torch.bfloat16
+ or not gate.is_cuda
+ or gate.shape != value.shape
+ or gate.shape[-1] != down.in_features
+ or gate.numel() < _MIN_ROWS * gate.shape[-1]
+ ):
+ return None
+ wq, ws = _payload(kind, weight)
+ if wq.device != gate.device:
+ return None
+ from .diffusion_convrot_quant import convrot_swiglu_act_quant
+
+ k = gate.shape[-1]
+ q = convrot_swiglu_act_quant(gate.reshape(-1, k), value.reshape(-1, k), group, kind == "v2")
+ if q is None:
+ return None
+ xq, xs = q
+ if fused:
+ y = _OP_HANDLE(xq, wq, xs.reshape(-1), ws, down.bias)
+ else:
+ y = stock_gemm(xq, wq, xs, ws, down.bias)
+ return y.reshape(*gate.shape[:-1], y.shape[-1])
+
+
+def _plain_silu(act: Any) -> bool:
+ """``act`` is an exact, unhooked ``nn.SiLU`` (the fused prologue hard-codes SiLU); ``type() is`` avoids a graph break."""
+ from torch import nn
+ return type(act) is nn.SiLU and not _hooked(act)
+
+
+def _swiglu_ff_forward(self: Any, hidden_states: Any) -> Any:
+ """``QwenImage21SwiGLUFeedForward.forward`` on the shared and SwiGLU-fused quants."""
+ pair = shared_rotq_linears(hidden_states, (self.gate_layer, self.proj))
+ if pair is None:
+ gate, value = self.gate_layer(hidden_states), self.proj(hidden_states)
+ else:
+ gate, value = pair
+ y = _swiglu_down(self.out, gate, value) if _plain_silu(self.activation_fn) else None
+ if y is None:
+ return self.out(self.activation_fn(gate) * value)
+ return y
+
+
+def _swiglu_on(index: int) -> bool:
+ from .diffusion_convrot_quant import _SWIGLU_DEVICE, rotquant_swiglu_enabled
+ return rotquant_swiglu_enabled() and bool(_SWIGLU_DEVICE.get(index))
+
+
+def _swiglu_ff_eligible(module: Any) -> bool:
+ from torch import nn
+
+ if type(module).__name__ not in _SWIGLU_FF_CLASSES or "forward" in module.__dict__:
+ return False
+ parts = [getattr(module, n, None) for n in ("gate_layer", "proj", "out")]
+ if any(p is None or _REC not in p.__dict__ for p in parts):
+ return False
+ act = getattr(module, "activation_fn", None)
+ if type(act) is not nn.SiLU or "forward" in act.__dict__:
+ return False
+ # only a rotated down projection on the fused rotation kernel gains (its input is the product)
+ return bool(parts[2].__dict__[_REC][2])
+
+
+def _install_swiglu_ff(transformer: Any, index: int) -> int:
+ """Patch the eligible SwiGLU MLPs on card ``index``."""
+ count = 0
+ for module in transformer.modules():
+ if _FF_MARK in module.__dict__:
+ count += 1
+ continue
+ if not _swiglu_ff_eligible(module) or _weight_card(module.out) != index:
+ continue
+ module.__dict__[_FF_MARK] = True
+ module.forward = types.MethodType(_swiglu_ff_forward, module)
+ count += 1
+ return count
+
+
def linear_from_q(q: Any, xs: Any, weight: Any, bias: Any) -> Optional[Any]:
"""For ``diffusion_int8_fused``: the down projection on an already-quantized activation, or None (stock)."""
import torch
@@ -867,13 +1033,31 @@ def _swap_on(transformer: Any, logger: Any, index: int) -> int:
module.__dict__[_MARK] = module.__dict__.get("forward", _NO_PREV)
module.forward = types.MethodType(_linear_forward, module)
count += 1
+ ff = _install_swiglu_ff(transformer, index) if rotq else 0
if logger is not None and count:
+ from .diffusion_convrot_quant import _H16_DEVICE
logger.info(
- "diffusion.int8_gemm: %d int8 Linear(s) %s on sm_%d%d%s",
+ "diffusion.int8_gemm: %d int8 Linear(s) %s on sm_%d%d%s%s",
count,
"run the fused-dequant GEMM (bf16 out)" if gemm else "keep cuBLAS",
*torch.cuda.get_device_capability(index),
- ", ConvRot rotation fused into the act quant" if rotq else "",
+ (
+ ", ConvRot rotation fused into the act quant ("
+ + ("H16 x H16 kernel" if _H16_DEVICE.get(index) else "dense rotation kernel")
+ + ")"
+ )
+ if rotq
+ else "",
+ (
+ f", one act quant for gate / value on {ff} SwiGLU MLP(s)"
+ + (
+ " + the SiLU product fused into the down projection's act quant"
+ if _swiglu_on(index)
+ else ""
+ )
+ )
+ if ff
+ else "",
)
return count
@@ -925,6 +1109,10 @@ def uninstall(transformer: Any = None) -> None:
cancel_first_call(transformer, "int8_gemm")
with _LOCK:
for module in transformer.modules():
+ if module.__dict__.pop(_FF_MARK, None) is not None:
+ fwd = module.__dict__.get("forward")
+ if getattr(fwd, "__func__", None) is _swiglu_ff_forward:
+ module.__dict__.pop("forward", None)
prev = module.__dict__.pop(_MARK, None)
if prev is None:
continue
@@ -936,7 +1124,8 @@ def uninstall(transformer: Any = None) -> None:
def is_installed(module: Any) -> bool:
- return _MARK in getattr(module, "__dict__", {})
+ d = getattr(module, "__dict__", {})
+ return _MARK in d or _FF_MARK in d
def call_count() -> int:
diff --git a/studio/backend/core/inference/diffusion_qwenimage21_fused.py b/studio/backend/core/inference/diffusion_qwenimage21_fused.py
index 059fff86a7d..31b9fb1d691 100644
--- a/studio/backend/core/inference/diffusion_qwenimage21_fused.py
+++ b/studio/backend/core/inference/diffusion_qwenimage21_fused.py
@@ -4,7 +4,9 @@
"""Qwen-Image-2.1 ConvRot int8: one rotation + one act quant per shared input (QKV, SwiGLU gate/value) in the compile.
Rotation is on the shared input axis and int8 scales are per row, so fused outputs equal the separate rotated ones bit
-for bit. Only where ``diffusion_int8_gemm`` leaves rotated Linears on the stock path (e.g. sm90, sm100), resident only.
+for bit. The fused QKV Linear: only where ``diffusion_int8_gemm`` leaves rotated Linears on the stock path (e.g. sm90,
+sm100), resident only. Where it swaps them, the patched helper routes Q / K / V through
+``diffusion_int8_gemm.shared_rotq_linears`` (Inductor does not merge the opaque kernel); resident or streamed.
Kill switch: ``UNSLOTH_DIFFUSION_Q21_CONVROT_FUSED=0``.
"""
@@ -101,6 +103,7 @@ def _make_prepare(stock: Any, mod: Any) -> Any:
import torch
from .diffusion_int8_fused import ensure_intmm_module, int8_linear
+ from .diffusion_int8_gemm import shared_rotq_linears
ensure_intmm_module() # resolved here, eagerly: an import under the trace is a graph break per Linear
@@ -108,12 +111,16 @@ def _make_prepare(stock: Any, mod: Any) -> Any:
attn, hidden_states, rotary_emb, layer_cache, kv_cache_mode, cache_write_slice
):
fused = _qkv_intact(attn) if torch.compiler.is_compiling() else None
- if fused is None:
- return stock(
- attn, hidden_states, rotary_emb, layer_cache, kv_cache_mode, cache_write_slice
- )
+ if fused is not None:
+ query, key, value = int8_linear(fused, hidden_states).chunk(3, dim = -1)
+ else:
+ qkv = shared_rotq_linears(hidden_states, (attn.to_q, attn.to_k, attn.to_v))
+ if qkv is None:
+ return stock(
+ attn, hidden_states, rotary_emb, layer_cache, kv_cache_mode, cache_write_slice
+ )
+ query, key, value = qkv
# stock body below the projections, op for op (fingerprinted at install)
- query, key, value = int8_linear(fused, hidden_states).chunk(3, dim = -1)
# main's split (by head_dim); equal to 0.41.0's ``(attn.heads, -1)`` when every head is local
head_dim = attn.inner_dim // attn.heads
@@ -184,6 +191,74 @@ def _patch_prepare(logger: Any = None) -> bool:
return True
+def _rotated_attention(root: Any) -> list:
+ """(attention, [to_q, to_k, to_v]) whose Q / K / V share one ConvRot group on one device."""
+ todo = []
+ for _name, module in root.named_modules():
+ if type(module).__name__ != "QwenImage21Attention":
+ continue
+ parts = [getattr(module, n, None) for n in ("to_q", "to_k", "to_v")]
+ if any(p is None for p in parts) or not _rotated_group(parts):
+ continue
+ if len({p.weight.device for p in parts}) != 1:
+ continue
+ todo.append((module, parts))
+ return todo
+
+
+def install_shared_qkv(transformer: Any, logger: Any = None) -> int:
+ """Patch the QKV helper for the int8 GEMM path (checked per call, so install order does not matter); returns the
+ rotated attention count."""
+ n = len(_rotated_attention(transformer))
+ if not n or not _patch_prepare(logger):
+ return 0
+ if logger is not None:
+ logger.info(
+ "diffusion.q21_convrot_fused: Q / K / V share one ConvRot rotation + act quant on the int8 GEMM path "
+ "(%d attention module(s))",
+ n,
+ )
+ return n
+
+
+def _swap_card_present(transformer: Any) -> bool:
+ """A card the transformer sits on (each card of a layer split; every visible card while its weights are off the
+ GPU) where the int8 GEMM swap covers rotated Linears, so the shared-QKV helper can engage. Not the current card:
+ on a mixed host it need not hold the transformer."""
+ import torch
+
+ from .diffusion_int8_fused import resident_cuda_cards
+
+ cards = resident_cuda_cards(transformer) or range(torch.cuda.device_count())
+ return any(_swap_covers(index) for index in cards)
+
+
+def _swap_covers(index: int) -> bool:
+ """True where ``diffusion_int8_gemm`` swaps rotated Linears onto ``rotq_i8`` on ``cuda:<index>``: NVIDIA CUDA only
+ (ROCm reports a CUDA-like capability but the swap declines it), the swap on, and the rotation kernel gated in and
+ not failed its per-device probe (``shared_rotq_linears`` declines every record without it, so the fused GEMM
+ alone does not count). Any failure counts as not covered, so the shared-QKV helper is never installed on a
+ guess."""
+ try:
+ import torch
+
+ if not torch.cuda.is_available() or is_rocm_torch(torch):
+ return False
+ from .diffusion_int8_gemm import _gates, int8_gemm_mode
+
+ if int8_gemm_mode() == "off":
+ return False
+ _, rotq = _gates(torch.cuda.get_device_capability(index))
+ if not rotq:
+ return False
+ from .diffusion_convrot_quant import _ROTQ_DEVICE
+
+ # probed already (resident swap ran first): its verdict; else the arch gate, re-checked per call
+ return _ROTQ_DEVICE.get(index, True) is not None
+ except Exception: # noqa: BLE001
+ return False
+
+
def install(
transformer: Any,
logger: Any = None,
@@ -194,14 +269,25 @@ def install(
if q21_convrot_fused_disabled():
uninstall(transformer)
return result
- if offload_active or type(transformer).__name__ != "QwenImage21Transformer2DModel":
+ if type(transformer).__name__ != "QwenImage21Transformer2DModel":
+ return result
+ try:
+ import torch
+ if torch.cuda.is_available() and _swap_card_present(transformer):
+ result["fused_qkv"] = install_shared_qkv(transformer, logger)
+ except Exception: # noqa: BLE001 - the stock helper stays
+ pass
+ shared = result["fused_qkv"]
+ if offload_active:
return result
from .diffusion_int8_fused import resident_cuda_cards, run_on_first_call
if resident_cuda_cards(transformer):
- return install_modules(transformer, logger)
+ out = install_modules(transformer, logger)
+ out["fused_qkv"] = max(out["fused_qkv"], shared)
+ return out
run_on_first_call(transformer, "q21_convrot_fused", lambda t: install_modules(t, logger))
- return {"fused_qkv": None, "out": None}
+ return {"fused_qkv": shared or None, "out": None}
def install_modules(root: Any, logger: Any = None) -> dict:
@@ -217,16 +303,7 @@ def install_modules(root: Any, logger: Any = None) -> dict:
return result
from .diffusion_zimage_fused import _fuse_linears, _share_storage
- todo = []
- for _name, module in root.named_modules():
- if type(module).__name__ != "QwenImage21Attention":
- continue
- parts = [getattr(module, n, None) for n in ("to_q", "to_k", "to_v")]
- if any(p is None for p in parts) or not _rotated_group(parts):
- continue
- if len({p.weight.device for p in parts}) != 1:
- continue
- todo.append((module, parts))
+ todo = _rotated_attention(root)
if not todo or not _patch_prepare(logger):
return result
with _LOCK:
diff --git a/studio/backend/tests/test_diffusion_int8_gemm.py b/studio/backend/tests/test_diffusion_int8_gemm.py
index 690c5d6e238..b8f8a7f6173 100644
--- a/studio/backend/tests/test_diffusion_int8_gemm.py
+++ b/studio/backend/tests/test_diffusion_int8_gemm.py
@@ -6,6 +6,8 @@ need NVIDIA CUDA, Triton and torchao (they force the lever on, so an arch outsid
from __future__ import annotations
+import types
+
import pytest
from core.inference import diffusion_convrot_quant as cq
@@ -19,15 +21,21 @@ def _clean(monkeypatch):
monkeypatch.delenv(g8.INT8_GEMM_ENV, raising = False)
monkeypatch.delenv(cq.INT8_ROTQUANT_ENV, raising = False)
monkeypatch.delenv(g8.INT8_GEMM_TILES_ENV, raising = False)
+ monkeypatch.delenv(cq.INT8_ROTQUANT_H16_ENV, raising = False)
+ monkeypatch.delenv(cq.INT8_ROTQUANT_SWIGLU_ENV, raising = False)
g8._DEVICE_CFG.clear()
g8._DEVICE_TILES.clear()
cq._ROTQ_DEVICE.clear()
cq._ROTQ_DEVICE_K.clear()
+ cq._H16_DEVICE.clear()
+ cq._SWIGLU_DEVICE.clear()
yield
g8._DEVICE_CFG.clear()
g8._DEVICE_TILES.clear()
cq._ROTQ_DEVICE.clear()
cq._ROTQ_DEVICE_K.clear()
+ cq._H16_DEVICE.clear()
+ cq._SWIGLU_DEVICE.clear()
@pytest.mark.parametrize(
@@ -637,6 +645,25 @@ def forced_rotq(forced):
return cfg
+def dense_rotq(forced, monkeypatch):
+ """The dense ``rotq_i8`` only (``UNSLOTH_DIFFUSION_INT8_ROTQUANT_H16=0``): codes bit-identical to the stock path."""
+ monkeypatch.setenv(cq.INT8_ROTQUANT_H16_ENV, "0")
+ cfg = cq.rotquant_device_config(torch.cuda.current_device())
+ if cfg is None:
+ pytest.skip("fused rotation probe refused this device")
+ assert cq._H16_DEVICE[torch.cuda.current_device()] is False
+ return cfg
+
+
+def h16_rotq(forced):
+ cfg = cq.rotquant_device_config(torch.cuda.current_device())
+ if cfg is None or not cq._H16_DEVICE.get(torch.cuda.current_device()):
+ pytest.skip("rotation probes refused this device")
+ return cfg
+
+
def _act(m, k, seed):
g = torch.Generator().manual_seed(seed)
x = torch.randn(m, k, generator = g) * (torch.rand(1, k, generator = g) * 4)
@@ -650,7 +677,7 @@ def _act(m, k, seed):
"m, k", [(17, 256), (300, 256 * 3), (1037, 5376), (257, 7168), (129, 14336), (19, 256 * 128)]
)
@pytest.mark.parametrize("kind", ["v1", "v2"])
-def test_rotquant_kernel_is_bit_exact_vs_rotation_then_torchao_quant(forced_rotq, m, k, kind):
+def test_rotquant_kernel_is_bit_exact_vs_rotation_then_torchao_quant(dense_rotq, m, k, kind):
x = _act(m, k, m + k)
q, s = cq._rotq_op()(x, 256, kind == "v2")
rq, rs = cq.rotquant_reference(x, 256, kind)
@@ -666,7 +693,7 @@ def test_rotquant_probe_accepts_this_torchao(forced):
@needs_cuda
-def test_rotquant_fake_op_matches_the_real_scale_dtype(forced_rotq):
+def test_rotquant_fake_op_matches_the_real_scale_dtype(dense_rotq):
from torch._subclasses.fake_tensor import FakeTensorMode
x = _act(40, 768, 9)
for v2 in (False, True):
@@ -677,11 +704,11 @@ def test_rotquant_fake_op_matches_the_real_scale_dtype(forced_rotq):
@needs_cuda
-def test_rotquant_unsupported_shapes_take_the_stock_math(forced_rotq):
+def test_rotquant_unsupported_shapes_take_the_stock_math(dense_rotq):
x = _act(40, 256 * 129, 3)
- assert not cq.rotquant_supported(x, 256, forced_rotq)
- assert not cq.rotquant_supported(_act(40, 1024, 4), 64, forced_rotq)
- assert not cq.rotquant_supported(_act(40, 1024, 5).half(), 256, forced_rotq)
+ assert not cq.rotquant_supported(x, 256, dense_rotq)
+ assert not cq.rotquant_supported(_act(40, 1024, 4), 64, dense_rotq)
+ assert not cq.rotquant_supported(_act(40, 1024, 5).half(), 256, dense_rotq)
q, s = cq._rotq_op()(x, 256, True)
rq, rs = cq.rotquant_reference(x, 256, "v2")
assert torch.equal(q, rq) and torch.equal(s, rs)
@@ -694,7 +721,7 @@ def test_rotquant_unsupported_shapes_take_the_stock_math(forced_rotq):
@needs_cuda
@pytest.mark.parametrize("version", [None, 2])
def test_convrot_linear_fuses_rotation_into_act_quant_eager_and_compiled(
- forced_rotq, monkeypatch, version
+ dense_rotq, monkeypatch, version
):
"""The rotated Linear quantizes its activation with the fused kernel: same output as ConvRotLinear.forward, eager
and compiled, one graph, no graph break, no recompile on a second call."""
@@ -849,6 +876,9 @@ def test_every_shipped_shape_tile_is_bit_exact(forced, tile, ws32):
def rotq_only(monkeypatch):
"""The fused rotation forced on, the fused GEMM forced off (what sm100 and other unfused archs run)."""
monkeypatch.setenv(cq.INT8_ROTQUANT_ENV, "1")
+ monkeypatch.setenv(
+ cq.INT8_ROTQUANT_H16_ENV, "0"
+ ) # the bit-identity tests below run the dense kernel
monkeypatch.setattr(g8, "device_config", lambda index: None)
monkeypatch.setattr(g8, "arch_config", lambda cap, mode = None: None)
cfg = cq.rotquant_device_config(torch.cuda.current_device())
@@ -925,7 +955,7 @@ def test_stock_gemm_matches_torchao_linear_bit_for_bit(rotq_only):
@needs_cuda
-def test_convrot_act_quant_api(forced_rotq):
+def test_convrot_act_quant_api(dense_rotq):
x = _act(300, 1024, 11)
q, s = cq.convrot_act_quant(x, 256, True)
rq, rs = cq.rotquant_reference(x, 256, "v2")
@@ -964,3 +994,441 @@ def test_every_shipped_rotq_k_tile_is_bit_exact(forced):
q, s = cq._rotq_launch(x, 256, kind, tile)
rq, rs = cq.rotquant_reference(x, 256, kind)
assert torch.equal(q, rq) and torch.equal(s, rs), (tile, m, k, kind)
+
+
+# ---- rotq_h16 (H16 x H16 rotation), the shared act quant and the SwiGLU prologue ----
+
+
+def _exact_codes(x, kind):
+ """Codes of an exact (fp64) rotation, rounded to bf16, then the stock quant: the target both kernels approximate."""
+ from core.inference.diffusion_convrot import build_convrot_hadamard
+
+ h = build_convrot_hadamard(256, device = x.device, dtype = torch.float64)
+ xr = (x.double().reshape(x.shape[0], -1, 256) @ h).reshape(x.shape).to(torch.bfloat16)
+ if kind == "v1":
+ return cq.act_quant_v1(xr)[0]
+ from torchao.quantization.granularity import PerRow
+ from torchao.quantization.quantize_.workflows.int8.int8_tensor import Int8Tensor
+
+ return Int8Tensor.from_hp(xr, PerRow()).qdata
+
+
+def test_codes_close_tolerance():
+ rq = torch.randint(-120, 120, (64, 1024), dtype = torch.int8)
+ rs = torch.rand(64) + 0.5
+ assert cq.codes_close(rq.clone(), rs.clone(), rq, rs)
+ q = rq.clone()
+ q[3, 7] += 1
+ q[9, 1] -= 2
+ assert cq.codes_close(q, rs, rq, rs)
+ q[5, 5] += 3 # three steps: a broken kernel
+ assert not cq.codes_close(q, rs, rq, rs)
+ q = rq.clone()
+ q[:2] += 1 # 2048 codes off on rows whose scale matches
+ assert not cq.codes_close(q, rs, rq, rs)
+ s = rs.clone()
+ s[4] = s[4] * (1 + 2.0**-8) # one row's amax rounded the other way
+ assert cq.codes_close(rq, s, rq, rs)
+ s[4] = s[4] * 1.1
+ assert not cq.codes_close(rq, s, rq, rs)
+ assert not cq.codes_close(rq, rs.to(torch.bfloat16), rq, rs)
+
+
+def test_h16_plan_keeps_every_chunk_full():
+ for ng in (1, 3, 12, 16, 21, 40, 48, 56, 129, 160):
+ cg, rows, nch, one = cq._h16_plan(ng)
+ assert ng % cg == 0 and nch * cg == ng and cg * rows == cq._H16_TILE_ROWS
+ assert one == (nch == 1)
+ assert cq._h16_plan(16) == (16, 1, 1, True) and cq._h16_plan(4) == (4, 4, 1, True)
+ assert cq._h16_plan(48) == (16, 1, 3, False) # Qwen-Image-2.1's K 12288
+
+
+@needs_cuda
+ "m, k",
+ [
+ (17, 256),
+ (300, 256 * 3),
+ (1037, 5376),
+ (257, 4096),
+ (129, 12288),
+ (19, 256 * 129),
+ (4, 256 * 16),
+ ],
+)
[email protected]("tf32x3", [False, True])
[email protected]("kind", ["v1", "v2"])
+def test_h16_kernel_matches_the_stock_codes_and_the_exact_rotation(h16_rotq, m, k, kind, tf32x3):
+ """Within ``codes_close`` of the stock rotation + quant, and no further from the exact rotation than the stock
+ (dense GEMM) path itself: the two only differ where an fp32 sum lands on the other side of a bf16 rounding."""
+ x = _act(m, k, m * 7 + k)
+ q, s = cq._h16_launch(x, kind, tf32x3 = tf32x3)
+ rq, rs = cq.rotquant_reference(x, 256, kind)
+ assert q.dtype == torch.int8 and s.dtype == rs.dtype and s.shape == (m,)
+ assert cq.codes_close(q, s, rq, rs)
+ ex = _exact_codes(x, kind)
+ assert int((q != ex).sum()) <= int((rq != ex).sum()) + max(4, q.numel() // 200000)
+
+
+@needs_cuda
+def test_h16_is_the_default_and_its_kill_switch_keeps_the_dense_kernel(forced, monkeypatch):
+ index = torch.cuda.current_device()
+ if cq.rotquant_device_config(index) is None:
+ pytest.skip("fused rotation probe refused this device")
+ if not cq._H16_DEVICE[index]:
+ pytest.skip("rotq_h16 probe refused this device")
+ x = _act(300, 256 * 129, 5) # 129 groups: no dense tile holds the row, rotq_h16 does
+ before = cq.h16_call_count()
+ q, s = cq.convrot_act_quant(x, 256, True)
+ assert cq.h16_call_count() == before + 1
+ assert cq.codes_close(q, s, *cq.rotquant_reference(x, 256, "v2"))
+ cq._ROTQ_DEVICE.clear()
+ cq._H16_DEVICE.clear()
+ monkeypatch.setenv(cq.INT8_ROTQUANT_H16_ENV, "0")
+ assert cq.rotquant_device_config(index) is not None and cq._H16_DEVICE[index] is False
+ assert cq.convrot_act_quant(x, 256, True) is None # dense tiles stop at 128 groups
+ x = _act(300, 1024, 6)
+ q, s = cq.convrot_act_quant(x, 256, True)
+ rq, rs = cq.rotquant_reference(x, 256, "v2")
+ assert torch.equal(q, rq) and torch.equal(s, rs) and cq.h16_call_count() == before + 1
+
+
+@needs_cuda
+def test_h16_mode_follows_the_arch(forced):
+ index = torch.cuda.current_device()
+ if cq.rotquant_device_config(index) is None or not cq._H16_DEVICE.get(index):
+ pytest.skip("rotation probes refused this device")
+ cap = tuple(torch.cuda.get_device_capability(index))
+ want = "tf32x3" if cap in cq._H16_TF32X3_ARCHS else "ieee"
+ assert cq._H16_DEVICE[index] == want
+
+
+@needs_cuda
+def test_h16_probe_refusal_keeps_the_dense_kernel(forced, monkeypatch):
+ monkeypatch.setattr(cq, "_h16_probe", lambda index: False)
+ index = torch.cuda.current_device()
+ if cq.rotquant_device_config(index) is None:
+ pytest.skip("fused rotation probe refused this device")
+ assert cq._H16_DEVICE[index] is False and cq._SWIGLU_DEVICE[index] is False
+ x = _act(300, 1024, 6)
+ q, s = cq.convrot_act_quant(x, 256, True)
+ rq, rs = cq.rotquant_reference(x, 256, "v2")
+ assert torch.equal(q, rq) and torch.equal(s, rs)
+
+
+def _swiglu_halves(m, k, seed):
+ gate = (_act(m, k, seed).float() * 0.05).to(torch.bfloat16)
+ gate[0, :6] = torch.tensor([-90.0, -20.0, -1e-3, 0.0, 1e-3, 90.0])
+ return gate, _act(m, k, seed + 1)
+
+
+@needs_cuda
[email protected]("m, k", [(300, 4096), (129, 12288), (33, 5376)])
[email protected]("kind", ["v1", "v2"])
+def test_swiglu_prologue_matches_the_stock_product_rotation_and_quant(h16_rotq, m, k, kind):
+ if not cq._SWIGLU_DEVICE.get(torch.cuda.current_device()):
+ pytest.skip("SwiGLU prologue probe refused this device")
+ gate, value = _swiglu_halves(m, k, m + k)
+ q, s = cq._h16_launch(gate, kind, value)
+ rq, rs = cq.rotquant_reference(gate, 256, kind, value)
+ assert cq.codes_close(q, s, rq, rs)
+ # a different tile (rows per program) gives the same codes bit for bit: the rotation is per group
+ q2, s2 = cq._h16_launch(gate, kind, value, tile_rows = 32)
+ assert torch.equal(q, q2) and torch.equal(s, s2)
+ before = cq.swiglu_call_count()
+ out = cq.convrot_swiglu_act_quant(gate, value, 256, kind == "v2")
+ assert out is not None and cq.swiglu_call_count() == before + 1
+ assert torch.equal(out[0], q) and torch.equal(out[1], s)
+ assert cq.convrot_swiglu_act_quant(gate, value[:, :256], 256, True) is None
+ assert cq.convrot_swiglu_act_quant(gate, value, 64, True) is None
+
+
+@needs_cuda
+def test_swiglu_kill_switch(forced, monkeypatch):
+ monkeypatch.setenv(cq.INT8_ROTQUANT_SWIGLU_ENV, "0")
+ index = torch.cuda.current_device()
+ if cq.rotquant_device_config(index) is None:
+ pytest.skip("fused rotation probe refused this device")
+ assert cq._SWIGLU_DEVICE[index] is False
+ gate, value = _swiglu_halves(64, 1024, 3)
+ assert cq.convrot_swiglu_act_quant(gate, value, 256, True) is None
+
+
+@needs_cuda
[email protected]("version", [None, 2])
+def test_shared_input_linears_quantize_once_and_match_the_separate_calls(
+ h16_rotq, monkeypatch, version
+):
+ """Q / K / V on one input: one fused rotation + act quant, three GEMMs, outputs bit-identical to the three swapped
+ Linears called one by one (each of those quantizes the same input to the same codes)."""
+ monkeypatch.delenv(g8.INT8_GEMM_CONVROT_ENV, raising = False)
+ lins = [
+ _convrot(_int8_linear(1024, n, bias, version))
+ for n, bias in ((1024, False), (512, True), (1024, False))
+ ]
+ holder = torch.nn.Sequential(*lins)
+ assert g8.install(holder) == 3
+ x = torch.randn(2, 300, 1024, device = "cuda", dtype = torch.bfloat16) * 3
+ x[0, 7, :5] *= 200
+ with torch.inference_mode():
+ separate = [m(x) for m in lins]
+ before = cq.rotquant_call_count()
+ shared = g8.shared_rotq_linears(x, tuple(lins))
+ assert cq.rotquant_call_count() == before + 1
+ assert shared is not None and all(torch.equal(a, b) for a, b in zip(shared, separate))
+ # a plain (unrotated) Linear, a replaced weight or a wrapped forward: not shareable
+ plain = _int8_linear(1024, 256, False, version)
+ g8.install(torch.nn.Sequential(plain))
+ assert g8.shared_rotq_linears(x, (lins[0], plain)) is None
+ lins[1]._diffusers_hook = object() # a leaf-level offload hook on one of them
+ assert g8.shared_rotq_linears(x, tuple(lins)) is None
+ del lins[1]._diffusers_hook
+ g8.uninstall(holder)
+
+
+def _swiglu_ff(dim, hidden, version):
+ """A module shaped and named like diffusers' QwenImage21SwiGLUFeedForward, int8 + ConvRot."""
+
+ def forward(self, hidden_states):
+ return self.out(
+ self.activation_fn(self.gate_layer(hidden_states)) * self.proj(hidden_states)
+ )
+
+ cls = type("QwenImage21SwiGLUFeedForward", (torch.nn.Module,), {"forward": forward})
+ ff = cls()
+ ff.proj = _convrot(_int8_linear(dim, hidden, False, version))
+ ff.out = _convrot(_int8_linear(hidden, dim, False, version))
+ ff.gate_layer = _convrot(_int8_linear(dim, hidden, False, version))
+ ff.activation_fn = torch.nn.SiLU()
+ return ff
+
+
+def _swapped_unfused(ff):
+ """``ff`` with its Linears swapped but the MLP forward left stock: each Linear quantizes on its own."""
+ assert g8.install(torch.nn.Sequential(ff)) == 3
+ ff.__dict__.pop("forward", None)
+ ff.__dict__.pop(g8._FF_MARK, None)
+ return ff
+
+
+@needs_cuda
[email protected]("version", [None, 2])
+def test_swiglu_mlp_fuses_the_product_into_the_down_quant_eager_and_compiled(
+ h16_rotq, monkeypatch, version
+):
+ """The patched MLP: gate / value share one act quant, the down projection takes its codes from the halves.
+ Output within the stock MLP's own int8 rounding (codes_close upstream), compiled fullgraph, one graph, no
+ recompile on a second input, uninstall restores the class forward."""
+ from torch._dynamo.utils import counters
+
+ if not cq._SWIGLU_DEVICE.get(torch.cuda.current_device()):
+ pytest.skip("SwiGLU prologue probe refused this device")
+ monkeypatch.delenv(g8.INT8_GEMM_CONVROT_ENV, raising = False)
+ stock = _swiglu_ff(1024, 3072, version)
+ unfused = _swapped_unfused(_swiglu_ff(1024, 3072, version))
+ ff = _swiglu_ff(1024, 3072, version)
+ holder = torch.nn.Sequential(ff)
+ assert g8.install(holder) == 3
+ assert g8.is_installed(ff) and ff.__dict__.get(g8._FF_MARK)
+ x = torch.randn(2, 300, 1024, device = "cuda", dtype = torch.bfloat16)
+ x[0, 7, :5] *= 50
+ x2 = x * 0.5
+ with torch.inference_mode():
+ before, sw = cq.rotquant_call_count(), cq.swiglu_call_count()
+ out = ff(x)
+ assert cq.rotquant_call_count() == before + 2 and cq.swiglu_call_count() == sw + 1
+ # vs the same kernels unfused (four quants, the product through HBM) and vs the stock ConvRotLinear MLP
+ for ref in (unfused(x), stock(x)):
+ cos = torch.nn.functional.cosine_similarity(
+ out.float().flatten(), ref.float().flatten(), dim = 0
+ )
+ assert cos > 0.9999
+ assert (out.float() - ref.float()).abs().max() <= 0.02 * ref.float().abs().max()
+ counters.clear()
+ torch._dynamo.reset()
+ with torch._inductor.config.patch(emulate_precision_casts = True):
+ compiled = torch.compile(ff, fullgraph = True)
+ c1 = compiled(x)
+ c2 = compiled(x2)
+ assert not counters["graph_break"]
+ assert counters["stats"]["unique_graphs"] == 1
+ assert torch.equal(c1, out) # opaque kernels + emulated epilogue: eager-exact
+ assert torch.equal(c2, ff(x2))
+ g8.uninstall(holder)
+ assert "forward" not in ff.__dict__ and not g8.is_installed(ff)
+
+
+@needs_cuda
+def test_swiglu_mlp_without_the_prologue_still_shares_the_gate_value_quant(h16_rotq, monkeypatch):
+ monkeypatch.delenv(g8.INT8_GEMM_CONVROT_ENV, raising = False)
+ cq._SWIGLU_DEVICE[torch.cuda.current_device()] = False
+ unfused = _swapped_unfused(_swiglu_ff(1024, 3072, 2))
+ ff = _swiglu_ff(1024, 3072, 2)
+ assert g8.install(torch.nn.Sequential(ff)) == 3 and ff.__dict__.get(g8._FF_MARK)
+ x = torch.randn(300, 1024, device = "cuda", dtype = torch.bfloat16)
+ with torch.inference_mode():
+ sw = cq.swiglu_call_count()
+ before = cq.rotquant_call_count()
+ out = ff(x)
+ # shared gate / value quant + the down projection's own: two kernels, no SwiGLU prologue
+ assert cq.rotquant_call_count() == before + 2 and cq.swiglu_call_count() == sw
+ before = cq.rotquant_call_count()
+ ref = unfused(x)
+ assert cq.rotquant_call_count() == before + 3
+ assert torch.equal(out, ref)
+ g8.uninstall(torch.nn.Sequential(ff))
+
+
+def test_hooked_linear_is_not_shared():
+ """A forward hook or pre-hook (module-level or global) on a swapped Linear must see its call, so the shared QKV /
+ SwiGLU paths, which run the GEMM without calling the module, decline it and the per-module call runs instead."""
+ lin = torch.nn.Linear(8, 8)
+ lin.__dict__[g8._REC] = ("v2", 64, True, lin.weight, False)
+ lin.__dict__[g8._MARK] = True
+ lin.forward = types.MethodType(g8._linear_forward, lin)
+ assert g8._swapped_rec(lin) is not None
+ noop = lambda *a, **k: None # noqa: E731
+ for register in (
+ lin.register_forward_hook,
+ lin.register_forward_pre_hook,
+ lambda f: lin.register_forward_hook(f, with_kwargs = True),
+ torch.nn.modules.module.register_module_forward_hook,
+ torch.nn.modules.module.register_module_forward_pre_hook,
+ ):
+ handle = register(noop)
+ try:
+ assert g8._swapped_rec(lin) is None
+ finally:
+ handle.remove()
+ assert g8._swapped_rec(lin) is not None
+
+
+def test_replaced_linear_forward_is_not_shared():
+ """An instance ``forward`` assigned over the installed ``_linear_forward`` (adapter / instrumentation code) is
+ what a module call runs, so the shared paths, which skip the call, decline it; restoring it re-enables them."""
+ lin = torch.nn.Linear(8, 8)
+ lin.__dict__[g8._REC] = ("v2", 64, True, lin.weight, False)
+ lin.__dict__[g8._MARK] = True
+ installed = types.MethodType(g8._linear_forward, lin)
+ lin.forward = installed
+ assert g8._swapped_rec(lin) is not None
+ lin.forward = lambda t: t
+ assert g8._swapped_rec(lin) is None
+ lin.forward = types.MethodType(lambda self, t: t, lin)
+ assert g8._swapped_rec(lin) is None
+ del lin.forward
+ assert g8._swapped_rec(lin) is None
+ lin.forward = installed
+ assert g8._swapped_rec(lin) is not None
+
+
+def test_hooked_activation_declines_the_swiglu_fusion(monkeypatch):
+ """The fused SwiGLU path never calls ``activation_fn``: a hook (module-level or global) or an instance
+ ``forward`` on it has to see the call, so the MLP takes ``out(act(gate) * value)`` instead."""
+ ff = torch.nn.Module()
+ ff.gate_layer, ff.proj, ff.out = (
+ torch.nn.Linear(8, 8),
+ torch.nn.Linear(8, 8),
+ torch.nn.Linear(8, 8),
+ )
+ ff.activation_fn = torch.nn.SiLU()
+ fused = object()
+ monkeypatch.setattr(g8, "shared_rotq_linears", lambda x, linears: None)
+ monkeypatch.setattr(g8, "_swiglu_down", lambda down, gate, value: fused)
+ x = torch.randn(3, 8)
+ assert g8._swiglu_ff_forward(ff, x) is fused
+ seen = []
+ for register in (
+ lambda f: ff.activation_fn.register_forward_hook(lambda m, a, o: seen.append(1)),
+ lambda f: ff.activation_fn.register_forward_pre_hook(lambda m, a: seen.append(1)),
+ lambda f: torch.nn.modules.module.register_module_forward_hook(
+ lambda m, a, o: seen.append(1)
+ ),
+ ):
+ handle = register(None)
+ try:
+ seen.clear()
+ y = g8._swiglu_ff_forward(ff, x)
+ assert y is not fused and seen
+ ref = ff.out(torch.nn.functional.silu(ff.gate_layer(x)) * ff.proj(x))
+ assert torch.equal(y, ref)
+ finally:
+ handle.remove()
+ assert g8._swiglu_ff_forward(ff, x) is fused
+ ff.activation_fn.forward = lambda t: t # an instance override replacing the activation
+ assert g8._swiglu_ff_forward(ff, x) is not fused
+
+
+def test_replaced_activation_declines_the_swiglu_fusion(monkeypatch):
+ """The fused prologue hard-codes SiLU: an ``activation_fn`` swapped after install for GELU, a custom module or a
+ ``SiLU`` subclass (no hooks, no instance ``forward``) has to run itself, and restoring a plain SiLU fuses again."""
+
+ class _SiLUSub(torch.nn.SiLU):
+ def forward(self, t):
+ return torch.nn.functional.silu(t) * 2
+
+ class _Custom(torch.nn.Module):
+ def forward(self, t):
+ return t * 3
+
+ ff = torch.nn.Module()
+ ff.gate_layer, ff.proj, ff.out = (
+ torch.nn.Linear(8, 8),
+ torch.nn.Linear(8, 8),
+ torch.nn.Linear(8, 8),
+ )
+ ff.activation_fn = torch.nn.SiLU()
+ fused = object()
+ monkeypatch.setattr(g8, "shared_rotq_linears", lambda x, linears: None)
+ monkeypatch.setattr(g8, "_swiglu_down", lambda down, gate, value: fused)
+ x = torch.randn(3, 8)
+ assert g8._swiglu_ff_forward(ff, x) is fused
+ for act in (torch.nn.GELU(), torch.nn.GELU(approximate = "tanh"), _SiLUSub(), _Custom()):
+ ff.activation_fn = act
+ y = g8._swiglu_ff_forward(ff, x)
+ assert y is not fused
+ assert torch.equal(y, ff.out(act(ff.gate_layer(x)) * ff.proj(x)))
+ ff.activation_fn = torch.nn.SiLU()
+ assert g8._swiglu_ff_forward(ff, x) is fused
+
+
+def test_codes_close_rejects_non_finite_scales():
+ """NaN compares false against every tolerance: a NaN / inf scale on one row (e.g. the probe's all-zero row) must
+ still fail, on either side."""
+ rq = torch.randint(-120, 120, (64, 1024), dtype = torch.int8)
+ rs = torch.rand(64) + 0.5
+ for bad in (float("nan"), float("inf"), float("-inf")):
+ s = rs.clone()
+ s[1] = bad
+ assert not cq.codes_close(rq, s, rq, rs)
+ assert not cq.codes_close(rq, rs, rq, s)
+
+
+@needs_cuda
+def test_h16_probe_covers_the_one_pass_branch_and_rejects_nan_scales(forced):
+ """The per-device probe runs both ``rotq_h16`` branches (one pass, two pass) on v1 / v2, and a kernel that returns
+ a NaN scale on one row is refused."""
+ index = torch.cuda.current_device()
+ real = cq._h16_launch
+ seen = set()
+
+ def recording(x, kind, *a, **k):
+ seen.add((cq._h16_plan(x.shape[-1] // 256)[3], kind))
+ return real(x, kind, *a, **k)
+
+ with pytest.MonkeyPatch.context() as mp:
+ mp.setattr(cq, "_h16_launch", recording)
+ if not cq._h16_probe(index):
+ pytest.skip("rotq_h16 probe refused this device")
+ assert seen == {(True, "v1"), (True, "v2"), (False, "v1"), (False, "v2")}
+
+ def nan_row(x, kind, *a, **k):
+ q, s = real(x, kind, *a, **k)
+ s = s.clone()
+ s[1] = float("nan") # the probe's all-zero row
+ return q, s
+
+ with pytest.MonkeyPatch.context() as mp:
+ mp.setattr(cq, "_h16_launch", nan_row)
+ assert cq._h16_probe(index) is False
+ assert cq._swiglu_probe(index) is False
diff --git a/studio/backend/tests/test_diffusion_qwenimage21_fused.py b/studio/backend/tests/test_diffusion_qwenimage21_fused.py
index 9469ae7e32c..c4fc42be75d 100644
--- a/studio/backend/tests/test_diffusion_qwenimage21_fused.py
+++ b/studio/backend/tests/test_diffusion_qwenimage21_fused.py
@@ -213,3 +213,179 @@ def test_model_unload_restores_the_process_global_patch(monkeypatch):
monkeypatch.setattr(qmod, qf._PREPARE, fake)
d._uninstall_fused_dit_patches()
assert getattr(qmod, qf._PREPARE) is sentinel
+
+
+def _gemm_path_ready() -> bool:
+ if not torch.cuda.is_available() or getattr(torch.version, "hip", None):
+ return False
+ try:
+ from torchao.quantization import Int8DynamicActivationInt8WeightConfig
+ Int8DynamicActivationInt8WeightConfig(version = 2, set_inductor_config = False)
+ except Exception: # noqa: BLE001
+ return False
+ return torch.cuda.get_device_capability() >= (8, 0)
+
+
[email protected](not _gemm_path_ready(), reason = "needs NVIDIA sm80+ CUDA and torchao Int8Tensor")
+def test_int8_gemm_path_rotates_each_shared_input_once(monkeypatch):
+ """Where diffusion_int8_gemm swaps the rotated Linears (forced here on any sm80+ part): Q / K / V and the SwiGLU
+ gate / value each quantize their shared input ONCE (4 fused rotation calls per block instead of 7), Q / K / V
+ bit-identical to the stock helper on the same swapped Linears, the block within the int8 rounding of it."""
+ from core.inference import diffusion_convrot_quant as cq
+ from core.inference import diffusion_int8_gemm as g8
+ from core.inference.diffusion_convrot import rotate_linears_, warm_rotation_cache
+ from torchao.quantization import Int8DynamicActivationInt8WeightConfig, quantize_
+
+ monkeypatch.setenv(g8.INT8_GEMM_ENV, "1")
+ index = torch.cuda.current_device()
+ g8._DEVICE_CFG.pop(index, None)
+ cq._ROTQ_DEVICE.pop(index, None)
+ if g8.device_config(index) is None or cq.rotquant_device_config(index) is None:
+ pytest.skip("int8 GEMM / fused rotation probe refused this device")
+ assert not qf.arch_ok()
+ torch.manual_seed(0)
+ blk = qmod.QwenImage21TransformerBlock(DIM, HEADS, HEAD_DIM).cuda().to(torch.bfloat16).eval()
+ for p in blk.parameters():
+ p.data.normal_(0, 0.05)
+ names = [n for n, m in blk.named_modules() if isinstance(m, torch.nn.Linear)]
+ rotate_linears_(blk, names, 256)
+ warm_rotation_cache(blk, "cuda", torch.bfloat16)
+ quantize_(
+ blk,
+ Int8DynamicActivationInt8WeightConfig(version = 2, set_inductor_config = False),
+ filter_fn = lambda m, fqn: isinstance(m, torch.nn.Linear),
+ )
+ assert g8.install(blk) == 7
+ x = _x()
+ stock_prepare = getattr(qmod, qf._PREPARE)
+ with torch.no_grad():
+ before = cq.rotquant_call_count()
+ ref_qkv = stock_prepare(blk.attn, x, None, None, None, None)
+ assert cq.rotquant_call_count() == before + 3
+ ref = blk(x, mod_params(x), rotary_emb = _rope(x.shape[1]))
+ assert qf.install_shared_qkv(blk) == 1
+ before = cq.rotquant_call_count()
+ qkv = getattr(qmod, qf._PREPARE)(blk.attn, x, None, None, None, None)
+ assert cq.rotquant_call_count() == before + 1
+ assert all(torch.equal(a, b) for a, b in zip(qkv[:3], ref_qkv[:3])) and qkv[3] == ref_qkv[3]
+ before = cq.rotquant_call_count()
+ out = blk(x, mod_params(x), rotary_emb = _rope(x.shape[1]))
+ assert cq.rotquant_call_count() == before + 4
+ cos = torch.nn.functional.cosine_similarity(out.float().flatten(), ref.float().flatten(), dim = 0)
+ assert cos > 0.9999
+ g8.uninstall(blk)
+
+
+def test_shared_qkv_reported_and_gated_on_the_transformer_cards(monkeypatch):
+ """The shared-QKV helper installs when a card holding the transformer (every visible card while it is off the
+ GPU) is one the int8 GEMM swap covers, whatever the current card is, and its count is reported even though the
+ fused-QKV module path declines on such a card."""
+ import core.inference.diffusion_qwenimage21_fused as mod
+
+ model = type("QwenImage21Transformer2DModel", (torch.nn.Module,), {})()
+ calls = []
+ swap_cards = {
+ 1
+ } # cuda:1 holds the transformer and is swap-covered; the current card cuda:0 is not
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(torch.cuda, "device_count", lambda: 2)
+ monkeypatch.setattr(torch.cuda, "current_device", lambda: 0)
+ monkeypatch.setattr(mod, "_swap_covers", lambda index: index in swap_cards)
+ monkeypatch.setattr(mod, "install_shared_qkv", lambda t, logger = None: calls.append(t) or 2)
+ monkeypatch.setattr(i8f, "resident_cuda_cards", lambda m: ())
+ assert mod.install(model, offload_active = True) == {"fused_qkv": 2, "out": 0}
+ monkeypatch.setattr(i8f, "resident_cuda_cards", lambda m: (1,))
+ monkeypatch.setattr(mod, "install_modules", lambda r, logger = None: {"fused_qkv": 0, "out": 0})
+ assert mod.install(model) == {"fused_qkv": 2, "out": 0}
+ assert calls == [model, model]
+ swap_cards.clear() # every card on the stock path: the helper is not installed
+ assert mod.install(model) == {"fused_qkv": 0, "out": 0}
+ assert calls == [model, model]
+
+
[email protected]("rocm", ["hip", "tag"])
+def test_rocm_cards_are_not_swap_covered(monkeypatch, rocm):
+ """ROCm: ``torch.cuda.is_available()`` and a CUDA-like capability, but the int8 GEMM swap declines it, so no card
+ counts as swap-covered and the process-global QKV helper is not installed or reported."""
+ import core.inference.diffusion_int8_gemm as g8
+ import core.inference.diffusion_qwenimage21_fused as mod
+
+ model = type("QwenImage21Transformer2DModel", (torch.nn.Module,), {})()
+ calls = []
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(torch.cuda, "device_count", lambda: 2)
+ monkeypatch.setattr(torch.cuda, "current_device", lambda: 0)
+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda index = None: (9, 0))
+ monkeypatch.setattr(g8, "_gates", lambda cap: (True, True))
+ monkeypatch.setattr(g8, "int8_gemm_mode", lambda: "auto")
+ monkeypatch.setattr(mod, "install_shared_qkv", lambda t, logger = None: calls.append(t) or 2)
+ monkeypatch.setattr(i8f, "resident_cuda_cards", lambda m: ())
+ assert mod._swap_card_present(model) # NVIDIA with the swap gated in: covered
+ if rocm == "hip":
+ monkeypatch.setattr(torch.version, "hip", "6.4.0", raising = False)
+ else:
+ monkeypatch.setattr(torch, "__version__", "2.9.0+rocm6.4")
+ assert not mod._swap_card_present(model)
+ assert mod.install(model, offload_active = True) == {"fused_qkv": 0, "out": 0}
+ assert calls == []
+
+
+def test_swap_probe_failure_is_not_swap_covered(monkeypatch):
+ import core.inference.diffusion_int8_gemm as g8
+ import core.inference.diffusion_qwenimage21_fused as mod
+
+ model = type("QwenImage21Transformer2DModel", (torch.nn.Module,), {})()
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(torch.cuda, "device_count", lambda: 1)
+ monkeypatch.setattr(i8f, "resident_cuda_cards", lambda m: ())
+
+ def boom(index = None):
+ raise RuntimeError("no device")
+
+ monkeypatch.setattr(torch.cuda, "get_device_capability", boom)
+ monkeypatch.setattr(g8, "int8_gemm_mode", lambda: "auto")
+ assert not mod._swap_card_present(model)
+
+
+ "env", ["UNSLOTH_DIFFUSION_INT8_ROTQUANT", "UNSLOTH_DIFFUSION_INT8_GEMM_CONVROT", "probe"]
+)
+def test_shared_qkv_needs_the_rotation_kernel_not_just_the_fused_gemm(monkeypatch, env):
+ """A fused-GEMM arch with ``rotq_i8`` switched off (or failed its per-device probe): ``shared_rotq_linears``
+ declines every record (``not r[2]``), so the helper is neither installed nor counted."""
+ import core.inference.diffusion_convrot_quant as cq
+ import core.inference.diffusion_int8_gemm as g8
+ import core.inference.diffusion_qwenimage21_fused as mod
+
+ model = type("QwenImage21Transformer2DModel", (torch.nn.Module,), {})()
+ calls = []
+ for name in (
+ "UNSLOTH_DIFFUSION_INT8_ROTQUANT",
+ "UNSLOTH_DIFFUSION_INT8_GEMM_CONVROT",
+ "UNSLOTH_DIFFUSION_INT8_GEMM",
+ ):
+ monkeypatch.delenv(name, raising = False)
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(torch.cuda, "device_count", lambda: 1)
+ monkeypatch.setattr(torch.cuda, "current_device", lambda: 0)
+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda index = None: (8, 9))
+ monkeypatch.setattr(torch.version, "hip", None, raising = False)
+ monkeypatch.setattr(g8, "int8_gemm_mode", lambda: "auto")
+ monkeypatch.setattr(mod, "install_shared_qkv", lambda t, logger = None: calls.append(t) or 2)
+ monkeypatch.setattr(i8f, "resident_cuda_cards", lambda m: ())
+ monkeypatch.delitem(cq._ROTQ_DEVICE, 0, raising = False)
+ assert g8._gates((8, 9)) == (True, True)
+ assert mod.install(model, offload_active = True) == {"fused_qkv": 2, "out": 0} # control: engaged
+ assert calls == [model]
+ calls.clear()
+ qf.uninstall()
+ if env == "probe":
+ monkeypatch.setitem(
+ cq._ROTQ_DEVICE, 0, None
+ ) # rotq_i8 failed its bit-exact probe on cuda:0
+ else:
+ monkeypatch.setenv(env, "0")
+ assert g8._gates((8, 9)) == (True, False)
+ assert not mod._swap_card_present(model)
+ assert mod.install(model, offload_active = True) == {"fused_qkv": 0, "out": 0}
+ assert calls == []