Skip to content

Studio: enable video generation on Apple Silicon - #8198

Merged
danielhanchen merged 17 commits into
unslothai:mainfrom
Lyxot:feat/studio-video-macos
Aug 10, 2026
Merged

danielhanchen merged 17 commits into
unslothai:mainfrom
Lyxot:feat/studio-video-macos

Conversation

@Lyxot

@Lyxot Lyxot commented Aug 8, 2026 •

Copy link
Copy Markdown
Collaborator

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.py and core/inference/video.py carry no capability check at all — video_capability() feeds /api/system/hardware only, which sets videoSupported, 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.py contains no torch.cuda, no device ==, and no backend ==: 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:

Knob Value on an MPS target
supports_model_cpu_offload / supports_default_torch_compile / supports_pinned_transfer False
snapshot_device_memory() unified_memory (the planner has had an Apple arm for as long as it has had a CUDA one)
compile_eligible(...) False
select_attention_backend(auto/native/cudnn/flash/sage/xformers) None — diffusers default SDPA, for all six
te_quant_supported(fp8/fp8_dynamic/int8/nvfp4) False, for all four

What changed

图片

fix(studio): run LTX-2 rotary embeddings in float32 on Metal

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 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), all gating the intermediate on a double_precision attribute. DiffusionDeviceTarget grows supports_float64 — a device capability, not a platform test — and force_float32_rope clears 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 Silicon

video_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 reports mps_unavailable; one with no torch reports pytorch_not_installed; and one whose torch is installed but fails to import reports detection_failed naming the failed import, rather than being told to install the PyTorch it already has. (_has_torch() reads False for both, and detect_hardware() records mlx_unavailable for an Apple host before the top-level detection_failed branch can fire, so the arm has to separate them itself.) A failed hardware probe still reports detection_failed first, 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_only answers 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 into config/hardware-verdict.ts as a pure videoNavHint() covering only the reasons that leave no video device at all, and the row is disabled exactly when that returns something. VideoPage likewise drops capabilitiesUnknown and gates on /api/system/hardware alone, 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 decode

With 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:

  • VAE tiling. The growth is within a tile, and clear_cache() runs per tile — 31 calls too late.
  • Torch's own watermarks. PYTORCH_MPS_LOW_WATERMARK_RATIO is 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 raises invalid low watermark ratio 1.4 at the next empty_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 returns None, since an nn.Module forward hook returning non-None replaces 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

  • Intel Macs. No MPS device; they stay unsupported.
  • A memory floor on the verdict. CUDA does not gate on VRAM — an 8 GB card reports video_supported: true and 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 on main, 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.h documents 0.0 as disabling the hard limit outright, "may cause system failure if system-wide OOM occurs".
  • The VAE encoder. _encode has the same loop shape, but image-to-video conditioning is a single frame, so there is no growth to bound.
  • The image path. force_float32_rope is 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).

Wan2.2-TI2V-5B-Diffusers, MPS, bf16
  load      52s   offload_policy=none  speed_mode=off  attention_backend=None
  generate  46s   13 frames @ 640x352, 6 steps -> 156853-byte H.264 MP4

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/backend 129 passed, studio/frontend 1,312 passed, npm run typecheck clean. Added coverage exercises the real MPS probe against a fake torch (previously every case stubbed it, so swapping mps.is_available() for mps.is_built() passed the whole suite), asserts the loader reaches force_float32_rope unconditionally, 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 passed

Every added test was mutation-checked: blanking force_float32_rope fails 2, removing the flag from one MPS constructor fails 3. The demotion was also verified against the real LTX2RotaryPosEmbed1d rather 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:

Run (Wan2.2 TI2V-5B, 121x704x1280, tiling on) Peak driver memory Time
before SIGKILL past 148 GiB —
after, gate at 0.85 91.72 GiB, 868 calls, 22 syncs 1174.2 s

Eight mutations were checked and all caught: gate inverted; gate removed; DECODE_SYNC_FRACTION raised 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 while driver_allocated_memory() counts only this process — so another process can still drive the system into pressure. Both are bounded by the same choice: a lower DECODE_SYNC_FRACTION trades resident memory for earlier synchronisation, and synchronising unconditionally holds the same decode at 4.90 GiB for no measurable wall-clock cost.

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.
@Lyxot
Lyxot force-pushed the feat/studio-video-macos branch from d0e1205 to 16eb6c4 Compare August 8, 2026 20:06
@Lyxot
Lyxot marked this pull request as ready for review August 8, 2026 20:07
@Lyxot
Lyxot requested a review from danielhanchen as a code owner August 8, 2026 20:07
@Lyxot

Lyxot commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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.
@Lyxot
Lyxot force-pushed the feat/studio-video-macos branch from 16eb6c4 to 6d342ea Compare August 8, 2026 22:45
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 6d342eae04

ℹ️ 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".

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.
@Lyxot
Lyxot force-pushed the feat/studio-video-macos branch from 3e64185 to 16b39cb Compare August 9, 2026 01:59
@Lyxot

Lyxot commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

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".

danielhanchen and others added 2 commits August 9, 2026 03:47
…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.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 9, 2026
@danielhanchen

Copy link
Copy Markdown
Member

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 blocker

Yes, as described.

  • core/inference/video.py contains no torch.cuda, no device == and no backend == (grep is empty at head). It resolves through resolve_diffusion_device_target() like the image path.
  • Every knob in the table declines on an MPS target. Checked against the shipped code with a synthetic MPS target: select_attention_backend returns None for all six of auto / native / cudnn / flash / sage / xformers; compile_eligible is False for both the dense and the GGUF call; dense_transformer_supported is False; te_quant_supported is False for fp8 / fp8_dynamic / int8 / nvfp4. The same CUDA target returns _native_cudnn, True, True, True respectively, so the flags are doing the declining rather than the calls being unreachable.
  • snapshot_device_memory()'s Apple arm is on main already and returns unified_memory. Confirmed live on a macos-15 runner: {'memory_kind': 'unified_memory', 'free_mib': 2962, 'total_mib': 7168}.

The float64 fix is correct and it is the only such site. On macos-15 / torch 2.10, torch.linspace(0.0, 1.0, 8, dtype=torch.float64, device="mps") raises exactly the quoted TypeError, and the real LTX2RotaryPosEmbed1d goes from that same TypeError before force_float32_rope to ok dtype=torch.float32 after it, on Metal. Across diffusers 0.39/0.40 the LTX-2 rope is the only unguarded float64 in the video path: transformer_wan.py:375 already picks its dtype off torch.backends.mps.is_available(), embeddings.py routes through maybe_adjust_dtype_for_device, and the flow-match and UniPC schedulers both carry an explicit "mps does not support float64" branch. Wan, HunyuanVideo-1.5 and the four video autoencoders have no float64 at all.

The precision claim checks out as stated. Against the shipped checkpoint config (rope_theta: 10000.0, rope_double_precision: true, in both connectors/config.json and transformer/config.json of Lightricks/LTX-2), the worst case over the dim/steps combinations these models use is 6 float32 ULP, 4.5e-07 relative. It only exceeds that at thetas these models do not use (8 ULP at theta 1e6).

2. One genuine bug, fixed in 785ef2a

install_decoder_sync() read torch.mps.recommended_max_memory() unguarded. That reading landed in torch 2.5: it is absent from torch/mps/__init__.py at v2.4.0 and present at v2.5.0, and an installed torch 2.4.1 confirms hasattr(torch.mps, "recommended_max_memory") is False.

torch 2.4 is inside the window this project keeps. install.sh sets TORCH_CONSTRAINT="torch>=2.4,<2.11.0" on macOS arm64 (raised to >=2.6 only for Python 3.13+), and _previous_torch_pin() deliberately keeps an existing venv's release when it is inside that window, so an older Mac install carrying torch 2.4.x stays there across updates.

Reproduced on a macos-14 runner with torch 2.4.1, on the same host, in the same process:

video_capability      = {'video_supported': True, ...}
install_decoder_sync  = RAISED AttributeError: module 'torch.mps' has no
                        attribute 'recommended_max_memory'

So the new capability arm advertises video and the load then dies inside install_decoder_sync, after the download, with no OOM to explain it.

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 it

Running the shipped planner against a unified-memory DeviceMemory gives, for a bf16 pipeline load at each family's default preset:

family DiT TE VAE runtime resident required
ltx-2 37.8 24.4 5.5 5.6 70.6 GB
wan2.2-ti2v-5b 10.0 11.4 2.8 7.7 32.2 GB
wan2.2-t2v-a14b 57.2 11.4 0.5 6.5 72.9 GB
hunyuanvideo-1.5 16.6 14.8 2.4 5.6 39.1 GB
hunyuanvideo-1.5-720p 16.6 14.8 2.4 7.7 41.2 GB

Against free - _reserve_mib(unified) = free - 20% of total, with free taken as 80% of RAM, nothing fits below 64 GB, and only wan2.2-ti2v-5b fits at 64 GB.

Two things follow that are worth naming explicitly.

GGUF barely helps on Metal, because the floor is not the DiT. For unsloth/Wan2.2-TI2V-5B-GGUF the transformer is the only component a quant replaces; the UMT5 encoder (11.4), the fp32 VAE (2.8), the frames-aware headroom (7.7) and the base overhead (2.0) stay. So Q8_0 is 28.2 GB and Q2_K is still 24.7 GB, a 23% cut off bf16 for a 3x smaller transformer. Same shape on LTX-2: Q8_0 is 57.7 GB because the Gemma3-12B encoder holds 24.4 GB, and te_quant_supported is False on MPS for every scheme, so the pre-cast encoder that makes this affordable on CUDA is unavailable here.

supports_model_cpu_offload = False is not what is costing anything. plan_diffusion_memory short-circuits on not can_offload or device_memory.is_unified, so flipping the flag changes no decision: the unified arm forces OFFLOAD_NONE on its own. As literal accounting the comment is right, a CPU tensor and an MPS buffer are the same DRAM. There is a second-order argument that CPU-resident weights are pageable while Metal buffers are not, which would make offload the difference between swapping and being killed, but I could not measure it without a Mac and am not asserting it.

What happens when it does not fit is the part I would look at next. It is not a graceful refusal. plan_diffusion_memory computes resident_required_mib and safe_device_budget_mib, and on the unified arm it never compares them, it just records "unified/system memory: CPU offload frees no device memory" and returns OFFLOAD_NONE. Nothing downstream refuses either. And because _mps_or_cpu_target() sets PYTORCH_MPS_HIGH_WATERMARK_RATIO=0.0, which MPSAllocator.h documents as disabling the hard limit outright, there is no torch OOM to catch, which is exactly why the failure in this PR's own third commit surfaced as a SIGKILL rather than an exception. On a 16 GB or 24 GB Mac every supported family is now one click from an OS kill of the whole Studio process, taking any concurrent chat session with it.

I am not asking for that here. It is pre-existing on main through the image path, it is a memory-policy decision that belongs to the planner rather than to a feature-enable PR, and the honest fix is a comparison plus an actionable error at load, not a floor on the verdict. But it is the one place I would spend the next change, and it is larger than the 6 ULP question.

4. No regressions

  • Backend suite: 71 failed / 18849 passed on main, 71 failed / 18877 passed on this branch, byte-identical failure set (diff of the sorted FAILED/ERROR lines is empty). Hub tests 304/304.
  • Frontend: npm test 1312/1312, npm run typecheck clean.
  • video_capability() across 25 host scenarios, [OS] x [device] x [torch state], run against main and this branch side by side: every Linux (x86 and aarch64), WSL and Windows (x86 and ARM64) case is identical in both video_supported and the reason, in all four torch states. Every change is on macOS, and the only Intel Mac change is the message.
  • Cross-platform CI on ubuntu-latest, macos-14, macos-15 and windows-latest: all green. The live probe confirms install_decoder_sync returns False and force_float32_rope demotes 0 modules on Linux and Windows, so both are inert off Metal by measurement, not only by construction.

Worth noting that nothing that existed before covered this: Mac Studio GGUF CI, Mac Studio UI + API + Update CI and Mac Studio Install Matrix CI all install with --no-torch, so no Mac job on main has ever imported torch, let alone touched MPS.

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.

@danielhanchen

Copy link
Copy Markdown
Member

Follow-up on the reachability of the recommended_max_memory bug, because I went looking for the exact window and it is narrower than "any torch 2.4" and worth stating precisely.

diffusers==0.39.0 does not import its video pipelines on torch 2.4 at all. WanPipeline, LTX2Pipeline and HunyuanVideo15Pipeline each raise at getattr(diffusers, fam.pipeline_class) with ValueError: infer_schema(func): Parameter q has unsupported type torch.Tensor, because torch 2.4's torch.library schema inference does not accept the PEP-604 X | None annotations on the flash-attention op. So on {torch 2.4, diffusers 0.39} the load dies before install_decoder_sync is ever called.

It is reachable one version back. On {torch 2.4.1, diffusers 0.35.1}, which is the diffusers floor video_families.py records for Wan ("diffusers >= 0.35, verified on 0.39"), from diffusers import WanPipeline imports cleanly, so a Wan2.2-TI2V-5B load runs the whole way to install_decoder_sync. Since neither torch nor diffusers is pinned for a macOS install, and install.sh deliberately preserves an existing torch release, that pairing is what an older Mac install upgrading into this feature would carry.

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

video_capability     = {'video_supported': True, ...}
install_decoder_sync = {'installed': True, 'output_shape': [2]}

where before the fix the same job on the same runner reported RAISED AttributeError: module 'torch.mps' has no attribute 'recommended_max_memory'.

Two smaller notes from the same sweep, neither worth a change:

  • On a Rosetta install (x86_64 Python on Apple Silicon) is_apple_silicon() is false, so the host takes the Intel Mac arm and is told "This Intel Mac has no Metal (MPS) device". The verdict is right, since torch's x86 macOS build has no MPS either way, but the sentence names the wrong machine.
  • GitHub's virtualized macOS runners report mps.is_available() == True and then fail every allocation against a 7.93 GB cap. That is a CI artefact rather than a user configuration, but it does mean is_available() alone can be true where Metal is unusable. The existing _mps_supports_bfloat16() probe already allocates for real and degrades to fp32, which is the behaviour you would want if a user ever hit it.

danielhanchen and others added 4 commits August 10, 2026 04:21
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.
@danielhanchen

Copy link
Copy Markdown
Member

Picked this up and pushed three things to the branch.

Merged main in

The 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 item

Right, and half of it was still open. clear_gpu_cache() now clears the MPS allocator under DeviceType.MLX, but the parenthetical in that review comment is the case that matters here: an Apple Silicon host whose MLX stack is unavailable reports DeviceType.CPU with reason mlx_unavailable, and this PR is precisely what makes video work on that host. diffusion_device says so itself at the fallthrough:

# MLX / CPU / else: diffusers uses MPS, so fall through to the torch probe (MPS over CPU).

So the host class this PR newly enables was the one falling through every branch of clear_gpu_cache and leaving torch's MPS reservations held. Pulled the clear into _clear_mps_cache() and call it from the MLX branch and from an is_apple_silicon() branch, with two tests: one that the clear fires when the device reads CPU on Apple Silicon, one that it does not on a non-Apple CPU host.

The sidebar item

Agreed and already fixed. videoNavHint keys off intel_mac and no_gpu only, so mlx_unavailable no longer blacks out the Video row while MLX is being repaired, and the host reaches VideoPage to get the backend's own video verdict. Moving the derivation out of the component into hardware-verdict.ts also makes it testable, which is the right call.

The MPS generator item

The availability premise does not hold. This PR documents its own floor as torch 2.4 (install.sh keeps an existing venv's torch as far back as 2.4, which is why the decode-sync threshold is written to survive a missing recommended_max_memory), and MPS generators have been constructible since well before that.

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 generate() now picks the CPU generator when the device is mps as well as when the family is modular, with a parametrized test covering mps -> cpu and cuda -> cuda. CUDA seeds are untouched, so nothing existing changes behaviour.

Commits

  • 25436e0c0 Clear the MPS allocator when Apple Silicon reports CPU
  • 65cc60e40 Seed Metal generations from a CPU generator

Both on top of 44941a2b2, the main merge. The one thing none of this can establish is the end to end run on real hardware, since I have no Apple Silicon box here; the three items above are all reasoned from the code and covered by tests.

@danielhanchen

Copy link
Copy Markdown
Member

Test evidence for the two commits above, plus a second main merge.

Backend

Head against the exact main this branch merged (a1fc4d42f), same CUDA_VISIBLE_DEVICES=2,3 on both, since a couple of tests read the mask and change their counts:

BASE  15 failed, 20346 passed, 87 skipped, 15 errors   (19m35s)
HEAD  15 failed, 20380 passed, 87 skipped, 15 errors   (19m36s)

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

npm test 1494 pass / 0 fail, npm run typecheck clean.

Second main merge

Merged 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 gh pr checks reports a cancelled job as fail exactly like a real failure. With the bump in place the matrix result is now meaningful. Also merged the pre-commit.ci formatting commit rather than force-pushing over it.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +74 to +75
if getattr(module, "double_precision", False):
module.double_precision = False

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

@danielhanchen danielhanchen Aug 10, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@danielhanchen

Copy link
Copy Markdown
Member

Pushed one test-only commit to this branch.

test_load_installs_the_pressure_gated_decoder_sync_on_mps failed on the Python 3.11 job while 3.10, 3.12 and 3.13 passed on the same commit. Not flaky ordering: 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 the test installs. The 3.11 runner had 14 GB free, so the 25 GB Wan2.2-TI2V-5B load was refused before the decoder hook was ever installed:

RuntimeError: 'wan2.2-ti2v-5b' needs about 25 GB of memory for its weights, but only
about 11 GB is usable on this device (of the 14 GB currently free, ...)

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 _system_memory_mib at 14 GB free locally: the test fails exactly as CI did without the change and passes with it. Full test_video_backend.py is 177 passed.

danielhanchen and others added 5 commits August 10, 2026 07:57
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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 10, 2026
@unslothai unslothai deleted a comment from Lyxot Aug 10, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 10, 2026
@unslothai unslothai deleted a comment from Lyxot Aug 10, 2026
@unslothai unslothai deleted a comment from Lyxot Aug 10, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 0e8948da9f

ℹ️ 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".

@danielhanchen
danielhanchen merged commit ef74942 into unslothai:main Aug 10, 2026
49 of 55 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants