Repository navigation
Studio Qwen-Image-2.1: reuse an unchanged condition image's VAE latents across renders - #17092
Conversation
…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.
Codex Review Summary: ✅ CompletedThis 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. |
[skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. 👍 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". |
…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.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Can't wait for the next one! 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". |
…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.
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:_encode_vae_imagewith a host-memory LRU (16 entries, 256 MiB; a 1024 px reference is about 0.5 MiB of latents).encode/forwardoverrides on the VAE or its encoder, the VAE config (solatents_mean/latents_stdchanges encode again),latent_channels, a weight revision (the summed version counters of its parameters and buffers, soload_state_dictor 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.QwenImage21Pipelineand only when the installed pipeline's_encode_vae_imagesource reads the posterior mode and never samples. Bypassed with grad enabled.UNSLOTH_REFERENCE_VAE_CACHE=0encodes 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 randomAutoencoderKLQwenImage21through the realprepare_latents):_encode_vae_imageis 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_latentswith a full-sizeAutoencoderKLQwenImage21(default config, random weights, float16), 1024 px references, six calls each with a new generator seed (a seed-only rerender loop). Base = merge base6244269, interleaved, 3 reps per arm.UNSLOTH_REFERENCE_VAE_CACHE=0The 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
prepare_latents.