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 ConvRot the Z-Image-Turbo INT8 default (#12612)
Daniel Han851c783597c3
diff --git a/studio/backend/core/inference/diffusion_int8_fused.py b/studio/backend/core/inference/diffusion_int8_fused.pyindex 588f8b1809e..05379d9b441 100644--- a/studio/backend/core/inference/diffusion_int8_fused.py+++ b/studio/backend/core/inference/diffusion_int8_fused.py@@ -12,7 +12,17 @@ Activation-scale contract follows the incoming scale's dtype: fp32 on torchao >=``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``.++ConvRot (Z-Image int8 default): w1 and w3 rotate the same input, so the SwiGLU's fused in-projection is a ConvRotLinear+(one rotation + one activation quant for both halves). A rotated w2 needs its input rotated BEFORE the quant, which the+kernel's fused quant cannot do, so that MLP computes the bf16 SiLU product with the stock epilogue ops and hands it to+w2's own (rotating) forward. Same ops on the same values as the three stock rotated Linears.++``int8_linear`` (also used by Z-Image's fused attention) runs a plain or rotated Int8Tensor Linear as torchao's act+quant + ``_int_mm`` + epilogue without torchao 0.17's always-on zero-point pass, and the act quant itself as one probed+Triton kernel (``int8_act_quant_rows``, bit-identical to torchao 0.17 and 0.18): Inductor's codegen of the same per-row+quant ran 2-3x slower on B200 (Z-Image shapes, M 4224: K 3840 24-32 -> 11 us, K 10240 53-70 -> 32 us).+Kill switch: ``UNSLOTH_DIFFUSION_INT8_FUSED=0`` (all of the above)."""from __future__ import annotations@@ -31,16 +41,25 @@ _MIN_ROWS = 17_OP_NAMESPACE = "unsloth_studio"_OP_NAME = "int8_dq_gelu_quant"_OP_NAME_SWIGLU = "int8_dq_swiglu_quant"+_OP_NAME_ACTQ = "int8_act_quant_rows"_SWIGLU_ATTR = "_unsloth_i8_swiglu"_LOCK = threading.Lock()# Read by the traced forwards: dynamo must not trace into the lru_cache'd registration._OP_HANDLE: Any = None+# set once the act quant kernel matched torchao bit for bit on a device; None = torchao's quant+_ACTQ_HANDLE: Any = None+# device indices whose own probe passed; the kernel never runs on a device that failed or was never probed+_ACTQ_DEVICES: frozenset = frozenset()+# UNSLOTH_DIFFUSION_INT8_FUSED=0 at the last install: int8_linear is then module(x)+_LINEAR_OFF = False# torchao's safe_int_mm home, resolved at install (outside any trace) for the same reason._INTMM_MODULE: Any = None# Marker on each patched module (no global registry: it would pin an unloaded transformer)._MARK = "_unsloth_i8_fused_prev"_NO_PREV = object()+# diffusion_int8_gemm's marker: int8_linear leaves those Linears to their fused-dequant GEMM forward+_I8_GEMM_MARK = "_unsloth_i8_gemm_prev"def int8_fused_disabled() -> bool:@@ -406,6 +425,57 @@ def _kernels() -> Optional[types.SimpleNamespace]:qi = tl.minimum(tl.maximum(qi, -128.0), 127.0)tl.store(qrow + offs, qi.to(tl.int8), mask = m)+ @triton.jit+ def act_quant_rows(+ x_ptr,+ q_ptr,+ s_ptr,+ K,+ stride_x,+ stride_q,+ BLOCK: tl.constexpr,+ ONE_PASS: tl.constexpr,+ FP32_SCALE: tl.constexpr,+ ):+ # torchao Int8Tensor.from_hp(x, PerRow()), symmetric: s = bf16(max(bf16(amax / 127.5), fp32 eps)); torchao+ # <= 0.17 keeps s in bf16 and rounds 1 / s and x * (1 / s) to bf16, >= 0.18 stores s as fp32 and keeps both+ # in fp32 (FP32_SCALE). q = clamp(rint(x * (1 / s)), -128, 127).+ row = tl.program_id(0).to(tl.int64)+ offs = tl.arange(0, BLOCK)+ xrow = x_ptr + row * stride_x+ qrow = q_ptr + row * stride_q+ if ONE_PASS:+ m = offs < K+ x = tl.load(xrow + offs, mask = m, other = 0.0).to(tl.float32)+ amax = tl.max(tl.abs(x), axis = 0)+ else:+ acc = tl.zeros((BLOCK,), dtype = tl.float32)+ for k in range(0, K, BLOCK):+ m = k + offs < K+ x = tl.load(xrow + k + offs, mask = m, other = 0.0).to(tl.float32)+ acc = tl.maximum(acc, tl.abs(x))+ amax = tl.max(acc, axis = 0)+ scale = _rbf16(tl.maximum(_rbf16(tl.math.div_rn(amax, 127.5)), 1.1920928955078125e-07))+ inv = tl.math.div_rn(1.0, scale)+ if not FP32_SCALE:+ inv = _rbf16(inv)+ tl.store(s_ptr + row, scale.to(s_ptr.dtype.element_ty))+ if ONE_PASS:+ p = x * inv+ if not FP32_SCALE:+ p = _rbf16(p)+ p = tl.minimum(tl.maximum(tl.extra.cuda.libdevice.rint(p), -128.0), 127.0)+ tl.store(qrow + offs, p.to(tl.int8), mask = m)+ else:+ for k in range(0, K, BLOCK):+ m = k + offs < K+ x = tl.load(xrow + k + offs, mask = m, other = 0.0).to(tl.float32)+ p = x * inv+ if not FP32_SCALE:+ p = _rbf16(p)+ p = tl.minimum(tl.maximum(tl.extra.cuda.libdevice.rint(p), -128.0), 127.0)+ tl.store(qrow + k + offs, p.to(tl.int8), mask = m)+@triton.jitdef gelu_bf16(x_ptr, o_ptr, n, BLOCK: tl.constexpr):offs = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK)@@ -452,6 +522,7 @@ def _kernels() -> Optional[types.SimpleNamespace]:return types.SimpleNamespace(dq_gelu_quant = dq_gelu_quant,dq_swiglu_quant = dq_swiglu_quant,+ act_quant_rows = act_quant_rows,gelu_bf16 = gelu_bf16,dq_bf16 = dq_bf16,triton = triton,@@ -640,6 +711,141 @@ def _op() -> Any:return types.SimpleNamespace(gelu = getattr(ns, _OP_NAME), swiglu = getattr(ns, _OP_NAME_SWIGLU))+@lru_cache(maxsize = 1)+def _act_scale_fp32() -> bool:+ """Whether this torchao's ``Int8Tensor.from_hp`` returns an fp32 activation scale (0.18+) or the input's bf16."""+ try:+ import torch+ from torchao.quantization.granularity import PerRow+ from torchao.quantization.quantize_.workflows.int8.int8_tensor import Int8Tensor++ x = torch.ones(1, 16, dtype = torch.bfloat16)+ return Int8Tensor.from_hp(x, PerRow()).scale.dtype == torch.float32+ except Exception: # noqa: BLE001 - the device probe still has to match torchao bit for bit+ return False+++def _launch_act_quant(x2d: Any) -> tuple:+ """(int8 [M, K], scale [M] in torchao's dtype) for a contiguous-row bf16 ``x2d``."""+ import torch++ k = _kernels()+ m, kk = x2d.shape+ if x2d.stride(-1) != 1:+ x2d = x2d.contiguous()+ fp32 = _act_scale_fp32()+ q = torch.empty((m, kk), device = x2d.device, dtype = torch.int8)+ s = torch.empty((m,), device = x2d.device, dtype = torch.float32 if fp32 else x2d.dtype)+ if m == 0:+ return q, s+ one_pass = kk <= 4096+ block = k.triton.next_power_of_2(kk) if one_pass else 2048+ with torch.cuda.device(x2d.device):+ k.act_quant_rows[(m,)](+ x2d,+ q,+ s,+ kk,+ x2d.stride(0),+ q.stride(0),+ BLOCK = block,+ ONE_PASS = one_pass,+ FP32_SCALE = fp32,+ num_warps = 8,+ enable_fp_fusion = False,+ )+ return q, s+++def reference_act_quant(x2d: Any) -> tuple:+ """torchao's own dynamic symmetric per-row quant of ``x2d``: (int8, scale [M])."""+ from torchao.quantization.granularity import PerRow+ from torchao.quantization.quantize_.workflows.int8.int8_tensor import Int8Tensor++ t = Int8Tensor.from_hp(x2d, PerRow())+ return t.qdata, t.scale.reshape(-1)+++@lru_cache(maxsize = 1)+def _act_quant_op() -> Any:+ """``unsloth_studio::int8_act_quant_rows`` (opaque to Inductor, allocation only), 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, _OP_NAME_ACTQ):+ return getattr(ns, _OP_NAME_ACTQ)+ custom_op = getattr(getattr(torch, "library", None), "custom_op", None)+ if custom_op is None:+ return None+ try:++ @custom_op(+ f"{_OP_NAMESPACE}::{_OP_NAME_ACTQ}",+ mutates_args = (),+ schema = "(Tensor x) -> (Tensor, Tensor)",+ )+ def _int8_act_quant_rows(x):+ return _launch_act_quant(x)++ @_int8_act_quant_rows.register_fake+ def _(x):+ return (+ x.new_empty((x.shape[0], x.shape[1]), dtype = torch.int8),+ x.new_empty((x.shape[0],), dtype = torch.float32 if _act_scale_fp32() else x.dtype),+ )+ except Exception: # noqa: BLE001+ return None+ return getattr(getattr(torch.ops, _OP_NAMESPACE), _OP_NAME_ACTQ)+++@lru_cache(maxsize = 8)+def _act_quant_device_ok(index: int) -> bool:+ """The per-row act quant kernel must equal torchao's quant bit for bit on this device and torchao: outlier+ channels, a zero row, huge values, one-pass and looped widths, ragged M."""+ try:+ import torch++ if _kernels() is None or _act_quant_op() is None:+ return False+ dev = torch.device("cuda", index)+ g = torch.Generator(device = "cpu").manual_seed(4)+ for m, k in ((33, 3840), (257, 10240), (17, 2560), (130, 256 * 7), (19, 4096), (5, 4097)):+ x = torch.randn(m, k, generator = g) * (torch.rand(1, k, generator = g) * 4)+ x[:, :5] *= 60+ x[1] = 0+ x[2, 3] = 3e4+ x = x.to(torch.bfloat16).to(dev)+ q, s = _launch_act_quant(x)+ rq, rs = reference_act_quant(x)+ if not (torch.equal(q, rq) and s.dtype == rs.dtype and torch.equal(s, rs)):+ return False+ torch.cuda.synchronize(dev)+ return True+ except Exception: # noqa: BLE001 - any failure keeps torchao's quant+ return False+++def _fast_act_quant(x2d: Any, weight: Any) -> tuple:+ """``_act_quant`` for a plain per-row Int8Tensor weight: the probed kernel when it matched torchao on this+ device (one pass over the row at bandwidth, where Inductor's codegen of the same quant ran 2-3x slower on B200),+ else torchao's own."""+ import torch++ if (+ _ACTQ_HANDLE is not None+ and x2d.is_cuda+ and x2d.device.index in _ACTQ_DEVICES+ and x2d.dtype == torch.bfloat16+ and x2d.dim() == 2+ and x2d.shape[0] > 0+ ):+ q, s = _ACTQ_HANDLE(x2d)+ return q, s.reshape(-1, 1)+ return _act_quant(x2d, weight)++@lru_cache(maxsize = 8)def _device_ok(index: int) -> bool:"""CUDA NVIDIA, Triton new enough, toolchain present, kernel compiles and matches the reference once."""@@ -1025,8 +1231,73 @@ def _get(module: Any, dotted: str) -> Any:return module+def _torchao_epilogue(c: Any, xs: Any, ws: Any, bias: Any, out_dtype: Any) -> Any:+ """torchao's Int8Tensor linear after ``_int_mm``, op for op: ``int_scaled_matmul``'s ``c * x_scale`` in the scale's+ dtype (fp32 for an fp16 scale), cast, ``* w_scale``, ``+ bias``, cast."""+ import torch++ inter = torch.float if xs.dtype == torch.half else xs.dtype+ y = (c * xs.reshape(-1, 1).to(inter)).to(out_dtype)+ y = y * ws.flatten()+ if bias is not None:+ y = y + bias+ return y.to(out_dtype)+++def int8_linear(module: Any, x: Any) -> Any:+ """``module(x)`` for a plain ``nn.Linear`` or ``ConvRotLinear`` holding a plain per-row ``Int8Tensor``: the module's+ own input rotation, torchao's act quant, ``_int_mm`` and torchao's epilogue, minus one term. torchao 0.17 applies+ the ASYMMETRIC zero-point correction whenever the activation carries a zero point, which its symmetric quant always+ does (zeros): a row sum of the int8 weight and a full-output ``- 0`` on every call (~4 ms per Z-Image 1024px step+ on B200). 0.18 skips it for symmetric activations, as this does; the values are the same (``y - 0 == y``).+ Anything else (LoRA wrappers, legacy tensors, small M, CPU, a Linear running diffusion_int8_gemm's fused GEMM) is+ ``module(x)``."""+ import torch+ from torch import nn++ from .diffusion_convrot import is_rotated_linear++ rotated = is_rotated_linear(module)+ # an instance-level forward is an offload hook (accelerate / diffusers) or another wrapper: only it may run+ if (+ _LINEAR_OFF+ or not (type(module) is nn.Linear or rotated)+ or _I8_GEMM_MARK in module.__dict__+ or "forward" in module.__dict__+ ):+ return module(x)+ weight = module.weight+ lead = x.shape[:-1]+ x2d = x.reshape(-1, x.shape[-1])+ if (+ x2d.shape[0] < _MIN_ROWS+ or not x.is_cuda+ or x.dtype != torch.bfloat16+ or not _plain_int8_weight(weight)+ or getattr(weight, "act_pre_scale", None) is not None+ or weight.device != x.device+ ):+ return module(x)+ if rotated:+ x2d = _rotate(x2d, module.convrot_groupsize)+ xq, xs = _fast_act_quant(x2d, weight)+ y = _torchao_epilogue(+ _int_mm(xq.reshape(-1, xq.shape[-1]), weight), xs, weight.scale, module.bias, x.dtype+ )+ return y.reshape(*lead, y.shape[-1])+++def _rotate(x2d: Any, group: int) -> Any:+ """``ConvRotLinear.forward``'s input rotation, same ops and dtype."""+ from .diffusion_convrot import build_convrot_hadamard, rotate_convrot_activation+ return rotate_convrot_activation(+ x2d, build_convrot_hadamard(group, device = x2d.device, dtype = x2d.dtype), group+ )++def _swiglu_forward(self: Any, hidden_states: Any, *args: Any, **kwargs: Any) -> Any:- """SwiGLU MLP with plain int8 weights: one act quant, one GEMM over [gate | value], fused SiLU-product quant."""+ """SwiGLU MLP with plain int8 weights: one act quant, one GEMM over [gate | value], fused SiLU-product quant.+ ConvRot parts: the shared input rotates once; a rotated down projection gets the bf16 product (see module doc)."""import torchrec = self.__dict__.get(_SWIGLU_ATTR)@@ -1041,13 +1312,36 @@ def _swiglu_forward(self: Any, hidden_states: Any, *args: Any, **kwargs: Any) ->)ok = ok and hidden_states.dtype == torch.bfloat16if ok:- fused_in, parts, down_name, n, gate_col, value_col = rec+ fused_in, parts, down_name, n, gate_col, value_col, in_group, down_group = recok = all(_get(self, nm) is mod for nm, mod in parts)if not ok:return type(self).forward(self, hidden_states, *args, **kwargs)down = _get(self, down_name)- xq, xs = _act_quant(x2d, fused_in.weight)+ if in_group:+ x2d = _rotate(x2d, in_group)+ xq, xs = _fast_act_quant(x2d, fused_in.weight)+ else:+ xq, xs = _act_quant(x2d, fused_in.weight)c = _int_mm(xq.reshape(-1, xq.shape[-1]), fused_in.weight)+ if down_group:+ ws = fused_in.weight.scale.flatten()+ bias = fused_in.bias+ dtype = hidden_states.dtype++ def half(col):+ return _torchao_epilogue(+ c[:, col : col + n],+ xs,+ ws[col : col + n],+ None if bias is None else bias[col : col + n],+ dtype,+ )++ gating = getattr(self, "_forward_silu_gating", None)+ g, v = half(gate_col), half(value_col)+ h = gating(g, v) if callable(gating) else torch.nn.functional.silu(g) * v+ y = int8_linear(down, h)+ return y.reshape(*lead, y.shape[-1])q, s = _OP_HANDLE.swiglu(c, xs.reshape(-1), fused_in.weight.scale.flatten(), fused_in.bias, gate_col, value_col, n)@@ -1076,6 +1370,8 @@ def _prepare_swiglu(module: Any) -> bool:n,gate_col,value_col,+ 0,+ 0,)return Truesplit = _split_spec(module)@@ -1083,7 +1379,8 @@ def _prepare_swiglu(module: Any) -> bool:return Falsegate_name, value_name, down_name = splitgate, value, down = _get(module, gate_name), _get(module, value_name), _get(module, down_name)- if any(type(m) is not nn.Linear for m in (gate, value, down)):+ groups = _split_rotation_groups(gate, value, down)+ if groups is None:return Falseif not all(_plain_int8_weight(m.weight) for m in (gate, value, down)):return False@@ -1094,10 +1391,22 @@ def _prepare_swiglu(module: Any) -> bool:return Falsen = gate.weight.shape[0]parts = ((gate_name, gate), (value_name, value), (down_name, down))- module.__dict__[_SWIGLU_ATTR] = (fused, parts, down_name, n, 0, n)+ module.__dict__[_SWIGLU_ATTR] = (fused, parts, down_name, n, 0, n, *groups)return True+def _split_rotation_groups(gate: Any, value: Any, down: Any) -> Optional[tuple]:+ """(in-projection ConvRot group, down ConvRot group), 0 = plain, for a split SwiGLU; None when the parts are+ neither plain Linears nor ConvRotLinears the forward reproduces (gate and value must agree: one input)."""+ from .diffusion_zimage_fused import _rotation_group++ in_group = _rotation_group([gate, value])+ down_group = _rotation_group([down])+ if in_group is None or down_group is None:+ return None+ return in_group, down_group++def _exact_linear(*modules: Any) -> bool:"""Plain nn.Linear only: a subclass (ConvRotLinear) may transform the input the fused _int_mm would skip."""from torch import nn@@ -1209,7 +1518,15 @@ def install(offload_active: bool = False,) -> int:"""Idempotent; returns the (candidate) count. Must run before the first compiled forward, which traces ``forward``."""- if int8_fused_disabled() or transformer is None or offload_active:+ global _ACTQ_HANDLE, _ACTQ_DEVICES, _LINEAR_OFF+ if int8_fused_disabled():+ # process-global: a previous load's probe must not outlive the kill switch+ _ACTQ_HANDLE = None+ _ACTQ_DEVICES = frozenset()+ _LINEAR_OFF = True+ return 0+ _LINEAR_OFF = False+ if transformer is None or offload_active:return 0if resident_cuda_device(transformer) is not None:return _finalize(transformer, logger)@@ -1239,12 +1556,14 @@ def _swiglu_eligible(module: Any) -> bool:spec = _swiglu_spec(module)if spec is not None:parts = (_get(module, spec[0]), _get(module, spec[2]))- else:- split = _split_spec(module)- if split is None:- return False- parts = tuple(_get(module, name) for name in split)- return all(type(m) is nn.Linear and _plain_int8_weight(m.weight) for m in parts)+ return all(type(m) is nn.Linear and _plain_int8_weight(m.weight) for m in parts)+ split = _split_spec(module)+ if split is None:+ return False+ parts = tuple(_get(module, name) for name in split)+ if _split_rotation_groups(*parts) is None:+ return False+ return all(_plain_int8_weight(m.weight) for m in parts)except Exception: # noqa: BLE001return False@@ -1257,7 +1576,7 @@ def _has_eligible(transformer: Any) -> bool:def _finalize(transformer: Any, logger: Any = None) -> int:- global _OP_HANDLE, _INTMM_MODULE+ global _OP_HANDLE, _ACTQ_HANDLE, _ACTQ_DEVICES, _INTMM_MODULEdev = resident_cuda_device(transformer)if dev is None:return 0@@ -1276,8 +1595,15 @@ def _finalize(transformer: Any, logger: Any = None) -> int:return 0count = 0rearm = False+ index = dev.index if dev.index is not None else torch.cuda.current_device()+ actq = _act_quant_op() if _act_quant_device_ok(index) else Nonewith _LOCK:_OP_HANDLE = _op()+ if actq is not None:+ _ACTQ_HANDLE = actq+ _ACTQ_DEVICES = _ACTQ_DEVICES | {index}+ else:+ _ACTQ_DEVICES = _ACTQ_DEVICES - {index}for _name, module in transformer.named_modules():if _MARK in module.__dict__:count += 1diff --git a/studio/backend/core/inference/diffusion_prequant.py b/studio/backend/core/inference/diffusion_prequant.pyindex a4011a741f9..4b590c4f90b 100644--- a/studio/backend/core/inference/diffusion_prequant.py+++ b/studio/backend/core/inference/diffusion_prequant.py@@ -653,11 +653,22 @@ def resolve_prequant_source(# safetensors spelling ahead of the pickle. Order-preserving dedup so a family that declares# exactly what the chain would derive does not make the downloader ask twice for it.declared = (preferred,) if preferred else ()- # opt-in rotated artifact goes first; the plain chain stays behind it (not yet hosted, or offline)- from .diffusion_transformer_quant import convrot_prequant_filename, int8_convrot_enabled+ # rotated artifact (hosted) first, only in its own repo; the plain chain stays behind it (offline, older caches)+ from .diffusion_transformer_quant import (+ convrot_prequant_filename,+ convrot_prequant_repo,+ int8_convrot_enabled,+ )- rotated = convrot_prequant_filename(scheme, getattr(fam, "name", None))- if rotated and int8_convrot_enabled():+ fam_name = getattr(fam, "name", None)+ rotated = convrot_prequant_filename(scheme, fam_name)+ rotated_repo = convrot_prequant_repo(scheme, fam_name)+ if (+ rotated+ and rotated_repo+ and str(repo_id).strip().lower() == rotated_repo.lower()+ and int8_convrot_enabled(fam_name)+ ):declared = (rotated,) + declarednames: list[str] = []for name in declared + derived:@@ -947,18 +958,80 @@ def _fingerprint_sampled(fqn: str) -> bool:return hashlib.md5(fqn.encode("utf-8")).digest()[0] % FINGERPRINT_SAMPLE_RATE == 0+def _verified_marker(path: Any, expected: dict) -> Optional[tuple]:+ """(marker file, identity) for a checkpoint whose full check passed before: same real file, size, mtime and+ recorded fingerprint. None when the file cannot be identified (then every load checks in full)."""+ import hashlib+ import json+ import os++ try:+ real = os.path.realpath(str(path))+ st = os.stat(real)+ from .diffusion_compile_cache import cache_root++ recorded = hashlib.md5(json.dumps(expected, sort_keys = True).encode("utf-8")).hexdigest()+ identity = {+ "path": real,+ "size": st.st_size,+ "mtime_ns": st.st_mtime_ns,+ "fingerprint": recorded,+ }+ name = hashlib.md5(real.encode("utf-8")).hexdigest() + ".json"+ return cache_root() / "prequant_verified" / name, identity+ except Exception: # noqa: BLE001 -- unidentifiable: check in full+ return None+++def _already_verified(marker: Optional[tuple]) -> bool:+ import json+ if marker is None:+ return False+ try:+ return json.loads(marker[0].read_text(encoding = "utf-8")) == marker[1]+ except Exception: # noqa: BLE001 -- absent or unreadable marker: check in full+ return False+++def _remember_verified(marker: Optional[tuple]) -> None:+ import json+ import os++ if marker is None:+ return+ try:+ marker[0].parent.mkdir(parents = True, exist_ok = True)+ tmp = marker[0].with_suffix(".tmp")+ tmp.write_text(json.dumps(marker[1], sort_keys = True), encoding = "utf-8")+ os.replace(tmp, marker[0])+ except Exception: # noqa: BLE001 -- the next load just checks in full again+ pass++def _verify_packed_fingerprint(state_dict: Any,metadata: Any,*,logger: Any = None,+ path: Any = None,) -> bool:- """Check the artifact's packed fingerprint: a mismatch drops to dense, a missing or uncomputable block passes."""+ """Check the artifact's packed fingerprint: a mismatch drops to dense, a missing or uncomputable block passes.++ A full pass is remembered per file (real path, size, mtime, recorded fingerprint) in the Studio cache, so later+ loads of the same unchanged file skip the md5 of every weight; any change to the file checks in full again."""block = (metadata or {}).get("fingerprint")expected = (block or {}).get("modules") if isinstance(block, dict) else Noneif not expected:return Truemode = _fingerprint_mode()+ marker = _verified_marker(path, expected) if path is not None and mode == "full" else None+ if _already_verified(marker):+ if logger is not None:+ logger.info(+ "diffusion.prequant: fingerprint verified on an earlier load of this unchanged file (%d weights)",+ len(expected),+ )+ return Trueif mode == "off":if logger is not None:logger.debug(@@ -997,6 +1070,7 @@ def _verify_packed_fingerprint(len(expected),mode,)+ _remember_verified(marker)return Trueif logger is not None:logger.error(@@ -1272,7 +1346,9 @@ def load_prequantized_transformer(return Nonestate_dict = ckpt["state_dict"]# The only check reading what the artifact HOLDS: corruption after build passes the rest.- if not _verify_packed_fingerprint(state_dict, ckpt.get("metadata") or {}, logger = logger):+ if not _verify_packed_fingerprint(+ state_dict, ckpt.get("metadata") or {}, logger = logger, path = path+ ):return None_repair_legacy_checkpoint(ckpt, scheme, logger)_pin_kernel_preference(state_dict, logger)diff --git a/studio/backend/core/inference/diffusion_transformer_quant.py b/studio/backend/core/inference/diffusion_transformer_quant.pyindex a30b9713d3c..d81687d816f 100644--- a/studio/backend/core/inference/diffusion_transformer_quant.py+++ b/studio/backend/core/inference/diffusion_transformer_quant.py@@ -221,18 +221,48 @@ _INT8_FAMILY_CONVROT: dict[str, tuple[int, tuple[str, ...]]] = {"img_mlp.out",),),+ # exactly the Linears the hosted INT8 checkpoint quantizes (all input axes 256-divisible)+ "z-image": (+ 256,+ (+ "attention.to_q",+ "attention.to_k",+ "attention.to_v",+ "attention.to_out.0",+ "feed_forward.w1",+ "feed_forward.w2",+ "feed_forward.w3",+ "cap_embedder.1",+ ),+ ),}_INT8_FAMILY_CONVROT_FILENAME: dict[str, str] = {"qwen-image-2.1": "Qwen-Image-2.1-INT8-ConvRot.safetensors",+ "z-image": "Z-Image-Turbo-INT8-ConvRot.safetensors",+}+# Only this repo gets the rotated name prepended: a same-named file elsewhere is not this build.+_INT8_FAMILY_CONVROT_REPO: dict[str, str] = {+ "qwen-image-2.1": "unsloth/Qwen-Image-2.1-FP8",+ "z-image": "unsloth/Z-Image-Turbo-FP8",}+# Families whose int8 runs ConvRot unless the env turns it off; the rest stay opt-in (``=1``).+_INT8_FAMILY_CONVROT_DEFAULT_ON: frozenset[str] = frozenset({"z-image"})+INT8_CONVROT_ENV = "UNSLOTH_DIFFUSION_INT8_CONVROT"-def int8_convrot_enabled() -> bool:- return (_os.environ.get(INT8_CONVROT_ENV) or "").strip().lower() in ("1", "on", "true", "yes")+def int8_convrot_enabled(family: Optional[str] = None) -> bool:+ """``UNSLOTH_DIFFUSION_INT8_CONVROT``: ``1`` turns ConvRot on for every family with a table entry, ``0`` turns it+ off everywhere (the kill switch); unset follows the family default."""+ raw = (_os.environ.get(INT8_CONVROT_ENV) or "").strip().lower()+ if raw in ("1", "on", "true", "yes"):+ return True+ if raw in ("0", "off", "false", "no"):+ return False+ return str(family or "").strip().lower() in _INT8_FAMILY_CONVROT_DEFAULT_ONdef convrot_spec_for_scheme(@@ -250,6 +280,13 @@ def convrot_prequant_filename(scheme: str, family: Optional[str] = None) -> Optireturn _INT8_FAMILY_CONVROT_FILENAME.get(str(family or "").strip().lower())+def convrot_prequant_repo(scheme: str, family: Optional[str] = None) -> Optional[str]:+ """The repo the family's rotated int8 artifact is published to, or None."""+ if scheme != TQ_INT8:+ return None+ return _INT8_FAMILY_CONVROT_REPO.get(str(family or "").strip().lower())++def convrot_fqns(transformer: Any, filter_fn: Any, group: int, suffixes: tuple[str, ...]) -> tuple[str, ...]:@@ -272,7 +309,7 @@ def apply_runtime_convrot() -> tuple[str, ...]:"""Rotate BEFORE quantize_; a later failure leaves an exact dense model, so fallback stays correct."""group, suffixes = convrot_spec_for_scheme(scheme, family)- if not group or not int8_convrot_enabled():+ if not group or not int8_convrot_enabled(family):return ()from .diffusion_convrot import CONVROT_ATTR, CONVROT_KIND, rotate_linears_, warm_rotation_cachediff --git a/studio/backend/core/inference/diffusion_zimage_fused.py b/studio/backend/core/inference/diffusion_zimage_fused.pyindex 857f14876fa..2b84b0b04e5 100644--- a/studio/backend/core/inference/diffusion_zimage_fused.py+++ b/studio/backend/core/inference/diffusion_zimage_fused.py@@ -5,6 +5,14 @@(bit-identical to the complex multiply Inductor cannot lower) and one fused QKV GEMM (exact for int8:per-row scales). ``to_q/to_k/to_v`` weights become views of the fused one; the fused Linear is used onlywhile they are still the modules it was built from, so LoRA / later wrappers fall back to stock.++int8 projections (fused QKV, ``to_out``) run through ``diffusion_int8_fused.int8_linear``: torchao's own math without+torchao 0.17's always-on zero-point correction, which re-sums the weight rows on every call.++ConvRot (int8 with a block-Hadamard input rotation): q, k and v rotate the SAME input, and the rotation acts on the+shared input axis, so the three rotated weights concatenate along the output axis like plain ones. The fused Linear is+then itself a ConvRotLinear at the parts' group: one rotation and one activation quant feed the fused GEMM instead of+three of each. Same ops on the same input, so the fused output equals the three separate rotated projections.Kill switch: ``UNSLOTH_DIFFUSION_ZIMAGE_FUSED=0``."""@@ -71,6 +79,9 @@ def _qkv_intact(attn: Any) -> Any:def _make_call(stock: Any) -> Any:import torch+ # bound here, not inside the traced __call__+ from .diffusion_int8_fused import int8_linear+def __call__(self,attn,@@ -87,7 +98,7 @@ def _make_call(stock: Any) -> Any:fused = _qkv_intact(attn)if fused is not None:- query, key, value = fused(hidden_states).chunk(3, dim = -1)+ query, key, value = int8_linear(fused, hidden_states).chunk(3, dim = -1)else:query = attn.to_q(hidden_states)key = attn.to_k(hidden_states)@@ -126,7 +137,7 @@ def _make_call(stock: Any) -> Any:parallel_config = self._parallel_config,)hidden_states = hidden_states.flatten(2, 3).to(dtype)- output = attn.to_out[0](hidden_states)+ output = int8_linear(attn.to_out[0], hidden_states)if len(attn.to_out) > 1:output = attn.to_out[1](output)return output@@ -144,13 +155,38 @@ def _stock_rope(x_in: Any, freqs_cis: Any) -> Any:return x_out.type_as(x_in)+def _rotation_group(linears: list) -> Any:+ """0 when every part is a plain ``nn.Linear``, the shared ConvRot group when every part rotates its input at the+ same group, else None (a mix cannot share one input)."""+ from torch import nn++ if all(type(lin) is nn.Linear for lin in linears):+ return 0+ try:+ from .diffusion_convrot import convrot_linear_class+ cls = convrot_linear_class()+ except Exception: # noqa: BLE001+ return None+ if not all(type(lin) is cls for lin in linears):+ return None+ groups = {getattr(lin, "convrot_groupsize", None) for lin in linears}+ if len(groups) != 1:+ return None+ group = groups.pop()+ if not isinstance(group, int) or group <= 0 or linears[0].in_features % group:+ return None+ return group++def _fuse_linears(linears: list) -> Any:- """One ``nn.Linear`` over the concatenated outputs, or None; torchao tensors are rebuilt from their data/attribute lists."""+ """One Linear over the concatenated outputs, or None; torchao tensors are rebuilt from their data/attribute lists.+ Parts that all rotate their input at one ConvRot group give a fused ConvRotLinear at that group."""import torchfrom torch import nnws = [lin.weight for lin in linears]- if any(type(lin) is not nn.Linear for lin in linears):+ group = _rotation_group(linears)+ if group is None:return Nonehas_bias = [lin.bias is not None for lin in linears]if any(has_bias) and not all(has_bias):@@ -196,6 +232,9 @@ def _fuse_linears(linears: list) -> Any:out.bias = nn.Parameter(torch.cat([lin.bias.detach() for lin in linears]), requires_grad = False)+ if group:+ from .diffusion_convrot import _install_rotation+ _install_rotation(out, group)return outdiff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.pyindex 2365db529b9..b710d4ad58f 100644--- a/studio/backend/tests/test_diffusion_backend.py+++ b/studio/backend/tests/test_diffusion_backend.py@@ -3046,6 +3046,9 @@ def test_unload_cancels_pipeline_construction(if phase.startswith("dense"):mp.setattr(diff_mod, "dense_transformer_supported", lambda target: True)mp.setattr(diff_mod, "select_transformer_quant_scheme", lambda *a, **k: "int8")+ # Z-Image declares its rotated INT8 artifact, so an auto GGUF pick (dense_fallback) would decline the+ # uncached hosted pre-quant and never reach the dense attempt this phase parks in. Treat it as cached.+ mp.setattr(diff_mod, "_uncached_prequant_repo", lambda *a, **k: None)mp.setattr(backend,"_dense_transformer_resident_bytes",diff --git a/studio/backend/tests/test_diffusion_int8_fused.py b/studio/backend/tests/test_diffusion_int8_fused.pyindex a3785c1ae99..b714b1de327 100644--- a/studio/backend/tests/test_diffusion_int8_fused.py+++ b/studio/backend/tests/test_diffusion_int8_fused.py@@ -839,3 +839,226 @@ def test_int8_flux_under_fbcache_renders_through_the_fused_kernel():out = run(model)assert torch.equal(out[0], ref[0]) and torch.equal(out[1], ref[1])assert all(fused.is_installed(b) for b in model.single_transformer_blocks)+++def _zimage_convrot_ff(rotate):+ """Z-Image FeedForward(256, 512) with ``rotate`` of w1 / w2 / w3 ConvRot-rotated at group 256, then int8."""+ from torchao.quantization import Int8DynamicActivationInt8WeightConfig, quantize_++ from core.inference.diffusion_convrot import rotate_linears_, warm_rotation_cache++ zmod = pytest.importorskip("diffusers.models.transformers.transformer_z_image")+ torch.manual_seed(0)+ ff = zmod.FeedForward(256, 512).cuda().to(torch.bfloat16).eval()+ for p in ff.parameters():+ p.data.normal_(0, 0.05)+ rotate_linears_(ff, list(rotate), 256)+ warm_rotation_cache(ff, "cuda", torch.bfloat16)+ quantize_(ff, _int8tensor_config(Int8DynamicActivationInt8WeightConfig))+ return _require_int8tensor(ff)+++def _int8tensor_config(cls):+ """The Int8Tensor (v2) config the hosted int8 checkpoints carry; torchao <= 0.17 defaults to the legacy tensor."""+ try:+ return cls(version = 2)+ except TypeError:+ return cls()+++def _outlier_input():+ g = torch.Generator(device = "cpu").manual_seed(3)+ x = torch.randn(2, 150, 256, generator = g)+ x[..., :4] *= 40 # a few heavy channels: what the rotation exists for+ return x.to(torch.bfloat16).cuda()+++@needs_cuda+ "rotate, groups",+ [(("w1", "w2", "w3"), (256, 256)), (("w1", "w3"), (256, 0)), (("w2",), (0, 256))],+)+def test_zimage_convrot_swiglu_fuses_and_matches_stock_eager(rotate, groups):+ if not groups[1] and not _act_scale_is_fp32():+ # A plain w2 runs the SwiGLU kernel's own quant, which matches torchao's fp32-scale act quant (>= 0.18) only;+ # this is the kernel's existing contract, unchanged here (the all-rotated MLP never reaches that quant).+ pytest.skip(+ "the fused SwiGLU kernel's act quant matches torchao >= 0.18 (fp32 activation scale) only"+ )+ ff = _zimage_convrot_ff(rotate)+ x = _outlier_input()+ with torch.no_grad():+ ref = ff(x)+ torch._dynamo.reset()+ stock_compiled = torch.compile(ff, fullgraph = True)(x)+ assert fused.install(ff) == 1+ assert ff.__dict__[fused._SWIGLU_ATTR][6:] == groups+ out = ff(x)+ torch._dynamo.reset()+ compiled = torch.compile(ff, fullgraph = True)(x)+ # one rotation + one act quant for w1 and w3 instead of two of each: the same ops on the same input+ assert torch.equal(out, ref)+ _assert_within_compile_floor(compiled, stock_compiled, ref)+++@needs_cuda+def test_zimage_convrot_swiglu_with_disagreeing_gate_and_value_keeps_stock():+ ff = _zimage_convrot_ff(("w1",)) # w3 plain: the two halves no longer share one input+ assert fused.install(ff) == 0+ assert not fused.is_installed(ff)+++def _act_scale_is_fp32() -> bool:+ from torchao.quantization.granularity import PerRow+ from torchao.quantization.quantize_.workflows.int8.int8_tensor import Int8Tensor++ x = torch.ones(32, 64, dtype = torch.bfloat16)+ return Int8Tensor.from_hp(x, PerRow()).scale.dtype == torch.float32+++@needs_cuda+ "m, k", [(4224, 3840), (4224, 10240), (77, 2560), (17, 4096), (40, 4352), (3, 256)]+)+def test_act_quant_kernel_is_bit_exact_vs_torchao(m, k):+ assert fused._act_quant_device_ok(torch.cuda.current_device())+ g = torch.Generator(device = "cpu").manual_seed(m + k)+ x = torch.randn(m, k, generator = g) * (torch.rand(1, k, generator = g) * 4)+ x[:, :5] *= 80+ x[min(1, m - 1)] = 0+ x = x.to(torch.bfloat16).cuda()+ q, s = fused._act_quant_op()(x)+ rq, rs = fused.reference_act_quant(x)+ # torchao's own scale dtype: bf16 up to 0.17, fp32 from 0.18+ assert s.dtype == rs.dtype == (torch.float32 if fused._act_scale_fp32() else torch.bfloat16)+ assert torch.equal(q, rq) and torch.equal(s, rs)+ with torch.no_grad():+ torch._dynamo.reset()+ cq, cs = torch.compile(lambda t: fused._act_quant_op()(t), fullgraph = True)(x)+ assert torch.equal(cq, rq) and torch.equal(cs, rs)+++@needs_cuda[email protected]("fast_quant", [False, True])[email protected]("rotated", [False, True])[email protected]("bias", [False, True])+def test_int8_linear_equals_the_module_without_the_zero_point_pass(+ rotated, bias, fast_quant, monkeypatch+):+ monkeypatch.setattr(fused, "_ACTQ_HANDLE", fused._act_quant_op() if fast_quant else None)+ monkeypatch.setattr(fused, "_ACTQ_DEVICES", frozenset({torch.cuda.current_device()}))+ from torchao.quantization import Int8DynamicActivationInt8WeightConfig, quantize_++ from core.inference.diffusion_convrot import rotate_linears_, warm_rotation_cache++ torch.manual_seed(0)+ holder = torch.nn.Sequential(torch.nn.Linear(512, 384, bias = bias)).cuda().to(torch.bfloat16)+ if rotated:+ rotate_linears_(holder, ["0"], 256)+ warm_rotation_cache(holder, "cuda", torch.bfloat16)+ quantize_(holder, _int8tensor_config(Int8DynamicActivationInt8WeightConfig))+ lin = _require_int8tensor(holder)[0]+ x = _outlier_input().repeat(1, 1, 2)+ with torch.no_grad():+ ref = lin(x)+ out = fused.int8_linear(lin, x)+ torch._dynamo.reset()+ compiled = torch.compile(lambda t: fused.int8_linear(lin, t), fullgraph = True)(x)+ stock_compiled = torch.compile(lin, fullgraph = True)(x)+ assert torch.equal(out, ref) # y - 0 == y: the dropped term is exactly zero+ _assert_within_compile_floor(compiled, stock_compiled, ref)+ # anything it cannot reproduce is the module itself+ small = x[:, :4]+ assert torch.equal(fused.int8_linear(lin, small), lin(small))+++def test_kill_switch_also_drops_the_act_quant_kernel(monkeypatch):+ monkeypatch.setattr(fused, "_ACTQ_HANDLE", object())+ monkeypatch.setattr(fused, "_ACTQ_DEVICES", frozenset({0}))+ monkeypatch.setenv(fused.INT8_FUSED_ENV, "0")+ assert fused.install(torch.nn.Linear(8, 8)) == 0+ assert fused._ACTQ_HANDLE is None and not fused._ACTQ_DEVICES+++@needs_cuda+def test_kill_switch_makes_int8_linear_the_module(monkeypatch):+ class Reached(Exception):+ pass++ def reached(*a, **k):+ raise Reached++ # a Linear int8_linear would otherwise run itself+ monkeypatch.setattr(fused, "_plain_int8_weight", lambda w: True)+ monkeypatch.setattr(fused, "_fast_act_quant", reached)+ lin = torch.nn.Linear(64, 32).cuda().to(torch.bfloat16)+ x = torch.randn(32, 64, device = "cuda", dtype = torch.bfloat16)+ monkeypatch.delenv(fused.INT8_FUSED_ENV, raising = False)+ fused.install(None)+ with pytest.raises(Reached):+ fused.int8_linear(lin, x)+ monkeypatch.setenv(fused.INT8_FUSED_ENV, "0")+ fused.install(None)+ assert torch.equal(fused.int8_linear(lin, x), lin(x))+ monkeypatch.delenv(fused.INT8_FUSED_ENV)+ fused.install(None)+ assert fused._LINEAR_OFF is False+++@needs_cuda+def test_int8_linear_leaves_offload_hooks_and_off_device_weights_to_the_module(monkeypatch):+ from accelerate.hooks import ModelHook, add_hook_to_module++ class Reached(Exception):+ pass++ def reached(*a, **k):+ raise Reached++ monkeypatch.setattr(fused, "_LINEAR_OFF", False)+ monkeypatch.setattr(fused, "_plain_int8_weight", lambda w: True)+ monkeypatch.setattr(fused, "_fast_act_quant", reached)+ x = torch.randn(32, 64, device = "cuda", dtype = torch.bfloat16)+ lin = torch.nn.Linear(64, 32).cuda().to(torch.bfloat16)+ with pytest.raises(Reached): # the control: a bare Linear is run by int8_linear itself+ fused.int8_linear(lin, x)++ calls = []++ class Onload(ModelHook):+ def pre_forward(self, module, *args, **kwargs):+ calls.append(module.weight.device.type)+ module.to("cuda")+ return args, kwargs++ # a hook runs even when the weight already sits on the input's device+ hooked = torch.nn.Linear(64, 32).cuda().to(torch.bfloat16)+ add_hook_to_module(hooked, Onload())+ assert torch.equal(fused.int8_linear(hooked, x), hooked(x)) and calls == ["cuda", "cuda"]+ # no hook and the weight elsewhere: module(x) (torch's own device error), never the int8 path+ off_device = torch.nn.Linear(64, 32).to(torch.bfloat16)+ with pytest.raises(RuntimeError):+ fused.int8_linear(off_device, x)+++@needs_cuda+def test_act_quant_kernel_only_runs_on_a_device_that_passed_its_probe(monkeypatch):+ calls = []+ monkeypatch.setattr(fused, "_ACTQ_HANDLE", lambda x: calls.append(x) or (x, x[:, 0]))+ monkeypatch.setattr(fused, "_act_quant", lambda x, w: ("stock", None))+ x = torch.zeros(32, 256, device = "cuda", dtype = torch.bfloat16)+ monkeypatch.setattr(fused, "_ACTQ_DEVICES", frozenset({x.device.index + 1}))+ assert fused._fast_act_quant(x, None) == ("stock", None) and not calls+ monkeypatch.setattr(fused, "_ACTQ_DEVICES", frozenset({x.device.index}))+ fused._fast_act_quant(x, None)+ assert len(calls) == 1+++def test_int8_linear_leaves_an_installed_int8_gemm_forward_alone(monkeypatch):+ from core.inference import diffusion_int8_gemm as g8++ assert fused._I8_GEMM_MARK == g8._MARK+ lin = torch.nn.Linear(8, 8)+ lin.__dict__[g8._MARK] = object() # what diffusion_int8_gemm.install leaves on a swapped Linear+ lin.forward = lambda x: "int8_gemm forward"+ assert fused.int8_linear(lin, torch.randn(32, 8)) == "int8_gemm forward"diff --git a/studio/backend/tests/test_diffusion_int8_runtime_convrot.py b/studio/backend/tests/test_diffusion_int8_runtime_convrot.pyindex f9fde1b62da..6f960d3956d 100644--- a/studio/backend/tests/test_diffusion_int8_runtime_convrot.py+++ b/studio/backend/tests/test_diffusion_int8_runtime_convrot.py@@ -402,3 +402,112 @@ def test_real_peft_adapters_rotate_their_base_layer_and_stay_exact(_fresh_peft_t) as exc: # peft < 0.19 with torchao >= 0.18, patched only once unsloth is importedpytest.skip(f"peft cannot dispatch LoRA on this torchao: {exc}")_check_base_layers_rotated(model)+++_ZIMAGE_SUFFIXES = {+ "attention.to_q",+ "attention.to_k",+ "attention.to_v",+ "attention.to_out.0",+ "feed_forward.w1",+ "feed_forward.w2",+ "feed_forward.w3",+ "cap_embedder.1",+}+++def test_zimage_int8_convrot_spec_and_artifact_name():+ group, suffixes = tq.convrot_spec_for_scheme(tq.TQ_INT8, "z-image")+ assert group == 256 and set(suffixes) == _ZIMAGE_SUFFIXES+ assert (+ tq.convrot_prequant_filename(tq.TQ_INT8, "z-image")+ == "Z-Image-Turbo-INT8-ConvRot.safetensors"+ )+ for scheme in (tq.TQ_FP8, tq.TQ_NVFP4, tq.TQ_MXFP8):+ assert tq.convrot_spec_for_scheme(scheme, "z-image") == (0, ())+ assert tq.convrot_prequant_filename(scheme, "z-image") is None+++def test_zimage_convrot_is_default_on_and_the_env_is_its_kill_switch(monkeypatch):+ monkeypatch.delenv(tq.INT8_CONVROT_ENV)+ assert tq.int8_convrot_enabled("z-image") and tq.int8_convrot_enabled(" Z-Image ")+ # every other family keeps the opt-in it had+ for family in (None, "qwen-image-2.1", "qwen-image", "flux.1", "minimax-h3"):+ assert not tq.int8_convrot_enabled(family)+ for off in ("0", "off", "false", "no", " OFF "):+ monkeypatch.setenv(tq.INT8_CONVROT_ENV, off)+ assert not tq.int8_convrot_enabled("z-image")+ monkeypatch.setenv(tq.INT8_CONVROT_ENV, "1")+ assert tq.int8_convrot_enabled("qwen-image-2.1") and tq.int8_convrot_enabled("z-image")++[email protected]("env, rotated_first", [(None, True), ("0", False), ("1", True)])+def test_zimage_int8_resolves_the_rotated_artifact_first_unless_killed(+ monkeypatch, env, rotated_first+):+ from core.inference.diffusion_families import detect_family+ from core.inference.diffusion_prequant import candidate_filenames_of, resolve_prequant_source++ if env is None:+ monkeypatch.delenv(tq.INT8_CONVROT_ENV)+ else:+ monkeypatch.setenv(tq.INT8_CONVROT_ENV, env)+ fam = detect_family("Tongyi-MAI/Z-Image-Turbo")+ src = resolve_prequant_source(fam, "int8")+ names = candidate_filenames_of(src)+ assert src.location == "unsloth/Z-Image-Turbo-FP8"+ # the plain artifact always stays in the chain behind it: not yet hosted, offline, or an older cache+ assert "Z-Image-Turbo-INT8.pt" in names+ assert (names[0] == "Z-Image-Turbo-INT8-ConvRot.safetensors") is rotated_first+ assert ("Z-Image-Turbo-INT8-ConvRot.safetensors" in names) is rotated_first+ assert "Z-Image-Turbo-INT8-ConvRot.safetensors" not in candidate_filenames_of(+ resolve_prequant_source(fam, "fp8")+ )+++def test_zimage_rotated_set_is_exactly_the_int8_quantized_set(monkeypatch):+ # The real Z-Image-Turbo skeleton on the meta device: ConvRot must cover every Linear the int8 filter quantizes+ # (a quantized Linear left unrotated would be a silent accuracy hole) and nothing it does not.+ monkeypatch.delenv(tq.INT8_CONVROT_ENV)+ zmod = pytest.importorskip("diffusers.models.transformers.transformer_z_image")+ from accelerate import init_empty_weights++ with init_empty_weights():+ model = zmod.ZImageTransformer2DModel(+ all_patch_size = (2,),+ all_f_patch_size = (1,),+ in_channels = 16,+ dim = 3840,+ n_layers = 30,+ n_refiner_layers = 2,+ n_heads = 30,+ n_kv_heads = 30,+ norm_eps = 1e-5,+ qk_norm = True,+ cap_feat_dim = 2560,+ rope_theta = 256.0,+ t_scale = 1000.0,+ axes_dims = [32, 48, 48],+ axes_lens = [1024, 512, 512],+ )+ filt = _filter("z-image")+ quantized = {n for n, m in model.named_modules() if isinstance(m, nn.Linear) and filt(m, n)}+ group, suffixes = tq.convrot_spec_for_scheme(tq.TQ_INT8, "z-image")+ rotated = set(tq.convrot_fqns(model, filt, group, suffixes))+ assert len(quantized) == 239+ assert rotated == quantized+++def test_zimage_rotated_artifact_is_only_named_in_its_own_repo(monkeypatch):+ # a variant base's repo (or any other repo a z-image family resolves) never gets the Turbo ConvRot name+ import dataclasses++ from core.inference.diffusion_families import detect_family+ from core.inference.diffusion_prequant import candidate_filenames_of, resolve_prequant_source++ monkeypatch.delenv(tq.INT8_CONVROT_ENV)+ fam = dataclasses.replace(+ detect_family("Tongyi-MAI/Z-Image-Turbo"), prequant_repos = (("int8", "org/other-int8"),)+ )+ names = candidate_filenames_of(resolve_prequant_source(fam, "int8"))+ assert "Z-Image-Turbo-INT8-ConvRot.safetensors" not in namesdiff --git a/studio/backend/tests/test_diffusion_prequant.py b/studio/backend/tests/test_diffusion_prequant.pyindex 22730e1311f..6ea55c086cb 100644--- a/studio/backend/tests/test_diffusion_prequant.py+++ b/studio/backend/tests/test_diffusion_prequant.py@@ -2845,3 +2845,41 @@ def test_the_download_plan_probes_with_the_user_token():src = inspect.getsource(DiffusionBackend.download_plan)assert '{**load_kwargs, "base_repo": base, "hf_token": hf_token}' in src+++def test_a_full_fingerprint_pass_is_remembered_per_unchanged_file(monkeypatch, tmp_path):+ import os++ import core.inference.diffusion_compile_cache as cc+ import core.inference.diffusion_prequant as pq++ monkeypatch.setenv(cc._ENV_DIR, str(tmp_path / "cache"))+ monkeypatch.delenv(pq.FINGERPRINT_MODE_ENV, raising = False)+ ckpt_file = tmp_path / "w.safetensors"+ ckpt_file.write_bytes(b"weights")+ expected = {"a.weight": "x", "b.weight": "y"}+ meta = {"fingerprint": {"modules": expected}}+ calls: list = []++ def fingerprint(state_dict, *, select = None):+ calls.append(select)+ return {"modules": dict(state_dict)}++ monkeypatch.setattr(pq, "packed_weight_fingerprint", fingerprint)+ assert pq._verify_packed_fingerprint(expected, meta, path = ckpt_file)+ assert pq._verify_packed_fingerprint(expected, meta, path = ckpt_file)+ assert len(calls) == 1 # the second load of the unchanged file skips the md5 pass+ # A changed file (size / mtime) is checked in full again, and a mismatch is never remembered.+ ckpt_file.write_bytes(b"weights, rebuilt")+ os.utime(ckpt_file, ns = (1, 1))+ assert not pq._verify_packed_fingerprint(+ {"a.weight": "x", "b.weight": "z"}, meta, path = ckpt_file+ )+ assert not pq._verify_packed_fingerprint(+ {"a.weight": "x", "b.weight": "z"}, meta, path = ckpt_file+ )+ assert len(calls) == 3+ # Without a path (or outside full mode) nothing is remembered.+ assert pq._verify_packed_fingerprint(expected, meta)+ assert pq._verify_packed_fingerprint(expected, meta)+ assert len(calls) == 5diff --git a/studio/backend/tests/test_diffusion_zimage_fused.py b/studio/backend/tests/test_diffusion_zimage_fused.pyindex 7320ac0d93e..5a68f68d970 100644--- a/studio/backend/tests/test_diffusion_zimage_fused.py+++ b/studio/backend/tests/test_diffusion_zimage_fused.py@@ -64,6 +64,49 @@ def test_fuse_linears_plain_bf16_matches_and_shares_storage():)+class _Holder(torch.nn.Module):+ def __init__(self, parts):+ super().__init__()+ self.parts = torch.nn.ModuleList(parts)+++def test_fuse_linears_rotated_parts_share_one_rotation():+ from core.inference.diffusion_convrot import (+ build_convrot_hadamard,+ is_rotated_linear,+ rotate_convrot_activation,+ rotate_linears_,+ )++ torch.manual_seed(0)+ parts = [torch.nn.Linear(64, 8, bias = False) for _ in range(3)]+ holder = _Holder(parts)+ rotate_linears_(holder, [f"parts.{i}" for i in range(3)], 16)+ x = torch.randn(5, 64)+ fused = zf._fuse_linears(parts)+ assert is_rotated_linear(fused) and fused.convrot_groupsize == 16+ assert zf._share_storage(fused, parts)+ xr = rotate_convrot_activation(x, build_convrot_hadamard(16), 16)+ assert torch.equal(+ fused(x), torch.nn.functional.linear(xr, torch.cat([p.weight for p in parts]))+ )+ # the rotation acts on the shared input axis: the fused rows reproduce each rotated projection+ assert torch.allclose(fused(x), torch.cat([p(x) for p in parts], dim = -1), atol = 1e-5)+++def test_fuse_linears_refuses_parts_that_cannot_share_a_rotation():+ from core.inference.diffusion_convrot import rotate_linears_++ mixed = [torch.nn.Linear(64, 8, bias = False) for _ in range(3)]+ rotate_linears_(_Holder(mixed), ["parts.0"], 16)+ assert zf._fuse_linears(mixed) is None+ groups = [torch.nn.Linear(64, 8, bias = False) for _ in range(2)]+ holder = _Holder(groups)+ rotate_linears_(holder, ["parts.0"], 16)+ rotate_linears_(holder, ["parts.1"], 64)+ assert zf._fuse_linears(groups) is None++def _block(quant: str):torch.manual_seed(0)blk = (@@ -74,11 +117,28 @@ def _block(quant: str):)for p in blk.parameters():p.data.normal_(0, 0.05)- if quant == "int8":+ if quant == "int8_convrot":+ from core.inference.diffusion_convrot import rotate_linears_, warm_rotation_cache++ names = [+ n+ for n, m in blk.named_modules()+ if isinstance(m, torch.nn.Linear) and "adaLN" not in n and m.in_features % 64 == 0+ ]+ rotate_linears_(blk, names, 64)+ warm_rotation_cache(blk, "cuda", torch.bfloat16)+ if quant in ("int8", "int8_convrot"):from torchao.quantization import Int8DynamicActivationInt8WeightConfig, quantize_++ config = Int8DynamicActivationInt8WeightConfig(set_inductor_config = False)+ if quant == "int8_convrot":+ try: # the Int8Tensor the hosted checkpoints carry; torchao <= 0.17 defaults to the legacy tensor+ config = Int8DynamicActivationInt8WeightConfig(version = 2, set_inductor_config = False)+ except TypeError:+ passquantize_(blk,- Int8DynamicActivationInt8WeightConfig(set_inductor_config = False),+ config,filter_fn = lambda m, fqn: isinstance(m, torch.nn.Linear) and "adaLN" not in fqn,)return blk@@ -95,17 +155,42 @@ def _inputs(seq = 96):@needs_cuda[email protected]("quant", ["bf16", "int8"])[email protected]("quant", ["bf16", "int8", "int8_convrot"])def test_compiled_block_stays_within_the_compile_floor(quant):# Not bit-identical to stock compiled (fusion boundaries move bf16 roundings): bar = stock compile's distance from eager.- if quant == "int8":+ # int8_convrot: rotated q/k/v fuse into ONE rotated Linear (one rotation + one act quant), same floor.+ if quant != "bf16":pytest.importorskip("torchao.quantization")blk = _block(quant)- if quant == "int8" and type(blk.attention.to_q.weight).__name__ != "Int8Tensor":+ if quant == "int8_convrot":+ from core.inference.diffusion_convrot import is_rotated_linear+ assert is_rotated_linear(blk.attention.to_q)+ if quant != "bf16" and type(blk.attention.to_q.weight).__name__ != "Int8Tensor":pytest.skip("this torchao's int8 config builds the legacy tensor, which keeps the stock projections")x, mask, freqs, adaln = _inputs()+ if quant == "int8_convrot":+ # Under Studio's emulate_precision_casts the rotated, fused block (one rotation + act quant for q/k/v, the int8+ # projections without torchao 0.17's zero-point pass) stays as close to eager as the stock compile (torch 2.11:+ # both bit-identical to eager; torch 2.12's compiled act quant is not eager-exact on either side).+ from core.inference.diffusion_convrot import is_rotated_linear++ with torch.no_grad(), torch._inductor.config.patch(emulate_precision_casts = True):+ eager = blk(x, mask, freqs, adaln)+ torch._dynamo.reset()+ ref = torch.compile(blk)(x, mask, freqs, adaln)+ res = zf.install_modules(blk)+ assert res["fused_qkv"] == 1+ assert is_rotated_linear(zf._qkv_intact(blk.attention))+ torch._dynamo.reset()+ out = torch.compile(blk)(x, mask, freqs, adaln)+ floor = (ref != eager).sum().item()+ assert (out != eager).sum().item() <= 1.1 * floor + 16+ assert (out.float() - eager.float()).abs().max().item() <= 2 * (+ ref.float() - eager.float()+ ).abs().max().item() + 1e-6+ returnwith torch.no_grad():eager = blk(x, mask, freqs, adaln)torch._dynamo.reset()