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: load FLUX.1 and Qwen-Image on fp16-only GPUs with small host RAM (#12480)
Daniel Han0a0da5229c6d
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex a2c997918f0..e05c6066fe5 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -102,6 +102,15 @@ from .diffusion_hidream import (hidream_te4_kwargs,)from .diffusion_krea2 import KREA2_FAMILY_NAME, load_krea2_pipeline+from .diffusion_small_host import (+ INT8_DENOISER_NAMES,+ decide_small_host,+ engaged_on as small_host_engaged_on,+ host_ram_mib,+ resolve_snapshot_dir,+ stored_components,+ torch_dtype_map as small_host_torch_dtype_map,+)from .model_ids import hf_cache_repo_idfrom .diffusion_memory import (MEMORY_MODE_BALANCED,@@ -6348,11 +6357,34 @@ class DiffusionBackend:)bf16_pipeline_plan = planself._raise_if_load_cancelled(_load_token)+ # bf16 -> fp16 conversion materialises in host RAM (35 GB for FLUX.1)+ small_host = self._small_host_decision(+ _base_local_dir or fetch_base,+ pipe_kwargs,+ target,+ dtype,+ lora_active = _has_active_lora(loras),+ )+ if small_host is not None and small_host.engaged:+ pipe_kwargs["torch_dtype"] = small_host_torch_dtype_map(+ small_host, dtype+ )# The prefetched snapshot dir keeps from_pretrained off the hub (24 GB per FLUX.1# otherwise)pipe = pipeline_cls.from_pretrained(_base_local_dir or fetch_base, **pipe_kwargs)+ if small_host is not None and small_host.engaged:+ plan = self._apply_small_host_route(+ pipe,+ plan,+ small_host,+ target,+ dtype,+ fam,+ logger,+ _load_token,+ )elif kind == "single_file" and fam.single_file_is_pipeline:# A single-file SDXL-style checkpoint is the WHOLE pipeline: load it through the pipeline# class with ``config`` on the base repo.@@ -6458,9 +6490,32 @@ class DiffusionBackend:))self._raise_if_load_cancelled(_load_token)+ # the companions (15.8 GB bf16 Qwen2.5-VL at fp32) fill the host here+ small_host = self._small_host_decision(+ _base_local_dir or fetch_base,+ pipe_kwargs,+ target,+ dtype,+ lora_active = _has_active_lora(loras),+ )+ if small_host is not None and small_host.engaged:+ pipe_kwargs["torch_dtype"] = small_host_torch_dtype_map(+ small_host, dtype+ )pipe = pipeline_cls.from_pretrained(_base_local_dir or fetch_base, **pipe_kwargs)+ if small_host is not None and small_host.engaged:+ plan = self._apply_small_host_route(+ pipe,+ plan,+ small_host,+ target,+ dtype,+ fam,+ logger,+ _load_token,+ )# The same helper the route preflight asked, so the two cannot disagree.pipeline_quant_uncompilable = _pipeline_quant_uncompilable_reason(@@ -6952,6 +7007,8 @@ class DiffusionBackend:int(headroom),fam.name,effective_speed,+ plan.estimates.get("measured_dense_transformer_mib"),+ plan.estimates.get("measured_compute_bytes"),)from .diffusion_qwenimage21_vision import configure_vision_attention@@ -6986,6 +7043,8 @@ class DiffusionBackend:# Apply the planned placement; apply_memory_plan returns what ACTUALLY engaged so status stays# honest.self._raise_if_load_cancelled(_load_token)+ # a refinement may have re-tiered the plan; routed encoders need group offload+ plan = self._small_host_plan(pipe, plan, fam, logger)effective_policy, effective_tiling = apply_memory_plan(pipe,plan,@@ -7924,6 +7983,140 @@ class DiffusionBackend:return Nonereturn unified_memory_shortfall_message(plan, family = fam.name)+ def _small_host_decision(+ self, source: Any, pipe_kwargs: dict, target: Any, dtype: Any, *, lora_active: bool+ ) -> Any:+ """Small-host decision for a pipeline load; raises its refusal, None without a local snapshot."""+ snapshot = resolve_snapshot_dir(source, hub_cache_dir())+ if snapshot is None:+ return None+ comps = {+ name: comp+ for name, comp in stored_components(snapshot).items()+ # pre-built components (hosted fp8 encoder, prequant denoiser) are not loaded here+ if name not in pipe_kwargs+ }+ total, available = host_ram_mib()+ decision = decide_small_host(+ comps,+ dtype,+ device = str(getattr(target, "backend", None) or getattr(target, "device", "")),+ host_total_mib = total,+ host_available_mib = available,+ lora_active = lora_active,+ )+ if decision.engaged or decision.refuse:+ logger.info(+ "diffusion.small_host: engaged=%s (%s); stored-dtype components=%s",+ decision.engaged,+ decision.reason,+ decision.storage_dtypes,+ )+ if decision.refuse:+ raise RuntimeError(decision.refuse)+ return decision++ def _apply_small_host_route(+ self,+ pipe: Any,+ plan: Any,+ decision: Any,+ target: Any,+ dtype: Any,+ fam: Any,+ logger: Any,+ load_token: Any = None,+ ) -> Any:+ """Convert the components loaded at their stored dtype and place the plan to keep them memory-mapped."""+ import torch++ from .diffusion_small_host import (+ cast_resident_,+ mark,+ prepare_streamed_encoder_,+ quantize_int8_weight_,+ )++ device = target.torch_device+ resident = plan.offload_policy == OFFLOAD_NONE+ info: dict[str, Any] = {"reason": decision.reason, "components": {}}+ for name in decision.storage_dtypes:+ module = getattr(pipe, name, None)+ if not isinstance(module, torch.nn.Module):+ continue+ if resident:+ cast_resident_(module, device, dtype)+ info["components"][name] = "cast on device"+ elif name.startswith("text_encoder"):+ mib = prepare_streamed_encoder_(module, dtype)+ info["components"][name] = f"memory-mapped, layerwise cast ({mib} MiB)"+ elif name not in INT8_DENOISER_NAMES:+ cast_resident_(module, "cpu", dtype)+ info["components"][name] = "converted"+ else:+ # pageable: pinning rounds blocks to powers of two (11.3 GB of FLUX.1 int8 held 18 GB pinned)+ stats = quantize_int8_weight_(+ module, compute_dtype = dtype, work_device = device, keep_device = "cpu"+ )+ info["components"][name] = (+ f"int8 weights ({stats['int8_bytes'] >> 20} MiB, {stats['linears']} linears)"+ )+ if load_token is not None:+ self._raise_if_load_cancelled(load_token)+ mark(pipe, info)+ logger.info("diffusion.small_host: %s", info["components"])+ return self._small_host_plan(pipe, plan, fam, logger)++ def _small_host_plan(self, pipe: Any, plan: Any, fam: Any, logger: Any) -> Any:+ """Group offload, routed encoders streamed; the denoiser keeps what fits after the runtime reserve resident."""+ info = small_host_engaged_on(pipe)+ if not info or plan.offload_policy == OFFLOAD_NONE:+ return plan+ if "small_host_loaded_transformer_mib" in plan.estimates and plan.stream_text_encoders:+ return plan # already placed by the route+ from .diffusion_memory import (+ DEFAULT_BASE_OVERHEAD_MIB,+ OFFLOAD_GROUP,+ _loaded_component_mib,+ )++ sizes = _loaded_component_mib(pipe) or {}+ dit = sum(m for m, r in sizes.values() if r == "dit")+ other = sum(m for m, r in sizes.values() if r == "other")+ est = dict(plan.estimates)+ budget = est.get("safe_device_budget_mib")+ headroom = int(est.get("runtime_headroom_mib") or 0)+ overhead = int(est.get("base_overhead_mib") or DEFAULT_BASE_OVERHEAD_MIB)+ room = None if budget is None else int(budget) - headroom - overhead - other+ stream_dit = room is None or dit <= 0 or room < dit+ resident_dit = None if not stream_dit or room is None or room <= 0 else int(room)+ new = replace(+ plan,+ offload_policy = OFFLOAD_GROUP,+ stream_text_encoders = True,+ stream_transformer = stream_dit,+ resident_transformer_mib = resident_dit+ if plan.resident_transformer_mib is None+ else plan.resident_transformer_mib,+ estimates = {**est, "small_host_loaded_transformer_mib": dit},+ reasons = plan.reasons+ + (+ f"small-host route: encoders stream from memory-mapped storage; transformer {dit} MiB "+ + (+ "resident"+ if not stream_dit+ else f"streams with {resident_dit or 0} MiB resident"+ ),+ ),+ )+ if (+ new.offload_policy != plan.offload_policy+ or new.stream_transformer != plan.stream_transformer+ or new.resident_transformer_mib != plan.resident_transformer_mib+ ):+ logger.info("diffusion.small_host: placement %s", new.reasons[-1])+ return new+def _plan_memory(self,target: DiffusionDeviceTarget,@@ -8462,6 +8655,12 @@ class DiffusionBackend:cuda_graph.reset_all(getattr(state, "cuda_graphs", ()))return+ if _small_host_int8(pipe):+ raise ValueError(+ "LoRA is not available on this load: system RAM was too small for the dense model, so Studio "+ "stored the transformer as int8 weights (small-host route), which cannot carry adapters. Load the "+ "model with the LoRA selected (Studio then keeps the dense transformer), or use a host with more RAM."+ )if not diffusion_lora.supports_lora(engine = "diffusers",family = getattr(state.family, "name", None),@@ -9754,7 +9953,9 @@ class DiffusionBackend:model_kind = state.kind,transformer_quant = state.transformer_quant,compiled = "compiled" in (getattr(state, "speed_optims", ()) or ()),- ),+ )+ and not _small_host_int8(state.pipe),+ "small_host": small_host_engaged_on(state.pipe),"supports_controlnet": diffusion_controlnet.supports_controlnet(engine = "diffusers",family = state.family.name,@@ -9767,6 +9968,12 @@ class DiffusionBackend:}+def _small_host_int8(pipe: Any) -> bool:+ """Whether the small-host route stored a denoiser as int8 weights on this pipe."""+ info = small_host_engaged_on(pipe) or {}+ return any(str(v).startswith("int8") for v in (info.get("components") or {}).values())++def _transformer_quant_backend(state: Any) -> Optional[str]:"""Which NVFP4 kernel path the loaded denoiser runs, read from the MODULE TREE, or None. Never raises."""if getattr(state, "transformer_quant", None) != TQ_NVFP4:diff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.pyindex 3edc8202c12..22552512151 100644--- a/studio/backend/core/inference/diffusion_families.py+++ b/studio/backend/core/inference/diffusion_families.py@@ -335,6 +335,8 @@ _FAMILIES: tuple[DiffusionFamily, ...] = ("qwenimageedit",),edit = True,+ # same DiT as qwen-image+ fp16_incompatible = True,),DiffusionFamily(name = "qwen-image",@@ -359,6 +361,8 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (te_prequant_repos = (("fp8", "text_encoder", "unsloth/Qwen-Image-FP8"),),cfg_kwarg = "true_cfg_scale",aliases = ("qwen_image", "qwenimage"),+ # fp16 overflows to NaN latents (black images)+ fp16_incompatible = True,trainable = True,train_base_repos = ("unsloth/Qwen-Image-2512-unsloth-bnb-4bit", "Qwen/Qwen-Image"),img2img_pipeline_class = "QwenImageImg2ImgPipeline",diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.pyindex 7cf126e8ed6..7777579fbf1 100644--- a/studio/backend/core/inference/diffusion_memory.py+++ b/studio/backend/core/inference/diffusion_memory.py@@ -1517,6 +1517,22 @@ def _pipe_denoisers_hold_torchao(pipe: Any) -> bool:)+def _pipe_denoisers_hold_packed(pipe: Any) -> bool:+ """GGUF / int8 weights dequantize a whole Linear per forward: unmeasured by the dense eager table."""+ try:+ import torch+ for name in ("transformer", "transformer_2", "unconditional_transformer", "unet"):+ params = getattr(getattr(pipe, name, None), "parameters", None)+ if callable(params) and any(+ type(p).__name__ == "GGUFParameter" or p.dtype in (torch.int8, torch.uint8)+ for p in params()+ ):+ return True+ except Exception: # noqa: BLE001+ return True+ return False++def plan_fits_total_capacity(plan: Any) -> bool:"""Whether ``plan``'s resident requirement fits TOTAL device capacity under the standardreserve + the 0.85 resident margin -- i.e. an offload decision can only stem from the@@ -2181,6 +2197,16 @@ _MEASURED_PEAK_SPEED_MODES = ("default", "max")_MEASURED_PEAK_MARGIN = 1.15_MEASURED_PEAK_ROUND_MIB = 256+# Dense denoisers, eager tier: worst CUDA MiB above resident weights, fp16, 1024x1024, encode + steps + VAE decode.+# family -> (peak MiB, largest loaded DiT MiB it covers; a bigger DiT keeps the flat estimate)+MEASURED_ACTIVATION_DENSE_ENV = "UNSLOTH_DIFFUSION_MEASURED_ACTIVATION_DENSE"+_MEASURED_DENSE_EAGER_PEAK_MIB: dict[str, tuple[int, int]] = {+ "flux.2-klein": (2455, 7800),+ "flux.1": (2448, 23800),+ "qwen-image": (4248, 40900),+}+_MEASURED_DENSE_SPEED_MODES = ("off",)+def _env_off(name: str) -> bool:return (os.environ.get(name) or "").strip().lower() in ("0", "off", "false", "no")@@ -2193,13 +2219,28 @@ def measured_image_runtime_mib(width: Optional[int] = None,height: Optional[int] = None,batch_size: int = 1,+ dense_transformer_mib: Optional[int] = None,+ compute_bytes: int = 2,) -> Optional[int]:- """Measured runtime headroom for ``family`` at this size, or None (unmeasured: use the flat estimate)."""+ """Measured runtime headroom for ``family`` at this size, or None (unmeasured: use the flat estimate).+ ``dense_transformer_mib`` selects the dense eager table; ``compute_bytes`` scales it (fp32 Qwen-Image: 8480 vs 4248)."""if _env_off(MEASURED_ACTIVATION_ENV):return None- peak = _MEASURED_IMAGE_PEAK_MIB.get(str(family or "").lower())- if peak is None or str(speed_mode or "") not in _MEASURED_PEAK_SPEED_MODES:- return None+ if dense_transformer_mib is not None:+ if _env_off(MEASURED_ACTIVATION_DENSE_ENV):+ return None+ entry = _MEASURED_DENSE_EAGER_PEAK_MIB.get(str(family or "").lower())+ if entry is None or str(speed_mode or "") not in _MEASURED_DENSE_SPEED_MODES:+ return None+ peak, max_dit = entry+ widen = max(2, int(compute_bytes or 2))+ peak, max_dit = peak * widen // 2, max_dit * widen // 2+ if int(dense_transformer_mib) <= 0 or int(dense_transformer_mib) > max_dit:+ return None+ else:+ peak = _MEASURED_IMAGE_PEAK_MIB.get(str(family or "").lower())+ if peak is None or str(speed_mode or "") not in _MEASURED_PEAK_SPEED_MODES:+ return Nonew = max(64, int(width or DEFAULT_IMAGE_WIDTH))h = max(64, int(height or DEFAULT_IMAGE_HEIGHT))scale = max(@@ -2242,6 +2283,20 @@ def _loaded_component_mib(pipe: Any) -> Optional[dict[str, tuple[int, str]]]:return None+def _denoiser_compute_bytes(pipe: Any) -> Optional[int]:+ """Denoiser compute element size for the dense table: 2 (fp16), 4 (fp32); None for bf16 / unreadable."""+ try:+ import torch+ for name in ("transformer", "unet"):+ module = getattr(pipe, name, None)+ dtype = getattr(module, "dtype", None) if module is not None else None+ if dtype is not None:+ return {torch.float16: 2, torch.float32: 4}.get(dtype)+ except Exception: # noqa: BLE001+ pass+ return None++def refine_plan_from_loaded_weights(pipe: Any,plan: MemoryPlan,@@ -2253,7 +2308,7 @@ def refine_plan_from_loaded_weights("""Re-place a streamed ``auto`` load from its LOADED weights and the family's measured activation peak.Keeps the flat plan's offload hooks and makes whole groups resident (denoiser first, then encoders) within the- safe budget left after the measured peak x margin and the base overhead. No-op for explicit modes, non-CUDA / unified memory, unmeasured families+ safe budget left after the measured peak x margin and the base overhead. No-op for explicit modes, non-CUDA / unified memory, unmeasured families (dense denoisers: the eager-tier table)or speed tiers, non-torchao denoisers and ``model`` plans."""try:if getattr(plan, "requested_mode", None) != MEMORY_MODE_AUTO:@@ -2264,11 +2319,6 @@ def refine_plan_from_loaded_weights(memory = plan.device_memoryif memory.is_unified or getattr(memory, "device", None) != "cuda":return plan- if not _pipe_denoisers_hold_torchao(pipe):- return plan- headroom = measured_image_runtime_mib(family, speed_mode)- if headroom is None:- return planbudget = plan.estimates.get("safe_device_budget_mib")if budget is None:return plan@@ -2281,11 +2331,23 @@ def refine_plan_from_loaded_weights(other = sum(m for m, r in sizes.values() if r == "other")if dit <= 0:return plan+ dense_mib = None if _pipe_denoisers_hold_torchao(pipe) else dit+ compute_bytes = _denoiser_compute_bytes(pipe)+ if dense_mib is not None and (compute_bytes is None or _pipe_denoisers_hold_packed(pipe)):+ # measured on fp16 / fp32 cards only; bf16 cards can compile later+ return plan+ headroom = measured_image_runtime_mib(+ family, speed_mode, dense_transformer_mib = dense_mib, compute_bytes = compute_bytes or 2+ )+ if headroom is None:+ return planoverhead = int(plan.estimates.get("base_overhead_mib") or DEFAULT_BASE_OVERHEAD_MIB)floor = headroom + overhead + otherestimates = dict(plan.estimates)estimates.update(measured_runtime_headroom_mib = headroom,+ measured_dense_transformer_mib = dense_mib,+ measured_compute_bytes = compute_bytes,loaded_transformer_mib = dit,loaded_text_encoder_mib = encoders,loaded_other_mib = other,@@ -2529,9 +2591,17 @@ def measured_request_extra_mib(reserve = getattr(pipe, "_unsloth_measured_reserve", None)if not reserve:return 0- headroom, family, speed_mode = reserve+ headroom, family, speed_mode = reserve[:3]+ dense_mib = reserve[3] if len(reserve) > 3 else None+ compute_bytes = reserve[4] if len(reserve) > 4 and reserve[4] else 2need = measured_image_runtime_mib(- family, speed_mode, width = width, height = height, batch_size = batch_size+ family,+ speed_mode,+ width = width,+ height = height,+ batch_size = batch_size,+ dense_transformer_mib = dense_mib,+ compute_bytes = compute_bytes,)if need is None:return 0@@ -3444,6 +3514,10 @@ def _apply_group_offload(logger,)gkwargs["low_cpu_mem_usage"] = not pin_streamed[0]+ if getattr(pipe, "_unsloth_small_host", None) and "low_cpu_mem_usage" in _params:+ # pinning would copy the small-host route's memory-mapped bytes back into host RAM+ pin_streamed = (False, False)+ gkwargs["low_cpu_mem_usage"] = True# ``background_pin``: a module the plan pins is applied unpinned and handed to a _GroupPinner, which the caller# starts with start_background_pins once the load has committed.if background_pin is None:diff --git a/studio/backend/core/inference/diffusion_small_host.py b/studio/backend/core/inference/diffusion_small_host.pynew file mode 100644index 00000000000..1b9a4824222--- /dev/null+++ b/studio/backend/core/inference/diffusion_small_host.py@@ -0,0 +1,481 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Small-host load route: a bf16 repo loaded at fp16/fp32 materialises every converted weight in anonymous host RAM+(FLUX.1 at fp16: 35 GB, OOM-killed on a 31 GB host before the planner runs). Engaged only when that dense load would+not fit: big components load at their stored bf16 (memory-mapped), encoders stream with layerwise casting, a streamed+denoiser is stored as int8 per-channel weights. ``UNSLOTH_DIFFUSION_SMALL_HOST=0|1`` disables / forces it;+``UNSLOTH_DIFFUSION_HOST_RAM_CHECK=0`` skips the pre-load refusal.+"""++from __future__ import annotations++import json+import os+import struct+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any, Optional++SMALL_HOST_ENV = "UNSLOTH_DIFFUSION_SMALL_HOST"+HOST_RAM_CHECK_ENV = "UNSLOTH_DIFFUSION_HOST_RAM_CHECK"+SMALL_HOST_ATTR = "_unsloth_small_host"++_MIB = 1024 * 1024+_STREAM_MIN_MIB = 512+_HOST_RESERVE_MIN_MIB = 3072+_HOST_RESERVE_FRACTION = 0.10+# fp16 T5 keeps ``wo`` in fp32 (``_keep_in_fp32_modules``): 9.5 GB stored, 11.0 GB loaded.+_CONVERT_MARGIN = 1.15+_INT8_MIN_ELEMENTS = 1 << 22+# DiT denoisers the route stores as int8; a UNet (mostly convs) converts dense like any other non-encoder component+INT8_DENOISER_NAMES = ("transformer", "transformer_2", "unconditional_transformer")+++def _env(name: str) -> str:+ return (os.environ.get(name) or "").strip().lower()+++def small_host_disabled() -> bool:+ return _env(SMALL_HOST_ENV) in ("0", "off", "false", "no")+++def small_host_forced() -> bool:+ return _env(SMALL_HOST_ENV) in ("1", "on", "true", "yes", "force")+++def host_ram_check_disabled() -> bool:+ return _env(HOST_RAM_CHECK_ENV) in ("0", "off", "false", "no")+++_ST_DTYPES = {"BF16": "bfloat16", "F16": "float16", "F32": "float32"}+++def _safetensors_bytes_by_dtype(path: Path, keep: tuple[str, ...] = ()) -> dict[str, int]:+ out: dict[str, int] = {}+ try:+ with open(path, "rb") as fh:+ (n,) = struct.unpack("<Q", fh.read(8))+ if not 0 < n <= 256 * _MIB:+ return out+ header = json.loads(fh.read(n))+ except Exception: # noqa: BLE001 - unreadable header: no claim about this file+ return out+ for name, meta in header.items():+ if name == "__metadata__":+ continue+ try:+ start, end = meta["data_offsets"]+ key = _ST_DTYPES.get(str(meta.get("dtype")), str(meta.get("dtype")).lower())+ out[key] = out.get(key, 0) + int(end) - int(start)+ if keep and any(f".{k}." in f".{name}." for k in keep):+ out["kept"] = out.get("kept", 0) + int(end) - int(start)+ except Exception: # noqa: BLE001+ continue+ return out+++@dataclass(frozen = True)+class StoredComponent:+ name: str+ mib: int+ dtype: str # dominant stored float dtype ("bfloat16", "float16", "float32", ...)+ # stored MiB of ``_keep_in_fp32_modules`` tensors: they convert to fp32 on the host even on the route+ kept_fp32_mib: int = 0+++def _keep_fp32_from_config(sub: Path) -> tuple[str, ...]:+ try:+ arch = (+ json.loads((sub / "config.json").read_text(encoding = "utf-8")).get("architectures")+ or [None]+ )[0]+ if not arch:+ return ()+ import transformers++ return _keep_fp32_patterns(getattr(transformers, str(arch), None))+ except Exception: # noqa: BLE001+ return ()+++def _weight_files(sub: Path) -> list[Path]:+ files = sorted(sub.glob("*.safetensors"))+ # ``model.fp16.safetensors`` next to ``model.safetensors`` is a variant from_pretrained does not read+ plain = [f for f in files if "." not in f.name[: -len(".safetensors")]]+ return plain or files+++def stored_components(snapshot: Any) -> dict[str, StoredComponent]:+ """Per component: stored MiB and dominant dtype, from safetensors headers only."""+ out: dict[str, StoredComponent] = {}+ try:+ root = Path(snapshot)+ if not root.is_dir():+ return out+ for sub in sorted(p for p in root.iterdir() if p.is_dir()):+ totals: dict[str, int] = {}+ keep = _keep_fp32_from_config(sub) if sub.name.startswith("text_encoder") else ()+ for f in _weight_files(sub):+ for k, v in _safetensors_bytes_by_dtype(f, keep).items():+ totals[k] = totals.get(k, 0) + v+ kept = totals.pop("kept", 0)+ if not totals:+ continue+ dtype = max(totals.items(), key = lambda kv: kv[1])[0]+ out[sub.name] = StoredComponent(+ sub.name, -(-sum(totals.values()) // _MIB), dtype, -(-kept // _MIB)+ )+ except Exception: # noqa: BLE001 - no claim+ return {}+ return out+++def resolve_snapshot_dir(repo_or_dir: Any, cache_dir: Any = None) -> Optional[Path]:+ """Local diffusers dir for a repo id (cache only) or path."""+ try:+ p = Path(str(repo_or_dir)).expanduser()+ if p.is_dir():+ return p+ from huggingface_hub import try_to_load_from_cache++ hit = try_to_load_from_cache(str(repo_or_dir), "model_index.json", cache_dir = cache_dir)+ if isinstance(hit, str):+ return Path(hit).parent+ except Exception: # noqa: BLE001+ return None+ return None+++def host_ram_mib() -> tuple[Optional[int], Optional[int]]:+ """(total, available) host MiB, both capped by an enforcing cgroup."""+ from .diffusion_memory import (+ _available_system_memory_mib,+ _cgroup_memory_limit_mib,+ _system_memory_mib,+ )++ total, _ = _system_memory_mib()+ available = _available_system_memory_mib()+ limit = _cgroup_memory_limit_mib()+ if total is not None and limit is not None:+ total = min(int(total), int(limit))+ return total, available+++def host_reserve_mib(total_mib: Optional[int]) -> int:+ return max(_HOST_RESERVE_MIN_MIB, int((total_mib or 0) * _HOST_RESERVE_FRACTION))+++def _dtype_name(dtype: Any) -> str:+ return str(dtype).replace("torch.", "")+++def _itemsize(name: str) -> int:+ return {"float32": 4, "bfloat16": 2, "float16": 2, "float8_e4m3fn": 1, "float8_e5m2": 1}.get(+ name, 2+ )+++@dataclass(frozen = True)+class SmallHostDecision:+ engaged: bool+ reason: str+ available_mib: Optional[int] = None+ total_mib: Optional[int] = None+ dense_host_mib: int = 0+ route_host_mib: int = 0+ # component -> stored dtype it loads at (memory-mapped)+ storage_dtypes: dict[str, str] = field(default_factory = dict)+ refuse: Optional[str] = None+++def decide_small_host(+ components: dict[str, StoredComponent],+ compute_dtype: Any,+ *,+ device: str,+ host_total_mib: Optional[int],+ host_available_mib: Optional[int],+ lora_active: bool = False,+) -> SmallHostDecision:+ """Whether this pipeline load takes the small-host route. Only CUDA loads converting large bf16 components+ (fp16 / fp32 compute) change; same-dtype loads already stay memory-mapped."""+ if small_host_disabled():+ return SmallHostDecision(False, f"{SMALL_HOST_ENV}=0")+ if str(device) != "cuda":+ return SmallHostDecision(False, "not a CUDA load")+ compute = _dtype_name(compute_dtype)+ if compute not in ("float16", "float32"):+ return SmallHostDecision(False, f"compute dtype {compute} needs no conversion")+ converted = {+ name: comp+ for name, comp in components.items()+ if comp.dtype == "bfloat16" and comp.mib >= _STREAM_MIN_MIB+ }+ if not converted:+ return SmallHostDecision(False, "no large bf16 component to convert")+ dense = int(+ sum(c.mib * _itemsize(compute) / _itemsize(c.dtype) for c in converted.values())+ * _CONVERT_MARGIN+ )+ # encoders stay memory-mapped except fp32-kept layers; a DiT lands as int8+ route = sum(+ c.mib // 2+ if n in INT8_DENOISER_NAMES+ else c.kept_fp32_mib * 4 // _itemsize(c.dtype)+ if n.startswith("text_encoder")+ else c.mib * _itemsize(compute) // _itemsize(c.dtype)+ for n, c in converted.items()+ )+ reserve = host_reserve_mib(host_total_mib)+ storage = {name: comp.dtype for name, comp in converted.items()}+ forced = small_host_forced()+ if host_available_mib is None and not forced:+ return SmallHostDecision(False, "host RAM unreadable", dense_host_mib = dense)+ fits = host_available_mib is not None and dense + reserve <= int(host_available_mib)+ if fits and not forced:+ return SmallHostDecision(+ False,+ f"dense {compute} load ({dense} MiB) fits {host_available_mib} MiB available host RAM",+ host_available_mib,+ host_total_mib,+ dense,+ route,+ )+ if lora_active and not forced:+ # the int8 denoiser cannot carry adapters+ return SmallHostDecision(+ False,+ f"LoRA adapters need the dense denoiser (dense load ~{dense} MiB, {host_available_mib} MiB available)",+ host_available_mib,+ host_total_mib,+ dense,+ route,+ )+ refuse = None+ if (+ host_available_mib is not None+ and route + reserve > int(host_available_mib)+ and not host_ram_check_disabled()+ ):+ refuse = _refusal(route, reserve, host_available_mib, "even the low-memory route")+ why = (+ f"{SMALL_HOST_ENV}=1"+ if forced and fits+ else f"dense {compute} load needs ~{dense} MiB + {reserve} MiB reserve of host RAM, "+ f"{host_available_mib} MiB available"+ )+ return SmallHostDecision(+ True, why, host_available_mib, host_total_mib, dense, route, storage, refuse+ )+++def _refusal(need: int, reserve: int, available: Optional[int], what: str) -> str:+ return (+ f"Not enough system RAM to load this model: {what} needs about {(need + reserve) / 1024:.1f} GB "+ f"of host memory and {((available or 0)) / 1024:.1f} GB is available. Close other applications, "+ f"pick a smaller or GGUF model, or set {HOST_RAM_CHECK_ENV}=0 to try anyway."+ )+++def torch_dtype_map(decision: SmallHostDecision, compute_dtype: Any) -> Any:+ """``torch_dtype`` for ``DiffusionPipeline.from_pretrained``: stored dtype for the routed components."""+ if not decision.engaged or not decision.storage_dtypes:+ return compute_dtype+ import torch++ mapping: dict[str, Any] = {"default": compute_dtype}+ for name, dtype in decision.storage_dtypes.items():+ mapping[name] = getattr(torch, dtype)+ return mapping+++def _int8_linear_class():+ import torch+ import torch.nn.functional as F++ class Int8WeightLinear(torch.nn.Module):+ """Linear with int8 per-output-channel weights, dequantised to the input dtype for each forward."""++ def __init__(self, qweight, scale, bias, in_features: int, out_features: int):+ super().__init__()+ self.in_features = in_features+ self.out_features = out_features+ 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)++ def forward(self, x):+ w = self.qweight.to(x.dtype) * self.scale.to(x.dtype)+ return F.linear(x, w, None if self.bias is None else self.bias.to(x.dtype))++ def extra_repr(self) -> str:+ return f"in_features={self.in_features}, out_features={self.out_features}, int8 weight"++ return Int8WeightLinear+++_INT8_CLS = None+++def int8_linear_class():+ global _INT8_CLS+ if _INT8_CLS is None:+ _INT8_CLS = _int8_linear_class()+ return _INT8_CLS+++def quantize_int8_weight_(+ module: Any,+ *,+ compute_dtype: Any,+ work_device: Any,+ keep_device: Any = "cpu",+) -> 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``."""+ import torch++ cls = int8_linear_class()+ work = torch.device(work_device)+ keep = torch.device(keep_device)+ stats = {"linears": 0, "dense_linears": 0, "int8_bytes": 0}+ targets = [+ (name, child) for name, child in module.named_modules() if type(child) is torch.nn.Linear+ ]+ for name, lin in targets:+ if lin.weight.numel() < _INT8_MIN_ELEMENTS:+ stats["dense_linears"] += 1+ continue+ with torch.no_grad():+ w = lin.weight.detach().to(work, non_blocking = False).float()+ scale = w.abs().amax(dim = 1, keepdim = True).clamp_min(1e-12) / 127.0+ q = torch.round(w / scale).clamp_(-127, 127).to(torch.int8)+ bias = None if lin.bias is None else lin.bias.detach().to(keep, compute_dtype)+ new = cls(+ q.to(keep),+ scale.to(compute_dtype).to(keep),+ bias,+ lin.in_features,+ lin.out_features,+ )+ del w, q, scale+ parent_name, _, attr = name.rpartition(".")+ parent = module.get_submodule(parent_name) if parent_name else module+ setattr(parent, attr, new)+ stats["linears"] += 1+ stats["int8_bytes"] += new.qweight.numel()+ with torch.no_grad():+ for sub in module.modules():+ if isinstance(sub, cls):+ continue+ for pname, p in list(sub.named_parameters(recurse = False)):+ if p.dtype == torch.bfloat16 and p.dtype != compute_dtype:+ p.data = p.data.to(keep, compute_dtype)+ elif p.device != keep:+ p.data = p.data.to(keep)+ for bname, b in list(sub.named_buffers(recurse = False)):+ if b is not None and b.dtype == torch.bfloat16 and b.dtype != compute_dtype:+ sub._buffers[bname] = b.to(keep, compute_dtype)+ if work.type == "cuda":+ torch.cuda.empty_cache()+ return stats+++def _keep_fp32_patterns(module: Any) -> tuple[str, ...]:+ pats = getattr(module, "_keep_in_fp32_modules", None) or ()+ strict = getattr(module, "_keep_in_fp32_modules_strict", None) or ()+ return tuple(str(p) for p in (*pats, *strict))+++def cast_resident_(module: Any, device: Any, compute_dtype: Any) -> None:+ """Move ``module`` to ``device`` one tensor at a time, cast as the dense load would (fp32 for kept modules)."""+ import torch++ dev = torch.device(device)+ keep = _keep_fp32_patterns(module)+ with torch.no_grad():+ for mname, sub in module.named_modules():+ want = torch.float32 if keep and any(k in mname for k in keep) else compute_dtype+ for pname, p in list(sub.named_parameters(recurse = False)):+ dt = want if p.dtype == torch.bfloat16 else p.dtype+ p.data = p.data.to(dev).to(dt)+ for bname, b in list(sub.named_buffers(recurse = False)):+ if b is None:+ continue+ dt = want if b.dtype == torch.bfloat16 else b.dtype+ sub._buffers[bname] = b.to(dev).to(dt)+++def prepare_streamed_encoder_(module: Any, compute_dtype: Any) -> int:+ """Layerwise-cast a memory-mapped bf16 encoder: Linear / Embedding weights keep their stored dtype, everything+ else converts now, including the owner of the first float parameter (``module.dtype`` sets the prompt-embedding+ dtype). Returns the MiB left memory-mapped."""+ import torch+ from diffusers.hooks import apply_layerwise_casting++ keep = _keep_fp32_patterns(module)+ streamable = (torch.nn.Linear, torch.nn.Embedding)++ def _kept(mname: str) -> bool:+ return bool(keep) and any(k in mname for k in keep)++ def _want(mname: str) -> Any:+ return torch.float32 if _kept(mname) else compute_dtype++ def _convert(sub: Any, want: Any) -> None:+ # fp32 buffers (RoPE ``inv_freq``) stay fp32, as in the dense load+ for pname, p in list(sub.named_parameters(recurse = False)):+ if p.dtype == torch.bfloat16 and p.dtype != want:+ p.data = p.data.to(want)+ for bname, b in list(sub.named_buffers(recurse = False)):+ if b is not None and b.dtype == torch.bfloat16 and b.dtype != want:+ sub._buffers[bname] = b.to(want)++ first_owner = None+ for pname, p in module.named_parameters():+ if p.is_floating_point():+ first_owner = pname.rpartition(".")[0]+ break+ streamed = 0+ with torch.no_grad():+ for mname, sub in module.named_modules():+ want = _want(mname)+ # kept-fp32 Linears convert now: T5 casts its input to ``wo.weight.dtype`` before the hook runs+ if (+ type(sub) in streamable+ and not _kept(mname)+ and mname != first_owner+ and sub.weight.dtype != want+ ):+ storage = sub.weight.dtype+ streamed += sub.weight.numel() * sub.weight.element_size()+ apply_layerwise_casting(+ sub,+ storage_dtype = storage,+ compute_dtype = want,+ skip_modules_pattern = None,+ skip_modules_classes = None,+ )+ continue+ _convert(sub, want)+ return streamed // _MIB+++def module_dtype_ok(module: Any, compute_dtype: Any) -> bool:+ try:+ return getattr(module, "dtype", compute_dtype) == compute_dtype+ except Exception: # noqa: BLE001+ return True+++def mark(pipe: Any, info: dict) -> None:+ try:+ setattr(pipe, SMALL_HOST_ATTR, dict(info))+ except Exception: # noqa: BLE001+ pass+++def engaged_on(pipe: Any) -> Optional[dict]:+ return getattr(pipe, SMALL_HOST_ATTR, None)diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.pyindex d9b8854e180..e84f9387477 100644--- a/studio/backend/tests/test_diffusion_backend.py+++ b/studio/backend/tests/test_diffusion_backend.py@@ -3858,10 +3858,10 @@ def test_plan_memory_sizes_the_mirrored_companion_cache(monkeypatch, tmp_path):def test_zimage_is_fp16_incompatible():- # Only Z-Image-class families carry the guard (their activations overflow fp16).+ # Only families whose activations overflow fp16 carry the guard: Z-Image, and Qwen-Image (NaN latents, black).assert detect_family("unsloth/Z-Image-Turbo-GGUF").fp16_incompatible is Trueassert detect_family("unsloth/Z-Image-GGUF").fp16_incompatible is True- assert detect_family("unsloth/Qwen-Image-2512-GGUF").fp16_incompatible is False+ assert detect_family("unsloth/Qwen-Image-2512-GGUF").fp16_incompatible is Trueassert detect_family("unsloth/FLUX.1-schnell-GGUF").fp16_incompatible is Falseassert detect_family("unsloth/FLUX.2-klein-4B-GGUF").fp16_incompatible is False@@ -3869,7 +3869,7 @@ def test_zimage_is_fp16_incompatible():def test_resolve_compute_dtype_promotes_fp16_for_zimage(fake_runtime):torch = sys.modules["torch"]z = detect_family("unsloth/Z-Image-GGUF")- q = detect_family("unsloth/Qwen-Image-GGUF")+ q = detect_family("unsloth/FLUX.1-schnell-GGUF")# Z-Image: fp16 promotes to fp32; bf16 / fp32 pass through unchanged.assert _resolve_diffusion_compute_dtype(z, torch.float16) is torch.float32assert _resolve_diffusion_compute_dtype(z, torch.bfloat16) is torch.bfloat16@@ -3881,7 +3881,8 @@ def test_resolve_compute_dtype_promotes_fp16_for_zimage(fake_runtime):def test_load_promotes_fp16_to_fp32_for_zimage_only(fake_runtime, monkeypatch, tmp_path):torch = sys.modules["torch"]- # Pre-Ampere CUDA resolves to fp16, so the guard must promote Z-Image (and only Z-Image) to fp32 or it renders black.+ # Pre-Ampere CUDA resolves to fp16, so the guard must promote Z-Image (and only fp16-incompatible families) to fp32+ # or it renders black.monkeypatch.setattr(torch.cuda, "is_available", lambda: True, raising = False)monkeypatch.setattr(torch.cuda, "get_device_capability", lambda: (7, 5), raising = False)(tmp_path / "m.gguf").write_bytes(b"x")@@ -3893,8 +3894,11 @@ def test_load_promotes_fp16_to_fp32_for_zimage_only(fake_runtime, monkeypatch, t# The promoted dtype reaches the transformer build (and thus the quant config).assert str(_FakeTransformer.last["torch_dtype"]) == "torch.float32"+ diffusers = sys.modules["diffusers"]+ monkeypatch.setattr(diffusers, "FluxPipeline", _FakePipeline, raising = False)+ monkeypatch.setattr(diffusers, "FluxTransformer2DModel", _FakeTransformer, raising = False)q = DiffusionBackend().load_pipeline(- str(tmp_path), gguf_filename = "m.gguf", family_override = "qwen-image"+ str(tmp_path), gguf_filename = "m.gguf", family_override = "flux.1")assert q["dtype"] == "float16" # fp16-compatible family keeps fp16 on pre-Amperediff --git a/studio/backend/tests/test_diffusion_measured_placement_dense.py b/studio/backend/tests/test_diffusion_measured_placement_dense.pynew file mode 100644index 00000000000..3b2e54ba955--- /dev/null+++ b/studio/backend/tests/test_diffusion_measured_placement_dense.py@@ -0,0 +1,203 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Measured-activation placement for DENSE denoisers on the eager tier (``diffusion_memory.py``).++The planner inputs are the estimates a FLUX.2-klein-4B auto load logged on a 15 GB T4 (fp16, speed off, no+transformer quant): ``safe_device_budget_mib 12758, model_dense_mib 15258, companion_dense_mib 7820,+text_encoder_dense_mib 7629, runtime_headroom_mib 8192`` gave ``resident_transformer_floor_mib 17869`` and streamed+the 7.4 GB DiT every step. Measured fp16 eager peak above the resident weights at 1024x1024: 2455 MiB. CPU-only; the+loaded sizes and the torchao check are stubbed.+"""++from __future__ import annotations++import types++import pytest++import core.inference.diffusion_memory as dm++KLEIN_LOADED = {+ "transformer": (7393, "dit"),+ "text_encoder": (7673, "text_encoder"),+ "vae": (160, "other"),+}+KLEIN_FLAT = dict(model_dense_mib = 15258, companion_dense_mib = 7820, text_encoder_dense_mib = 7629)+T4_TOTAL = 15095+KLEIN_HEADROOM = 3072 # 2455 x 1.15, rounded up to 256 MiB+ENVS = (+ "UNSLOTH_DIFFUSION_MEASURED_ACTIVATION",+ "UNSLOTH_DIFFUSION_MEASURED_ACTIVATION_DENSE",+ "UNSLOTH_DIFFUSION_PARTIAL_RESIDENT",+)+++def _memory(budget_mib: int, total_mib: int) -> "dm.DeviceMemory":+ reserve = dm._reserve_mib("discrete_vram", total_mib)+ return dm.DeviceMemory("cuda", "cuda", "discrete_vram", budget_mib + reserve, total_mib)+++def _flat_plan(+ budget_mib: int,+ total_mib: int = T4_TOTAL,+ mode = None,+):+ return dm.plan_diffusion_memory(+ target = types.SimpleNamespace(supports_model_cpu_offload = True),+ device_memory = _memory(budget_mib, total_mib),+ runtime_headroom_mib = dm.estimate_image_runtime_mib(+ width = None, height = None, family = "flux.2-klein"+ ),+ requested_mode = mode,+ **KLEIN_FLAT,+ )+++def klein_pipe(monkeypatch):+ for name in ENVS:+ monkeypatch.delenv(name, raising = False)+ monkeypatch.setattr(dm, "_loaded_component_mib", lambda pipe: dict(KLEIN_LOADED))+ monkeypatch.setattr(dm, "_pipe_denoisers_hold_torchao", lambda pipe: False)+ import torch++ # fp16 on the T4: the compute dtype the dense eager table was measured at+ return types.SimpleNamespace(transformer = types.SimpleNamespace(dtype = torch.float16))+++def _refine(+ pipe,+ plan,+ family = "flux.2-klein",+ speed = "off",+):+ return dm.refine_plan_from_loaded_weights(pipe, plan, family = family, speed_mode = speed)+++def test_dense_headroom_values(klein_pipe, monkeypatch):+ m = dm.measured_image_runtime_mib+ assert m("flux.2-klein", "off", dense_transformer_mib = 7393) == KLEIN_HEADROOM+ assert m("flux.1", "off", dense_transformer_mib = 22680) == 2816+ assert m("qwen-image", "off", dense_transformer_mib = 38968) == 5120+ assert m("flux.2-klein", "off", dense_transformer_mib = 7393, width = 2048, height = 2048) == 11520+ # compiled tiers, unmeasured families and a larger DiT of the same family (klein-9B) keep the flat estimate+ assert m("flux.2-klein", "default", dense_transformer_mib = 7393) is None+ assert m("sdxl", "off", dense_transformer_mib = 4900) is None+ assert m("flux.2-klein", "off", dense_transformer_mib = 17300) is None+ # the torchao table is untouched by the dense one+ assert m("flux.2-klein", "off") is None+ monkeypatch.setenv("UNSLOTH_DIFFUSION_MEASURED_ACTIVATION_DENSE", "0")+ assert m("flux.2-klein", "off", dense_transformer_mib = 7393) is None+ assert m("qwen-image-2.1", "default") == 2304+ monkeypatch.delenv("UNSLOTH_DIFFUSION_MEASURED_ACTIVATION_DENSE")+ monkeypatch.setenv("UNSLOTH_DIFFUSION_MEASURED_ACTIVATION", "0")+ assert m("flux.2-klein", "off", dense_transformer_mib = 7393) is None+++def test_t4_klein_transformer_resident(klein_pipe):+ plan = _flat_plan(12758)+ # the logged flat decision: every DiT block streamed, encoders streamed+ assert plan.estimates["resident_transformer_floor_mib"] == 17869+ assert plan.offload_policy == dm.OFFLOAD_GROUP+ assert plan.stream_transformer and plan.stream_text_encoders+ new = _refine(klein_pipe, plan)+ assert (new.offload_policy, new.stream_transformer, new.stream_text_encoders) == (+ dm.OFFLOAD_GROUP,+ True,+ True,+ )+ assert new.resident_transformer_mib == 7393+ assert new.estimates["measured_runtime_headroom_mib"] == KLEIN_HEADROOM+ assert new.estimates["measured_dense_transformer_mib"] == 7393+ assert 7393 + 160 + KLEIN_HEADROOM + dm.DEFAULT_BASE_OVERHEAD_MIB <= 12758++[email protected]("env", ENVS[:2])+def test_kill_switches_restore_flat_plan(klein_pipe, monkeypatch, env):+ plan = _flat_plan(12758)+ monkeypatch.setenv(env, "0")+ assert _refine(klein_pipe, plan) is plan+++def test_large_card_and_other_tiers_untouched(klein_pipe):+ resident = _flat_plan(160000, 183359)+ assert resident.offload_policy == dm.OFFLOAD_NONE+ assert _refine(klein_pipe, resident) is resident+ plan = _flat_plan(12758)+ assert _refine(klein_pipe, plan, speed = "default") is plan+ assert _refine(klein_pipe, plan, family = "sdxl") is plan+ balanced = _flat_plan(12758, mode = "balanced")+ assert _refine(klein_pipe, balanced) is balanced+++def test_bigger_dense_dit_untouched(klein_pipe, monkeypatch):+ monkeypatch.setattr(+ dm,+ "_loaded_component_mib",+ lambda pipe: {**KLEIN_LOADED, "transformer": (17300, "dit")},+ )+ plan = _flat_plan(12758)+ assert _refine(klein_pipe, plan) is plan++[email protected]("budget", list(range(3000, 30001, 250)))+def test_every_budget_fits_measured_need(klein_pipe, budget):+ """Only resident room is ever added, and kept bytes + measured peak x margin + base overhead fit the budget."""+ plan = _flat_plan(budget, max(8188, budget + 2400))+ new = _refine(klein_pipe, plan)+ if new is plan:+ return+ assert (new.offload_policy, new.stream_transformer, new.stream_text_encoders) == (+ plan.offload_policy,+ plan.stream_transformer,+ plan.stream_text_encoders,+ )+ kept = (+ 160+ + (7393 if not new.stream_transformer else int(new.resident_transformer_mib or 0))+ + int(new.resident_text_encoder_mib or 0)+ + (0 if new.stream_text_encoders else 7673)+ )+ assert int(new.resident_transformer_mib or 0) <= 7393+ assert kept + KLEIN_HEADROOM + dm.DEFAULT_BASE_OVERHEAD_MIB <= budget+++def test_dense_request_extra_releases_for_oversized(monkeypatch):+ for name in ENVS:+ monkeypatch.delenv(name, raising = False)+ pipe = types.SimpleNamespace(+ _unsloth_measured_reserve = (KLEIN_HEADROOM, "flux.2-klein", "off", 7393)+ )+ assert dm.measured_request_extra_mib(pipe, width = 1024, height = 1024) == 0+ assert dm.measured_request_extra_mib(pipe, width = 2048, height = 2048) == 11520 - KLEIN_HEADROOM+ assert dm.measured_request_extra_mib(pipe, width = 1024, height = 1024, batch_size = 2) > 0+ # the three-field torchao reserve still reads as before+ q21 = types.SimpleNamespace(_unsloth_measured_reserve = (2304, "qwen-image-2.1", "default"))+ assert dm.measured_request_extra_mib(q21, width = 2048, height = 2048) == 8704 - 2304+++def test_gguf_denoiser_keeps_the_flat_plan(klein_pipe):+ import torch++ class GGUFParameter(torch.nn.Parameter):+ pass++ dit = torch.nn.Linear(4, 4)+ dit.weight = GGUFParameter(dit.weight.data, requires_grad = False)+ klein_pipe.transformer = types.SimpleNamespace(dtype = torch.float16, parameters = dit.parameters)+ # GGUF dequantizes a whole Linear per forward: a transient the dense eager table never measured+ plan = _flat_plan(12758)+ assert _refine(klein_pipe, plan) is plan+++def test_small_host_int8_denoiser_keeps_the_flat_plan(klein_pipe):+ import torch++ import core.inference.diffusion_small_host as sh++ dit = torch.nn.Sequential(torch.nn.Linear(2048, 2048)).to(torch.bfloat16)+ sh.quantize_int8_weight_(dit, compute_dtype = torch.float16, work_device = "cpu")+ klein_pipe.transformer = types.SimpleNamespace(dtype = torch.float16, parameters = dit.parameters)+ plan = _flat_plan(12758)+ assert _refine(klein_pipe, plan) is plandiff --git a/studio/backend/tests/test_diffusion_small_host.py b/studio/backend/tests/test_diffusion_small_host.pynew file mode 100644index 00000000000..71f71fabf07--- /dev/null+++ b/studio/backend/tests/test_diffusion_small_host.py@@ -0,0 +1,318 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Small-host load route (``diffusion_small_host.py``): host-RAM pre-check, decision table, the memory-mapped+conversions, and the plan the route pins.++Sizes are the ones a Kaggle T4 (fp16 only, 15 GB, 31 GB host RAM) sees: FLUX.1-schnell stores a 22.7 GB bf16+transformer and an 8.9 GB bf16 T5; Qwen-Image a 38.9 GB transformer and a 15.8 GB Qwen2.5-VL. CPU only.+"""++from __future__ import annotations++import json+import struct+import types++import pytest+import torch++import core.inference.diffusion_memory as dm+import core.inference.diffusion_small_host as sh++FLUX1 = {+ "transformer": sh.StoredComponent("transformer", 22700, "bfloat16"),+ "text_encoder_2": sh.StoredComponent("text_encoder_2", 9083, "bfloat16"),+ "text_encoder": sh.StoredComponent("text_encoder", 235, "float32"),+ "vae": sh.StoredComponent("vae", 160, "float32"),+}+QWEN = {+ "transformer": sh.StoredComponent("transformer", 38900, "bfloat16"),+ "text_encoder": sh.StoredComponent("text_encoder", 15820, "bfloat16"),+ "vae": sh.StoredComponent("vae", 242, "bfloat16"),+}+KAGGLE_TOTAL = 31 * 1024+KAGGLE_AVAILABLE = 29900++[email protected](autouse = True)+def _clean_env(monkeypatch):+ for name in (sh.SMALL_HOST_ENV, sh.HOST_RAM_CHECK_ENV):+ monkeypatch.delenv(name, raising = False)+++def _decide(+ comps,+ dtype = torch.float16,+ total = KAGGLE_TOTAL,+ available = KAGGLE_AVAILABLE,+ **kw,+):+ return sh.decide_small_host(+ comps,+ dtype,+ device = kw.pop("device", "cuda"),+ host_total_mib = total,+ host_available_mib = available,+ **kw,+ )+++def test_flux1_on_a_31gb_fp16_host_takes_the_route():+ d = _decide(FLUX1)+ assert d.engaged and d.refuse is None+ # only the large bf16 components load memory-mapped; the fp32 CLIP and VAE convert as before+ assert d.storage_dtypes == {"transformer": "bfloat16", "text_encoder_2": "bfloat16"}+ assert d.dense_host_mib > KAGGLE_AVAILABLE+ assert d.route_host_mib == 22700 // 2+++def test_unet_and_large_vae_are_budgeted_at_their_converted_size():+ comps = {+ "unet": sh.StoredComponent("unet", 4900, "bfloat16"),+ "vae": sh.StoredComponent("vae", 600, "bfloat16"),+ "text_encoder_2": sh.StoredComponent("text_encoder_2", 1300, "bfloat16"),+ }+ d = _decide(comps, total = 8 * 1024, available = 6000)+ assert d.engaged+ # only a DiT is stored as int8; the UNet and VAE convert dense on the host, the encoder stays memory-mapped+ assert d.route_host_mib == 4900 + 600+ assert d.refuse is not None+ assert (+ d.route_host_mib+ == _decide(comps, dtype = torch.float32, total = 8 * 1024, available = 6000).route_host_mib // 2+ )+++def test_qwen_image_fp32_promoted_takes_the_route():+ d = _decide(QWEN, dtype = torch.float32)+ assert d.engaged and d.refuse is None+ assert d.dense_host_mib > 2 * (38900 + 15820)+++def test_large_host_and_bf16_cards_are_untouched():+ assert not _decide(FLUX1, total = 230 * 1024, available = 220 * 1024).engaged+ # bf16 compute loads a bf16 repo memory-mapped already: never routed, whatever the host+ assert not _decide(FLUX1, dtype = torch.bfloat16).engaged+ assert not _decide(FLUX1, device = "mps").engaged+ assert not _decide({"transformer": sh.StoredComponent("transformer", 9000, "float16")}).engaged+++def test_kill_switch_and_force(monkeypatch):+ monkeypatch.setenv(sh.SMALL_HOST_ENV, "0")+ assert not _decide(FLUX1).engaged+ monkeypatch.setenv(sh.SMALL_HOST_ENV, "1")+ assert _decide(FLUX1, total = 230 * 1024, available = 220 * 1024).engaged+++def test_refuses_before_loading_when_even_the_route_cannot_fit(monkeypatch):+ d = _decide(QWEN, dtype = torch.float32, total = 16 * 1024, available = 14000)+ assert d.engaged and d.refuse and "Not enough system RAM" in d.refuse+ monkeypatch.setenv(sh.HOST_RAM_CHECK_ENV, "0")+ assert _decide(QWEN, dtype = torch.float32, total = 16 * 1024, available = 14000).refuse is None+++def test_lora_keeps_the_dense_load():+ d = _decide(FLUX1, lora_active = True)+ assert not d.engaged and d.refuse is None and "LoRA" in d.reason+++def test_torch_dtype_map_only_names_routed_components():+ d = _decide(FLUX1)+ m = sh.torch_dtype_map(d, torch.float16)+ assert m == {+ "default": torch.float16,+ "transformer": torch.bfloat16,+ "text_encoder_2": torch.bfloat16,+ }+ assert sh.torch_dtype_map(_decide(FLUX1, available = 10**6), torch.float16) is torch.float16+++def _write_safetensors(path, tensors):+ header, offset = {}, 0+ for name, (dtype, nbytes) in tensors.items():+ header[name] = {+ "dtype": dtype,+ "shape": [nbytes // 2],+ "data_offsets": [offset, offset + nbytes],+ }+ offset += nbytes+ raw = json.dumps(header).encode()+ with open(path, "wb") as fh:+ fh.write(struct.pack("<Q", len(raw)))+ fh.write(raw)+ fh.write(b"\0" * offset)+++def test_stored_components_read_headers_only(tmp_path):+ (tmp_path / "transformer").mkdir()+ (tmp_path / "vae").mkdir()+ (tmp_path / "scheduler").mkdir()+ _write_safetensors(tmp_path / "transformer" / "a.safetensors", {"w": ("BF16", 3 << 20)})+ _write_safetensors(tmp_path / "transformer" / "b.safetensors", {"x": ("F32", 1 << 20)})+ _write_safetensors(tmp_path / "vae" / "v.safetensors", {"w": ("F32", 2 << 20)})+ comps = sh.stored_components(tmp_path)+ assert comps["transformer"] == sh.StoredComponent("transformer", 4, "bfloat16")+ assert comps["vae"].dtype == "float32"+ assert "scheduler" not in comps+ assert sh.resolve_snapshot_dir(tmp_path) == tmp_path+++def test_t5_kept_fp32_layers_are_budgeted_and_variants_ignored(tmp_path):+ te = tmp_path / "text_encoder_2"+ te.mkdir()+ (te / "config.json").write_text(json.dumps({"architectures": ["T5EncoderModel"]}))+ _write_safetensors(+ te / "model.safetensors",+ {+ "encoder.block.0.layer.1.DenseReluDense.wo.weight": ("BF16", 2 << 20),+ "encoder.block.0.layer.1.DenseReluDense.wi.weight": ("BF16", 6 << 20),+ },+ )+ _write_safetensors(te / "model.fp16.safetensors", {"w": ("F16", 8 << 20)})+ comps = sh.stored_components(tmp_path)+ assert comps["text_encoder_2"] == sh.StoredComponent("text_encoder_2", 8, "bfloat16", 2)+ tiny = {+ "transformer": sh.StoredComponent("transformer", 4000, "bfloat16"),+ "text_encoder_2": sh.StoredComponent("text_encoder_2", 9084, "bfloat16", 1920),+ }+ # the streamed encoder's ``wo`` converts to fp32 on the host: 1920 MiB stored -> 3840 MiB loaded+ assert _decide(tiny).route_host_mib == 2000 + 3840+++def test_int8_weight_storage_matches_the_dense_layer():+ torch.manual_seed(0)+ model = torch.nn.Sequential(+ torch.nn.Linear(2048, 4096), torch.nn.LayerNorm(4096), torch.nn.Linear(4096, 16)+ ).to(torch.bfloat16)+ ref = [m.weight.detach().float().clone() for m in (model[0], model[2])]+ stats = sh.quantize_int8_weight_(model, compute_dtype = torch.float32, work_device = "cpu")+ assert stats["linears"] == 1 and stats["dense_linears"] == 1+ big = model[0]+ assert isinstance(big, sh.int8_linear_class()) and big.qweight.dtype == torch.int8+ assert model[1].weight.dtype == torch.float32 and model[2].weight.dtype == torch.float32+ x = torch.randn(8, 2048)+ out = big(x)+ want = torch.nn.functional.linear(x, ref[0], model[0].bias.float())+ rel = (out - want).norm() / want.norm()+ assert rel < 0.01, rel+++def test_streamed_encoder_keeps_linear_storage_and_reports_compute_dtype():+ pytest.importorskip("diffusers")+ from diffusers.hooks import HookRegistry++ class Block(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.wi = torch.nn.Linear(64, 128, bias = False)+ self.wo = torch.nn.Linear(128, 64, bias = False)++ def forward(self, x):+ # T5's pattern: the parent reads wo.weight.dtype BEFORE wo runs+ h = self.wi(x)+ return self.wo(h.to(self.wo.weight.dtype))++ class Enc(torch.nn.Module):+ _keep_in_fp32_modules = ["wo"]++ def __init__(self):+ super().__init__()+ self.embed = torch.nn.Embedding(100, 64)+ self.block = Block()+ self.norm = torch.nn.LayerNorm(64)+ # computed at init, never stored: fp32 in the dense fp16 load too (RoPE inv_freq)+ self.register_buffer("inv_freq", torch.rand(8), persistent = False)++ @property+ def dtype(self):+ return next(p.dtype for p in self.parameters() if p.is_floating_point())++ def forward(self, ids):+ return self.norm(self.block(self.embed(ids)))++ torch.manual_seed(0)+ enc = Enc()+ for p in enc.parameters():+ p.data = p.data.to(+ torch.bfloat16+ ) # the stored-dtype load: parameters bf16, init-time buffers fp32+ dense = Enc()+ dense.load_state_dict({k: v.float() for k, v in enc.state_dict().items()})+ dense.inv_freq = enc.inv_freq.clone()+ sh.prepare_streamed_encoder_(enc, torch.float16)+ assert enc.inv_freq.dtype == torch.float32+ enc_fp16 = enc+ enc = Enc()+ for p in enc.parameters():+ p.data = p.data.to(torch.bfloat16)+ dense.load_state_dict({k: v.float() for k, v in enc.state_dict().items()})+ dense.inv_freq = enc.inv_freq.clone()+ del enc_fp16+ sh.prepare_streamed_encoder_(enc, torch.float32)+ # the first float parameter's owner converts so .dtype reports the compute dtype+ assert enc.dtype == torch.float32+ assert enc.block.wi.weight.dtype == torch.bfloat16 # memory-mapped storage stays+ assert (+ HookRegistry.check_if_exists_or_initialize(enc.block.wi).get_hook("layerwise_casting")+ is not None+ )+ assert enc.block.wo.weight.dtype == torch.float32 # kept-fp32 converts now+ ids = torch.randint(0, 100, (2, 7))+ with torch.no_grad():+ assert torch.equal(enc(ids), dense(ids)) # bf16 -> fp32 is exact+++def _group_plan(**kw):+ memory = dm.DeviceMemory("cuda", "cuda", "discrete_vram", 14647, 15095)+ base = dict(+ requested_mode = dm.MEMORY_MODE_AUTO,+ offload_policy = dm.OFFLOAD_MODEL,+ vae_tiling = False,+ vae_slicing = False,+ device_memory = memory,+ estimates = {+ "safe_device_budget_mib": 12599,+ "runtime_headroom_mib": 3072,+ "base_overhead_mib": 2048,+ },+ )+ base.update(kw)+ return dm.MemoryPlan(**base)+++def test_route_plan_streams_encoders_and_keeps_what_fits(monkeypatch):+ from core.inference.diffusion import DiffusionBackend++ monkeypatch.setattr(+ dm,+ "_loaded_component_mib",+ lambda pipe: {+ "transformer": (11353, "dit"),+ "text_encoder_2": (9346, "text_encoder"),+ "vae": (160, "other"),+ },+ )+ pipe = types.SimpleNamespace(_unsloth_small_host = {"components": {}})+ log = types.SimpleNamespace(info = lambda *a, **k: None)+ plan = DiffusionBackend._small_host_plan(None, pipe, _group_plan(), None, log)+ assert plan.offload_policy == dm.OFFLOAD_GROUP and plan.stream_text_encoders+ assert plan.stream_transformer and plan.resident_transformer_mib == 12599 - 3072 - 2048 - 160+ # a plan that already keeps everything resident, or a pipe the route did not touch, is left alone+ none = _group_plan(offload_policy = dm.OFFLOAD_NONE)+ assert DiffusionBackend._small_host_plan(None, pipe, none, None, log) is none+ other = _group_plan()+ assert DiffusionBackend._small_host_plan(None, object(), other, None, log) is other+++def test_lora_refused_and_status_reports_the_int8_route():+ from core.inference.diffusion import _small_host_int8++ pipe = types.SimpleNamespace(+ _unsloth_small_host = {"components": {"transformer": "int8 weights (1 MiB)"}}+ )+ assert _small_host_int8(pipe)+ assert not _small_host_int8(+ types.SimpleNamespace(_unsloth_small_host = {"components": {"transformer": "cast on device"}})+ )+ assert not _small_host_int8(object())diff --git a/studio/backend/tests/test_diffusion_small_host_planner.py b/studio/backend/tests/test_diffusion_small_host_planner.pynew file mode 100644index 00000000000..79981136207--- /dev/null+++ b/studio/backend/tests/test_diffusion_small_host_planner.py@@ -0,0 +1,69 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Planner inputs the small-host route depends on, kept apart from ``test_diffusion_small_host.py`` so they run+against trees without that module: Qwen-Image computes in fp32 on an fp16-only card (fp16 renders NaN / black), and+the dense measured activation peak scales with that compute dtype. CPU only."""++from __future__ import annotations++import torch++import core.inference.diffusion_memory as dm+++def test_qwen_image_is_fp16_incompatible():+ from core.inference.diffusion import _resolve_diffusion_compute_dtype+ from core.inference.diffusion_families import detect_family+ for name in ("qwen-image", "qwen-image-edit"):+ fam = detect_family("", override = name)+ assert fam.fp16_incompatible, name+ assert _resolve_diffusion_compute_dtype(fam, torch.float16) is torch.float32+ assert _resolve_diffusion_compute_dtype(fam, torch.bfloat16) is torch.bfloat16+++def test_dense_measured_peak_scales_with_fp32_compute(monkeypatch):+ for name in (dm.MEASURED_ACTIVATION_ENV, "UNSLOTH_DIFFUSION_MEASURED_ACTIVATION_DENSE"):+ monkeypatch.delenv(name, raising = False)+ fp16 = dm.measured_image_runtime_mib("qwen-image", "off", dense_transformer_mib = 19525)+ fp32 = dm.measured_image_runtime_mib(+ "qwen-image", "off", dense_transformer_mib = 19525, compute_bytes = 4+ )+ # measured: 4248 MiB above the weights at fp16, 8480 at fp32+ assert fp16 == 5120 and fp32 >= 8480 * 1.15+++def test_dense_table_skips_bf16_denoisers(monkeypatch):+ """The dense eager table was measured on fp16 (and fp32-promoted) cards; a bf16 card keeps the flat plan."""+ import types++ for name in (+ dm.MEASURED_ACTIVATION_ENV,+ "UNSLOTH_DIFFUSION_MEASURED_ACTIVATION_DENSE",+ dm.PARTIAL_RESIDENT_ENV,+ ):+ monkeypatch.delenv(name, raising = False)+ monkeypatch.setattr(+ dm,+ "_loaded_component_mib",+ lambda pipe: {+ "transformer": (22700, "dit"),+ "text_encoder_2": (9346, "text_encoder"),+ "vae": (160, "other"),+ },+ )+ monkeypatch.setattr(dm, "_pipe_denoisers_hold_torchao", lambda pipe: False)+ memory = dm.DeviceMemory("cuda", "cuda", "discrete_vram", 24000, 24564)+ plan = dm.MemoryPlan(+ requested_mode = dm.MEMORY_MODE_AUTO,+ offload_policy = dm.OFFLOAD_GROUP,+ vae_tiling = False,+ vae_slicing = False,+ device_memory = memory,+ estimates = {"safe_device_budget_mib": 21500, "base_overhead_mib": 2048},+ stream_text_encoders = True,+ )+ for dtype, kept in ((torch.bfloat16, False), (torch.float16, True)):+ pipe = types.SimpleNamespace(transformer = types.SimpleNamespace(dtype = dtype))+ out = dm.refine_plan_from_loaded_weights(pipe, plan, family = "flux.1", speed_mode = "off")+ assert bool(out.resident_transformer_mib) is kept, dtype