Skip to content

Studio Images: Hires fix latent upscale interpolates the base latents directly, as ComfyUI's LatentUpscale - #14863

Merged
danielhanchen merged 3 commits into
mainfrom
studio-hires-latent-direct
Oct 23, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
studio-hires-latent-direct

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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 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.
  • 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).

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.
@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-23T02:34:01.216578Z 4b98861 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: 4b9886173a

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

Base automatically changed from studio-hires-offload-device to main October 23, 2026 02:41
…irect

# Conflicts:
#	studio/backend/core/inference/diffusion_hires.py
#	studio/backend/tests/test_diffusion_hires.py
@danielhanchen
danielhanchen merged commit 4afc4f0 into main Oct 23, 2026
2 of 34 checks passed
@danielhanchen
danielhanchen deleted the studio-hires-latent-direct branch October 23, 2026 04:42
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.
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