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: quantise the hosted int8 leftovers on the GPU on offloaded loads (#17002)
Daniel Han5505f7ef318d
diff --git a/studio/backend/core/inference/diffusion_prequant.py b/studio/backend/core/inference/diffusion_prequant.pyindex 59b10acf924..3cffe613ade 100644--- a/studio/backend/core/inference/diffusion_prequant.py+++ b/studio/backend/core/inference/diffusion_prequant.py@@ -2565,6 +2565,7 @@ def load_prequantized_transformer(scheme,metadata.get("family") or family,min_features = int(metadata.get("min_features") or min_features or 512),+ device = device,logger = logger,)diff --git a/studio/backend/core/inference/diffusion_transformer_quant.py b/studio/backend/core/inference/diffusion_transformer_quant.pyindex 5f909b1761f..9c9a873f668 100644--- a/studio/backend/core/inference/diffusion_transformer_quant.py+++ b/studio/backend/core/inference/diffusion_transformer_quant.py@@ -208,9 +208,11 @@ def quantize_streamed_weight_only(family: Optional[str],*,min_features: int = DEFAULT_MIN_LINEAR_FEATURES,+ device: Any = None,logger: Any = None,) -> tuple[str, ...]:"""Quantise the still-dense Linears named by ``streamed_weight_only_tokens_for_scheme``; returns their fqns.+ Host-placed Linears are quantised on CUDA ``device`` and moved back.Weight-only (default): the timestep-embedding outlier channels stay dense beside the int8 codes and the fused GEMVruns them (``diffusion_int8_gemv``). An artifact loaded with them already weight-only only gets the GEMV forward.Best effort: any failure leaves them dense (the build is still valid, only bigger)."""@@ -244,9 +246,6 @@ def quantize_streamed_weight_only(if mode == "wo"else ())- if outliers:- modules = dict(transformer.named_modules())- used = min(split_outliers_(modules[name], outliers) for name in names)if mode == "w8a8rot":from .diffusion_convrot import DEFAULT_CONVROT_GROUPSIZE, rotate_linears_rotate_linears_(@@ -257,7 +256,21 @@ def quantize_streamed_weight_only(if transformer.get_submodule(n).in_features % DEFAULT_CONVROT_GROUPSIZE == 0],)- quantize_(transformer, config, filter_fn = lambda _m, fqn = "": fqn in wanted)+ modules = dict(transformer.named_modules())+ splits: list = []++ def _split_and_quantize(module: Any) -> None:+ if outliers:+ splits.append(split_outliers_(module, outliers))+ quantize_(module, config)++ _hop_each(+ [modules[name] for name in names if name in wanted],+ _hop_device(device),+ _split_and_quantize,+ )+ if outliers:+ used = min(splits)if mode == "wo":install(transformer, names, logger = logger)else:@@ -2147,6 +2160,115 @@ def _quantize_native(return None+def _hop_device(device: Any) -> Any:+ """CUDA ``torch.device`` to quantise host-placed Linears on, else None. An unindexed "cuda" resolves to this+ thread's current card here: the upload thread does not inherit it and would default to cuda:0."""+ if device is None:+ return None+ try:+ import torch++ work = torch.device(device)+ if work.type != "cuda":+ return None+ if work.index is None and torch.cuda.is_available():+ work = torch.device("cuda", torch.cuda.current_device())+ except Exception: # noqa: BLE001 - an unparsable device quantises in place+ return None+ return work+++def _hop_each(modules: list, work: Any, fn: Callable[[Any], None]) -> None:+ """``fn`` on each module, host-placed ones on ``work``; a raise leaves every module on its home device."""+ if work is None:+ for module in modules:+ fn(module)+ return++ def _home(module: Any) -> Any:+ weight = getattr(module, "weight", None)+ return getattr(weight, "device", None)++ from .host_pinning import host_pinning_allowed++ staged = host_pinning_allowed(work)++ def _up(module: Any) -> Any:+ home = _home(module)+ if home is None or home.type != "cpu":+ return None+ if not (staged and _upload_staged(module, work)):+ module.to(work)+ return home++ try:+ _hop_loop(modules, fn, _up)+ finally:+ if staged:+ from .diffusion_memory import release_pinned_host_memory+ release_pinned_host_memory()+++def _upload_staged(module: Any, work: Any) -> bool:+ """``module.to(work)`` via pinned copies (pageable H2D is 1-2 GB/s on cloud hosts); False = nothing moved."""+ import torch++ try:+ tensors = list(module._parameters.items()) + list(module._buffers.items())+ except AttributeError: # not an nn.Module+ return False+ if any(+ t is not None and (type(t.data) is not torch.Tensor or not t.data.is_contiguous())+ for _n, t in tensors+ ):+ return False+ try:+ moved = {+ name: t.data.pin_memory().to(work, non_blocking = True)+ for name, t in tensors+ if t is not None and t.device.type == "cpu"+ }+ torch.cuda.current_stream(work).synchronize()+ except Exception: # noqa: BLE001 - pinning refused: the pageable copy still works+ return False+ for name, value in moved.items():+ if name in module._parameters:+ module._parameters[name].data = value+ else:+ module._buffers[name] = value+ return True+++def _hop_loop(modules: list, fn: Callable[[Any], None], _up: Callable[[Any], Any]) -> None:+ """Upload module i + 1 on a helper thread while ``fn`` runs on module i."""+ from concurrent.futures import ThreadPoolExecutor++ pending = None+ with ThreadPoolExecutor(max_workers = 1, thread_name_prefix = "quant-hop") as pool:+ try:+ pending = (modules[0], pool.submit(_up, modules[0])) if modules else None+ for i, module in enumerate(modules):+ home = pending[1].result()+ pending = (+ (modules[i + 1], pool.submit(_up, modules[i + 1]))+ if i + 1 < len(modules)+ else None+ )+ try:+ fn(module)+ finally:+ if home is not None:+ module.to(home)+ finally:+ if pending is not None:+ try:+ home = pending[1].result()+ except Exception: # noqa: BLE001 - its upload failed: still home+ home = None+ if home is not None:+ pending[0].to(home)++def quantize_runtime_leftovers(transformer: Any,scheme: str,@@ -2188,23 +2310,13 @@ def quantize_runtime_leftovers(]if not targets:return 0- work = None- try:- work = torch.device(device) if device is not None else None- except Exception: # noqa: BLE001 - an unparsable device quantises in place- work = None- if work is not None and work.type != "cuda":- work = Noneconfig = _make_quant_config(scheme)t0 = time.perf_counter()- for _name, module in targets:- home = module.weight.device- hop = work is not None and home.type == "cpu"- if hop:- module.to(work)- quantize_(module, config)- if hop:- module.to(home)+ _hop_each(+ [module for _name, module in targets],+ _hop_device(device),+ lambda module: quantize_(module, config),+ )if logger is not None:logger.info("diffusion.transformer_quant: quantised %d %s Linear(s) the artifact kept dense (%s) in %.1f s",diff --git a/studio/backend/tests/test_diffusion_quant_hop.py b/studio/backend/tests/test_diffusion_quant_hop.pynew file mode 100644index 00000000000..85c08de3690--- /dev/null+++ b/studio/backend/tests/test_diffusion_quant_hop.py@@ -0,0 +1,106 @@+# Unsloth Zoo - Utilities for Unsloth+# Copyright 2023-present Daniel Han-Chen, Michael Han-Chen & the Unsloth team. All rights reserved.+#+# This program is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published+# by the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU Affero General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License+# along with this program. If not, see <https://www.gnu.org/licenses/>.++"""_hop_each: host-placed Linears are quantised on the CUDA device and always come back home."""++import types++import pytest++torch = pytest.importorskip("torch")++from core.inference import diffusion_transformer_quant as tq+++class _Mod:+ def __init__(+ self,+ name,+ log,+ home = "cpu",+ ):+ self.name = name+ self.log = log+ self.weight = types.SimpleNamespace(device = torch.device(home))++ def to(self, device):+ self.log.append(("to", self.name, str(device)))+ self.weight = types.SimpleNamespace(device = torch.device(device))+ return self+++def test_hop_device_only_takes_cuda():+ assert tq._hop_device(None) is None+ assert tq._hop_device("cpu") is None+ assert tq._hop_device("mps") is None+ assert tq._hop_device("not a device") is None+ assert tq._hop_device("cuda:1") == torch.device("cuda:1")+++def test_no_work_device_quantises_in_place():+ log = []+ mods = [_Mod(i, log) for i in range(3)]+ tq._hop_each(mods, None, lambda m: log.append(("q", m.name, str(m.weight.device))))+ assert log == [("q", 0, "cpu"), ("q", 1, "cpu"), ("q", 2, "cpu")]+++def test_each_module_quantises_on_work_and_returns_home():+ log = []+ mods = [_Mod(i, log) for i in range(4)] + [_Mod(9, log, home = "meta")]+ seen = []+ tq._hop_each(+ mods, torch.device("cuda:0"), lambda m: seen.append((m.name, str(m.weight.device)))+ )+ assert seen == [(0, "cuda:0"), (1, "cuda:0"), (2, "cuda:0"), (3, "cuda:0"), (9, "meta")]+ assert all(str(m.weight.device) in ("cpu", "meta") for m in mods)+ assert [m.weight.device.type for m in mods[:4]] == ["cpu"] * 4+ assert not any(entry[1] == 9 for entry in log if entry[0] == "to")+++def test_a_raise_leaves_every_module_home():+ log = []+ mods = [_Mod(i, log) for i in range(4)]++ def fn(m):+ if m.name == 1:+ raise RuntimeError("boom")++ with pytest.raises(RuntimeError):+ tq._hop_each(mods, torch.device("cuda:0"), fn)+ assert [m.weight.device.type for m in mods] == ["cpu"] * 4+++def test_staged_upload_refuses_what_it_cannot_copy_exactly():+ assert tq._upload_staged(object(), torch.device("cuda:0")) is False+ lin = torch.nn.Linear(4, 4)+ lin.weight.data = lin.weight.data.t() # non-contiguous: left to module.to+ assert tq._upload_staged(lin, torch.device("cuda:0")) is False+ assert lin.weight.device.type == "cpu"++[email protected](torch.cuda.is_available(), reason = "checks the no-CUDA fallback")+def test_staged_upload_without_cuda_moves_nothing():+ lin = torch.nn.Linear(4, 4)+ assert tq._upload_staged(lin, torch.device("cuda:0")) is False+ assert lin.weight.device.type == "cpu"+++def test_an_unindexed_cuda_device_resolves_in_the_calling_thread(monkeypatch):+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ monkeypatch.setattr(torch.cuda, "current_device", lambda: 3)+ assert tq._hop_device("cuda") == torch.device("cuda:3")+ assert tq._hop_device(torch.device("cuda")) == torch.device("cuda:3")+ assert tq._hop_device("cuda:1") == torch.device("cuda:1")