Skip to content

Studio diffusion: fp32 VAE upcasts keep the offloaded VAE's pinned host weights (SDXL-class force_upcast VAEs) - #14946

Merged
danielhanchen merged 5 commits into
mainfrom
studio-vae-upcast-keeps-pinned
Oct 23, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
studio-vae-upcast-keeps-pinned

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 23, 2026 •

Copy link
Copy Markdown
Member

Problem

SDXL-class VAEs set config.force_upcast. On a 16-bit load, diffusers' SDXL decode and img2img prepare_latents run vae.to(torch.float32) and later vae.to(float16). The fp16 decode's fp32 encode / fallback (_fp32_call in diffusion_vae_fp16.py) does the same round trip. Every one of those casts gives every parameter a new storage.

Under whole-module CPU offload (enable_model_cpu_offload + keep_cpu_weights_on_offload) this breaks the kept host weights for the VAE:

  • The decode's upcast runs while the VAE is still offloaded, before its first onload. The kept-hook pre_forward sees replaced tensors, drops them from the kept set, and has nothing to pin. The VAE is never pinned.
  • So every render converts the host weights to fp32 on the CPU and onloads them as one pageable per-tensor copy each, at twice the bytes. The offload then copies the fp16 weights back to new pageable host tensors.
  • Once a VAE has been pinned (for example the fp16-decode path, whose encode upcasts only the encoder), the round trip re-points the affected weights at fresh pageable tensors, while the old pinned chunks stay referenced by pin_layout.

Measured on current main with hf-internal-testing/tiny-sdxl-pipe (fp16, force_upcast=True, model offload on cuda, UNSLOTH_DIFFUSION_OFFLOAD_PIN=1), with a torch.profiler memcpy count per render:

main this branch
VAE params pinned after 3 txt2img renders 0 / 124 124 / 124
pin_layout recorded for the VAE no yes
H2D copies per render, pageable / pinned 129 / 3 5 / 4
VAE params pinned after 2 img2img renders 0 / 124 124 / 124
fp16-decode load, VAE params pinned after 2 img2img renders 70 / 124 124 / 124
txt2img render wall time, 3 runs (ms) 2918, 4351, 4219 153, 259, 144

The wall times come from a shared, non-exclusive card with a tiny model, so treat them as indicative only. The copy counts and pinned counts are deterministic.

Fix

New core/inference/diffusion_vae_upcast.py with one shared mechanism:

  • upcast_keeping_storage(owner, parts) / restore_storage(token) / fp32_keeping_storage(owner, parts): if the owner sits behind a kept offload hook, it is first onloaded through that hook, so the weights go up as pinned chunks in the load dtype. The cast to fp32 then happens on the device. The cast back puts the original tensor objects back instead of allocating new ones, so the offload re-points them at the pinned host copy. If a tensor was replaced or moved in the meantime, it is cast back to its load dtype instead, which matches the stock cast.
  • pipeline_upcasts_keep_storage(pipe): wraps Studio's single pipe(**chunk_kwargs) call site. For that one call, a dtype-only to on a force_upcast 16-bit VAE routes diffusers' own vae.to(torch.float32) / vae.to(float16) (SDXL decode, img2img prepare_latents) through the helper above. Device moves and any other cast go to the stock to. diffusers itself is not patched. If the call raises between the upcast and the cast back, the VAE is left in its load dtype.
  • The fp16 decode's _fp32_call uses fp32_keeping_storage in place of their own to(float32) / to(float16) pair.
  • diffusion_memory: the kept hook's pinned-chunk onload stays engaged when the instance-level to is this dtype-only one. It also restores that to after its temporary shadow instead of popping it. Other instance-level movers (stable arena, pinned swap) still defer exactly as before.

The math does not change. fp16 to fp32 is exact, the fp32 compute is the same, and diffusers still sees an fp32 VAE (vae.dtype, the post_quant_conv dtype read before denormalising), so outputs are bit-identical to main. This follows ComfyUI's behaviour of not rewriting a VAE's stored weights to get a higher compute dtype.

Tests

studio/backend/tests/test_diffusion_vae_upcast_storage.py, 11 tests:

  • CPU (8): the round trip puts back the same tensors; a parts-only upcast; a tensor replaced meanwhile is cast back, not overwritten; the pipeline round trip is bit-identical to a stock fp32 decode and keeps storage; a raise mid-upcast leaves the load dtype; the wrapper is inert for fp32 VAEs or when force_upcast is off; the fp16-decode fp32 encode keeps encoder storage and is bit-identical.
  • CUDA (1, tiny SDXL): under model offload the VAE is pinned after the first render and stays pinned, and renders match main bit for bit.

On main: 8 CPU tests fail and the CUDA test fails. That includes the behavioural ones, such as the fp32-encode storage asserts. On this branch all of them pass.

Merged with main after #14863: main's Hires fix now interpolates the base latents directly (as ComfyUI's LatentUpscale) and no longer runs the VAE, so the Hires encode wrapper and its two tests were dropped in the merge. diffusion_hires.py is identical to main.

Existing suites (test_diffusion_vae_fp16, test_diffusion_hires, test_diffusion_offload_keep_cpu, test_diffusion_offload_fast_upload, test_diffusion_sdxl, test_diffusion_offload_precision, test_diffusion_base_precision, test_diffusion_inpaint_mask_sdxl, test_diffusion_vae_oom, test_diffusion_offload_cuda_graph) on a CUDA host had identical results on main and this branch, with no failures on either side: 23 + 36 (3 skipped) + 14 + 169 + 80 + 6 + 15 + 116 + 46 passed, and the other 193 Hires tests passed or skipped the same way on both sides. The remaining Hires test, test_tiny_sdxl_hires_sequencing, hit a 40 minute timeout on both main and this branch. The host was heavily oversubscribed (load average about 1200), so that test produced no verdict either way.

Not covered

  • Real SDXL weights were not used. The evidence is from the tiny SDXL pipeline, so the end-to-end speedup on a full-size VAE was not timed on an exclusive card.
  • Group offload and sequential offload are unchanged. The group plan keeps the VAE resident, and the sequential path was only exercised by the existing Hires test.
  • ROCm, MPS and Windows did not run.

… the fp32 round trip

diffusers' SDXL decode and img2img prepare_latents, the Hires latent encode and
the fp16 decode's fp32 encode cast the whole VAE to fp32 and back. Each cast
replaced every parameter's storage, so under model offload the VAE was never
pinned and every onload was a per-tensor pageable copy of fp32 weights.

Upcast on the device after a pinned onload and put the original tensors back on
the cast down. Output is bit-identical.
@danielhanchen danielhanchen self-assigned this Oct 23, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 23, 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-23T11:04:22.076565Z 4f8f84b 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 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: 5fea6a2c10

ℹ️ 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 +88 to +91
if p.data_ptr() == cast_ptr and p.device == orig.device:
p.data = orig
elif p.dtype != orig.dtype:
p.data = p.data.to(orig.dtype)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Restore storages after nested load-dtype casts

On supported Python 3.9 installations, pyproject.toml permits pre-0.37 diffusers, whose SDXL upcast_vae() casts the whole VAE to fp32 and then casts post_quant_conv, decoder.conv_in, and decoder.mid_block back to the load dtype before decoding. Those nested casts change each parameter's pointer, so when the final intercepted vae.to(load_dtype) reaches this branch, p.dtype == orig.dtype and neither condition restores orig. With kept CPU offload, those weights consequently fail _init_hook's pointer check, abandon their pinned host storage, and revert to pageable transfers on every render while the old pin layout remains retained. The restore token needs to distinguish these expected nested load-dtype casts from unrelated external replacements.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Confirmed. On Python 3.9 the extra still allows diffusers below 0.37. Those versions' upcast_vae() casts the whole VAE to fp32 and then casts post_quant_conv, decoder.conv_in and decoder.mid_block back to fp16 with submodule .to calls, which the intercept never sees. When the last vae.to(float16) arrives, those parameters are already fp16 at new addresses. Neither branch restored them, so they left the pinned host copy.

Fixed in ddd394c. restore_storage now also puts the original tensor back when the current one has the load dtype, sits on the same device with the same shape, and is torch.equal to it. That check only runs for tensors replaced inside the block. A same-dtype replacement with different values is still left alone.

Tests (CPU), in test_diffusion_vae_upcast_storage.py:

  • test_nested_load_dtype_casts_still_restore_the_original_tensors reproduces the old upcast_vae sequence under pipeline_upcasts_keep_storage and checks every parameter's data_ptr and dtype afterwards. It fails on 5fea6a2 and passes now.
  • test_a_changed_same_dtype_replacement_is_left_alone passes.

parts = [owner] if parts is None else [p for p in parts if p is not None]
_onload_through_kept_hook(owner)
params, buffers = _float_tensors(parts, dtype)
saved_params = [(p, p.data) for p in params]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Restore replacement parameters used by sequential offload

When a force-upcast fp16 VAE uses the supported sequential CPU-offload mode, Accelerate's leaf hooks replace each registered Parameter while loading it from meta and replace it again when offloading after the encode/decode. This token retains only the pre-forward Parameter object, so restore_storage() updates a detached object and leaves the parameter actually registered on the VAE as fp32. The previous finally: vae.to(dtype) acted on the current registrations; after this change a sequentially offloaded txt2img render instead leaves vae.dtype as fp32, and a following Hires latent encode treats fp32 as the load dtype and performs the post-encode scaling/interpolation in fp32 rather than the prior fp16 path, breaking the promised bit-identical behavior. Track the owning module and parameter name, as is already done for buffers, so the current registration can be restored.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Confirmed. Under sequential CPU offload, accelerate's leaf hooks register a new Parameter on every onload from meta and again on the offload back to meta. The token held the pre-forward Parameter objects, so the restore updated detached objects and the registered parameters stayed fp32. The old vae.to(dtype) acted on the current registrations.

Fixed in ddd394c. The token is now keyed by (module, name) for parameters as well as buffers, and restore_storage acts on whatever is registered at restore time. A meta fp32 parameter matches the meta cast and gets the original meta fp16 tensor back. Anything else that is still fp32 is cast back to the load dtype, as the stock cast does.

Test (CPU): test_sequential_offload_replacement_parameters_return_to_the_load_dtype[helper|pipeline] applies accelerate.cpu_offload to a tiny fp16 force_upcast AutoencoderKL. It runs an fp32 encode through fp32_keeping_storage and through the pipeline intercept, then asserts every registered parameter is fp16 and the latents are bit-identical to a stock fp32 encode. Both cases fail on 5fea6a2 and pass now. The existing sequential-offload Hires CUDA test also passes: 34 of the targeted CUDA, offload and encode tests pass in total.

Key the restore token by (module, name) so sequential offload's replacement
Parameters return to the load dtype, and put the original tensor back when a
nested load-dtype cast inside the block (diffusers < 0.37 upcast_vae) left an
equal copy.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: ddd394cc55

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

…ps-pinned

# Conflicts:
#	studio/backend/core/inference/diffusion_hires.py

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 4f8f84b84d

ℹ️ 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 30e7688 into main Oct 23, 2026
@danielhanchen
danielhanchen deleted the studio-vae-upcast-keeps-pinned branch October 23, 2026 17:27
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 24, 2026
…unslothai#15058)

## Summary

The fp32 VAE upcast added in unslothai#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
unslothai#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.
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