Skip to content

Studio Qwen-Image-2.1: reuse an unchanged condition image's VAE latents across renders - #17092

Merged
danielhanchen merged 5 commits into
mainfrom
studio/reference-vae-latent-cache
Nov 8, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
studio/reference-vae-latent-cache

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 8, 2026 •

Copy link
Copy Markdown
Member

Problem

Qwen-Image-2.1 and Qwen-Image-2.1-Turbo take up to ten condition images. Every render VAE-encodes each of them again inside the pipeline's prepare_latents, even when only the seed or the prompt changed between renders (the usual "try a few seeds" loop). The pipeline encodes condition images with the posterior mode (retrieve_latents(..., sample_mode="argmax")), never a sample, so the latents depend only on the preprocessed pixels and the VAE: the repeat encodes recompute the same tensor, and on an offloaded VAE they also pull the VAE onto the card early.

Change

New diffusion_reference_cache.py, installed per pipe at render time next to the device postprocess:

  • Wraps the pipeline instance's _encode_vae_image with a host-memory LRU (16 entries, 256 MiB; a 1024 px reference is about 0.5 MiB of latents).
  • Key: a blake2b digest of the preprocessed pixels plus their shape, dtype and compute device, and the VAE's identity, parameter dtype, tiling / slicing / tile-size attributes, any instance-level encode / forward overrides on the VAE or its encoder, the VAE config (so latents_mean / latents_std changes encode again), latent_channels, a weight revision (the summed version counters of its parameters and buffers, so load_state_dict or any in-place write invalidates while offload device moves do not) and the per-device autocast state and dtype. A different VAE object clears the cache. The key costs about 0.5 ms on the full-size Qwen-Image VAE (238 tensors, CPU), well under the pixel digest and the encode it saves.
  • A hit returns a copy of the stored latents on the compute device. A miss runs the stock method and stores a host copy.
  • Installed only for QwenImage21Pipeline and only when the installed pipeline's _encode_vae_image source reads the posterior mode and never samples. Bypassed with grad enabled.
  • UNSLOTH_REFERENCE_VAE_CACHE=0 encodes every render again (checked at install and per call).

The generator is never read by a mode encode, so the target noise and the generator state are unchanged.

Tests

tests/test_diffusion_reference_cache.py (tiny random AutoencoderKLQwenImage21 through the real prepare_latents):

  • Three renders with different seeds: condition latents, target noise and generator state equal to an uninstalled pipeline; the VAE encodes each reference once.
  • A changed pixel, VAE tiling on, a float64 cast and a replaced VAE object each encode again; tiling off again hits the earlier entry.
  • Kill switch at install and per call; a sampling _encode_vae_image is never wrapped; other pipelines are left alone; the LRU bound evicts the oldest entry.

CPU: 6 passed.

GPU measurement

Kaggle T4, diffusers 0.42.1, the real QwenImage21Pipeline.prepare_latents with a full-size AutoencoderKLQwenImage21 (default config, random weights, float16), 1024 px references, six calls each with a new generator seed (a seed-only rerender loop). Base = merge base 6244269, interleaved, 3 reps per arm.

references arm VAE encodes over 6 calls first call (s) later calls, median (s)
1 base 6 0.923 / 0.924 (5.165 cold) 0.433 / 0.435 / 0.436
1 this PR 1 0.929 / 0.983 / 0.926 0.024 / 0.023 / 0.022
3 base 18 1.776 / 1.810 / 1.852 1.311 / 1.323 / 1.333
3 this PR 3 1.870 / 1.853 / 1.875 0.070 / 0.068 / 0.067
3 this PR, UNSLOTH_REFERENCE_VAE_CACHE=0 18 1.799 1.345

The condition latents and the target noise hash identically in every arm and call. A cache hit still costs about 22 ms per reference on a T4 (the pixel digest and the host-to-card copy); the first call can cost that much extra too, which is inside the base spread at three references.

Not covered

  • A complete Qwen-Image-2.1 render with the real checkpoint was not run (no weights were downloaded); the encode path measured is the pipeline's own prepare_latents.
  • Studio's VAE wrappers (OOM retry, fused encoder) are part of the key through the encode overrides, but a render that flips one of them mid-session was only covered by the CPU tests.
  • ROCm, XPU, MPS and Windows were not run; the cache is plain tensor and hashing code.

…ts across renders

Every Qwen-Image-2.1 / Turbo render with reference images VAE-encoded each reference again, even when only the seed
or prompt changed. The pipeline encodes references with the posterior mode, never a sample, so the latents depend
only on the preprocessed pixels and the VAE.

The render now wraps the pipeline's reference encode with a small host-memory LRU (16 entries, 256 MiB) keyed by a
digest of the preprocessed pixels, their shape / dtype / device, and the VAE's identity, dtype, tiling / slicing
settings and encode overrides. A hit returns a copy of the stored latents on the compute device; the encode, the
VAE onload it triggers and the generator are untouched. Installed only when the installed pipeline's source reads
the posterior mode. UNSLOTH_REFERENCE_VAE_CACHE=0 encodes every render again.
@danielhanchen danielhanchen self-assigned this Nov 8, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-08T09:37:19.558131Z 7222c8f 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.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 26ab146cc8

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

…nfig

A hit now requires the same per-device autocast state, the same parameter and buffer version
counters (load_state_dict and other in-place writes invalidate, offload moves do not) and the
same VAE config, so normalization changes encode again. Tests cover each transition.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 7222c8ffa9

ℹ️ 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 e1e4cc6 into main Nov 8, 2026
@danielhanchen
danielhanchen deleted the studio/reference-vae-latent-cache branch November 8, 2026 15:01
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Nov 9, 2026
…e_dict(assign=True) on its VAE (unslothai#17197)

Follow-up to unslothai#17092, which reuses a condition image's VAE latents across
Qwen-Image-2.1 / Turbo renders.

## What happened

The cache key tells a weight change apart by `_weights_revision`, the
tensor count plus the sum of the tensors' version counters. An in-place
`load_state_dict` bumps those counters, so it encodes again.
`load_state_dict(..., assign=True)` does not write in place: it swaps in
the incoming tensors, whose counters can equal the old ones. The VAE
object, config, dtype and method overrides are also unchanged, so the
next render with the same pixels hit the old entry and returned latents
encoded with the previous weights.

With the tiny `AutoencoderKLQwenImage21` and the real
`_encode_vae_image`, assigning a differently seeded state dict left the
revision unchanged and the cached result differed from a fresh encode.

No default Studio flow does this today: every `assign=True` load builds
the VAE before the pipeline installs the cache. It is still a silent
wrong-output path for any later reload, so it is closed here.

## Fix

When the cache first sees a VAE it registers a `load_state_dict` post
hook on each of the VAE's modules. Any load on the VAE or one of its
submodules (in place or `assign=True`) clears the entries and bumps a
generation number that is part of the key, so an encode that was in
flight during the load cannot be served afterwards. Offload moves that
swap `.data` do not run the hook and keep their hits, as before. A VAE
that refuses the hook is never cached. The per-render cost is one
attribute read; the hooks are registered once per VAE.

`UNSLOTH_REFERENCE_VAE_CACHE=0` still turns the cache off.

## Tests

`studio/backend/tests/test_diffusion_reference_cache.py`:
- `test_assigned_weights_encode_again`: `assign=True` on the whole VAE
and on `vae.decoder` both encode again and equal a fresh encode. Fails
on main (stale latents), passes here.
- `test_a_vae_that_takes_no_hooks_is_never_cached`: a VAE that refuses
the hook bypasses the cache.

CPU, diffusers 0.42.1 / torch 2.10 and diffusers 0.41.0 / torch 2.10
(cpu): main 2 failed / 8 passed, this branch 10 passed on both.
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