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: refuse a diffusion or video load that cannot fit unified memory (#8213)
Daniel Hana90589529796
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 5d88ccb3c03..99724f6df04 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -25,7 +25,7 @@ import reimport sysimport threadingimport time-from dataclasses import dataclass+from dataclasses import dataclass, replacefrom pathlib import Pathfrom typing import Any, Callable, Optional, Sequence@@ -44,6 +44,7 @@ from .diffusion_families import (DiffusionFamily,assert_flux2_gguf_matches_base,assert_pipeline_class_available,+ _is_local_path,canonical_base,cache_holds_files,default_generation_params,@@ -77,9 +78,11 @@ from .diffusion_memory import (plan_diffusion_memory,plan_fits_total_capacity,raise_on_image_activation_shortfall,+ raise_on_unified_memory_shortfall,reclaimable_snapshot_device_memory,refine_memory_plan_for_components,settled_snapshot_device_memory,+ unified_memory_shortfall_message,)from .diffusion_speed import (SPEED_DEFAULT,@@ -138,6 +141,7 @@ from .diffusion_auto_policy import (RESOLVED_APPLIED,RESOLVED_FELL_BACK,RESOLVED_UNSUPPORTED,+ base_repo_bf16_components_gb,build_resolved_record,family_bf16_components_gb,precision_fallback_allowed,@@ -2625,6 +2629,22 @@ class DiffusionBackend:base_local_dir = _base_local_dir,fetch_base = fetch_base,)+ # On unified memory the plan above is final -- the quant re-plans below are+ # CUDA-only -- and its 'none' policy is a placement, not a fit. Refuse here,+ # after the eviction above freed the previous pipeline (so the free reading is+ # the memory this load actually gets) and before any weight is materialised.+ # A pipeline's weight term is cached SHARD bytes, which is a download size, not a+ # resident one: Z-Image and Lumina ship fp32 shards that halve when loaded as bf16+ # (the size table records 24.6 GB of Z-Image shards as 12.3 GB resident). Refusing+ # on the download figure would turn away a load that fits, so judge the refusal+ # against the table's resident total whenever it knows this base.+ raise_on_unified_memory_shortfall(+ self._resident_sized_plan(+ plan, fam, base, target, kind, text_encoder_quant = text_encoder_quant+ ),+ family = getattr(fam, "name", None),+ logger = logger,+ )# The caller's RAW request, captured before the tri-state below rewrites it: status# has to be able to say "you asked for fp8" long after the loader declined it.@@ -2986,7 +3006,23 @@ class DiffusionBackend:# at the snapshot the load will read, not the live root alone.base_local_dir = _base_local_dir,)- if dense_plan.offload_policy != OFFLOAD_NONE:+ # On unified memory the policy cannot express a misfit -- the planner+ # returns 'none' for ANY size there, because offload shuffles bytes+ # within one pool -- so the check above never fires and the dense build+ # proceeds to be OS-killed. Size it explicitly instead, and decline to+ # the packed GGUF (which already passed the load-level refusal) rather+ # than raising: a fallback that fits is better than no load at all.+ unified_shortfall = unified_memory_shortfall_message(+ dense_plan, family = getattr(fam, "name", None)+ )+ if unified_shortfall is not None:+ dense_possible = False+ dense_fallback_allowed = False+ dense_decline_reason = (+ "the dense bf16 transformer this quant is built from does not "+ f"fit this device's unified memory ({dense_mib} MiB)"+ )+ elif dense_plan.offload_policy != OFFLOAD_NONE:dense_possible = Falsedense_fallback_allowed = Falsedense_decline_reason = (@@ -3007,6 +3043,72 @@ class DiffusionBackend:"prefetch's capacity gate declined its shards), so the dense bf16 ""build cannot run on this host")+ # A hosted prequant never builds dense, so the check above says nothing+ # about what actually lands. On unified memory that gap is a hole: the+ # OFFLOAD_NONE gate below is satisfied for ANY size there, and an fp8/int8+ # artifact can outweigh the packed GGUF that just passed the load-level+ # refusal (0.55x bf16 against a Q4's ~0.3x), so the load would materialise+ # an unsized transformer and be OS-killed. Size the artifact itself and+ # decline to the GGUF when it does not fit. Unified only: off it, the+ # OFFLOAD_NONE test already carries this and the extra resolve is waste.+ if (+ prequant is not None+ and getattr(plan.device_memory, "memory_kind", None) == "unified_memory"+ ):+ prequant_candidate = resolve_dense_quant_candidate(+ fam = fam,+ target = target,+ requested = transformer_quant,+ base_repo = base,+ prequant_path = transformer_prequant_path,+ force_dense = _has_active_lora(loras),+ logger = logger,+ )+ if (+ prequant_candidate is not None+ and unified_memory_shortfall_message(+ self._plan_memory(+ target,+ single_file_path,+ base,+ fam,+ memory_mode,+ cpu_offload,+ kind = kind,+ repo_id = repo_id,+ fetch_base = fetch_base,+ transformer_resident_override_mib = (+ prequant_candidate.transient_transformer_mib+ ),+ # companions_mib is the DENSE encoder plus the VAE, but+ # assembly is handed text_encoder_quant and injects the+ # pre-cast encoder when one is configured. Price that+ # share the way the load-level plan does, or a footprint+ # that fits is declined on bytes never materialised.+ companion_override_mib = (+ self._precast_scaled_companions_mib(+ prequant_candidate, fam, target, text_encoder_quant+ )+ ),+ ),+ family = getattr(fam, "name", None),+ )+ is not None+ ):+ dense_declined = True+ dense_possible = False+ dense_fallback_allowed = False+ transformer_quant_decline = (+ "the pre-quantised transformer does not fit this device's "+ "unified memory, where offloading it would free nothing, so "+ "the packed GGUF was loaded instead"+ )+ logger.info(+ "diffusion.transformer_quant_declined: the pre-quantised "+ "transformer (%s MiB) does not fit unified memory; "+ "loading the GGUF",+ prequant_candidate.transient_transformer_mib,+ )# A dense misfit with a prequant source only forbids the dense fallback; with# none, auto could still have picked a DIFFERENT scheme that does have a# hosted checkpoint. auto returns one winner, and a winner with no published@@ -3055,12 +3157,24 @@ class DiffusionBackend:transformer_resident_override_mib = (retry_candidate.transient_transformer_mib),- companion_override_mib = retry_candidate.companions_mib,+ # Same pre-cast encoder pricing as the fit check above.+ companion_override_mib = self._precast_scaled_companions_mib(+ retry_candidate, fam, target, text_encoder_quant+ ),)if retry_candidate is not Noneelse None)- if retry_plan is not None and retry_plan.offload_policy == OFFLOAD_NONE:+ if (+ retry_plan is not None+ and retry_plan.offload_policy == OFFLOAD_NONE+ # Same unified caveat as above: 'none' is not a fit there, so the+ # rung being retried has to be sized explicitly before it is pinned.+ and unified_memory_shortfall_message(+ retry_plan, family = getattr(fam, "name", None)+ )+ is None+ ):logger.info("diffusion.transformer_quant: %s has no prequant and cannot ""build dense; retrying auto at %s, whose checkpoint is cached "@@ -3896,6 +4010,120 @@ class DiffusionBackend:pipe.to(device)return pipe+ @staticmethod+ def _precast_scaled_companions_mib(+ candidate: Any, fam: DiffusionFamily, target: Any, text_encoder_quant: Optional[str]+ ) -> Optional[int]:+ """``candidate.companions_mib`` with the text-encoder share priced at the PRE-CAST size+ when this pick takes its encoder from a hosted fp8 checkpoint.++ The estimate is always the DENSE encoder plus the VAE, but assembly is handed+ ``text_encoder_quant`` and injects the pre-cast encoder when one is configured, so the+ unified-memory fit check below would refuse on bytes the load never materialises: for+ FLUX.2-dev's Mistral-24B that is ~17 GB of an encoder the pipeline never builds. Keyed on+ the same ``te_prequant_budget_scale`` the load-level resident plan uses, so a budget cannot+ claim a saving the load does not take. The VAE share is untouched: nothing on this path+ quantises it."""+ companions = getattr(candidate, "companions_mib", None)+ if companions is None:+ return None+ try:+ from .diffusion_te_prequant import te_prequant_budget_scale++ scale = te_prequant_budget_scale(fam, te_quant_mode = text_encoder_quant, target = target)+ encoders = int(getattr(candidate, "text_encoders_mib", 0) or 0)+ if scale == 1.0 or encoders <= 0:+ return int(companions)+ return int(companions) - encoders + int(encoders * scale)+ except Exception: # noqa: BLE001 -- sizing aid only; the dense total still refuses safely+ return int(companions)++ def _resident_sized_plan(+ self,+ plan: Any,+ fam: DiffusionFamily,+ base: str,+ target: DiffusionDeviceTarget,+ kind: str,+ text_encoder_quant: Optional[str] = None,+ ) -> Any:+ """``plan`` with its weight term replaced by the family table's bf16-RESIDENT total, for+ the unified-memory refusal only.++ A full-pipeline plan sizes weights from cached shard bytes, which is what the repo stores,+ not what ends up resident: a family shipping fp32 shards (Z-Image, Lumina) halves on the+ bf16 cast, so the refusal would reject a load that comfortably fits. The table is+ documented as post-cast resident sizes, so it is the right number to refuse on. Only ever+ LOWERS the estimate -- a table that reads higher than the shards (a narrow fp8 base that+ upcasts) is already handled in the plan, and taking the max here would double-count it.+ Left alone entirely for single-file/GGUF kinds, whose on-disk size IS their resident size,+ on any target that is not sized in bf16, and for a LOCAL directory: the table is keyed on+ upstream repo ids, so a local checkpoint can only ever reach the coarse family entry, and+ a family covering more than one size (a local FLUX.2-klein 9B against klein's 4B default)+ would be lowered to a number less than half what it loads. On disk is the measured truth+ there; only a hub id the table actually recognises earns the substitution."""+ try:+ # A whole-pipeline single file (SDXL) carries the U-Net, VAE and text encoders itself,+ # and the base repo is read for config only -- but the plan still adds the base's+ # cached companion weights, so a user who once loaded the full pipeline has those+ # bytes counted twice. Harmless as an offload hint, a rejected load as a hard refusal.+ if kind == "single_file" and getattr(fam, "single_file_is_pipeline", False):+ companion = plan.estimates.get("companion_dense_mib")+ current = plan.estimates.get("model_dense_mib")+ if companion and current is not None and int(companion) < int(current):+ return replace(+ plan,+ estimates = {+ **plan.estimates,+ "model_dense_mib": int(current) - int(companion),+ },+ )+ return plan+ if kind != "pipeline" or _is_local_path(base):+ return plan+ import torch++ if getattr(target, "dtype", None) not in (torch.bfloat16, torch.float16):+ return plan+ # RECOGNISED bases only. The table is keyed on exact upstream ids, so a fine-tune or a+ # renamed mirror the family detector still matches by name would fall through to the+ # coarse family entry -- and for a family carrying two sizes that entry is the smaller+ # one, so a 9B derivative would be lowered to the 4B number and walk past the refusal.+ # Accept the family's own default base and anything with an explicit override; anything+ # else keeps its measured size.+ canonical = canonical_base(base)+ if (+ base_repo_bf16_components_gb(base) is None+ and canonical.lower() != str(getattr(fam, "base_repo", "") or "").lower()+ ):+ return plan+ table = family_bf16_components_gb(fam, base)+ if table is None:+ return plan+ # The table's encoder term is the DENSE one. When this pick takes its encoder pre-cast+ # from a hosted fp8 checkpoint the resident encoder is about 0.65x that, and for a+ # heavyweight one (FLUX.2-dev's Mistral-24B, 48 GB) budgeting the dense figure is tens+ # of GB of weights the pipeline never materialises -- enough to refuse a load that fits.+ # Keyed on te_prequant_sources through the shared helper, the same resolver assembly+ # uses, so the budget cannot claim a saving the load does not take.+ from .diffusion_te_prequant import te_prequant_budget_scale++ te_scale = te_prequant_budget_scale(+ fam, te_quant_mode = text_encoder_quant, target = target+ )+ transformer_gb, text_encoders_gb, vae_gb = table+ resident_gb = transformer_gb + text_encoders_gb * te_scale + vae_gb+ current = plan.estimates.get("model_dense_mib")+ table_mib = int(resident_gb * (1000.0**3) / (1024.0 * 1024.0))+ if current is None or table_mib >= int(current):+ return plan+ return replace(+ plan,+ estimates = {**plan.estimates, "model_dense_mib": table_mib},+ )+ except Exception: # noqa: BLE001 — sizing aid only; refuse on the plan as built+ return plan+def _plan_memory(self,target: DiffusionDeviceTarget,diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.pyindex dc224c85e5e..ff0b1fb712c 100644--- a/studio/backend/core/inference/diffusion_memory.py+++ b/studio/backend/core/inference/diffusion_memory.py@@ -208,8 +208,24 @@ def settled_snapshot_device_memory(fell back to offloaded GGUF; the identical retry saw >= 124 GB and went resident). Settlethe allocator (synchronize + empty_cache, best-effort) and take the MAX free over a fewspaced reads: a transient can only SHRINK free, so the max rejects transient undercounts- while a persistent tenant still caps every read. Non-cuda targets keep the single read."""- if getattr(target, "device", "cpu") != "cuda":+ while a persistent tenant still caps every read. Non-cuda targets keep the single read.++ On mps the budget is system memory, and torch's MPS caching allocator holds the previous+ pipeline's freed buffers as reserved -- which reads as used system memory. Release them first,+ or a swap is budgeted against a pool that only looks too small+ (torch.mps.empty_cache: "Releases all unoccupied cached memory currently held by the caching+ allocator so that those can be used in other GPU applications")."""+ device = getattr(target, "device", "cpu")+ if device == "mps":+ try:+ import torch+ empty_cache = getattr(getattr(torch, "mps", None), "empty_cache", None)+ if callable(empty_cache):+ empty_cache()+ except Exception: # noqa: BLE001 — settle is best-effort; the snapshot below still runs+ pass+ return snapshot_device_memory(target)+ if device != "cuda":return snapshot_device_memory(target)try:import torch@@ -395,6 +411,101 @@ def plan_fits_total_capacity(plan: Any) -> bool:return int(required) <= int((int(total) - _reserve_mib(kind, int(total))) * 0.85)+# Opt-in escape hatch for the unified-memory refusal below: the shortfall check is an+# estimate, so an operator who believes it is wrong can still attempt the load.+UNIFIED_OVERSIZE_ENV = "UNSLOTH_DIFFUSION_ALLOW_OVERSIZED_LOAD"+++def _unified_oversize_override() -> bool:+ return os.environ.get(UNIFIED_OVERSIZE_ENV, "").strip().lower() in ("1", "true", "yes", "on")+++def unified_memory_shortfall_message(plan: Any, *, family: Optional[str] = None) -> Optional[str]:+ """On UNIFIED device memory, a user-facing refusal when the WEIGHTS alone cannot fit the+ safe budget (else None).++ Unified memory is the one placement where the planner has no fallback left. On discrete+ VRAM an oversized model still loads: it degrades to group / whole-module CPU offload and+ streams from host RAM. On Apple Silicon (and integrated CUDA) the CPU and GPU share one+ pool, so offload moves bytes within that pool and frees nothing -- ``plan_diffusion_memory``+ correctly returns ``none``, and the load then allocates past physical memory. There is no+ torch OOM to catch, because ``_mps_or_cpu_target`` sets PYTORCH_MPS_HIGH_WATERMARK_RATIO=0.0+ to disable the MPS allocator's hard limit, so the failure is the OS killing the process+ with no Python exception. Refusing up front is the only way the user learns why.++ Weights only (``model_dense_mib`` + the flat base overhead): the per-call runtime headroom+ is the SOFT term -- it is a coarse activation / VAE-decode estimate, and the mps path+ already turns on VAE tiling + slicing, which cuts the decode peak this estimate does not+ model. Counting it would refuse marginal loads that would in fact complete. The weights are+ the hard term: they are unavoidable resident bytes, sized from measured per-family+ component tables or from on-disk checkpoint size, and if they alone do not fit then nothing+ at generation time can rescue the load. Same reasoning as the llama.cpp APU guard, which+ budgets weights and lets KV/context auto-reduce.++ Fail-open on anything unknown (no budget, no size), matching the planner's own+ "budget or model size unknown; staying resident"."""+ if _unified_oversize_override():+ return None+ try:+ memory = plan.device_memory+ # ``system_memory`` (plain CPU) is deliberately excluded: it is an opt-in fringe path,+ # it has swap, and it is not what gets Metal-killed. Only the accelerator-on-system-pool+ # case is guarded.+ if getattr(memory, "memory_kind", None) != "unified_memory":+ return None+ estimates = plan.estimates+ budget = estimates.get("safe_device_budget_mib")+ weights = estimates.get("model_dense_mib")+ overhead = estimates.get("base_overhead_mib")+ free = getattr(memory, "free_mib", None)+ except Exception: # noqa: BLE001 — malformed plan: never block the load+ return None+ if budget is None or weights is None:+ return None+ required = int(weights) + int(overhead or 0)+ if required <= int(budget):+ return None+ what = f"'{family}'" if family else "This model"+ free_note = (+ f"of the {int(free) / 1024:.0f} GB currently free, after reserving room for the "+ "operating system"+ if free is not None+ else "after reserving room for the operating system"+ )+ return (+ f"{what} needs about {required / 1024:.0f} GB of memory for its weights, but only "+ f"about {int(budget) / 1024:.0f} GB is usable on this device ({free_note}). This device "+ "has unified memory, so the CPU and GPU share one pool: offloading weights to the CPU "+ "frees nothing, and the operating system stops an oversized load outright instead of "+ "reporting an out-of-memory error. Use a smaller or more quantized model, free memory "+ f"by closing other applications, or set {UNIFIED_OVERSIZE_ENV}=1 to attempt the load "+ "anyway."+ )+++def raise_on_unified_memory_shortfall(+ plan: Any,+ *,+ family: Optional[str] = None,+ logger: Any = None,+) -> None:+ """Refuse a load whose weights cannot fit unified device memory. No-op on every other+ placement, so the discrete-VRAM path is untouched.++ Lives outside ``plan_diffusion_memory`` on purpose: the planner is a pure sizing function+ that both loaders call SPECULATIVELY (the image loader re-plans candidate quantisations, and+ both re-plan against a settled snapshot), and a planner that raised would turn those probes+ into load failures instead of letting a smaller candidate win. Call this once, on the plan+ the loader has committed to, after the previous pipeline has been evicted so the free+ reading is the memory the load actually gets."""+ message = unified_memory_shortfall_message(plan, family = family)+ if message is None:+ return+ if logger is not None:+ logger.error("diffusion.memory: refusing oversized unified-memory load: %s", message)+ raise RuntimeError(message)++def _sum_required(*values: Optional[int]) -> Optional[int]:total = 0for value in values:diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex 90abb48d395..1e2d0e45656 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -67,7 +67,8 @@ from .diffusion_memory import (file_size_mib,normalize_memory_mode,plan_diffusion_memory,- snapshot_device_memory,+ raise_on_unified_memory_shortfall,+ settled_snapshot_device_memory,)from .diffusion_speed import (SPEED_DEFAULT,@@ -1946,6 +1947,7 @@ class VideoBackend:diffusers = diffusers,torch = torch,fam = fam,+ target = target,repo_id = repo_id,base = base,kind = kind,@@ -1980,7 +1982,9 @@ class VideoBackend:transformer_quant = "off" if speed_off else TQ_AUTO# ── memory plan: family-table resident estimate + frames-aware headroom.- device_memory = snapshot_device_memory(target)+ # Settled, not raw: this plan is the one the unified-memory refusal below judges, so the+ # previous pipeline's cached-but-free allocator buffers must not read as occupied.+ device_memory = settled_snapshot_device_memory(target)components = fam.bf16_components_gbmib_per_gb = 1000.0**3 / (1024.0 * 1024.0)# bf16_components_gb is (transformer, text_encoder, vae) at bf16. When this pick takes its@@ -2012,7 +2016,16 @@ class VideoBackend:its bf16 size. Pure and cheap (``plan_diffusion_memory`` is arithmetic), so thedense-encoder plan can be rebuilt below if the pre-cast injection does not land."""text_encoder_gb = components[1] * scale if components is not None else 0.0- companions_gb = text_encoder_gb + components[2] if components is not None else 0.0+ # dtype_scale doubles bf16 terms when the fp16 promotion lands fp32 on an accelerator.+ # A vae_force_fp32 family is the one component it must NOT touch: its table term is+ # already recorded at fp32 and assembly pins the VAE to fp32 either way, so scaling it+ # counts those bytes twice (2.8 GB on Wan TI2V-5B) against a hard refusal.+ vae_gb = components[2] if components is not None else 0.0+ vae_scale = 1.0 if getattr(fam, "vae_force_fp32", False) else dtype_scale+ scaled_te_gb = text_encoder_gb * dtype_scale+ scaled_vae_gb = vae_gb * vae_scale+ companions_gb = text_encoder_gb + vae_gb if components is not None else 0.0+ scaled_companions_gb = scaled_te_gb + scaled_vae_gb if components is not None else 0.0if log and scale != 1.0 and components is not None:logger.info("video.te_prequant_budget: budgeting the pre-cast %s text encoder at %.2f of "@@ -2024,16 +2037,14 @@ class VideoBackend:)if kind == "pipeline":model_dense_mib = (- int((components[0] + companions_gb) * mib_per_gb * dtype_scale)+ int((components[0] * dtype_scale + scaled_companions_gb) * mib_per_gb)if components is not Noneelse None)companion_mib = Noneelse:companion_mib = (- int(companions_gb * mib_per_gb * dtype_scale)- if components is not None- else None+ int(scaled_companions_gb * mib_per_gb) if components is not None else None)# Budget ALL weights: companions stay resident, so budgeting the transformer alone lets auto pick OFFLOAD_NONE and OOM.model_dense_mib = (@@ -2050,6 +2061,14 @@ class VideoBackend:# Parity with the image dense-quant path: the bf16-table plan can force offload a quantised DiT would not need, so re-plan with the scheme factor and keep resident if it fits.dense_plan = plannedreplanned_for_quant = False+ # NOT re-triggered by a unified-memory shortfall, deliberately. This re-plan prices the+ # quantised DiT's STEADY size, but the video path has no pre-quantised artifact: the DiT+ # is always materialised dense (from_pretrained / from_single_file) and+ # quantize_transformer rewrites it in place afterwards, so the build PEAK is the bf16+ # figure whatever scheme is picked. On discrete VRAM the steady state is the right thing+ # to plan placement against -- an oversized peak raises a catchable torch OOM and offload+ # is still there -- but on unified memory the peak is what the OS kills for, with no+ # exception to catch, so the refusal below has to keep reading the dense plan.if (kind == "pipeline"and planned.offload_policy != "none"@@ -2086,6 +2105,12 @@ class VideoBackend:plan, bf16_plan, quant_replanned = _plan_for_te_scale(te_scale, log = True)+ # On unified memory the plan's 'none' policy is a placement, not a fit: there is no+ # offload tier left to fall back to, so an oversized load is killed by the OS with no+ # torch OOM to catch. Refuse now, after the eviction above and before any weight is+ # materialised -- on the dense plan, which is what the DiT build peaks at (see above).+ raise_on_unified_memory_shortfall(plan, family = getattr(fam, "name", None), logger = logger)+# ── build the pipeline.pipeline_cls = getattr(diffusers, fam.pipeline_class)# cache_dir pins every loader call to the live cache root, so a mid-session change cannot split one model across roots.@@ -2533,6 +2558,66 @@ class VideoBackend:)return self.status()+ @staticmethod+ def _raise_on_modular_unified_shortfall(+ fam: VideoFamily,+ *,+ target: Any,+ dtype: Any,+ device: str,+ memory_mode: Optional[str],+ scheme: Optional[str],+ ) -> None:+ """Refuse a modular (MiniMax-H3) load whose components cannot fit unified memory.++ The conventional path plans and refuses in ``load_pipeline``; the modular dispatch returns+ before that, so the one family whose dense component set is 144.2 GB -- the largest by a+ wide margin, and the one the refusal matrix says must be declined on every Mac it models --+ was the only one that never reached the check.++ Sized on what ``load_components`` will actually build: the family's dense bf16 table, with+ the denoiser priced at its steady quantised size when a hosted pre-quantized checkpoint is+ about to be seeded in its place. Best-effort like the rest of the sizing helpers -- a+ family with no table, or an unreadable device, plans nothing and the load proceeds as+ before."""+ components = getattr(fam, "bf16_components_gb", None)+ if not components:+ return+ import torch++ # Same rule as the conventional path: the table is bf16, so an fp32 promotion on an+ # accelerator doubles it.+ dtype_scale = 2.0 if device != "cpu" and dtype is torch.float32 else 1.0+ transformer_gb, text_encoder_gb, vae_gb = components+ # Only a scheme with a hosted checkpoint replaces the dense denoiser; anything else (auto+ # included) keeps the released bfloat16 components, which is what the modular loader does.+ #+ # Its MEASURED size when the family publishes one, not the generic steady factor: H3's+ # hosted denoisers are quantized AND structurally pruned (the curve-form adaLN), so 0.55 x+ # 66.3 GB reads 36.5 GB against a real ~20.3 GB, and the 16 GB gap is enough to refuse a+ # supported prequant load that fits on a 128 GB Mac.+ measured = getattr(fam, "prequant_resident_gb", None) if scheme else None+ factor = _QUANT_STEADY_FACTOR.get(scheme) if scheme else None+ if measured:+ transformer_gb = float(measured)+ elif factor is not None:+ transformer_gb *= factor+ mib_per_gb = 1000.0**3 / (1024.0 * 1024.0)+ plan = plan_diffusion_memory(+ target = target,+ device_memory = settled_snapshot_device_memory(target),+ model_dense_mib = int(+ (transformer_gb + text_encoder_gb + vae_gb) * dtype_scale * mib_per_gb+ ),+ runtime_headroom_mib = estimate_video_runtime_mib(+ width = fam.resolution_presets[0][0],+ height = fam.resolution_presets[0][1],+ num_frames = fam.default_num_frames,+ ),+ requested_mode = normalize_memory_mode(memory_mode),+ )+ raise_on_unified_memory_shortfall(plan, family = getattr(fam, "name", None), logger = logger)+def _load_h3_modular_pipeline(self,*,@@ -2548,6 +2633,7 @@ class VideoBackend:memory_mode: Optional[str],transformer_quant: Optional[str] = None,h3_task: Optional[str] = None,+ target: Any = None,_load_token: Optional[int] = None,_base_local_dir: Optional[str] = None,) -> dict[str, Any]:@@ -2586,6 +2672,22 @@ class VideoBackend:f"no hosted pre-quantized {scheme} checkpoint for {fam.name} reference video")scheme = None+ # The conventional loader refuses an oversized unified-memory load before any weight is+ # materialised; this workflow returns above that check, so it runs its own here. It has to:+ # load_components builds every component dense, and the ComponentsManager's CPU offload+ # frees nothing on unified memory (host and device are one pool), so H3's 144.2 GB+ # component set is an OS kill with no torch OOM to catch. Placed after `scheme` settles and+ # before ANY weight is opened -- the hosted pre-quantized denoiser below is materialised on+ # the CPU, which is the same memory.+ umem_target = target if target is not None else resolve_diffusion_device_target()+ self._raise_on_modular_unified_shortfall(+ fam,+ target = umem_target,+ dtype = dtype,+ device = device,+ memory_mode = memory_mode,+ scheme = scheme,+ )if scheme is not None:from .diffusion_prequant import load_prequantized_transformer, resolve_prequant_sourcefrom .diffusion_transformer_quant import DEFAULT_MIN_LINEAR_FEATURES@@ -2656,6 +2758,20 @@ class VideoBackend:# keyframe/reference paths). workflow= only narrows the name list load_components already# built, and that list skips every component whose attribute is set, so the seeding above# still keeps the dense 66.3 GB transformer from being fetched.+ if scheme is not None and transformer_quant_engaged is None:+ # The seeding above is best-effort by contract: a missing, corrupt, stale or+ # base-mismatched checkpoint drops to the released bfloat16 denoiser, and that is the+ # 66.3 GB the check before it did not size. load_components would then build it with+ # no refusal left to stop it, which on unified memory is the OS kill this whole guard+ # exists to prevent. Re-run it on the dense set, still before any weight is opened.+ self._raise_on_modular_unified_shortfall(+ fam,+ target = umem_target,+ dtype = dtype,+ device = device,+ memory_mode = memory_mode,+ scheme = None,+ )pipe.load_components(workflow = workflow,dtype = dtype,diff --git a/studio/backend/core/inference/video_families.py b/studio/backend/core/inference/video_families.pyindex 46252edfd03..c3864982f1d 100644--- a/studio/backend/core/inference/video_families.py+++ b/studio/backend/core/inference/video_families.py@@ -86,6 +86,12 @@ class VideoFamily:# can take one without the other. Same semantics as DiffusionFamily.prequant_repos, so the# shared diffusion_prequant resolver reads this table through plain attribute access.prequant_repos: tuple[tuple[str, str], ...] = field(default_factory = tuple)+ # RESIDENT size of one of those hosted denoisers, in decimal GB, when the generic+ # _QUANT_STEADY_FACTOR does not describe it. MiniMax-H3's is both quantized AND structurally+ # pruned (the curve-form adaLN, ~40% of the released parameters), so 0.55 x 66.3 GB over-states+ # it by 16 GB and a hard refusal turns away a load that fits. Measured from Hub file metadata+ # (2026-08-09): MiniMax-H3-FP8.pt 20,260,192,855 bytes, MiniMax-H3-INT8.pt 20,253,894,865.+ prequant_resident_gb: Optional[float] = None# Per-variant overrides as (base_repo, scheme, repo_id), keyed on the LOWERCASED upstream base# id. A pre-quantized checkpoint is baked from ONE base's weights and the loader refuses it for# any other base, so a variant that ships its own denoiser needs its own entry; a variant@@ -149,6 +155,8 @@ _FAMILIES: tuple[VideoFamily, ...] = (# the layout every image-side prequant repo already uses and the one prequant_repo_filename# builds without help.prequant_repos = (("int8", "unsloth/MiniMax-H3-FP8"), ("fp8", "unsloth/MiniMax-H3-FP8")),+ # Both schemes are ~20.3 GB resident against the 66.3 GB dense denoiser; see the field.+ prequant_resident_gb = 20.3,modular_workflow = "fl2va",default_flow_shift = 12.0,default_audio_flow_shift = 3.0,diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.pyindex 7edd7cacd97..6e0074c2929 100644--- a/studio/backend/tests/test_diffusion_backend.py+++ b/studio/backend/tests/test_diffusion_backend.py@@ -7380,6 +7380,149 @@ def test_download_plan_skips_nothing_when_the_hub_reports_no_commit(monkeypatch)}+# ── unified-memory oversize refusal, at the image load seam ───────────────────+# The planner is shared with video, so the image loader needs the same guard: a Mac user+# picking an oversized image checkpoint hits the identical SIGKILL (no torch OOM to catch,+# because the mps target disables the MPS allocator's high-watermark limit).+++def _unified_snapshot(total_gib):+ from core.inference.diffusion_memory import DeviceMemory+ total = total_gib * 1024+ return lambda target: DeviceMemory("mps", "mps", "unified_memory", int(total * 0.80), total)+++def _oversized_gguf(+ monkeypatch,+ tmp_path,+ total_gib,+ *,+ resident_mib = 24 * 1024,+):+ (tmp_path / "model.gguf").write_bytes(b"weights")+ monkeypatch.setattr(+ "core.inference.diffusion.settled_snapshot_device_memory", _unified_snapshot(total_gib)+ )+ # The 7-byte fake checkpoint sizes to 1 MiB; stand in a realistic resident footprint.+ monkeypatch.setattr(+ "core.inference.diffusion.estimate_gguf_resident_mib", lambda storage: resident_mib+ )+ return DiffusionBackend()+++def test_unified_memory_refuses_an_oversized_image_load(fake_runtime, monkeypatch, tmp_path):+ backend = _oversized_gguf(monkeypatch, tmp_path, 16)+ with pytest.raises(RuntimeError) as excinfo:+ backend.load_pipeline(+ str(tmp_path),+ gguf_filename = "model.gguf",+ base_repo = "base/repo",+ family_override = "z-image",+ )+ message = str(excinfo.value)+ assert "z-image" in message+ assert "unified memory" in message+ assert "UNSLOTH_DIFFUSION_ALLOW_OVERSIZED_LOAD=1" in message+ # Refused before the pipeline was built.+ assert backend.status()["loaded"] is False+++def test_unified_memory_allows_an_image_load_that_fits(fake_runtime, monkeypatch, tmp_path):+ backend = _oversized_gguf(monkeypatch, tmp_path, 128)+ status = backend.load_pipeline(+ str(tmp_path),+ gguf_filename = "model.gguf",+ base_repo = "base/repo",+ family_override = "z-image",+ )+ assert status["loaded"] is True+++def test_unified_memory_image_refusal_is_overridable(fake_runtime, monkeypatch, tmp_path):+ from core.inference.diffusion_memory import UNIFIED_OVERSIZE_ENV++ backend = _oversized_gguf(monkeypatch, tmp_path, 16)+ monkeypatch.setenv(UNIFIED_OVERSIZE_ENV, "1")+ status = backend.load_pipeline(+ str(tmp_path),+ gguf_filename = "model.gguf",+ base_repo = "base/repo",+ family_override = "z-image",+ )+ assert status["loaded"] is True+++def test_discrete_vram_image_load_is_unaffected_by_the_refusal(fake_runtime, monkeypatch, tmp_path):+ from core.inference.diffusion_memory import DeviceMemory++ (tmp_path / "model.gguf").write_bytes(b"weights")+ monkeypatch.setattr(+ "core.inference.diffusion.settled_snapshot_device_memory",+ lambda target: DeviceMemory("cuda", "cuda", "discrete_vram", 13_107, 16_384),+ )+ monkeypatch.setattr(+ "core.inference.diffusion.estimate_gguf_resident_mib", lambda storage: 24 * 1024+ )+ status = DiffusionBackend().load_pipeline(+ str(tmp_path),+ gguf_filename = "model.gguf",+ base_repo = "base/repo",+ family_override = "z-image",+ )+ assert status["loaded"] is True+++# ── the resident-size substitution must not out-guess a measured local checkpoint ──+++def _plan_with_weights(mib):+ from core.inference.diffusion_memory import DeviceMemory, MemoryPlan+ return MemoryPlan(+ requested_mode = "auto",+ offload_policy = "none",+ vae_tiling = False,+ vae_slicing = False,+ device_memory = DeviceMemory("mps", "mps", "unified_memory", 32_768, 65_536),+ estimates = {"model_dense_mib": mib, "safe_device_budget_mib": 24_000},+ )+++def test_the_resident_size_table_never_shrinks_a_local_checkpoint(fake_runtime, monkeypatch):+ """The table is keyed on UPSTREAM ids, so a local directory can only reach the coarse family+ entry -- and a family with more than one size under it (a local FLUX.2-klein 9B against+ klein's 4B default) would be re-sized to less than half what it loads, walking straight past+ the refusal into the OS killer. On disk is the measured truth for a local path."""+ import torch++ from core.inference.diffusion_device import DiffusionDeviceTarget+ from core.inference.diffusion_families import detect_family++ target = DiffusionDeviceTarget(+ device = "mps",+ dtype = torch.bfloat16,+ backend = "mps",+ vendor = "apple",+ supports_model_cpu_offload = False,+ supports_default_torch_compile = False,+ supports_pinned_transfer = False,+ )+ fam = detect_family("black-forest-labs/FLUX.2-klein-9B")+ backend = DiffusionBackend()+ measured = 34_000 # what a 9B pipeline's shards actually weigh++ local = str(Path.cwd())+ plan = _plan_with_weights(measured)+ kept = backend._resident_sized_plan(plan, fam, local, target, "pipeline")+ assert kept.estimates["model_dense_mib"] == measured++ # A hub id the table does recognise still gets the substitution: that is the fp32-shard case+ # (Z-Image, Lumina) this exists for, and it is what keeps a load that fits from being refused.+ lowered = backend._resident_sized_plan(+ plan, fam, "black-forest-labs/FLUX.2-klein-4B", target, "pipeline"+ )+ assert lowered.estimates["model_dense_mib"] < measured++def test_speed_off_is_not_reported_as_a_staging_failure(fake_runtime, tmp_path, monkeypatch):"""An explicit Speed=off rewrites an auto request to "off" and the plan stages notransformer/ on purpose. Reading that expected absence as a decline told the caller their@@ -8032,6 +8175,271 @@ def test_cancel_generate_is_a_no_op_without_a_load(fake_runtime):assert DiffusionBackend().cancel_generate() is False+def test_unified_memory_declines_a_prequant_that_outweighs_the_gguf(+ fake_runtime, monkeypatch, tmp_path+):+ """A GGUF pick on unified memory can still be upsized by the dense fast path: the hosted+ fp8/int8 artifact is roughly 0.55x bf16 against a Q4's ~0.3x, so it can be twice the file that+ just passed the load-level refusal. The planner returns 'none' for any size on unified memory,+ so the OFFLOAD_NONE gate cannot catch that, and the prequant path skips the dense-size check+ (it never builds dense). Without an explicit size the load materialises it and is OS-killed."""+ from core.inference import diffusion as dmod+ from core.inference.diffusion_auto_policy import DenseQuantEstimate++ backend = _oversized_gguf(monkeypatch, tmp_path, 32, resident_mib = 8 * 1024)+ _force_cuda_target(backend, monkeypatch)+ monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)+ monkeypatch.setattr(+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "fp8"+ )+ # A hosted pre-cast checkpoint IS available, which is what skips the dense-size check.+ monkeypatch.setattr(dmod, "usable_prequant_source", lambda *a, **kw: "unsloth/Z-Image-FP8")+ monkeypatch.setattr(+ dmod,+ "resolve_dense_quant_candidate",+ lambda **kw: DenseQuantEstimate(+ scheme = "fp8",+ steady_transformer_mib = 40 * 1024,+ transient_transformer_mib = 40 * 1024, # far past a 32 GiB pool's safe budget+ companions_mib = 2 * 1024,+ prequant = True,+ ),+ )++ status = backend.load_pipeline(+ str(tmp_path),+ gguf_filename = "model.gguf",+ family_override = "z-image",+ model_kind = "gguf",+ )+ # The GGUF fits and loads; the oversized quant is declined rather than materialised.+ assert status["loaded"] is True+ assert status["transformer_quant"] is None+ resolved = status["resolved"]["transformer_quant"]+ assert resolved["value"] == "off"+ assert "unified memory" in (resolved["reason"] or "")+++def test_unified_memory_keeps_a_prequant_that_fits(fake_runtime, monkeypatch, tmp_path):+ # The same shape with an artifact that fits must be untouched: this guard only ever removes a+ # candidate the device cannot hold, never one it can.+ from core.inference import diffusion as dmod+ from core.inference.diffusion_auto_policy import DenseQuantEstimate++ backend = _oversized_gguf(monkeypatch, tmp_path, 32, resident_mib = 8 * 1024)+ _force_cuda_target(backend, monkeypatch)+ monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)+ monkeypatch.setattr(+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "fp8"+ )+ monkeypatch.setattr(dmod, "usable_prequant_source", lambda *a, **kw: "unsloth/Z-Image-FP8")+ monkeypatch.setattr(+ dmod,+ "resolve_dense_quant_candidate",+ lambda **kw: DenseQuantEstimate(+ scheme = "fp8",+ steady_transformer_mib = 6 * 1024,+ transient_transformer_mib = 6 * 1024,+ companions_mib = 2 * 1024,+ prequant = True,+ ),+ )+ calls: list = []++ def _record(self, *a, **kw):+ calls.append("built")+ # Raising here keeps the stub out of pipeline assembly; the loader's own handler falls+ # back to the GGUF, and reaching this line at all is the assertion.+ raise RuntimeError("stub")++ monkeypatch.setattr(dmod.DiffusionBackend, "_load_dense_quant_pipeline", _record)++ backend.load_pipeline(+ str(tmp_path),+ gguf_filename = "model.gguf",+ family_override = "z-image",+ model_kind = "gguf",+ )+ assert calls == ["built"], "a prequant that fits must still reach the dense fast path"+++def test_the_resident_size_table_prices_a_pre_cast_encoder_at_its_real_size(+ fake_runtime, monkeypatch+):+ """The table's encoder term is the dense one, and a pick that takes its encoder PRE-CAST from a+ hosted fp8 checkpoint loads roughly 0.65x of it. Budgeting the dense figure against a hard+ refusal turns tens of GB the pipeline never materialises into a rejected load."""+ import torch++ from core.inference import diffusion as dmod+ from core.inference.diffusion_device import DiffusionDeviceTarget+ from core.inference.diffusion_families import detect_family+ from core.inference.diffusion_te_prequant import TE_PREQUANT_BUDGET_SCALE++ target = DiffusionDeviceTarget(+ device = "mps",+ dtype = torch.bfloat16,+ backend = "mps",+ vendor = "apple",+ supports_model_cpu_offload = False,+ supports_default_torch_compile = False,+ supports_pinned_transfer = False,+ )+ fam = detect_family("Tongyi-MAI/Z-Image-Turbo")+ base = "Tongyi-MAI/Z-Image-Turbo"+ backend = DiffusionBackend()+ plan = _plan_with_weights(200_000) # so the table always wins++ dense = backend._resident_sized_plan(plan, fam, base, target, "pipeline")+ monkeypatch.setattr(dmod, "family_bf16_components_gb", dmod.family_bf16_components_gb)+ monkeypatch.setattr(+ "core.inference.diffusion_te_prequant.te_prequant_sources",+ lambda fam, te_quant_mode = None, target = None: {"text_encoder": object()},+ )+ precast = backend._resident_sized_plan(+ plan, fam, base, target, "pipeline", text_encoder_quant = "fp8"+ )+ dense_mib = dense.estimates["model_dense_mib"]+ precast_mib = precast.estimates["model_dense_mib"]+ assert precast_mib < dense_mib, "a pre-cast encoder must lower the refusal's weight term"+ # Only the ENCODER term moves: transformer and VAE are untouched by a text-encoder quant.+ transformer_gb, encoders_gb, _vae = dmod.family_bf16_components_gb(fam, base)+ saved_gb = (dense_mib - precast_mib) * (1024.0 * 1024.0) / (1000.0**3)+ assert saved_gb == pytest.approx(encoders_gb * (1.0 - TE_PREQUANT_BUDGET_SCALE), rel = 0.02)+++def test_the_resident_size_table_never_shrinks_an_unrecognised_remote_variant(fake_runtime):+ """Same hole as the local-path one, reached from the Hub: a fine-tune or a renamed mirror that+ the family detector still matches by name is NOT an exact key in the size table, so it falls+ through to the family entry -- and for a family carrying two sizes that entry is the smaller+ one. A 9B derivative lowered to the 4B number walks straight past the refusal."""+ import torch++ from core.inference.diffusion_device import DiffusionDeviceTarget+ from core.inference.diffusion_families import detect_family++ target = DiffusionDeviceTarget(+ device = "mps",+ dtype = torch.bfloat16,+ backend = "mps",+ vendor = "apple",+ supports_model_cpu_offload = False,+ supports_default_torch_compile = False,+ supports_pinned_transfer = False,+ )+ fam = detect_family("black-forest-labs/FLUX.2-klein-9B")+ backend = DiffusionBackend()+ measured = 34_000+ plan = _plan_with_weights(measured)++ kept = backend._resident_sized_plan(+ plan, fam, "someone/FLUX.2-klein-9B-anime-tune", target, "pipeline"+ )+ assert kept.estimates["model_dense_mib"] == measured+ # The two recognised shapes still get it: an explicit per-base override, and the family default.+ override = backend._resident_sized_plan(+ plan, fam, "black-forest-labs/FLUX.2-klein-9B", target, "pipeline"+ )+ assert override.estimates["model_dense_mib"] < measured+ default = backend._resident_sized_plan(plan, fam, fam.base_repo, target, "pipeline")+ assert default.estimates["model_dense_mib"] < measured+++def test_a_whole_pipeline_single_file_is_not_charged_for_cached_companions(fake_runtime):+ """An SDXL-style single file carries the U-Net, VAE and text encoders itself and the base repo+ is read for config only, but the plan still adds the base's cached companion weights. As an+ offload hint that is conservative; as a hard refusal it rejects a checkpoint that fits, and+ only for users who happen to have loaded the full pipeline before."""+ import torch++ from core.inference.diffusion_device import DiffusionDeviceTarget+ from core.inference.diffusion_families import detect_family+ from core.inference.diffusion_memory import DeviceMemory, MemoryPlan++ target = DiffusionDeviceTarget(+ device = "mps",+ dtype = torch.bfloat16,+ backend = "mps",+ vendor = "apple",+ supports_model_cpu_offload = False,+ supports_default_torch_compile = False,+ supports_pinned_transfer = False,+ )+ fam = detect_family("stabilityai/stable-diffusion-xl-base-1.0")+ assert fam.single_file_is_pipeline, "this test is about the SDXL-shaped families"+ plan = MemoryPlan(+ requested_mode = "auto",+ offload_policy = "none",+ vae_tiling = False,+ vae_slicing = False,+ device_memory = DeviceMemory("mps", "mps", "unified_memory", 32_768, 65_536),+ estimates = {+ "model_dense_mib": 14_000, # the checkpoint (7 GB) plus 7 GB of cached companions+ "companion_dense_mib": 7_000,+ "safe_device_budget_mib": 10_000,+ },+ )+ sized = DiffusionBackend()._resident_sized_plan(+ plan, fam, "stabilityai/stable-diffusion-xl-base-1.0", target, "single_file"+ )+ assert sized.estimates["model_dense_mib"] == 7_000+++def test_the_prequant_fit_check_prices_a_pre_cast_text_encoder(fake_runtime, monkeypatch):+ """``DenseQuantEstimate.companions_mib`` is always the DENSE encoder plus the VAE, but the+ assembly this check is sizing is handed ``text_encoder_quant`` and injects the pre-cast+ encoder. Refusing on the dense figure declines a prequant that fits on bytes never+ materialised -- for FLUX.2-dev's Mistral-24B that is tens of GB. The load-level resident plan+ already applies te_prequant_budget_scale; this is the same scale on the same estimate."""+ from core.inference.diffusion import DiffusionBackend+ from core.inference.diffusion_families import detect_family+ from core.inference.diffusion_te_prequant import TE_PREQUANT_BUDGET_SCALE++ fam = detect_family("black-forest-labs/FLUX.2-dev")+ assert fam is not None and fam.te_prequant_repos, "the fixture family lost its pre-cast repo"+ # 48 GB of encoder, 0.4 GB of VAE, in the estimate's own units.+ encoders = 48_000+ candidate = types.SimpleNamespace(companions_mib = encoders + 400, text_encoders_mib = encoders)++ scaled = DiffusionBackend._precast_scaled_companions_mib(candidate, fam, object(), "fp8")+ # No pre-cast encoder resolves in this environment unless te_prequant_sources says so, so pin+ # the two outcomes on the resolver rather than assuming one.+ from core.inference.diffusion_te_prequant import te_prequant_sources++ if te_prequant_sources(fam, te_quant_mode = "fp8", target = object()):+ assert scaled == 400 + int(encoders * TE_PREQUANT_BUDGET_SCALE)+ assert scaled < candidate.companions_mib+ else:+ assert scaled == candidate.companions_mib++ # No encoder quant requested: the estimate is passed through untouched, byte for byte.+ assert (+ DiffusionBackend._precast_scaled_companions_mib(candidate, fam, object(), None)+ == candidate.companions_mib+ )+ # The VAE share is never scaled, and a candidate with no split degrades to the dense total.+ no_split = types.SimpleNamespace(companions_mib = 1234, text_encoders_mib = 0)+ assert DiffusionBackend._precast_scaled_companions_mib(no_split, fam, object(), "fp8") == 1234+ # An estimate with no companions at all stays None, which _plan_memory reads as "no override".+ empty = types.SimpleNamespace(companions_mib = None)+ assert DiffusionBackend._precast_scaled_companions_mib(empty, fam, object(), "fp8") is None+++def test_the_pre_cast_companion_scale_matches_the_load_level_plan(fake_runtime, monkeypatch):+ """Both sides must read the same scale from the same resolver, or the fit check and the plan+ it gates disagree about what the load builds."""+ from core.inference.diffusion import DiffusionBackend+ from core.inference.diffusion_families import detect_family++ fam = detect_family("black-forest-labs/FLUX.2-dev")+ monkeypatch.setattr(+ "core.inference.diffusion_te_prequant.te_prequant_budget_scale",+ lambda fam, *, te_quant_mode, target: 0.5 if te_quant_mode == "fp8" else 1.0,+ )+ candidate = types.SimpleNamespace(companions_mib = 10_400, text_encoders_mib = 10_000)+ assert DiffusionBackend._precast_scaled_companions_mib(candidate, fam, object(), "fp8") == 5_400++def test_an_offload_memory_request_is_not_reported_as_unstaged_shards(fake_runtime, tmp_path, monkeypatch):diff --git a/studio/backend/tests/test_diffusion_memory.py b/studio/backend/tests/test_diffusion_memory.pyindex 68781e9d14c..a5fb6d5bd2f 100644--- a/studio/backend/tests/test_diffusion_memory.py+++ b/studio/backend/tests/test_diffusion_memory.py@@ -894,6 +894,227 @@ def test_plan_fits_total_capacity():assert plan_fits_total_capacity(types.SimpleNamespace()) is False+# ── the unified-memory oversize refusal ───────────────────────────────────────+# Apple Silicon shares one CPU/GPU pool, so the planner's OFFLOAD_NONE there is a placement+# with no fallback tier, and PYTORCH_MPS_HIGH_WATERMARK_RATIO=0.0 removes the allocator's hard+# limit: an oversized load is killed by the OS with no Python exception. These cover the+# load-time refusal that replaces that SIGKILL with a message.++_MPS_TOTAL_MIB = 16 * 1024+_MPS_FREE_MIB = int(_MPS_TOTAL_MIB * 0.80) # RAM free once macOS + a browser + Studio are up+++def _unified_plan(+ *,+ model_dense_mib,+ runtime_headroom_mib = 3072,+ free_mib = _MPS_FREE_MIB,+ total_mib = _MPS_TOTAL_MIB,+ kind = "unified_memory",+ device = "mps",+):+ """A plan straight from the shipped planner, so the budget arithmetic under test is the+ real arithmetic rather than a hand-written copy of it."""+ return plan_diffusion_memory(+ target = _target(device = device, backend = device, supports_offload = False),+ device_memory = DeviceMemory(device, device, kind, free_mib, total_mib),+ model_dense_mib = model_dense_mib,+ runtime_headroom_mib = runtime_headroom_mib,+ )+++def test_unified_oversize_refuses_and_names_family_and_both_numbers():+ from core.inference.diffusion_memory import unified_memory_shortfall_message++ # 16 GiB Mac, 12.8 GiB free, 20% unified reserve, so about 9.5 GiB of budget. 24 GiB cannot fit.+ plan = _unified_plan(model_dense_mib = 24 * 1024)+ assert plan.offload_policy == OFFLOAD_NONE # the planner still has no fallback to offer+ message = unified_memory_shortfall_message(plan, family = "wan2.2-ti2v-5b")+ assert message is not None+ assert "wan2.2-ti2v-5b" in message+ # Weights + the flat base overhead, and the safe budget, both rendered in GB.+ assert "about 26 GB of memory for its weights" in message # 24 GiB weights + 2 GiB overhead+ assert "about 10 GB is usable" in message # 12.8 GiB free, less 20% of 16 GiB+ assert "13 GB currently free" in message+ # The most useful thing the user can change, and the escape hatch.+ assert "smaller or more quantized model" in message+ assert "UNSLOTH_DIFFUSION_ALLOW_OVERSIZED_LOAD=1" in message+++def test_unified_oversize_ignores_the_soft_runtime_headroom():+ """The refusal budgets WEIGHTS only. A load whose weights fit but whose weights + activation+ headroom do not is marginal, and VAE tiling/slicing (always on for mps) cuts the decode peak+ the headroom estimate does not model, so it must NOT be refused."""+ from core.inference.diffusion_memory import unified_memory_shortfall_message++ budget = _MPS_FREE_MIB - max(2048, int(_MPS_TOTAL_MIB * 0.20))+ weights = budget - 2048 # weights + the 2048 base overhead land exactly on the budget+ plan = _unified_plan(model_dense_mib = weights, runtime_headroom_mib = 8192)+ assert plan.estimates["resident_required_mib"] > budget # refused if headroom counted+ assert unified_memory_shortfall_message(plan) is None+ # One MiB more of weights does tip it over.+ assert unified_memory_shortfall_message(_unified_plan(model_dense_mib = weights + 1)) is not None+++def test_unified_oversize_never_refuses_discrete_vram():+ """Discrete VRAM keeps its fallback ladder: an oversized model streams from host RAM under+ group / whole-module offload, so refusing it would break a load that works today."""+ from core.inference.diffusion_memory import unified_memory_shortfall_message++ plan = plan_diffusion_memory(+ target = _target(device = "cuda", backend = "cuda", supports_offload = True),+ device_memory = DeviceMemory("cuda", "cuda", "discrete_vram", 12_000, 16_384),+ model_dense_mib = 80 * 1024,+ runtime_headroom_mib = 6963,+ )+ assert plan.offload_policy == OFFLOAD_MODEL+ assert unified_memory_shortfall_message(plan, family = "ltx-2") is None+++def test_unified_oversize_never_refuses_plain_cpu_system_memory():+ # A CPU target reports system_memory, has swap, and is an opt-in fringe path: unchanged.+ from core.inference.diffusion_memory import unified_memory_shortfall_message+ plan = _unified_plan(model_dense_mib = 80 * 1024, kind = "system_memory", device = "cpu")+ assert unified_memory_shortfall_message(plan) is None+++ "kwargs",+ [+ {"free_mib": None}, # psutil unavailable: budget unknown+ {"model_dense_mib": None}, # unscannable checkpoint: size unknown+ ],+)+def test_unified_oversize_fails_open_on_unknown_inputs(kwargs):+ """Matches the planner's own "budget or model size unknown; staying resident": never turn a+ failed probe into a refusal."""+ from core.inference.diffusion_memory import unified_memory_shortfall_message++ kwargs = {"model_dense_mib": 80 * 1024, **kwargs}+ assert unified_memory_shortfall_message(_unified_plan(**kwargs)) is None+++def test_unified_oversize_env_override_attempts_the_load_anyway(monkeypatch):+ from core.inference.diffusion_memory import (+ UNIFIED_OVERSIZE_ENV,+ raise_on_unified_memory_shortfall,+ unified_memory_shortfall_message,+ )++ plan = _unified_plan(model_dense_mib = 80 * 1024)+ assert unified_memory_shortfall_message(plan) is not None+ for value in ("1", "true", "YES", "on"):+ monkeypatch.setenv(UNIFIED_OVERSIZE_ENV, value)+ assert unified_memory_shortfall_message(plan) is None+ raise_on_unified_memory_shortfall(plan) # must not raise+ monkeypatch.setenv(UNIFIED_OVERSIZE_ENV, "0")+ assert unified_memory_shortfall_message(plan) is not None+++def test_unified_oversize_message_survives_a_malformed_plan():+ from core.inference.diffusion_memory import unified_memory_shortfall_message+ assert unified_memory_shortfall_message(types.SimpleNamespace()) is None+++def test_raise_on_unified_memory_shortfall_raises_runtime_error_with_the_message():+ """RuntimeError matches the llama.cpp unified-memory APU refusal. Both loaders call this on+ a worker thread inside load_pipeline, where _run_load stringifies it onto load_progress, so+ the text reaches the UI toast and the 409 mapping of the synchronous route never applies."""+ from core.inference.diffusion_memory import (+ raise_on_unified_memory_shortfall,+ unified_memory_shortfall_message,+ )++ plan = _unified_plan(model_dense_mib = 80 * 1024)+ with pytest.raises(RuntimeError) as excinfo:+ raise_on_unified_memory_shortfall(plan, family = "ltx-2")+ assert str(excinfo.value) == unified_memory_shortfall_message(plan, family = "ltx-2")+ # A plan that fits is a silent no-op.+ raise_on_unified_memory_shortfall(_unified_plan(model_dense_mib = 1024))+++def test_unified_oversize_decision_matrix_for_the_real_video_families():+ """The shipped video family tables against real Mac RAM sizes: the refusal must fire exactly+ where the weights genuinely cannot fit, and must stay silent where they can.++ ``video_families`` is a pure table module (no torch, no diffusers), so this stays hermetic.+ ``free`` is modelled at 80% of RAM, the share left once macOS, a browser and Studio are up.+ """+ from core.inference.video_families import _FAMILIES+ from core.inference.diffusion_memory import (+ DEFAULT_BASE_OVERHEAD_MIB,+ estimate_video_runtime_mib,+ unified_memory_shortfall_message,+ )++ mib_per_gb = 1000.0**3 / (1024.0 * 1024.0) # the tables are DECIMAL GB+ # family: the RAM sizes (GiB) at which the load must be REFUSED.+ expected_refusals = {+ # 144.2 GB of bf16 weights, the largest video family by a wide margin: refused at every+ # size in this matrix, 128 GiB included. That is the correct answer rather than a gap in+ # the table -- the dense pipeline cannot fit any Mac modelled here, and a user on one+ # reaches H3 through the GGUF or prequantized artifacts instead.+ "minimax-h3": {16, 24, 32, 64, 96, 128},+ "ltx-2": {16, 24, 32, 64, 96},+ "wan2.2-ti2v-5b": {16, 24, 32},+ "wan2.2-t2v-a14b": {16, 24, 32, 64, 96},+ "hunyuanvideo-1.5": {16, 24, 32},+ "hunyuanvideo-1.5-720p": {16, 24, 32},+ }+ assert {f.name for f in _FAMILIES} == set(+ expected_refusals+ ), "a video family was added or renamed: extend the expected refusal matrix"+ for fam in _FAMILIES:+ width, height = fam.resolution_presets[0]+ dense = int(sum(fam.bf16_components_gb) * mib_per_gb)+ headroom = estimate_video_runtime_mib(+ width = width, height = height, num_frames = fam.default_num_frames+ )+ for ram_gib in (16, 24, 32, 64, 96, 128):+ total = ram_gib * 1024+ plan = _unified_plan(+ model_dense_mib = dense,+ runtime_headroom_mib = headroom,+ free_mib = int(total * 0.80),+ total_mib = total,+ )+ # The planner never has an alternative to offer on unified memory: that is the bug.+ assert plan.offload_policy == OFFLOAD_NONE+ refused = unified_memory_shortfall_message(plan, family = fam.name) is not None+ assert refused is (ram_gib in expected_refusals[fam.name]), (+ f"{fam.name} at {ram_gib} GiB: refused={refused}, "+ f"weights+overhead={dense + DEFAULT_BASE_OVERHEAD_MIB} MiB, "+ f"budget={plan.estimates['safe_device_budget_mib']} MiB"+ )+++# -- the unified refusal is judged on resident sizes, not download sizes --------+++def test_unified_memory_policy_cannot_express_a_misfit():+ """Why the dense-quant fast path needed its own explicit check: on unified memory the planner+ returns OFFLOAD_NONE for ANY size (offload just shuffles bytes within one pool), so the+ "policy is not none" test the dense re-plan relied on can never fire there."""+ from core.inference.diffusion_memory import (+ DeviceMemory,+ OFFLOAD_NONE,+ plan_diffusion_memory,+ unified_memory_shortfall_message,+ )++ target = type("T", (), {"supports_model_cpu_offload": True, "device": "cuda"})()+ memory = DeviceMemory("cuda", "cuda", "unified_memory", 8_000, 16_000)+ plan = plan_diffusion_memory(+ target = target,+ device_memory = memory,+ model_dense_mib = 90_000, # wildly oversized+ runtime_headroom_mib = 1_000,+ )+ assert plan.offload_policy == OFFLOAD_NONE+ # ... but the explicit sizing check does see the shortfall.+ assert unified_memory_shortfall_message(plan, family = "flux.1") is not None++# ── the streamed-text-encoder group tier ──────────────────────────────────────# A text encoder runs ONCE, before step 0, but group offload places every non-streamed component# resident, so its bytes are reserved for the whole denoise. Where that is the only thing pushingdiff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.pyindex 5fa35770d15..ea3ce215890 100644--- a/studio/backend/tests/test_video_backend.py+++ b/studio/backend/tests/test_video_backend.py@@ -3495,6 +3495,102 @@ def test_attention_trim_skipped_for_static_shape_and_off_tiers(fake_runtime, monassert "hunyuan_attn_trim" not in status["speed_optims"], mode+# ── unified-memory oversize refusal, at the video load seam ───────────────────+++def _unified_snapshot(total_gib):+ """Stand in for a Mac's memory snapshot: unified pool, 80% of RAM free."""+ from core.inference.diffusion_memory import DeviceMemory++ total = total_gib * 1024+ return lambda target: DeviceMemory("mps", "mps", "unified_memory", int(total * 0.80), total)+++def test_unified_memory_refuses_an_oversized_video_load(fake_runtime, monkeypatch):+ """A 16 GiB Mac loading LTX-2 (about 65 GiB of weights): the planner has no offload tier to+ fall back to on unified memory and PYTORCH_MPS_HIGH_WATERMARK_RATIO=0.0 removes the+ allocator's limit, so without this refusal the OS kills Studio with no Python exception.+ _run_load stringifies this onto load_progress, so the text is what the UI toasts."""+ import core.inference.video as video_mod++ monkeypatch.setattr(video_mod, "settled_snapshot_device_memory", _unified_snapshot(16))++ backend = VideoBackend()+ with pytest.raises(RuntimeError) as excinfo:+ backend.load_pipeline("Lightricks/LTX-2", model_kind = "pipeline")+ message = str(excinfo.value)+ assert "ltx-2" in message # names the family+ assert "unified memory" in message+ assert "UNSLOTH_DIFFUSION_ALLOW_OVERSIZED_LOAD=1" in message+ # Refused BEFORE the pipeline was built: nothing was allocated and nothing is loaded.+ assert backend.status()["loaded"] is False+++def test_unified_memory_allows_a_video_load_that_fits(fake_runtime, monkeypatch):+ # The same family on a 128 GiB Mac fits, so the refusal must stay out of the way.+ import core.inference.video as video_mod++ monkeypatch.setattr(video_mod, "settled_snapshot_device_memory", _unified_snapshot(128))++ backend = VideoBackend()+ status = backend.load_pipeline("Lightricks/LTX-2", model_kind = "pipeline")+ assert status["loaded"] is True+++def test_unified_memory_refusal_is_overridable_at_the_video_load_seam(fake_runtime, monkeypatch):+ import core.inference.video as video_mod+ from core.inference.diffusion_memory import UNIFIED_OVERSIZE_ENV++ monkeypatch.setattr(video_mod, "settled_snapshot_device_memory", _unified_snapshot(16))+ monkeypatch.setenv(UNIFIED_OVERSIZE_ENV, "1")++ backend = VideoBackend()+ assert backend.load_pipeline("Lightricks/LTX-2", model_kind = "pipeline")["loaded"] is True+++def test_discrete_vram_video_load_is_unaffected_by_the_refusal(fake_runtime, monkeypatch):+ """The same impossible-looking numbers on a discrete card still load: offload streams the+ weights from host RAM, so refusing there would break a path that works today. (The fake+ runtime resolves a CPU target, so the policy itself is not meaningful here; what this pins+ is that a discrete-VRAM snapshot never reaches the refusal.)"""+ import core.inference.video as video_mod+ from core.inference.diffusion_memory import DeviceMemory++ monkeypatch.setattr(+ video_mod,+ "settled_snapshot_device_memory",+ lambda target: DeviceMemory("cuda", "cuda", "discrete_vram", 13_107, 16_384),+ )++ backend = VideoBackend()+ assert backend.load_pipeline("Lightricks/LTX-2", model_kind = "pipeline")["loaded"] is True+++def test_the_mps_allocator_cache_is_released_before_the_budget_is_read(monkeypatch):+ """Dropping a pipeline leaves its buffers RESERVED in torch's MPS caching allocator. The+ budget is a system-memory reading, which counts those bytes as used, so without emptying the+ cache first a model swap that fits is refused. torch.mps.empty_cache "releases all unoccupied+ cached memory currently held by the caching allocator"."""+ import sys+ import types++ import core.inference.diffusion_memory as dm++ calls: list = []+ fake_torch = types.SimpleNamespace(+ mps = types.SimpleNamespace(empty_cache = lambda: calls.append("mps"))+ )+ monkeypatch.setitem(sys.modules, "torch", fake_torch)+ monkeypatch.setattr(+ dm,+ "snapshot_device_memory",+ lambda t: dm.DeviceMemory("mps", "mps", "unified_memory", 1, 2),+ )++ dm.settled_snapshot_device_memory(types.SimpleNamespace(device = "mps", backend = "mps"))+ assert calls == ["mps"], "the MPS allocator must be emptied before the reading is taken"++def _fake_h3_vae():"""A stand-in with the shapes that matter: an encoder half, a decoder with bothautocast-eligible and float32-only parameters, and a post_quant_conv."""@@ -5040,3 +5136,305 @@ def test_dense_quant_replan_uses_the_scaled_text_encoder(fake_runtime, monkeypat(transformer_gb * _QUANT_STEADY_FACTOR["int8"] + text_encoder_gb * scale + vae_gb)* _MIB_PER_GB)+++# ── the refusal reads the plan the load will actually take ────────────────────+# Two ways the hard unified-memory refusal added in PR #8213 can read a number the load never+# occupies, both of which turn it from a guard into a false rejection.+++def _fp32_promoted_cuda_target(monkeypatch):+ """A CUDA target whose fp16 promotes to fp32, i.e. dtype_scale == 2 in the video planner."""+ import torch++ import core.inference.video as video_mod+ from core.inference.diffusion_device import DiffusionDeviceTarget++ target = DiffusionDeviceTarget(+ device = "cuda",+ dtype = torch.float16,+ backend = "cuda",+ vendor = "nvidia",+ supports_model_cpu_offload = True,+ supports_default_torch_compile = False,+ supports_pinned_transfer = True,+ )+ monkeypatch.setattr(video_mod, "resolve_diffusion_device_target", lambda: target)+ return target+++def test_the_fp32_promotion_does_not_double_an_already_fp32_wan_vae(fake_runtime, monkeypatch):+ # A device without bf16 promotes the whole plan by 2. Wan's VAE term is recorded at fp32+ # ALREADY (the family comment says so) and assembly pins that VAE to fp32 whatever the+ # promotion does, so doubling it counts 2.8 GB twice on TI2V-5B. Against a hard refusal that+ # is a load rejected over bytes it never allocates.+ from core.inference.video_families import detect_video_family++ _fp32_promoted_cuda_target(monkeypatch)+ transformer_gb, te_gb, vae_gb = detect_video_family(+ "Wan-AI/Wan2.2-TI2V-5B-Diffusers"+ ).bf16_components_gb++ calls = _capture_plan(monkeypatch)+ VideoBackend().load_pipeline("Wan-AI/Wan2.2-TI2V-5B-Diffusers", model_kind = "pipeline")+ # bf16 terms doubled, the fp32 VAE term left exactly where the table put it.+ assert calls[0]["model_dense_mib"] == int(+ ((transformer_gb + te_gb) * 2.0 + vae_gb) * _MIB_PER_GB+ )+++def test_the_fp32_promotion_still_doubles_a_bf16_vae(fake_runtime, monkeypatch):+ # LTX-2 does not force fp32, so its VAE term IS a bf16 one and must keep scaling with the rest.+ from core.inference.video_families import detect_video_family++ _fp32_promoted_cuda_target(monkeypatch)+ components = detect_video_family("Lightricks/LTX-2").bf16_components_gb++ calls = _capture_plan(monkeypatch)+ VideoBackend().load_pipeline("Lightricks/LTX-2", model_kind = "pipeline")+ assert calls[0]["model_dense_mib"] == int(sum(components) * 2.0 * _MIB_PER_GB)+++def test_unified_memory_refuses_on_the_dense_peak_even_when_a_quant_is_requested(+ fake_runtime, monkeypatch+):+ """The quant re-plan prices the DiT's STEADY size, but the video path has no pre-quantised+ artifact: the transformer is always built dense and quantize_transformer rewrites it in place,+ so the build PEAK is the bf16 figure. On unified memory the peak is what the OS kills for, so+ the refusal must keep reading the dense plan -- accepting the steady size here would wave+ through exactly the load this guard exists to stop."""+ import torch++ import core.inference.video as video_mod+ from core.inference.diffusion_device import DiffusionDeviceTarget+ from core.inference.diffusion_memory import DeviceMemory++ target = DiffusionDeviceTarget(+ device = "cuda",+ dtype = torch.bfloat16,+ backend = "cuda",+ vendor = "nvidia",+ supports_model_cpu_offload = True,+ supports_default_torch_compile = False,+ supports_pinned_transfer = True,+ )+ monkeypatch.setattr(video_mod, "resolve_diffusion_device_target", lambda: target)+ monkeypatch.setattr(video_mod, "dense_transformer_supported", lambda t: True)+ monkeypatch.setattr(+ video_mod, "select_transformer_quant_scheme", lambda t, q, family = None: "fp8"+ )+ # An integrated CUDA device: 48 GiB shared, so LTX-2's ~65 GB of dense weights cannot fit even+ # though the fp8 steady size would.+ total = 48 * 1024+ monkeypatch.setattr(+ video_mod,+ "settled_snapshot_device_memory",+ lambda t: DeviceMemory("cuda", "cuda", "unified_memory", int(total * 0.80), total),+ )++ with pytest.raises(RuntimeError) as excinfo:+ VideoBackend().load_pipeline(+ "Lightricks/LTX-2", model_kind = "pipeline", transformer_quant = "auto"+ )+ assert "unified memory" in str(excinfo.value)+++def test_unified_memory_refuses_the_h3_modular_load_before_load_components(+ fake_runtime, monkeypatch+):+ """MiniMax-H3 returns into the modular workflow ABOVE load_pipeline's refusal, so the one+ family the matrix says must be declined on every Mac it models was the only one that never+ reached the check. load_components builds every component dense and the ComponentsManager's+ CPU offload frees nothing on unified memory, so 144.2 GB of components is an OS kill with no+ torch OOM to catch."""+ import core.inference.video as video_mod+ from core.inference.diffusion_device import DiffusionDeviceTarget++ torch = sys.modules["torch"]+ diffusers = sys.modules["diffusers"]+ diffusers.ComponentsManager = _FakeComponentsManager+ diffusers.ModularPipeline = _FakeModularPipeline+ _FakeModularPipeline.instance = None++ target = DiffusionDeviceTarget(+ device = "mps",+ dtype = torch.bfloat16,+ backend = "mps",+ vendor = "apple",+ supports_model_cpu_offload = True,+ supports_default_torch_compile = False,+ supports_pinned_transfer = False,+ )+ monkeypatch.setattr(video_mod, "resolve_diffusion_device_target", lambda: target)+ monkeypatch.setattr(video_mod, "settled_snapshot_device_memory", _unified_snapshot(128))++ fam = _detect_load_family("MiniMaxAI/MiniMax-H3", None, "minimax-h3")+ backend = VideoBackend()+ with pytest.raises(RuntimeError) as excinfo:+ backend._load_h3_modular_pipeline(+ diffusers = diffusers,+ torch = torch,+ fam = fam,+ repo_id = "MiniMaxAI/MiniMax-H3",+ base = fam.base_repo,+ kind = "pipeline",+ dtype = torch.bfloat16,+ device = "mps",+ hf_token = None,+ memory_mode = None,+ target = target,+ )+ message = str(excinfo.value)+ assert "minimax-h3" in message and "unified memory" in message+ # Refused BEFORE any component was built.+ assert _FakeModularPipeline.instance is not None+ assert _FakeModularPipeline.instance.load_kwargs is None+ assert backend.status()["loaded"] is False+++def test_the_h3_modular_refusal_prices_a_seeded_prequant_denoiser(fake_runtime, monkeypatch):+ """A hosted pre-quantized checkpoint replaces the dense 66.3 GB denoiser, so the refusal must+ size that instead -- refusing it on the dense figure would reject a load that never builds+ those weights. It is still the whole component set: the encoder and the VAEs load dense."""+ import core.inference.video as video_mod+ from core.inference.video_families import detect_video_family++ fam = detect_video_family("MiniMaxAI/MiniMax-H3")+ transformer_gb, te_gb, vae_gb = fam.bf16_components_gb+ seen: list[int] = []++ def _capture(*, model_dense_mib = None, **kwargs):+ seen.append(int(model_dense_mib or 0))+ return types.SimpleNamespace(offload_policy = "none", estimates = {}, device_memory = None)++ monkeypatch.setattr(video_mod, "plan_diffusion_memory", _capture)+ monkeypatch.setattr(video_mod, "settled_snapshot_device_memory", lambda t: None)+ monkeypatch.setattr(video_mod, "raise_on_unified_memory_shortfall", lambda *a, **k: None)++ # The MEASURED hosted size, not the generic 0.55 steady factor: H3's checkpoints are+ # quantized AND structurally pruned, so the factor reads 36.5 GB against a real ~20.3 GB and+ # the 16 GB gap refuses a supported prequant load that fits on a 128 GB Mac.+ assert fam.prequant_resident_gb == 20.3+ for scheme, expected_transformer in (+ (None, transformer_gb),+ ("fp8", fam.prequant_resident_gb),+ ("int8", fam.prequant_resident_gb),+ # An unknown scheme still takes the family's hosted size when it publishes one; the+ # generic factor is only the fallback for a family that does not.+ ("bogus", fam.prequant_resident_gb),+ ):+ VideoBackend._raise_on_modular_unified_shortfall(+ fam,+ target = None,+ dtype = sys.modules["torch"].bfloat16,+ device = "mps",+ memory_mode = None,+ scheme = scheme,+ )+ assert seen[-1] == int(+ (expected_transformer + te_gb + vae_gb) * (1000.0**3 / (1024.0 * 1024.0))+ ), scheme+ # The whole point: on a unified-memory host big enough for the ~20.3 GB checkpoint but not+ # for the 36.5 GB the generic factor invents, the fp8 pick must NOT be refused. 160 GiB at+ # 80% free is inside that window (the dense set is refused there either way).+ from core.inference.diffusion_memory import unified_memory_shortfall_message++ from core.inference.diffusion_memory import (+ DeviceMemory,+ estimate_video_runtime_mib,+ plan_diffusion_memory,+ )++ mib_per_gb = 1000.0**3 / (1024.0 * 1024.0)+ total = 160 * 1024+ memory = DeviceMemory("mps", "mps", "unified_memory", int(total * 0.80), total)+ device = type("T", (), {"supports_model_cpu_offload": True, "device": "mps"})()+ headroom = estimate_video_runtime_mib(+ width = fam.resolution_presets[0][0],+ height = fam.resolution_presets[0][1],+ num_frames = fam.default_num_frames,+ )+ for gb, refused in (+ (fam.prequant_resident_gb + te_gb + vae_gb, False),+ # What the generic 0.55 factor would have budgeted: refused, for 16 GB that do not exist.+ (transformer_gb * 0.55 + te_gb + vae_gb, True),+ (sum(fam.bf16_components_gb), True),+ ):+ plan = plan_diffusion_memory(+ target = device,+ device_memory = memory,+ model_dense_mib = int(gb * mib_per_gb),+ runtime_headroom_mib = headroom,+ )+ assert (unified_memory_shortfall_message(plan, family = fam.name) is not None) is refused, gb+++def test_the_h3_modular_refusal_reruns_when_the_prequant_checkpoint_does_not_land(+ fake_runtime, monkeypatch+):+ """The hosted-denoiser load is best-effort by contract: a missing, corrupt, stale or+ base-mismatched checkpoint drops to the released bfloat16 components. Sizing the load as+ quantized and then building dense with no second check is the OS kill this guard exists to+ prevent -- on a host whose budget fits the ~20.3 GB checkpoint but not the 66.3 GB dense one."""+ import core.inference.video as video_mod+ from core.inference.diffusion_device import DiffusionDeviceTarget++ torch = sys.modules["torch"]+ diffusers = sys.modules["diffusers"]+ diffusers.ComponentsManager = _FakeComponentsManager+ diffusers.ModularPipeline = _FakeModularPipeline+ diffusers.MiniMaxH3Transformer3DModel = _FakeTransformer+ _FakeModularPipeline.instance = None++ target = DiffusionDeviceTarget(+ device = "mps",+ dtype = torch.bfloat16,+ backend = "mps",+ vendor = "apple",+ supports_model_cpu_offload = True,+ supports_default_torch_compile = False,+ supports_pinned_transfer = False,+ )+ monkeypatch.setattr(video_mod, "resolve_diffusion_device_target", lambda: target)+ # 160 GiB: the prequant pick fits, the dense component set does not.+ monkeypatch.setattr(video_mod, "settled_snapshot_device_memory", _unified_snapshot(160))++ fam = _detect_load_family("MiniMaxAI/MiniMax-H3", None, "minimax-h3")+ sized: list = []+ real = VideoBackend._raise_on_modular_unified_shortfall++ def _spy(family, **kwargs):+ sized.append(kwargs["scheme"])+ return real(family, **kwargs)++ monkeypatch.setattr(VideoBackend, "_raise_on_modular_unified_shortfall", staticmethod(_spy))+ # The checkpoint resolves but does not load: exactly the best-effort None contract.+ import core.inference.diffusion_prequant as prequant_mod++ monkeypatch.setattr(+ prequant_mod,+ "resolve_prequant_source",+ lambda fam, scheme, base_repo = None: types.SimpleNamespace(location = "unsloth/H3-FP8"),+ )+ monkeypatch.setattr(prequant_mod, "load_prequantized_transformer", lambda *a, **k: None)++ with pytest.raises(RuntimeError) as excinfo:+ VideoBackend()._load_h3_modular_pipeline(+ diffusers = diffusers,+ torch = torch,+ fam = fam,+ repo_id = "MiniMaxAI/MiniMax-H3",+ base = fam.base_repo,+ kind = "pipeline",+ dtype = torch.bfloat16,+ device = "mps",+ hf_token = None,+ memory_mode = None,+ transformer_quant = "fp8",+ target = target,+ )+ assert "minimax-h3" in str(excinfo.value) and "unified memory" in str(excinfo.value)+ # Sized twice: once for the pick that was requested, once for what actually landed.+ assert sized == ["fp8", None]+ # ... and nothing was built.+ assert _FakeModularPipeline.instance.load_kwargs is Nonediff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.pyindex 2e835c0d8a8..dc477cc4995 100644--- a/studio/backend/utils/hardware/hardware.py+++ b/studio/backend/utils/hardware/hardware.py@@ -712,8 +712,17 @@ def clear_gpu_cache():except Exception as e:logger.debug("Failed to clear XPU cache: %s", e)elif device == DeviceType.MLX:- # MLX manages memory automatically; gc.collect() above is enough.- pass+ # MLX manages its own memory, but Apple Silicon also runs torch MPS (diffusion/video),+ # and torch's MPS caching allocator keeps freed buffers reserved from the shared pool.+ # Those bytes read as used system memory, so a teardown that skips this leaves the next+ # load budgeting against a pool that looks smaller than it is.+ try:+ import torch+ empty_cache = getattr(getattr(torch, "mps", None), "empty_cache", None)+ if callable(empty_cache):+ empty_cache()+ except Exception as e:+ logger.debug("Failed to clear MPS cache: %s", e)def get_gpu_memory_info() -> Dict[str, Any]: