Skip to content

Studio: int8 ConvRot Qwen-Image-2.1 text encoder on Apple Silicon, and release text encoders during denoise on unified memory - #13026

Merged
danielhanchen merged 5 commits into
mainfrom
studio/unified-te-release
Oct 8, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
studio/unified-te-release

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

For #11792. Not run on a Mac yet, so this does not close the issue on its own (see Not covered).

Problem

On a 48 GB M5 Max, Studio refuses unsloth/Qwen-Image-2.1-GGUF Q4_K_M ("needs about 24 GB ... only about 17 GB is usable"), and with UNSLOTH_DIFFUSION_ALLOW_OVERSIZED_LOAD=1 it loads but swaps. Two things add up:

  • The text encoder is bf16 on Apple Silicon. Qwen-Image-2.1 picks the hosted int8 ConvRot Qwen3-VL-8B encoder by default, but te_prequant_sources only admits a pre-cast encoder where fp8 runs (CUDA). On MPS the load falls back to the dense 17.5 GB encoder next to a 4.2 GB GGUF denoiser: 22.4 GB of weights. On unified memory the load-time check reserves 20% of total RAM for the OS, so 27 GB free leaves about 17.4 GB of budget, and 22.4 GB plus overhead is refused.
  • The encoder stays resident through the whole render. It runs once per prompt, before step 0, but nothing releases it, so it sits next to the denoise activations and the VAE decode. On unified memory there is no other pool to offload to.

Change

1. The int8 ConvRot encoder on Apple Silicon (diffusion_te_prequant.py)

  • The int8 ConvRot encoder is plain tensors: int8 codes, fp32 row scales, and a forward that is a Hadamard matmul plus F.linear on a per-call dequantised view. It needs no torchao, no fp8 dtype and no CUDA kernel.
  • te_prequant_sources now admits it on an MPS target. The fp8 fallback names are dropped there, since fp8 cannot run on MPS, and the fp8 retry in _te_prequant_pipe_kwargs is gated the same way.
  • On that path the plan prices the encoder at 0.56 of the dense size: the hosted file is 9,349,769,248 bytes against 17,534,339,488 dense, a ratio of 0.533. A cached file is priced exactly, as before.
  • CUDA, ROCm and CPU go through exactly the same gates as before.

For the numbers in the report (48 GB total, 27 GB free), the weights go from 22.4 GB to 14.2 GB, which is under the 17.4 GB budget. A genuinely oversized load, such as the dense bf16 transformer with the same encoder, is still refused.

2. Release the text encoders during denoise on unified memory (new diffusion_te_release.py)

  • When a load is committed on unified memory and the planned resident set does not fit the safe budget, Studio installs a releaser on the pipeline's text encoders. The resident set is every weight, plus the generation headroom, plus the base overhead.
  • When the denoise loop starts, the encoders' large tensors are freed.
    • Every parameter and persistent buffer of 1 MB or more is freed. Device and dtype are kept, so code that reads them before encoding still works.
    • The first release writes those tensors to a local snapshot under Studio's cache, in 512 MB shards, once per load. Later releases reuse it.
  • A forward pre-hook on every module that owns a released tensor reloads the snapshot before that module runs again. The reload is bit-exact and needs no network.
  • Studio's prompt cache already answers a repeated prompt without running the encoders, so the same prompt with a new seed never reloads.
  • Auto engages only on unified memory, and only when that set does not fit. UNSLOTH_DIFFUSION_RELEASE_TEXT_ENCODER=1 forces it on and =0 forces it off.
  • The releaser stays off and the encoders stay resident in these cases:
    • an encoder is under an offload hook;
    • an encoder holds a non-plain tensor (torchao);
    • there is not enough free disk for the snapshot.
  • The snapshot is deleted on unload, and a crashed backend's snapshot is swept on the next release.

The load-time check itself is unchanged. The load still materialises every weight at once, so the release cannot lower what the load needs, only what each render holds afterwards.

Results

One B200, Studio's DiffusionBackend with unsloth/Qwen-Image-2.1-GGUF Q4_K_M, 1024x1024, 20 steps, guidance 4, speed mode off. The release is forced with UNSLOTH_DIFFUSION_RELEASE_TEXT_ENCODER=1, since this host is discrete VRAM; on a Mac it engages automatically. Three generations per arm: prompt A seed 42, prompt A seed 43 (prompt cache, no encoder run), then prompt B seed 42 (the encoder runs again). Peak is torch's peak allocation for that generation.

int8 ConvRot encoder (the default this PR brings to Apple Silicon):

Arm gen1 peak gen2 peak gen3 peak Held between renders gen1 / gen2 / gen3 s
main 19.83 GiB 19.83 GiB 19.84 GiB 13.26 GiB 13.05 / 10.48 / 8.28
this PR, release off 19.83 GiB 19.83 GiB 19.84 GiB 13.26 GiB 9.21 / 7.57 / 8.67
this PR, release on 13.36 GiB 11.13 GiB 13.37 GiB 4.56 GiB 14.97 / 7.62 / 9.73

bf16 encoder (text_encoder_quant=none, today's Apple Silicon default):

Arm gen1 peak gen2 peak gen3 peak Held between renders gen1 / gen2 / gen3 s
main 26.30 GiB 26.30 GiB 26.30 GiB 19.72 GiB 9.88 / 7.41 / 7.63
this PR, release on 19.73 GiB 11.13 GiB 19.74 GiB 4.55 GiB 22.02 / 7.26 / 10.82
  • Every arm renders pixel-identical images to main for the same prompt and seed (pixel md5 equal for all three generations, with both encoders). The reload is exact.
  • Release on cuts the peak of a render by 6.5 GiB, the encoder share. A repeated prompt never loads the encoder at all (11.1 GiB). Between renders only the denoiser and the VAE stay resident (4.6 GiB instead of 13.3 or 19.7).
  • Cost:
    • The first render writes the snapshot once: about 6 s for the 9.4 GB int8 encoder and 12 s for the 17.5 GB bf16 one on this host.
    • A new prompt then reloads it: about 1 s for int8 and 3 s for bf16.
    • Denoise speed is unchanged.
    • These are single runs; gen1 also includes first-render warmup in every arm.

Testing

  • tests/test_diffusion_te_release.py (20 tests):
    • The MPS source and budget: the int8 file with no fp8 names; fp8 and CPU take nothing; CUDA keeps its fallback and its 0.65 scale.
    • The refusal with the report's numbers: refused with the bf16 encoder, accepted with the int8 encoder, still refused when genuinely oversized, discrete VRAM untouched.
    • When the release engages: unified and oversized, fits, discrete, and the env forcing it either way.
    • Release and reload on the runner's own accelerator (MPS on Apple Silicon runners, else CUDA, else CPU):
      • bit-exact output;
      • device and dtype kept;
      • tied weights;
      • snapshot reuse;
      • a submodule called directly;
      • snapshot cleanup;
      • refusal under an offload hook or a full disk.
    • The int8 ConvRot projection running on the runner's accelerator.
    • The tiny QwenImage21Pipeline (hf-internal-testing/tiny-qwenimage21-pipe) rendering identical images with the release on, through the real progress_bar denoise hook. That test skips only when the installed diffusers has no QwenImage21Pipeline.
  • 14 related backend suites (diffusion memory, precision, prompt cache, te prequant, int8 ConvRot, unified memory, backend) on base and head: 1194 passed on both, and the same single test fails on both (test_video_h3_te_quant.py::test_the_read_layer_matches_the_diffusers_pipeline, which already fails on main on this host).

Not covered

  • No run on a real Mac. The Apple Silicon numbers are planner arithmetic plus the CUDA run above, so the macOS process footprint and swap behaviour with this change are not measured. The release tests do run on MPS on an Apple Silicon runner.
  • An explicitly requested text_encoder_quant=int8 on MPS is still refused by the pre-load check, as before. Only the default (auto) pick takes the int8 encoder there.
  • The load itself still holds every weight at once, so a Mac with less free memory than the full weight set is still refused at load. The release only lowers what each render holds afterwards.
  • The snapshot costs disk equal to the encoder size while the model is loaded.
  • Video families are untouched.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-08T14:04:39.186616Z 055b87f Manual request
🔒 Security Review ⚠️ Failed 2026-10-08T08:45:53.667832Z ae52c4e 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.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
🔒 Security Review 🔄 Running since 2026-10-08T08:45:51.007661Z ae52c4e 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 added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 8, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 8, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 8, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: 055b87f7a9

ℹ️ 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 added a commit to Imagineer99/unsloth that referenced this pull request Oct 8, 2026
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Oct 8, 2026
@danielhanchen
danielhanchen merged commit 97b416c into main Oct 8, 2026
@danielhanchen
danielhanchen deleted the studio/unified-te-release branch October 8, 2026 15:48
danielhanchen added a commit to LeoBorcherding/unsloth that referenced this pull request Oct 11, 2026
danielhanchen added a commit that referenced this pull request Oct 20, 2026
…apacity fix for its pre-download check (#14379)

Refs #14267

On Apple Silicon and other unified-memory devices, Studio refuses a
diffusion load whose weights it estimates will not fit. The only way
past that refusal was the server env var
`UNSLOTH_DIFFUSION_ALLOW_OVERSIZED_LOAD=1`, which a Desktop install
launched from Finder or the Dock cannot set. This PR adds a per-load
override and a persistent setting, with a confirmation step. It also
fixes one real sizing bug found while auditing the reported numbers.

## Where the reported numbers come from

The refusal in #14267 reads "needs about 56 GB ... only about 51 GB is
usable (after reserving room for the operating system)". It has no
"currently free" clause, so it comes from the pre-download verdict (Hub
metadata, judged at capacity), not the in-load check. The numbers match
the bf16 `Qwen/Qwen-Image` pipeline (`Qwen-Image-2512` has the same
sizes) on a 64 GiB unified pool:

| Term | MiB |
| --- | --- |
| transformer (40,861,227,138 bytes) | 38,968 |
| text encoder, Qwen2.5-VL-7B (16,584,475,660 bytes) | 15,816 |
| VAE | 242 |
| flat base overhead | 2,048 |
| **required** | **57,074 (56 GB)** |
| 64 GiB minus the 20% unified reserve | **52,429 (51 GB)** |

### What is not over-counted

- **Weights are counted once.** The bf16 shards are what lands resident.
- **The text encoder is needed at load.** Releasing it after encoding
(#13026) frees about 15 GB during denoise. The pipeline still
materialises every weight before the first encode, so the load peak
includes it.
- **An explicit int8 on MPS is built from bf16.** The transformer is
quantized in place after a bf16 build, so the build peak is still bf16.
- **Quantized parts are sized as stored.** A GGUF transformer is sized
at its file size times 1.05, not unpacked. A hosted pre-cast encoder
replaces the dense encoder shards in the declared total, rather than
adding to them.
- **MPS gets the bf16 encoder.** MPS has no fp8 storage, and
Qwen-Image's hosted encoder is fp8 only.

So 56 GB is an accurate estimate for that pick. This PR keeps the
refusal as the default.

### Reserve, compared with ComfyUI and Studio's own allocator cap

| | Weights ceiling on 64 GiB |
| --- | --- |
| This refusal: total minus 20%, against weights plus 2 GiB overhead |
52,429 MiB |
| ComfyUI `maximum_vram_for_weights`: 0.88 x total minus 1.2 GiB |
56,443 MiB |
| Studio's MPS allocator cap: total minus max(1.5 GiB, 10%) | 58,982 MiB
|

On MPS, ComfyUI runs in `VRAMState.SHARED`. It never refuses a load;
that ceiling only chooses fp8 storage over bf16. The bf16 Qwen-Image
load at 57,074 MiB falls between this refusal and the allocator cap.
That is the case an explicit "Load anyway" is for, and the per-load
override keeps the allocator cap (see below). This PR does not loosen
the default reserve without a measurement on a Mac.

### The bug that was fixed

The pre-download verdict is meant to judge capacity, so that a model
loaded right now does not make a valid swap look too large. On MPS,
`snapshot_device_memory` chooses between the RAM view and Metal's
working-set view based on what is free right now. The pre-download path
kept that choice and only then replaced the free reading with capacity.
The same pick on the same 64 GB Mac was therefore judged against 51 GB
when idle, and against 41 GB (85% of the 48 GiB working set) whenever
less than the working set was free. `unified_capacity_memory` now
re-reads RAM at capacity, the floor the snapshot already guarantees. A
load past RAM capacity is still refused.

### Smaller hosted variants

When the dense companions fit, the refusal now says how much room a
quantized main model has. For the Qwen-Image case: "Its text encoders
and VAE need about 18 GB, which leaves room for a main model of up to
about 34 GB: use a lower GGUF quant ...". Every
`unsloth/Qwen-Image-2512-GGUF` quant up to Q8_0 (21.8 GB) fits that
room. The pick is never changed silently.

## Changes

### Backend

- `allow_oversized_load` (default false) on `DiffusionLoadRequest`,
which is also the `/images/download-plan` body, and on
`VideoLoadRequest`.
- The loaders scope it with a context variable over the load's worker
thread, so it is honoured exactly like the env var for that load only.
The plan route hands it to its worker the same way.
  - The env var keeps working.
- The native sd.cpp and MLX engines accept the field for interface
parity.
- The refusal raises `UnifiedMemoryShortfallError`, a `RuntimeError`
subclass, so existing handlers still catch it.
- Its stable code `unified-memory-load` is returned as `error_code` on
image and video load-progress, and as `incompatible_code` on the
download plan.
- An override that actually goes past the estimate is logged as a
warning naming its source (`allow_oversized_load` or the env var). It is
never silent.
- The env var also lifts the MPS allocator cap; the per-load flag does
not. That cap is process-wide and set once when the device is resolved.
Keeping it means an over-commit past RAM minus its reserve fails with an
MPS out-of-memory error instead of the OS ending the process.
- The refusal text now leads with the in-app remedy: "To try anyway,
choose Load anyway, or turn on 'Allow oversized model loads' in Settings
> System > Model memory (API callers can send allow_oversized_load;
server installs can set UNSLOTH_DIFFUSION_ALLOW_OVERSIZED_LOAD=1)."

### Frontend

- A new **Allow oversized model loads** switch in Settings > System >
Model memory.
- It is off by default and stored locally, following the pattern of the
existing "Allow oversized generations" switch.
- When on, every image and video load and download plan sends
`allow_oversized_load`.
- On Images and Video, a load refused with `unified-memory-load` shows a
titled toast with a **Load anyway** action.
- The action opens a confirmation that restates the risk: the load can
fail, use up all memory, swap heavily, stop responding or stop Studio.
- Only Confirm retries that pick once with the override. Cancel does
nothing, nothing retries on its own, and other refusals are unchanged.

## Testing

### Backend

`studio/backend/tests/test_diffusion_unified_load_override.py` has 22
new tests covering:

- the issue's numbers, reproduced exactly;
- the capacity-view fix;
- the default still refusing, now with the code;
- the request flag lifting the refusal only within its own scope;
- the env var still working;
- the override's warning;
- context propagation through `asyncio.to_thread`, and no leak into
another thread;
- the request and response models;
- `begin_load` handing the flag to the worker;
- `error_code` from the image and video workers.

On the merge base, a version of these tests with the new imports removed
fails 8 of 12. That includes the capacity-view test: the busy Mac reads
"only about 41 GB is usable" on base.

The existing guard, MPS budget, ROCm APU reserve, text-encoder release,
pre-download guard and device suites: 383 passed, 1 skipped. Wider
diffusion, video, route, MCP and engine suites: 2,800+ passed. The
failures in those suites also fail on the merge base on this host:

- `test_begin_load_rejects_concurrent`
- four `test_diffusion_native_quant` cases (bitsandbytes CUDA setup)
- `test_a_gated_base_with_a_live_mirror_is_not_refused` (network)
- the `test_begin_load_answers_without_waiting_on_the_header_probe`
timing check

### Frontend

- `tests/unified-memory-load-refusal.test.ts` adds 11 tests. The full
unit suite passes: 12,906 passed, 0 failed.
- `node scripts/typecheck.mjs --tests` passes.
- Strict i18n parity passes across all 14 locales.
- ESLint error and warning counts on the two pages match the base.

### Studio UI

Studio ran from the branch with the diffusion CUDA memory reader patched
to report a 3.5 GiB unified pool. The pick was the curated Qwen-Image
entry, with its requests redirected to a 30 MB random-weight Qwen-Image
pipeline, so no real weights were downloaded. Results:

- **Before:** the refusal toast offers only the env var.
- **After:** the toast has Load anyway. Confirming loads the model, and
the backend logs `loading past the unified-memory estimate
(allow_oversized_load)`.
- **Setting on:** the same pick loads with no refusal.

<!-- screenshots: compare_refusal_before_after.png, head_03_confirm.png,
head_04_after_load_anyway.png, compare_settings_before_after.png -->

## Not covered here

- No run on a real Mac. Whether bf16 Qwen-Image (57 GB with overhead)
completes on a 64 GB Apple Silicon machine under the allocator cap is
not measured.
- A per-model version of the setting.
- Persistence across Desktop restarts and updates is reasoned from local
storage under the app's fixed origin, not exercised in a Desktop build.


## Screenshots

Studio run with a simulated 3.5 GiB unified pool, on a tiny Qwen-Image
so no large weights were downloaded.

The refusal before and after: the toast now has a title and a Load
anyway action.

![Refusal toast, before and
after](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/14379/compare_refusal_before_after-f39ba5d5a29c.png)

Load anyway opens a confirmation that restates the risk; only Confirm
retries the load.

![Load anyway
confirmation](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/14379/head_03_confirm-a87eccec22d0.png)

After confirming, the model loads (the backend logs that it is loading
past the unified-memory estimate).

![Model loaded after Load
anyway](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/14379/head_04_after_load_anyway-f8345c296202.png)

Settings > System > Model memory: the new "Allow oversized model loads"
switch, off by default.

![Settings, before and
after](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/14379/compare_settings_before_after-c54a0115cd92.png)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant