Skip to content

Studio: fp32 VAE upcast frees each 16-bit device tensor as it is cast - #15058

Merged
danielhanchen merged 3 commits into
mainfrom
studio-vae-upcast-no-dual-copy
Oct 24, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
studio-vae-upcast-no-dual-copy

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

The fp32 VAE upcast added in #14946 kept every 16-bit device weight alive next to its fp32 copy for the whole fp32 window. Peak VAE weight memory was about 1.5x the fp32 size (about +160 MiB for an SDXL-sized VAE), so the upcast could OOM where diffusers' stock vae.to(torch.float32) fits. This happened for resident VAEs too, not only offloaded ones. A conversion that failed partway (an OOM) also left the VAE with mixed fp16 / fp32 parameters, because the restore only ran after the upcast returned.

This change casts one tensor at a time, freeing each 16-bit device tensor as its fp32 copy lands, as Module.to does. The purpose of #14946 is kept: the offloaded VAE's stored host weights stay pinned and in their storage dtype.

Details

studio/backend/core/inference/diffusion_vae_upcast.py:

  • Device tensors are cast in place one at a time; their 16-bit originals are not held. Host (and meta) originals are still kept and put back exactly, since they are the stored weights.
  • Behind the kept offload hook, the onload is a single device chunk shared by every weight. Weights that are the hook's untouched onload of a pinned host tensor are first pointed back at that host tensor, which frees the chunk before any fp32 copy exists, and are then cast from the pinned host tensor.
  • On restore, the fp32 tensor is cast back to the load dtype (16-bit to fp32 to 16-bit is exact). If it was not touched in the fp32 window, it is recorded as the hook's onload, so the offload still re-points it at the pinned fp16 host tensor instead of copying it to a new pageable one. A weight cast back meanwhile by a submodule to (diffusers < 0.37 upcast_vae) is compared against its host tensor first.
  • If the upcast raises, every tensor is put back in its load dtype before the error propagates.

Peak torch.cuda.max_memory_allocated above the allocation before the upcast. Random weights at SDXL VAE dims (fp16 weights 159.6 MiB, fp32 319.1 MiB), B200, torch 2.14.1:

Path Stock vae.to(float32) main This PR
Resident VAE on CUDA 164.0 MiB 319.1 MiB 164.0 MiB
Model offload, kept pinned hook (rounds 1 and 2) n/a 478.7 MiB 323.6 MiB

Resident now matches stock. Under offload the device holds only the fp32 copies plus one tensor in flight (main held the 16-bit chunk on top). After each offload all 248 parameters are back on the host as pinned fp16 tensors on both main and this PR. Decode outputs are bit-identical between main and this PR, and to stock fp32, on every arm.

Tests

New in studio/backend/tests/test_diffusion_vae_upcast_storage.py. All four fail on main and pass here:

  • test_a_failed_upcast_leaves_every_tensor_in_the_load_dtype[helper|pipeline]: an injected OOM partway through the upcast leaves every tensor in fp16 at its original storage, and a later upcast still works.
  • test_device_upcast_frees_each_16bit_tensor_as_it_goes_cuda: peak over a resident fp16 VAE stays within the extra fp32 half plus one tensor; decode equals stock fp32.
  • test_offloaded_upcast_frees_the_pinned_onload_and_stays_pinned_cuda: same bound behind the kept hook over two rounds; after each offload every weight is pinned fp16 on the host; decode equals stock fp32.

Run on CUDA: test_diffusion_vae_upcast_storage.py, test_diffusion_offload_keep_cpu.py, test_diffusion_offload_fast_upload.py, test_diffusion_vae_fp16.py, test_diffusion_vae_oom.py, test_diffusion_vae_oom_faults.py: 3561 passed, 3 skipped.

Not covered here: a real SDXL render on a 4 GB / 6 GB card, ROCm, MPS and Windows.

The upcast kept every 16-bit device weight alive next to its fp32 copy for
the whole fp32 window (about 1.5x the fp32 VAE weights at the decode peak,
also for VAEs that are not offloaded). Cast one tensor at a time instead,
as Module.to does. Behind the kept offload hook, first point the untouched
onload back at its pinned host tensor so the shared device chunk is freed
before any fp32 copy exists, and record the cast-back tensor as the hook's
onload so the offload still re-points it at the pinned fp16 host weights.
A failed upcast now puts every tensor back in its load dtype before raising.
@danielhanchen danielhanchen self-assigned this Oct 24, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 24, 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-24T01:28:15.564705Z 9cd3798 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: Didn't find any major issues. Delightful!

Reviewed commit: 9cd3798f6e

ℹ️ 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 f8743f8 into main Oct 24, 2026
41 of 42 checks passed
@danielhanchen
danielhanchen deleted the studio-vae-upcast-no-dual-copy branch October 24, 2026 03:40
danielhanchen added a commit that referenced this pull request Oct 28, 2026
…ain commit (#15761)

Diffusers 0.42.1 is on PyPI and carries FLUX.3 Image Klein, so Studio
can go back to installing a release instead of the pinned main commit.
This mirrors #13045, which did the same for 0.41.0 and Qwen-Image-2.1.

## What changes

- `diffusers-pin.txt` now pins one release per Python floor. Diffusers
0.42.0 declares `requires-python >= 3.11`, so a single `>= 3.10` line
would leave a 3.10 host with nothing to resolve.

  | Python | Release |
  | --- | --- |
  | 3.11 and newer | `diffusers==0.42.1` |
  | 3.10 | `diffusers==0.41.0` (unchanged) |
  | 3.9 | `diffusers==0.36.0` (unchanged) |

The installers create 3.13 by default (3.12 on Intel Macs), and
`install.ps1` only accepts 3.11 to 3.13, so 3.10 and 3.9 are only
reached by pip installs and `install.sh --python`.
- The commit line in `diffusers-main.txt` is commented out. The commit
(d42ebf9c), its archive SHA-256 and the explanation all stay, so a
future unreleased model can re-pin by uncommenting one line. The whole
git / zip route (11c, `--repair-diffusers-main`,
`--prefetch-diffusers-main`, the setup fast-path probe) is kept and
already treats an all-comment file as "nothing pinned".
- `_UNRELEASED_MIN_DIFFUSERS` is empty again, because 0.42.0 exists. The
FLUX.3 minimum stays at 0.42.0, the first release that has it.
- The too-old message for a family that needs 0.42.0 or newer now
depends on the Python version:
- On 3.11 or newer it says to update Unsloth, or `pip install -U
'diffusers>=0.42.0'`.
- On 3.10 or 3.9 it says that release needs Python 3.11 and that an
update cannot install it here.

  Before this change a 3.10 user was told the release did not exist yet.
- `_PIPELINE_PROBE_FILES` keeps its FLUX.3 entries, and only the comment
changes. The startup self-heal only replaces index installs. A host that
still has the d42ebf9c build (which reports 0.41.0.dev0) keeps FLUX.3
until its next update instead of losing it to a version comparison.
- Comment-only updates: the installer comments that assumed a main build
counts as current, the `overrides-darwin-arm64.txt` hub floor note
(0.42.1 declares the same `huggingface-hub>=1.32.0`), and the FLUX.3
forward digest note.

## Why

- d42ebf9c is an ancestor of v0.42.1, so the release is a superset of
what Studio ran: FLUX.3 Image Klein (huggingface/diffusers#15046) and
the prompt upsampler block (#15058) are both in it.
- 0.42.1 differs from 0.42.0 by a single fix. Library names read from
`model_index.json` / `modular_model_index.json` are no longer imported
unless they are a known loadable library or a `diffusers.pipelines`
module. Without that fix, a repository on `sys.path` could run its own
code on `from_pretrained()`.
- Installing from PyPI also takes git and github.com out of the default
install path again.

## Upgrade path for existing installs

- **Hosts with the d42ebf9c git or zip build** (0.41.0.dev0 plus a
`direct_url.json`): `_diffusers_release_behind` reads that as 0.41.0,
which is behind 0.42.1. The setup fast-path probe therefore forces the
dependency pass. The release step is no longer superseded, because no
main build is pinned, so it installs 0.42.1. A uv dry run of the new pin
file in an environment holding that build reports `-
diffusers==0.41.0.dev0 (from git+...@d42ebf9c...)`, `+
diffusers==0.42.1`.
- **Index installs of 0.41.0 on Python 3.11 or newer** are now behind
the pin. They are moved by the next update, or by the startup release
repair.
- **The startup repair leaves git, zip and checkout builds alone**, as
before (#13045), so the d42ebf9c build stays until `unsloth studio
update` or a desktop update.
- **Python 3.10 and 3.9 hosts** see no change.

## Tests

- **Pin tests** (`tests/studio/install/test_diffusers_pin.py`):
  - The pin file must contain exactly these three lines.
- New: a parametrized test evaluates the markers for Python 3.9, 3.10,
3.11, 3.13 and 3.14 and checks that each gets exactly one release.
- The shipped main pin is commented out but keeps its 40-character
commit and exactly one digest.
  - The retired FLUX.3 commit and digest are still in the file.
- The fast-path and repair tests now treat 0.42.1 as current, and 0.42.0
and 0.41.0 as behind.
- New: the d42ebf9c git or zip build forces the dependency pass and does
not supersede the release step. This fails on main.
- **Repair tests** (`studio/backend/tests/test_diffusers_repair.py`):
  - The shipped main pin is inactive.
- A current 0.42.1 starts nothing, and a 0.41.0 index install is behind.
  - New: the startup repair leaves the retired git build for the update.
- **FLUX.3 gate tests**
(`studio/backend/tests/test_diffusion_flux3.py`):
  - 0.42.0 is no longer in the unreleased set.
- On 3.12, a 0.41.0 install is told to update and given the pip command.
- On 3.10 and 3.9 the message names the Python 3.11 requirement, with no
pip, archive or "not released yet" text.

Real installs, CPU only:

- **Imports:** with diffusers 0.42.1 (Python 3.11, transformers 5.5.0),
`Flux3ModularPipeline`, `Flux3DistilledModularPipeline`,
`QwenImage21Pipeline`, `Flux2Pipeline` and `Flux2KleinPipeline` all
import.
- **Tiny-config forward:** the `Flux3Transformer2DModel` config from
diffusers' own model test (1 + 1 layers, 16-dim heads) runs with and
without image conditioning. It produces bit-identical output on 0.42.1
and on d42ebf9c with the same seed.
- **Family availability:** with Studio's family table on 0.42.1, every
family is selectable, including both FLUX.3 Klein variants and
Qwen-Image-2.1. On a real Python 3.10 environment built from the new pin
file (which resolves to 0.41.0), both FLUX.3 families are unavailable
and the refusal names Python 3.11.
- **Source guards:** every Studio guard that replaces or patches
diffusers code gives the same verdict on 0.42.1 as on d42ebf9c. That
covers:
  - the FLUX.3 forward digest
  - the Qwen-Image-2.1 fast-step and RoPE digests
  - the Qwen RoPE, Z-Image fused and Wan fused digests
  - FLUX.3 prompt-upsampler removal
  - LTX-2 import compat
  - FBCache source checks
  - the hires timestep rule

None of the diffusers files those guards read changed between the two
refs. All 120 `from diffusers ... import` statements in Studio's backend
resolve the same way on both. `dispatch_attention_fn` gained one line,
so its flash re-time fingerprint changes. That fingerprint already
includes the diffusers version, so the only effect is one re-time on
first use.

Suites, base (this branch's merge base) vs head, compared by failing
test IDs:

| Suite | Environment | Base | Head |
| --- | --- | --- | --- |
| `studio/backend/tests/test_diffusion*.py` + `test_video*.py` | Python
3.11, base on d42ebf9c, head on 0.42.1 | 19856 passed, 303 failed, 26
errors | 19857 passed, 303 failed, 26 errors |
| `tests/studio/install` | same | 9421 passed, 23 failed, 2 errors |
9430 passed, 23 failed, 2 errors |
| `studio/backend/tests/test_diffusion*.py` + `test_video*.py` | Python
3.13, no importable diffusers | 16602 passed, 400 failed, 119 errors |
16603 passed, 400 failed, 119 errors |
| `tests/studio/install` | same | 10221 passed, 25 failed | 10230
passed, 25 failed |

The failing test IDs are identical between base and head in every row.
These failures are already on main and come from this CPU-only host and
missing optional packages (`test_video_backend.py`,
`test_diffusion_offload_precision.py`, `test_diffusion_unified_edit.py`,
and the like). They are not from this change. Running the head test
files against base code fails 22 tests (15 pin, 2 repair, 3 FLUX.3 gate,
plus 2 FLUX.3 checkpoint tests that already fail on main). Those are the
ones that cover the new state.

## Not covered

- No GPU runs. Image quality and speed of FLUX.3, Qwen-Image-2.1 and the
patched kernels on 0.42.1 were not rendered or timed. Only the gates
that decide whether those paths engage were checked.
- Diffusers 0.42.1 changes how FLUX.3 preprocesses a single reference
image. It is now reflect-padded to the 16-pixel grid instead of
center-cropped, and with no size given the output is cropped back to the
reference's size. Studio resizes references to about 1 MP first, so the
difference should be small, but single-reference edits were not
re-rendered against d42ebf9c.
- The 0.42.1 library-name rule was checked against the cached Studio
model indexes and the MiniMax-H3 / Music 3 modular indexes (only
`diffusers` and `transformers` appear). Other catalog repos were not
fetched.
- Windows and macOS installers were not run. Their Python choices were
read from `install.ps1` and `install.sh`.
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