Skip to content

Studio Images: run the Hires fix latent encode where an offloaded SDXL VAE computes - #14851

Merged
danielhanchen merged 2 commits into
mainfrom
studio-hires-offload-device
Oct 23, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
studio-hires-offload-device

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

The SDXL Hires fix latent upscaler (the SDXL default) fails on loads that use CPU offload. encode_upscaled_latents took its device from next(vae.parameters()).device. Under enable_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_hook then moves the VAE to the card for encode and the call fails with:

RuntimeError: Expected all tensors to be on the same device, but got weight is on cuda:0, different from other tensors on cpu

This happens after the whole base pass has run. Under sequential offload the weights are on meta, so the input was sent to meta instead.

Fix

encode_upscaled_latents now resolves where the VAE computes, not where its weights rest:

  1. the VAE's own accelerate offload hook execution_device (whole-module offload);
  2. else the weights' device when it is a real device (resident, or a VAE placed on its own card by a split);
  3. else pipe._execution_device (sequential offload, weights on meta);
  4. else the weights' device (duck-typed pipes).

The input image and the latents_mean / latents_std tensors 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_device itself.

Tests

New tests in studio/backend/tests/test_diffusion_hires.py, using a fresh copy of hf-internal-testing/tiny-stable-diffusion-xl-pipe so the offload hooks do not leak into the shared fixture:

  • test_latent_encode_runs_where_the_offload_hook_computes: VAE under accelerate cpu_offload (weights on meta, 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_offload and enable_sequential_cpu_offload, latents land on CUDA and match the resident encode.
  • test_tiny_sdxl_hires_latent_under_model_offload_on_cuda: end to end DiffusionBackend.generate(hires=...) with upscaler="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

  • Real SDXL weights on a small card were not run; the tiny pipeline exercises the same offload hooks.
  • The CUDA tests skip on runners without a GPU; only the meta / CPU test and the resolution order test run there.
  • The force_upcast round 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 img2img prepare_latents and in Studio's fp32 encode wrapper, so it is not specific to Hires fix and is left for a separate change.

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.
@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-23T01:30:54.567931Z 9b5e076 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. Keep them coming!

Reviewed commit: 9b5e07622a

ℹ️ 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 82c4efe into main Oct 23, 2026
2 of 34 checks passed
@danielhanchen
danielhanchen deleted the studio-hires-offload-device branch October 23, 2026 02:41
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).
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