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: int8 activations on T4 for Qwen-Image (2.5x per step) (#12690)
Daniel Han7fce87bd5141
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 8cf0a47bd2c..6a25c0140af 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -8340,6 +8340,8 @@ class DiffusionBackend:from .diffusion_small_host import (cast_resident_,+ int8_act_device_ok,+ int8_act_family,mark,prepare_streamed_encoder_,quantize_int8_weight_,@@ -8363,11 +8365,18 @@ class DiffusionBackend:info["components"][name] = "converted"else:# pageable: pinning rounds blocks to powers of two (11.3 GB of FLUX.1 int8 held 18 GB pinned)+ act_int8 = int8_act_family(fam) and int8_act_device_ok(device)stats = quantize_int8_weight_(- module, compute_dtype = dtype, work_device = device, keep_device = "cpu"+ module,+ compute_dtype = dtype,+ work_device = device,+ keep_device = "cpu",+ act_int8 = act_int8,)info["components"][name] = (- f"int8 weights ({stats['int8_bytes'] >> 20} MiB, {stats['linears']} linears)"+ f"int8 weights ({stats['int8_bytes'] >> 20} MiB, {stats['linears']} linears"+ + (", int8 activations" if act_int8 else "")+ + ")")if load_token is not None:self._raise_if_load_cancelled(load_token)diff --git a/studio/backend/core/inference/diffusion_small_host.py b/studio/backend/core/inference/diffusion_small_host.pyindex 657e51bb496..ac7f207dd8f 100644--- a/studio/backend/core/inference/diffusion_small_host.py+++ b/studio/backend/core/inference/diffusion_small_host.py@@ -291,12 +291,70 @@ def torch_dtype_map(decision: SmallHostDecision, compute_dtype: Any) -> Any:return mapping+INT8_ACT_ENV = "UNSLOTH_DIFFUSION_SMALL_HOST_INT8_ACT"+# Measured on a T4 (LPIPS inside the fp32-vs-bf16 spread); qwen-image-edit shares the DiT but is unmeasured.+INT8_ACT_FAMILIES = frozenset({"qwen-image"})+# torch._int_mm: rows M > 16, K and N multiples of 8.+_INT8_ACT_MIN_ROWS = 17+_INT8_ACT_ALIGN = 8+_INT8_ACT_DEVICE_OK: dict[int, bool] = {}+_INT8_ACT_COUNTS = {"int8_act": 0, "dequant": 0}+++def int8_act_disabled() -> bool:+ return _env(INT8_ACT_ENV) in ("0", "off", "false", "no")+++def int8_act_family(fam: Any) -> bool:+ """Whether ``fam``'s int8-stored denoiser may run W8A8 (still gated per device and per call)."""+ if int8_act_disabled():+ return False+ name = str(getattr(fam, "name", fam) or "").strip().lower()+ return name in INT8_ACT_FAMILIES+++def int8_act_counts() -> dict[str, int]:+ return dict(_INT8_ACT_COUNTS)+++def int8_act_device_ok(device: Any) -> bool:+ """sm_75 CUDA only (fp32-promoted, int8 tensor cores; on sm_80+ bf16 eager W8A8 does not win; ROCm capabilities+ differ), and ``torch._int_mm`` must return the exact integer product there."""+ import torch++ try:+ dev = torch.device(device)+ if dev.type != "cuda" or getattr(torch.version, "hip", None):+ return False+ idx = dev.index if dev.index is not None else torch.cuda.current_device()+ except Exception: # noqa: BLE001+ return False+ hit = _INT8_ACT_DEVICE_OK.get(idx)+ if hit is not None:+ return hit+ ok = False+ try:+ if tuple(torch.cuda.get_device_capability(idx)) == (7, 5) and hasattr(torch, "_int_mm"):+ g = torch.Generator(device = "cpu").manual_seed(0)+ a = torch.randint(-127, 128, (32, 64), generator = g, dtype = torch.int8)+ b = torch.randint(-127, 128, (48, 64), generator = g, dtype = torch.int8)+ want = a.to(torch.int64) @ b.to(torch.int64).t()+ got = torch._int_mm(a.to(dev), b.to(dev).t())+ ok = bool(torch.equal(got.cpu().to(torch.int64), want))+ except Exception: # noqa: BLE001 - no usable int8 GEMM: keep the dequantised path+ ok = False+ _INT8_ACT_DEVICE_OK[idx] = ok+ return ok++def _int8_linear_class():import torchimport torch.nn.functional as Fclass Int8WeightLinear(torch.nn.Module):- """Linear with int8 per-output-channel weights, dequantised to the input dtype for each forward."""+ """Linear with int8 per-output-channel weights, dequantised to the input dtype for each forward.++ ``act_int8``: eligible float32 CUDA calls quantise activations per row and run ``torch._int_mm`` instead."""def __init__(self, qweight, scale, bias, in_features: int, out_features: int):super().__init__()@@ -305,8 +363,34 @@ def _int8_linear_class():self.qweight = torch.nn.Parameter(qweight, requires_grad = False)self.scale = torch.nn.Parameter(scale, requires_grad = False)self.bias = None if bias is None else torch.nn.Parameter(bias, requires_grad = False)+ self.act_int8 = False++ def _int8_act_ok(self, x) -> bool:+ if not self.act_int8 or x.dtype is not torch.float32 or not x.is_cuda:+ return False+ if self.in_features % _INT8_ACT_ALIGN or self.out_features % _INT8_ACT_ALIGN:+ return False+ if x.numel() // max(1, self.in_features) < _INT8_ACT_MIN_ROWS:+ return False+ return int8_act_device_ok(x.device)++ def _forward_int8_act(self, x):+ x2 = x.reshape(-1, self.in_features)+ xs = torch.linalg.vector_norm(x2, ord = float("inf"), dim = 1, keepdim = True)+ xs = xs.clamp_min_(1e-12).div_(127.0)+ xq = torch.div(x2, xs).round_().clamp_(-127, 127).to(torch.int8)+ acc = torch._int_mm(xq, self.qweight.t())+ y = torch.mul(acc, xs).mul_(self.scale.reshape(1, -1).to(torch.float32))+ if self.bias is not None:+ y.add_(self.bias.to(torch.float32))+ return y.reshape(*x.shape[:-1], self.out_features)def forward(self, x):+ if self._int8_act_ok(x):+ _INT8_ACT_COUNTS["int8_act"] += 1+ return self._forward_int8_act(x)+ if self.act_int8:+ _INT8_ACT_COUNTS["dequant"] += 1scale = self.scaleif scale.dtype == x.dtype:# int8 * float promotes: cast + scale in one pass, bit-identical (int8 -> fp16/fp32 is exact).@@ -337,9 +421,11 @@ def quantize_int8_weight_(compute_dtype: Any,work_device: Any,keep_device: Any = "cpu",+ act_int8: bool = False,) -> dict[str, int]:"""Replace every large ``nn.Linear`` with per-row int8 weights in place, one Linear at a time (quantised on- ``work_device``, stored on ``keep_device``); everything else casts to ``compute_dtype``."""+ ``work_device``, stored on ``keep_device``); everything else casts to ``compute_dtype``. ``act_int8`` lets the+ new Linears run W8A8 where ``Int8WeightLinear`` allows it."""import torchcls = int8_linear_class()@@ -365,6 +451,7 @@ def quantize_int8_weight_(lin.in_features,lin.out_features,)+ new.act_int8 = bool(act_int8)del w, q, scaleparent_name, _, attr = name.rpartition(".")parent = module.get_submodule(parent_name) if parent_name else modulediff --git a/studio/backend/tests/test_diffusion_small_host_int8_act.py b/studio/backend/tests/test_diffusion_small_host_int8_act.pynew file mode 100644index 00000000000..2f1b8b3e730--- /dev/null+++ b/studio/backend/tests/test_diffusion_small_host_int8_act.py@@ -0,0 +1,165 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""W8A8 for the small-host int8 denoiser on Turing (``Int8WeightLinear`` with ``act_int8``).++Qwen-Image on a T4 is promoted to float32 and stored as int8 weights; the float32 dequantised GEMM runs on SIMT+cores. With ``act_int8`` the Linear quantises its activation per row and runs ``torch._int_mm`` instead. CPU only:+the int8 GEMM is replaced by an exact integer reference where a CUDA kernel would run.+"""++from __future__ import annotations++import types++import pytest+import torch++import core.inference.diffusion_small_host as sh++[email protected](autouse = True)+def _clean(monkeypatch):+ monkeypatch.delenv(sh.INT8_ACT_ENV, raising = False)+ sh._INT8_ACT_DEVICE_OK.clear()+ yield+ sh._INT8_ACT_DEVICE_OK.clear()+++def _exact_int_mm(a, b):+ return (a.to(torch.int64) @ b.to(torch.int64)).to(torch.int32)+++def _layer(+ k = 256,+ n = 128,+ bias = True,+ act_int8 = True,+ seed = 0,+):+ torch.manual_seed(seed)+ lin = torch.nn.Linear(k, n, bias = bias)+ model = torch.nn.Sequential(lin)+ sh._INT8_MIN_ELEMENTS, old = 1, sh._INT8_MIN_ELEMENTS+ try:+ sh.quantize_int8_weight_(+ model, compute_dtype = torch.float32, work_device = "cpu", act_int8 = act_int8+ )+ finally:+ sh._INT8_MIN_ELEMENTS = old+ return model[0], lin+++def test_family_allowlist_and_kill_switch(monkeypatch):+ assert sh.int8_act_family(types.SimpleNamespace(name = "qwen-image"))+ assert sh.int8_act_family(types.SimpleNamespace(name = "Qwen-Image"))+ assert sh.int8_act_family("qwen-image")+ for other in ("qwen-image-edit", "flux.1", "z-image", "hidream-i1", "qwen-image-2.1", None):+ assert not sh.int8_act_family(types.SimpleNamespace(name = other))+ monkeypatch.setenv(sh.INT8_ACT_ENV, "0")+ assert not sh.int8_act_family(types.SimpleNamespace(name = "qwen-image"))+++def test_quantize_sets_the_flag_only_when_asked():+ on, _ = _layer(act_int8 = True)+ off, _ = _layer(act_int8 = False)+ assert isinstance(on, sh.int8_linear_class()) and on.act_int8 is True+ assert off.act_int8 is False+++def _fake_cuda(+ monkeypatch,+ cap = (7, 5),+ int_mm = _exact_int_mm,+ hip = None,+):+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda idx = None: cap)+ monkeypatch.setattr(torch.cuda, "current_device", lambda: 0)+ monkeypatch.setattr(torch.version, "hip", hip, raising = False)+ monkeypatch.setattr(torch, "_int_mm", int_mm, raising = False)+ real_to = torch.Tensor.to++ def to(self, *a, **k): # the probe moves its operands to "cuda"; keep them on the CPU+ if a and isinstance(a[0], torch.device) and a[0].type == "cuda":+ return self+ return real_to(self, *a, **k)++ monkeypatch.setattr(torch.Tensor, "to", to)+++def test_device_gate_turing_only(monkeypatch):+ _fake_cuda(monkeypatch, cap = (7, 5))+ assert sh.int8_act_device_ok("cuda")+ for cap in ((8, 0), (8, 6), (8, 9), (9, 0), (10, 0), (12, 0), (7, 0), (6, 1)):+ sh._INT8_ACT_DEVICE_OK.clear()+ _fake_cuda(monkeypatch, cap = cap)+ assert not sh.int8_act_device_ok("cuda"), cap+++def test_device_gate_refuses_rocm_cpu_and_a_wrong_or_failing_kernel(monkeypatch):+ _fake_cuda(monkeypatch, hip = "6.2")+ assert not sh.int8_act_device_ok("cuda")+ sh._INT8_ACT_DEVICE_OK.clear()+ assert not sh.int8_act_device_ok("cpu")++ def wrong(a, b):+ return _exact_int_mm(a, b) + 1++ def boom(a, b):+ raise RuntimeError("CUBLAS_STATUS_NOT_SUPPORTED")++ for bad in (wrong, boom):+ sh._INT8_ACT_DEVICE_OK.clear()+ _fake_cuda(monkeypatch, int_mm = bad)+ assert not sh.int8_act_device_ok("cuda")+++def test_int8_act_math_matches_the_reference_and_the_dense_layer(monkeypatch):+ monkeypatch.setattr(torch, "_int_mm", _exact_int_mm, raising = False)+ layer, lin = _layer(k = 256, n = 128)+ x = torch.randn(4, 9, 256)+ y = layer._forward_int8_act(x)+ assert y.shape == (4, 9, 128) and y.dtype == torch.float32+ # reference: per-row symmetric absmax, round half to even, int32 product, scales in float32+ x2 = x.reshape(-1, 256)+ xs = x2.abs().amax(1, keepdim = True).clamp_min(1e-12) / 127.0+ xq = torch.round(x2 / xs).clamp(-127, 127).to(torch.int8)+ acc = _exact_int_mm(xq, layer.qweight.t())+ want = (acc.float() * xs) * layer.scale.reshape(1, -1).float() + layer.bias.float()+ assert torch.allclose(y.reshape(-1, 128), want, rtol = 1e-6, atol = 1e-6)+ dense = lin(x)+ rel = (y - dense).norm() / dense.norm()+ assert rel < 0.02, rel+++def test_forward_routes_by_dtype_rows_alignment_and_device(monkeypatch):+ calls = []+ layer, _ = _layer(k = 256, n = 128)+ monkeypatch.setattr(sh, "int8_act_device_ok", lambda dev: True)+ monkeypatch.setattr(+ type(layer), "_forward_int8_act", lambda self, x: calls.append(x.shape) or torch.zeros(())+ )+ cuda_x = types.SimpleNamespace(+ dtype = torch.float32, is_cuda = True, device = "cuda", numel = lambda: 17 * 256+ )+ assert layer._int8_act_ok(cuda_x)+ assert not layer._int8_act_ok(+ types.SimpleNamespace(**{**cuda_x.__dict__, "dtype": torch.float16})+ )+ assert not layer._int8_act_ok(+ types.SimpleNamespace(**{**cuda_x.__dict__, "numel": lambda: 16 * 256})+ )+ assert not layer._int8_act_ok(types.SimpleNamespace(**{**cuda_x.__dict__, "is_cuda": False}))+ layer.act_int8 = False+ assert not layer._int8_act_ok(cuda_x)+ layer.act_int8 = True+ layer.out_features = 129 # unaligned N+ assert not layer._int8_act_ok(cuda_x)+ layer.out_features = 128+ monkeypatch.setattr(sh, "int8_act_device_ok", lambda dev: False)+ assert not layer._int8_act_ok(cuda_x)+ # a CPU float32 call takes the dequantised path, bit-identical to a layer without the flag+ x = torch.randn(32, 256)+ off, _ = _layer(k = 256, n = 128, act_int8 = False)+ assert torch.equal(layer(x), off(x))+ assert calls == []