Repository navigation
Studio Images: run the Hires fix latent encode where an offloaded SDXL VAE computes - #14851
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.
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". |
danielhanchen
added a commit
that referenced
this pull request
Oct 23, 2026
… directly, as ComfyUI's LatentUpscale (#14863) 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` (and `LatentUpscaleBy`, `scale_by` 1.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_hires` marks the base pass `latent_output` when the upscaler is `latent` (always a refine: denoise 0 is refused for it). - `generate` then runs the SDXL base call with `output_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. - The refine pass gets `diffusion_hires.upscale_latents(pipe, latents, size)`, which is only `F.interpolate(latents, size=(h // 8, w // 8), mode="nearest-exact")`. `encode_upscaled_latents` and the `_vae_execution_device` helper from #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. - Lanczos and model (ESRGAN) upscalers are unchanged: they still decode, since they need pixels. - The base image is never returned or stored for a Hires request (`run_hires` replaces `images` with the refined ones, and the UI and gallery only read `hires_base_width` / `hires_base_height`), so nothing has to decode it. - The decode-free base pass records no learned activation peak, because it misses the decode phase that a plain render at that size has. Recording it would under-size a later plain render. - `format_generation_for_log` no longer reads a tensor's `size` method as a pixel size. ## Tests All runs use tiny SDXL (`hf-internal-testing/tiny-stable-diffusion-xl-pipe`). - New `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 with `output_type="latent"`. Each refine input is exactly `F.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. - New `test_latent_upscale_is_comfyui_nearest_exact_and_needs_latents` and `test_generation_log_line_takes_a_latent_base_pass`. `test_run_hires_plans_against_the_model_loaded_when_the_slot_is_held` now also asserts that the base pass is asked for latents. - On the base branch the 6 new or changed tests fail. With this change they pass. - `tests/test_diffusion_hires.py` on 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.py` and `test_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): | | base branch | this PR | |---|---|---| | batch 1 | 2 decode, 1 encode | 1 decode, 0 encode | | batch 2 | 3 decode, 2 encode | 2 decode, 0 encode | Compiled tier (Studio `default` speed: `compiled`, `fused_qkv`, `vae_fused`, `cuda_graph`), loaded through `load_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 no `TORCH_LOGS=recompiles` lines, 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 - No side-by-side run against a live ComfyUI. Parity is shown by construction: the refine input is exactly ComfyUI's nearest-exact interpolate of the sampler latents. - Timing is not from an exclusive card, and real SDXL timing is a single pass per arm. - The `max` speed tier, sd.cpp (native engine, unchanged) and MLX are not exercised. - With the decode-free base pass recording no learned peak, a CUDA-graph load whose first latent Hires request captures new graphs leaves those graphs unaccounted. Later renders then skip peak learning (the conservative path the probe already takes for unrecorded renders).
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.
Problem
The SDXL Hires fix latent upscaler (the SDXL default) fails on loads that use CPU offload.
encode_upscaled_latentstook its device fromnext(vae.parameters()).device. Underenable_model_cpu_offload(the policy Studio picks when SDXL does not fit the card) the VAE weights sit on the CPU between calls, so the preprocessed base image was placed on the CPU. diffusers'apply_forward_hookthen moves the VAE to the card forencodeand the call fails with:This happens after the whole base pass has run. Under sequential offload the weights are on
meta, so the input was sent tometainstead.Fix
encode_upscaled_latentsnow resolves where the VAE computes, not where its weights rest:execution_device(whole-module offload);pipe._execution_device(sequential offload, weights onmeta);The input image and the
latents_mean/latents_stdtensors go to that device. The rest of the hires path was checked for the same pattern: the Lanczos path is PIL only, the model upscaler already runs on the load's state device, and the refine pass and its decode run inside the diffusers img2img pipeline, which uses_execution_deviceitself.Tests
New tests in
studio/backend/tests/test_diffusion_hires.py, using a fresh copy ofhf-internal-testing/tiny-stable-diffusion-xl-pipeso the offload hooks do not leak into the shared fixture:test_latent_encode_runs_where_the_offload_hook_computes: VAE under acceleratecpu_offload(weights onmeta, executing on CPU), result matches the resident encode. Runs without a GPU.test_vae_execution_device_order: the device resolution order above.test_latent_encode_under_cpu_offload_on_cuda[model|sequential]:enable_model_cpu_offloadandenable_sequential_cpu_offload, latents land on CUDA and match the resident encode.test_tiny_sdxl_hires_latent_under_model_offload_on_cuda: end to endDiffusionBackend.generate(hires=...)withupscaler="latent"on a model-offloaded tiny SDXL load.All 5 fail on main (the end to end test with the device mismatch above) and pass with the fix. The existing hires, upscale gate, sd.cpp args, diffusion backend, SDXL inpaint and VAE fp16 test files show the same results on main and on this branch (975 passed on main, 980 with the 5 new tests here); the one failure,
test_diffusion_backend.py::test_mirrored_base_still_trips_the_flux2_shape_guard, fails identically on main and is unrelated.Not covered
force_upcastround trip (vae.to(float32)and back) is unchanged. Under whole-module offload it replaces the VAE's kept, pinned host weights with new unpinned tensors, so later VAE onloads copy from pageable memory. The same round trip happens in diffusers' own SDXL img2imgprepare_latentsand in Studio's fp32 encode wrapper, so it is not specific to Hires fix and is left for a separate change.