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 weight-only transformer quant on Apple Silicon through the Metal int8 kernel (#13344)
Daniel Hanfb0c987df0f6
diff --git a/studio/backend/core/inference/diffusion_native_quant.py b/studio/backend/core/inference/diffusion_native_quant.pyindex 8bd1f7e172b..b1e656485c4 100644--- a/studio/backend/core/inference/diffusion_native_quant.py+++ b/studio/backend/core/inference/diffusion_native_quant.py@@ -16,6 +16,18 @@ NATIVE_FP8 = "fp8"_QMAX = {NATIVE_INT8: 127.0, NATIVE_FP8: 448.0}NATIVE_INT8_ACT_ENV = "UNSLOTH_NATIVE_INT8_ACT"NATIVE_INT8_ROT_ENV = "UNSLOTH_NATIVE_INT8_ROT"+# Apple Silicon int8 weight-only via the Metal ``_weight_int8pack_mm`` kernel. Unset: a load-time probe decides;+# ``0`` keeps the dequantise path; ``1`` takes the kernel without probing.+NATIVE_MPS_INT8PACK_ENV = "UNSLOTH_DIFFUSION_MPS_INT8PACK"+# The Metal kernel asserts N % 32 == 0 and K % 32 == 0.+_INT8PACK_ALIGN = 32+# The kernel runs near fp32 GEMM speed and is not bit-reproducible run to run, so it is taken only where it beats the+# chip's own bf16 GEMM by this much (M1: about 1.3x; M3 parity; M5 4x behind, as its 16-bit GEMM uses matrix units).+_INT8PACK_MIN_SPEEDUP = 1.10+_INT8PACK_PROBE_ROWS = 1024+# (dtype, in_features, out_features) of the probed layer -> verdict for this process (one chip per process). Each+# quantised transformer's layers carry their own verdict, so a later model with other shapes is probed afresh.+_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@@ -31,6 +43,144 @@ def int8_act_disabled() -> bool:return os.environ.get(NATIVE_INT8_ACT_ENV, "").strip() == "0"+def mps_int8pack_disabled() -> bool:+ import os+ return os.environ.get(NATIVE_MPS_INT8PACK_ENV, "").strip().lower() in (+ "0",+ "off",+ "false",+ "no",+ )+++def mps_int8pack_forced() -> bool:+ import os+ return os.environ.get(NATIVE_MPS_INT8PACK_ENV, "").strip().lower() in ("1", "on", "true", "yes")+++def mps_int8pack_selected(dtype: Any, layer: Any = None) -> bool:+ """Whether ``dtype`` forwards of ``layer`` may take the Metal kernel: the env override, else the verdict its+ transformer's probe stamped on it (no probe yet = dequantise, which is deterministic). Without ``layer``: whether+ any probe this process chose the kernel for ``dtype``."""+ if mps_int8pack_disabled():+ return False+ if mps_int8pack_forced():+ return True+ if layer is not None:+ return bool(getattr(layer, "_int8pack_verdict", {}).get(dtype, False))+ return any(v for (d, _, _), v in _INT8PACK_PROBED.items() if d == dtype)+++def _median_call_s(+ fn: Callable[[], Any],+ sync: Callable[[], None],+ reps: int = 5,+) -> float:+ import time++ times = []+ for _ in range(reps):+ sync()+ t0 = time.perf_counter()+ fn()+ sync()+ times.append(time.perf_counter() - t0)+ times.sort()+ return times[len(times) // 2]+++def _bench_int8pack_vs_dense(layer: Any, dtype: Any, device: Any) -> tuple:+ """(kernel s, dense ``dtype`` F.linear s) per call on ``layer``'s real shape, arms interleaved over 3 rounds."""+ import torch++ w_q = layer.weight_q.detach().to(device)+ scale = layer.weight_scale.view(torch.float32).to(device).to(dtype).contiguous()+ w = (w_q.to(dtype) * scale.unsqueeze(1)).contiguous()+ x = torch.randn(_INT8PACK_PROBE_ROWS, layer.in_features, dtype = dtype, device = device)+ sync = torch.mps.synchronize if device.type == "mps" else (lambda: None)+ kernel = lambda: torch._weight_int8pack_mm(x, w_q, scale)+ dense = lambda: torch.nn.functional.linear(x, w)+ kernel()+ dense()+ k_s, d_s = [], []+ for _ in range(3):+ k_s.append(_median_call_s(kernel, sync))+ d_s.append(_median_call_s(dense, sync))+ k_s.sort()+ d_s.sort()+ return k_s[1], d_s[1]+++def probe_mps_int8pack(+ module: Any,+ dtype: Any,+ *,+ device: Any = "mps",+ logger: Any = None,+) -> bool:+ """Time the Metal kernel against a dense ``dtype`` GEMM on ``module``'s largest kernel-eligible layer and stamp+ the verdict on every eligible layer of ``module``. Verdicts are cached per (dtype, probed shape), so another model+ with the same largest layer reuses it and one with a different shape is probed. The env override skips the probe."""+ import torch++ if mps_int8pack_disabled() or mps_int8pack_forced():+ return mps_int8pack_selected(dtype)+ cls = native_linear_class()+ layers = [+ m+ for m in module.modules()+ if isinstance(m, cls) and m._int8pack_layer_ok(dtype, probe = True)+ ]+ if not layers:+ return False+ layer = max(layers, key = lambda m: m.in_features * m.out_features)+ key = (dtype, layer.in_features, layer.out_features)++ def stamp(verdict: bool) -> bool:+ for m in layers:+ m._int8pack_verdict = {**getattr(m, "_int8pack_verdict", {}), dtype: verdict}+ return verdict++ if key in _INT8PACK_PROBED:+ return stamp(_INT8PACK_PROBED[key])+ try:+ kernel_s, dense_s = _bench_int8pack_vs_dense(layer, dtype, torch.device(device))+ except Exception as exc: # noqa: BLE001 -- a failed probe keeps the dequantise path+ if logger is not None:+ logger.info("diffusion.native_quant: int8pack probe failed, dequantising: %s", exc)+ _INT8PACK_PROBED[key] = False+ return stamp(False)+ speedup = dense_s / max(kernel_s, 1e-9)+ verdict = speedup >= _INT8PACK_MIN_SPEEDUP+ _INT8PACK_PROBED[key] = verdict+ stamp(verdict)+ if logger is not None:+ logger.info(+ "diffusion.native_quant: int8pack probe %dx%dx%d: kernel %.3f ms, dense %s %.3f ms (%.2fx) -> %s",+ _INT8PACK_PROBE_ROWS,+ layer.in_features,+ layer.out_features,+ kernel_s * 1e3,+ str(dtype).replace("torch.", ""),+ dense_s * 1e3,+ speedup,+ "Metal int8 kernel" if verdict else "dequantise",+ )+ return verdict+++def snap_scale_up(scale: Any, dtype: Any) -> Any:+ """``scale`` rounded up to a ``dtype``-exact fp32 value: the Metal kernel takes ``dtype`` scales, so a call-time+ cast would add per-row gain error (up to 2**-9 in bf16); rounding up never clips a code."""+ import torch++ # nextafter is not implemented on every backend.+ host = scale.detach().to("cpu", torch.float32)+ cast = host.to(dtype)+ up = torch.nextafter(cast, torch.full_like(cast, float("inf")))+ return torch.where(cast.float() < host, up, cast).float().to(scale.device)++def int8_rotation_group() -> int:import os@@ -90,11 +240,12 @@ def native_linear_class():rot_group: int = 0,codes: Any = None,scale: Any = None,+ scale_dtype: Any = None,):"""``codes`` / ``scale``: int8 (or, for the fp8 scheme, float8_e4m3fn) codes [out, in] and per-rowscales made elsewhere, stored as given (``linear`` then supplies only the shapes, dtype and bias).With ``rot_group`` int8 codes are already ConvRot-rotated, so the rotation is installed whether or- not activations go int8."""+ not activations go int8. ``scale_dtype``: snap int8 scales exact in that dtype (``snap_scale_up``)."""super().__init__()if scheme not in _QMAX:raise ValueError(f"unsupported native scheme {scheme!r}")@@ -144,6 +295,8 @@ def native_linear_class():)self.register_buffer("rot_h", h.to(self.compute_dtype), persistent = False)scale = w.abs().amax(dim = 1, keepdim = True).clamp(min = 1e-12) / _QMAX[scheme]+ if scheme == NATIVE_INT8 and scale_dtype is not None:+ scale = snap_scale_up(scale, scale_dtype)if scheme == NATIVE_INT8:wq = (w / scale).round_().clamp_(-127, 127).to(torch.int8)else:@@ -157,6 +310,7 @@ def native_linear_class():self.bias = linear.bias# 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 None+ self._int8pack_scales: dict = {}def _stored_weight(self, dtype: Any) -> Any:wq = (@@ -232,7 +386,71 @@ def native_linear_class():)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))+ # Keyed on the buffer's storage and version so load_state_dict / copy_ into it is never served stale.+ stamp = (self.weight_scale.data_ptr(), self.weight_scale._version)+ hit = self._int8pack_scales.get(key)+ if hit is None or hit[0] != stamp:+ scale = self.weight_scale.view(torch.float32)+ cast = scale.to(dtype)+ exact = bool(torch.equal(cast.float(), scale))+ hit = (stamp, cast.contiguous() if exact else None)+ self._int8pack_scales[key] = hit+ return hit[1]++ def _int8pack_layer_ok(+ self,+ dtype: Any,+ probe: bool = False,+ ) -> bool:+ """``probe``: the layer's shape and codes suit the kernel, whatever the probe decided."""+ return (+ self.scheme == NATIVE_INT8+ and not self.act_int8+ and not self.rot_group+ and dtype in (torch.bfloat16, torch.float16, torch.float32)+ and self.in_features % _INT8PACK_ALIGN == 0+ and self.out_features % _INT8PACK_ALIGN == 0+ and hasattr(torch, "_weight_int8pack_mm")+ and (+ self._int8pack_scale(dtype, self.weight_q.device) is not None+ if probe+ else mps_int8pack_selected(dtype, self)+ )+ )++ def _int8pack_ok(self, x: Any) -> bool:+ return x.device.type == "mps" and x.numel() > 0 and self._int8pack_layer_ok(x.dtype)++ def int8pack_engaged(self, dtype: Any) -> bool:+ """Whether a ``dtype`` forward on the stored device takes the Metal int8 kernel."""+ device = self.weight_q.device+ return (+ device.type == "mps"+ and self._int8pack_layer_ok(dtype)+ and self._int8pack_scale(dtype, device) is not None+ )++ def _forward_int8pack(self, x: Any) -> Any:+ """None = take the dequantise path."""+ scale = self._int8pack_scale(x.dtype, x.device)+ if scale is None:+ return None+ x2 = x.reshape(-1, self.in_features)+ if not x2.is_contiguous():+ x2 = x2.contiguous()+ out = torch._weight_int8pack_mm(x2, self.weight_q, scale)+ if self.bias is not None:+ out = out + self.bias.to(out.dtype)+ return out.reshape(*x.shape[:-1], self.out_features)+def forward(self, x: Any) -> Any:+ if self._int8pack_ok(x):+ out = self._forward_int8pack(x)+ if out is not None:+ return outif self.rot_group:x = self._rotate(x)if (@@ -271,6 +489,7 @@ def apply_native_weight_quant(filter_fn: Callable[[Any, str], bool],act_int8: bool,logger: Any = None,+ scale_dtype: Any = None,) -> int:"""Swap every Linear ``filter_fn`` keeps for a native weight-only twin; returns layers swapped. One layerat a time; a failure part-way leaves a partial conversion the caller must refuse."""@@ -283,7 +502,15 @@ def apply_native_weight_quant(parent_name, _, leaf = name.rpartition(".")parent = transformer.get_submodule(parent_name) if parent_name else transformersetattr(- parent, leaf, cls(getattr(parent, leaf), scheme, act_int8 = act_int8, rot_group = rot_group)+ parent,+ leaf,+ cls(+ getattr(parent, leaf),+ scheme,+ act_int8 = act_int8,+ rot_group = rot_group,+ scale_dtype = scale_dtype if scheme == NATIVE_INT8 and not act_int8 else None,+ ),)if logger is not None:logger.info(@@ -326,6 +553,19 @@ def native_quant_signature(module: Any) -> Optional[str]:return f"{layer.scheme}-w8a8" + (f"-rot{rot}" if rot else "")+def _int8pack_reported(layer: Any) -> bool:+ engaged = getattr(layer, "int8pack_engaged", None)+ if engaged is None or getattr(getattr(layer, "weight_q", None), "device", None) is None:+ return False+ import torch++ bias = getattr(layer, "bias", None)+ try:+ return bool(engaged(bias.dtype if bias is not None else torch.bfloat16))+ except Exception: # noqa: BLE001 -- a status line must not fail the load+ return False++def native_quant_reason(module: Any, scheme: str) -> str:layer = _first_native_linear(module)if layer is not None and getattr(layer, "act_int8", False):@@ -335,6 +575,12 @@ def native_quant_reason(module: Any, scheme: str) -> str:+ (f" with a g{rot} ConvRot rotation" if rot else "")+ " (torchao-free; plain buffers, so the offload hooks can move it)")+ if layer is not None and _int8pack_reported(layer):+ return (+ f"weight-only: {scheme} weights through the Apple Silicon int8 kernel, which measured faster than "+ "bf16 here (torchao-free; half the weight memory; not bit-reproducible run to run, "+ f"{NATIVE_MPS_INT8PACK_ENV}=0 for repeatable images)"+ )return (f"weight-only: {scheme} weights, bf16 compute ""(torchao-free, a memory saving rather than a speed-up)"diff --git a/studio/backend/core/inference/diffusion_transformer_quant.py b/studio/backend/core/inference/diffusion_transformer_quant.pyindex b9e24287f54..eb92dd9a75b 100644--- a/studio/backend/core/inference/diffusion_transformer_quant.py+++ b/studio/backend/core/inference/diffusion_transformer_quant.py@@ -897,10 +897,23 @@ def dense_transformer_unsupported_reason(target: Any) -> str:NATIVE_QUANT_SCHEMES = (TQ_INT8, TQ_FP8)+def _mps_bf16(target: Any) -> bool:+ if getattr(target, "device", None) != "mps":+ return False+ try:+ import torch+ return getattr(target, "dtype", None) is torch.bfloat16+ except Exception:+ return False++def native_quant_host(target: Any) -> bool:"""Whether ``target`` is a bf16 GPU whose torchao path is closed for a platform reason: a ROCm torch- (the NVIDIA-shaped capability ladder misclassifies it, and gfx1151 refuses fp8 ``_scaled_mm``) or the- Windows-ROCm torchao stub. False on every NVIDIA, MPS, XPU and CPU host, which keep the torchao path."""+ (the NVIDIA-shaped capability ladder misclassifies it, and gfx1151 refuses fp8 ``_scaled_mm``), the+ Windows-ROCm torchao stub, or Apple Silicon MPS (no ``_int_mm`` and no fp8; int8 weight-only runs on the+ Metal ``_weight_int8pack_mm`` kernel). False on every NVIDIA, XPU and CPU host, which keep the torchao path."""+ if _mps_bf16(target):+ return Trueif getattr(target, "device", None) != "cuda":return Falseif not (torch_is_rocm() or is_stubbed("torchao")):@@ -942,12 +955,18 @@ def native_quant_scheme(offload and scheme in NATIVE_OFFLOAD_SCHEMES and native_offload_host(target)):return None+ # MPS has no float8 storage.+ if _mps_bf16(target) and scheme != TQ_INT8:+ return Noneif _family_denied(family, scheme):return Nonereturn schemedef native_int8_act(target: Any) -> bool:+ # MPS has no ``_int_mm``: W8A8 would only add the activation quant.+ if _mps_bf16(target):+ return Falseif native_quant_host(target):return int8_act_requested()return not int8_act_disabled()@@ -1808,7 +1827,8 @@ def quantize_transformer("""Quantise ``pipe.transformer`` in place, returning the scheme or None (GGUF); ``base_repo`` picks the NVFP4 policy."""native = native_quant_scheme(target, mode, family = family, offload = offload)if native is not None:- if act_int8 is None:+ mps = _mps_bf16(target)+ if act_int8 is None or mps:act_int8 = native_int8_act(target)return _quantize_native(pipe,@@ -1817,6 +1837,7 @@ def quantize_transformer(min_features = min_features,act_int8 = bool(act_int8) and native == TQ_INT8,logger = logger,+ scale_dtype = getattr(target, "dtype", None) if mps else None,)scheme = select_transformer_quant_scheme(target, mode, family = family, base_repo = base_repo)if scheme is None:@@ -1884,7 +1905,14 @@ def quantize_transformer(def _quantize_native(- pipe: Any, scheme: str, *, family: Optional[str], min_features: int, act_int8: bool, logger: Any+ pipe: Any,+ scheme: str,+ *,+ family: Optional[str],+ min_features: int,+ act_int8: bool,+ logger: Any,+ scale_dtype: Any = None,) -> Optional[str]:transformer = getattr(pipe, "transformer", None)if transformer is None:@@ -1899,9 +1927,19 @@ def _quantize_native(require_bf16 = True,)if not apply_native_weight_quant(- transformer, scheme, filter_fn = filter_fn, act_int8 = act_int8, logger = logger+ transformer,+ scheme,+ filter_fn = filter_fn,+ act_int8 = act_int8,+ logger = logger,+ scale_dtype = scale_dtype,):return None+ if scale_dtype is not None:+ from .diffusion_native_quant import probe_mps_int8pack++ # Timed on this chip, not assumed from the device type.+ probe_mps_int8pack(transformer, scale_dtype, logger = logger)try:transformer._unsloth_runtime_quant = schemeexcept Exception: # noqa: BLE001 - marker is best-effortdiff --git a/studio/backend/tests/test_diffusion_native_quant.py b/studio/backend/tests/test_diffusion_native_quant.pyindex 2ff27ecdfdb..2812df5a681 100644--- a/studio/backend/tests/test_diffusion_native_quant.py+++ b/studio/backend/tests/test_diffusion_native_quant.py@@ -92,7 +92,6 @@ def test_auto_and_other_schemes_never_go_native(rocm, scheme):"target",[_target(device = "cpu"),- _target(device = "mps"),_target(device = "xpu"),_target(dtype = torch.float16),_target(dtype = torch.float32),@@ -103,7 +102,7 @@ def test_non_cuda_or_non_bf16_is_never_native_even_on_rocm(rocm, target):assert tq.native_quant_scheme(target, "int8") is None[email protected]("device", ["cuda", "cpu", "mps", "xpu"])[email protected]("device", ["cuda", "cpu", "xpu"])def test_nvidia_and_other_hosts_are_never_native_without_offload(nvidia, device):assert not tq.native_quant_host(_target(device = device))for scheme in ("int8", "fp8", "nvfp4", "mxfp8", "auto"):@@ -135,7 +134,6 @@ def test_nvidia_takes_native_int8_only_under_offload(nvidia, scheme, offload, ex"target",[_target(device = "cpu"),- _target(device = "mps"),_target(device = "xpu"),_target(dtype = torch.float16),_target(dtype = torch.float32),diff --git a/studio/backend/tests/test_diffusion_native_quant_mps.py b/studio/backend/tests/test_diffusion_native_quant_mps.pynew file mode 100644index 00000000000..6fc49129fd5--- /dev/null+++ b/studio/backend/tests/test_diffusion_native_quant_mps.py@@ -0,0 +1,425 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Apple Silicon int8 weight-only; kernel math checked on CPU, dispatch tests need real MPS."""++from __future__ import annotations++import sys+import types++import pytest++torch = pytest.importorskip("torch")++import core.inference.diffusion_native_quant as nq+import core.inference.diffusion_transformer_quant as tq++_MPS = bool(getattr(torch.backends, "mps", None) and torch.backends.mps.is_available())+_HAS_OP = hasattr(torch, "_weight_int8pack_mm")+++def _mps_target(dtype = None):+ return types.SimpleNamespace(device = "mps", dtype = torch.bfloat16 if dtype is None else dtype)+++class _Toy(torch.nn.Module):+ def __init__(self, dim = 128):+ super().__init__()+ self.to_q = torch.nn.Linear(dim, dim)+ self.ff = torch.nn.Linear(dim, 2 * dim, bias = False)+ self.out = torch.nn.Linear(2 * dim, dim)++ def forward(self, x):+ return x + self.out(torch.nn.functional.gelu(self.ff(self.to_q(x))))+++def _block_torchao(monkeypatch):+ monkeypatch.setitem(sys.modules, "torchao", None)+ monkeypatch.setitem(sys.modules, "torchao.quantization", None)++[email protected]("scheme", ["int8", "INT8", " int8 "])+def test_mps_bf16_takes_explicit_int8(scheme):+ assert tq.native_quant_host(_mps_target())+ assert tq.native_quant_scheme(_mps_target(), scheme) == "int8"+ assert tq.native_quant_scheme(_mps_target(), scheme, offload = True) == "int8"++[email protected]("scheme", [None, "auto", "none", "off", "fp8", "mxfp8"])+def test_mps_refuses_everything_but_int8(scheme):+ # ``auto`` stays dense until measured on real Apple Silicon.+ assert tq.native_quant_scheme(_mps_target(), scheme) is None++[email protected]("dtype", ["float16", "float32"])+def test_mps_without_bf16_is_not_native(dtype):+ target = _mps_target(getattr(torch, dtype))+ assert not tq.native_quant_host(target)+ assert tq.native_quant_scheme(target, "int8") is None+++def test_mps_never_takes_int8_activations(monkeypatch):+ monkeypatch.setenv(nq.NATIVE_INT8_ACT_ENV, "1")+ assert tq.native_int8_act(_mps_target()) is False+++def test_mps_family_deny_list_still_applies(monkeypatch):+ monkeypatch.setitem(tq._FAMILY_SCHEME_DENY, "z-image", frozenset({tq.TQ_INT8}))+ assert tq.native_quant_scheme(_mps_target(), "int8", family = "z-image") is None+++def test_snap_scale_up_is_exact_in_the_dtype_and_never_clips():+ torch.manual_seed(0)+ scale = torch.rand(4096) * 0.05 + 1e-6+ for dtype in (torch.bfloat16, torch.float16):+ snapped = nq.snap_scale_up(scale, dtype)+ assert snapped.dtype == torch.float32+ assert torch.equal(snapped.to(dtype).float(), snapped)+ assert bool((snapped >= scale).all())+ assert float(((snapped - scale) / scale).max()) <= 2.0**-7+++def test_quantize_transformer_on_mps_snaps_scales_and_skips_w8a8(monkeypatch):+ _block_torchao(monkeypatch)+ monkeypatch.setenv(nq.NATIVE_INT8_ACT_ENV, "1")+ torch.manual_seed(0)+ model = _Toy().to(torch.bfloat16)+ x = torch.randn(5, 128, dtype = torch.bfloat16)+ with torch.no_grad():+ ref = model(x).float()+ pipe = types.SimpleNamespace(transformer = model)+ # act_int8 = True is overridden on MPS.+ got = tq.quantize_transformer(pipe, _mps_target(), mode = "int8", min_features = 64, act_int8 = True)+ assert got == "int8"+ layers = [m for m in model.modules() if nq.is_native_linear(m)]+ assert len(layers) == 3+ for layer in layers:+ assert not layer.act_int8 and layer.rot_group == 0+ scale = layer.weight_scale.view(torch.float32)+ assert torch.equal(scale.to(torch.bfloat16).float(), scale)+ assert int(layer.weight_q.abs().max()) <= 127+ with torch.no_grad():+ out = model(x).float()+ assert ((out - ref).norm() / ref.norm()).item() < 0.05+++def test_other_hosts_keep_unsnapped_scales():+ torch.manual_seed(0)+ lin = torch.nn.Linear(128, 64).to(torch.bfloat16)+ layer = nq.native_linear_class()(lin, "int8")+ scale = layer.weight_scale.view(torch.float32)+ expect = lin.weight.float().abs().amax(dim = 1).clamp(min = 1e-12) / 127.0+ assert torch.equal(scale, expect)+++def _layer(+ n_in = 128,+ n_out = 64,+ bias = True,+ dtype = torch.bfloat16,+):+ torch.manual_seed(0)+ lin = torch.nn.Linear(n_in, n_out, bias = bias).to(dtype)+ return lin, nq.native_linear_class()(lin, "int8", scale_dtype = dtype)++[email protected](not _HAS_OP, reason = "torch has no _weight_int8pack_mm")[email protected]("dtype", [torch.bfloat16, torch.float32])+def test_int8pack_math_matches_the_dequantised_layer_on_cpu(dtype):+ _, layer = _layer(dtype = dtype)+ x = torch.randn(2, 7, 128, dtype = dtype)+ try:+ got = layer._forward_int8pack(x)+ except (RuntimeError, NotImplementedError) as exc:+ pytest.skip(f"no CPU int8pack kernel for {dtype}: {exc}")+ assert got is not None and got.shape == (2, 7, 64) and got.dtype == dtype+ ref = torch.nn.functional.linear(+ x.float(), layer.dequantized_weight(torch.float32), layer.bias.float()+ )+ assert ((got.float() - ref).norm() / ref.norm()).item() < 1e-2+++def test_inexact_scales_decline_the_kernel():+ # A silent cast of non-bf16-exact checkpoint scales would bias every row.+ lin = torch.nn.Linear(64, 32).to(torch.bfloat16)+ codes = torch.randint(-127, 128, (32, 64), dtype = torch.int8)+ scale = torch.full((32,), 1.0 + 2.0**-12)+ layer = nq.native_linear_class()(lin, "int8", codes = codes, scale = scale)+ assert layer._int8pack_scale(torch.bfloat16, "cpu") is None+ assert layer._forward_int8pack(torch.randn(3, 64, dtype = torch.bfloat16)) is None+++def test_cpu_inputs_never_take_the_mps_kernel(monkeypatch):+ _, layer = _layer()+ monkeypatch.setattr(+ layer, "_forward_int8pack", lambda x: pytest.fail("int8pack on a CPU input")+ )+ x = torch.randn(4, 128, dtype = torch.bfloat16)+ assert torch.equal(+ layer(x), torch.nn.functional.linear(x, layer.dequantized_weight(x.dtype), layer.bias)+ )++[email protected](not _MPS, reason = "needs an MPS device")+def test_mps_forward_runs_the_kernel_and_matches_dequantise(monkeypatch):+ monkeypatch.setenv(nq.NATIVE_MPS_INT8PACK_ENV, "1")+ _, layer = _layer(n_in = 256, n_out = 96)+ layer = layer.to("mps")+ calls = []+ real = torch._weight_int8pack_mm+ monkeypatch.setattr(torch, "_weight_int8pack_mm", lambda *a: calls.append(1) or real(*a))+ x = torch.randn(3, 40, 256, dtype = torch.bfloat16, device = "mps")+ got = layer(x)+ assert calls, "the Metal kernel was not used"+ ref = torch.nn.functional.linear(+ x.float(), layer.dequantized_weight(torch.float32), layer.bias.float()+ )+ assert ((got.float() - ref).norm() / ref.norm()).item() < 1e-2+ xt = torch.randn(256, 40, dtype = torch.bfloat16, device = "mps").t()+ ref_t = torch.nn.functional.linear(+ xt.float(), layer.dequantized_weight(torch.float32), layer.bias.float()+ )+ assert ((layer(xt).float() - ref_t).norm() / ref_t.norm()).item() < 1e-2++[email protected](not _MPS, reason = "needs an MPS device")+def test_mps_kill_switch_and_unaligned_shapes_keep_dequantise(monkeypatch):+ monkeypatch.setenv(nq.NATIVE_MPS_INT8PACK_ENV, "1")+ monkeypatch.setattr(torch, "_weight_int8pack_mm", lambda *a: pytest.fail("kernel used"))+ _, odd = _layer(n_in = 128, n_out = 40) # N % 32 != 0+ odd = odd.to("mps")+ odd(torch.randn(4, 128, dtype = torch.bfloat16, device = "mps"))+ _, layer = _layer()+ layer = layer.to("mps")+ monkeypatch.setenv(nq.NATIVE_MPS_INT8PACK_ENV, "0")+ layer(torch.randn(4, 128, dtype = torch.bfloat16, device = "mps"))+++def _image_gate(+ monkeypatch,+ family,+ pinned,+ model_kind = "pipeline",+):+ import core.inference.diffusion as d+ from core.inference.diffusion_families import _FAMILIES++ fam = next(f for f in _FAMILIES if f.name == family)+ monkeypatch.setattr(d, "effective_te_quant", lambda *a, **k: None)+ d.DiffusionBackend._assert_precision_for_target(+ None,+ fam,+ _mps_target(),+ model_kind = model_kind,+ pinned = pinned,+ te_mode = None,+ memory_mode = None,+ cpu_offload = False,+ )++[email protected]("family", ["z-image", "qwen-image-2.1", "flux.2-klein"])+def test_image_gate_admits_int8_on_mps(monkeypatch, family):+ _image_gate(monkeypatch, family, "int8")++[email protected]("pinned", ["fp8", "mxfp8"])+def test_image_gate_still_refuses_other_schemes_on_mps(monkeypatch, pinned):+ with pytest.raises(RuntimeError, match = "transformer_quant"):+ _image_gate(monkeypatch, "z-image", pinned)+++def test_image_gate_refuses_int8_on_a_gguf_load_on_mps(monkeypatch):+ with pytest.raises(RuntimeError, match = "transformer_quant"):+ _image_gate(monkeypatch, "z-image", "int8", model_kind = "gguf")+++def test_reloaded_scales_are_not_served_from_the_cache():+ _, layer = _layer()+ first = layer._int8pack_scale(torch.bfloat16, "cpu").clone()+ state = layer.state_dict()+ state["weight_scale"] = (state["weight_scale"].view(torch.float32) * 2).view(+ state["weight_scale"].dtype+ )+ layer.load_state_dict(state)+ assert torch.equal(layer._int8pack_scale(torch.bfloat16, "cpu").float(), first.float() * 2)+++def _reported_layer(engaged):+ return types.SimpleNamespace(+ scheme = "int8",+ act_int8 = False,+ bias = None,+ weight_q = types.SimpleNamespace(device = torch.device("mps")),+ int8pack_engaged = lambda dtype: engaged,+ )++[email protected]("engaged", [True, False])+def test_reason_names_the_metal_kernel_only_when_it_dispatches(monkeypatch, engaged):+ monkeypatch.setattr(nq, "_first_native_linear", lambda module: _reported_layer(engaged))+ assert ("Apple Silicon int8 kernel" in nq.native_quant_reason(object(), "int8")) is engaged+++def test_kill_switch_and_alignment_close_the_kernel_for_the_status_line(monkeypatch):+ _, layer = _layer()+ monkeypatch.setenv(nq.NATIVE_MPS_INT8PACK_ENV, "1")+ assert layer._int8pack_layer_ok(torch.bfloat16) is _HAS_OP+ monkeypatch.setenv(nq.NATIVE_MPS_INT8PACK_ENV, "0")+ assert not layer._int8pack_layer_ok(torch.bfloat16)+ monkeypatch.setenv(nq.NATIVE_MPS_INT8PACK_ENV, "1")+ _, odd = _layer(n_out = 40)+ assert not odd._int8pack_layer_ok(torch.bfloat16)+ assert not layer.int8pack_engaged(torch.bfloat16) # stored on CPU++[email protected](autouse = True)+def _no_probe_state(monkeypatch):+ monkeypatch.delenv(nq.NATIVE_MPS_INT8PACK_ENV, raising = False)+ monkeypatch.setattr(nq, "_INT8PACK_PROBED", {})+++def _toy_native():+ toy = _Toy().to(torch.bfloat16)+ nq.apply_native_weight_quant(+ toy, "int8", filter_fn = lambda m, n: True, act_int8 = False, scale_dtype = torch.bfloat16+ )+ return toy+++def test_unprobed_auto_mode_keeps_dequantise(_no_probe_state):+ # No verdict yet: the deterministic dequantise path, never the kernel by default.+ _, layer = _layer()+ assert not layer._int8pack_layer_ok(torch.bfloat16)+ assert layer._int8pack_layer_ok(torch.bfloat16, probe = True) is _HAS_OP++[email protected](not _HAS_OP, reason = "torch has no _weight_int8pack_mm")+ "kernel_s, dense_s, expect",+ [+ (0.6, 0.8, True), # M1-like: bf16 GEMM has no fast path+ (1.02, 1.0, False), # M3-like: parity+ (4.1, 1.0, False), # M5-like: 16-bit GEMM on the matrix units+ (0.95, 1.0, False), # under the margin: not worth a nondeterministic kernel+ ],+)+def test_probe_takes_the_kernel_only_when_it_beats_bf16(+ _no_probe_state, monkeypatch, kernel_s, dense_s, expect+):+ seen = []++ def bench(layer, dtype, device):+ seen.append((layer.in_features, layer.out_features))+ return kernel_s, dense_s++ monkeypatch.setattr(nq, "_bench_int8pack_vs_dense", bench)+ toy = _toy_native()+ assert nq.probe_mps_int8pack(toy, torch.bfloat16, device = "cpu") is expect+ assert seen == [(128, 256)] # the largest eligible layer, probed once+ assert nq.mps_int8pack_selected(torch.bfloat16) is expect+ assert nq.probe_mps_int8pack(toy, torch.bfloat16, device = "cpu") is expect+ assert len(seen) == 1++[email protected](not _HAS_OP, reason = "torch has no _weight_int8pack_mm")+def test_probe_verdict_is_kept_per_model_shape(_no_probe_state, monkeypatch):+ # A second model in the same process with a different largest layer is probed again, and each model's layers+ # follow their own verdict; the same shape reuses the cached verdict.+ verdicts = {(128, 256): (0.6, 0.8), (256, 512): (4.1, 1.0)}+ seen = []++ def bench(layer, dtype, device):+ seen.append((layer.in_features, layer.out_features))+ return verdicts[(layer.in_features, layer.out_features)]++ monkeypatch.setattr(nq, "_bench_int8pack_vs_dense", bench)+ first = _toy_native()+ assert nq.probe_mps_int8pack(first, torch.bfloat16, device = "cpu") is True+ big = torch.nn.Sequential(torch.nn.Linear(256, 512, bias = False)).to(torch.bfloat16)+ nq.apply_native_weight_quant(+ big, "int8", filter_fn = lambda m, n: True, act_int8 = False, scale_dtype = torch.bfloat16+ )+ assert nq.probe_mps_int8pack(big, torch.bfloat16, device = "cpu") is False+ assert seen == [(128, 256), (256, 512)]+ assert first.ff._int8pack_layer_ok(torch.bfloat16) and not big[0]._int8pack_layer_ok(+ torch.bfloat16+ )+ again = _toy_native()+ assert nq.probe_mps_int8pack(again, torch.bfloat16, device = "cpu") is True+ assert len(seen) == 2 and again.ff._int8pack_layer_ok(torch.bfloat16)++[email protected]("env, expect", [("0", False), ("1", True)])+def test_env_override_skips_the_probe(_no_probe_state, monkeypatch, env, expect):+ monkeypatch.setenv(nq.NATIVE_MPS_INT8PACK_ENV, env)+ monkeypatch.setattr(+ nq, "_bench_int8pack_vs_dense", lambda *a: pytest.fail("probed despite the override")+ )+ assert nq.probe_mps_int8pack(_toy_native(), torch.bfloat16, device = "cpu") is expect++[email protected](not _HAS_OP, reason = "torch has no _weight_int8pack_mm")+def test_failed_probe_keeps_dequantise(_no_probe_state, monkeypatch):+ def boom(*a):+ raise RuntimeError("no Metal device")++ monkeypatch.setattr(nq, "_bench_int8pack_vs_dense", boom)+ assert nq.probe_mps_int8pack(_toy_native(), torch.bfloat16, device = "cpu") is False+ assert not nq.mps_int8pack_selected(torch.bfloat16)++[email protected](not _HAS_OP, reason = "torch has no _weight_int8pack_mm")+def test_bench_times_both_arms_on_the_real_layer_shape(_no_probe_state):+ toy = _toy_native()+ try:+ kernel_s, dense_s = nq._bench_int8pack_vs_dense(toy.ff, torch.bfloat16, torch.device("cpu"))+ except (RuntimeError, NotImplementedError) as exc:+ pytest.skip(f"no CPU int8pack kernel: {exc}")+ assert kernel_s > 0 and dense_s > 0+++def test_quantize_transformer_on_mps_runs_the_probe(_no_probe_state, monkeypatch):+ _block_torchao(monkeypatch)+ calls = []+ monkeypatch.setattr(+ nq, "probe_mps_int8pack", lambda module, dtype, **k: calls.append(dtype) or False+ )+ pipe = types.SimpleNamespace(transformer = _Toy().to(torch.bfloat16))+ assert tq.quantize_transformer(pipe, _mps_target(), mode = "int8", min_features = 64) == "int8"+ assert calls == [torch.bfloat16]++[email protected]("pinned", ["int8"])+def test_video_gate_admits_int8_on_mps(monkeypatch, pinned):+ # video.py shares native_quant_host, so Mac video int8 takes the same native path as images.+ import core.inference.video as v+ from core.inference.video_families import _FAMILIES as VIDEO_FAMILIES++ fam = next(f for f in VIDEO_FAMILIES if f.name == "wan2.2-ti2v-5b")+ monkeypatch.setattr(v, "effective_te_quant", lambda *a, **k: None)+ v._assert_video_precision_for_target(+ fam, _mps_target(), model_kind = "pipeline", transformer_quant = pinned+ )+++def test_video_gate_still_refuses_fp8_on_mps(monkeypatch):+ import core.inference.video as v+ from core.inference.video_families import _FAMILIES as VIDEO_FAMILIES++ fam = next(f for f in VIDEO_FAMILIES if f.name == "wan2.2-ti2v-5b")+ monkeypatch.setattr(v, "effective_te_quant", lambda *a, **k: None)+ with pytest.raises(RuntimeError, match = "transformer_quant"):+ v._assert_video_precision_for_target(+ fam, _mps_target(), model_kind = "pipeline", transformer_quant = "fp8"+ )++[email protected](not _MPS, reason = "needs an MPS device")+def test_mps_probe_times_the_real_kernel_and_records_a_verdict():+ toy = _toy_native().to("mps")+ verdict = nq.probe_mps_int8pack(toy, torch.bfloat16)+ assert nq._INT8PACK_PROBED == {(torch.bfloat16, 128, 256): verdict}+ assert nq.mps_int8pack_selected(torch.bfloat16) is verdict+ assert toy.ff.int8pack_engaged(torch.bfloat16) is verdict