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: enable video generation on Apple Silicon (#8198)

Long Yixingef74942f8c74
diff --git a/studio/backend/core/inference/diffusion_device.py b/studio/backend/core/inference/diffusion_device.py
index 4ae551a4083..f50ded7428d 100644
--- a/studio/backend/core/inference/diffusion_device.py
+++ b/studio/backend/core/inference/diffusion_device.py
@@ -27,6 +27,7 @@ class DiffusionDeviceTarget:
supports_model_cpu_offload: bool
supports_default_torch_compile: bool
supports_pinned_transfer: bool
+ supports_float64: bool = True
@property
def is_cuda_torch_device(self) -> bool:
@@ -41,9 +42,101 @@ class DiffusionDeviceTarget:
"supports_model_cpu_offload": self.supports_model_cpu_offload,
"supports_default_torch_compile": self.supports_default_torch_compile,
"supports_pinned_transfer": self.supports_pinned_transfer,
+ "supports_float64": self.supports_float64,
}
+def force_float32_rope(
+ pipe: Any,
+ target: DiffusionDeviceTarget,
+ *,
+ logger: Any = None,
+) -> int:
+ """Drop the float64 intermediate in RoPE frequency tables on a device without float64.
+
+ LTX-2 builds ``theta ** linspace(0, 1, n)`` in float64 and casts straight back to float32;
+ Metal has no float64, so torch raises before the first step. The modules gate that
+ intermediate on a ``double_precision`` attribute, and clearing it costs at most 6 float32 ULP
+ against a value the next line truncates anyway.
+
+ Returns the number of modules changed; a no-op wherever float64 works, so CUDA/XPU/CPU stay
+ bit-for-bit.
+ """
+ if target.supports_float64:
+ return 0
+ changed = 0
+ for component in getattr(pipe, "components", {}).values() or ():
+ modules = getattr(component, "modules", None)
+ if not callable(modules):
+ continue
+ for module in modules():
+ if getattr(module, "double_precision", False):
+ module.double_precision = False
+ changed += 1
+ if changed and logger is not None:
+ logger.info("video.rope_float32: %d module(s) demoted (no float64 on this device)", changed)
+ return changed
+
+
+# Fraction of the device's recommended working set above which a decode starts synchronising.
+DECODE_SYNC_FRACTION = 0.85
+
+
+def install_decoder_sync(
+ pipe: Any,
+ target: DiffusionDeviceTarget,
+ *,
+ logger: Any = None,
+) -> bool:
+ """Cap the memory a video VAE decode holds on Metal, by synchronising once it is running out.
+
+ Wan's VAE decodes one latent frame per call in a loop that never forces a commit, and Metal
+ cannot reuse a buffer until the work holding it completes, so intermediates accumulate until
+ the OS kills the process. Neither tiling (the growth is within one tile) nor torch's adaptive
+ commit bounds it.
+
+ Fires per decoder call and only above the threshold, so a decode with room to spare pays only
+ the memory read; synchronising costs the pipelining, not the decode.
+
+ ``torch.mps.recommended_max_memory()`` arrived in torch 2.5 while install.sh keeps an existing
+ venv's torch as far back as 2.4, so an unreadable budget falls back to synchronising every
+ call (measured to hold the same decode at 4.90 GiB for no wall-clock cost) rather than
+ failing the load or dropping the bound. Every probe is best-effort for the same reason.
+ """
+ if target.device != "mps":
+ return False
+ decoder = getattr(getattr(pipe, "vae", None), "decoder", None)
+ if not callable(getattr(decoder, "register_forward_hook", None)):
+ return False
+ import torch
+
+ budget: Optional[float] = None
+ try:
+ budget = torch.mps.recommended_max_memory() * DECODE_SYNC_FRACTION
+ except Exception as exc: # noqa: BLE001 -- torch < 2.5 has no such reading
+ if logger is not None:
+ logger.info(
+ "video.decoder_sync: no memory reading (%s); synchronising every decode", exc
+ )
+
+ def _sync(_module, _args, _output) -> None:
+ if budget is not None:
+ try:
+ if torch.mps.driver_allocated_memory() < budget:
+ return
+ except Exception: # noqa: BLE001 -- an unreadable gauge syncs, the safe side
+ pass
+ try:
+ torch.mps.synchronize()
+ except Exception: # noqa: BLE001 -- a decode is worth more than the bound
+ pass
+
+ decoder.register_forward_hook(_sync)
+ if logger is not None and budget is not None:
+ logger.info("video.decoder_sync: decode synchronises above %.1f GiB", budget / 1024**3)
+ return True
+
+
def _studio_device_is(studio_device: Any, device_type: Any, name: str) -> bool:
"""True if ``studio_device`` equals ``DeviceType.<name>`` (when that member exists)."""
member = getattr(device_type, name, None)
@@ -145,6 +238,7 @@ def diffusion_device_target_from_torch_device(
supports_model_cpu_offload = False,
supports_default_torch_compile = False,
supports_pinned_transfer = False,
+ supports_float64 = False,
)
return _cpu_target(torch = None, dtype = dtype)
@@ -230,6 +324,7 @@ def _mps_or_cpu_target(torch: Any) -> DiffusionDeviceTarget:
supports_model_cpu_offload = False,
supports_default_torch_compile = False,
supports_pinned_transfer = False,
+ supports_float64 = False,
)
return _cpu_target(torch)
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index b2750a091c1..7dea62ffe94 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -58,7 +58,11 @@ from .diffusion_cache import (
maybe_toggle_step_cache,
normalize_transformer_cache,
)
-from .diffusion_device import resolve_diffusion_device_target
+from .diffusion_device import (
+ force_float32_rope,
+ install_decoder_sync,
+ resolve_diffusion_device_target,
+)
from .diffusion_memory import (
apply_memory_plan,
estimate_gguf_resident_mib,
@@ -705,6 +709,24 @@ class VideoBackend:
f"model{gguf_hint}."
)
if fam.modular_workflow and kind == "pipeline":
+ # Metal cannot place a modular workflow at all. _load_h3_modular_pipeline hands every
+ # non-CPU device to ComponentsManager.enable_auto_cpu_offload, which reads
+ # torch.<device>.mem_get_info and raises NotImplementedError for a device module
+ # without one; torch.mps has never exposed it. Refuse here, before ~145 GB downloads
+ # and the resident pipeline is torn down to make room for it.
+ if resolve_diffusion_device_target().device == "mps":
+ gguf_hint = (
+ f" Load a .gguf checkpoint from '{fam.gguf_repo}' instead, which runs on the "
+ f"native engine."
+ if fam.gguf_repo
+ else ""
+ )
+ raise ValueError(
+ f"'{fam.name}' cannot run on Apple Silicon: its Modular Diffusers workflow "
+ f"places components through the Diffusers auto CPU offload, which needs a "
+ f"torch device exposing mem_get_info, and Metal (MPS) does not have it."
+ f"{gguf_hint}"
+ )
# Same normaliser the load uses, so a malformed value raises the identical message it
# would below and only a real scheme reaches the availability check.
requested_scheme = normalize_transformer_quant(transformer_quant)
@@ -2872,6 +2894,9 @@ class VideoBackend:
if effective_speed not in (SPEED_OFF, SPEED_MAX)
else False
)
+ # Sets a flag the pipelines read when they first build their frequency tables, so it need
+ # only happen before generation, not before placement.
+ force_float32_rope(pipe, target, logger = logger)
speed_optims: tuple = ()
for view in views:
# Both helpers act on ``view.transformer``; call once per view (engaged values match, so record the first). is_gguf needs kind==gguf AND no quant engaged.
@@ -2918,6 +2943,8 @@ class VideoBackend:
vae_tiling = True
except Exception as exc: # noqa: BLE001 -- tiling is an optimisation only
logger.warning("video.vae_tiling_failed: %s", exc)
+ # Wan's decode also grows within a single tile, which tiling alone cannot bound.
+ install_decoder_sync(pipe, target, logger = logger)
resolved = build_resolved_record(
{
@@ -3899,7 +3926,12 @@ class VideoBackend:
"available. Load the GGUF artifact instead."
)
- generator = torch.Generator(device = "cpu" if fam.modular_workflow else state.device)
+ # MPS seeds from the CPU generator too: diffusers reproduces a Metal seed only
+ # that way, and the pipelines move the noise to the device themselves.
+ generator_device = (
+ "cpu" if fam.modular_workflow or str(state.device) == "mps" else state.device
+ )
+ generator = torch.Generator(device = generator_device)
if seed is None:
seed = int(generator.seed()) % (2**53)
generator = generator.manual_seed(int(seed))
diff --git a/studio/backend/main.py b/studio/backend/main.py
index 4ef7da2afe7..442f4d90069 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -1491,9 +1491,10 @@ async def health_check(request: Request):
await _await_hardware_detection(_HEALTH_DETECT_BUDGET_S)
# Snapshot, not a bare global read: a forced re-detect can start at any moment.
snapshot = _hardware_snapshot()
- # A chat-only verdict the MLX self-heal is about to overturn is not an answer yet. Hold
- # it back and keep replying provisionally, or the Mac gets Train and Video greyed out
- # under a tooltip the reinstall makes wrong minutes later.
+ # A chat-only verdict the MLX self-heal is about to overturn is not an answer yet. Hold it
+ # back and keep replying provisionally, or the Mac gets Train greyed out under a tooltip the
+ # reinstall makes wrong minutes later. Video does not wait on this: it runs on Metal without
+ # MLX, so it reads /api/system/hardware instead.
mlx_repairing = _superseded_by_mlx_repair(snapshot)
if mlx_repairing:
snapshot = None
diff --git a/studio/backend/tests/test_diffusion_device.py b/studio/backend/tests/test_diffusion_device.py
index 88f7d16c262..1c5c503559b 100644
--- a/studio/backend/tests/test_diffusion_device.py
+++ b/studio/backend/tests/test_diffusion_device.py
@@ -322,3 +322,310 @@ def test_public_dict_dtype_string(dtype, expected):
)
d = t.as_public_dict()
assert d["dtype"] == expected and "torch." not in d["dtype"]
+
+
+# -- float64 capability + the RoPE demotion it drives -------------------------------------------
+
+
+def test_only_mps_lacks_float64(monkeypatch):
+ torch = _make_torch(mps_available = True, mps_probe = "pass")
+ _install(monkeypatch, torch)
+ assert dd.resolve_diffusion_device_target().supports_float64 is False
+ for device in ("cuda", "xpu", "cpu"):
+ assert dd.diffusion_device_target_from_torch_device(device, FP32).supports_float64 is True
+ assert dd.diffusion_device_target_from_torch_device("mps", FP32).supports_float64 is False
+
+
+class _RopeModule:
+ def __init__(self, double_precision = True):
+ self.double_precision = double_precision
+
+
+class _Component:
+ def __init__(self, *mods):
+ self._mods = mods
+
+ def modules(self):
+ return iter(self._mods)
+
+
+class _Pipe:
+ def __init__(self, **components):
+ self.components = components
+
+
+def _mps_target():
+ return dd.diffusion_device_target_from_torch_device("mps", FP32)
+
+
+def _cuda_target():
+ return dd.diffusion_device_target_from_torch_device("cuda", FP32)
+
+
+def test_force_float32_rope_demotes_every_component_on_mps():
+ # Two components, several modules each: the connectors and the transformer both carry RoPE,
+ # so demoting only the first one found would still crash inside the denoise loop.
+ conn, dit_a, dit_b = _RopeModule(), _RopeModule(), _RopeModule()
+ pipe = _Pipe(connectors = _Component(conn), transformer = _Component(dit_a, dit_b))
+ assert dd.force_float32_rope(pipe, _mps_target()) == 3
+ assert not any(m.double_precision for m in (conn, dit_a, dit_b))
+
+
+def test_force_float32_rope_leaves_float64_devices_untouched():
+ rope = _RopeModule()
+ pipe = _Pipe(transformer = _Component(rope))
+ assert dd.force_float32_rope(pipe, _cuda_target()) == 0
+ assert rope.double_precision is True
+
+
+def test_force_float32_rope_skips_modules_without_the_flag():
+ already_off = _RopeModule(double_precision = False)
+ plain = object()
+ pipe = _Pipe(vae = _Component(already_off, plain))
+ assert dd.force_float32_rope(pipe, _mps_target()) == 0
+
+
+def test_force_float32_rope_tolerates_non_module_components():
+ # Pipelines carry schedulers and tokenizers with no .modules(); they must not abort the walk.
+ rope = _RopeModule()
+ pipe = _Pipe(scheduler = object(), tokenizer = None, transformer = _Component(rope))
+ assert dd.force_float32_rope(pipe, _mps_target()) == 1
+ assert rope.double_precision is False
+
+
+def test_the_video_loader_demotes_rope():
+ # The tests above prove the helper works, not that anything calls it: deleting the call site
+ # leaves every one of them green while LTX-2 goes back to raising on Metal. Where in the
+ # loader is not asserted -- the flag is read when a pipeline first builds its frequency
+ # tables, after load_pipeline returns -- but reaching it unconditionally is, since the helper
+ # already no-ops on a float64 device and a guard here could only ever get the polarity wrong.
+ #
+ # Asserted as "reached with no condition above it" rather than by rejecting `if`: a guard can
+ # equally be written `target.supports_float64 and force_float32_rope(...)` or as a ternary,
+ # and naming the shapes only rejects the ones already thought of.
+ import ast
+ from pathlib import Path
+
+ src = (Path(__file__).resolve().parent.parent / "core/inference/video.py").read_text(
+ encoding = "utf-8"
+ )
+ loader = next(
+ n
+ for n in ast.walk(ast.parse(src))
+ if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and n.name == "load_pipeline"
+ )
+
+ def _is_rope_call(node):
+ return (
+ isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Name)
+ and node.func.id == "force_float32_rope"
+ )
+
+ # Everything a condition could skip, whatever syntax expresses it.
+ conditional = {
+ id(inner)
+ for node in ast.walk(loader)
+ if isinstance(node, (ast.If, ast.IfExp, ast.BoolOp))
+ for inner in ast.walk(node)
+ }
+ assert any(
+ isinstance(n, ast.Expr) and _is_rope_call(n.value) and id(n) not in conditional
+ for n in ast.walk(loader)
+ ), (
+ "load_pipeline does not reach force_float32_rope unconditionally, so the demotion is "
+ "either gone or behind a guard -- and a guard here can only be wrong, since the helper "
+ "already no-ops wherever float64 works"
+ )
+
+
+# ── Pressure-gated decoder sync ───────────────────────────────────────
+
+
+def _target(device: str) -> dd.DiffusionDeviceTarget:
+ return dd.DiffusionDeviceTarget(
+ device = device,
+ dtype = FP32,
+ backend = device,
+ vendor = None,
+ supports_model_cpu_offload = False,
+ supports_default_torch_compile = False,
+ supports_pinned_transfer = False,
+ )
+
+
+class _FakeDecoder:
+ """A VAE decoder module, following nn.Module: a hook returning non-None replaces the output."""
+
+ def __init__(self) -> None:
+ self.hooks: list = []
+
+ def register_forward_hook(self, hook):
+ self.hooks.append(hook)
+
+ def decode(self, calls: int) -> list:
+ outputs = []
+ for index in range(calls):
+ out = f"out{index}"
+ for hook in self.hooks:
+ replacement = hook(self, (), out)
+ if replacement is not None:
+ out = replacement
+ outputs.append(out)
+ return outputs
+
+
+def _pipe_with(decoder) -> types.SimpleNamespace:
+ return types.SimpleNamespace(vae = types.SimpleNamespace(decoder = decoder))
+
+
+def _mps_torch(used = 0, recommended = 100) -> types.ModuleType:
+ """torch whose mps backend counts synchronize() calls over a settable memory reading."""
+ torch = types.ModuleType("torch")
+ torch.syncs = 0
+ torch.used = used
+
+ def _bump():
+ torch.syncs += 1
+
+ torch.mps = types.SimpleNamespace(
+ synchronize = _bump,
+ recommended_max_memory = lambda: recommended,
+ driver_allocated_memory = lambda: torch.used,
+ )
+ return torch
+
+
[email protected]("device", ["cuda", "xpu", "cpu"])
+def test_decoder_sync_is_metal_only(monkeypatch, device):
+ monkeypatch.setitem(sys.modules, "torch", _mps_torch())
+ decoder = _FakeDecoder()
+ assert dd.install_decoder_sync(_pipe_with(decoder), _target(device)) is False
+ assert decoder.hooks == []
+
+
+def test_decoder_sync_idle_while_memory_is_plentiful(monkeypatch):
+ # The whole point of the gate: a decode that fits pays nothing at all.
+ torch = _mps_torch(recommended = 100, used = 10)
+ monkeypatch.setitem(sys.modules, "torch", torch)
+ decoder = _FakeDecoder()
+ assert dd.install_decoder_sync(_pipe_with(decoder), _target("mps")) is True
+ decoder.decode(5)
+ assert torch.syncs == 0
+
+
+def test_decoder_sync_runs_once_per_decoder_call_above_the_threshold(monkeypatch):
+ torch = _mps_torch(recommended = 100, used = 10)
+ monkeypatch.setitem(sys.modules, "torch", torch)
+ decoder = _FakeDecoder()
+ dd.install_decoder_sync(_pipe_with(decoder), _target("mps"))
+ decoder.decode(2)
+ assert torch.syncs == 0
+ # The growth this bounds is per decoder call, so every call above the threshold syncs.
+ torch.used = 100 * dd.DECODE_SYNC_FRACTION
+ decoder.decode(3)
+ assert torch.syncs == 3
+ # ...and it stands down again once the allocator has given the memory back.
+ torch.used = 10
+ decoder.decode(4)
+ assert torch.syncs == 3
+
+
+def test_decoder_sync_threshold_scales_with_the_device(monkeypatch):
+ # Pins the policy AND that the budget is a fraction of this device's working set rather than a
+ # fixed byte count -- a decode is only "running out" relative to the machine it runs on.
+ torch = _mps_torch(recommended = 200, used = 169)
+ monkeypatch.setitem(sys.modules, "torch", torch)
+ decoder = _FakeDecoder()
+ dd.install_decoder_sync(_pipe_with(decoder), _target("mps"))
+ decoder.decode(1)
+ assert torch.syncs == 0
+ torch.used = 170
+ decoder.decode(1)
+ assert torch.syncs == 1
+ assert dd.DECODE_SYNC_FRACTION == 0.85
+
+
+def test_decoder_sync_preserves_the_decoder_output(monkeypatch):
+ # An nn.Module forward hook that returns non-None REPLACES the output; this one must not.
+ torch = _mps_torch(recommended = 100, used = 100)
+ monkeypatch.setitem(sys.modules, "torch", torch)
+ decoder = _FakeDecoder()
+ dd.install_decoder_sync(_pipe_with(decoder), _target("mps"))
+ assert decoder.decode(2) == ["out0", "out1"]
+ assert torch.syncs == 2
+
+
[email protected]("pipe", [types.SimpleNamespace(), _pipe_with(None), _pipe_with(object())])
+def test_decoder_sync_no_op_without_a_hookable_decoder(monkeypatch, pipe):
+ monkeypatch.setitem(sys.modules, "torch", _mps_torch())
+ assert dd.install_decoder_sync(pipe, _target("mps")) is False
+
+
+def _mps_torch_without_recommended(used = 0) -> types.ModuleType:
+ """torch 2.4's mps surface: driver_allocated_memory and synchronize, no working-set reading.
+
+ Verified against torch/mps/__init__.py at v2.4.0 (absent) and v2.5.0 (present), and against
+ an installed torch 2.4.1.
+ """
+ torch = _mps_torch(used = used)
+ del torch.mps.recommended_max_memory
+ return torch
+
+
+def test_decoder_sync_survives_a_torch_without_the_memory_reading(monkeypatch):
+ # install.sh keeps an existing venv's torch (>=2.4), and reading a 2.5 API there raised
+ # AttributeError from inside the video load -- after the download, with no OOM to explain it.
+ torch = _mps_torch_without_recommended()
+ monkeypatch.setitem(sys.modules, "torch", torch)
+ decoder = _FakeDecoder()
+ assert dd.install_decoder_sync(_pipe_with(decoder), _target("mps")) is True
+ # No budget to compare against, so it must not silently decide the decode is fine: an
+ # unbounded Wan decode is what grew past 148 GiB.
+ assert decoder.decode(3) == ["out0", "out1", "out2"]
+ assert torch.syncs == 3
+
+
+def test_decoder_sync_survives_a_working_set_reading_that_raises(monkeypatch):
+ torch = _mps_torch()
+
+ def _boom():
+ raise RuntimeError("MPS backend is not available")
+
+ torch.mps.recommended_max_memory = _boom
+ monkeypatch.setitem(sys.modules, "torch", torch)
+ decoder = _FakeDecoder()
+ assert dd.install_decoder_sync(_pipe_with(decoder), _target("mps")) is True
+ decoder.decode(2)
+ assert torch.syncs == 2
+
+
+def test_decoder_sync_survives_a_gauge_that_raises_mid_decode(monkeypatch):
+ torch = _mps_torch(recommended = 100, used = 10)
+
+ def _boom():
+ raise RuntimeError("driver reading unavailable")
+
+ torch.mps.driver_allocated_memory = _boom
+ monkeypatch.setitem(sys.modules, "torch", torch)
+ decoder = _FakeDecoder()
+ dd.install_decoder_sync(_pipe_with(decoder), _target("mps"))
+ # The decode survives, and an unreadable gauge takes the safe side rather than skipping.
+ assert decoder.decode(2) == ["out0", "out1"]
+ assert torch.syncs == 2
+
+
+def test_decoder_sync_survives_a_synchronize_that_raises(monkeypatch):
+ # The no-budget fallback synchronises every call, so a torch whose mps surface is degraded
+ # enough to hide recommended_max_memory would then raise on every decoder call. The bound is
+ # an optimisation; losing the generation to it is not a trade worth making.
+ torch = _mps_torch_without_recommended()
+
+ def _boom():
+ raise RuntimeError("Torch not compiled with MPS enabled")
+
+ torch.mps.synchronize = _boom
+ monkeypatch.setitem(sys.modules, "torch", torch)
+ decoder = _FakeDecoder()
+ assert dd.install_decoder_sync(_pipe_with(decoder), _target("mps")) is True
+ assert decoder.decode(2) == ["out0", "out1"]
diff --git a/studio/backend/tests/test_utils.py b/studio/backend/tests/test_utils.py
index 741f19c67ab..632c8011f42 100644
--- a/studio/backend/tests/test_utils.py
+++ b/studio/backend/tests/test_utils.py
@@ -177,6 +177,28 @@ class TestClearGpuCache:
with patch("utils.hardware.hardware.get_device", return_value = DeviceType.CPU):
clear_gpu_cache()
+ @needs_torch
+ def test_clears_mps_on_apple_silicon_without_mlx(self):
+ """An Apple Silicon host with a broken MLX stack reports CPU, but diffusion and video
+ still run on Metal, so the MPS allocator has to be released on that path too."""
+ with (
+ patch("utils.hardware.hardware.get_device", return_value = DeviceType.CPU),
+ patch("utils.hardware.hardware.is_apple_silicon", return_value = True),
+ patch("torch.mps.empty_cache") as mock_empty,
+ ):
+ clear_gpu_cache()
+ mock_empty.assert_called_once()
+
+ @needs_torch
+ def test_does_not_clear_mps_on_a_non_apple_cpu_host(self):
+ with (
+ patch("utils.hardware.hardware.get_device", return_value = DeviceType.CPU),
+ patch("utils.hardware.hardware.is_apple_silicon", return_value = False),
+ patch("torch.mps.empty_cache") as mock_empty,
+ ):
+ clear_gpu_cache()
+ mock_empty.assert_not_called()
+
# ========== get_gpu_memory_info() ==========
diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.py
index 6f7c5686d0c..8822609b012 100644
--- a/studio/backend/tests/test_video_backend.py
+++ b/studio/backend/tests/test_video_backend.py
@@ -8,7 +8,7 @@ stack loads."""
import builtins
import contextlib
-from pathlib import Path
+import dataclasses
import sys
import threading
import time
@@ -18,6 +18,7 @@ from pathlib import Path
import pytest
+from core.inference.diffusion_device import DiffusionDeviceTarget
from core.inference.video import (
VideoBackend,
_detect_load_family,
@@ -99,6 +100,7 @@ class _FakePipe:
"num_frames": num_frames,
"frame_rate": frame_rate,
"sigmas": sigmas,
+ "generator": generator,
**kwargs,
}
if callback_on_step_end is not None:
@@ -161,9 +163,18 @@ class _FakeWanDiT:
yield
+class _FakeWanDecoder:
+ def __init__(self) -> None:
+ self.hooks: list = []
+
+ def register_forward_hook(self, hook):
+ self.hooks.append(hook)
+
+
class _FakeWanVae:
def __init__(self) -> None:
self.tiled = False
+ self.decoder = _FakeWanDecoder()
def enable_tiling(self) -> None:
self.tiled = True
@@ -913,6 +924,23 @@ def test_generate_defaults_from_variant(fake_runtime, tmp_path):
assert call["sigmas"] == list(LTX23_DISTILLED_SIGMAS)
[email protected]("device, expected", [("mps", "cpu"), ("cuda", "cuda")])
+def test_generate_seeds_metal_from_a_cpu_generator(fake_runtime, tmp_path, device, expected):
+ # Metal reproduces a seed only through a CPU generator, and this also keeps the path off
+ # whatever torch.Generator(device="mps") does on the older torch releases install.sh keeps.
+ (tmp_path / "ltx-2.3-22b-distilled-1.1-Q4_K_M.gguf").write_bytes(b"w")
+ backend = VideoBackend()
+ backend.load_pipeline(
+ str(tmp_path),
+ gguf_filename = "ltx-2.3-22b-distilled-1.1-Q4_K_M.gguf",
+ base_repo = "Lightricks/LTX-2",
+ family_override = "ltx-2",
+ )
+ backend._state = dataclasses.replace(backend._state, device = device)
+ backend.generate(prompt = "a sloth", seed = 7)
+ assert backend._state.pipe.last_kwargs["generator"].device == expected
+
+
def test_ltx23_load_forwards_the_precast_encoder(fake_runtime, tmp_path, monkeypatch):
# The wiring half of the same bug: the 2.3 branch does not use pipe_kwargs, so the loader must pass the pre-cast encoder across explicitly.
from core.inference import diffusion_te_prequant, video_ltx2
@@ -1411,6 +1439,62 @@ def test_load_wan_ti2v_5b_pipeline(fake_runtime):
assert status["defaults"]["frame_step"] == 4
assert status["transformer_quant"] is None
assert _FakeWanPipelineSingle.last["repo"] == "Wan-AI/Wan2.2-TI2V-5B-Diffusers"
+ # Nothing to sync on this CPU-resolved target; the hook must not cost non-MPS loads a thing.
+ assert backend._state.pipe.vae.decoder.hooks == []
+
+
+def _fits_in_memory_snapshot(device):
+ """A memory snapshot big enough that no load is ever refused for size, so a test forcing a
+ device does not inherit the runner's own free memory as a precondition."""
+ from core.inference.diffusion_memory import DeviceMemory
+
+ total = 512 * 1024
+ kind = "unified_memory" if device == "mps" else "discrete_vram"
+ return lambda target: DeviceMemory(device, device, kind, int(total * 0.80), total)
+
+
[email protected]("device,hooked", [("mps", 1), ("cuda", 0)])
+def test_load_installs_the_pressure_gated_decoder_sync_on_mps(
+ fake_runtime, monkeypatch, device, hooked
+):
+ # Tiling alone does not bound a Wan decode on MPS: intermediates accumulate within a single
+ # tile until the OS kills the process. The load must arm the sync.
+ torch = sys.modules["torch"]
+ monkeypatch.setattr(
+ torch,
+ device,
+ types.SimpleNamespace(
+ synchronize = lambda: None,
+ recommended_max_memory = lambda: 64 * 1024**3,
+ driver_allocated_memory = lambda: 0,
+ ),
+ raising = False,
+ )
+ monkeypatch.setattr(
+ "core.inference.video.resolve_diffusion_device_target",
+ lambda: DiffusionDeviceTarget(
+ device = device,
+ dtype = torch.bfloat16,
+ backend = device,
+ vendor = None,
+ supports_model_cpu_offload = False,
+ supports_default_torch_compile = False,
+ supports_pinned_transfer = False,
+ ),
+ )
+ # Forcing device="mps" also forces the unified-memory placement, and that snapshot is read
+ # from the HOST's free RAM (snapshot_device_memory sends mps to _system_memory_mib), not from
+ # the torch.mps stub above. A runner with little free RAM therefore refuses this 25 GB load
+ # before the hook is ever installed, which is correct behaviour and nothing to do with what
+ # is being asserted here. Pin a pool with room to spare so the result does not depend on how
+ # busy the machine is.
+ monkeypatch.setattr(
+ "core.inference.video.settled_snapshot_device_memory",
+ _fits_in_memory_snapshot(device),
+ )
+ backend = VideoBackend()
+ backend.load_pipeline("Wan-AI/Wan2.2-TI2V-5B-Diffusers", model_kind = "pipeline")
+ assert len(backend._state.pipe.vae.decoder.hooks) == hooked
def test_video_dense_speed_defaults_to_compile_profile(fake_runtime):
diff --git a/studio/backend/tests/test_video_capability.py b/studio/backend/tests/test_video_capability.py
index 188a447ad9b..70c6a64e7cb 100644
--- a/studio/backend/tests/test_video_capability.py
+++ b/studio/backend/tests/test_video_capability.py
@@ -3,15 +3,21 @@
"""Tests for video generation capability gating.
-Video runs through the diffusers pipelines in core/inference/video.py, which have no Apple path,
-so it is supported iff ``get_device() in {CUDA, XPU}`` with a reason otherwise (macos_unsupported
-/ pytorch_not_installed / no_accelerator / detection_failed). Mirrors test_export_capability.py:
-the matrix mocks the hardware probes, wiring is checked with ast, so it runs on CPU.
+Video runs through the diffusers pipelines in core/inference/video.py, so it is supported on
+CUDA and XPU, and on Apple Silicon whenever torch exposes a Metal device -- which is independent
+of MLX, and so of whether the host can train. Everything else gets a reason: macos_unsupported /
+pytorch_not_installed / mps_unavailable / no_accelerator / detection_failed. Mirrors
+test_export_capability.py: the matrix mocks the hardware probes, wiring is checked with ast, so
+it runs on CPU.
"""
import ast
+import sys
+import types
from pathlib import Path
+import pytest
+
import utils.hardware.hardware as hw
_BACKEND = Path(__file__).resolve().parent.parent
@@ -37,11 +43,17 @@ def _patch(
apple: bool,
chat_only_reason = "no_gpu",
system = None,
+ mps = None,
+ torch_import_error = None,
):
monkeypatch.setattr(hw, "_has_torch", lambda: torch)
monkeypatch.setattr(hw, "get_device", lambda: device)
monkeypatch.setattr(hw, "is_apple_silicon", lambda: apple)
monkeypatch.setattr(hw, "CHAT_ONLY_REASON", chat_only_reason)
+ # Pinned rather than left ambient: a real broken-torch host would otherwise leak into every
+ # case here, and the Apple branch reads it to tell "installed but broken" from "absent".
+ monkeypatch.setattr(hw, "TORCH_IMPORT_ERROR", torch_import_error)
+ monkeypatch.setattr(hw, "_torch_mps_available", lambda: torch if mps is None else mps)
# Pin the OS too. video_capability() asks platform.system() directly so an Intel Mac
# is covered, which means the non-Mac cases below would flip to macos_unsupported
# when this suite runs on a macOS runner. Default follows `apple` so existing callers
@@ -65,24 +77,71 @@ def test_xpu_supports_video(monkeypatch):
assert hw.video_capability()["video_supported"] is True
-def test_apple_silicon_reports_coming_soon(monkeypatch):
- """A healthy Apple Silicon host is not chat-only, so the tab is enabled and would just fail
- at load. Say what is actually true instead: there is no Apple video path yet."""
+def test_apple_silicon_with_mps_supports_video(monkeypatch):
+ """Apple Silicon runs the same device-neutral diffusers pipelines on Metal. The host may
+ report MLX or plain CPU depending on what else is installed; neither changes the answer."""
for device in (hw.DeviceType.MLX, hw.DeviceType.CPU):
_patch(monkeypatch, torch = True, device = device, apple = True)
cap = hw.video_capability()
- assert cap["video_supported"] is False
- assert cap["video_unsupported_reason"] == "macos_unsupported"
- assert "coming soon" in cap["video_unsupported_message"].lower()
+ assert cap["video_supported"] is True
+ assert cap["video_unsupported_reason"] is None
+ assert cap["video_unsupported_message"] is None
-def test_mlx_device_is_unsupported_even_without_the_apple_probe(monkeypatch):
- # MLX only exists on Apple, so an is_apple_silicon() that fails to answer must not
- # reclassify the host as a CPU box missing a GPU.
- _patch(monkeypatch, torch = False, device = hw.DeviceType.MLX, apple = False)
+def test_apple_silicon_without_torch_reports_pytorch_missing(monkeypatch):
+ _patch(monkeypatch, torch = False, device = hw.DeviceType.MLX, apple = True)
+ cap = hw.video_capability()
+ assert cap["video_supported"] is False
+ assert cap["video_unsupported_reason"] == "pytorch_not_installed"
+
+
+ "device, chat_only_reason",
+ [
+ # Both states detect_hardware() can actually publish for a broken torch on Apple Silicon.
+ # MLX needs no torch, so a healthy stack still reports MLX with no chat-only reason; a
+ # broken one falls back to CPU and records mlx_unavailable. Pairing MLX with
+ # mlx_unavailable would let the production check be narrowed to either and still pass.
+ (hw.DeviceType.MLX, None),
+ (hw.DeviceType.CPU, "mlx_unavailable"),
+ ],
+)
+def test_apple_silicon_with_broken_torch_is_not_told_to_install_it(
+ monkeypatch, device, chat_only_reason
+):
+ # A wheel with unresolved native libs raises from torch's own __init__, so _has_torch() reads
+ # False for it exactly as it does for an absent one, and neither reason above routes this host
+ # to the detection_failed branch. Without the explicit check it is told to install the
+ # PyTorch already sitting there broken.
+ _patch(
+ monkeypatch,
+ torch = False,
+ device = device,
+ apple = True,
+ chat_only_reason = chat_only_reason,
+ torch_import_error = "OSError('broken native library')",
+ )
+ cap = hw.video_capability()
+ assert cap["video_supported"] is False
+ assert cap["video_unsupported_reason"] == "detection_failed"
+ assert "fails to import" in cap["video_unsupported_message"]
+ assert "not installed" not in cap["video_unsupported_message"]
+
+
+def test_apple_silicon_without_a_metal_device_is_not_supported(monkeypatch):
+ # Apple Silicon alone does not imply MPS: a torch built without it leaves the pipelines
+ # with nowhere to run, and claiming support would fail at load instead of at the gate.
+ _patch(monkeypatch, torch = True, device = hw.DeviceType.MLX, apple = True, mps = False)
cap = hw.video_capability()
assert cap["video_supported"] is False
- assert cap["video_unsupported_reason"] == "macos_unsupported"
+ assert cap["video_unsupported_reason"] == "mps_unavailable"
+
+
+def test_mlx_device_is_apple_even_without_the_apple_probe(monkeypatch):
+ # MLX only exists on Apple, so an is_apple_silicon() that fails to answer must not
+ # reclassify the host as a CPU box missing a GPU. With torch + Metal it is supported.
+ _patch(monkeypatch, torch = True, device = hw.DeviceType.MLX, apple = False)
+ assert hw.video_capability()["video_supported"] is True
def test_no_torch_non_apple_reports_pytorch_missing(monkeypatch):
@@ -128,26 +187,83 @@ def test_main_endpoints_expose_video_capability():
assert '"/api/system/hardware"' in m and '"/api/system"' in m
+# -- the Metal probe itself ---------------------------------------------------------------------
+#
+# The matrix above stubs _torch_mps_available, so nothing there executes it. These drive the real
+# helper against a fake torch: without them, changing its predicate is invisible to the suite.
+
+
+def _fake_torch(monkeypatch, backends):
+ torch = types.ModuleType("torch")
+ torch.backends = backends
+ monkeypatch.setitem(sys.modules, "torch", torch)
+ monkeypatch.setattr(hw, "_has_torch", lambda: True)
+
+
+def test_mps_probe_reads_availability_not_whether_torch_was_built_with_it(monkeypatch):
+ class _Mps:
+ def __init__(self, available):
+ self._available = available
+
+ def is_available(self):
+ return self._available
+
+ def is_built(self):
+ return True
+
+ # is_built() is true on any Metal-capable build, including one that cannot reach a device
+ # here, so a probe on that predicate would promise video the host cannot run.
+ _fake_torch(monkeypatch, types.SimpleNamespace(mps = _Mps(available = False)))
+ assert hw._torch_mps_available() is False
+ _fake_torch(monkeypatch, types.SimpleNamespace(mps = _Mps(available = True)))
+ assert hw._torch_mps_available() is True
+
+
+def test_mps_probe_treats_a_torch_without_the_backend_as_no_metal(monkeypatch):
+ _fake_torch(monkeypatch, types.SimpleNamespace())
+ assert hw._torch_mps_available() is False
+
+
+def test_mps_probe_reports_no_metal_rather_than_raising(monkeypatch):
+ class _Boom:
+ def is_available(self):
+ raise RuntimeError("Metal probe blew up")
+
+ _fake_torch(monkeypatch, types.SimpleNamespace(mps = _Boom()))
+ assert hw._torch_mps_available() is False
+
+
+def test_mps_probe_reports_no_metal_when_torch_is_absent(monkeypatch):
+ # Only the answer is asserted, not that the import was skipped: an import of the None below
+ # raises into the same except, so both paths return False and no assertion can tell them apart.
+ monkeypatch.setattr(hw, "_has_torch", lambda: False)
+ monkeypatch.setitem(sys.modules, "torch", None)
+ assert hw._torch_mps_available() is False
+
+
def test_hardware_package_reexports_video_capability():
init = _src("utils/hardware/__init__.py")
assert "def video_capability()" in init
assert '"video_capability"' in init
-def test_video_capability_excludes_the_apple_backends():
+def test_video_capability_separates_apple_silicon_from_intel_macs():
cap = _func_src("utils/hardware/hardware.py", "video_capability")
- # Supported set is CUDA + XPU only; MLX is named solely on the unsupported side.
assert "DeviceType.CUDA, DeviceType.XPU" in cap
assert "_has_torch()" in cap
- # Strip comments and docstrings before asserting on the gate. This assertion used to
- # name is_apple_silicon(), and when the check widened to every Darwin host it kept
- # passing on the word surviving in a comment, which is not a test of anything.
+ # Strip comments before asserting on the gate. This assertion used to name
+ # is_apple_silicon(), and when the check widened to every Darwin host it kept passing on the
+ # word surviving in a comment, which is not a test of anything.
code = "\n".join(
line.split("#", 1)[0] for line in cap.splitlines() if not line.strip().startswith("#")
)
+ assert "_torch_mps_available()" in code, (
+ "Apple Silicon must be admitted on a measured Metal device, not on the platform alone, "
+ "or a torch without MPS is promised video it cannot run"
+ )
assert 'platform.system() == "Darwin"' in code, (
- "the macOS branch must key on Darwin, not Apple Silicon, or an Intel Mac is told "
- "to install PyTorch or buy a GPU for something macOS cannot do at all"
+ "the remaining macOS branch must key on Darwin, or an Intel Mac falls through to be "
+ "told to install PyTorch or buy a GPU for something it cannot do either way"
)
assert "DeviceType.MLX" in code
@@ -163,8 +279,8 @@ def test_frontend_reads_the_new_fields():
def test_intel_mac_is_macos_unsupported_not_a_missing_gpu(monkeypatch):
# An Intel Mac detects as plain CPU and is_apple_silicon() is False, so the reason
# used to come out as pytorch_not_installed or no_accelerator. Both tell the user to
- # install PyTorch or add a GPU, and neither enables video: the pipelines have no
- # supported macOS path at all. Same answer on both Macs.
+ # install PyTorch or add a GPU, and neither enables video on a machine with no Metal
+ # device. Installing torch does not change that, so the answer holds either way.
for torch_present in (True, False):
_patch(
monkeypatch,
@@ -172,13 +288,14 @@ def test_intel_mac_is_macos_unsupported_not_a_missing_gpu(monkeypatch):
device = hw.DeviceType.CPU,
apple = False,
system = "Darwin",
+ mps = False,
)
cap = hw.video_capability()
assert cap["video_supported"] is False
assert cap["video_unsupported_reason"] == "macos_unsupported", (
f"Intel Mac with torch={torch_present} reported " f"{cap['video_unsupported_reason']!r}"
)
- assert "coming soon" in cap["video_unsupported_message"].lower()
+ assert "Apple Silicon" in cap["video_unsupported_message"]
assert "GPU" not in cap["video_unsupported_message"]
diff --git a/studio/backend/tests/test_video_prequant.py b/studio/backend/tests/test_video_prequant.py
index 8ee9439f2c8..9b6bd71c02a 100644
--- a/studio/backend/tests/test_video_prequant.py
+++ b/studio/backend/tests/test_video_prequant.py
@@ -219,6 +219,62 @@ def test_auto_is_never_refused():
pass
+def _forced_target(device):
+ """A resolved diffusion target on ``device``, so a refusal keyed on the device can be tested
+ off the hardware that has it."""
+ from core.inference.diffusion_device import DiffusionDeviceTarget
+ return lambda: DiffusionDeviceTarget(
+ device = device,
+ dtype = None,
+ backend = device,
+ vendor = None,
+ supports_model_cpu_offload = False,
+ supports_default_torch_compile = False,
+ supports_pinned_transfer = False,
+ supports_float64 = device != "mps",
+ )
+
+
+def test_the_modular_pipeline_is_refused_on_metal(monkeypatch):
+ # _load_h3_modular_pipeline places every non-CPU device with
+ # ComponentsManager.enable_auto_cpu_offload, which raises NotImplementedError when the device
+ # module has no mem_get_info, and torch.mps has none. Refuse before ~145 GB downloads.
+ monkeypatch.setattr(
+ "core.inference.video.resolve_diffusion_device_target", _forced_target("mps")
+ )
+ backend = VideoBackend()
+ with pytest.raises(ValueError, match = "cannot run on Apple Silicon"):
+ backend.validate_load_request("MiniMaxAI/MiniMax-H3")
+
+
+def test_the_metal_refusal_names_the_artifact_that_does_run_there(monkeypatch):
+ # A dead end is not an answer: H3's GGUF checkpoints run on the native engine on the same
+ # host, so the refusal has to point at them.
+ monkeypatch.setattr(
+ "core.inference.video.resolve_diffusion_device_target", _forced_target("mps")
+ )
+ backend = VideoBackend()
+ with pytest.raises(ValueError, match = "unsloth/MiniMax-H3-GGUF"):
+ backend.validate_load_request("MiniMaxAI/MiniMax-H3")
+
+
+def test_the_metal_refusal_leaves_every_other_device_alone(monkeypatch):
+ # The mirror image: CUDA is where this workflow is meant to run, so the refusal must be
+ # scoped to the device that cannot place it.
+ monkeypatch.setattr(
+ "core.inference.video.resolve_diffusion_device_target", _forced_target("cuda")
+ )
+ backend = VideoBackend()
+ try:
+ backend.validate_load_request("MiniMaxAI/MiniMax-H3")
+ except ValueError as exc: # pragma: no cover - only on a regression
+ pytest.fail(f"a CUDA modular load must not be refused: {exc}")
+ except Exception:
+ # Anything past the refusal (the diffusers probe further down) already proves it did not
+ # fire.
+ pass
+
+
def test_the_refusals_run_before_the_diffusers_availability_probe():
# Placement matters: the probe below imports diffusers, and on an environment where that raises
# the user would get an unrelated error instead of the actionable refusal. Asserting the
diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.py
index dc477cc4995..4422b478dc4 100644
--- a/studio/backend/utils/hardware/hardware.py
+++ b/studio/backend/utils/hardware/hardware.py
@@ -235,6 +235,22 @@ def _has_torch() -> bool:
return False
+def _torch_mps_available() -> bool:
+ """True when torch exposes a usable Metal (MPS) device.
+
+ Apple Silicon alone is not enough: a torch built without MPS, or one that fails to import,
+ leaves the pipelines nowhere to run. Never raises; a failed probe reads as no MPS.
+ """
+ if not _has_torch():
+ return False
+ try:
+ import torch
+ mps = getattr(getattr(torch, "backends", None), "mps", None)
+ return bool(mps is not None and mps.is_available())
+ except Exception:
+ return False
+
+
def _has_mlx() -> bool:
"""True if MLX is importable."""
try:
@@ -267,10 +283,11 @@ def verdict_pending_mlx_repair(chat_only: bool, reason: Optional[str]) -> bool:
Detection gets its answer before utils.mlx_repair gets its turn, so an Apple Silicon
host whose MLX stack is missing or unreadable settles chat-only first and flips only
- once the background reinstall lands. Published as final, that greys Train and Video
- behind a "run `unsloth studio update`" tooltip the repair makes wrong a minute later,
- and the rows then enable themselves on the frontend's recovery poll -- the reported
- "greyed out, then they come out". Callers report it as still-detecting instead.
+ once the background reinstall lands. Published as final, that greys Train behind a
+ "run `unsloth studio update`" tooltip the repair makes wrong a minute later, and the row
+ then enables itself on the frontend's recovery poll -- the reported "greyed out, then
+ they come out". Callers report it as still-detecting instead. Video is unaffected either
+ way: it runs on Metal without MLX and reads its own capability verdict.
The "mlx_unavailable" check is also what lets mlx_repair_in_flight() be cheap: that
reason means this pass has just measured the stack as unusable, so the self-heal only
@@ -634,10 +651,10 @@ def export_capability() -> dict:
def video_capability() -> dict:
"""Whether video generation can run here, with a torch-aware reason when it cannot.
- Video runs through the diffusers pipelines in core/inference/video.py, which have no Apple
- path: no MLX backend, and the families ship no MPS-tested route, so macOS is reported as
- unsupported rather than left to fail at load. Supported iff ``get_device() in {CUDA, XPU}``.
- Safe to call without torch.
+ Supported on CUDA and XPU, and on Apple Silicon with a usable MPS device. The pipelines in
+ core/inference/video.py are device-neutral -- they resolve the device through the shared
+ diffusion device target, whose capability flags already decline the CUDA-only options -- so
+ Metal needs no branches of its own. Safe to call without torch.
Returns {video_supported, video_unsupported_reason, video_unsupported_message}.
"""
@@ -655,14 +672,43 @@ def video_capability() -> dict:
"Hardware detection failed on this host, so video generation is disabled. The server "
"log records the underlying error; restart Unsloth Studio to retry detection."
)
- elif platform.system() == "Darwin" or get_device() == DeviceType.MLX:
- # Every Mac, not just Apple Silicon. An Intel Mac detects as plain CPU, so an
- # is_apple_silicon() test drops it into the branches below and tells the user to
- # install PyTorch or add a GPU. Neither enables video here: the pipelines have no
- # supported macOS path at all, so the honest answer is the same on both Macs.
+ elif is_apple_silicon() or get_device() == DeviceType.MLX:
# The MLX arm covers an Apple host whose platform probe somehow disagrees.
+ if _torch_mps_available():
+ return {
+ "video_supported": True,
+ "video_unsupported_reason": None,
+ "video_unsupported_message": None,
+ }
+ if TORCH_IMPORT_ERROR is not None:
+ # Installed but broken reads as no torch below, and detect_hardware() records
+ # mlx_unavailable for this host, so neither the branch above nor the one below sees
+ # it -- and the host would be told to install the PyTorch it already has.
+ reason = "detection_failed"
+ message = (
+ "PyTorch is installed but fails to import on this host, so the video pipelines "
+ "cannot start. The server log records the error; reinstall PyTorch to fix it."
+ )
+ elif not _has_torch():
+ reason = "pytorch_not_installed"
+ message = (
+ "PyTorch is not installed. Video generation on Apple Silicon requires PyTorch "
+ "with Metal (MPS) support. Install PyTorch to enable video generation."
+ )
+ else:
+ reason = "mps_unavailable"
+ message = (
+ "This PyTorch build exposes no Metal (MPS) device, so the video pipelines have "
+ "nowhere to run. Reinstall PyTorch with MPS support to enable video generation."
+ )
+ elif platform.system() == "Darwin":
+ # Ahead of the torch/GPU branches below: neither installing torch nor adding a GPU
+ # enables video on an Intel Mac, so it must not be told to try either.
reason = "macos_unsupported"
- message = "Video generation on macOS is coming soon."
+ message = (
+ "Video generation requires Apple Silicon. This Intel Mac has no Metal (MPS) device "
+ "for the video pipelines to run on."
+ )
elif not _has_torch():
reason = "pytorch_not_installed"
message = (
@@ -712,17 +758,28 @@ def clear_gpu_cache():
except Exception as e:
logger.debug("Failed to clear XPU cache: %s", e)
elif device == DeviceType.MLX:
- # 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)
+ _clear_mps_cache()
+ elif is_apple_silicon():
+ # An Apple Silicon host whose MLX stack is unavailable reports CPU, but diffusion and
+ # video still run on Metal (see diffusion_device._mps_or_cpu_target), so the MPS
+ # allocator needs the same teardown the MLX branch gets.
+ _clear_mps_cache()
+
+
+def _clear_mps_cache() -> None:
+ """Return torch's MPS reservations to the shared pool.
+
+ MLX manages its own memory, but Apple Silicon also runs torch MPS (diffusion/video), whose
+ caching allocator keeps freed buffers reserved. Those bytes read as used system memory, so
+ skipping 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]:
diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsx
index d4c9f2cadbc..70f94632c32 100644
--- a/studio/frontend/src/app/routes/__root.tsx
+++ b/studio/frontend/src/app/routes/__root.tsx
@@ -96,8 +96,8 @@ const CHAT_ONLY_ALLOWED = new Set([
// Paths that render their own "still checking" state and self-gate once the verdict lands.
// The redirect below is one-way, so acting on the pre-measurement guess strands a healthy host
// on /chat; these two wait it out instead. Everything else keeps the old behaviour.
-// /video is allowed outright below, so in practice this is what keeps /studio off the guess;
-// it stays listed because that is the property the page's own loading panel relies on.
+// /video is allowed outright below, so this is in practice what keeps /studio off the guess. It
+// stays listed so that admission is the only thing /video depends on, not both.
const SELF_GATED_WHILE_UNKNOWN = ["/studio", "/video"];
function waitsOutUnknownVerdict(pathname: string): boolean {
@@ -112,10 +112,9 @@ function isChatOnlyAllowed(pathname: string): boolean {
return true;
// Images runs on CPU/MPS via the native sd.cpp engine, the very no-GPU setup it was added for. The chat-only flag is about training/export, so it must not redirect /images.
if (pathname === "/images" || pathname.startsWith("/images/")) return true;
- // Video follows /export: the page explains an unsupported host itself, using the backend's
- // own video verdict (no GPU, no PyTorch, no Apple path). A measured chat-only host is exactly
- // where that explanation belongs, so a direct link or a reload has to reach VideoPage's gate
- // instead of bouncing to /chat. It self-gates on videoSupported, so nothing loads.
+ // Video follows /export: the page explains an unsupported host itself from the backend's video
+ // verdict, and on Apple Silicon a chat-only host is where video works anyway. So a direct link
+ // or a reload must reach VideoPage's gate, which self-gates on videoSupported.
if (pathname === "/video" || pathname.startsWith("/video/")) return true;
return false;
}
diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsx
index b9342343d3b..0e2df7720c0 100644
--- a/studio/frontend/src/components/app-sidebar.tsx
+++ b/studio/frontend/src/components/app-sidebar.tsx
@@ -146,6 +146,7 @@ import type { SidebarNavItemId } from "@/features/settings";
import { useEffectiveProfile, UserAvatar } from "@/features/profile";
import { resolveNavRowState } from "@/components/nav-row-state";
import { fetchDeviceType, usePlatformStore } from "@/config/env";
+import { videoNavHint } from "@/config/hardware-verdict";
import { clearAuthTokens, logout } from "@/features/auth";
import { TOUR_OPEN_EVENT } from "@/features/tour";
import {
@@ -618,7 +619,6 @@ export function AppSidebar() {
const chatOnly = usePlatformStore((s) => s.isChatOnly());
const chatOnlyReason = usePlatformStore((s) => s.chatOnlyReason);
const detectionDeferred = usePlatformStore((s) => s.detectionDeferred);
- const platformDeviceType = usePlatformStore((s) => s.deviceType);
// Until /api/health answers, `chatOnly` is the browser-platform guess, so every Mac painted
// Train and Video blacked out on load and only recovered once the backend reported. Gate the
// rows on a measured verdict and let them spin until it lands.
@@ -635,16 +635,9 @@ export function AppSidebar() {
: chatOnlyReason === "no_gpu"
? "Training needs an NVIDIA or AMD GPU."
: undefined;
- // Video's hint is derived the same way. It used to be hardcoded to "needs an NVIDIA or AMD
- // GPU", which is wrong on an Apple Silicon host: video has no Apple path at all, so the row
- // says so rather than pointing at hardware the user cannot add.
- const videoDisabledHint: string | undefined = !chatOnlyMeasured
- ? undefined
- : platformDeviceType === "mac"
- ? "Video generation on macOS is coming soon."
- : chatOnlyReason === "no_gpu"
- ? "Video generation needs an NVIDIA or AMD GPU."
- : undefined;
+ // Everything without a hint reaches VideoPage, which answers from the backend's video verdict.
+ const videoDisabledHint = videoNavHint(chatOnlyMeasured, chatOnlyReason);
+ const videoDisabled = videoDisabledHint !== undefined;
// Two things can change the verdict after the first /api/health. The backend MLX self-heal
// (utils/mlx_repair) can reinstall MLX and flip chat_only false without a restart, and
@@ -659,7 +652,8 @@ export function AppSidebar() {
// provisional reply, and nothing else is scheduled to re-read it: the rows above would spin
// and /studio would hold its loading panel for the rest of the session. This is the only
// recovery poll in the app, and the sidebar is mounted on every route that gates on the
- // verdict (studio-page and video-page read the same store, so they recover with it).
+ // verdict (studio-page reads the same store, so it recovers with it; video-page reads the
+ // backend's video verdict instead and needs nothing from here).
if (selfHealSettled && !capabilitiesUnknown) return;
let pollingSince = 0;
// Which read currently owns the guard. A read that outlived the stall window is replaced,
@@ -1116,12 +1110,12 @@ export function AppSidebar() {
preloadSilently(router.preloadRoute({ to: "/studio" }));
},
},
- // Video is diffusers-only, so a chat-only host cannot load it: disable with a hint instead of bouncing off the root guard.
+ // A host with no video device at all is disabled with a hint instead of bouncing off the root guard.
video: {
icon: FlimSlateIcon,
label: t("shell.navigation.video"),
active: pathname === "/video" || pathname.startsWith("/video/"),
- disabled: chatOnlyMeasured,
+ disabled: videoDisabled,
tooltip: videoDisabledHint,
pending: capabilitiesUnknown,
pendingTooltip: t("shell.navigation.videoChecking"),
diff --git a/studio/frontend/src/config/hardware-verdict.ts b/studio/frontend/src/config/hardware-verdict.ts
index cd6607f4e6e..b5b5bb0c9eb 100644
--- a/studio/frontend/src/config/hardware-verdict.ts
+++ b/studio/frontend/src/config/hardware-verdict.ts
@@ -1,9 +1,10 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-// Whether a /api/health reply carries a measured hardware verdict or the backend's
-// pre-detection default. Its own import-free module so it is testable: env.ts reaches
-// import.meta.env through api-base.ts, which only vite can load.
+// The /api/health hardware verdict: whether a reply carries a measured one or the backend's
+// pre-detection default, and what the shell derives from it. Its own import-free module so it is
+// testable: env.ts reaches import.meta.env through api-base.ts, which only vite can load, and a
+// derivation left in a component can only be checked by grepping its source.
export type HealthVerdict = {
chat_only?: boolean;
@@ -31,6 +32,25 @@ export function isDetectionDeferred(data: HealthVerdict): boolean {
}
+/** The Video row's tooltip, or undefined when the row stays navigable.
+ *
+ * Only the chat-only reasons that leave no video device at all. Apple Silicon runs video on Metal
+ * with or without a healthy MLX stack, so "mlx_unavailable" is not one of them: those hosts reach
+ * VideoPage, which reports the backend's video verdict.
+ */
+export function videoNavHint(
+ chatOnlyMeasured: boolean,
+ chatOnlyReason: string | null,
+): string | undefined {
+ if (!chatOnlyMeasured) return undefined;
+ // Not "or a GPU": an Intel Mac's own dGPU is not one the video pipelines can use, so offering
+ // that reads as a fix that would not work. Mirrors the backend's message for this host.
+ if (chatOnlyReason === "intel_mac")
+ return "Video generation requires Apple Silicon. This Intel Mac has no Metal device to run it.";
+ if (chatOnlyReason === "no_gpu") return "Video generation needs an NVIDIA or AMD GPU.";
+ return undefined;
+}
+
/** The verdict to store. A provisional reply keeps the previous values: storing
* its chat_only tells a GPU host it has no GPU, and beforeLoad redirects on that. */
export function resolveVerdict(
diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsx
index 6187e2b8b9f..5c9343e611d 100644
--- a/studio/frontend/src/features/video/video-page.tsx
+++ b/studio/frontend/src/features/video/video-page.tsx
@@ -15,7 +15,6 @@ import { HugeiconsIcon } from "@hugeicons/react";
import { AdvancedDisclosure } from "@/components/advanced-disclosure";
import { ImageDropzone } from "@/components/image-dropzone";
import { MediaPageLink } from "@/components/media-page-link";
-import { usePlatformStore } from "@/config/env";
import { useHardwareInfo } from "@/hooks/use-hardware-info";
import { usePersistedToggle } from "@/hooks/use-persisted-toggle";
import { Button } from "@/components/ui/button";
@@ -687,20 +686,18 @@ function VideoGate({ children }: { children: ReactNode }) {
/**
* Capability gate in front of the generator.
*
- * The root guard never bounces /video: not on the browser-platform guess, and not on a measured
- * chat-only verdict either, because a CPU-only host or a Mac without MLX is precisely where the
- * explanation below has something to say. Video also has no Apple path in the backend, so the
- * page answers for itself: spin while the answer is out, explain when it is no.
+ * The root guard never bounces /video: a chat-only host is both where the explanation below has
+ * something to say (a CPU-only box) and where video works anyway (Apple Silicon whose only
+ * problem is MLX). So the page answers for itself: spin while the answer is out, explain a no.
*
- * The spin is bounded: AppSidebar is mounted on this route and re-reads /api/health while the
- * verdict is unknown, writing it to the same store this reads, so a host slower than
- * fetchDeviceType's bounded wait still lands here rather than spinning for the session.
+ * That answer is /api/system/hardware's alone, which settles detection before replying. Waiting
+ * on the chat-only verdict too would spin through an MLX self-heal /api/health holds it back for,
+ * which cannot change a Metal answer.
*/
export function VideoPage({ active = true }: { active?: boolean }) {
const hardware = useHardwareInfo();
- const capabilitiesUnknown = usePlatformStore((s) => s.capabilitiesUnknown());
- if (capabilitiesUnknown || !hardware.loaded) {
+ if (!hardware.loaded) {
return (
<VideoGate>
<Spinner className="size-5" />
diff --git a/studio/frontend/tests/hardware-verdict-recovery.test.ts b/studio/frontend/tests/hardware-verdict-recovery.test.ts
index 1c5565a1bf2..6911f83d6b9 100644
--- a/studio/frontend/tests/hardware-verdict-recovery.test.ts
+++ b/studio/frontend/tests/hardware-verdict-recovery.test.ts
@@ -151,15 +151,15 @@ test("the poll is mounted on every route that gates on the verdict", async () =>
);
const hidden = /const HIDDEN_NAVBAR_ROUTES = \[([^\]]*)\]/.exec(root);
assert.ok(hidden, "could not find HIDDEN_NAVBAR_ROUTES in __root.tsx");
- for (const path of ["/studio", "/video"]) {
- assert.ok(
- !hidden[1].includes(`"${path}"`),
- `${path} renders without the sidebar, so nothing re-reads the verdict it waits on`,
- );
- }
+ assert.ok(
+ !hidden[1].includes('"/studio"'),
+ "/studio renders without the sidebar, so nothing re-reads the verdict it waits on",
+ );
assert.match(root, /<AppSidebar \/>/, "the component that owns the poll is not rendered");
- // Both pages read the same store rather than starting a second poll of their own.
+ // Neither page starts a poll of its own. Video needs none at all -- its answer is
+ // /api/system/hardware's, which settles detection before replying -- so it is absent from the
+ // waits-on-the-verdict assertion below, but a second /api/health poll would still be wrong.
for (const page of [
"../src/features/studio/studio-page.tsx",
"../src/features/video/video-page.tsx",
@@ -169,10 +169,14 @@ test("the poll is mounted on every route that gates on the verdict", async () =>
!/fetchDeviceType\(/.test(src),
`${page} re-reads the verdict itself instead of reading the store`,
);
- assert.match(
- src,
- /capabilitiesUnknown/,
- `${page} no longer waits on the verdict it shares with the poll`,
- );
}
+ const studio = await readFile(
+ new URL("../src/features/studio/studio-page.tsx", import.meta.url),
+ "utf8",
+ );
+ assert.match(
+ studio,
+ /capabilitiesUnknown/,
+ "the Train page no longer waits on the verdict it shares with the poll",
+ );
});
diff --git a/studio/frontend/tests/provisional-hardware-verdict.test.ts b/studio/frontend/tests/provisional-hardware-verdict.test.ts
index e4d1aa5f96e..1872e98c251 100644
--- a/studio/frontend/tests/provisional-hardware-verdict.test.ts
+++ b/studio/frontend/tests/provisional-hardware-verdict.test.ts
@@ -13,7 +13,7 @@ import { registerBundlerResolver } from "./helpers/kit.ts";
registerBundlerResolver();
-const { isDetectionDeferred, isProvisionalVerdict, resolveVerdict } = await import(
+const { isDetectionDeferred, isProvisionalVerdict, resolveVerdict, videoNavHint } = await import(
"../src/config/hardware-verdict.ts"
);
@@ -400,8 +400,8 @@ test("the route guard waits out an unknown verdict on Train and Video", async ()
);
});
-// The tab is enabled on a healthy Apple Silicon host (chat_only is false there), and the
-// backend has no video path for it, so the page has to say so rather than fail at load.
+// The tab is reachable on hosts the backend still refuses — no GPU, no MPS device, no PyTorch —
+// so the page has to say which, rather than fail at load.
test("the Video page gates on the backend's own capability answer", async () => {
const { readFile } = await import("node:fs/promises");
const src = await readFile(
@@ -415,9 +415,17 @@ test("the Video page gates on the backend's own capability answer", async () =>
);
assert.match(
src,
- /capabilitiesUnknown \|\| !hardware\.loaded/,
+ /if \(!hardware\.loaded\)/,
"the page renders its generator before the verdict has landed",
);
+ // /api/health withholds the chat-only verdict for the whole MLX self-heal. Video does not use
+ // MLX, so waiting on it would spin this page through a reinstall that cannot change its answer.
+ // The whole store is forbidden, not just capabilitiesUnknown: any of its properties would put
+ // the training verdict back in front of an answer that is already authoritative.
+ assert.ok(
+ !/usePlatformStore/.test(src),
+ "the Video gate waits on the training verdict again",
+ );
// A backend that predates the field sends nothing, which arrives as null; only an explicit
// false may hide the generator.
assert.ok(
@@ -426,24 +434,79 @@ test("the Video page gates on the backend's own capability answer", async () =>
);
});
-// The hardcoded "needs an NVIDIA or AMD GPU" is wrong on Apple Silicon: no GPU the user can
-// add would help, because there is no Apple video path at all.
-test("the Video tooltip is derived, not hardcoded", async () => {
+// The hardcoded "needs an NVIDIA or AMD GPU" is wrong on a Mac: no GPU the user can add would
+// un-chat-only the host. The hint names the measured chat-only reason instead.
+test("the Video hint names the reason the host has no video device", () => {
+ assert.equal(videoNavHint(false, null), undefined, "a capable host is disabled");
+ // An unmeasured verdict can still carry a reason from a previous reply, and must not be read
+ // as one: the row would grey out on a host nothing has measured yet.
+ assert.equal(videoNavHint(false, "no_gpu"), undefined, "an unmeasured host is disabled");
+ assert.equal(videoNavHint(false, "intel_mac"), undefined, "an unmeasured host is disabled");
+ assert.equal(
+ videoNavHint(true, "no_gpu"),
+ "Video generation needs an NVIDIA or AMD GPU.",
+ "a GPU-less host is not told why",
+ );
+ assert.match(
+ videoNavHint(true, "intel_mac") ?? "",
+ /Apple Silicon/,
+ "an Intel Mac is not told what video actually needs",
+ );
+ // No wording may offer graphics hardware as the fix. An Intel Mac can have an AMD dGPU and it
+ // is still useless here: torch's only macOS backend is MPS, and MPS needs Apple Silicon.
+ assert.ok(
+ !/gpu|graphics|coming soon/i.test(videoNavHint(true, "intel_mac") ?? ""),
+ "an Intel Mac is pointed at graphics hardware that cannot run video",
+ );
+});
+
+// A broken MLX stack makes the host chat-only, but video runs on Metal and does not use MLX,
+// so the backend reports video_supported there. Disabling the row would strand the capability
+// behind a training dependency, reachable only by typing the URL.
+test("a chat-only Apple Silicon host keeps Video navigable", () => {
+ assert.equal(
+ videoNavHint(true, "mlx_unavailable"),
+ undefined,
+ "a repairable MLX stack disables video, which does not use MLX",
+ );
+ // Same for a probe that never produced a reason: VideoPage explains it, the sidebar cannot.
+ assert.equal(videoNavHint(true, "detection_failed"), undefined);
+ assert.equal(videoNavHint(true, null), undefined);
+});
+
+// The row's disabled state must follow the hint, not chatOnly: that is the wiring the two
+// tests above only describe.
+test("the Video row is disabled exactly when the hint has something to say", async () => {
const { readFile } = await import("node:fs/promises");
const src = await readFile(
new URL("../src/components/app-sidebar.tsx", import.meta.url),
"utf8",
);
- assert.match(src, /const videoDisabledHint: string \| undefined/, "no derived video hint");
assert.match(
src,
- /platformDeviceType === "mac"\s*\?\s*"Video generation on macOS is coming soon\."/,
- "a Mac is still told to fit a GPU",
+ /const videoDisabledHint = videoNavHint\(chatOnlyMeasured, chatOnlyReason\)/,
+ "the Video hint no longer comes from the shared derivation",
);
- assert.ok(
- !/tooltip: chatOnly\s*\n?\s*\? "Video generation needs an NVIDIA or AMD GPU\."/.test(src),
- "the hardcoded tooltip is still wired to the row",
+ assert.match(
+ src,
+ /const videoDisabled = videoDisabledHint !== undefined/,
+ "the Video row's disabled state is no longer derived from its hint",
+ );
+ // The train row keeps `disabled: chatOnlyMeasured`, so match inside the video row only.
+ const videoRow = src.slice(src.indexOf(" video: {"));
+ const videoBody = videoRow.slice(0, videoRow.indexOf("},"));
+ assert.match(
+ videoBody,
+ /disabled: videoDisabled,/,
+ "the Video row is gated on the training verdict again",
+ );
+ // Disabled without the hint is worse than either alone: a greyed row with nothing to explain it.
+ assert.match(
+ videoBody,
+ /tooltip: videoDisabledHint,/,
+ "the Video row is disabled with no reason shown",
);
+ assert.ok(!/coming soon/.test(src), "the Video row still promises macOS support that has shipped");
});
// The Video gate waits on useHardwareInfo's `loaded`, and a failed probe used to resolve to
diff --git a/studio/frontend/tests/sidebar-nav-backend-parity.test.ts b/studio/frontend/tests/sidebar-nav-backend-parity.test.ts
index 54abfc462b3..362d2cd5415 100644
--- a/studio/frontend/tests/sidebar-nav-backend-parity.test.ts
+++ b/studio/frontend/tests/sidebar-nav-backend-parity.test.ts
@@ -57,7 +57,14 @@ test("Train and Video are still the capability-gated rows", async () => {
assert.ok(bodies.has(id), `the backend ships a "${id}" row the sidebar does not define`);
}
- for (const id of ["train", "video"]) {
+ // Train reads the chat-only verdict; Video reads only the subset of its reasons that leave no
+ // video device, and that expression is pinned in provisional-hardware-verdict.test.ts, so it is
+ // not restated here. Video is still required to have a disabled state -- swapping it for
+ // Train's would pass there, and un-gate the row on a Mac whose only problem is MLX.
+ for (const [id, disabled] of [
+ ["train", /disabled: chatOnlyMeasured,/],
+ ["video", /disabled: (?!chatOnlyMeasured)\w+,/],
+ ] as const) {
const body = bodies.get(id);
assert.ok(body, `no ${id} row`);
assert.match(
@@ -67,8 +74,8 @@ test("Train and Video are still the capability-gated rows", async () => {
);
assert.match(
body,
- /disabled: chatOnlyMeasured,/,
- `the ${id} row disables on the browser-platform guess`,
+ disabled,
+ `the ${id} row is no longer capability-gated on its own verdict`,
);
}
});