Skip to content

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.

Studio diffusion: cap the single-file host RAM refusal reserve at the fp8-storage reserve (#14758)

Daniel Hanadf2a6c9122c
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index d3023f7b823..8bdb03899a0 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -430,6 +430,7 @@ from .diffusion_comfy_quant import (
comfy_int8_backend,
comfy_torchao_quantized,
fp8_storage_wanted,
+ fp8_widen_chosen,
fp8_stored_layers,
pipe_fp8_stored_layers,
load_comfy_quant_transformer,
@@ -9793,6 +9794,9 @@ class DiffusionBackend:
fp8_storage = self._fp8_storage_for(
single_file_path, target, loras
),
+ fp8_widen_chosen = self._fp8_widen_for(
+ single_file_path, target, loras
+ ),
)
comfy_compile = comfy_torchao_quantized(transformer)
else:
@@ -9810,6 +9814,9 @@ class DiffusionBackend:
fp8_storage = self._fp8_storage_for(
single_file_path, target, loras
),
+ fp8_widen_chosen = self._fp8_widen_for(
+ single_file_path, target, loras
+ ),
)
else:
# A safetensors single-file (fp8) carries its own dtype: no GGUF dequant config.
@@ -11186,6 +11193,14 @@ class DiffusionBackend:
priced = getattr(self, "_comfy_priced_offload", None) or {}
return not plan_keeps_transformer_resident(plan) or bool(priced.get(str(single_file_path)))
+ def _fp8_widen_for(self, single_file_path: Any, target: Any, loras: Any) -> bool:
+ """The planner's ``fp8_widen_chosen`` pick for this file, re-checked against device / LoRA / env: only then
+ does the host RAM refusal reserve what that rule keeps free."""
+ picks = getattr(self, "_fp8_widen_picks", None) or {}
+ return bool(picks.get(str(single_file_path))) and comfy_fp8_storage(
+ target, lora = _has_active_lora(loras)
+ )
+
def _fp8_storage_for(self, single_file_path: Any, target: Any, loras: Any) -> bool:
"""The planner's ``fp8_storage_wanted`` pick for this file, re-checked against device / LoRA / env."""
picks = getattr(self, "_fp8_storage_picks", None) or {}
@@ -12727,21 +12742,25 @@ class DiffusionBackend:
# Re-plan at the fp8-stored size: a widened load that had to offload may now stay resident.
from .diffusion_memory import _available_system_memory_mib
- store = fp8_storage_wanted(
- target,
+ fp8_rule = dict(
lora = lora,
offload = not plan_keeps_transformer_resident(plan),
widened_mib = transformer_resident,
host_available_mib = _available_system_memory_mib(),
)
+ store = fp8_storage_wanted(target, **fp8_rule)
picks = self.__dict__.setdefault("_fp8_storage_picks", {})
picks[str(single_file_path)] = store
+ self.__dict__.setdefault("_fp8_widen_picks", {})[str(single_file_path)] = (
+ not store and fp8_widen_chosen(target, **fp8_rule)
+ )
if store:
plan = _plan(
model_dense_mib - int(transformer_resident) + single_file_fp8_stored_mib
)
elif kind == "single_file" and single_file_path:
self.__dict__.setdefault("_fp8_storage_picks", {})[str(single_file_path)] = False
+ self.__dict__.setdefault("_fp8_widen_picks", {})[str(single_file_path)] = False
return plan
@staticmethod
diff --git a/studio/backend/core/inference/diffusion_comfy_quant.py b/studio/backend/core/inference/diffusion_comfy_quant.py
index 9e20379479b..54d9f037b0f 100644
--- a/studio/backend/core/inference/diffusion_comfy_quant.py
+++ b/studio/backend/core/inference/diffusion_comfy_quant.py
@@ -30,6 +30,7 @@ from typing import Any, Optional
from .diffusion_comfy_block import BLOCK_SIZES, MXFP8, NVFP4, tiled_scale_numel
from .diffusion_single_file_converters import host_ram_budget_scope
+from .diffusion_small_host import FP8_STORAGE_HOST_RESERVE_MIB
COMFY_QUANT_SUFFIX = ".comfy_quant"
QUANT_METADATA_KEY = "_quantization_metadata"
@@ -39,7 +40,6 @@ COMFY_FP8_ENV = "UNSLOTH_DIFFUSION_COMFY_FP8"
# Store fp8 layers no fp8 GEMM takes as fp8, widened per layer (ComfyUI manual_cast). Unset: only when widening
# would offload or crowd host RAM (per-layer widen costs eager steps); ``1``: always; ``0``: never.
FP8_STORAGE_ENV = "UNSLOTH_DIFFUSION_FP8_STORAGE"
-FP8_STORAGE_HOST_RESERVE_MIB = 4096
# Header metadata our own converter writes (base model, scheme); ComfyUI ignores it.
CONVERSION_RECORD_KEY = "unsloth_comfy_conversion"
@@ -979,6 +979,26 @@ def fp8_storage_wanted(
return int(widened_mib) + FP8_STORAGE_HOST_RESERVE_MIB > int(host_available_mib)
+def fp8_widen_chosen(
+ target: Any = None,
+ *,
+ lora: bool = False,
+ offload: bool = False,
+ widened_mib: Optional[int] = None,
+ host_available_mib: Optional[int] = None,
+) -> bool:
+ """Whether ``fp8_storage_wanted`` had the choice and widened because the load fits with its host reserve free. Only
+ such a load is refused against that reserve (``single_file_host_reserve_mib``); every other one keeps the
+ proportional small-host reserve."""
+ if not comfy_fp8_storage(target, lora = lora) or fp8_storage_forced() or offload:
+ return False
+ if widened_mib is None or host_available_mib is None:
+ return False
+ return not fp8_storage_wanted(
+ target, lora = lora, widened_mib = widened_mib, host_available_mib = host_available_mib
+ )
+
+
def comfy_fp8_storage(target: Any = None, *, lora: bool = False) -> bool:
"""Whether fp8 storage can run: same weights as the load-time dequant, half the bytes. Off for a LoRA (needs
dense Linears), MPS and torch without float8."""
@@ -1118,6 +1138,7 @@ def load_comfy_quant_transformer(
prepare_model: Any = None,
keep_dtype: Any = None,
fp8_storage: Optional[bool] = None,
+ fp8_widen_chosen: bool = False,
) -> Any:
"""Build ``transformer_cls`` from the ComfyUI-quantized ``path``.
@@ -1263,7 +1284,16 @@ def load_comfy_quant_transformer(
# The header estimate refuses early; the budget it activates is charged by every allocating helper
# below, so a layer the estimate cannot see (runtime filters, nibble swaps) still cannot OOM the host.
budget = HostRamBudget(
- path, f"expanding its quantized weights to {str(dtype).replace('torch.', '')}", logger
+ path,
+ f"expanding its quantized weights to {str(dtype).replace('torch.', '')}",
+ logger,
+ # The fp8-storage rule chose to widen this load: refuse against its reserve, and only if fp8 layers widen.
+ fp8_widen_chosen = bool(fp8_widen_chosen)
+ and not fp8_storage
+ and any(
+ layer.format in FP8_FORMATS and _widened.get(layer.name + ".weight")
+ for layer in scan.layers.values()
+ ),
)
budget.check(
converted_host_bytes(
diff --git a/studio/backend/core/inference/diffusion_single_file_converters.py b/studio/backend/core/inference/diffusion_single_file_converters.py
index 84521321467..cdb1fff832d 100644
--- a/studio/backend/core/inference/diffusion_single_file_converters.py
+++ b/studio/backend/core/inference/diffusion_single_file_converters.py
@@ -445,11 +445,14 @@ class HostRamBudget:
path: str,
why: str,
logger: Any = None,
+ *,
+ fp8_widen_chosen: bool = False,
) -> None:
from .diffusion_small_host import (
host_ram_check_disabled,
host_ram_mib,
host_reserve_mib,
+ single_file_host_reserve_mib,
)
self.path, self.why, self.logger = path, why, logger
@@ -469,7 +472,11 @@ class HostRamBudget:
if available is None:
return
self.available_mib = int(available)
- self.reserve_mib = host_reserve_mib(total)
+ # Capped only for a load the fp8-storage rule chose to widen, so the two never disagree; any other load
+ # (no fp8 storage option, LoRA, int8 / nvfp4 layers) keeps the proportional small-host reserve.
+ self.reserve_mib = (
+ single_file_host_reserve_mib(total) if fp8_widen_chosen else host_reserve_mib(total)
+ )
# Armed by the file size here, and by the widened estimate in ``check``: a 900 MiB nvfp4 file widens
# to 3.6 GiB of bf16. Only a load small on disk AND in its estimate is never checked.
try:
@@ -581,11 +588,13 @@ def load_original_layout_transformer(
logger: Any = None,
*,
fp8_storage: bool = False,
+ fp8_widen_chosen: bool = False,
) -> Any:
"""Load a plain original-layout safetensors file for a class without ``from_single_file``
(Krea 2 on diffusers 0.40). ``sf_kwargs`` = the ``from_single_file`` kwargs. Cast like
``from_pretrained`` (``_keep_in_fp32_modules`` stay fp32); strict on keys and shapes. ``fp8_storage``
- keeps fp8 Linears as fp8 with unit scales."""
+ keeps fp8 Linears as fp8 with unit scales; ``fp8_widen_chosen``: the fp8-storage rule chose to widen it, so the
+ host RAM refusal uses that rule's reserve."""
import torch
from diffusers.loaders import single_file_model as sfm
@@ -612,7 +621,10 @@ def load_original_layout_transformer(
keep = [keep]
# Before any read: fp8 widened to bf16 (13B Krea 2: ~26 GB) used to OOM the whole app.
budget = HostRamBudget(
- path, f"widening its weights to {str(dtype).replace('torch.', '')}", logger
+ path,
+ f"widening its weights to {str(dtype).replace('torch.', '')}",
+ logger,
+ fp8_widen_chosen = bool(fp8_widen_chosen) and not fp8_storage,
)
budget.check(
converted_host_bytes(
diff --git a/studio/backend/core/inference/diffusion_small_host.py b/studio/backend/core/inference/diffusion_small_host.py
index bcd16521278..99294eedb25 100644
--- a/studio/backend/core/inference/diffusion_small_host.py
+++ b/studio/backend/core/inference/diffusion_small_host.py
@@ -27,6 +27,9 @@ _MIB = 1024 * 1024
_STREAM_MIN_MIB = 512
_HOST_RESERVE_MIN_MIB = 3072
_HOST_RESERVE_FRACTION = 0.10
+# Host RAM the fp8-storage rule (``diffusion_comfy_quant.fp8_storage_wanted``) keeps free when it lets a single file
+# widen. The single-file refusal reserves at most this much, so it never refuses a widened load that rule chose.
+FP8_STORAGE_HOST_RESERVE_MIB = 4096
# 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
@@ -186,6 +189,12 @@ def host_reserve_mib(total_mib: Optional[int]) -> int:
return max(_HOST_RESERVE_MIN_MIB, int((total_mib or 0) * _HOST_RESERVE_FRACTION))
+def single_file_host_reserve_mib(total_mib: Optional[int]) -> int:
+ """Reserve of the single-file host RAM refusal: the small-host reserve, capped at the fp8-storage rule's. Hosts
+ up to 40 GB are unchanged; above, 10% would refuse loads the fp8-storage rule widens because they fit."""
+ return min(host_reserve_mib(total_mib), FP8_STORAGE_HOST_RESERVE_MIB)
+
+
def _dtype_name(dtype: Any) -> str:
return str(dtype).replace("torch.", "")
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 11b76bfc512..eff8afd8e8f 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -66,6 +66,7 @@ from .diffusion_comfy_quant import (
comfy_fp8_backend,
comfy_int8_backend,
fp8_storage_wanted,
+ fp8_widen_chosen,
pipe_fp8_stored_layers,
comfy_resident_mib,
load_comfy_quant_transformer,
@@ -508,13 +509,21 @@ def _video_comfy_backends(
DiT price; a resident load stores fp8 when widening it would leave under the host reserve, as an image does.
``keep=False`` (the user asked for the bf16 DiT) dequantizes everything."""
if not keep:
- return {"int8_backend": None, "fp8_backend": None, "fp8_storage": False}
+ return {
+ "int8_backend": None,
+ "fp8_backend": None,
+ "fp8_storage": False,
+ "fp8_widen_chosen": False,
+ }
offload = priced_offload or not _video_comfy_resident(plan, bf16_plan)
name = getattr(fam, "name", None)
+ storage = _video_fp8_storage(fam, target, offload, widened_mib = widened_mib)
return {
"int8_backend": comfy_int8_backend(target, name, base, offload = offload),
"fp8_backend": comfy_fp8_backend(target, name, base, offload = offload),
- "fp8_storage": _video_fp8_storage(fam, target, offload, widened_mib = widened_mib),
+ "fp8_storage": storage,
+ "fp8_widen_chosen": not storage
+ and _video_fp8_storage(fam, target, offload, widened_mib = widened_mib, widen_chosen = True),
}
@@ -538,18 +547,19 @@ def _video_fp8_storage(
offload: bool,
*,
widened_mib: Optional[int] = None,
+ widen_chosen: bool = False,
) -> bool:
"""``fp8_storage_wanted`` for a video DiT, with the host RAM the load would widen into when ``widened_mib`` is
- known. H3 is excluded: its pin / stream / residency path is built on torchao weights."""
+ known. H3 is excluded: its pin / stream / residency path is built on torchao weights. ``widen_chosen``: answer
+ ``fp8_widen_chosen`` instead (the rule had the choice and widened)."""
if getattr(fam, "name", None) == "minimax-h3":
return False
available = None
if widened_mib is not None and not offload:
from .diffusion_small_host import host_ram_mib
available = host_ram_mib()[1]
- return fp8_storage_wanted(
- target, offload = offload, widened_mib = widened_mib, host_available_mib = available
- )
+ rule = fp8_widen_chosen if widen_chosen else fp8_storage_wanted
+ return rule(target, offload = offload, widened_mib = widened_mib, host_available_mib = available)
def _video_comfy_resident_mib(
diff --git a/studio/backend/core/inference/video_ltx2.py b/studio/backend/core/inference/video_ltx2.py
index 66057f8e6fb..a8ecf3862df 100644
--- a/studio/backend/core/inference/video_ltx2.py
+++ b/studio/backend/core/inference/video_ltx2.py
@@ -1253,6 +1253,7 @@ def load_ltx23_comfy_transformer(
int8_backend: Optional[str] = None,
fp8_backend: Optional[str] = None,
fp8_storage: Optional[bool] = None,
+ fp8_widen_chosen: bool = False,
family: Optional[str] = None,
target: Any = None,
logger: Any = None,
@@ -1281,6 +1282,7 @@ def load_ltx23_comfy_transformer(
int8_backend = int8_backend,
fp8_backend = fp8_backend,
fp8_storage = fp8_storage,
+ fp8_widen_chosen = fp8_widen_chosen,
family = family,
target = target,
logger = logger,
diff --git a/studio/backend/core/inference/video_ltx25.py b/studio/backend/core/inference/video_ltx25.py
index 68898defb93..5f50fa05897 100644
--- a/studio/backend/core/inference/video_ltx25.py
+++ b/studio/backend/core/inference/video_ltx25.py
@@ -414,6 +414,7 @@ def load_ltx25_comfy_transformer(
int8_backend: Optional[str] = None,
fp8_backend: Optional[str] = None,
fp8_storage: Optional[bool] = None,
+ fp8_widen_chosen: bool = False,
family: Optional[str] = None,
target: Any = None,
logger: Any = None,
@@ -440,6 +441,7 @@ def load_ltx25_comfy_transformer(
int8_backend = int8_backend,
fp8_backend = fp8_backend,
fp8_storage = fp8_storage,
+ fp8_widen_chosen = fp8_widen_chosen,
family = family,
target = target,
logger = logger,
diff --git a/studio/backend/tests/test_diffusion_comfy_quant.py b/studio/backend/tests/test_diffusion_comfy_quant.py
index 3d7fc2d1539..a7dfe53754a 100644
--- a/studio/backend/tests/test_diffusion_comfy_quant.py
+++ b/studio/backend/tests/test_diffusion_comfy_quant.py
@@ -1215,9 +1215,33 @@ def test_fnuz_krea2_file_is_not_planned_at_the_stored_size(monkeypatch, tmp_path
monkeypatch, tmp_path, fam = fam, resident_at = path, fits_mib = 500
)
assert backend._fp8_storage_picks[p] is picked, dtype
+ assert backend._fp8_widen_picks[p] is False, dtype
assert seen[-1] == (1000 if picked else 2000)
+def test_a_resident_widen_with_host_room_is_recorded_as_the_fp8_rules_choice(monkeypatch, tmp_path):
+ """Fits resident and the host has room: the rule widens, and the load refuses against the rule's reserve; a LoRA
+ at load time drops that choice (it widens because it must)."""
+ from safetensors.torch import save_file
+
+ from core.inference import diffusion as d
+ from core.inference.diffusion_krea2 import KREA2_FAMILY_NAME
+
+ monkeypatch.delenv(cq.FP8_STORAGE_ENV, raising = False)
+ fam = types.SimpleNamespace(name = KREA2_FAMILY_NAME, single_file_is_pipeline = False)
+ path = tmp_path / "krea2_fn.safetensors"
+ save_file({"blocks.0.weight": torch.zeros(4, 4, dtype = torch.float8_e4m3fn)}, str(path))
+ backend, final, seen, p = _plan_harness(
+ monkeypatch, tmp_path, fam = fam, resident_at = path, fits_mib = 5000
+ )
+ assert backend._fp8_storage_picks[p] is False and final.resident is True
+ assert backend._fp8_widen_picks[p] is True
+ monkeypatch.setattr(d, "comfy_fp8_storage", lambda target, lora = False: not lora)
+ assert backend._fp8_widen_for(p, None, None) is True
+ monkeypatch.setattr(d, "_has_active_lora", lambda loras: True)
+ assert backend._fp8_widen_for(p, None, None) is False
+
+
def test_a_plan_priced_with_the_offload_only_backend_keeps_it_when_resident(monkeypatch, tmp_path):
"""Int8 priced via the offload twin: the re-plan fits resident but the loader must still probe offloaded."""
diff --git a/studio/backend/tests/test_diffusion_single_file_host_ram.py b/studio/backend/tests/test_diffusion_single_file_host_ram.py
index 8da0aa8de08..6d81a664c12 100644
--- a/studio/backend/tests/test_diffusion_single_file_host_ram.py
+++ b/studio/backend/tests/test_diffusion_single_file_host_ram.py
@@ -267,3 +267,145 @@ def test_a_file_that_fits_only_stored_loads_with_fp8_storage_and_is_refused_wide
monkeypatch.setenv(cq.FP8_STORAGE_ENV, "0")
with pytest.raises(RuntimeError, match = "Not enough system RAM"):
load(fp8_storage = cq.comfy_fp8_storage(None))
+
+
+_GIB = 1024
+_KREA2_WIDENED_MIB = 24 * _GIB # Krea 2 fp8 widened to bf16
+
+
+def _budget(
+ tmp_path,
+ monkeypatch,
+ total_mib,
+ available_mib,
+ fp8_widen_chosen = False,
+):
+ monkeypatch.delenv(small_host.HOST_RAM_CHECK_ENV, raising = False)
+ _host(monkeypatch, available_mib, total_mib)
+ path = tmp_path / "krea2.safetensors"
+ path.write_bytes(b"\0")
+ return conv.HostRamBudget(
+ str(path), "widening its weights to bfloat16", fp8_widen_chosen = fp8_widen_chosen
+ )
+
+
[email protected]("available_gib", [28.5, 29.0, 30.0, 30.3])
+def test_big_host_loads_what_the_fp8_storage_rule_widens(tmp_path, monkeypatch, available_gib):
+ """64 GB host, Krea 2 (~24 GB widened), 28-30.4 GB free: the fp8-storage rule widens (the widened load fits its
+ reserve), so the single-file refusal must not reserve more and refuse the load the rule just chose."""
+ monkeypatch.delenv(cq.FP8_STORAGE_ENV, raising = False)
+ available = int(available_gib * _GIB)
+ cuda = type("T", (), {"device": "cuda", "dtype": torch.bfloat16})()
+ assert (
+ cq.fp8_storage_wanted(cuda, widened_mib = _KREA2_WIDENED_MIB, host_available_mib = available)
+ is False
+ )
+ chosen = cq.fp8_widen_chosen(cuda, widened_mib = _KREA2_WIDENED_MIB, host_available_mib = available)
+ assert chosen is True
+ budget = _budget(tmp_path, monkeypatch, 64 * _GIB, available, fp8_widen_chosen = chosen)
+ budget.check(_KREA2_WIDENED_MIB * conv._MIB) # no refusal
+
+
[email protected]("available_gib", [28.5, 29.0, 30.0, 30.3])
+def test_big_host_keeps_the_proportional_reserve_without_an_fp8_widen_choice(
+ tmp_path, monkeypatch, available_gib
+):
+ """No fp8-storage choice was made (int8 / nvfp4 file, LoRA, kill switch): the same load keeps the 10% reserve of
+ #14510 and is refused, as before the cap."""
+ budget = _budget(tmp_path, monkeypatch, 64 * _GIB, int(available_gib * _GIB))
+ assert (
+ budget.reserve_mib
+ == small_host.host_reserve_mib(64 * _GIB)
+ > cq.FP8_STORAGE_HOST_RESERVE_MIB
+ )
+ with pytest.raises(RuntimeError, match = "Not enough system RAM"):
+ budget.check(_KREA2_WIDENED_MIB * conv._MIB)
+
+
+def test_fp8_widen_chosen_only_when_the_rule_had_the_choice(monkeypatch):
+ monkeypatch.delenv(cq.FP8_STORAGE_ENV, raising = False)
+ cuda = type("T", (), {"device": "cuda", "dtype": torch.bfloat16})()
+ mps = type("T", (), {"device": "mps", "dtype": torch.bfloat16})()
+ room = dict(widened_mib = _KREA2_WIDENED_MIB, host_available_mib = 29 * _GIB)
+ assert cq.fp8_widen_chosen(cuda, **room) is True
+ # no fp8 storage option: LoRA, MPS, offload forces storage, unknown sizes, crowded host (stores instead)
+ assert cq.fp8_widen_chosen(cuda, lora = True, **room) is False
+ assert cq.fp8_widen_chosen(mps, **room) is False
+ assert cq.fp8_widen_chosen(cuda, offload = True, **room) is False
+ assert cq.fp8_widen_chosen(cuda, widened_mib = _KREA2_WIDENED_MIB) is False
+ assert (
+ cq.fp8_widen_chosen(cuda, widened_mib = _KREA2_WIDENED_MIB, host_available_mib = 26 * _GIB)
+ is False
+ )
+ for env in ("0", "1"):
+ monkeypatch.setenv(cq.FP8_STORAGE_ENV, env)
+ assert cq.fp8_widen_chosen(cuda, **room) is False
+
+
+def _reserve_seen(monkeypatch):
+ seen = []
+ real = conv.HostRamBudget.check
+
+ def spy(self, need_bytes):
+ seen.append(self.reserve_mib)
+ return real(self, need_bytes)
+
+ monkeypatch.setattr(conv.HostRamBudget, "check", spy)
+ return seen
+
+
+def test_loaders_cap_the_reserve_only_for_an_fp8_widen_choice(tmp_path, monkeypatch, krea2):
+ """Both single-file loaders refuse against the capped reserve only when the planner chose to widen fp8."""
+ total = 64 * _GIB
+ proportional = small_host.host_reserve_mib(total)
+ _host(monkeypatch, 60 * _GIB, total)
+ seen = _reserve_seen(monkeypatch)
+ path, _ = _write(tmp_path, "fp8")
+ conv.load_original_layout_transformer(krea2, str(path), dict(_KWARGS))
+ conv.load_original_layout_transformer(krea2, str(path), dict(_KWARGS), fp8_widen_chosen = True)
+ path, _ = _write(tmp_path, "fp8_scaled")
+ scan = cq.refuse_comfy_quant(str(path))
+ for chosen in (False, True):
+ cq.load_comfy_quant_transformer(
+ krea2,
+ str(path),
+ scan,
+ dict(_KWARGS),
+ int8_backend = None,
+ fp8_backend = None,
+ fp8_widen_chosen = chosen,
+ )
+ cap = cq.FP8_STORAGE_HOST_RESERVE_MIB
+ assert seen == [proportional, cap, proportional, cap]
+
+
+def test_reserves_cannot_drift(monkeypatch):
+ """The single-file refusal never reserves more than the fp8-storage rule keeps free when it widens."""
+ for total in (8 * _GIB, 16 * _GIB, 31 * _GIB, 40 * _GIB, 64 * _GIB, 256 * _GIB, 2048 * _GIB):
+ assert small_host.single_file_host_reserve_mib(total) <= cq.FP8_STORAGE_HOST_RESERVE_MIB
+ assert cq.FP8_STORAGE_HOST_RESERVE_MIB == small_host.FP8_STORAGE_HOST_RESERVE_MIB
+
+
+def test_big_host_still_refuses_a_load_that_cannot_fit(tmp_path, monkeypatch):
+ """Too little free RAM for even the cheapest path is still refused before any read."""
+ budget = _budget(tmp_path, monkeypatch, 64 * _GIB, 20 * _GIB)
+ with pytest.raises(RuntimeError, match = "Not enough system RAM"):
+ budget.check(_KREA2_WIDENED_MIB * conv._MIB)
+ # fp8-stored (~12 GB) fits 20 GB free with the reserve; the same stored need is refused at 15 GB free
+ budget.check(12 * _GIB * conv._MIB)
+ budget = _budget(tmp_path, monkeypatch, 64 * _GIB, 15 * _GIB)
+ with pytest.raises(RuntimeError, match = "Not enough system RAM"):
+ budget.check(12 * _GIB * conv._MIB)
+
+
[email protected]("total_gib", [8, 16, 24, 31])
+def test_small_host_reserve_unchanged(tmp_path, monkeypatch, total_gib):
+ """Hosts up to 40 GB keep the small-host reserve max(3 GB, 10%) on the single-file refusal."""
+ total = total_gib * _GIB
+ reserve = max(3072, int(total * 0.10))
+ assert small_host.host_reserve_mib(total) == reserve
+ budget = _budget(tmp_path, monkeypatch, total, 6 * _GIB + reserve)
+ assert budget.reserve_mib == reserve
+ budget.check(6 * _GIB * conv._MIB)
+ with pytest.raises(RuntimeError, match = "Not enough system RAM"):
+ budget.check((6 * _GIB + 1) * conv._MIB)
diff --git a/studio/backend/tests/test_video_comfy_quant.py b/studio/backend/tests/test_video_comfy_quant.py
index c3687c2711e..f03f2928b61 100644
--- a/studio/backend/tests/test_video_comfy_quant.py
+++ b/studio/backend/tests/test_video_comfy_quant.py
@@ -414,6 +414,7 @@ def test_video_backends_follow_studio_rules(monkeypatch):
"int8_backend": "torchao",
"fp8_backend": "torchao",
"fp8_storage": False,
+ "fp8_widen_chosen": False,
}
# either plan offloading the DiT means the hooks move it: int8 takes the torchao-free twin, fp8 has no GEMM
# and stays stored as fp8, widened per layer
@@ -421,11 +422,13 @@ def test_video_backends_follow_studio_rules(monkeypatch):
"int8_backend": "native",
"fp8_backend": None,
"fp8_storage": True,
+ "fp8_widen_chosen": False,
}
assert vid._video_comfy_backends(fam, "b", None, _plan(True), keep = False) == {
"int8_backend": None,
"fp8_backend": None,
"fp8_storage": False,
+ "fp8_widen_chosen": False,
}
h3 = types.SimpleNamespace(name = "minimax-h3")
assert (
@@ -456,7 +459,12 @@ def test_a_smaller_offloaded_price_replans_and_keeps_the_offloaded_backends(monk
resident = vid._video_comfy_backends(fam, "b", None, _plan(True), _plan(True))
assert resident["fp8_storage"] is False and resident["int8_backend"] is None
kept = vid._video_comfy_backends(fam, "b", None, _plan(True), _plan(True), priced_offload = True)
- assert kept == {"int8_backend": "native", "fp8_backend": None, "fp8_storage": True}
+ assert kept == {
+ "int8_backend": "native",
+ "fp8_backend": None,
+ "fp8_storage": True,
+ "fp8_widen_chosen": False,
+ }
def test_video_plan_size_prices_only_what_runs_quantized(monkeypatch, tmp_path):
@@ -1087,13 +1095,21 @@ def test_a_resident_video_dit_that_fits_only_stored_gets_fp8_storage(tmp_path, m
)
picked = backends(widened_mib = widened)
- assert picked == {"int8_backend": None, "fp8_backend": None, "fp8_storage": True}
+ assert picked == {
+ "int8_backend": None,
+ "fp8_backend": None,
+ "fp8_storage": True,
+ "fp8_widen_chosen": False,
+ }
model = load(**picked)
assert model._unsloth_comfy_quant["fp8_stored"] == 4
assert model.attn.to_q.weight_q.dtype == torch.uint8
# room to widen: the faster widened load; H3 keeps its torchao-or-dequantize rule
monkeypatch.setattr(small_host, "host_ram_mib", lambda: (1 << 40, 4 * widened))
assert backends(widened_mib = widened)["fp8_storage"] is False
+ # that widen was the rule's choice, so its load refuses against the rule's reserve; no host price, no choice
+ assert backends(widened_mib = widened)["fp8_widen_chosen"] is True
+ assert backends()["fp8_widen_chosen"] is False
monkeypatch.setattr(small_host, "host_ram_mib", lambda: (1 << 40, available))
h3 = types.SimpleNamespace(name = "minimax-h3")
assert (
@@ -1105,6 +1121,6 @@ def test_a_resident_video_dit_that_fits_only_stored_gets_fp8_storage(tmp_path, m
# the kill switch widens, and the host RAM check refuses that load
monkeypatch.setenv(cq.FP8_STORAGE_ENV, "0")
widened_pick = backends(widened_mib = widened)
- assert widened_pick["fp8_storage"] is False
+ assert widened_pick["fp8_storage"] is False and widened_pick["fp8_widen_chosen"] is False
with pytest.raises(RuntimeError, match = "Not enough system RAM"):
load(**widened_pick)