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 diffusion: run an eager native int8 W8A8 linear as one compiled function (bit-identical, 1.33x streamed) (#15183)
Daniel Han34304b53dd92
diff --git a/studio/backend/core/inference/diffusion_native_quant.py b/studio/backend/core/inference/diffusion_native_quant.pyindex 6708c6919b0..ceb5487e1cf 100644--- a/studio/backend/core/inference/diffusion_native_quant.py+++ b/studio/backend/core/inference/diffusion_native_quant.py@@ -31,6 +31,10 @@ _INT8PACK_PROBED: dict = {}# torch._int_mm needs M > 16 and K, N multiples of 8._INT_MM_MIN_ROWS = 17_INT_MM_CHUNK_ELEMS = 1 << 25+# Compiled linear holds only the int32 accumulator (no fp32 temporaries), so 4x the eager chunk.+_INT_MM_FUSED_CHUNK_ELEMS = 1 << 27+# ``0`` keeps eager CUDA W8A8 kernels instead of one compiled function per linear.+NATIVE_INT8_FUSED_ENV = "UNSLOTH_NATIVE_INT8_FUSED"# fp8 codes a native fp8 layer may hold; e5m2 only from a checkpoint (the quantise path writes e4m3fn).NATIVE_FP8_FORMATS = ("float8_e4m3fn", "float8_e5m2")@@ -247,6 +251,84 @@ def _row_major_op() -> Any:return torch.ops.unsloth_studio.native_row_major+def int8_fused_disabled() -> bool:+ import os+ return os.environ.get(NATIVE_INT8_FUSED_ENV, "").strip().lower() in ("0", "false", "no", "off")+++def _w8a8_rows(x2: Any, rot_h: Any, weight_q: Any, weight_scale: Any, bias: Any) -> Any:+ """Eager ``_rotate`` + ``_int_mm_rows`` maths on tensors only, so offload hooks never invalidate the graph."""+ import torch++ if rot_h is not None:+ g = rot_h.shape[0]+ x2 = (x2.reshape(x2.shape[0], -1, g) @ rot_h.to(x2.dtype)).reshape(x2.shape)+ x_scale = torch.linalg.vector_norm(+ x2, ord = float("inf"), dim = 1, keepdim = True, dtype = torch.float32+ ).clamp(min = 1e-12)+ # fp64 reciprocal: matches eager CUDA bit-for-bit; Triton's fp32 reciprocal is approximate and drifts codes.+ x_scale = x_scale * (1.0 / 127.0)+ x_recip = (1.0 / x_scale.double()).float()+ xq = torch.mul(x2, x_recip).round().clamp(-127, 127).to(torch.int8)+ if rot_h is None:+ op = _FUSED_STATE.get("row_major")+ xq = op(xq) if op is not None else xq.contiguous()+ acc = torch._int_mm(xq, weight_q.t())+ out = torch.mul(acc, x_scale)+ w_scale = weight_scale.view(torch.float32)+ if bias is not None:+ out = torch.addcmul(bias.float(), out, w_scale)+ else:+ out = out * w_scale+ return out.to(x2.dtype)+++_FUSED_STATE: dict = {"fn": None, "failed": None}+++def _fused_w8a8() -> Optional[Callable[..., Any]]:+ """Compiled ``_w8a8_rows``, or None if disabled, no inductor runtime, ROCm, or already failed."""+ if _FUSED_STATE["failed"] is not None or int8_fused_disabled():+ return None+ fn = _FUSED_STATE["fn"]+ if fn is not None:+ return fn+ import torch++ from .rocm_bf16 import is_rocm_torch++ try:+ from .diffusion_speed import torch_compile_runtime_available+ runtime = torch_compile_runtime_available()+ except Exception: # noqa: BLE001 - unknown runtime: stay eager+ runtime = False+ if not runtime or is_rocm_torch(torch):+ _FUSED_STATE["failed"] = "no inductor runtime" if not runtime else "ROCm"+ return None+ # Registered in eager, before any trace reads the handle.+ _FUSED_STATE["row_major"] = _row_major_op()+ fn = torch.compile(_w8a8_rows, dynamic = True, fullgraph = True)+ _FUSED_STATE["fn"] = fn+ return fn+++def _fused_w8a8_failed(exc: BaseException) -> None:+ import logging++ _FUSED_STATE["failed"] = repr(exc)+ _FUSED_STATE["fn"] = None+ logging.getLogger(__name__).warning(+ "diffusion.native_quant: the compiled int8 W8A8 linear failed (%s); eager kernels from here on "+ "(set %s=0 to skip it)",+ exc,+ NATIVE_INT8_FUSED_ENV,+ )+++def fused_w8a8_state() -> dict:+ return {"calls": _FUSED_STATE.get("calls", 0), "failed": _FUSED_STATE["failed"]}++@lru_cache(maxsize = 1)def native_linear_class():"""``NativeWeightOnlyLinear``, defined on first use so this module imports torch-free."""@@ -419,6 +501,40 @@ def native_linear_class():)return out.reshape(*x.shape[:-1], self.out_features)+ def _forward_fused(self, x: Any) -> Any:+ """Chunked compiled forward; None = use eager kernels (also during CUDA graph capture)."""+ in_f = self.in_features+ rows = x.numel() // max(1, in_f)+ if not self._int_mm_ok(rows) or (+ x.is_cuda and torch.cuda.is_current_stream_capturing()+ ):+ return None+ fn = _fused_w8a8()+ if fn is None:+ return None+ # Detached: guards on a view's base / Parameter shape would recompile per layout / layer.+ x2 = x.reshape(-1, in_f).detach()+ rot_h = self.rot_h if self.rot_group else None+ bias = self.bias.detach() if self.bias is not None else None+ chunk = _INT_MM_FUSED_CHUNK_ELEMS // max(in_f, self.out_features)+ try:+ if rows <= chunk or chunk < 2 * _INT_MM_MIN_ROWS:+ out = fn(x2, rot_h, self.weight_q, self.weight_scale, bias)+ else:+ out = torch.cat(+ [+ fn(part.detach(), rot_h, self.weight_q, self.weight_scale, bias)+ for part in torch.tensor_split(x2, -(-rows // chunk))+ ]+ )+ except torch.cuda.OutOfMemoryError:+ raise+ except Exception as exc: # noqa: BLE001 - a compile failure falls back to the eager kernels+ _fused_w8a8_failed(exc)+ return None+ _FUSED_STATE["calls"] = _FUSED_STATE.get("calls", 0) + 1+ return out.reshape(*x.shape[:-1], self.out_features)+def _int8pack_scale(self, dtype: Any, device: Any) -> Any:"""Per-row scale in ``dtype`` if that cast is exact (cached), else None: keep dequantise."""key = (dtype, str(device))@@ -484,6 +600,10 @@ def native_linear_class():out = self._forward_int8pack(x)if out is not None:return out+ if self.act_int8 and x.is_cuda and not torch.compiler.is_compiling():+ out = self._forward_fused(x)+ if out is not None:+ return outif self.rot_group:x = self._rotate(x)if (diff --git a/studio/backend/tests/test_diffusion_native_quant_fused.py b/studio/backend/tests/test_diffusion_native_quant_fused.pynew file mode 100644index 00000000000..fa3f2a1eae2--- /dev/null+++ b/studio/backend/tests/test_diffusion_native_quant_fused.py@@ -0,0 +1,182 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Compiled W8A8 linear: gates, fallback, and bit-equality with the eager kernels."""++from __future__ import annotations++import pytest++torch = pytest.importorskip("torch")++import core.inference.diffusion_native_quant as nq++[email protected](autouse = True)+def fresh_state(monkeypatch):+ monkeypatch.setattr(nq, "_FUSED_STATE", {"fn": None, "failed": None})+ monkeypatch.delenv(nq.NATIVE_INT8_FUSED_ENV, raising = False)+++def _layer(+ rot = 256,+ bias = True,+ in_f = 512,+ out_f = 128,+):+ torch.manual_seed(0)+ lin = torch.nn.Linear(in_f, out_f, bias = bias).to(torch.bfloat16)+ return nq.native_linear_class()(lin, "int8", act_int8 = True, rot_group = rot)+++def _int_mm_on_cpu():+ try:+ torch._int_mm(torch.ones(32, 8, dtype = torch.int8), torch.ones(8, 8, dtype = torch.int8))+ return True+ except (RuntimeError, AttributeError, NotImplementedError):+ return False++[email protected]("value", ["0", "false", "off", "no"])+def test_kill_switch_disables_the_compiled_linear(monkeypatch, value):+ monkeypatch.setenv(nq.NATIVE_INT8_FUSED_ENV, value)+ assert nq.int8_fused_disabled()+ assert nq._fused_w8a8() is None+++def test_no_inductor_runtime_or_rocm_keeps_eager(monkeypatch):+ import core.inference.diffusion_speed as sp++ monkeypatch.setattr(sp, "torch_compile_runtime_available", lambda: False)+ assert nq._fused_w8a8() is None+ assert nq.fused_w8a8_state()["failed"] == "no inductor runtime"+ monkeypatch.setattr(nq, "_FUSED_STATE", {"fn": None, "failed": None})+ monkeypatch.setattr(sp, "torch_compile_runtime_available", lambda: True)+ monkeypatch.setattr(torch.version, "hip", "6.4", raising = False)+ assert nq._fused_w8a8() is None+ assert nq.fused_w8a8_state()["failed"] == "ROCm"+ # AMD SDK / Radeon wheels leave torch.version.hip unset and tag __version__ instead.+ monkeypatch.setattr(nq, "_FUSED_STATE", {"fn": None, "failed": None})+ monkeypatch.setattr(torch.version, "hip", None, raising = False)+ monkeypatch.setattr(torch, "__version__", "2.9.0+rocm7.0")+ assert nq._fused_w8a8() is None+ assert nq.fused_w8a8_state()["failed"] == "ROCm"+++def test_cpu_input_never_takes_the_compiled_linear(monkeypatch):+ layer = _layer()+ monkeypatch.setattr(+ layer, "_forward_fused", lambda x: pytest.fail("compiled linear on a CPU input")+ )+ layer(torch.randn(32, 512, dtype = torch.bfloat16))+++def test_too_few_rows_or_switched_off_returns_none(monkeypatch):+ layer = _layer()+ monkeypatch.setattr(nq, "_fused_w8a8", lambda: pytest.fail("no compile for a 16-row input"))+ assert layer._forward_fused(torch.randn(16, 512, dtype = torch.bfloat16)) is None+ monkeypatch.setattr(nq, "_fused_w8a8", lambda: None)+ assert layer._forward_fused(torch.randn(64, 512, dtype = torch.bfloat16)) is None+++def test_a_failing_compile_falls_back_once_and_stays_eager(monkeypatch):+ layer = _layer()++ def boom(*_a):+ raise RuntimeError("inductor exploded")++ nq._FUSED_STATE["fn"] = boom+ assert layer._forward_fused(torch.randn(64, 512, dtype = torch.bfloat16)) is None+ state = nq.fused_w8a8_state()+ assert "inductor exploded" in state["failed"]+ assert nq._fused_w8a8() is None+++def test_an_oom_propagates_and_keeps_the_compiled_linear(monkeypatch):+ layer = _layer()++ def oom(*_a):+ raise torch.cuda.OutOfMemoryError("CUDA out of memory")++ nq._FUSED_STATE["fn"] = oom+ with pytest.raises(torch.cuda.OutOfMemoryError):+ layer._forward_fused(torch.randn(64, 512, dtype = torch.bfloat16))+ assert nq.fused_w8a8_state()["failed"] is None+++def test_compiled_linear_gets_detached_non_parameter_inputs(monkeypatch):+ layer = _layer()+ seen = []++ def spy(x2, rot_h, wq, ws, bias):+ seen.append((x2._base, isinstance(bias, torch.nn.Parameter), rot_h is layer.rot_h))+ return (+ nq._w8a8_rows(x2, rot_h, wq, ws, bias)+ if _int_mm_on_cpu()+ else x2.new_zeros(x2.shape[0], 128)+ )++ nq._FUSED_STATE["fn"] = spy+ out = layer._forward_fused(torch.randn(2, 40, 512, dtype = torch.bfloat16))+ assert out.shape == (2, 40, 128)+ assert seen == [(None, False, True)]+ assert nq.fused_w8a8_state()["calls"] == 1+++def test_large_inputs_are_chunked_on_the_accumulator(monkeypatch):+ layer = _layer()+ monkeypatch.setattr(nq, "_INT_MM_FUSED_CHUNK_ELEMS", 512 * 40) # 40 rows per chunk+ rows = []++ def spy(x2, rot_h, wq, ws, bias):+ rows.append(x2.shape[0])+ return x2.new_zeros(x2.shape[0], 128)++ nq._FUSED_STATE["fn"] = spy+ assert layer._forward_fused(torch.randn(100, 512, dtype = torch.bfloat16)).shape == (100, 128)+ assert sum(rows) == 100 and max(rows) <= 40++[email protected](not _int_mm_on_cpu(), reason = "torch._int_mm has no CPU kernel in this build")[email protected]("rot", [256, 0])[email protected]("bias", [True, False])+def test_fused_maths_tracks_the_eager_kernels(rot, bias):+ # CPU eager divides, so only ulp-level agreement; the CUDA test checks bit-equality.+ layer = _layer(rot = rot, bias = bias)+ x = torch.randn(48, 512, dtype = torch.bfloat16)+ x_rot = layer._rotate(x) if rot else x+ ref = layer._int_mm_rows(x_rot).to(x.dtype)+ got = nq._w8a8_rows(+ x, layer.rot_h if rot else None, layer.weight_q, layer.weight_scale, layer.bias+ )+ assert got.dtype == torch.bfloat16 and got.shape == ref.shape+ assert ((got.float() - ref.float()).norm() / ref.float().norm()).item() < 2e-2++[email protected](not torch.cuda.is_available(), reason = "needs CUDA torch._int_mm and inductor")[email protected]("rot", [256, 0])+def test_cuda_compiled_linear_is_bit_identical_to_eager(monkeypatch, rot):+ torch.manual_seed(0)+ cls = nq.native_linear_class()+ layers = [+ cls(+ torch.nn.Linear(i, o, bias = b).to("cuda", torch.bfloat16),+ "int8",+ act_int8 = True,+ rot_group = rot,+ )+ for i, o, b in ((512, 1536, True), (512, 512, False), (1536, 512, True))+ ]+ torch._dynamo.reset()+ with torch.no_grad():+ for shape in ((1, 700), (2, 333), (4096,)):+ for layer in layers:+ x = torch.randn(*shape, layer.in_features, device = "cuda", dtype = torch.bfloat16) * 3+ monkeypatch.setenv(nq.NATIVE_INT8_FUSED_ENV, "0")+ ref = layer(x)+ monkeypatch.delenv(nq.NATIVE_INT8_FUSED_ENV)+ calls = nq.fused_w8a8_state()["calls"]+ got = layer(x)+ assert nq.fused_w8a8_state()["calls"] == calls + 1+ assert torch.equal(got, ref)+ assert nq.fused_w8a8_state()["failed"] is None