Repository navigation
Studio diffusion: fp32 VAE upcasts keep the offloaded VAE's pinned host weights (SDXL-class force_upcast VAEs) - #14946
Conversation
… 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.
[skip ci]
|
@codex review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
| 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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_tensorsreproduces the oldupcast_vaesequence underpipeline_upcasts_keep_storageand checks every parameter's data_ptr and dtype afterwards. It fails on 5fea6a2 and passes now.test_a_changed_same_dtype_replacement_is_left_alonepasses.
| 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] |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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]
|
@codex review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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]
|
@codex review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…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.
Problem
SDXL-class VAEs set
config.force_upcast. On a 16-bit load, diffusers' SDXL decode and img2imgprepare_latentsrunvae.to(torch.float32)and latervae.to(float16). The fp16 decode's fp32 encode / fallback (_fp32_callindiffusion_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: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:pin_layoutrecorded for the VAEThe 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.pywith 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 singlepipe(**chunk_kwargs)call site. For that one call, a dtype-onlytoon a force_upcast 16-bit VAE routes diffusers' ownvae.to(torch.float32)/vae.to(float16)(SDXL decode, img2imgprepare_latents) through the helper above. Device moves and any other cast go to the stockto. diffusers itself is not patched. If the call raises between the upcast and the cast back, the VAE is left in its load dtype._fp32_callusesfp32_keeping_storagein place of their ownto(float32)/to(float16)pair.diffusion_memory: the kept hook's pinned-chunk onload stays engaged when the instance-leveltois this dtype-only one. It also restores thattoafter 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, thepost_quant_convdtype 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:force_upcastis off; the fp16-decode fp32 encode keeps encoder storage and is bit-identical.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.pyis 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