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: build native int8 image transformers per tensor on a cache miss (#15289)
Daniel Handf4b4a5a835a
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex e9f4d360a83..73878f9eebf 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -9402,6 +9402,7 @@ class DiffusionBackend:load_bg_compile = Nonestate = Nonepending_cache_write = None+ native_streamed = Falsetry:self._raise_if_load_cancelled(_load_token)if (@@ -9712,8 +9713,26 @@ class DiffusionBackend:_load_token),)+ if native_cached is None:+ # Miss: build per tensor so the dense module is never resident beside the codes.+ native_cached = self._native_quant_build_streamed(+ fam,+ transformer_cls,+ native_offload_scheme,+ target,+ dtype,+ source_base = _base_local_dir or fetch_base,+ config_kwargs = {+ "local_files_only": local_files_only,+ "cache_dir": hub_cache_dir(),+ **({"token": hf_token} if hf_token else {}),+ },+ cancel_check = lambda: self._raise_if_load_cancelled(+ _load_token+ ),+ )+ native_streamed = native_cached is not Noneif native_cached is not None:- # Cached native build: skips loading dense shards and re-quantizing.pipe_kwargs["transformer"] = native_cachednative_scheme = native_offload_schemetransformer_quant_engaged = native_offload_scheme@@ -10129,6 +10148,21 @@ class DiffusionBackend:_load_token,)+ if native_streamed and pipe is not None:+ pending_cache_write = self._save_pipeline_quant_to_cache(+ pipe,+ fam,+ denoiser_modules(pipe),+ loras = loras,+ base = base,+ source_base = _base_local_dir or fetch_base,+ cancel_check = lambda: self._raise_if_load_cancelled(_load_token),+ defer = True,+ native_cache = native_cache_ok,+ )+ if not hasattr(pending_cache_write, "start"):+ pending_cache_write = None+ self._raise_if_load_cancelled(_load_token)# Quantise dense bf16 pipeline denoisers in place. The blocker excludes UNet and pre-quantised# pipelines; offloaded plans stay dense unless whole-module.if (@@ -11861,6 +11895,47 @@ class DiffusionBackend:logger.warning("diffusion.prequant_cache: native read skipped (%s)", exc)return None+ @staticmethod+ def _native_quant_build_streamed(+ fam: Any,+ transformer_cls: Any,+ scheme: Optional[str],+ target: Any,+ dtype: Any,+ *,+ source_base: Optional[str],+ config_kwargs: Optional[dict] = None,+ cancel_check: Optional[Callable[[], None]] = None,+ ) -> Any:+ """Forced-offload native ``transformer`` built per tensor, or None for the dense load. Never raises."""+ try:+ if (+ fam is None+ or scheme is None+ or not source_base+ or getattr(target, "device", None) != "cuda"+ ):+ return None+ from .diffusion_native_cache import build_from_shards, native_spec++ family = getattr(fam, "name", None)+ spec = native_spec(+ scheme, family, act_int8 = scheme == TQ_INT8 and native_int8_act(target)+ )+ return build_from_shards(+ transformer_cls,+ str(source_base),+ spec,+ family = family,+ dtype = dtype,+ config_kwargs = config_kwargs,+ logger = logger,+ cancel_check = cancel_check,+ )+ except Exception as exc: # noqa: BLE001 - the dense load still runs+ logger.warning("diffusion.transformer_quant: per-tensor native build skipped (%s)", exc)+ return None+@staticmethoddef _save_pipeline_quant_to_cache(pipe: Any,diff --git a/studio/backend/core/inference/diffusion_native_cache.py b/studio/backend/core/inference/diffusion_native_cache.pyindex 3f4b1420461..4603b800404 100644--- a/studio/backend/core/inference/diffusion_native_cache.py+++ b/studio/backend/core/inference/diffusion_native_cache.py@@ -456,6 +456,239 @@ def load(return None+STREAM_BUILD_ENV = "UNSLOTH_DIFFUSION_NATIVE_STREAM_BUILD"+# Dtypes a bf16 load never casts; any other floating dtype falls back to the dense load.+_STREAM_DTYPES = {+ "BF16": "bfloat16",+ "I64": "int64",+ "I32": "int32",+ "I16": "int16",+ "I8": "int8",+ "U8": "uint8",+ "BOOL": "bool",+}+++def stream_build_enabled() -> bool:+ value = (os.environ.get(STREAM_BUILD_ENV) or "").strip().lower()+ return value not in ("0", "off", "false", "no")+++def _dense_shards(source: Any, component: str, cache_dir: Optional[str]) -> Optional[list[str]]:+ """The shard files ``from_pretrained(source, subfolder = component)`` reads (index first, as diffusers), or None."""+ stem = f"{component}/diffusion_pytorch_model"+ index = _cache._local_file(str(source), f"{stem}.safetensors.index.json", cache_dir)+ if index is not None:+ with open(index, "r", encoding = "utf-8") as fh:+ weight_map = (json.load(fh) or {}).get("weight_map") or {}+ names = sorted(set(str(v) for v in weight_map.values()))+ paths = [_cache._local_file(str(source), f"{component}/{n}", cache_dir) for n in names]+ return [str(p) for p in paths] if names and all(paths) else None+ single = _cache._local_file(str(source), f"{stem}.safetensors", cache_dir)+ return [str(single)] if single else None+++def _shard_entries(path: str) -> Optional[tuple[int, dict]]:+ """(data start, ``{key: header entry}``) of a shard holding only dtypes in ``_STREAM_DTYPES``, else None."""+ raw = _cache.read_header_bytes(path)+ if raw is None:+ return None+ header = json.loads(raw[8:].decode("utf-8"))+ header.pop("__metadata__", None)+ if any(entry.get("dtype") not in _STREAM_DTYPES for entry in header.values()):+ return None+ return len(raw), header+++def _map_tensor(fd: int, start: int, entry: dict) -> Any:+ """One tensor over its own private mapping, unmapped when freed (a whole-shard mapping stays resident while any+ tensor survives)."""+ import mmap++ import torch++ begin, end = (int(v) for v in entry["data_offsets"])+ dtype = getattr(torch, _STREAM_DTYPES[entry["dtype"]])+ shape = [int(d) for d in entry["shape"]]+ count = 1+ for d in shape:+ count *= d+ if end - begin != count * torch.empty((), dtype = dtype).element_size():+ raise ValueError("shard entry size does not match its shape")+ if end == begin:+ return torch.empty(shape, dtype = dtype)+ offset = start + begin+ aligned = offset - offset % mmap.ALLOCATIONGRANULARITY+ # Copy-on-write: writable, nothing reaches the file.+ window = mmap.mmap(+ fd, offset + (end - begin) - aligned, offset = aligned, access = mmap.ACCESS_COPY+ )+ flat = torch.frombuffer(window, dtype = torch.uint8, count = end - begin, offset = offset - aligned)+ return flat.view(dtype).reshape(shape)+++def build_from_shards(+ transformer_cls: Any,+ config_source: str,+ spec: dict,+ *,+ family: Optional[str],+ dtype: Any,+ component: str = "transformer",+ config_kwargs: Optional[dict] = None,+ logger: Any = None,+ cancel_check: Optional[Any] = None,+) -> Any:+ """Build the native ``component`` per tensor, bit-identical to the in-place build, or None for the dense load+ (also on cancel, which the caller re-checks). Never raises."""+ cancelled = [False]++ def _check() -> None:+ if cancel_check is None:+ return+ try:+ cancel_check()+ except BaseException:+ cancelled[0] = True+ raise++ t0 = time.perf_counter()+ try:+ import torch++ from .diffusion_native_quant import NATIVE_INT8, native_linear_class+ from .diffusion_transformer_quant import exclude_tokens_for_scheme, make_filter_fn++ def skip(why: str) -> None:+ _cache._log(logger, "info", f"native {component}: per-tensor build skipped ({why})")++ if not stream_build_enabled() or transformer_cls is None:+ return None+ if dtype is not torch.bfloat16:+ return skip(f"loads at {str(dtype).replace('torch.', '')}, not bfloat16")+ if getattr(transformer_cls, "_keep_in_fp32_modules", None):+ return skip("the class keeps fp32 modules")+ scheme = spec["scheme"]+ cache_dir = (config_kwargs or {}).get("cache_dir")+ shards = _dense_shards(config_source, component, cache_dir)+ if not shards:+ return skip("dense shards not found locally")+ if _cache._hub_source_stale(shards, logger):+ return None+ entries = []+ for shard in shards:+ found = _shard_entries(shard)+ if found is None:+ return skip("a shard holds a dtype other than bf16")+ entries.append((shard, *found))+ stored = {key: entry for _shard, _start, header in entries for key, entry in header.items()}+ _check()+ config = transformer_cls.load_config(+ config_source, subfolder = component, **(config_kwargs or {})+ )+ try:+ from accelerate import init_empty_weights+ except Exception: # noqa: BLE001+ return skip("accelerate is missing")+ # Buffers stay real: non-persistent ones (rope tables) are built by __init__ as a dense load builds them.+ with init_empty_weights(include_buffers = False):+ model = transformer_cls.from_config(config)+ # The in-place build filters the loaded module, whose weights carry the stored dtype.+ for name, mod in model.named_modules():+ entry = stored.get(f"{name}.weight") if name else None+ if (+ isinstance(mod, torch.nn.Linear)+ and entry is not None+ and mod.weight.device.type == "meta"+ ):+ mod.weight = torch.nn.Parameter(+ torch.empty(+ mod.weight.shape,+ dtype = getattr(torch, _STREAM_DTYPES[entry["dtype"]]),+ device = "meta",+ ),+ requires_grad = mod.weight.requires_grad,+ )+ filter_fn = make_filter_fn(+ int(spec["min_features"]),+ exclude_name_tokens = exclude_tokens_for_scheme(scheme, family) + ("lora_",),+ require_bf16 = True,+ )+ quant = {name for name, mod in model.named_modules() if name and filter_fn(mod, name)}+ act_int8 = scheme == NATIVE_INT8 and bool(spec["act_int8"])+ rot_group = int(spec["rot_group"]) if act_int8 else 0+ cls = native_linear_class()+ state: dict = {}+ built = 0+ for shard, start, header in entries:+ fd = os.open(shard, os.O_RDONLY)+ try:+ for key, entry in sorted(+ header.items(), key = lambda kv: int(kv[1]["data_offsets"][0])+ ):+ _check()+ tensor = _map_tensor(fd, start, entry)+ fqn, _, leaf = key.rpartition(".")+ if leaf != "weight" or fqn not in quant:+ state[key] = tensor+ continue+ parent_name, _, attr = fqn.rpartition(".")+ parent = model.get_submodule(parent_name) if parent_name else model+ dense = getattr(parent, attr)+ stand_in = torch.nn.Linear(+ int(dense.in_features),+ int(dense.out_features),+ bias = dense.bias is not None,+ device = "meta",+ dtype = tensor.dtype,+ )+ stand_in.weight = torch.nn.Parameter(tensor, requires_grad = False)+ del tensor+ layer = cls(stand_in, scheme, act_int8 = act_int8, rot_group = rot_group)+ del stand_in+ setattr(parent, attr, layer)+ state[f"{fqn}.weight_q"] = layer.weight_q+ state[f"{fqn}.weight_scale"] = layer.weight_scale+ built += 1+ finally:+ # The mappings outlive the descriptor; each closes with its tensor.+ os.close(fd)+ if built != len(quant):+ return skip(f"{len(quant) - built} quantizable weights missing from the shards")+ model.load_state_dict(state, strict = True, assign = True)+ del state+ if any(t.device.type == "meta" for t in (*model.parameters(), *model.buffers())):+ return skip("tensors left on meta")+ model.eval()+ try:+ model._unsloth_runtime_quant = scheme+ model._unsloth_runtime_quant_info = {"scheme": scheme, "native": True}+ except Exception: # noqa: BLE001+ pass+ _cache._log(+ logger,+ "info",+ f"native {component}: {scheme} "+ + (+ ("W8A8 torch._int_mm" + (f" ConvRot g{rot_group}" if rot_group else ""))+ if act_int8+ else "weight-only"+ )+ + f" built per tensor from {len(shards)} dense shard(s) on {built} linears "+ f"in {time.perf_counter() - t0:.1f} s",+ )+ return model+ except Exception as exc: # noqa: BLE001 - the caller loads the dense module whole instead+ if cancelled[0]:+ return None+ _cache._log(+ logger,+ "warning",+ f"native {component}: per-tensor build failed: {type(exc).__name__}: {str(exc)[:200]}",+ )+ return None++def build_spec(transformer: Any, family: Optional[str]) -> Optional[dict]:"""``native_spec`` of an in-memory native build, read from its layers, or None (no native layers, or a mix)."""try:diff --git a/studio/backend/tests/test_diffusion_native_stream_build.py b/studio/backend/tests/test_diffusion_native_stream_build.pynew file mode 100644index 00000000000..6f7baf7ad9f--- /dev/null+++ b/studio/backend/tests/test_diffusion_native_stream_build.py@@ -0,0 +1,258 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A native int8 cache miss builds the layers per tensor from the dense shards, bit-identical to the in-place build."""++from __future__ import annotations++import sys+import types+from pathlib import Path++import pytest++torch = pytest.importorskip("torch")+diffusers = pytest.importorskip("diffusers")+pytest.importorskip("safetensors")+pytest.importorskip("accelerate")++BACKEND = Path(__file__).resolve().parents[1]+if str(BACKEND) not in sys.path:+ sys.path.insert(0, str(BACKEND))++from core.inference import diffusion as D # noqa: E402+from core.inference import diffusion_native_cache as NC # noqa: E402+from core.inference import diffusion_prequant_cache as C # noqa: E402+from core.inference import diffusion_transformer_quant as tq # noqa: E402+from core.inference.diffusion_families import detect_family # noqa: E402++FAMILY = "flux.1"+BASE = "black-forest-labs/FLUX.1-schnell"+CUDA = types.SimpleNamespace(device = "cuda", dtype = torch.bfloat16)+++def _fam():+ return detect_family(BASE, override = FAMILY)+++def _tiny(dtype = torch.bfloat16):+ torch.manual_seed(0)+ # 2 x 256 = 512 wide: every block Linear passes the 512 filter and g256 ConvRot divides it.+ return diffusers.FluxTransformer2DModel(+ patch_size = 1,+ in_channels = 16,+ num_layers = 1,+ num_single_layers = 1,+ attention_head_dim = 256,+ num_attention_heads = 2,+ joint_attention_dim = 512,+ pooled_projection_dim = 64,+ axes_dims_rope = (32, 112, 112),+ ).to(dtype)++[email protected](params = ["single", "sharded"])+def base_dir(tmp_path, request):+ root = tmp_path / "FLUX.1-schnell"+ kwargs = {"max_shard_size": "2MB"} if request.param == "sharded" else {}+ _tiny().save_pretrained(str(root / "transformer"), safe_serialization = True, **kwargs)+ shards = sorted((root / "transformer").glob("*.safetensors"))+ assert (len(shards) > 1) == (request.param == "sharded")+ return str(root)++[email protected](autouse = True)+def cache_root(tmp_path, monkeypatch):+ root = tmp_path / "cache"+ monkeypatch.setenv(C.ENV_DIR, str(root))+ monkeypatch.delenv(C.ENV_MODE, raising = False)+ monkeypatch.delenv(C.ENV_ASYNC, raising = False)+ monkeypatch.delenv(NC.STREAM_BUILD_ENV, raising = False)+ monkeypatch.setattr(C, "_hub_source_stale", lambda shards, logger = None: False)+ return root+++def _in_place(base_dir, act_int8):+ model = diffusers.FluxTransformer2DModel.from_pretrained(+ base_dir, subfolder = "transformer", torch_dtype = torch.bfloat16+ )+ view = types.SimpleNamespace(transformer = model)+ assert (+ tq._quantize_native(+ view,+ "int8",+ family = FAMILY,+ min_features = tq.DEFAULT_MIN_LINEAR_FEATURES,+ act_int8 = act_int8,+ logger = None,+ )+ == "int8"+ )+ return model+++def _streamed(base_dir, act_int8, **kwargs):+ return NC.build_from_shards(+ diffusers.FluxTransformer2DModel,+ base_dir,+ NC.native_spec("int8", FAMILY, act_int8 = act_int8),+ family = FAMILY,+ dtype = kwargs.pop("dtype", torch.bfloat16),+ **kwargs,+ )+++def _assert_same_module(a, b):+ sa, sb = a.state_dict(), b.state_dict()+ assert sa.keys() == sb.keys()+ for k in sa:+ assert sa[k].dtype == sb[k].dtype and torch.equal(sa[k], sb[k]), k+ ma, mb = dict(a.named_modules()), dict(b.named_modules())+ assert ma.keys() == mb.keys()+ for name in ma:+ assert type(ma[name]).__name__ == type(mb[name]).__name__, name+ for (na, pa), (nb, pb) in zip(a.named_parameters(), b.named_parameters()):+ assert na == nb and pa.requires_grad == pb.requires_grad, na+ ba = dict(a.named_buffers())+ bb = dict(b.named_buffers())+ assert ba.keys() == bb.keys()+ for k in ba:+ assert ba[k].dtype == bb[k].dtype and torch.equal(ba[k], bb[k]), k++[email protected]("act_int8", [True, False])+def test_streamed_build_is_bit_identical_to_the_in_place_build(base_dir, act_int8):+ ref = _in_place(base_dir, act_int8)+ got = _streamed(base_dir, act_int8)+ assert got is not None+ assert got._unsloth_runtime_quant_info == {"scheme": "int8", "native": True}+ _assert_same_module(ref, got)+ from core.inference.diffusion_native_quant import is_native_linear++ layers = {n: m for n, m in got.named_modules() if is_native_linear(m)}+ assert layers+ for name, layer in ref.named_modules():+ if is_native_linear(layer):+ other = layers[name]+ assert (layer.scheme, layer.act_int8, layer.rot_group, layer.compute_dtype) == (+ other.scheme,+ other.act_int8,+ other.rot_group,+ other.compute_dtype,+ )+ x = torch.randn(1, 8, 16, dtype = torch.bfloat16)+ ctx = torch.randn(1, 4, 512, dtype = torch.bfloat16)+ kwargs = dict(+ hidden_states = x,+ encoder_hidden_states = ctx,+ pooled_projections = torch.randn(1, 64, dtype = torch.bfloat16),+ timestep = torch.tensor([0.5], dtype = torch.bfloat16),+ img_ids = torch.zeros(8, 3),+ txt_ids = torch.zeros(4, 3),+ return_dict = False,+ )+ with torch.no_grad():+ assert torch.equal(ref(**kwargs)[0], got(**kwargs)[0])+++def test_cache_entry_is_byte_identical_to_the_in_place_entry(base_dir, tmp_path, monkeypatch):+ monkeypatch.setenv(C.ENV_ASYNC, "0")+ entries = []+ for arm, build in (("ref", _in_place), ("streamed", _streamed)):+ monkeypatch.setenv(C.ENV_DIR, str(tmp_path / f"cache_{arm}"))+ model = build(base_dir, True)+ out = NC.save_deferred(model, _fam(), base_repo = BASE, source_base = base_dir)+ assert isinstance(out, str) and Path(out).is_file()+ entries.append(Path(out))+ assert entries[0].parent.name == entries[1].parent.name+ assert entries[0].read_bytes() == entries[1].read_bytes()+++def _mapped_shard_bytes(base_dir):+ total = 0+ for line in Path("/proc/self/maps").read_text().splitlines():+ if str(Path(base_dir).resolve()) in line:+ lo, hi = line.split()[0].split("-")+ total += int(hi, 16) - int(lo, 16)+ return total+++def test_only_kept_tensors_stay_mapped(base_dir):+ import gc+ import mmap++ if not Path("/proc/self/maps").is_file():+ pytest.skip("needs /proc/self/maps")+ got = _streamed(base_dir, True)+ assert got is not None+ from core.inference.diffusion_native_quant import is_native_linear++ native = {+ id(t) for m in got.modules() if is_native_linear(m) for t in (m.weight_q, m.weight_scale)+ }+ kept = [t for t in got.state_dict().values() if id(t) not in native]+ dense = sum(t.numel() * t.element_size() for t in _tiny().state_dict().values())+ kept_bytes = sum(t.numel() * t.element_size() for t in kept)+ mapped = _mapped_shard_bytes(base_dir)+ # Each kept tensor maps its own bytes (plus page slack); no quantized weight leaves a mapping behind.+ assert 0 < mapped <= kept_bytes + len(kept) * 2 * mmap.ALLOCATIONGRANULARITY+ assert kept_bytes < dense+ del got, kept+ gc.collect()+ assert _mapped_shard_bytes(base_dir) == 0+++def test_declines_leave_the_dense_load(base_dir, tmp_path, monkeypatch):+ # an fp16 load, a non-bf16 checkpoint, missing shards and the kill switch all fall back to the dense load+ assert _streamed(base_dir, True, dtype = torch.float16) is None+ fp32 = tmp_path / "fp32"+ _tiny(torch.float32).save_pretrained(str(fp32 / "transformer"), safe_serialization = True)+ assert _streamed(str(fp32), True) is None+ assert _streamed(str(tmp_path / "missing"), True) is None+ monkeypatch.setenv(NC.STREAM_BUILD_ENV, "0")+ assert _streamed(base_dir, True) is None+++def test_a_cancel_is_a_none(base_dir):+ calls = []++ def cancel():+ calls.append(1)+ if len(calls) > 3:+ raise RuntimeError("cancelled")++ assert _streamed(base_dir, True, cancel_check = cancel) is None+ assert len(calls) == 4+++def test_backend_builds_on_cuda_only_and_the_save_writes_it(base_dir, monkeypatch):+ monkeypatch.setenv(C.ENV_ASYNC, "0")+ build = lambda target, scheme = "int8": D.DiffusionBackend._native_quant_build_streamed( # noqa: E731+ _fam(),+ diffusers.FluxTransformer2DModel,+ scheme,+ target,+ torch.bfloat16,+ source_base = base_dir,+ )+ assert build(types.SimpleNamespace(device = "mps", dtype = torch.bfloat16)) is None+ assert build(CUDA, None) is None+ got = build(CUDA)+ assert got is not None+ _assert_same_module(_in_place(base_dir, D.native_int8_act(CUDA)), got)+ out = D.DiffusionBackend._save_pipeline_quant_to_cache(+ types.SimpleNamespace(transformer = got),+ _fam(),+ [("transformer", got)],+ loras = None,+ base = BASE,+ source_base = base_dir,+ defer = True,+ native_cache = True,+ )+ assert isinstance(out, str) and Path(out).is_file()+ hit = D.DiffusionBackend._native_quant_from_cache(+ _fam(), diffusers.FluxTransformer2DModel, "int8", CUDA, base = BASE, source_base = base_dir+ )+ assert hit is not None+ _assert_same_module(got, hit)