Skip to content

Install torch 2.13 on new Apple Silicon homes for the fused MPS attention kernel - #18428

Merged
danielhanchen merged 3 commits into
mainfrom
mac-torch-ceiling
Nov 20, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
mac-torch-ceiling

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Problem

install.sh caps torch below 2.12 on every route except cu130, so Apple Silicon installs get torch 2.11. On MPS, only torch 2.13 and later have a fused (prefill) SDPA kernel. Below that, every attention call materialises the full score matrix, which:

  • costs memory that grows with tokens squared;
  • is the cause of the wrong values at large attention sizes in pytorch#179352.

Studio guards only Qwen-Image-2.1 against it.

The mflux pin (mflux==0.22.0, installed with --no-deps) also declares torch>=2.13.0, so today every Mac runs mflux below its declared floor.

Change

New macOS arm64 installs take torch 2.13 / torchvision 0.28 / torchaudio 2.11.x from the default cpu index when all of these hold:

  • macOS 14 or later (torch 2.13's macOS wheels are macosx_14_0);
  • a GIL-enabled Python 3.10 to 3.14;
  • the default cpu index;
  • the released unsloth on PyPI admits torch 2.13, as on the cu130 route.

Existing homes keep their resident 2.4 to 2.14 torch unless UNSLOTH_TORCH_UPGRADE=1. Linux, Windows, CUDA, ROCm, XPU, the CPU route and the generic ceiling are unchanged. torch 2.15 is not used, because it has no cp310 macOS wheel and no torchvision 0.30.

Tests

  • tests/sh/test_macos_torch213_route.sh: 71 checks that replay the route decision. Fails on main, passes here.
  • tests/python/test_macos_torch213_pins.py: 5 tests on the pinned trio and the torchcodec mapping.
  • studio/backend/tests/test_mps_attention_families.py (skipped without MPS): MPS attention against a CPU fp64 reference at each image family's head shape, in fp32 / fp16 / bf16, plus a mask case. It records whether the prefill kernel engaged.
  • Existing torch-related shell suites pass (cu130 route 104, test_get_torch_index_url 109, test_previous_torch_pin 50 and the rest), as do the Python install suites (170 + 119 + 127). shellcheck reports the same warnings as main.

macOS 15 runner (GitHub Apple Silicon, main vs this branch)

Fresh-home ./install.sh --local:

arm Python torch / torchvision / torchaudio torchcodec MPS
main 3.10 2.11.0 / 0.26.0 / 2.11.1 not installed True
main 3.13 2.11.0 / 0.26.0 / 2.11.1 0.11.1, fails to load its FFmpeg libraries True
this PR 3.10 2.13.0 / 0.28.0 / 2.11.1 not installed True
this PR 3.13 2.13.0 / 0.28.0 / 2.11.1 0.17.0, imports True

MPS attention against a CPU fp64 reference, tests/test_mps_attention_families.py:

  • Below the threshold: at each family's head shape at 256 and 512 px, in fp32 / fp16 / bf16, both torch versions match. Cosine is at least 0.99999.
  • Just past Studio's measured threshold (about 2^29 score elements per call, bf16), the two versions split:
family torch 2.11 torch 2.13
z-image cos 0.000 cos 0.999992
flux2-klein-4b cos 0.000 cos 0.999992
qwen-image-2.1 cos 0.000 cos 0.999992
sd3.5-large cos 0.000 cos 0.999995
  • Engagement and memory: torch 2.13 takes the fused prefill kernel on every call. Memory growth is 1024 MiB on 2.13, against 2084 to 6336 MiB on 2.11.
  • A larger call: at 2^32.14 score elements (Qwen-Image-2.1), torch 2.13 still matches (0.999992).
  • Totals: torch 2.13 gives 89 passed. torch 2.11 gives 84 passed, 1 skipped and the 4 failures in the table above.

So on torch 2.11 the attention output past that size is wrong, not only slower, for every family tested. Only Qwen-Image-2.1 has a guard today. Existing Mac homes stay on their torch unless UNSLOTH_TORCH_UPGRADE=1, so a follow-up should widen the guard to every family on torch below 2.13.

These are GitHub's virtual Apple Silicon runners: they prove installs and correctness, not speed on real Macs.

…tion kernel

New macOS arm64 installs on macOS 14+ with a GIL-enabled Python 3.10 - 3.14 take
torch 2.13 / torchvision 0.28 / torchaudio 2.11 from the cpu index, the first torch
whose MPS SDPA runs a fused prefill kernel instead of materialising the score
matrix. Existing homes keep a resident 2.4 - 2.14 release unless UNSLOTH_TORCH_UPGRADE=1,
and the route needs the PyPI unsloth release to admit torch 2.13, as on cu130.
torch 2.15 is not used: it has no cp310 macOS wheel and no matching torchvision.

Also adds an MPS attention parity test at each image family's head shape against
a CPU reference, recording whether the prefill kernel engaged.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-20T05:14:37.703328Z 231bff4 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-19T07:13:33.049413Z
We couldn’t complete this review. Comment @codex review to try again.
71cbf8d PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 71cbf8dddc

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

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 231bff4498

ℹ️ 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 a5e941b into main Nov 20, 2026
@danielhanchen
danielhanchen deleted the mac-torch-ceiling branch November 20, 2026 19:29
danielhanchen added a commit that referenced this pull request Nov 20, 2026
…18659)

## Summary

`unsloth studio update` re-resolves `unsloth` and `unsloth-zoo` with
dependencies. On Linux and Windows x64, `_FreezeNewTorchForCoreUpdate`
pins the resident torch, torchvision and torchaudio through
`UV_OVERRIDE` while that happens, but only for torch >= 2.13. macOS had
no freeze.

Apple Silicon is moving to torch 2.13 for new installs only (#18428).
Existing installs keep their torch unless the user runs a manual repair,
which sets `UNSLOTH_TORCH_UPGRADE=1` through install.sh. Without a
freeze, a released unsloth with a torch ceiling (2026.9.11 declared
`torch<2.13.0`) could move a 2.13 Mac install back to 2.12 on `studio
update`. A torch floor could also move a 2.11 install up.

## Change

- `studio/install_python_stack.py`: on Apple Silicon (`darwin` +
`arm64`), `_FreezeNewTorchForCoreUpdate` now freezes every resident
plain `X.Y.Z` torch release, not only >= 2.13. install.sh already
freezes the trio this way for every with-deps unsloth install, on every
OS. The bundled `overrides-darwin-arm64.txt` is folded into the frozen
file, minus any torch lines, so the MLX transformers / anyio /
huggingface_hub overrides still apply.
- Linux, Windows x64, Windows on ARM and Intel macOS behave exactly as
before. The predicate for those hosts is unchanged, and an absent or
non-release torch still returns early.
- While the freeze is active, a uv failure on Apple Silicon now stops
instead of falling back to pip. pip ignores `UV_OVERRIDE` and would
honour the released cap. This is the same behaviour Linux already has
under the freeze.

## Tests

New file: `studio/backend/tests/test_macos_core_update_torch_freeze.py`,
CPU only.

- Apple Silicon at 2.11.0 / 2.12.1 / 2.13.0 / 2.14.0: the trio is
pinned, the MLX overrides are folded in, and `UV_OVERRIDE` is restored
afterwards.
- An unset `UV_OVERRIDE` is restored to unset.
- A uv failure under the freeze never runs pip.
- These hosts are not frozen: Intel macOS, Apple Silicon without a
release torch, Linux aarch64 at 2.12.1, Linux arm64 at 2.11.0, Windows
arm64 at 2.12.1.

Base (main) vs head: 6 tests fail on main and pass on the branch. The 6
host-unchanged cases pass on both. No head test fails.

Across all 75 test files that import `install_python_stack` (8.5k
tests), the head's failing test IDs are a subset of main's. The failures
are pre-existing and come from this host's environment. They are
identical apart from one ROCm spoof test that failed only on the main
arm.

## Not covered

- No real Apple Silicon run. The uv override semantics are the same ones
the Linux freeze and install.sh rely on, but they were not exercised on
a Mac here.
danielhanchen added a commit that referenced this pull request Nov 22, 2026
…amily on Apple Silicon (#18783)

Below torch 2.13, every MPS `scaled_dot_product_attention` call runs on
the MPSGraph path, which builds the full score matrix. Past about 0.9 *
2^29 score elements per call (macOS 15), that path returns wrong values:
cosine 0.000 against an fp64 reference (pytorch#179352). #18428 moved
new Apple Silicon installs to torch 2.13, whose prefill kernel never
builds the scores. Existing homes keep their torch unless the user runs
a repair with `UNSLOTH_TORCH_UPGRADE=1`, and only Qwen-Image-2.1 had a
bound of its own. A single 1024 px FLUX call (24 heads x 4608 tokens,
2^28.92 elements) is right at that edge. Z-Image, FLUX.2 klein, SD3.5
and Qwen-Image go past it at the resolutions Studio offers.

## Change

- New `core/_mps_sdpa_guard.py`. On Apple Silicon with MPS it wraps
`torch.nn.functional.scaled_dot_product_attention`. An MPS call that has
more than 2^28 score elements (the bound
`diffusion_qwenimage21_math.MPS_SCORE_ELEMENTS` already uses) and that
the prefill kernel would not take (`mps_prefill_attention`) runs in
query-row chunks, which are then concatenated.
- Every query row is independent, so the result is the same as one call.
- Masks whose query axis is the full length are sliced with the rows.
`is_causal` becomes the matching top-left-aligned bool mask for each
chunk.
  - `scale`, `dropout_p` and `enable_gqa` are passed through.
- Calls under the cap, calls the prefill kernel serves (torch 2.13+) and
all non-MPS calls go to SDPA unchanged.
  - `UNSLOTH_MPS_ATTENTION_GUARD=0` turns it off.
- `diffusion_attention._apply_attention_backend_impl` installs it for
MPS image and video loads. The training worker does not need it: its
Apple Silicon fallback without a usable MLX stack runs on CPU tensors,
where the guard never splits. It is idempotent and a no-op off macOS.

diffusers' native backend, its SDPA processors and transformers all look
up the function on every call, so this covers every family.
Qwen-Image-2.1 keeps its own bounded processor (segmented prefill,
cached decode). Its calls are already under the cap, so they pass
straight through.

## Tests

- `tests/test_mps_attention_guard_on_load.py` (CPU): an MPS load wraps
SDPA once, the wrapped function stays bit-identical off MPS, and CPU /
CUDA loads keep the stock function. Fails on main, passes here.
- `tests/test_mps_large_attention_guard.py` (CPU, with CPU tensors
standing in for MPS and a small cap), 25 tests:
- The split matches one fp64 call for bool and float masks of shapes
`[B,H,Sq,Sk]`, `[B,1,Sq,Sk]`, `[1,1,1,Sk]`, `[B,1,1,Sk]`, `[Sq,Sk]` and
`[1,Sk]`.
- It also matches for `is_causal` with Sq = Sk, Sq > Sk and Sq < Sk, for
GQA with a custom scale, for 3-D inputs, and through autograd.
  - Calls under the cap, prefill calls and off-MPS calls are untouched.
  - The install gating works.
- Mutation check: dropping the mask slicing fails 6 tests, and dropping
the causal mask fails 3.
- `tests/test_mps_attention_families.py`:
`test_the_guard_fixes_the_studio_measured_threshold` runs the same
past-threshold cells as `test_past_the_studio_measured_threshold`, with
the guard installed. It asserts that the guard split the call on torch <
2.13 and left it alone on 2.13+.
- `test_differential.py`: DISCRIMINATING, head_fail=0.
- `tests/test_diffusion_attention*.py`,
`tests/test_rocm_windows_wide_head_sdpa.py` and the new files: 557
passed, 2 skipped on CPU.

### macOS 15 runner (GitHub Apple Silicon, main vs this branch, same
job)

Past-threshold cells (2^29.05 score elements, bf16, worst cosine against
fp64 over 4 heads x 192 rows; growth is the MPS driver allocation during
the call):

| family | torch 2.11 main | torch 2.11 this PR | torch 2.13 main |
torch 2.13 this PR |
|---|---|---|---|---|
| z-image | cos 0.000000, 2436 MiB | cos 0.999999, 204 MiB | cos
0.999992, 1024 MiB | cos 0.999992, 1024 MiB |
| flux2-klein-4b | cos 0.000000, 2084 MiB | cos 0.999999, 1032 MiB | cos
0.999992, 1024 MiB | cos 0.999992, 1024 MiB |
| qwen-image-2.1 | cos 0.000000, 2090 MiB | cos 0.999999, 1024 MiB | cos
0.999992, 1024 MiB | cos 0.999992, 1024 MiB |
| sd3.5-large | cos 0.000000, 2078 MiB | cos 0.999999, 1032 MiB | cos
0.999995, 1024 MiB | cos 0.999995, 1024 MiB |

- On torch 2.11, the guard split each of these calls once
(`chunked_calls=1`). On torch 2.13 it split none (`chunked_calls=0`),
because the prefill kernel takes them.
- The head selection was 79 passed on both torch versions: the
small-size cells for 8 families x 2 sizes x 3 dtypes, the key-padding
mask cell, the 25 guard tests and the guarded large cells.
- On main, torch 2.11 failed the 4 past-threshold cells, and torch 2.13
passed them.

## Not proven here

- These are GitHub's virtual Apple Silicon runners. They prove
correctness, not speed on real Macs. Chunking can add some per-call
overhead on torch 2.11, and that was not timed.
- No full image render on torch 2.11 was compared before and after. The
proof is the attention call at each family's shape.
- macOS 14 and torch versions between 2.11 and 2.13 (2.12) did not run.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant