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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: make the fused int8 kernels bit-exact on torchao 0.17 and round int32 to bf16 twice like PyTorch (#12633)
Daniel Han335fb3d97261
diff --git a/studio/backend/core/inference/diffusion_int8_fused.py b/studio/backend/core/inference/diffusion_int8_fused.pyindex 9d1fa301edf..28b4e7c60e2 100644--- a/studio/backend/core/inference/diffusion_int8_fused.py+++ b/studio/backend/core/inference/diffusion_int8_fused.py@@ -4,9 +4,12 @@"""Fused int8 activation path between two torchao int8 GEMMs of a DiT feed-forward: one Triton kernelreads the int32 ``_int_mm`` output, applies dequant + GELU(tanh) / SwiGLU and writes int8 + the fp32 row scale.-NUMERICS: bit-identical to EAGER torchao + ATen (every bf16 rounding kept, fp contraction off so+NUMERICS: bit-identical to EAGER torchao + ATen (every bf16 rounding kept, ATen's GELU(tanh) formula op for op (equal+on every bf16 input), fp contraction off so``y * w_scale + bias`` rounds twice, row scale ``bf16(amax / 127.5)`` clamped at fp32 eps, quantizer multiplies bythe correctly rounded reciprocal). The compiled stock path is NOT eager-exact (Inductor keeps fp32 chains).+Activation-scale contract follows the incoming scale's dtype: fp32 on torchao >= 0.18; bf16 on <= 0.17, where+``int32 * bf16`` rounds twice (int32 -> fp32 -> bf16) and ``1 / s`` and ``x * (1 / s)`` round to bf16.Anything but a plain dynamic symmetric per-row ``Int8Tensor`` on CUDA + Triton >= 3.2 keeps the stock path.Kill switch: ``UNSLOTH_DIFFUSION_INT8_FUSED=0``.@@ -85,9 +88,12 @@ def _kernels() -> Optional[types.SimpleNamespace]:@triton.jitdef _gelu_tanh(y):- # 0.5 * y * (1 + tanh(u)) == y * sigmoid(2u) == y / (1 + exp(-2u)), u = sqrt(2/pi) * (y + 0.044715 y^3)- u = 0.7978845608028654 * (y + 0.044715 * (y * y * y))- return y / (1.0 + tl.exp2(u * -2.8853900817779268))+ # ATen's GELU(tanh) op for op (y / (1 + exp(-2u)) is NOT bf16-equal); *_rn: ptxas FMA-fuses f32x2 on sm_100.+ cube = tl.extra.cuda.libdevice.mul_rn(tl.extra.cuda.libdevice.mul_rn(y, y), y)+ inner = 0.7978845608028654 * tl.extra.cuda.libdevice.add_rn(+ y, tl.extra.cuda.libdevice.mul_rn(0.044715, cube)+ )+ return 0.5 * y * (1.0 + tl.extra.cuda.libdevice.tanh(inner))@triton.jitdef _pre(@@ -101,20 +107,36 @@ def _kernels() -> Optional[types.SimpleNamespace]:WS_FP32: tl.constexpr,EVICT: tl.constexpr,FINAL_ROUND: tl.constexpr,+ FP32_SCALE: tl.constexpr,+ PIN_RN: tl.constexpr,):# torchao Int8Tensor linear epilogue: (int32 * x_scale).to(bf16) * w_scale (+ bias), then .to(bf16).# FINAL_ROUND=False leaves the last rounding to the caller (it commutes with a row max).- c = tl.load(c_ptr + offs, mask = mask, other = 0, eviction_policy = EVICT).to(tl.float32)+ c = tl.load(c_ptr + offs, mask = mask, other = 0, eviction_policy = EVICT)+ if FP32_SCALE:+ c = c.to(tl.float32)+ else:+ # int32 -> fp32 -> bf16 rounds twice; Triton folds a plain cast chain into one rounding.+ c = _rbf16(tl.extra.cuda.libdevice.int2float_rn(c))y = _rbf16(c * xs)- y = y * tl.load(ws_ptr + offs, mask = mask, other = 0.0, eviction_policy = "evict_last").to(+ w = tl.load(ws_ptr + offs, mask = mask, other = 0.0, eviction_policy = "evict_last").to(tl.float32)+ # PIN_RN (sm_100+): ptxas fuses packed f32x2 mul + add into an FMA even with fp fusion off; elsewhere it costs.+ if PIN_RN:+ y = tl.extra.cuda.libdevice.mul_rn(y, w)+ else:+ y = y * wif not WS_FP32:y = _rbf16(y)if HAS_BIAS:- y = y + tl.load(b_ptr + offs, mask = mask, other = 0.0, eviction_policy = "evict_last").to(+ b = tl.load(b_ptr + offs, mask = mask, other = 0.0, eviction_policy = "evict_last").to(tl.float32)+ if PIN_RN:+ y = tl.extra.cuda.libdevice.add_rn(y, b)+ else:+ y = y + bif FINAL_ROUND:y = _rbf16(y)return y@@ -138,6 +160,8 @@ def _kernels() -> Optional[types.SimpleNamespace]:p_sh,HAS_BIAS: tl.constexpr,WS_FP32: tl.constexpr,+ FP32_SCALE: tl.constexpr,+ PIN_RN: tl.constexpr,HAS_PREFIX: tl.constexpr,HEAD_DIM: tl.constexpr,CHUNK: tl.constexpr,@@ -154,7 +178,20 @@ def _kernels() -> Optional[types.SimpleNamespace]:for k in range(0, N, CHUNK):offs = k + basem = offs < N- y = _pre(crow, xs, ws_ptr, b_ptr, offs, m, HAS_BIAS, WS_FP32, "evict_last", False)+ y = _pre(+ crow,+ xs,+ ws_ptr,+ b_ptr,+ offs,+ m,+ HAS_BIAS,+ WS_FP32,+ "evict_last",+ False,+ FP32_SCALE,+ PIN_RN,+ )vmax = tl.maximum(vmax, tl.where(m, y, float("-inf")))# bf16 rounding is monotone, so max(round(v)) == round(max(v)): round once, after the reduction.amax = _rbf16(_gelu_tanh(_rbf16(tl.max(vmax, axis = 0))))@@ -166,7 +203,18 @@ def _kernels() -> Optional[types.SimpleNamespace]:g = _rbf16(_gelu_tanh(_pre(- crow, xs, ws_ptr, b_ptr, offs, m, HAS_BIAS, WS_FP32, "evict_last", True+ crow,+ xs,+ ws_ptr,+ b_ptr,+ offs,+ m,+ HAS_BIAS,+ WS_FP32,+ "evict_last",+ True,+ FP32_SCALE,+ PIN_RN,)))@@ -190,7 +238,9 @@ def _kernels() -> Optional[types.SimpleNamespace]:scale = _rbf16(tl.math.div_rn(amax, 127.5))scale = tl.maximum(scale, 1.1920928955078125e-07)inv = tl.math.div_rn(1.0, scale)- tl.store(s_ptr + row, scale)+ if not FP32_SCALE:+ inv = _rbf16(inv)+ tl.store(s_ptr + row, scale.to(s_ptr.dtype.element_ty))if HAS_PREFIX:for k in range(0, NA, CHUNK_A):j = k + abase@@ -198,7 +248,10 @@ def _kernels() -> Optional[types.SimpleNamespace]:v = tl.load(pbase + (j // HEAD_DIM) * p_sh + (j % HEAD_DIM), mask = m, other = 0.0).to(tl.float32)- qi = tl.extra.cuda.libdevice.nearbyint(v * inv)+ p = v * inv+ if not FP32_SCALE:+ p = _rbf16(p)+ qi = tl.extra.cuda.libdevice.nearbyint(p)qi = tl.minimum(tl.maximum(qi, -128.0), 127.0)tl.store(qrow + j, qi.to(tl.int8), mask = m)# pass 2: rebuild (the int32 row is mostly still in L2) and quantize.@@ -207,10 +260,26 @@ def _kernels() -> Optional[types.SimpleNamespace]:m = offs < Ng = _rbf16(_gelu_tanh(- _pre(crow, xs, ws_ptr, b_ptr, offs, m, HAS_BIAS, WS_FP32, "evict_first", True)+ _pre(+ crow,+ xs,+ ws_ptr,+ b_ptr,+ offs,+ m,+ HAS_BIAS,+ WS_FP32,+ "evict_first",+ True,+ FP32_SCALE,+ PIN_RN,+ )))- qi = tl.extra.cuda.libdevice.nearbyint(g * inv)+ p = g * inv+ if not FP32_SCALE:+ p = _rbf16(p)+ qi = tl.extra.cuda.libdevice.nearbyint(p)qi = tl.minimum(tl.maximum(qi, -128.0), 127.0)tl.store(qrow + NA + offs, qi.to(tl.int8), mask = m)@@ -232,9 +301,37 @@ def _kernels() -> Optional[types.SimpleNamespace]:HAS_BIAS: tl.constexpr,WS_FP32: tl.constexpr,EVICT: tl.constexpr,+ FP32_SCALE: tl.constexpr,+ PIN_RN: tl.constexpr,):- g = _pre(crow + g0, xs, ws_ptr + g0, b_ptr + g0, offs, m, HAS_BIAS, WS_FP32, EVICT, True)- v = _pre(crow + v0, xs, ws_ptr + v0, b_ptr + v0, offs, m, HAS_BIAS, WS_FP32, EVICT, True)+ g = _pre(+ crow + g0,+ xs,+ ws_ptr + g0,+ b_ptr + g0,+ offs,+ m,+ HAS_BIAS,+ WS_FP32,+ EVICT,+ True,+ FP32_SCALE,+ PIN_RN,+ )+ v = _pre(+ crow + v0,+ xs,+ ws_ptr + v0,+ b_ptr + v0,+ offs,+ m,+ HAS_BIAS,+ WS_FP32,+ EVICT,+ True,+ FP32_SCALE,+ PIN_RN,+ )return _rbf16(_rbf16(_silu(g)) * v)@triton.jit@@ -253,6 +350,8 @@ def _kernels() -> Optional[types.SimpleNamespace]:stride_q,HAS_BIAS: tl.constexpr,WS_FP32: tl.constexpr,+ FP32_SCALE: tl.constexpr,+ PIN_RN: tl.constexpr,CHUNK: tl.constexpr,):# c row = the fused GEMM output; the gate half starts at column G0, the value half at V0 (both N wide).@@ -268,7 +367,19 @@ def _kernels() -> Optional[types.SimpleNamespace]:offs = k + basem = offs < Nh = _swiglu_val(- crow, xs, ws_ptr, b_ptr, G0, V0, offs, m, HAS_BIAS, WS_FP32, "evict_first"+ crow,+ xs,+ ws_ptr,+ b_ptr,+ G0,+ V0,+ offs,+ m,+ HAS_BIAS,+ WS_FP32,+ "evict_first",+ FP32_SCALE,+ PIN_RN,)tl.store(hrow + offs, h.to(tl.bfloat16), mask = m, eviction_policy = "evict_last")acc = tl.maximum(acc, tl.where(m, tl.abs(h), 0.0))@@ -276,7 +387,9 @@ def _kernels() -> Optional[types.SimpleNamespace]:scale = _rbf16(tl.math.div_rn(amax, 127.5))scale = tl.maximum(scale, 1.1920928955078125e-07)inv = tl.math.div_rn(1.0, scale)- tl.store(s_ptr + row, scale)+ if not FP32_SCALE:+ inv = _rbf16(inv)+ tl.store(s_ptr + row, scale.to(s_ptr.dtype.element_ty))qrow = q_ptr + row * stride_qfor k in range(0, N, CHUNK):offs = k + base@@ -284,15 +397,83 @@ def _kernels() -> Optional[types.SimpleNamespace]:h = tl.load(hrow + offs, mask = m, other = 0.0, eviction_policy = "evict_first").to(tl.float32)- qi = tl.extra.cuda.libdevice.nearbyint(h * inv)+ p = h * inv+ if not FP32_SCALE:+ p = _rbf16(p)+ qi = tl.extra.cuda.libdevice.nearbyint(p)qi = tl.minimum(tl.maximum(qi, -128.0), 127.0)tl.store(qrow + offs, qi.to(tl.int8), mask = m)+ @triton.jit+ def gelu_bf16(x_ptr, o_ptr, n, BLOCK: tl.constexpr):+ offs = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK)+ m = offs < n+ y = tl.load(x_ptr + offs, mask = m, other = 0.0).to(tl.float32)+ tl.store(o_ptr + offs, _gelu_tanh(y).to(tl.bfloat16), mask = m)++ @triton.jit+ def dq_bf16(+ c_ptr,+ xs_ptr,+ ws_ptr,+ b_ptr,+ o_ptr,+ N,+ HAS_BIAS: tl.constexpr,+ WS_FP32: tl.constexpr,+ FP32_SCALE: tl.constexpr,+ PIN_RN: tl.constexpr,+ CHUNK: tl.constexpr,+ ):+ row = tl.program_id(0).to(tl.int64)+ xs = tl.load(xs_ptr + row).to(tl.float32)+ base = tl.arange(0, CHUNK)+ for k in range(0, N, CHUNK):+ offs = k + base+ m = offs < N+ y = _pre(+ c_ptr + row * N,+ xs,+ ws_ptr,+ b_ptr,+ offs,+ m,+ HAS_BIAS,+ WS_FP32,+ "evict_first",+ True,+ FP32_SCALE,+ PIN_RN,+ )+ tl.store(o_ptr + row * N + offs, y.to(tl.bfloat16), mask = m)+return types.SimpleNamespace(- dq_gelu_quant = dq_gelu_quant, dq_swiglu_quant = dq_swiglu_quant, triton = triton+ dq_gelu_quant = dq_gelu_quant,+ dq_swiglu_quant = dq_swiglu_quant,+ gelu_bf16 = gelu_bf16,+ dq_bf16 = dq_bf16,+ triton = triton,)+@lru_cache(maxsize = 8)+def _pin_rn_index(index: int) -> bool:+ import torch+ return torch.cuda.get_device_capability(index)[0] >= 10+++def _pin_rn(device: Any) -> bool:+ """Packed f32x2 mul / add (which ptxas contracts) exist from sm_100 on."""+ import torch+ return _pin_rn_index(device.index if device.index is not None else torch.cuda.current_device())+++def _scale_dtype(xs: Any) -> Any:+ """The output act-quant scale dtype: the incoming one (torchao's contract: fp32 on >= 0.18, bf16 on <= 0.17)."""+ import torch+ return torch.float32 if xs.dtype == torch.float32 else torch.bfloat16++def _launch(c: Any, xs: Any, ws: Any, bias: Any, prefix: Any) -> tuple:"""Run the kernel. ``prefix`` is None or a [B, S, H, D] view (any strides, last dim contiguous)."""import torch@@ -307,7 +488,7 @@ def _launch(c: Any, xs: Any, ws: Any, bias: Any, prefix: Any) -> tuple:s, d, na = 1, 1, 0p_sb = p_ss = p_sh = 0q = torch.empty((m_rows, na + n), device = c.device, dtype = torch.int8)- scale = torch.empty((m_rows,), device = c.device, dtype = torch.float32)+ scale = torch.empty((m_rows,), device = c.device, dtype = _scale_dtype(xs))with torch.cuda.device(c.device):k.dq_gelu_quant[(m_rows,)](c,@@ -327,6 +508,8 @@ def _launch(c: Any, xs: Any, ws: Any, bias: Any, prefix: Any) -> tuple:p_sh,HAS_BIAS = bias is not None,WS_FP32 = ws.dtype == torch.float32,+ FP32_SCALE = xs.dtype == torch.float32,+ PIN_RN = _pin_rn(xs.device),HAS_PREFIX = prefix is not None,HEAD_DIM = d,CHUNK = 2048,@@ -346,7 +529,7 @@ def _launch_swiglu(k = _kernels()m_rows = c.shape[0]q = torch.empty((m_rows, n), device = c.device, dtype = torch.int8)- scale = torch.empty((m_rows,), device = c.device, dtype = torch.float32)+ scale = torch.empty((m_rows,), device = c.device, dtype = _scale_dtype(xs))scratch = torch.empty((m_rows, n), device = c.device, dtype = torch.bfloat16)with torch.cuda.device(c.device):k.dq_swiglu_quant[(m_rows,)](@@ -364,6 +547,8 @@ def _launch_swiglu(q.stride(0),HAS_BIAS = bias is not None,WS_FP32 = ws.dtype == torch.float32,+ FP32_SCALE = xs.dtype == torch.float32,+ PIN_RN = _pin_rn(xs.device),CHUNK = 2048,num_warps = 8,enable_fp_fusion = False,@@ -385,8 +570,15 @@ def reference_dq_swiglu_quant(return y.to(torch.bfloat16)h = F.silu(part(gate_col)) * part(value_col)+ return _reference_act_quant(h, _scale_dtype(xs))+++def _reference_act_quant(h: Any, scale_dtype: Any) -> tuple:+ """torchao ``Int8Tensor.from_hp(h, PerRow())`` for a bf16 ``h``."""+ import torch+amax = torch.maximum(-h.amin(dim = 1).clamp(max = 0), h.amax(dim = 1).clamp(min = 0))- scale = (amax / 127.5).clamp(min = torch.finfo(torch.float32).eps).to(torch.float32)+ scale = (amax / 127.5).clamp(min = torch.finfo(torch.float32).eps).to(scale_dtype)q = torch.clamp(torch.round(h * (1.0 / scale).reshape(-1, 1)), -128, 127).to(torch.int8)return q, scale@@ -423,7 +615,7 @@ def _op() -> Any:na = 0 if prefix is None else prefix.shape[-2] * prefix.shape[-1]return (c.new_empty((c.shape[0], na + c.shape[1]), dtype = torch.int8),- c.new_empty((c.shape[0],), dtype = torch.float32),+ c.new_empty((c.shape[0],), dtype = _scale_dtype(xs)),)@custom_op(@@ -438,7 +630,7 @@ def _op() -> Any:def _(c, xs, ws, bias, gate_col, value_col, n):return (c.new_empty((c.shape[0], n), dtype = torch.int8),- c.new_empty((c.shape[0],), dtype = torch.float32),+ c.new_empty((c.shape[0],), dtype = _scale_dtype(xs)),)except Exception: # noqa: BLE001 - a registration failure keeps the stock pathreturn None@@ -464,20 +656,125 @@ def _device_ok(index: int) -> bool:try:dev = torch.device("cuda", index)g = torch.Generator(device = "cpu").manual_seed(0)- c = torch.randint(-(2**20), 2**20, (33, 200), generator = g, dtype = torch.int32).to(dev)- xs = (torch.rand(33, generator = g) * 1e-3 + 1e-5).to(torch.bfloat16).float().to(dev)+ c = torch.randint(-(2**20), 2**20, (33, 200), generator = g, dtype = torch.int32)+ c[1:5] = _bf16_tie_ints((4, 200), g)+ c = c.to(dev)+ xs = (torch.rand(33, generator = g) * 1e-3 + 1e-5).to(torch.bfloat16)+ xs[1:5] *= 2**-10ws = (torch.rand(200, generator = g) * 1e-4 + 1e-6).to(dev)bias = (torch.randn(200, generator = g) * 0.1).to(torch.bfloat16).to(dev)- q, s = _launch(c, xs, ws, bias, None)- q_ref, s_ref = reference_dq_gelu_quant(c, xs, ws, bias, None)- ok = bool(torch.equal(q, q_ref) and torch.equal(s, s_ref))- q, s = _launch_swiglu(c, xs, ws, bias, 104, 0, 96)- q_ref, s_ref = reference_dq_swiglu_quant(c, xs, ws, bias, 104, 0, 96)- return ok and bool(torch.equal(q, q_ref) and torch.equal(s, s_ref))+ for x_scale in (xs.float().to(dev), xs.to(dev)):+ for w_scale in (ws, ws.to(torch.bfloat16)):+ q, s = _launch(c, x_scale, w_scale, bias, None)+ q_ref, s_ref = reference_dq_gelu_quant(c, x_scale, w_scale, bias, None)+ if not (s.dtype == s_ref.dtype and torch.equal(q, q_ref) and torch.equal(s, s_ref)):+ return False+ q, s = _launch_swiglu(c, x_scale, w_scale, bias, 104, 0, 96)+ q_ref, s_ref = reference_dq_swiglu_quant(c, x_scale, w_scale, bias, 104, 0, 96)+ if not (s.dtype == s_ref.dtype and torch.equal(q, q_ref) and torch.equal(s, s_ref)):+ return False+ return (+ _act_quant_contract_ok(dev)+ and _gelu_matches_aten(dev)+ and _epilogue_matches_torchao(dev)+ )except Exception: # noqa: BLE001 - any build / launch failure keeps the stock pathreturn False+def _bf16_tie_ints(shape: tuple, generator: Any) -> Any:+ """int32 values in [2^24, 2^30) within one fp32 ulp of a bf16 midpoint: one vs two roundings disagree there."""+ import torch++ n = 1+ for d in shape:+ n *= d+ e = torch.randint(24, 30, (n,), generator = generator, dtype = torch.int64)+ mant = torch.randint(0, 128, (n,), generator = generator, dtype = torch.int64)+ ulp = torch.bitwise_left_shift(torch.ones_like(e), e - 23)+ off = torch.randint(-1, 2, (n,), generator = generator, dtype = torch.int64) * (ulp // 2).clamp(+ min = 1+ ) + torch.randint(-1, 2, (n,), generator = generator, dtype = torch.int64)+ mid = (+ torch.bitwise_left_shift(torch.ones_like(e), e)+ + mant * torch.bitwise_left_shift(torch.ones_like(e), e - 7)+ + torch.bitwise_left_shift(torch.ones_like(e), e - 8)+ )+ sign = torch.randint(0, 2, (n,), generator = generator, dtype = torch.int64) * 2 - 1+ return ((mid + off) * sign).to(torch.int32).reshape(shape)+++def _epilogue_matches_torchao(+ dev: Any,+ m: int = 1031,+ n: int = 2056,+) -> bool:+ """The epilogue equals torchao's ``bf16(bf16(c * xs) * ws + bias)``; fp32 ``ws`` + bias exposes an FMA."""+ import torch++ g = torch.Generator(device = "cpu").manual_seed(2)+ c = torch.randint(-(2**20), 2**20, (m, n), generator = g, dtype = torch.int32).to(dev)+ ws = (torch.rand(n, generator = g) * 1e-4 + 1e-6).to(dev)+ bias = (torch.randn(n, generator = g) * 0.1).to(torch.bfloat16).to(dev)+ xs = (torch.rand(m, generator = g) * 1e-3 + 1e-5).to(torch.bfloat16)+ k = _kernels()+ for x_scale in (xs.float().to(dev), xs.to(dev)):+ out = torch.empty((m, n), device = dev, dtype = torch.bfloat16)+ with torch.cuda.device(dev):+ k.dq_bf16[(m,)](+ c,+ x_scale,+ ws,+ bias,+ out,+ n,+ HAS_BIAS = True,+ WS_FP32 = True,+ FP32_SCALE = x_scale.dtype == torch.float32,+ PIN_RN = _pin_rn(x_scale.device),+ CHUNK = 2048,+ num_warps = 8,+ enable_fp_fusion = False,+ )+ ref = ((c * x_scale.reshape(-1, 1)).to(torch.bfloat16) * ws + bias).to(torch.bfloat16)+ if not torch.equal(out, ref):+ return False+ return True+++def _gelu_matches_aten(dev: Any) -> bool:+ """The kernels' GELU(tanh) equals ``F.gelu(x, approximate="tanh")`` on every finite bf16 ``x``, bit for bit."""+ import torch+ import torch.nn.functional as F++ x = torch.arange(-(2**15), 2**15, dtype = torch.int32).to(torch.int16).view(torch.bfloat16)+ x = x[torch.isfinite(x)].to(dev)+ out = torch.empty_like(x)+ k = _kernels()+ with torch.cuda.device(dev):+ k.gelu_bf16[(k.triton.cdiv(x.numel(), 1024),)](+ x, out, x.numel(), BLOCK = 1024, num_warps = 4, enable_fp_fusion = False+ )+ return bool(torch.equal(out.view(torch.int16), F.gelu(x, approximate = "tanh").view(torch.int16)))+++def _act_quant_contract_ok(dev: Any) -> bool:+ """``_reference_act_quant`` in this torchao's scale dtype equals ``Int8Tensor.from_hp(h, PerRow())`` bit for bit."""+ import torch+ from torchao.quantization.granularity import PerRow+ from torchao.quantization.quantize_.workflows.int8.int8_tensor import Int8Tensor++ g = torch.Generator(device = "cpu").manual_seed(1)+ h = torch.randn(37, 520, generator = g) * (torch.rand(1, 520, generator = g) * 4)+ h[:, :3] *= 50+ h[2] = 0+ h = h.to(torch.bfloat16).to(dev)+ t = Int8Tensor.from_hp(h, PerRow())+ s_ref = t.scale.reshape(-1)+ q, s = _reference_act_quant(h, s_ref.dtype)+ return bool(torch.equal(q, t.qdata) and torch.equal(s, s_ref))++def reference_dq_gelu_quant(c: Any, xs: Any, ws: Any, bias: Any, prefix: Any) -> tuple:"""Eager torch mirror of the stock chain (torchao epilogue, ATen GELU, torchao per-row act quant)."""import torch@@ -492,10 +789,7 @@ def reference_dq_gelu_quant(c: Any, xs: Any, ws: Any, bias: Any, prefix: Any) ->g = torch.cat([prefix.reshape(prefix.shape[0] * prefix.shape[1], -1).to(g.dtype), g], dim = -1)- amax = torch.maximum(-g.amin(dim = 1).clamp(max = 0), g.amax(dim = 1).clamp(min = 0))- scale = (amax / 127.5).clamp(min = torch.finfo(torch.float32).eps).to(torch.float32)- q = torch.clamp(torch.round(g * (1.0 / scale).reshape(-1, 1)), -128, 127).to(torch.int8)- return q, scale+ return _reference_act_quant(g, _scale_dtype(xs))def _plain_int8_weight(w: Any) -> bool:@@ -535,12 +829,11 @@ def _act_quant(x2d: Any, weight: Any) -> tuple:_choose_quant_func_and_quantize_tensor,)- act = _choose_quant_func_and_quantize_tensor(- x2d,- weight.act_quant_kwargs,- scale = weight.act_quant_scale,- zero_point = weight.act_quant_zero_point,- )+ kwargs = {"scale": weight.act_quant_scale}+ # torchao <= 0.16 has no activation zero point (neither the attribute nor the kwarg).+ if hasattr(weight, "act_quant_zero_point"):+ kwargs["zero_point"] = weight.act_quant_zero_point+ act = _choose_quant_func_and_quantize_tensor(x2d, weight.act_quant_kwargs, **kwargs)return act.qdata, act.scale@@ -555,10 +848,11 @@ def _linear_from_q(q: Any, xs: Any, weight: Any, bias: Any, out_dtype: Any) -> Aif out_dtype == torch.bfloat16:from .diffusion_int8_gemm import linear_from_q- fused = linear_from_q(q, xs.reshape(-1).to(torch.float32), weight, bias)+ fused = linear_from_q(q, xs.reshape(-1), weight, bias)if fused is not None:return fused- y = (_int_mm(q, weight) * xs.reshape(-1, 1).to(torch.float32)).to(out_dtype)+ inter = torch.float32 if xs.dtype == torch.float16 else xs.dtype+ y = (_int_mm(q, weight) * xs.reshape(-1, 1).to(inter)).to(out_dtype)y = y * weight.scale.flatten()if bias is not None:y = y + biasdiff --git a/studio/backend/core/inference/diffusion_int8_gemm.py b/studio/backend/core/inference/diffusion_int8_gemm.pyindex 111b98d42a1..32c8276be64 100644--- a/studio/backend/core/inference/diffusion_int8_gemm.py+++ b/studio/backend/core/inference/diffusion_int8_gemm.py@@ -9,7 +9,8 @@ writes bf16, so every int8 Linear writes half the bytes and its consumer (norm,NUMERICS: the Linear output is bit-identical to torchao's epilogue, eager and compiled under Studio's``emulate_precision_casts``: ``bf16(bf16(r(c) * xs) * ws)`` (+ bias as a bf16 add), where ``r`` rounds the int32-accumulator to bf16 when the activation scale is bf16 (int32 * bf16 promotes to bf16) and is exact when it is fp32.+accumulator to bf16 when the activation scale is bf16 (int32 * bf16 promotes to bf16, via fp32: two roundings) and to+fp32 when it is fp32.The activation quant is torchao's own math, so Inductor still fuses it into the producer. A compiled block is NOTbit-identical end to end: the consumer reductions (LayerNorm / RMSNorm Welford) that used to fuse the epilogue nowread bf16 and Inductor re-tiles them, a rounding-order change smaller than compiled-vs-eager (LPIPS-gated).@@ -166,15 +167,18 @@ def _kernels() -> Optional[types.SimpleNamespace]:# torchao epilogue, every rounding kept: (int32 * xs) -> xs dtype, * ws -> ws dtype, -> bf16, + bias.xs = tl.load(xs_ptr + rm).to(tl.float32)ws = tl.load(ws_ptr + rn).to(tl.float32)- y = acc.to(tl.float32)- if not XS_FP32:- y = _rbf16(y)+ if XS_FP32:+ y = acc.to(tl.float32)+ else:+ # int32 -> fp32 -> bf16 rounds twice; Triton folds ``acc.to(fp32).to(bf16)`` into one rounding.+ y = _rbf16(tl.extra.cuda.libdevice.int2float_rn(acc))y = _rbf16(y * xs[:, None])- y = y * ws[None, :]+ # *_rn: ptxas fuses packed f32x2 mul + add into an FMA on sm_100 even with fp fusion off.+ y = tl.extra.cuda.libdevice.mul_rn(y, ws[None, :])if not WS_FP32:y = _rbf16(y)if HAS_BIAS:- y = y + tl.load(b_ptr + rn).to(tl.float32)[None, :]+ y = tl.extra.cuda.libdevice.add_rn(y, tl.load(b_ptr + rn).to(tl.float32)[None, :])c_ptrs = c_ptr + offs_m[:, None] * stride_cm + offs_n[None, :]mask = (offs_m[:, None] < M) & (offs_n[None, :] < N)tl.store(c_ptrs, y.to(tl.bfloat16), mask = mask)@@ -350,12 +354,47 @@ def _probe(index: int, cfg: tuple) -> bool:b = (torch.randn(n, generator = g) * 0.1).to(torch.bfloat16).to(dev) if bias else Noneif not torch.equal(_launch(a, w, xs, ws, b, cfg), reference(a, w, xs, ws, b)):return False+ a, w = tie_operands(dev)+ xs = torch.ones(a.shape[0], device = dev, dtype = torch.bfloat16)+ ws = torch.ones(w.shape[0], device = dev, dtype = torch.bfloat16)+ if not torch.equal(_launch(a, w, xs, ws, None, cfg), reference(a, w, xs, ws, None)):+ return Falsetorch.cuda.synchronize(dev)return Trueexcept Exception: # noqa: BLE001 - out of shared memory, compile failure, ...return False+def tie_operands(+ device: Any,+ rows: int = 32,+ k: int = 4096,+) -> tuple:+ """int8 (a, w) whose int32 products sit one or two units off a bf16 midpoint in [2^24, 2^26), both signs."""+ import torch++ k2 = 128+ k1 = k - k2+ targets = []+ for e in (24, 25):+ for mult in (0, 3, 50, 100):+ mid = (1 << e) + mult * (1 << (e - 7)) + (1 << (e - 8))+ for d in (-1, 1, -2, 2):+ targets += [mid + d, -(mid + d)]+ w = torch.zeros(len(targets), k, dtype = torch.int8)+ for j, t in enumerate(targets):+ s1, s2 = divmod(abs(t), 127)+ full, rem = divmod(s1, 127)+ sign = 1 if t >= 0 else -1+ w[j, :full] = 127 * sign+ if rem:+ w[j, full] = rem * sign+ w[j, k1] = s2 * sign+ a = torch.ones(rows, k, dtype = torch.int8)+ a[:, :k1] = 127+ return a.to(device), w.to(device)++def _v1_parts(w: Any) -> Optional[tuple]:"""(int8 [N, K], scale [N]) of a torchao v1 ``LinearActivationQuantizedTensor`` over a plain-layout symmetricper-channel ``AffineQuantizedTensor`` with the per-token reduced-range activation quant, else None."""diff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.pyindex 3908109a1f4..035776cff64 100644--- a/studio/backend/tests/conftest.py+++ b/studio/backend/tests/conftest.py@@ -189,6 +189,20 @@ def _reset_gpu_query_cache():_reset()[email protected](autouse = True)+def _restore_fp32_matmul_precision():+ # torchao's default config handler sets set_float32_matmul_precision("high") process-wide.+ def _get():+ getter = getattr(sys.modules.get("torch"), "get_float32_matmul_precision", None)+ return getter() if getter is not None else None++ before = _get() or "highest"+ yield+ after = _get()+ if after is not None and after != before:+ sys.modules["torch"].set_float32_matmul_precision(before)++@pytest.fixture(autouse = True)def _reset_media_import_window(monkeypatch):# A load path claims the window for the process; later prewarm tests would skip.diff --git a/studio/backend/tests/test_diffusion_int8_fused.py b/studio/backend/tests/test_diffusion_int8_fused.pyindex 2f666a23328..0e72ca2c718 100644--- a/studio/backend/tests/test_diffusion_int8_fused.py+++ b/studio/backend/tests/test_diffusion_int8_fused.py@@ -28,6 +28,35 @@ needs_cuda = pytest.mark.skipif()+def _cuda_int8_toolchain() -> bool:+ """The probe's prerequisites without the probe: on such a host a refused probe is a failure, not a skip."""+ if not torch.cuda.is_available() or getattr(torch.version, "hip", None):+ return False+ try:+ from torchao.quantization.quantize_.workflows.int8.int8_tensor import Int8Tensor # noqa: F401+ except Exception: # noqa: BLE001+ return False+ return fused._triton_version_ok() and fused._triton_jit_toolchain_ok()+++ not _cuda_int8_toolchain(), reason = "needs CUDA (not ROCm), Triton >= 3.2, torchao"+)+def test_device_probe_accepts_this_torchao():+ fused._device_ok.cache_clear()+ assert fused._device_ok(torch.cuda.current_device())+++def _int8_config():+ """Studio's int8 config as an ``Int8Tensor`` (0.17 defaults to the legacy tensor), no process-wide setter."""+ from torchao.quantization import Int8DynamicActivationInt8WeightConfig++ cfg = Int8DynamicActivationInt8WeightConfig(set_inductor_config = False)+ if hasattr(cfg, "version"):+ cfg.version = 2+ return cfg++def _require_int8tensor(module):"""Skip when the torchao (<= 0.17) int8 config builds the legacy tensor: the fused path then keeps stock."""for m in module.modules():@@ -97,16 +126,23 @@ def _rand_inputs(ws_dtype = torch.float32,bias = True,seed = 0,+ xs_dtype = torch.float32,):g = torch.Generator(device = "cpu").manual_seed(seed)c = torch.randint(-(2**20), 2**20, (m, n), generator = g, dtype = torch.int32).cuda()- xs = (torch.rand(m, generator = g) * 1e-3 + 1e-5).to(torch.bfloat16).float().cuda()+ xs = (torch.rand(m, generator = g) * 1e-3 + 1e-5).to(torch.bfloat16).to(xs_dtype).cuda()ws = (torch.rand(n, generator = g) * 1e-4 + 1e-6).to(ws_dtype).cuda()b = (torch.randn(n, generator = g) * 0.1).to(torch.bfloat16).cuda() if bias else Nonereturn c, xs, ws, b+_XS_DTYPES = pytest.mark.parametrize(+ "xs_dtype", [torch.float32, torch.bfloat16], ids = ["xs_fp32", "xs_bf16"]+)++@needs_cuda+@_XS_DTYPES@pytest.mark.parametrize("m, n, ws_dtype, bias",[@@ -116,18 +152,20 @@ def _rand_inputs((17, 8, torch.float32, True), # smallest eligible],)-def test_kernel_bit_exact_vs_eager_reference(m, n, ws_dtype, bias):- c, xs, ws, b = _rand_inputs(m, n, ws_dtype = ws_dtype, bias = bias)+def test_kernel_bit_exact_vs_eager_reference(m, n, ws_dtype, bias, xs_dtype):+ c, xs, ws, b = _rand_inputs(m, n, ws_dtype = ws_dtype, bias = bias, xs_dtype = xs_dtype)q, s = fused._launch(c, xs, ws, b, None)q_ref, s_ref = fused.reference_dq_gelu_quant(c, xs, ws, b, None)+ assert s.dtype == s_ref.dtype == xs_dtypeassert torch.equal(s, s_ref)assert torch.equal(q, q_ref)@needs_cuda-def test_kernel_small_activations_take_the_exact_amax_path():+@_XS_DTYPES+def test_kernel_small_activations_take_the_exact_amax_path(xs_dtype):# Every pre-activation negative: max|gelu| comes from the negative lobe, not gelu(max y).- c, xs, ws, b = _rand_inputs(256, 1024, bias = False)+ c, xs, ws, b = _rand_inputs(256, 1024, bias = False, xs_dtype = xs_dtype)c = -c.abs() - 1q, s = fused._launch(c, xs, ws, b, None)q_ref, s_ref = fused.reference_dq_gelu_quant(c, xs, ws, b, None)@@ -135,10 +173,11 @@ def test_kernel_small_activations_take_the_exact_amax_path():@needs_cuda+@_XS_DTYPES@pytest.mark.parametrize("transposed", [False, True])-def test_kernel_prefix_segment(transposed):+def test_kernel_prefix_segment(transposed, xs_dtype):bsz, seq, heads, hd, n = 2, 300, 4, 64, 1024- c, xs, ws, b = _rand_inputs(bsz * seq, n)+ c, xs, ws, b = _rand_inputs(bsz * seq, n, xs_dtype = xs_dtype)if transposed: # SDPA output layout [B, H, S, D] seen as [B, S, H, D]prefix = ((torch.randn(bsz, heads, seq, hd, device = "cuda") * 3).to(torch.bfloat16).transpose(1, 2)@@ -157,7 +196,7 @@ def _quantized_ff(seed = 0,):FeedForward = pytest.importorskip("diffusers.models.attention").FeedForward- from torchao.quantization import Int8DynamicActivationInt8WeightConfig, quantize_+ from torchao.quantization import quantize_torch.manual_seed(seed)ff = (@@ -168,7 +207,7 @@ def _quantized_ff()for p in ff.parameters():p.data.normal_(0, 0.05)- quantize_(ff, Int8DynamicActivationInt8WeightConfig())+ quantize_(ff, _int8_config())return _require_int8tensor(ff)@@ -235,7 +274,7 @@ def test_uninstall_restores_stock_forward():@needs_cudadef test_flux_single_block_bit_identical_to_stock_eager():tf = pytest.importorskip("diffusers.models.transformers.transformer_flux")- from torchao.quantization import Int8DynamicActivationInt8WeightConfig, quantize_+ from torchao.quantization import quantize_torch.manual_seed(0)blk = (@@ -248,7 +287,7 @@ def test_flux_single_block_bit_identical_to_stock_eager():p.data.normal_(0, 0.05)quantize_(blk,- Int8DynamicActivationInt8WeightConfig(),+ _int8_config(),filter_fn = lambda m, fqn: isinstance(m, torch.nn.Linear) and "norm" not in fqn,)_require_int8tensor(blk)@@ -263,22 +302,123 @@ def test_flux_single_block_bit_identical_to_stock_eager():@needs_cuda+@_XS_DTYPES@pytest.mark.parametrize("m, n, gate_col, value_col", [(4352, 10240, 0, 10240), (300, 1024, 1024, 0), (17, 64, 0, 64)])-def test_swiglu_kernel_bit_exact_vs_eager_reference(m, n, gate_col, value_col):- c, xs, ws, b = _rand_inputs(m, 2 * n, bias = False)+def test_swiglu_kernel_bit_exact_vs_eager_reference(m, n, gate_col, value_col, xs_dtype):+ c, xs, ws, b = _rand_inputs(m, 2 * n, bias = False, xs_dtype = xs_dtype)q, s = fused._launch_swiglu(c, xs, ws, None, gate_col, value_col, n)q_ref, s_ref = fused.reference_dq_swiglu_quant(c, xs, ws, None, gate_col, value_col, n)+ assert s.dtype == s_ref.dtype == xs_dtype+ assert torch.equal(s, s_ref) and torch.equal(q, q_ref)+++def _bf16_tie_ints(m, n, seed):+ """int32 accumulators in [2^24, 2^30) within one fp32 ulp of a bf16 rounding midpoint, both signs."""+ g = torch.Generator(device = "cpu").manual_seed(seed)+ e = torch.randint(24, 30, (m, n), generator = g, dtype = torch.int64)+ one = torch.ones_like(e)+ mid = (+ torch.bitwise_left_shift(one, e)+ + torch.randint(0, 128, (m, n), generator = g, dtype = torch.int64)+ * torch.bitwise_left_shift(one, e - 7)+ + torch.bitwise_left_shift(one, e - 8)+ )+ half_ulp = torch.bitwise_left_shift(one, e - 24)+ off = torch.randint(-1, 2, (m, n), generator = g, dtype = torch.int64) * half_ulp+ off = off + torch.randint(-1, 2, (m, n), generator = g, dtype = torch.int64)+ sign = torch.randint(0, 2, (m, n), generator = g, dtype = torch.int64) * 2 - 1+ return ((mid + off) * sign).to(torch.int32).cuda()+++def _double_rounding_hits(c):+ """How many int32 values round differently int32 -> bf16 directly (exact RNE in int64) than via fp32 (torch)."""+ v = c.cpu().to(torch.int64)+ a = v.abs()+ e = torch.floor(torch.log2(a.double().clamp(min = 1))).to(torch.int64)+ shift = (e - 7).clamp(min = 1)+ one = torch.ones_like(a)+ q = torch.bitwise_right_shift(a, shift)+ r = a - torch.bitwise_left_shift(q, shift)+ half = torch.bitwise_left_shift(one, shift - 1)+ q = q + ((r > half) | ((r == half) & (q % 2 == 1))).to(torch.int64)+ single = torch.bitwise_left_shift(q, shift) * v.sign()+ double = c.cpu().float().to(torch.bfloat16).double().to(torch.int64)+ return int((single != double)[a >= 2**24].sum())+++@needs_cuda+@_XS_DTYPES+def test_kernels_round_large_accumulators_like_torchao(xs_dtype):+ m, n = 64, 2048+ c = _bf16_tie_ints(m, n, 3)+ assert _double_rounding_hits(c) > 100 # the inputs do reach the case+ _, xs, ws, b = _rand_inputs(m, n, xs_dtype = xs_dtype)+ xs = (xs * 2**-10).to(xs_dtype) # |c * xs| stays O(1-100): GELU / SiLU in their curved range+ q, s = fused._launch(c, xs, ws, b, None)+ q_ref, s_ref = fused.reference_dq_gelu_quant(c, xs, ws, b, None)+ assert torch.equal(s, s_ref) and torch.equal(q, q_ref)+ q, s = fused._launch_swiglu(c, xs, ws, b, n // 2, 0, n // 2)+ q_ref, s_ref = fused.reference_dq_swiglu_quant(c, xs, ws, b, n // 2, 0, n // 2)assert torch.equal(s, s_ref) and torch.equal(q, q_ref)+@needs_cuda+def test_gelu_rounds_every_bf16_input_like_aten():+ assert fused._gelu_matches_aten(torch.device("cuda", torch.cuda.current_device()))+++@needs_cuda+def test_epilogue_rounds_scale_product_and_bias_separately():+ assert fused._epilogue_matches_torchao(+ torch.device("cuda", torch.cuda.current_device()), 4101, 3000+ )+++@needs_cuda+def test_reference_act_quant_is_torchao_own():+ from torchao.quantization.granularity import PerRow+ from torchao.quantization.quantize_.workflows.int8.int8_tensor import Int8Tensor++ g = torch.Generator(device = "cpu").manual_seed(5)+ h = torch.randn(300, 3072, generator = g) * (torch.rand(1, 3072, generator = g) * 6)+ h[:, :4] *= 80+ h[7] = 0+ h = h.to(torch.bfloat16).cuda()+ t = Int8Tensor.from_hp(h, PerRow())+ q, s = fused._reference_act_quant(h, t.scale.dtype)+ assert torch.equal(q, t.qdata) and torch.equal(s, t.scale.reshape(-1))+++@needs_cuda+@_XS_DTYPES+def test_fake_ops_report_the_real_scale_dtype(xs_dtype):+ from torch._subclasses.fake_tensor import FakeTensorMode++ c, xs, ws, b = _rand_inputs(40, 256, xs_dtype = xs_dtype)+ op = fused._op()+ real = (op.gelu(c, xs, ws, b, None)[1], op.swiglu(c, xs, ws, b, 128, 0, 128)[1])+ with FakeTensorMode() as mode:+ fc, fxs, fws, fb = (mode.from_tensor(t) for t in (c, xs, ws, b))+ fake = (op.gelu(fc, fxs, fws, fb, None)[1], op.swiglu(fc, fxs, fws, fb, 128, 0, 128)[1])+ assert [t.dtype for t in fake] == [t.dtype for t in real] == [xs_dtype, xs_dtype]+++@needs_cuda+def test_quantizing_leaves_fp32_matmul_precision_alone():+ # The default handler's recommended_inductor_config_setter() turns on TF32 process-wide; Studio opts out.+ before = torch.get_float32_matmul_precision()+ _quantized_ff()+ assert torch.get_float32_matmul_precision() == before++def _quantize(module):- from torchao.quantization import Int8DynamicActivationInt8WeightConfig, quantize_+ from torchao.quantization import quantize_for p in module.parameters():p.data.normal_(0, 0.05)- quantize_(module, Int8DynamicActivationInt8WeightConfig())+ quantize_(module, _int8_config())return _require_int8tensor(module)@@ -606,7 +746,7 @@ def test_int8_flux_under_fbcache_renders_through_the_fused_kernel():tf = pytest.importorskip("diffusers.models.transformers.transformer_flux")hooks = pytest.importorskip("diffusers.hooks")- from torchao.quantization import Int8DynamicActivationInt8WeightConfig, quantize_+ from torchao.quantization import quantize_torch.manual_seed(0)model = (@@ -629,7 +769,7 @@ def test_int8_flux_under_fbcache_renders_through_the_fused_kernel():p.data.normal_(0, 0.05)quantize_(model,- Int8DynamicActivationInt8WeightConfig(),+ _int8_config(),filter_fn = lambda m, fqn: isinstance(m, torch.nn.Linear)and "single_transformer_blocks" in fqnand "norm" not in fqn,diff --git a/studio/backend/tests/test_diffusion_int8_gemm.py b/studio/backend/tests/test_diffusion_int8_gemm.pyindex 5c1853f7560..93b03ec3cff 100644--- a/studio/backend/tests/test_diffusion_int8_gemm.py+++ b/studio/backend/tests/test_diffusion_int8_gemm.py@@ -187,6 +187,74 @@ def test_op_is_bit_exact_vs_torchao_epilogue(forced, m, k, n, bias, xs32, ws32):assert torch.equal(out, g8.reference(a, w, xs, ws, b))+def _tie_operands(k = 4096, rows = 32):+ """int8 a, w whose int32 products sit one or two units off a bf16 midpoint in [2^24, 2^26), both signs."""+ k1 = k - 128+ targets = []+ for e in (24, 25):+ for mult in (0, 3, 50, 100):+ mid = (1 << e) + mult * (1 << (e - 7)) + (1 << (e - 8))+ for d in (-1, 1, -2, 2):+ targets += [mid + d, -(mid + d)]+ w = torch.zeros(len(targets), k, dtype = torch.int8)+ for j, t in enumerate(targets):+ s1, s2 = divmod(abs(t), 127)+ full, rem = divmod(s1, 127)+ sign = 1 if t >= 0 else -1+ w[j, :full] = 127 * sign+ w[j, full] = rem * sign+ w[j, k1] = s2 * sign+ a = torch.ones(rows, k, dtype = torch.int8)+ a[:, :k1] = 127+ return a.cuda(), w.cuda(), torch.tensor(targets, dtype = torch.int32)+++@needs_cuda[email protected]("cfg", sorted({g8._FALLBACK_CONFIG, *g8._ARCH_CONFIG.values()}))[email protected]("ws32", [False, True])+def test_epilogue_rounds_large_accumulators_twice_like_torch(cfg, ws32):+ # Arch-independent epilogue math: every tile config is launched directly, past the arch gate.+ a, w, targets = _tie_operands()+ assert torch.equal(torch._int_mm(a, w.t())[0].cpu(), targets)+ assert (+ int((_one_rounding_bf16(targets) != targets.float().to(torch.bfloat16).float()).sum()) >= 8+ )+ xs = torch.ones(a.shape[0], device = "cuda", dtype = torch.bfloat16)+ ws = torch.ones(w.shape[0], device = "cuda", dtype = torch.float32 if ws32 else torch.bfloat16)+ try:+ out = g8._launch(a, w, xs, ws, None, cfg)+ except Exception as exc: # noqa: BLE001 - a tile this part's shared memory cannot hold+ pytest.skip(f"tile {cfg} does not launch here: {exc}")+ ref = g8.reference(a, w, xs, ws, None)+ assert torch.equal(ref[0].float().cpu(), targets.float().to(torch.bfloat16).float())+ assert torch.equal(out, ref)+++@needs_cuda+def test_probe_covers_the_double_rounding():+ a, w = g8.tie_operands(torch.device("cuda"))+ c = torch._int_mm(a, w.t())[0].cpu()+ assert int((_one_rounding_bf16(c) != c.float().to(torch.bfloat16).float()).sum()) >= 8+ xs = torch.ones(a.shape[0], device = "cuda", dtype = torch.bfloat16)+ ws = torch.ones(w.shape[0], device = "cuda", dtype = torch.bfloat16)+ out = g8._launch(a, w, xs, ws, None, g8._FALLBACK_CONFIG)+ assert torch.equal(out, g8.reference(a, w, xs, ws, None))+++def _one_rounding_bf16(c):+ """int32 -> bf16 with ONE round-to-nearest-even (exact, in int64), as fp32 values."""+ v = c.to(torch.int64)+ a = v.abs()+ e = torch.floor(torch.log2(a.double().clamp(min = 1))).to(torch.int64)+ shift = (e - 7).clamp(min = 1)+ q = torch.bitwise_right_shift(a, shift)+ r = a - torch.bitwise_left_shift(q, shift)+ half = torch.bitwise_left_shift(torch.ones_like(a), shift - 1)+ q = q + ((r > half) | ((r == half) & (q % 2 == 1))).to(torch.int64)+ out = (torch.bitwise_left_shift(q, shift) * v.sign()).double()+ return torch.where(a < 256, v.double(), out).float()++@needs_cuda@pytest.mark.parametrize("version", [None, 2])@pytest.mark.parametrize("bias", [False, True])diff --git a/studio/backend/tests/test_diffusion_zimage_fused.py b/studio/backend/tests/test_diffusion_zimage_fused.pyindex 3bf49476f0b..7320ac0d93e 100644--- a/studio/backend/tests/test_diffusion_zimage_fused.py+++ b/studio/backend/tests/test_diffusion_zimage_fused.py@@ -78,7 +78,7 @@ def _block(quant: str):from torchao.quantization import Int8DynamicActivationInt8WeightConfig, quantize_quantize_(blk,- Int8DynamicActivationInt8WeightConfig(),+ Int8DynamicActivationInt8WeightConfig(set_inductor_config = False),filter_fn = lambda m, fqn: isinstance(m, torch.nn.Linear) and "adaLN" not in fqn,)return blk