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.

feat(studio): store ComfyUI fp8 layers as fp8 on Apple MPS when the widened model would not fit (#15507)

Long Yixingd742d0767e0a
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 66c3f1fc405..0bbd8e2cbba 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -201,6 +201,7 @@ from .diffusion_memory import (
estimate_safetensors_dense_mib,
file_size_mib,
largest_streamable_companion_mib,
+ mps_plan_tight,
normalize_memory_mode,
plan_diffusion_memory,
plan_fits_total_capacity,
@@ -12445,7 +12446,7 @@ class DiffusionBackend:
fp8_rule = dict(
lora = lora,
- offload = not plan_keeps_transformer_resident(plan),
+ offload = not plan_keeps_transformer_resident(plan) or mps_plan_tight(plan),
widened_mib = transformer_resident,
host_available_mib = _available_system_memory_mib(),
)
diff --git a/studio/backend/core/inference/diffusion_comfy_quant.py b/studio/backend/core/inference/diffusion_comfy_quant.py
index 37bd834a123..b90881f2c66 100644
--- a/studio/backend/core/inference/diffusion_comfy_quant.py
+++ b/studio/backend/core/inference/diffusion_comfy_quant.py
@@ -961,8 +961,9 @@ def fp8_storage_wanted(
widened_mib: Optional[int] = None,
host_available_mib: Optional[int] = None,
) -> bool:
- """Store fp8 only when widening would offload or leave under the host reserve: widening is otherwise faster
- (measured +45% s/step eager for storage on Krea 2 / B200, parity compiled)."""
+ """Store fp8 only when widening would offload (on MPS, which never offloads: overrun the resident margin,
+ ``diffusion_memory.mps_plan_tight``) or leave under the host reserve: widening is otherwise faster (measured
+ +45% s/step eager for storage on Krea 2 / B200, parity compiled; +13% on MPS)."""
if not comfy_fp8_storage(target, lora = lora):
return False
if fp8_storage_forced() or offload:
@@ -994,11 +995,9 @@ def fp8_widen_chosen(
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."""
+ dense Linears) and torch without float8."""
if lora or fp8_storage_disabled():
return False
- if str(getattr(target, "device", "") or "").split(":")[0] == "mps":
- return False
try:
import torch
return hasattr(torch, "float8_e4m3fn") and hasattr(torch, "float8_e5m2")
diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.py
index 81bb8bc8eb3..fca4c070cec 100644
--- a/studio/backend/core/inference/diffusion_memory.py
+++ b/studio/backend/core/inference/diffusion_memory.py
@@ -2400,6 +2400,21 @@ def plan_fits_total_capacity(plan: Any) -> bool:
return int(required) <= budget
+def mps_plan_tight(plan: Any) -> bool:
+ """Whether an Apple MPS plan, which stays resident whatever it needs (unified memory), needs more than the 0.85
+ share of its budget a discrete plan stays resident in. False on every other device or when a size is unknown."""
+ try:
+ if plan.device_memory.device != "mps":
+ return False
+ required = plan.estimates.get("resident_required_mib")
+ budget = plan.estimates.get("safe_device_budget_mib")
+ except Exception: # noqa: BLE001 - malformed plan: not tight
+ return False
+ if required is None or budget is None:
+ return False
+ return int(required) > int(int(budget) * 0.85)
+
+
def total_capacity_budget_mib(memory: DeviceMemory) -> Optional[int]:
"""TOTAL capacity minus the same reserve the free budget takes, times the 0.85 resident margin. None when the
total is unknown. Shared with the dense prefetch gate so the two cannot disagree."""
diff --git a/studio/backend/core/inference/diffusion_mps_fp16.py b/studio/backend/core/inference/diffusion_mps_fp16.py
index caeea52938b..0db3ab57763 100644
--- a/studio/backend/core/inference/diffusion_mps_fp16.py
+++ b/studio/backend/core/inference/diffusion_mps_fp16.py
@@ -150,7 +150,9 @@ def _castable(mod: Any) -> bool:
if mod is None:
return False
if _is_native_quant(mod):
- return getattr(mod, "scheme", "int8") == "int8" and not getattr(mod, "act_int8", False)
+ return getattr(mod, "scheme", "int8") in ("int8", "fp8") and not getattr(
+ mod, "act_int8", False
+ )
for sub in mod.modules():
if _is_native_quant(sub) or hasattr(sub, "compute_dtype"):
return False
diff --git a/studio/backend/core/inference/diffusion_native_quant.py b/studio/backend/core/inference/diffusion_native_quant.py
index 4e5f4b436bd..2cea276d047 100644
--- a/studio/backend/core/inference/diffusion_native_quant.py
+++ b/studio/backend/core/inference/diffusion_native_quant.py
@@ -62,6 +62,14 @@ def fp8_bits_to_float32(bits: Any, fmt: str = "float8_e4m3fn") -> Any:
return torch.where((b & 0x80) != 0, -mag, mag)
+@lru_cache(maxsize = None)
+def fp8_lookup_table(fmt: str, device: str) -> Any:
+ """float32 value of every fp8 code on ``device``. MPS has no fp8 casts before torch 2.15; indexing this table
+ with the uint8 codes gives the same bits as the cast on any torch."""
+ import torch
+ return torch.arange(256, dtype = torch.uint8).view(getattr(torch, fmt)).float().to(device)
+
+
def int8_act_requested() -> bool:
import os
return os.environ.get(NATIVE_INT8_ACT_ENV, "").strip() == "1"
@@ -449,6 +457,11 @@ def native_linear_class():
wide = self.weight_q.to(torch.float32)
elif torch.compiler.is_compiling():
wide = fp8_bits_to_float32(self.weight_q, self.fp8_format)
+ elif self.weight_q.device.type == "mps":
+ lut = fp8_lookup_table(self.fp8_format, str(self.weight_q.device))
+ wide = lut.index_select(0, self.weight_q.reshape(-1).int()).view(
+ self.weight_q.shape
+ )
else:
wide = self.weight_q.view(getattr(torch, self.fp8_format)).to(torch.float32)
return (wide * scale[:, None]).to(dtype)
diff --git a/studio/backend/core/inference/diffusion_transformer_quant.py b/studio/backend/core/inference/diffusion_transformer_quant.py
index ad640af2b6c..3a3dd936442 100644
--- a/studio/backend/core/inference/diffusion_transformer_quant.py
+++ b/studio/backend/core/inference/diffusion_transformer_quant.py
@@ -989,7 +989,7 @@ def native_quant_scheme(
offload and scheme in NATIVE_OFFLOAD_SCHEMES and native_offload_host(target)
):
return None
- # MPS has no float8 storage.
+ # MPS cannot cast to fp8 before torch 2.15; checkpoint fp8 codes take ``comfy_fp8_storage`` instead.
if _mps_bf16(target) and scheme != TQ_INT8:
return None
if _family_denied(family, scheme):
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 00043e3a19a..4a02e5a9f1c 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -147,6 +147,7 @@ from .diffusion_memory import (
estimate_safetensors_dense_mib,
estimate_video_runtime_mib,
file_size_mib,
+ mps_plan_tight,
normalize_memory_mode,
plan_diffusion_memory,
plan_keeps_transformer_resident,
@@ -499,9 +500,9 @@ def _video_comfy_backends(
) -> dict[str, Optional[str]]:
"""``load_comfy_quant_transformer`` backends for a ComfyUI-quantized video DiT: the ones Studio's own int8 / fp8
quant would run on this card and plan (int8: torchao resident, the torchao-free twin under offload; fp8: torchao
- resident only; else fp8 storage under offload). ``priced_offload``: the plan was sized with the offloaded
- backends (``_video_offload_reprice``), so a load that now fits resident keeps them. ``widened_mib``: the planned
- DiT price; a resident load stores fp8 when widening it would leave under the host reserve, as an image does.
+ resident only; else fp8 storage under offload or a tight MPS plan). ``priced_offload``: the plan was sized with the
+ offloaded backends (``_video_offload_reprice``), so a load that now fits resident keeps them. ``widened_mib``: the
+ planned 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 {
@@ -512,23 +513,31 @@ def _video_comfy_backends(
}
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)
+ store_pays = offload or mps_plan_tight(plan)
+ storage = _video_fp8_storage(fam, target, store_pays, 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": storage,
"fp8_widen_chosen": not storage
- and _video_fp8_storage(fam, target, offload, widened_mib = widened_mib, widen_chosen = True),
+ and _video_fp8_storage(fam, target, store_pays, widened_mib = widened_mib, widen_chosen = True),
}
+def _video_comfy_reprice(plan: Any, bf16_plan: Any = None) -> bool:
+ """Whether a ComfyUI DiT is re-priced with the offloaded backends: an offloaded plan (fp8 layers dequantize on
+ NVIDIA), or an MPS plan past its resident margin (MPS never offloads; its offloaded backends are its resident ones
+ plus fp8 storage)."""
+ return not _video_comfy_resident(plan, bf16_plan) or mps_plan_tight(plan)
+
+
def _video_offload_reprice(
fam: Any, transformer_mib: Optional[int], offload_mib: Optional[int]
) -> tuple[Optional[int], bool]:
- """``(transformer_mib, priced_offload)`` once an offloaded plan re-prices the DiT with the offloaded backends.
- Larger: re-plan at it. Smaller (fp8 stored, the int8 twin where only it runs): re-plan at it too, and the load must
- then keep those backends even if the new plan fits resident, else it widens past the size it was planned at.
- H3 keeps its resident torchao path, so only a larger price moves it."""
+ """``(transformer_mib, priced_offload)`` once an offloaded (or tight MPS) plan re-prices the DiT with the offloaded
+ backends. Larger: re-plan at it. Smaller (fp8 stored, the int8 twin where only it runs): re-plan at it too, and
+ the load must then keep those backends even if the new plan fits resident, else it widens past the size it was
+ planned at. H3 keeps its resident torchao path, so only a larger price moves it."""
if offload_mib is None or transformer_mib is None or offload_mib == transformer_mib:
return transformer_mib, False
if offload_mib < transformer_mib and getattr(fam, "name", None) == "minimax-h3":
@@ -8655,8 +8664,8 @@ class VideoBackend:
denoiser_seed_gb = None
plan, bf16_plan, quant_replanned = _plan_for_te_scale(te_scale, log = False)
comfy_priced_offload = False
- if comfy_scan is not None and not _video_comfy_resident(plan, bf16_plan):
- # Offloaded, fp8 layers dequantize on NVIDIA: price the DiT the load will actually build.
+ if comfy_scan is not None and _video_comfy_reprice(plan, bf16_plan):
+ # Price the DiT the load will actually build.
offload_mib = _video_comfy_resident_mib(
fam,
base,
diff --git a/studio/backend/tests/test_diffusion_comfy_quant.py b/studio/backend/tests/test_diffusion_comfy_quant.py
index a7dfe53754a..e122388c19a 100644
--- a/studio/backend/tests/test_diffusion_comfy_quant.py
+++ b/studio/backend/tests/test_diffusion_comfy_quant.py
@@ -587,6 +587,23 @@ def test_fp8_native_backend_keeps_codes_and_computes_the_dense_product(tmp_path,
assert _cos(linear(x), want) > 0.999
+ not (getattr(torch.backends, "mps", None) and torch.backends.mps.is_available()),
+ reason = "needs Apple MPS",
+)
+def test_mps_fp8_storage_matches_the_load_time_dequant_bitwise(tmp_path, monkeypatch):
+ """MPS has no fp8 cast before torch 2.15: stored codes widen through a lookup table to the same bf16 weights."""
+ monkeypatch.setattr(cq, "_mapping", lambda cls: (_convert, _sfm()))
+ path, _dense, _tensors = _fp8_file(tmp_path)
+ stored = _load_bf16(path, fp8_backend = None, fp8_storage = True).to("mps")
+ dense = _load_bf16(path, fp8_backend = None, fp8_storage = False).to("mps")
+ assert cq.fp8_stored_layers(stored) == 10
+ x = torch.randn(64, DIM, dtype = torch.bfloat16, device = "mps")
+ for name, layer in dense.named_modules():
+ if isinstance(layer, nn.Linear):
+ assert torch.equal(stored.get_submodule(name)(x), layer(x)), name
+
+
def test_fp8_without_a_runtime_dequantizes(tmp_path, monkeypatch):
monkeypatch.setattr(cq, "_mapping", lambda cls: (_convert, _sfm()))
path, _dense, tensors = _fp8_file(tmp_path)
@@ -689,8 +706,8 @@ def test_fp8_storage_follows_the_device_lora_and_kill_switch(monkeypatch):
assert cq.comfy_fp8_storage(cuda) is True
assert cq.comfy_fp8_storage(types.SimpleNamespace(device = "cpu")) is True
assert cq.comfy_fp8_storage(None) is True
- # MPS has no float8 dtypes; a LoRA needs dense Linears to attach to
- assert cq.comfy_fp8_storage(types.SimpleNamespace(device = "mps")) is False
+ # MPS widens stored codes through a lookup table; a LoRA needs dense Linears to attach to
+ assert cq.comfy_fp8_storage(types.SimpleNamespace(device = "mps")) is True
assert cq.comfy_fp8_storage(cuda, lora = True) is False
for off in ("0", "off", "false"):
monkeypatch.setenv(cq.FP8_STORAGE_ENV, off)
@@ -979,7 +996,7 @@ def test_a_lora_on_stored_fp8_layers_is_refused_with_the_way_out(tmp_path, monke
def test_fp8_storage_default_rule_is_offload_or_host_ram(monkeypatch):
- """Unset env stores only when widening would offload or crowd host RAM; ``1`` always; MPS and LoRA never."""
+ """Unset env stores only when widening would offload or crowd host RAM; ``1`` always; LoRA never."""
monkeypatch.delenv(cq.FP8_STORAGE_ENV, raising = False)
cuda = types.SimpleNamespace(device = "cuda", dtype = torch.bfloat16)
want = cq.fp8_storage_wanted
@@ -989,7 +1006,7 @@ def test_fp8_storage_default_rule_is_offload_or_host_ram(monkeypatch):
assert want(cuda, widened_mib = 24000, host_available_mib = 24000 + reserve + 1) is False
assert want(cuda, widened_mib = 24000, host_available_mib = 24000 + reserve - 1) is True
assert want(cuda, offload = True, lora = True) is False
- assert want(types.SimpleNamespace(device = "mps"), offload = True) is False
+ assert want(types.SimpleNamespace(device = "mps"), offload = True) is True
monkeypatch.setenv(cq.FP8_STORAGE_ENV, "1")
assert want(cuda) is True
@@ -1044,8 +1061,10 @@ def _plan_harness(
resident_at,
fits_mib,
comfy_mib = None,
+ mps_budget_mib = None,
):
- """Run ``_plan_memory`` for a single file with a fake planner (resident iff the DiT fits ``fits_mib``)."""
+ """Run ``_plan_memory`` for a single file with a fake planner (resident iff the DiT fits ``fits_mib``; with
+ ``mps_budget_mib`` an MPS plan that stays resident against that budget)."""
from core.inference import diffusion as d
from core.inference import diffusion_memory as dm
@@ -1057,6 +1076,15 @@ def _plan_harness(
def plan(**kwargs):
mib = kwargs["model_dense_mib"]
seen.append(mib)
+ if mps_budget_mib is not None:
+ return types.SimpleNamespace(
+ resident = True,
+ device_memory = types.SimpleNamespace(device = "mps", is_unified = True),
+ estimates = {
+ "resident_required_mib": mib,
+ "safe_device_budget_mib": mps_budget_mib,
+ },
+ )
return types.SimpleNamespace(resident = mib is not None and mib <= fits_mib)
monkeypatch.setattr(d, "plan_diffusion_memory", plan)
@@ -1268,6 +1296,37 @@ def test_a_plan_priced_with_the_offload_only_backend_keeps_it_when_resident(monk
assert backend._comfy_offload_for(final, path) is False
[email protected]("budget, store", [(2000, True), (4000, False)])
+def test_mps_stores_fp8_only_past_the_resident_margin(monkeypatch, tmp_path, budget, store):
+ """MPS never offloads: the widened DiT (2000) keeps its fp8 codes (1000) only when it overruns 0.85 of
+ the budget, else it widens, which runs faster."""
+
+ def comfy_mib(
+ path,
+ fam,
+ target,
+ base,
+ *,
+ lora = False,
+ fp8_storage = False,
+ offload = False,
+ ):
+ return 1000 if fp8_storage else 2000
+
+ fam = types.SimpleNamespace(name = "flux.1", single_file_is_pipeline = False)
+ backend, _final, seen, path = _plan_harness(
+ monkeypatch,
+ tmp_path,
+ fam = fam,
+ resident_at = None,
+ fits_mib = 10**6,
+ comfy_mib = comfy_mib,
+ mps_budget_mib = budget,
+ )
+ assert backend._fp8_storage_picks[path] is store
+ assert seen[-1] == (1000 if store else 2000)
+
+
def test_a_plan_repriced_larger_under_offload_does_not_force_the_offload_probe(
monkeypatch, tmp_path
):
diff --git a/studio/backend/tests/test_diffusion_memory.py b/studio/backend/tests/test_diffusion_memory.py
index 51e8ab85e32..ff8e8ae8806 100644
--- a/studio/backend/tests/test_diffusion_memory.py
+++ b/studio/backend/tests/test_diffusion_memory.py
@@ -1254,6 +1254,27 @@ def _unified_plan(
)
+def test_mps_plan_is_tight_past_the_resident_margin_only():
+ from core.inference.diffusion_memory import mps_plan_tight
+
+ budget = _unified_plan(model_dense_mib = 1000).estimates["safe_device_budget_mib"]
+ # resident_required = weights + the 3072 runtime headroom + the 2048 base overhead
+ at_margin = int(budget * 0.85) - 3072 - 2048
+ assert not mps_plan_tight(_unified_plan(model_dense_mib = at_margin))
+ assert mps_plan_tight(_unified_plan(model_dense_mib = at_margin + 1))
+ # far past their budgets, but only MPS changes: discrete VRAM, an integrated GPU and the CPU keep their rules
+ for kind, device in (
+ ("discrete_vram", "cuda"),
+ ("unified_memory", "cuda"),
+ ("system_memory", "cpu"),
+ ):
+ other = _unified_plan(model_dense_mib = 4 * budget, kind = kind, device = device)
+ assert other.estimates["resident_required_mib"] > other.estimates["safe_device_budget_mib"]
+ assert not mps_plan_tight(other), (kind, device)
+ assert not mps_plan_tight(_unified_plan(model_dense_mib = at_margin + 1, free_mib = None))
+ assert not mps_plan_tight(None)
+
+
def test_unified_oversize_refuses_and_names_family_and_both_numbers():
from core.inference.diffusion_memory import unified_memory_shortfall_message
diff --git a/studio/backend/tests/test_diffusion_mps_fp16.py b/studio/backend/tests/test_diffusion_mps_fp16.py
index 4e148ff0d64..30b4c7f2fc1 100644
--- a/studio/backend/tests/test_diffusion_mps_fp16.py
+++ b/studio/backend/tests/test_diffusion_mps_fp16.py
@@ -326,24 +326,39 @@ class NativeWeightOnlyLinear(nn.Module):
return nn.functional.linear(x.float(), w).to(x.dtype)
+def _studio_fp8(lin):
+ """Studio's own fp8 weight-only Linear, recording its activation dtypes like the int8 stand-in above."""
+ from core.inference.diffusion_native_quant import native_linear_class
+
+ cls = native_linear_class()
+
+ def forward(self, x):
+ self.seen.append(x.dtype)
+ return cls.forward(self, x)
+
+ layer = type("NativeWeightOnlyLinear", (cls,), {"forward": forward})(lin, "fp8")
+ layer.seen = []
+ return layer
+
+
@needs_fp16
-def test_int8_weight_only_layers_keep_storage_and_get_fp16_activations():
[email protected]("scheme", ["int8", "fp8"])
+def test_weight_only_layers_keep_storage_and_get_fp16_activations(scheme):
model = _model()
q = []
+ make = NativeWeightOnlyLinear if scheme == "int8" else _studio_fp8
+ codes, scales = (torch.int8, torch.float32) if scheme == "int8" else (torch.uint8, torch.int32)
for blk in (*model.layers, *model.noise_refiner, *model.context_refiner):
for parent, names in (
(blk.attention, ("to_q", "to_k", "to_v")),
(blk.feed_forward, ("w1", "w2", "w3")),
):
for n in names:
- layer = NativeWeightOnlyLinear(getattr(parent, n))
+ layer = make(getattr(parent, n))
setattr(parent, n, layer)
q.append(layer)
assert mf.install_mps_fp16(model, MPS_BF16) > 0
- assert all(
- layer.weight_q.dtype is torch.int8 and layer.weight_scale.dtype is torch.float32
- for layer in q
- )
+ assert all(layer.weight_q.dtype is codes and layer.weight_scale.dtype is scales for layer in q)
out = _run(model, torch.bfloat16)
assert torch.isfinite(out).all()
assert q[0].seen and all(d is torch.float16 for layer in q for d in layer.seen)
diff --git a/studio/backend/tests/test_diffusion_native_quant_mps.py b/studio/backend/tests/test_diffusion_native_quant_mps.py
index 6fc49129fd5..4c487b46117 100644
--- a/studio/backend/tests/test_diffusion_native_quant_mps.py
+++ b/studio/backend/tests/test_diffusion_native_quant_mps.py
@@ -52,6 +52,34 @@ def test_mps_refuses_everything_but_int8(scheme):
assert tq.native_quant_scheme(_mps_target(), scheme) is None
[email protected](not _MPS, reason = "needs Apple MPS")
[email protected]("fmt", ["float8_e4m3fn", "float8_e5m2"])
[email protected]("dtype", ["float32", "bfloat16", "float16"])
+def test_mps_fp8_dequant_matches_the_cpu_cast_bitwise(fmt, dtype):
+ """Every code, NaN and inf included, against the CPU cast; MPS has no fp8 cast before torch 2.15."""
+ codes = torch.arange(256, dtype = torch.uint8).repeat(4, 1).view(getattr(torch, fmt))
+ scale = torch.tensor([[1.0], [0.5], [3.0], [2.0**-9]])
+ linear = torch.nn.Linear(256, 4, dtype = torch.bfloat16)
+ layer = nq.native_linear_class()(linear, "fp8", codes = codes, scale = scale)
+ want = layer.dequantized_weight(getattr(torch, dtype))
+ got = layer.to("mps").dequantized_weight(getattr(torch, dtype)).cpu()
+ nan = want.isnan()
+ assert torch.equal(got.isnan(), nan)
+ bits = torch.int32 if dtype == "float32" else torch.int16
+ assert torch.equal(got[~nan].view(bits), want[~nan].view(bits))
+
+
[email protected]("fmt", ["float8_e4m3fn", "float8_e5m2"])
+def test_fp8_lookup_table_matches_the_cast_bitwise(fmt):
+ # Runs everywhere: the MPS dispatch test above skips off Apple Silicon.
+ codes = torch.arange(256, dtype = torch.uint8)
+ got = nq.fp8_lookup_table(fmt, "cpu").index_select(0, codes.int())
+ want = codes.view(getattr(torch, fmt)).float()
+ nan = want.isnan()
+ assert torch.equal(got.isnan(), nan)
+ assert torch.equal(got[~nan].view(torch.int32), want[~nan].view(torch.int32))
+
+
@pytest.mark.parametrize("dtype", ["float16", "float32"])
def test_mps_without_bf16_is_not_native(dtype):
target = _mps_target(getattr(torch, dtype))
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 6d81a664c12..b5e82d819cb 100644
--- a/studio/backend/tests/test_diffusion_single_file_host_ram.py
+++ b/studio/backend/tests/test_diffusion_single_file_host_ram.py
@@ -328,9 +328,9 @@ def test_fp8_widen_chosen_only_when_the_rule_had_the_choice(monkeypatch):
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)
+ # no fp8 storage option: LoRA, 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(mps, **room) is True
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 (
diff --git a/studio/backend/tests/test_video_comfy_quant.py b/studio/backend/tests/test_video_comfy_quant.py
index f03f2928b61..fde66dd9c3e 100644
--- a/studio/backend/tests/test_video_comfy_quant.py
+++ b/studio/backend/tests/test_video_comfy_quant.py
@@ -440,6 +440,24 @@ def test_video_backends_follow_studio_rules(monkeypatch):
)
[email protected]("required, store", [(1800, True), (1700, False)])
+def test_mps_video_stores_fp8_only_past_the_resident_margin(monkeypatch, required, store):
+ """MPS never offloads, so a plan past 0.85 of its budget is what makes fp8 storage pay."""
+ monkeypatch.delenv(cq.FP8_STORAGE_ENV, raising = False)
+ monkeypatch.setattr(vid, "comfy_int8_backend", lambda *a, **k: None)
+ monkeypatch.setattr(vid, "comfy_fp8_backend", lambda *a, **k: None)
+ plan = types.SimpleNamespace(
+ offload_policy = "none",
+ device_memory = types.SimpleNamespace(device = "mps", is_unified = True),
+ estimates = {"resident_required_mib": required, "safe_device_budget_mib": 2000},
+ )
+ mps = types.SimpleNamespace(device = "mps", dtype = torch.bfloat16)
+ fam = types.SimpleNamespace(name = "wan2.2-ti2v-5b")
+ assert vid._video_comfy_backends(fam, "b", mps, plan)["fp8_storage"] is store
+ # the shortfall check then sees the stored price, not the widened one
+ assert vid._video_comfy_reprice(plan) is store
+
+
def test_a_smaller_offloaded_price_replans_and_keeps_the_offloaded_backends(monkeypatch):
"""fp8 stored under offload prices below the widened resident estimate: re-plan at it, and a plan that now fits
resident keeps fp8 storage (else the load widens past the size it was planned at)."""
@@ -730,6 +748,12 @@ def test_offloaded_plan_size_prices_fp8_that_only_runs_resident(monkeypatch, tmp
assert vid._video_comfy_resident_mib(fam, "b", None, path, scan, offload = True) == 2
monkeypatch.setenv(cq.FP8_STORAGE_ENV, "0")
assert vid._video_comfy_resident_mib(fam, "b", None, path, scan, offload = True) == 3
+ monkeypatch.delenv(cq.FP8_STORAGE_ENV)
+ mps = types.SimpleNamespace(device = "mps", dtype = torch.bfloat16)
+ monkeypatch.setattr(vid, "comfy_fp8_backend", lambda *a, **k: None)
+ # MPS has no fp8 GEMM: resident widens, the re-price stores
+ assert vid._video_comfy_resident_mib(fam, "b", mps, path, scan) == 3
+ assert vid._video_comfy_resident_mib(fam, "b", mps, path, scan, offload = True) == 2
def test_dense_h3_maps_its_timestep_mlp_and_keeps_adaln_at_compute_dtype():