Repository navigation
Studio: enable video generation on Apple Silicon - #8198
Conversation
LTX-2's rotary embeddings build `theta ** linspace(0, 1, n)` in float64 and cast the result straight back to float32 on the next line. Metal implements no float64 and torch raises rather than demoting, so on an Apple GPU the generation dies in the connectors before the first denoise step: ``` TypeError: Cannot convert a MPS Tensor to float64 dtype as the MPS framework doesn't support float64. Please use float32 instead. diffusers/pipelines/ltx2/connectors.py:128 in forward ``` Six sites share the pattern (two in the connectors, four in the transformer) and all gate the intermediate on a `double_precision` attribute, so clearing it yields the identical float32 value the caller was going to take anyway. Across the theta/dim combinations these models use the two paths differ by at most 6 float32 ULP (max relative 4.4e-07), against a value that is truncated to float32 immediately after. Expressed as a device capability rather than a platform test: `DiffusionDeviceTarget` grows `supports_float64`, defaulted true so only the two MPS constructors have to say otherwise, and `force_float32_rope` walks the pipeline's components once at load. It is a no-op wherever float64 works, so CUDA, XPU and CPU keep the upstream computation bit-for-bit.
d0e1205 to
16eb6c4
Compare
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 16eb6c402c
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Video was reported unsupported on every Mac, with "Video generation on macOS is coming soon." That verdict was the only thing standing in the way: `routes/video.py` and `core/inference/video.py` carry no capability check at all, and the backend already accepted a video load on a Mac. The UI simply never issued one. The pipelines are device-neutral. They resolve the device through the same target the image path uses, which already returns a working MPS device, and the CUDA-only options are already declined there by the target's capability flags: no torch.compile, no cuDNN/flash/sage attention, no torchao quantisation, and no CPU offload, which a unified memory pool has nowhere to do anyway. The memory planner has had an Apple arm for as long as it has had a CUDA one. So `video_capability()` grows an Apple Silicon arm, admitted on a measured Metal device rather than on the platform alone: Apple Silicon whose torch exposes no MPS device reports `mps_unavailable`, and one with no torch at all reports `pytorch_not_installed`, instead of being promised video neither can run. A failed hardware probe still reports `detection_failed` first, matching the export verdict. Intel Macs stay unsupported, but their message changes. "Coming soon" described a platform with no path at all, which is no longer true of macOS, so it now names what is actually missing: Apple Silicon, and with it a Metal device for the pipelines to run on. The sidebar's video hint likewise moves from the browser's platform guess to the measured chat-only reason, so a Mac is never told to fit a GPU it cannot fit. Validated on an M3 Max: Wan2.2-TI2V-5B loads on MPS in bf16 and generates a coherent, temporally stable clip, with every degradation landing exactly as the capability flags predict.
16eb6c4 to
6d342ea
Compare
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Wan's VAE decodes one latent frame per call in a Python loop that never forces a commit. Metal cannot reuse a buffer until the work holding it has completed, so every frame's intermediates stay resident: a 121x704x1280 Wan2.2 TI2V-5B decode grew ~0.72 GiB per call and passed 148 GiB before the OS killed the process. Denoising completed and no torch OOM was ever raised, so the failure surfaced only as a SIGKILL. VAE tiling does not bound it, because the growth is within a single tile and the per-tile cache reset comes 31 calls too late. Torch's own adaptive commit does not either: a low watermark set to a tenth of the recommended working set left the peak unchanged, and the hard watermark reaches the same result through a full cache release, at 35% more wall clock. A forward hook on the VAE decoder synchronises once allocation passes 0.85 of the device's recommended working set, so memory plateaus there instead of climbing. Synchronising waits only on work already enqueued, and below the threshold a decode pays just the memory read: 2.8 ms across 868 calls. The decode above now completes at 91.72 GiB. The hook fires per decoder call, which is per frame on Wan and per tile on the video VAEs that decode a whole tensor at once.
3e64185 to
16b39cb
Compare
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 16b39cb0e8
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
Codex Review: Didn't find any major issues. Another round soon, please! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…ended_max_memory
install_decoder_sync() read torch.mps.recommended_max_memory() unguarded. That
reading arrived in torch 2.5 (absent in torch/mps/__init__.py at v2.4.0, present
at v2.5.0), while install.sh keeps an existing venv's torch release whenever it
is inside the active window, which on macOS arm64 is torch>=2.4,<2.11. So an
Apple Silicon host carrying torch 2.4.x is told video_supported: true by the new
capability arm and then dies with
AttributeError: module 'torch.mps' has no attribute 'recommended_max_memory'
inside the load, after the download and with no OOM to explain it. Reproduced on
a macos-14 runner with torch 2.4.1: video_capability() returns supported on the
same host where install_decoder_sync() raises.
An unreadable budget now falls back to synchronising every decoder call rather
than failing the load or, worse, skipping the hook and leaving the unbounded
decode it exists to stop. Unconditional synchronise was already measured to hold
the same Wan decode at 4.90 GiB for no wall-clock cost, so the fallback is the
cheap side of the trade. Both memory readings and the synchronise itself are
best-effort for the same reason: a gauge that raises mid-decode is not worth
losing the generation over, and an unreadable gauge takes the safe side and
synchronises.
Four regression tests, each mutation-checked: dropping either guard, skipping the
sync when there is no budget, and letting an unreadable gauge skip instead of
synchronise are all caught.
|
Reviewed this end to end. The central claim holds, the float64 fix is real and I reproduced both the failure and the fix on a real Apple Silicon runner, and I found one bug in the new code, which is fixed in 785ef2a. 1. Was the gate the only blockerYes, as described.
The float64 fix is correct and it is the only such site. On macos-15 / torch 2.10, The precision claim checks out as stated. Against the shipped checkpoint config ( 2. One genuine bug, fixed in 785ef2a
torch 2.4 is inside the window this project keeps. Reproduced on a macos-14 runner with torch 2.4.1, on the same host, in the same process: So the new capability arm advertises video and the load then dies inside 785ef2a falls back to synchronising every decoder call when the budget cannot be read, rather than failing the load or skipping the hook and leaving the unbounded decode. That fallback is the one this PR already measured as free (4.90 GiB, no measurable wall clock). Both readings and the synchronise are now best-effort, so a gauge that raises mid-decode cannot lose a generation, and an unreadable gauge takes the safe side. Four tests, each mutation-checked: dropping either guard, skipping the sync when there is no budget, and letting an unreadable gauge skip instead of synchronise are all caught, five mutations, five failures. 3. Memory on Apple Silicon: the planner sizes it right and then cannot act on itRunning the shipped planner against a unified-memory
Against Two things follow that are worth naming explicitly. GGUF barely helps on Metal, because the floor is not the DiT. For
What happens when it does not fit is the part I would look at next. It is not a graceful refusal. I am not asking for that here. It is pre-existing on 4. No regressions
Worth noting that nothing that existed before covered this: Two caveats on what I could not establish. I have no Mac, so every number in section 3 is the shipped planner's arithmetic rather than a measured peak, and the decode-sync figures in the description are yours, not reproduced. And GitHub's macOS runners are virtualized with a 7.93 GB Metal cap, so they can prove the dtype and API behaviour, which is what section 1 rests on, but not the memory behaviour. |
|
Follow-up on the reachability of the
It is reachable one version back. On {torch 2.4.1, diffusers 0.35.1}, which is the diffusers floor Either way the fix is confirmed on real hardware rather than argued: with 785ef2a on the branch, a macos-14 and a macos-15 runner both running torch 2.4.1 now report where before the fix the same job on the same runner reported Two smaller notes from the same sweep, neither worth a change:
|
An Apple Silicon host whose MLX stack is unavailable reports DeviceType.CPU, but diffusion and video still run on Metal, so clear_gpu_cache() fell through every branch and left torch's MPS reservations held. Pull the clear into a helper and call it on that path as well as under MLX.
torch.Generator(device="mps") is not the way to reproduce a seed on Metal, and routing through the CPU generator also keeps the new Apple path off whatever that constructor does on the older torch releases install.sh leaves in place. The pipelines move the noise to the device themselves.
|
Picked this up and pushed three things to the branch. Merged main inThe branch was 83 commits behind, and the last CI run was against a base where main itself was red, so every red check on it was uninformative. Merged main in rather than rebasing, so the SHAs cited in the review threads stay valid. No conflicts. Its own footprint against current main is unchanged: 14 files, 817 insertions. The MPS allocator itemRight, and half of it was still open. So the host class this PR newly enables was the one falling through every branch of The sidebar itemAgreed and already fixed. The MPS generator itemThe availability premise does not hold. This PR documents its own floor as torch 2.4 ( There is still a good reason to make the change, just a different one: Metal does not reproduce a seed through a device generator, and the diffusers guidance for MPS is to pass a CPU generator and let the pipeline move the noise. The modular path already does exactly that. So Commits
Both on top of |
|
Test evidence for the two commits above, plus a second main merge. BackendHead against the exact main this branch merged ( FAILED and ERROR line sets are identical. The +34 passed are this branch's own tests. So nothing here regresses, and the 15/15 that fail are pre-existing on main. Frontend
Second main mergeMerged main again to pick up #8281, which raised the Backend CI job timeout from 15 to 30 minutes. The suite runs 14 to 15 minutes, so the Python matrix on this branch was a coin flip between finishing and being cancelled, and |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0d6de481d1
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if getattr(module, "double_precision", False): | ||
| module.double_precision = False |
There was a problem hiding this comment.
Convert MiniMax-H3 position IDs before moving them to Metal
If the MiniMax-H3 modular workflow gets past loading on MPS, its before-denoise block constructs position_ids as torch.float64 and then executes position_ids.to(device) before the transformer can cast them to float32. MPS rejects that transfer for the same lack of float64 support handled here, but force_float32_rope() only changes modules carrying a double_precision attribute and therefore cannot affect this pipeline-state tensor; the first generation deterministically fails. Patch the H3 block to cast before the MPS transfer, or exclude that pipeline from the newly exposed Metal path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The mechanism is right and the path is unreachable, so this is a rejection.
Accurate parts, source-verified against diffusers 0.40.0.dev0: modular_pipelines/minimax_h3/before_denoise.py:320 does build position_ids at torch.float64, line 444 does position_ids.to(device) with no cast in between, and force_float32_rope() only clears double_precision on modules, so it cannot reach a block-state tensor. Nothing here disputes any of that.
It never executes on Metal. The condition this item opens with, "if the MiniMax-H3 modular workflow gets past loading on MPS", is exactly what the neighbouring item on hardware.py:681 shows cannot happen: enable_auto_cpu_offload raises NotImplementedError for a device module without mem_get_info, and torch.mps has none. As of be0c472 validate_load_request refuses the modular pipeline outright when the resolved diffusion target is mps, so the before-denoise block is not reachable from an Apple host at any point. A cast added to it would be dead code on the only device that would need it, and it would be a change to shared pipeline-state handling made for a case that cannot occur.
If the modular workflow ever gets an MPS-compatible placement path, the float64 position_ids is the next thing that has to be handled, and this item is the right description of it. It is not a defect on this branch.
Not measured: no Apple Silicon hardware in this environment, so both halves are read from the diffusers and torch sources rather than run.
test_load_installs_the_pressure_gated_decoder_sync_on_mps forces device="mps", which also forces the unified-memory placement. That snapshot comes from the host's free RAM (snapshot_device_memory routes mps to _system_memory_mib), not from the torch.mps stub the test installs, so a busy runner refuses the 25 GB Wan2.2-TI2V-5B load before the hook is ever installed. Correct behaviour, and nothing to do with what the test asserts, but it made the case pass or fail on how loaded the machine was: the Python 3.11 job saw 14 GB free and failed while 3.10, 3.12 and 3.13 passed on the same commit. Pin the snapshot seam to a pool with room to spare. Reproduced by stubbing _system_memory_mib at 14 GB free: fails exactly as CI did without this, passes with it.
|
Pushed one test-only commit to this branch.
That refusal is correct and is what the PR wants on a small Mac; it just is not what this test asserts. The fix pins the snapshot seam to a pool with room to spare so the assertion no longer depends on how loaded the runner is. Confirmed by stubbing |
One conflict, both sides adding an import at the same line. Kept dataclasses from this branch and the single 'from pathlib import Path' that was already below it, rather than main's second copy of the same import.
|
Codex Review: Didn't find any major issues. You're on a roll. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
What
Enables video generation on Apple Silicon. The Video page previously reported "Video generation on macOS is coming soon." on every Mac; it now loads and generates through the same diffusers pipelines CUDA uses.
Why the gate was the only blocker
routes/video.pyandcore/inference/video.pycarry no capability check at all —video_capability()feeds/api/system/hardwareonly, which setsvideoSupported, which gates exactly one frontend branch. The backend already accepted a video load on a Mac; the UI simply never issued one.The pipelines are device-neutral.
core/inference/video.pycontains notorch.cuda, nodevice ==, and nobackend ==: it resolves through the same device target the image path uses, which already returns a working MPS device. Every CUDA-only option is already declined there by the target's capability flags — verified on an M3 Max before changing anything:supports_model_cpu_offload/supports_default_torch_compile/supports_pinned_transferFalsesnapshot_device_memory()unified_memory(the planner has had an Apple arm for as long as it has had a CUDA one)compile_eligible(...)Falseselect_attention_backend(auto/native/cudnn/flash/sage/xformers)None— diffusers default SDPA, for all sixte_quant_supported(fp8/fp8_dynamic/int8/nvfp4)False, for all fourWhat changed
fix(studio): run LTX-2 rotary embeddings in float32 on MetalLTX-2's rotary embeddings build
theta ** linspace(0, 1, n)in float64 and cast the result straight back to float32 on the next line. Metal implements no float64 and torch raises rather than demoting, so on an Apple GPU generation dies in the connectors before the first denoise step:Six sites share the pattern (two in the connectors, four in the transformer), all gating the intermediate on a
double_precisionattribute.DiffusionDeviceTargetgrowssupports_float64— a device capability, not a platform test — andforce_float32_ropeclears the flag once at load. A no-op wherever float64 works, so CUDA, XPU and CPU keep the upstream computation bit-for-bit.Precision was measured, not assumed: across the theta/dim combinations these models use the two paths differ by at most 6 float32 ULP (max relative 4.4e-07), against a value truncated to float32 on the next line.
feat(studio): enable video generation on Apple Siliconvideo_capability()grows an Apple Silicon arm admitted on a measured Metal device rather than the platform alone. Apple Silicon whose torch exposes no MPS device reportsmps_unavailable; one with no torch reportspytorch_not_installed; and one whose torch is installed but fails to import reportsdetection_failednaming the failed import, rather than being told to install the PyTorch it already has. (_has_torch()readsFalsefor both, anddetect_hardware()recordsmlx_unavailablefor an Apple host before the top-leveldetection_failedbranch can fire, so the arm has to separate them itself.) A failed hardware probe still reportsdetection_failedfirst, matching the export verdict.Intel Macs stay unsupported, and their message changes: "coming soon" described a platform with no path at all, which is no longer true of macOS. It now names what is actually missing, and deliberately does not offer a GPU as the fix — an Intel Mac can carry an AMD dGPU and it is still unusable here, because torch's only macOS backend is MPS and MPS needs Apple Silicon.
The UI stops treating the training verdict as the video verdict.
chat_onlyanswers whether a host can train, and both the sidebar row and the Video page borrowed it because, until now, no chat-only host could run diffusers either. That is no longer true of exactly one reason: an Apple Silicon host whose MLX stack is missing or broken is chat-only, and runs video on Metal regardless, since video never imports MLX. So the row's tooltip derivation moves intoconfig/hardware-verdict.tsas a purevideoNavHint()covering only the reasons that leave no video device at all, and the row is disabled exactly when that returns something.VideoPagelikewise dropscapabilitiesUnknownand gates on/api/system/hardwarealone, which settles detection before replying — otherwise the page spun for the length of an MLX reinstall that could not change its answer.fix(studio): bound Metal memory during video VAE decodeWith the two commits above, a Wan2.2 TI2V-5B clip at 121x704x1280 denoised to completion and was then SIGKILLed during VAE decode. No torch OOM was ever raised, so the failure surfaced only as a dead process.
Wan's VAE decodes one latent frame per call in a Python loop that never forces a commit. Metal cannot reuse a buffer until the work holding it has completed, so every call's intermediates stay resident: driver memory grew ~0.72 GiB per call against a 1.5 MB decoded frame, with RSS flat — nothing leaks in the Python sense. It reached 25.19 GiB by the end of tile 0 and 148.06 GiB at tile 7 of 28.
Two mechanisms that look like they should cover this do not:
clear_cache()runs per tile — 31 calls too late.PYTORCH_MPS_LOW_WATERMARK_RATIOis documented as a soft limit honoured by "committing command buffers more frequently (a.k.a, adaptive commit)", which is the mechanism wanted here, but set to a tenth of the recommended working set it left the peak unchanged at 25.20 GiB. The hard watermark does bound the decode, at 35% more wall clock, because it gets there through a full cache release rather than a wait — and set below the default low watermark of 1.4 it raisesinvalid low watermark ratio 1.4at the nextempty_cache(), not where it is set.A forward hook on the VAE decoder synchronises once allocation passes
DECODE_SYNC_FRACTION(0.85) of the device's recommended working set, so memory plateaus there instead of climbing. Synchronising waits only on work already enqueued, and below the threshold a decode pays just the memory read — 2.8 ms across 868 calls. The hook returnsNone, since annn.Moduleforward hook returning non-Nonereplaces the module's output. It fires per decoder call, which is per frame on Wan and per tile on the video VAEs that decode a whole tensor at once.Deliberately not in scope
video_supported: trueand relies on the memory planner and the load-time error. A macOS-only floor would make this path stricter than the one it mirrors, and would put a second memory policy beside the planner that already owns that decision.PYTORCH_MPS_HIGH_WATERMARK_RATIO=0.0. Already onmain, and measured not to be what drives the decode growth — the same run under torch's default watermark grew identically. Worth a separate look, though:MPSAllocator.hdocuments0.0as disabling the hard limit outright, "may cause system failure if system-wide OOM occurs"._encodehas the same loop shape, but image-to-video conditioning is a single frame, so there is no growth to bound.force_float32_ropeis wired into the video load only. Other families may hit the same float64 pattern on MPS; extending it belongs in a follow-up rather than widening this PR.Validation
Ran on an M3 Max (macOS 26.5.1, torch 2.10.0, diffusers 0.39.0).
Checked on output rather than exit status, since the known MPS failure mode is silent: decoded frames have mean 154-200, std 53-80, full 0-255 range, mean frame-to-frame delta 14.4, and visual inspection of frames 0, 6 and 12 shows a coherent, temporally stable clip. Not black, not noise, not frozen.
Test suites:
studio/backend129 passed,studio/frontend1,312 passed,npm run typecheckclean. Added coverage exercises the real MPS probe against a fake torch (previously every case stubbed it, so swappingmps.is_available()formps.is_built()passed the whole suite), asserts the loader reachesforce_float32_ropeunconditionally, and pins both detector states a broken torch can actually produce on an Apple host.python -m pytest studio/backend/tests/test_video_backend.py \ studio/backend/tests/test_video_capability.py \ studio/backend/tests/test_video_routes.py \ studio/backend/tests/test_video_families.py \ studio/backend/tests/test_video_gallery.py \ studio/backend/tests/test_diffusion_device.py -q # 229 passedEvery added test was mutation-checked: blanking
force_float32_ropefails 2, removing the flag from one MPS constructor fails 3. The demotion was also verified against the realLTX2RotaryPosEmbed1drather than the test fakes.The decode fix was measured on the same M3 Max, against the real VAE fed latents of the shape the transformer produces:
Eight mutations were checked and all caught: gate inverted; gate removed;
DECODE_SYNC_FRACTIONraised so it never fires; the budget made a fixed byte count instead of device-scaled; the hook returning non-None; the Metal-only guard dropped; the hook never registered; the call site removed.Risk
The float32 change and the decode sync are both inert off Metal, so CUDA and XPU behaviour is unchanged by construction. The verdict change is user-visible on macOS only. The largest residual risk is that Apple Silicon hosts too small for a given family now reach a load that fails on memory instead of being refused at the gate — which is the same behaviour a small CUDA card has today.
The decode gate is a threshold, so it carries the limits of one: it samples after each decoder call, so a call can overshoot between checks (measured 0.02 GiB tiled, 8.7 GiB untiled, where each call allocates far more), and
recommended_max_memory()is a performance recommendation rather than available memory whiledriver_allocated_memory()counts only this process — so another process can still drive the system into pressure. Both are bounded by the same choice: a lowerDECODE_SYNC_FRACTIONtrades resident memory for earlier synchronisation, and synchronising unconditionally holds the same decode at 4.90 GiB for no measurable wall-clock cost.