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 ROCm RDNA int8: Triton W8A8 kernels and fused Qwen-Image-2.1 projections (gfx1151 INT8 -12% per step, explicit int8 -26% to -34%) (#17334)
Daniel Han57c9573420c2
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 3e57c1c1cb6..bf9aa62d07e 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -547,6 +547,7 @@ from .diffusion_transformer_quant import (nvfp4_gated_base,native_int8_act,rdna_auto_w8a8_reason,+ rdna_explicit_int8_reason,native_offload_host,native_quant_host,native_quant_scheme,@@ -8709,6 +8710,21 @@ class DiffusionBackend:rdna_auto_w8a8,)transformer_quant = TQ_INT8+ # An explicit int8 request compiles from render 1 when the denoiser stays resident; W8A8 only where the+ # family's AUTO table measured it faster (weight-only int8 elsewhere).+ rdna_explicit_int8 = (+ rdna_explicit_int8_reason(target, getattr(fam, "name", None))+ if rdna_auto_w8a8 is None+ and transformer_quant_pinned == TQ_INT8+ and kind == "pipeline"+ and not _memory_request_forces_offload(memory_mode, cpu_offload)+ and (+ speed_mode is None+ or normalize_speed_mode(speed_mode) in (SPEED_DEFAULT, SPEED_MAX)+ )+ and compile_eligible(target, is_gguf = False, family = fam, probe = False)+ else None+ )native_scheme = (native_quant_scheme(target,@@ -10468,6 +10484,9 @@ class DiffusionBackend:plan.offload_policy,)inplace_decline = None+ if rdna_explicit_int8 is not None and not keeps_resident:+ # Measured resident only: an offloaded int8 DiT keeps the eager weight-only path.+ rdna_explicit_int8 = Noneif rdna_auto_w8a8 is not None and not keeps_resident:# Measured resident only: AUTO keeps bf16 when even the int8 plan offloads.native_scheme = rdna_auto_w8a8 = None@@ -10527,7 +10546,17 @@ class DiffusionBackend:{"offload": plan.offload_policy != OFFLOAD_NONE,"act_int8": native_scheme == TQ_INT8- and (native_int8_act(target) or rdna_auto_w8a8 is not None),+ and (+ native_int8_act(target)+ or rdna_auto_w8a8 is not None+ or (+ rdna_explicit_int8 is not None+ and rdna_auto_w8a8_reason(+ target, getattr(fam, "name", None)+ )+ is not None+ )+ ),}if native_scheme is not Noneelse {}@@ -10704,14 +10733,14 @@ class DiffusionBackend:)effective_speed = SPEED_DEFAULTif (- rdna_auto_w8a8 is not None+ (rdna_auto_w8a8 is not None or rdna_explicit_int8 is not None)and transformer_quant_engaged is not Noneand speed_mode is Noneand effective_speed == SPEED_OFFand compile_eligible(target, is_gguf = False, family = fam, probe = False)):logger.info(- "diffusion.speed: speed_mode=default from render 1 (auto int8 W8A8 on RDNA is "+ "diffusion.speed: speed_mode=default from render 1 (int8 on RDNA is ""measured compiled)")effective_speed = SPEED_DEFAULTdiff --git a/studio/backend/core/inference/diffusion_native_quant.py b/studio/backend/core/inference/diffusion_native_quant.pyindex 95016fac3e9..5ea074e1efa 100644--- a/studio/backend/core/inference/diffusion_native_quant.py+++ b/studio/backend/core/inference/diffusion_native_quant.py@@ -493,6 +493,8 @@ def native_linear_class():from torch import nnfrom torch.nn import functional as F+ from . import diffusion_native_w8a8_rdna as rdna+class NativeWeightOnlyLinear(nn.Module):"""A Linear whose weight is stored as int8 / fp8 with a per-output-row scale."""@@ -594,6 +596,13 @@ def native_linear_class():# Registered here, in eager, so a compiled forward only reads the handle (see _row_major_op).self._row_major = _row_major_op() if self.act_int8 and not self.rot_group else Noneself._int8pack_scales: dict = {}+ # ROCm RDNA: fused rotate+quant and int8 GEMM kernels, probed per card here, in eager, before any trace.+ self._rdna = False+ if self.act_int8:+ self._rdna = (+ rdna.shape_supported(self.in_features, self.out_features, self.rot_group)+ and rdna.prepare()+ )def _widen(self, codes: Any) -> Any:"""Exact float32 values of a row slice of ``weight_q``, as the eager branches below."""@@ -691,6 +700,27 @@ def native_linear_class():out = out.mul_(w_scale)return out+ def _forward_rdna(self, x: Any) -> Any:+ x2 = x.reshape(-1, self.in_features)+ xq, xs = rdna.rotq(x2, self.rot_group)+ out = rdna.w8a8_mm(+ xq, xs, self.weight_q, self.weight_scale.view(torch.float32), self.bias, x.dtype+ )+ return out.reshape(*x.shape[:-1], self.out_features)++ def _rdna_on(self, x: Any) -> bool:+ if not (self._rdna and x.is_cuda and x.dtype in (torch.bfloat16, torch.float16)):+ return False+ # The custom ops have no backward: a graph that needs input gradients keeps the stock maths.+ if x.requires_grad and torch.is_grad_enabled():+ return False+ index = x.device.index+ if not torch.compiler.is_compiling() and index not in rdna._STATE["on"]:+ rdna.prepare(x.device)+ return rdna.enabled_for(index) and self._int_mm_ok(+ x.numel() // max(1, self.in_features)+ )+def _forward_int_mm(self, x: Any) -> Any:x2 = x.reshape(-1, self.in_features)rows = x2.shape[0]@@ -831,6 +861,8 @@ def native_linear_class():out = self._forward_int8pack(x)if out is not None:return out+ if self.act_int8 and self._rdna_on(x):+ return self._forward_rdna(x)if self.act_int8 and x.is_cuda and not torch.compiler.is_compiling():out = self._forward_fused(x)if out is not None:diff --git a/studio/backend/core/inference/diffusion_native_w8a8_rdna.py b/studio/backend/core/inference/diffusion_native_w8a8_rdna.pynew file mode 100644index 00000000000..7e0a86232d3--- /dev/null+++ b/studio/backend/core/inference/diffusion_native_w8a8_rdna.py@@ -0,0 +1,566 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Triton W8A8 linear for the native int8 layers on ROCm RDNA3 / RDNA4 (gfx11xx / gfx12xx): one kernel rotates+(ConvRot) and row-quantises the activation, one int8 GEMM applies both row scales and the bias in its epilogue.+Opaque custom ops, so a compiled model keeps them whole and calls sharing an input (Q / K / V) share one quant.+Each card runs a parity probe first; a failure there keeps the stock path. UNSLOTH_NATIVE_INT8_RDNA_TRITON=0 disables."""++from __future__ import annotations++import os+import re+import threading+import types+from functools import lru_cache+from typing import Any, Optional++RDNA_TRITON_ENV = "UNSLOTH_NATIVE_INT8_RDNA_TRITON"+_NS = "unsloth_studio"+_ROTQ_OP = "native_rdna_rotq_rows"+_MM_OP = "native_rdna_w8a8_mm"+_ARCH = re.compile(r"^gfx1[12][0-9a-f]{2}$")+_MIN_TRITON = (3, 2)+_ROTQ_MAX_GROUPS = 128+_QUANT_CHUNK = 256+# rotq: (group-rows per program BLOCK_M, K step, warps, stages); BLOCK_M grows to hold one whole activation row.+# mm: (BLOCK_M, BLOCK_N, BLOCK_K, GROUP_M, warps, stages). gfx1151 sweep at 4096 rows: K 12288 fastest at+# 128x128x128 / 8 warps (8.41 ms vs 12.96 stock); K <= 4096 at 64x128x128 / 4 warps (1.92 vs 2.04 ms for the+# 128-row tile, 2.45 stock; N 3072 and 12288 alike). Under 1024 rows the 64-wide tile.+_CFG = {+ "rotq": (64, 32, 4, 1),+ "mm_large": (128, 128, 128, 8, 8, 2),+ "mm_large_short_k": (64, 128, 128, 8, 4, 2),+ "mm_small": (64, 64, 64, 8, 4, 2),+}+_SHORT_K = 4096+RDNA_TILES_ENV = "UNSLOTH_NATIVE_INT8_RDNA_TILES"+++def _tile_overrides(raw: Optional[str]) -> dict:+ """``{"rotq": [bm, bk, warps, stages], "mm_large": [...6], "mm_large_short_k": [...6], "mm_small": [...6]}`` from+ JSON; bad input -> {}."""+ import json+ try:+ got = json.loads(raw) if raw else {}+ out = {}+ for key, size in (("rotq", 4), ("mm_large", 6), ("mm_large_short_k", 6), ("mm_small", 6)):+ val = got.get(key)+ if val is not None:+ val = tuple(int(v) for v in val)+ if len(val) != size or any(v <= 0 for v in val):+ return {}+ out[key] = val+ return out+ except Exception: # noqa: BLE001+ return {}+++_CFG.update(_tile_overrides(os.environ.get(RDNA_TILES_ENV)))+# The per-row reduction tile is [BLOCK_M, ROWS_P2]; AMD WMMA layouts need both dims >= 16.+_MIN_ROWS_P2 = 16++# "devices": device key -> None (runs) or the reason it does not; "on": card index -> True, read by compiled graphs.+# Every key exists up front: a compiled graph guards on this dict's keys, so later writes must not add any.+_STATE: dict = {"devices": {}, "on": {}, "broken": None, "rotq": None, "mm": None}+_LOCK = threading.Lock()+++def rdna_triton_disabled() -> bool:+ return os.environ.get(RDNA_TRITON_ENV, "").strip().lower() in ("0", "false", "no", "off")+++def _triton_version_ok() -> bool:+ try:+ import triton+ match = re.match(r"(\d+)\.(\d+)", str(triton.__version__))+ return bool(match) and (int(match.group(1)), int(match.group(2))) >= _MIN_TRITON+ except Exception: # noqa: BLE001+ return False+++@lru_cache(maxsize = 1)+def _kernels() -> Optional[types.SimpleNamespace]:+ try:+ import triton+ import triton.language as tl+ except Exception: # noqa: BLE001 - no Triton means the stock path+ return None++ @triton.jit(do_not_specialize = ["M"])+ def rotq_rows(+ x_ptr,+ h_ptr,+ q_ptr,+ s_ptr,+ M,+ NG,+ stride_xm,+ G: tl.constexpr, # rotation group width (also the quant chunk without a rotation)+ BLOCK_M: tl.constexpr, # group rows per program+ BLOCK_K: tl.constexpr, # K step inside a group+ ROWS: tl.constexpr, # activation rows per program+ ROWS_P2: tl.constexpr, # ROWS next pow2+ ROT: tl.constexpr, # apply the Hadamard+ ):+ # One program = ROWS whole rows laid out as (row, group) lanes, so each row's amax closes in the tile.+ pid = tl.program_id(0)+ t = tl.arange(0, BLOCK_M)+ lr = t // NG+ gi = t % NG+ row = pid.to(tl.int64) * ROWS + lr+ live = (lr < ROWS) & (row < M)+ row_c = tl.where(live, row, 0)+ offs_n = tl.arange(0, G)+ if ROT:+ offs_k = tl.arange(0, BLOCK_K)+ acc = tl.zeros((BLOCK_M, G), dtype = tl.float32)+ a_ptrs = x_ptr + row_c[:, None] * stride_xm + gi[:, None] * G + offs_k[None, :]+ h_ptrs = h_ptr + offs_k[:, None] * G + offs_n[None, :]+ for _k in range(0, G // BLOCK_K):+ a = tl.load(a_ptrs, mask = live[:, None], other = 0.0)+ acc = tl.dot(a, tl.load(h_ptrs), acc, out_dtype = tl.float32)+ a_ptrs += BLOCK_K+ h_ptrs += BLOCK_K * G+ # The stock rotation is a bf16 / fp16 matmul: its output rounds to the activation dtype.+ z = acc.to(x_ptr.dtype.element_ty).to(tl.float32)+ else:+ z = tl.load(+ x_ptr + row_c[:, None] * stride_xm + gi[:, None] * G + offs_n[None, :],+ mask = live[:, None],+ other = 0.0,+ ).to(tl.float32)+ j = tl.arange(0, ROWS_P2)+ sel = lr[:, None] == j[None, :]+ amax = tl.max(tl.where(sel, tl.max(tl.abs(z), axis = 1)[:, None], 0.0), axis = 0)+ # As _w8a8_rows: s = max(amax, 1e-12) * fp32(1 / 127), reciprocal in fp64 rounded to fp32.+ s = tl.maximum(amax, 1e-12) * 0.007874015748031496+ inv = (1.0 / s.to(tl.float64)).to(tl.float32)+ inv_t = tl.max(tl.where(sel, inv[None, :], 0.0), axis = 1)+ # Round half to even for |p| < 2**22 without libdevice (no shared spelling on HIP); fp fusion is off.+ p = (z * inv_t[:, None] + 12582912.0) - 12582912.0+ p = tl.minimum(tl.maximum(p, -127.0), 127.0)+ tl.store(+ q_ptr + row_c[:, None] * (NG * G) + gi[:, None] * G + offs_n[None, :],+ p.to(tl.int8),+ mask = live[:, None],+ )+ srow = pid.to(tl.int64) * ROWS + j+ tl.store(s_ptr + srow, s, mask = (j < ROWS) & (srow < M))++ @triton.jit(do_not_specialize = ["M"])+ def w8a8_mm(+ a_ptr,+ w_ptr,+ xs_ptr,+ ws_ptr,+ b_ptr,+ c_ptr,+ M,+ N,+ K,+ HAS_BIAS: tl.constexpr,+ EVEN_K: tl.constexpr,+ BLOCK_M: tl.constexpr,+ BLOCK_N: tl.constexpr,+ BLOCK_K: tl.constexpr,+ GROUP_M: tl.constexpr,+ ):+ pid = tl.program_id(0)+ num_pid_m = tl.cdiv(M, BLOCK_M)+ num_pid_n = tl.cdiv(N, BLOCK_N)+ num_pid_in_group = GROUP_M * num_pid_n+ group_id = pid // num_pid_in_group+ first_pid_m = group_id * GROUP_M+ group_size_m = tl.minimum(num_pid_m - first_pid_m, GROUP_M)+ pid_m = first_pid_m + ((pid % num_pid_in_group) % group_size_m)+ pid_n = (pid % num_pid_in_group) // group_size_m+ offs_m = pid_m.to(tl.int64) * BLOCK_M + tl.arange(0, BLOCK_M)+ offs_n = pid_n.to(tl.int64) * BLOCK_N + tl.arange(0, BLOCK_N)+ rm = tl.max_contiguous(tl.multiple_of(offs_m % M, BLOCK_M), BLOCK_M)+ rn = tl.max_contiguous(tl.multiple_of(offs_n % N, BLOCK_N), BLOCK_N)+ offs_k = tl.arange(0, BLOCK_K)+ a_ptrs = a_ptr + rm[:, None] * K + offs_k[None, :]+ w_ptrs = w_ptr + rn[None, :] * K + offs_k[:, None]+ acc = tl.zeros((BLOCK_M, BLOCK_N), dtype = tl.int32)+ for k in range(0, tl.cdiv(K, BLOCK_K)):+ if EVEN_K:+ a = tl.load(a_ptrs)+ b = tl.load(w_ptrs)+ else:+ kmask = offs_k < K - k * BLOCK_K+ a = tl.load(a_ptrs, mask = kmask[None, :], other = 0)+ b = tl.load(w_ptrs, mask = kmask[:, None], other = 0)+ acc = tl.dot(a, b, acc, out_dtype = tl.int32)+ a_ptrs += BLOCK_K+ w_ptrs += BLOCK_K+ # As _w8a8_rows: (int32 * xs) * ws (+ bias), all fp32, one rounding to the output dtype.+ xs = tl.load(xs_ptr + rm)+ ws = tl.load(ws_ptr + rn)+ y = acc.to(tl.float32) * xs[:, None]+ y = y * ws[None, :]+ if HAS_BIAS:+ y = y + tl.load(b_ptr + rn).to(tl.float32)[None, :]+ c_ptrs = c_ptr + offs_m[:, None] * N + offs_n[None, :]+ mask = (offs_m[:, None] < M) & (offs_n[None, :] < N)+ tl.store(c_ptrs, y.to(c_ptr.dtype.element_ty), mask = mask)++ return types.SimpleNamespace(rotq_rows = rotq_rows, w8a8_mm = w8a8_mm, triton = triton)+++def _rotq_tile(k: int, group: int) -> Optional[tuple]:+ """(group width, groups per row, BLOCK_M, rows per program), or None if K does not fit."""+ g = int(group) if group else _QUANT_CHUNK+ # Only the group the per-card probe checks: a group below BLOCK_K skips the rotation loop and quantises zeros.+ if k <= 0 or g != _QUANT_CHUNK or k % g:+ return None+ ng = k // g+ if ng > _ROTQ_MAX_GROUPS:+ return None+ bm = _CFG["rotq"][0]+ while bm < ng:+ bm *= 2+ return g, ng, bm, bm // ng+++def shape_supported(in_features: int, out_features: int, group: int) -> bool:+ return (+ _rotq_tile(int(in_features), int(group)) is not None+ and int(in_features) % 16 == 0+ and int(out_features) % 16 == 0+ )+++def _rotq_launch(x2: Any, group: int) -> tuple:+ import torch++ from .diffusion_convrot import build_convrot_hadamard++ m, k = x2.shape+ q = torch.empty((m, k), device = x2.device, dtype = torch.int8)+ s = torch.empty((m, 1), device = x2.device, dtype = torch.float32)+ if m == 0:+ return q, s+ tile = _rotq_tile(k, group)+ if tile is None or x2.stride(-1) != 1:+ return reference_rotq(x2, group)+ if _STATE.get("broken"):+ return reference_rotq(x2, group)+ g, ng, bm, rows = tile+ _, bk, warps, stages = _CFG["rotq"]+ kern = _kernels()+ triton = kern.triton+ h = build_convrot_hadamard(g, device = x2.device, dtype = x2.dtype) if group else x2+ try:+ _launch_rotq(kern, x2, h, q, s, m, ng, g, bm, bk, rows, group, warps, stages)+ except torch.cuda.OutOfMemoryError:+ raise+ except Exception as exc: # noqa: BLE001 - a kernel that cannot build here: stock maths from now on+ _mark_broken("rotate+quant", exc)+ return reference_rotq(x2, group)+ return q, s+++def _launch_rotq(kern, x2, h, q, s, m, ng, g, bm, bk, rows, group, warps, stages) -> None:+ import torch+ triton = kern.triton+ with torch.cuda.device(x2.device):+ kern.rotq_rows[(triton.cdiv(m, rows),)](+ x2,+ h,+ q,+ s,+ m,+ ng,+ x2.stride(0),+ G = g,+ BLOCK_M = bm,+ BLOCK_K = bk,+ ROWS = rows,+ ROWS_P2 = max(triton.next_power_of_2(rows), _MIN_ROWS_P2),+ ROT = bool(group),+ num_warps = warps,+ num_stages = stages,+ enable_fp_fusion = False,+ )+++def _mark_broken(what: str, exc: BaseException) -> None:+ if _STATE.get("broken"):+ return+ _STATE["broken"] = f"{what}: {type(exc).__name__}: {str(exc)[:200]}"+ import logging++ logging.getLogger(__name__).warning(+ "diffusion.native_quant: RDNA Triton %s failed (%s); stock int8 maths from now on (set %s=0 to skip it)",+ what,+ exc,+ RDNA_TRITON_ENV,+ )+++def _mm_launch(xq: Any, xs: Any, wq: Any, ws: Any, bias: Any, out_dtype: Any) -> Any:+ import torch++ xq, xs, wq, ws = xq.contiguous(), xs.contiguous(), wq.contiguous(), ws.contiguous()+ bias = bias.contiguous() if bias is not None else None+ m, k = xq.shape+ n = wq.shape[0]+ out = torch.empty((m, n), device = xq.device, dtype = out_dtype)+ if m == 0:+ return out+ if _STATE.get("broken"):+ return reference_mm_stock(xq, xs, wq, ws, bias, out_dtype)+ try:+ _launch_mm(xq, xs, wq, ws, bias, out, m, n, k)+ except torch.cuda.OutOfMemoryError:+ raise+ except Exception as exc: # noqa: BLE001+ _mark_broken("int8 GEMM", exc)+ return reference_mm_stock(xq, xs, wq, ws, bias, out_dtype)+ return out+++def _mm_cfg(m: int, k: int) -> tuple:+ if m < 1024:+ return _CFG["mm_small"]+ return _CFG["mm_large_short_k"] if k <= _SHORT_K else _CFG["mm_large"]+++def _launch_mm(xq, xs, wq, ws, bias, out, m, n, k) -> None:+ import torch++ kern = _kernels()+ triton = kern.triton+ bm, bn, bk, gm, warps, stages = _mm_cfg(m, k)+ with torch.cuda.device(xq.device):+ kern.w8a8_mm[(triton.cdiv(m, bm) * triton.cdiv(n, bn),)](+ xq,+ wq,+ xs,+ ws,+ bias if bias is not None else ws,+ out,+ m,+ n,+ k,+ HAS_BIAS = bias is not None,+ EVEN_K = k % bk == 0,+ BLOCK_M = bm,+ BLOCK_N = bn,+ BLOCK_K = bk,+ GROUP_M = gm,+ num_warps = warps,+ num_stages = stages,+ enable_fp_fusion = False,+ )+++def reference_rotq(x2: Any, group: int) -> tuple:+ """Eager ``_w8a8_rows`` prologue: (int8 codes [M, K], fp32 row scales [M, 1])."""+ import torch++ from .diffusion_convrot import build_convrot_hadamard++ if group:+ h = build_convrot_hadamard(int(group), device = x2.device, dtype = x2.dtype)+ x2 = (x2.reshape(x2.shape[0], -1, int(group)) @ h).reshape(x2.shape)+ s = torch.linalg.vector_norm(x2, ord = float("inf"), dim = 1, keepdim = True, dtype = torch.float32)+ s = s.clamp(min = 1e-12) * (1.0 / 127.0)+ inv = (1.0 / s.double()).float()+ q = torch.mul(x2, inv).round().clamp(-127, 127).to(torch.int8)+ return q, s+++def reference_mm_stock(xq: Any, xs: Any, wq: Any, ws: Any, bias: Any, out_dtype: Any) -> Any:+ """The stock ``_w8a8_rows`` GEMM + epilogue (torch._int_mm needs > 16 rows; fewer go through fp32)."""+ import torch++ if xq.shape[0] > 16 and xq.is_cuda:+ acc = torch._int_mm(xq, wq.t())+ else:+ acc = (xq.float() @ wq.float().t()).round().to(torch.int32)+ out = torch.mul(acc, xs.reshape(-1, 1))+ w = ws.reshape(-1)+ out = torch.addcmul(bias.float(), out, w) if bias is not None else out * w+ return out.to(out_dtype)+++def reference_mm(xq: Any, xs: Any, wq: Any, ws: Any, bias: Any, out_dtype: Any) -> Any:+ import torch++ acc = torch.matmul(xq.to(torch.float64), wq.t().to(torch.float64)).to(torch.float32)+ out = acc * xs.reshape(-1, 1) * ws.reshape(1, -1)+ if bias is not None:+ out = out + bias.float()+ return out.to(out_dtype)+++@lru_cache(maxsize = 1)+def _ops() -> Optional[types.SimpleNamespace]:+ try:+ import torch+ except Exception: # noqa: BLE001+ return None+ ns = getattr(torch.ops, _NS, None)+ if ns is not None and hasattr(ns, _ROTQ_OP) and hasattr(ns, _MM_OP):+ return types.SimpleNamespace(rotq = getattr(ns, _ROTQ_OP), mm = getattr(ns, _MM_OP))+ custom_op = getattr(getattr(torch, "library", None), "custom_op", None)+ if custom_op is None:+ return None+ try:++ @custom_op(+ f"{_NS}::{_ROTQ_OP}",+ mutates_args = (),+ schema = "(Tensor x, int group) -> (Tensor, Tensor)",+ )+ def _rotq(x, group):+ return _rotq_launch(x, group)++ @_rotq.register_fake+ def _(x, group):+ return (+ x.new_empty(x.shape, dtype = torch.int8),+ x.new_empty((x.shape[0], 1), dtype = torch.float32),+ )++ @custom_op(+ f"{_NS}::{_MM_OP}",+ mutates_args = (),+ schema = "(Tensor xq, Tensor xs, Tensor wq, Tensor ws, Tensor? bias, ScalarType out_dtype) -> Tensor",+ )+ def _mm(xq, xs, wq, ws, bias, out_dtype):+ return _mm_launch(xq, xs, wq, ws, bias, out_dtype)++ @_mm.register_fake+ def _(xq, xs, wq, ws, bias, out_dtype):+ return xq.new_empty((xq.shape[0], wq.shape[0]), dtype = out_dtype)+ except Exception: # noqa: BLE001 - a registration failure keeps the stock path+ return None+ ns = getattr(torch.ops, _NS)+ return types.SimpleNamespace(rotq = getattr(ns, _ROTQ_OP), mm = getattr(ns, _MM_OP))+++def _key(device: Any) -> Any:+ import torch++ if device is None:+ return torch.device("cuda", int(torch.cuda.current_device()))+ device = torch.device(device)+ if device.index is None:+ return torch.device(device.type, int(torch.cuda.current_device()))+ return device+++def _probe(device: Any) -> Optional[str]:+ """None when both kernels match the eager reference on ``device``, else why not."""+ import torch++ gen = torch.Generator(device = "cpu").manual_seed(0)+ ops = _ops()+ for dtype in (torch.bfloat16, torch.float16):+ # 1040 rows: the large GEMM tiles (short K and long K) with a partial last block; 96 / 64: the small tile.+ # K covers several whole-row tilings (3 / 12 / 48 groups of 256) and the unrotated quant.+ for group, k, rows in (+ (256, 768, 1040),+ (256, 3072, 1040),+ (256, 12288, 1040),+ (256, 12288, 64),+ (0, 3072, 96),+ ):+ x = (torch.randn(rows, k, generator = gen) * 3).to(dtype).to(device)+ x[3] = 0 # an all-zero row keeps the 1e-12 floor+ wq = torch.randint(-127, 128, (48, k), generator = gen, dtype = torch.int8).to(device)+ _STATE["broken"] = None+ ws = (torch.rand(48, generator = gen) * 1e-2 + 1e-4).to(device)+ bias = torch.randn(48, generator = gen).to(dtype).to(device)+ q, s = ops.rotq(x, group)+ rq, rs = reference_rotq(x, group)+ diff = (q.int() - rq.int()).abs()+ # The rotation's fp32 accumulation order may move a bf16 tie: at most one code, rarely.+ if int(diff.max()) > 1 or float((diff > 0).float().mean()) > 1e-3:+ return f"rotate+quant codes differ ({dtype}, group {group})"+ if not torch.allclose(s, rs, rtol = 1e-2, atol = 0):+ return f"rotate+quant scales differ ({dtype}, group {group})"+ out = ops.mm(rq, rs, wq, ws, bias, dtype)+ ref = reference_mm(rq, rs, wq, ws, bias, dtype)+ if not torch.allclose(out.float(), ref.float(), rtol = 2e-2, atol = 1e-2):+ return f"int8 GEMM differs ({dtype})"+ out = ops.mm(rq, rs, wq, ws, None, dtype)+ ref = reference_mm(rq, rs, wq, ws, None, dtype)+ if not torch.allclose(out.float(), ref.float(), rtol = 2e-2, atol = 1e-2):+ return f"int8 GEMM differs ({dtype}, no bias)"+ if _STATE.get("broken"): # a launch failed and fell back: the kernels do not build here+ why, _STATE["broken"] = _STATE["broken"], None+ return why+ torch.cuda.synchronize(device)+ return None+++def prepare(device: Any = None) -> bool:+ if rdna_triton_disabled():+ return False+ try:+ import torch++ from .rocm_bf16 import _device_gfx_arch, is_rocm_torch++ if not is_rocm_torch(torch) or not torch.cuda.is_available():+ return False+ key = _key(device)+ if key.type != "cuda":+ return False+ except Exception: # noqa: BLE001+ return False+ devices = _STATE["devices"]+ with _LOCK:+ if key in devices:+ return devices[key] is None+ why: Optional[str] = None+ arch = _device_gfx_arch(torch, key.index)+ if not _ARCH.match(arch):+ why = f"ROCm {arch or 'unknown arch'}"+ elif not _triton_version_ok() or _kernels() is None:+ why = "no Triton >= 3.2"+ elif _ops() is None:+ why = "no torch.library.custom_op"+ else:+ try:+ why = _probe(key)+ except Exception as exc: # noqa: BLE001 - a kernel that cannot build keeps the stock path+ why = f"{type(exc).__name__}: {exc}"+ devices[key] = why+ if why is None:+ ops = _ops()+ # Plain dict entries: a compiled graph reads the op handles without tracing the lru_cache.+ _STATE["rotq"], _STATE["mm"] = ops.rotq, ops.mm+ _STATE["on"][int(key.index)] = True+ try:+ from loggers import get_logger+ log = get_logger(__name__)+ except Exception: # noqa: BLE001+ import logging+ log = logging.getLogger(__name__)+ if why is None:+ log.info("diffusion.native_quant: int8 W8A8 on %s runs the RDNA Triton kernels", key)+ else:+ log.info("diffusion.native_quant: int8 W8A8 on %s keeps the stock kernels (%s)", key, why)+ return why is None+++def enabled_for(index: Any) -> bool:+ """Traceable lookup of an earlier ``prepare`` for card ``index`` (never probes; a compiled graph reads one dict)."""+ return bool(_STATE["on"].get(index, False))+++def state() -> dict:+ return {str(k): why for k, why in _STATE["devices"].items()}+++def rotq(x2: Any, group: int) -> tuple:+ return _STATE["rotq"](x2, group)+++def w8a8_mm(xq: Any, xs: Any, wq: Any, ws: Any, bias: Any, out_dtype: Any) -> Any:+ return _STATE["mm"](xq, xs, wq, ws, bias, out_dtype)diff --git a/studio/backend/core/inference/diffusion_qwenimage21_dense_fused.py b/studio/backend/core/inference/diffusion_qwenimage21_dense_fused.pyindex 16f5e971f18..0d5f58527c4 100644--- a/studio/backend/core/inference/diffusion_qwenimage21_dense_fused.py+++ b/studio/backend/core/inference/diffusion_qwenimage21_dense_fused.py@@ -6,7 +6,10 @@ the SwiGLU ``gate_layer`` + ``proj`` (the single-file layout's ``gate_up``; theand, under compile, attention ``to_q`` + ``to_k`` + ``to_v`` (through the shared Q / K / V helper of``diffusion_qwenimage21_fused``). The parts become row views of the fused weight, so it costs no memory and in-placeweight writes (LoRA fold / restore) reach both. Plain bf16 / fp16 / fp32 Linears on one resident GPU only-(quantised, GGUF, LoRA-wrapped, hooked or offloaded layers keep the stock modules); compiled loads only.+(GGUF, LoRA-wrapped, hooked or offloaded layers keep the stock modules); compiled loads only.+Native int8 layers with int8 activations (the W8A8 linear, ROCm RDNA) fuse the same way: their codes, row scales+and biases concatenate by output row, so the fused int32 GEMM and its per-row / per-column epilogue give the parts'+values exactly, with one rotation and one activation quant instead of two or three.UNSLOTH_DIFFUSION_Q21_DENSE_FUSED=0 keeps the stock projections."""from __future__ import annotations@@ -52,6 +55,100 @@ def _plain_dense(lin: Any) -> bool:)+def _plain_native(lin: Any) -> bool:+ """A native int8 Linear with int8 activations (exact to fuse: int32 accumulation, row-wise epilogue)."""+ from .diffusion_native_quant import NATIVE_INT8, is_native_linear++ if not is_native_linear(lin) or not getattr(lin, "act_int8", False):+ return False+ if lin.scheme != NATIVE_INT8 or "forward" in lin.__dict__:+ return False+ if lin._forward_hooks or lin._forward_pre_hooks:+ return False+ return lin.weight_q.device.type in _DEVICE_TYPES and lin.weight_q.dim() == 2+++def _native_compatible(parts: list) -> bool:+ if not all(_plain_native(p) for p in parts):+ return False+ first = parts[0]+ has_bias = [p.bias is not None for p in parts]+ if any(has_bias) and not all(has_bias):+ return False+ return all(+ p.in_features == first.in_features+ and p.rot_group == first.rot_group+ and p.compute_dtype == first.compute_dtype+ and p.weight_q.device == first.weight_q.device+ and (p.bias is None or p.bias.dtype == first.bias.dtype)+ for p in parts+ )+++def _fuse_native(parts: list) -> Any:+ """Fused native int8 Linear; parts' buffers become row views of it. None on mismatch."""+ import torch+ from torch import nn++ from .diffusion_native_quant import NATIVE_INT8, native_linear_class++ if not _native_compatible(parts):+ return None+ first = parts[0]+ n_out = sum(p.out_features for p in parts)+ with torch.no_grad():+ codes = torch.cat([p.weight_q for p in parts], dim = 0)+ scale = torch.cat([p.weight_scale.view(torch.float32) for p in parts], dim = 0)+ bias = (+ nn.Parameter(torch.cat([p.bias.detach() for p in parts]), requires_grad = False)+ if first.bias is not None+ else None+ )+ shape = types.SimpleNamespace(+ in_features = first.in_features,+ out_features = n_out,+ weight = torch.empty(0, dtype = first.compute_dtype, device = "meta"),+ bias = bias,+ )+ try:+ fused = native_linear_class()(+ shape,+ NATIVE_INT8,+ act_int8 = True,+ rot_group = first.rot_group,+ codes = codes,+ scale = scale,+ )+ except Exception: # noqa: BLE001 - an unexpected layout keeps the stock projections+ return None+ if fused.rot_group != first.rot_group or not fused.act_int8:+ return None+ if first.rot_group:+ fused.rot_h = first.rot_h.detach().clone()+ start = 0+ for p in parts:+ stop = start + p.out_features+ p.weight_q = fused.weight_q[start:stop]+ p.weight_scale = fused.weight_scale[start:stop]+ if bias is not None:+ p.bias = nn.Parameter(fused.bias.detach()[start:stop], requires_grad = False)+ start = stop+ fused.__dict__[_PART_CODES] = tuple(p.weight_q for p in parts)+ return fused+++_PART_CODES = "_unsloth_q21_part_codes"+++def _native_intact(fused: Any, parts: tuple) -> bool:+ """The parts still hold the row views of ``fused`` made at fusion (identity checks only: traceable, and a+ reload or move that replaced a part's buffers declines)."""+ views = fused.__dict__.get(_PART_CODES)+ if views is None or len(views) != len(parts):+ return False+ return all(p.weight_q is v for p, v in zip(parts, views))++def _resident_device(module: Any) -> Any:try:devices = {p.device for p in module.parameters()}@@ -70,6 +167,8 @@ def _intact(ff: Any) -> Any:weight, gate, proj, gate_w, proj_w = recif ff.gate_layer is not gate or ff.proj is not proj:return None+ if gate_w is None: # native int8: ``weight`` is the fused Linear+ return weight if _native_intact(weight, (gate, proj)) else Noneif gate.weight is not gate_w or proj.weight is not proj_w:return Noneif weight.device != gate_w.device:@@ -78,12 +177,16 @@ def _intact(ff: Any) -> Any:def _forward(self: Any, hidden_states: Any) -> Any:+ import torchimport torch.nn.functional as Fweight = _intact(self)if weight is None:return type(self).forward(self, hidden_states)- gate, value = F.linear(hidden_states, weight).chunk(2, dim = -1)+ if isinstance(weight, torch.Tensor):+ gate, value = F.linear(hidden_states, weight).chunk(2, dim = -1)+ else:+ gate, value = weight(hidden_states).chunk(2, dim = -1)return self.out(self.activation_fn(gate) * value)@@ -92,6 +195,15 @@ def _fuse(ff: Any) -> bool:from torch import nngate, proj = ff.gate_layer, ff.proj+ if _plain_native(gate) and _plain_native(proj):+ if gate.out_features != proj.out_features:+ return False+ fused = _fuse_native([gate, proj])+ if fused is None:+ return False+ ff.__dict__[_FF_ATTR] = (fused, gate, proj, None, None)+ ff.forward = types.MethodType(_forward, ff)+ return Trueif not (_plain_dense(gate) and _plain_dense(proj)) or not _plain_dense(ff.out):return Falsegw, pw = gate.weight, proj.weight@@ -111,7 +223,15 @@ def _fuse_qkv(attn: Any, qkv_attr: str) -> bool:from .diffusion_zimage_fused import _fuse_linears, _share_storageparts = [getattr(attn, n, None) for n in ("to_q", "to_k", "to_v")]- if any(p is None or not _plain_dense(p) for p in parts):+ if any(p is None for p in parts):+ return False+ if all(_plain_native(p) for p in parts):+ fused = _fuse_native(parts)+ if fused is None:+ return False+ attn.__dict__[qkv_attr] = (fused, *parts)+ return True+ if any(not _plain_dense(p) for p in parts):return Falseif len({(p.weight.dtype, p.weight.device, p.weight.shape[1]) for p in parts}) != 1:return False@@ -122,6 +242,25 @@ def _fuse_qkv(attn: Any, qkv_attr: str) -> bool:return True+def _release_parts(root: Any) -> None:+ """Hand the parts' old buffers (now replaced by row views of the fused weights) back to the device: the caching+ allocator would otherwise keep them reserved (+2.7 GiB peak device memory for a native int8 Qwen-Image-2.1)."""+ try:+ import gc++ import torch++ device = _resident_device(root)+ if device is None or device.type != "cuda" or not torch.cuda.is_available():+ return+ gc.collect()+ with torch.cuda.device(device):+ torch.cuda.synchronize()+ torch.cuda.empty_cache()+ except Exception: # noqa: BLE001 - only a memory hint+ pass++def install_modules(root: Any, logger: Any = None) -> dict:result = {"gate_up": 0, "qkv": 0}if disabled() or _resident_device(root) is None:@@ -129,15 +268,24 @@ def install_modules(root: Any, logger: Any = None) -> dict:from . import diffusion_qwenimage21_fused as q21fqkv_ok = not q21f.q21_convrot_fused_disabled() and q21f._patch_prepare(logger)+ fused_now = 0with _LOCK:for module in root.modules():name = type(module).__name__if name == _FF_CLASS:- if _intact(module) is not None or _fuse(module):+ if _intact(module) is not None:+ result["gate_up"] += 1+ elif _fuse(module):result["gate_up"] += 1+ fused_now += 1elif name == _ATTN_CLASS and qkv_ok:- if q21f._qkv_intact(module) is not None or _fuse_qkv(module, q21f._QKV_ATTR):+ if q21f._qkv_intact(module) is not None:result["qkv"] += 1+ elif _fuse_qkv(module, q21f._QKV_ATTR):+ result["qkv"] += 1+ fused_now += 1+ if fused_now:+ _release_parts(root)if logger is not None and (result["gate_up"] or result["qkv"]):logger.info("diffusion.q21_dense_fused: one GEMM for gate + value in %d MLP(s), for Q / K / V in %d attention(s)",@@ -176,7 +324,7 @@ def uninstall(transformer: Any = None) -> None:with _LOCK:for module in transformer.modules():rec = module.__dict__.get(_QKV_ATTR)- if rec is not None and _plain_dense(rec[0]):+ if rec is not None and (_plain_dense(rec[0]) or _plain_native(rec[0])):module.__dict__.pop(_QKV_ATTR, None)if module.__dict__.pop(_FF_ATTR, None) is not None:fwd = module.__dict__.get("forward")@@ -191,7 +339,11 @@ def is_replica_record(key: str, value: Any) -> bool:from .diffusion_qwenimage21_fused import _QKV_ATTRtry:- return key == _QKV_ATTR and isinstance(value, tuple) and _plain_dense(value[0])+ return (+ key == _QKV_ATTR+ and isinstance(value, tuple)+ and (_plain_dense(value[0]) or _plain_native(value[0]))+ )except Exception: # noqa: BLE001return Falsediff --git a/studio/backend/core/inference/diffusion_qwenimage21_fused.py b/studio/backend/core/inference/diffusion_qwenimage21_fused.pyindex fb26c104933..59f83262e78 100644--- a/studio/backend/core/inference/diffusion_qwenimage21_fused.py+++ b/studio/backend/core/inference/diffusion_qwenimage21_fused.py@@ -92,6 +92,12 @@ def _qkv_intact(attn: Any) -> Any:lin, q, k, v = recif attn.to_q is not q or attn.to_k is not k or attn.to_v is not v:return None+ codes = lin.__dict__.get("_unsloth_q21_part_codes")+ if codes is not None:+ # Native int8 (diffusion_qwenimage21_dense_fused): never read ``.weight``, it dequantises.+ if q.weight_q is not codes[0] or k.weight_q is not codes[1] or v.weight_q is not codes[2]:+ return None+ return linif lin.weight.device != q.weight.device:return None # a layer split moved the parts after the fusion; the stale fused copy is on another cardreturn lin@@ -109,7 +115,9 @@ 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 not None:+ if fused is not None and "_unsloth_q21_part_codes" in fused.__dict__:+ query, key, value = fused(hidden_states).chunk(3, dim = -1)+ elif 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))diff --git a/studio/backend/core/inference/diffusion_transformer_quant.py b/studio/backend/core/inference/diffusion_transformer_quant.pyindex 6f4747ba0f3..068ba48e648 100644--- a/studio/backend/core/inference/diffusion_transformer_quant.py+++ b/studio/backend/core/inference/diffusion_transformer_quant.py@@ -1398,6 +1398,21 @@ def rdna_auto_w8a8_reason(target: Any, family: Optional[str]) -> Optional[str]:return reason+def rdna_explicit_int8_reason(target: Any, family: Optional[str]) -> Optional[str]:+ """Why an explicit int8 request on this ROCm RDNA card compiles its denoiser from render 1, else None (eager).+ Weight-only int8 stays the scheme unless the family's AUTO table measured W8A8 faster (``rdna_auto_w8a8_reason``);+ eager int8 is slower than bf16 on gfx1151 for every measured family. Kill switch UNSLOTH_NATIVE_INT8_ACT=0."""+ if not _rocm_cuda(target) or not native_quant_host(target):+ return None+ if not _sys.platform.startswith("linux"):+ return None+ if int8_act_disabled() or not rocm_rdna_w8a8_ready(getattr(target, "ordinal", None)):+ return None+ if native_quant_scheme(target, TQ_INT8, family = family) != TQ_INT8:+ return None+ return "an explicit int8 request on RDNA is measured compiled"++def select_transformer_quant_scheme(target: Any,requested: Optional[str],diff --git a/studio/backend/tests/test_diffusion_native_quant.py b/studio/backend/tests/test_diffusion_native_quant.pyindex ee730a83930..f7680683205 100644--- a/studio/backend/tests/test_diffusion_native_quant.py+++ b/studio/backend/tests/test_diffusion_native_quant.py@@ -212,6 +212,32 @@ def test_rdna_auto_w8a8_reason_is_per_family_with_a_kill_switch(rocm, monkeypatcassert tq.rdna_auto_w8a8_reason(_target(), "toy-family") is None+def test_rdna_explicit_int8_reason_covers_every_family_with_the_same_gates(rocm, monkeypatch):+ monkeypatch.delenv(nq.NATIVE_INT8_ACT_ENV, raising = False)+ monkeypatch.setattr(tq._sys, "platform", "linux")+ monkeypatch.setattr(tq, "rocm_rdna_w8a8_ready", lambda *_a: True)+ assert tq.rdna_explicit_int8_reason(_target(), "toy-family") is not None+ assert tq.rdna_explicit_int8_reason(_target(), "flux.3-klein") is not None+ assert tq.rdna_explicit_int8_reason(_target(dtype = torch.float16), "toy-family") is None+ assert tq.rdna_explicit_int8_reason(_target("cpu"), "toy-family") is None+ monkeypatch.setenv(nq.NATIVE_INT8_ACT_ENV, "0")+ assert tq.rdna_explicit_int8_reason(_target(), "toy-family") is None+ monkeypatch.delenv(nq.NATIVE_INT8_ACT_ENV)+ monkeypatch.setattr(tq, "rocm_rdna_w8a8_ready", lambda *_a: False)+ assert tq.rdna_explicit_int8_reason(_target(), "toy-family") is None+ monkeypatch.setattr(tq, "rocm_rdna_w8a8_ready", lambda *_a: True)+ monkeypatch.setitem(tq._FAMILY_SCHEME_DENY, "toy-family", frozenset({tq.TQ_INT8}))+ assert tq.rdna_explicit_int8_reason(_target(), "toy-family") is None+ monkeypatch.setattr(tq._sys, "platform", "win32")+ assert tq.rdna_explicit_int8_reason(_target(), "flux.3-klein") is None+++def test_rdna_explicit_int8_reason_is_rocm_only(nvidia, monkeypatch):+ monkeypatch.setattr(tq, "rocm_rdna_w8a8_ready", lambda *_a: True)+ monkeypatch.setattr(tq._sys, "platform", "linux")+ assert tq.rdna_explicit_int8_reason(_target(), "toy-family") is None++def test_rdna_auto_w8a8_ships_only_for_the_measured_families():# Wan, small DiTs, edit / layered stay bf16.assert set(tq._FAMILY_RDNA_AUTO_W8A8) == {"qwen-image", "qwen-image-2.1"}diff --git a/studio/backend/tests/test_diffusion_native_w8a8_rdna.py b/studio/backend/tests/test_diffusion_native_w8a8_rdna.pynew file mode 100644index 00000000000..95a59ee83dc--- /dev/null+++ b/studio/backend/tests/test_diffusion_native_w8a8_rdna.py@@ -0,0 +1,171 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""RDNA W8A8 Triton kernels: gating on CPU / CUDA hosts, tile planning, and the kernels' maths in the Triton+interpreter (fp16: the interpreter has no bf16 dot)."""++from __future__ import annotations++import os+import types+import subprocess+import sys+import textwrap+from pathlib import Path++import pytest++torch = pytest.importorskip("torch")++import core.inference.diffusion_native_quant as nq+import core.inference.diffusion_native_w8a8_rdna as rdna++BACKEND = Path(__file__).resolve().parents[1]+++def test_tile_plan_whole_rows_per_program():+ assert rdna._rotq_tile(3072, 256) == (256, 12, 64, 5)+ assert rdna._rotq_tile(12288, 256) == (256, 48, 64, 1)+ assert rdna._rotq_tile(256 * 100, 256) == (256, 100, 128, 1)+ assert rdna._rotq_tile(512, 0) == (256, 2, 64, 32)+ assert rdna._rotq_tile(256 * 129, 256) is None+ assert rdna._rotq_tile(3000, 256) is None+++def test_shape_supported_needs_aligned_features():+ assert rdna.shape_supported(3072, 3072, 256)+ assert not rdna.shape_supported(3072, 3000, 256)+ assert not rdna.shape_supported(3000, 3072, 0)++[email protected]("group", [8, 16, 32, 64, 128, 512])+def test_rotation_groups_the_probe_does_not_check_keep_the_stock_path(group):+ # Group 16 with BLOCK_K 32 ran the rotation loop zero times and quantised every activation to zero.+ assert rdna._rotq_tile(3072, group) is None+ assert not rdna.shape_supported(3072, 512, group)+++def test_prepare_off_rocm_and_kill_switch(monkeypatch):+ monkeypatch.setattr(+ rdna, "_STATE", {"devices": {}, "on": {}, "broken": None, "rotq": None, "mm": None}+ )+ if not getattr(torch.version, "hip", None):+ assert rdna.prepare() is False+ assert rdna._STATE["devices"] == {}+ monkeypatch.setenv(rdna.RDNA_TRITON_ENV, "0")+ assert rdna.prepare() is False+ assert rdna.enabled_for(0) is False+++def test_cpu_layer_keeps_stock_path():+ lin = torch.nn.Linear(512, 256, dtype = torch.float32)+ layer = nq.native_linear_class()(lin, nq.NATIVE_INT8, act_int8 = True, rot_group = 256)+ # ``_rdna`` follows the card's probe (a CPU-built layer may move to the GPU); a CPU input never engages it.+ x = torch.randn(4, 512)+ assert layer._rdna_on(x) is False+ assert layer(x).shape == (4, 256)+++def test_enabled_for_reads_only_prepared_cards(monkeypatch):+ monkeypatch.setattr(+ rdna, "_STATE", {"devices": {}, "on": {1: True}, "broken": None, "rotq": None, "mm": None}+ )+ assert rdna.enabled_for(1) is True+ assert rdna.enabled_for(0) is False+++_INTERP = textwrap.dedent(+ """+ import contextlib, os, sys+ os.environ["TRITON_INTERPRET"] = "1"+ sys.path.insert(0, sys.argv[1])+ import torch+ from core.inference import diffusion_native_w8a8_rdna as r+ torch.cuda.device = lambda d: contextlib.nullcontext()+ torch.manual_seed(0)+ for group, k, m in ((256, 768, 70), (256, 3072, 33), (0, 512, 40)):+ x = (torch.randn(m, k) * 3).half()+ x[3] = 0+ q, s = r._rotq_launch(x, group)+ rq, rs = r.reference_rotq(x, group)+ assert torch.equal(q, rq), (group, k, m)+ assert torch.equal(s, rs), (group, k, m)+ wq = torch.randint(-127, 128, (48, k), dtype = torch.int8)+ ws = torch.rand(48) * 1e-2 + 1e-4+ for bias in (torch.randn(48).half(), None):+ out = r._mm_launch(rq, rs, wq, ws, bias, torch.float16)+ ref = r.reference_mm(rq, rs, wq, ws, bias, torch.float16)+ assert torch.equal(out, ref), (group, k, m, bias is None)+ print("INTERP_OK")+ """+)+++def test_kernels_match_reference_in_interpreter(tmp_path):+ pytest.importorskip("triton")+ script = tmp_path / "interp.py"+ script.write_text(_INTERP)+ env = dict(os.environ, CUDA_VISIBLE_DEVICES = "")+ proc = subprocess.run(+ [sys.executable, str(script), str(BACKEND)],+ capture_output = True,+ text = True,+ timeout = 600,+ env = env,+ )+ if (+ "INTERP_OK" not in proc.stdout+ and "interpreter" in proc.stderr.lower()+ and "not supported" in proc.stderr.lower()+ ):+ pytest.skip("Triton interpreter unavailable")+ assert "INTERP_OK" in proc.stdout, proc.stderr[-3000:]+++def test_failed_launch_falls_back_to_stock_maths(monkeypatch):+ monkeypatch.setattr(+ rdna, "_STATE", {"devices": {}, "on": {}, "broken": None, "rotq": None, "mm": None}+ )+ monkeypatch.setattr(rdna, "_kernels", lambda: types.SimpleNamespace(triton = None))++ def boom(*a, **k):+ raise RuntimeError("PassManager::run failed")++ monkeypatch.setattr(rdna, "_launch_rotq", boom)+ monkeypatch.setattr(rdna, "_launch_mm", boom)+ x = torch.randn(40, 512, dtype = torch.float32)+ q, s = rdna._rotq_launch(x, 256)+ rq, rs = rdna.reference_rotq(x, 256)+ assert torch.equal(q, rq) and torch.equal(s, rs)+ assert "rotate+quant" in rdna._STATE["broken"]+ wq = torch.randint(-127, 128, (32, 512), dtype = torch.int8)+ ws = torch.rand(32) * 1e-2+ b = torch.randn(32)+ out = rdna._mm_launch(rq, rs, wq, ws, b, torch.float32)+ torch.testing.assert_close(+ out, rdna.reference_mm(rq, rs, wq, ws, b, torch.float32), rtol = 1e-5, atol = 1e-4+ )+ assert set(rdna._STATE) == {"devices", "on", "broken", "rotq", "mm"}+++def test_reduction_tile_meets_the_wmma_minimum():+ assert rdna._MIN_ROWS_P2 >= 16+++def test_tile_overrides_parse_or_ignore():+ assert rdna._tile_overrides('{"rotq": [32, 64, 8, 1]}') == {"rotq": (32, 64, 8, 1)}+ assert rdna._tile_overrides('{"mm_large": [128, 256, 64, 8, 8, 2]}') == {+ "mm_large": (128, 256, 64, 8, 8, 2)+ }+ assert rdna._tile_overrides('{"rotq": [32, 64]}') == {}+ assert rdna._tile_overrides("not json") == {}+ assert rdna._tile_overrides(None) == {}+++def test_gemm_tile_follows_rows_and_k():+ assert rdna._mm_cfg(512, 3072) == rdna._CFG["mm_small"]+ assert rdna._mm_cfg(4096, 3072) == rdna._CFG["mm_large_short_k"]+ assert rdna._mm_cfg(4096, 12288) == rdna._CFG["mm_large"]+ assert rdna._tile_overrides('{"mm_large_short_k": [64, 64, 128, 8, 4, 2]}') == {+ "mm_large_short_k": (64, 64, 128, 8, 4, 2)+ }diff --git a/studio/backend/tests/test_diffusion_qwenimage21_dense_fused.py b/studio/backend/tests/test_diffusion_qwenimage21_dense_fused.pyindex 06c27f10bdd..2fbee05bfb9 100644--- a/studio/backend/tests/test_diffusion_qwenimage21_dense_fused.py+++ b/studio/backend/tests/test_diffusion_qwenimage21_dense_fused.py@@ -345,3 +345,149 @@ def test_cfg_replica_rebuild_frees_the_copied_parts(monkeypatch):replica = mg._copy_module(m, torch.device("cpu"))assert alive_after_rebuild == [False] * len(replica.blocks)assert all(dfu._intact(b) is not None for b in replica.blocks)+++# Native int8 layers with int8 activations (the W8A8 linear on ROCm RDNA): same fusion over int8 codes.+++def _native(+ linear,+ act_int8 = True,+ group = 16,+):+ from core.inference.diffusion_native_quant import NATIVE_INT8, native_linear_class+ return native_linear_class()(linear, NATIVE_INT8, act_int8 = act_int8, rot_group = group)+++class QwenImage21Attention(nn.Module):+ def __init__(+ self,+ dim = 64,+ bias = True,+ ):+ super().__init__()+ self.to_q = nn.Linear(dim, dim, bias = bias)+ self.to_k = nn.Linear(dim, dim, bias = bias)+ self.to_v = nn.Linear(dim, dim, bias = bias)+++def _native_model(+ act_int8 = True,+ dim = 64,+ group = 16,+):+ m = QwenImage21Transformer2DModel(dim = dim).to(torch.bfloat16).eval()+ m.attn = QwenImage21Attention(dim).to(torch.bfloat16)+ for b in m.blocks:+ for name in ("gate_layer", "proj", "out"):+ setattr(b, name, _native(getattr(b, name), act_int8, group))+ for name in ("to_q", "to_k", "to_v"):+ setattr(m.attn, name, _native(getattr(m.attn, name), act_int8, group))+ return m+++def _int8_rows(lin, x):+ """The W8A8 maths the GPU runs (rotation, row quant, int32 GEMM, row x column scale epilogue)."""+ x2 = x.reshape(-1, lin.in_features)+ if lin.rot_group:+ x2 = lin._rotate(x2)+ return lin._int_mm_rows(x2)+++def test_native_int8_fusion_is_exact_and_shares_the_codes(monkeypatch):+ from core.inference import diffusion_qwenimage21_fused as q21f++ monkeypatch.setattr(q21f, "_patch_prepare", lambda logger = None: True)+ m = _native_model()+ x = torch.randn(40, 64, dtype = torch.bfloat16)+ with torch.no_grad():+ ref_ff = [+ torch.cat([_int8_rows(b.gate_layer, x), _int8_rows(b.proj, x)], -1) for b in m.blocks+ ]+ ref_qkv = torch.cat(+ [_int8_rows(getattr(m.attn, n), x) for n in ("to_q", "to_k", "to_v")], -1+ )+ ref_fwd = [b(x) for b in m.blocks]+ codes_before = sum(t.numel() for t in m.buffers() if t.dtype == torch.int8)+ assert dfu.install(m) == {"gate_up": 2, "qkv": 1}+ with torch.no_grad():+ for b, want, want_fwd in zip(m.blocks, ref_ff, ref_fwd):+ fused = dfu._intact(b)+ assert fused is not None and fused.out_features == 2 * 192+ assert (+ b.gate_layer.weight_q.untyped_storage().data_ptr()+ == fused.weight_q.untyped_storage().data_ptr()+ )+ assert (+ b.proj.weight_q.untyped_storage().data_ptr()+ == fused.weight_q.untyped_storage().data_ptr()+ )+ assert torch.equal(_int8_rows(fused, x), want)+ assert torch.equal(b(x), want_fwd)+ qkv = q21f._qkv_intact(m.attn)+ assert qkv is not None and qkv.out_features == 3 * 64+ assert torch.equal(_int8_rows(qkv, x), ref_qkv)+ assert torch.equal(+ qkv.bias.float(),+ torch.cat([m.attn.to_q.bias, m.attn.to_k.bias, m.attn.to_v.bias]).float(),+ )+ assert sum(t.numel() for t in m.buffers() if t.dtype == torch.int8) == codes_before+ dfu.uninstall(m)+ assert q21f._qkv_intact(m.attn) is None and dfu._intact(m.blocks[0]) is None+++def test_native_int8_reloaded_part_falls_back(monkeypatch):+ from core.inference import diffusion_qwenimage21_fused as q21f++ monkeypatch.setattr(q21f, "_patch_prepare", lambda logger = None: True)+ m = _native_model()+ dfu.install(m)+ b = m.blocks[0]+ b.proj.weight_q = (+ b.proj.weight_q.clone()+ ) # load_state_dict(assign=True) / a move replaced the buffer+ assert dfu._intact(b) is None+ x = torch.randn(3, 64, dtype = torch.bfloat16)+ with torch.no_grad():+ torch.testing.assert_close(+ b(x), b.out(b.activation_fn(b.gate_layer(x)) * b.proj(x)), rtol = 0, atol = 0+ )+ m.attn.to_k.weight_q = m.attn.to_k.weight_q.clone()+ assert q21f._qkv_intact(m.attn) is None++[email protected]("why", ["weight_only", "mixed", "hook", "group"])+def test_native_int8_declines(monkeypatch, why):+ from core.inference import diffusion_qwenimage21_fused as q21f++ monkeypatch.setattr(q21f, "_patch_prepare", lambda logger = None: True)+ m = _native_model(act_int8 = why != "weight_only")+ b = m.blocks[0]+ if why == "mixed":+ b.proj = nn.Linear(64, 192, bias = False).to(torch.bfloat16)+ m.attn.to_v = nn.Linear(64, 64).to(torch.bfloat16)+ elif why == "hook":+ b.proj.register_forward_hook(lambda *a: None)+ m.attn.to_v.register_forward_pre_hook(lambda *a: None)+ elif why == "group":+ b.proj = _native(nn.Linear(64, 192, bias = True).to(torch.bfloat16), True, 64)+ m.attn.to_v = _native(nn.Linear(64, 64).to(torch.bfloat16), True, 64)+ out = dfu.install(m)+ assert dfu._intact(b) is None+ assert q21f._qkv_intact(m.attn) is None+ if why == "weight_only":+ assert out == {"gate_up": 0, "qkv": 0}+ else:+ assert out == {"gate_up": 1, "qkv": 0}+++def test_native_int8_compiles_without_graph_breaks():+ m = _native_model()+ dfu.install(m)+ torch._dynamo.reset()+ try:+ explain = torch._dynamo.explain(m.blocks[0])(torch.randn(2, 4, 64, dtype = torch.bfloat16))+ finally:+ torch._dynamo.reset()+ assert explain.graph_break_count == 0+ assert explain.graph_count == 1