Repository navigation
Studio Images: Hires fix latent upscale interpolates the base latents directly, as ComfyUI's LatentUpscale - #14863
Merged
Merged
Conversation
Under enable_model_cpu_offload the SDXL VAE weights rest on the CPU (on meta under sequential offload), so the latent upscaler built its input there and the offload hook's move of the VAE to the card made encode fail with a device mismatch after the base pass. Resolve the device from the VAE offload hook, then resident weights, then the pipeline execution device.
…tUpscale The latent upscaler decoded the base pass to an 8-bit image, then VAE-encoded it again before the nearest-exact interpolate. ComfyUI's LatentUpscale interpolates the sampler's own latents (common_upscale, nearest-exact, crop disabled). Run the SDXL base call with output_type="latent" for a latent Hires request, hand each image's latents to the refine pass and interpolate them there: one VAE decode and one encode fewer per image, and no 8-bit round trip. Lanczos and model upscalers keep the decode. The decode-free base pass records no learned activation peak, since it misses the decode phase a plain render at that size has.
Member
Author
|
@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. |
|
Codex Review: Didn't find any major issues. Keep them coming! 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". |
…irect # Conflicts: # studio/backend/core/inference/diffusion_hires.py # studio/backend/tests/test_diffusion_hires.py
danielhanchen
added a commit
to Etherll/unsloth
that referenced
this pull request
Oct 23, 2026
…st weights (SDXL-class force_upcast VAEs) (unslothai#14946) ## 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 unslothai#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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stacked on #14851 (
studio-hires-offload-device): land this after #14851.Problem
The SDXL Hires fix "latent" upscaler did not upscale in latent space. The base pass decoded its latents to an 8-bit PIL image, then the refine pass VAE-encoded that image again (
latent_dist.mode()), scaled it and interpolated it nearest-exact. That costs one VAE decode and one VAE encode per hires image, and the refine pass starts from a decode, 8-bit quantise and encode round trip of the base latents instead of the latents themselves.ComfyUI, which Studio follows for Hires fix defaults, does not do this.
LatentUpscale(andLatentUpscaleBy,scale_by1.5) interpolates the sampler's own latents:common_upscale(samples, w // 8, h // 8, "nearest-exact", crop="disabled"). Our method and crop already matched; only the decode and re-encode differed.Fix
run_hiresmarks the base passlatent_outputwhen the upscaler islatent(always a refine: denoise 0 is refused for it).generatethen runs the SDXL base call withoutput_type="latent"and returns one(1, C, h, w)slice per image (a copy, so no later forward can reuse its storage), with seeds unchanged. The base pass skips its VAE decode and the PIL post-processing tied to it.diffusion_hires.upscale_latents(pipe, latents, size), which is onlyF.interpolate(latents, size=(h // 8, w // 8), mode="nearest-exact").encode_upscaled_latentsand the_vae_execution_devicehelper from Studio Images: run the Hires fix latent encode where an offloaded SDXL VAE computes #14851 go away: no encode runs, and the img2img pipeline moves the latents to its own execution device, so resident, model offload and sequential offload all work.run_hiresreplacesimageswith the refined ones, and the UI and gallery only readhires_base_width/hires_base_height), so nothing has to decode it.format_generation_for_logno longer reads a tensor'ssizemethod as a pixel size.Tests
All runs use tiny SDXL (
hf-internal-testing/tiny-stable-diffusion-xl-pipe).test_latent_upscaler_refines_the_sampler_latents_like_comfyui, parametrised over CPU resident, CUDA resident, CUDA model offload and CUDA sequential offload. It checks four things. The base call runs withoutput_type="latent". Each refine input is exactlyF.interpolate(base_latents[i:i+1], size, mode="nearest-exact")(torch.equal, same device). A batch of 2 makes 0 VAE encodes and 2 decodes. The base latents decode to the pixels a plain render returns (max abs diff <= 1), so the base pass itself is unchanged.test_latent_upscale_is_comfyui_nearest_exact_and_needs_latentsandtest_generation_log_line_takes_a_latent_base_pass.test_run_hires_plans_against_the_model_loaded_when_the_slot_is_heldnow also asserts that the base pass is asked for latents.tests/test_diffusion_hires.pyon GPU: 192 passed, 2 skipped. On CPU,test_diffusion_hires.py,test_diffusion_auto_policy.py,test_diffusion_learned_peaks.py,test_diffusion_sd_controls.py,test_diffusion_inpaint_mask_sdxl.pyandtest_diffusion_embeddings.py: 410 passed, 7 skipped.test_diffusion_backend.py: 663 passed and 1 failed. That failure (test_mirrored_base_still_trips_the_flux2_shape_guard,No module named 'gguf') also fails on the base branch.VAE calls per latent Hires request (resident, model offload and sequential offload are identical):
Compiled tier (Studio
defaultspeed:compiled,fused_qkv,vae_fused,cuda_graph), loaded throughload_pipeline, with three latent Hires prompts at 256 to 384. The 2nd and 3rd prompts make 0 fresh compiles, 0 new CUDA graph captures and noTORCH_LOGS=recompileslines, the same as the base branch. The first prompt's one recompile is also the same on both branches.Timing on tiny SDXL, CUDA resident and eager, 256 to 384 with 2 base and 2 refine steps: 30 requests per run, 3 runs per arm, interleaved on one shared card. The base branch's A/A run medians were 855, 1170 and 854 ms. This PR's were 322, 418 and 427 ms. The refine-phase median dropped from 680 to 980 ms down to 190 to 225 ms. The card was shared, so these numbers show the direction and rough size, not a precise speedup.
Output change: on tiny SDXL the hires output differs from the base branch (LPIPS 0.52, max abs 253). The tiny VAE has random weights, so its decode and encode round trip is far from identity. This shows that the old path changed the refine input, not that quality got worse. On real SDXL base 1.0, run from the fp16 weights already in the cache (1024 to 1536, 20 base and 10 refine steps, denoise 0.5, seeds 7 and 11), the output moves by LPIPS 0.022 and 0.020 (mean abs 2.4 and 2.1 of 255). The images are the same composition with small detail changes, and neither is black or NaN. The VAE calls per image drop from 2 decodes and 1 encode to 1 decode and 0 encodes. The warm request took 5.59 s on the base branch and 4.76 s with this PR (single pass per arm).
Not covered
maxspeed tier, sd.cpp (native engine, unchanged) and MLX are not exercised.