Skip to content

Studio: a denoiser-only LoRA change keeps the cached text embeddings - #17105

Merged
danielhanchen merged 5 commits into
mainfrom
studio-prompt-cache-denoiser-lora-key
Nov 8, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
studio-prompt-cache-denoiser-lora-key

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 8, 2026 •

Copy link
Copy Markdown
Member

Summary

Studio's text-embedding cache (diffusion_prompt_cache) included the whole attached LoRA selection (name, path, strength) in every cache key. As a result, a strength sweep with an adapter that only patches the transformer re-ran the text encoder for the same prompt at every new strength, even though the embeddings cannot change. On an offloaded Qwen-Image text encoder, that is one full encoder pass per strength step.

Changes

An adapter is now left out of the key only when both of these hold:

  1. Every component it patches is a denoiser (transformer, transformer_2, unet, ...). The components come from:
    • diffusers' get_list_adapters()
    • the LoKR slots' roots
    • adapters merged into quantised denoiser weights (diffusion_lora_quant_merge), which by construction live only in the denoisers.
  2. The pipeline's encode provably runs no denoiser. This is a static read, done once at install, of the class's encode_prompt body and every self method it calls. The check fails (and the encode keeps the full key) if any of these appear:
    • a denoiser attribute other than .dtype / .device / .config
    • self handed to another callable
    • getattr(self, ...)
    • super()
    • an instance-level override

Everything else keeps today's key:

  • text-encoder adapters
  • one file patching both a denoiser and a text encoder
  • adapters with no recorded component
  • encodes that cannot be proven

Textual-inversion embeddings stay in the key as before.

In diffusers 0.42.1, the check proves these encodes, among others:

  • Qwen-Image / Qwen-Image 2.1 / Edit Plus
  • FLUX.1, FLUX.2
  • SDXL, SD3, Chroma
  • Z-Image, Wan, HiDream, Krea 2

It keeps the full key for:

  • FLUX.3 (its encode builds the modular pipeline)
  • SD 1.5, PixArt, Lumina 2, HunyuanDiT

Kill switch: UNSLOTH_DIFFUSION_TE_SCOPED_LORA_KEY=0.

Evidence

Real tiny QwenImagePipeline (CPU), a transformer LoRA, strengths 0.25 / 0.5 / 0.75 / 1.0 / 0.5:

Arm text-encoder forwards embeddings vs uncached encode
main 4 bit-equal
this PR 1 bit-equal

New tests in tests/test_diffusion_prompt_cache.py cover:

  • the sweep (1 encode instead of 5)
  • text-encoder, mixed and unclassified adapters still missing
  • an encode that runs the transformer still missing
  • a .dtype read allowed
  • quant-merged adapters
  • an instance override
  • super() / dynamic getattr / self-to-helper / indirect denoiser calls being unprovable
  • the kill switch

Result: 40 passed, 1 skipped. On main, 5 of the new tests fail.

Follow-up: helpers the check cannot see

The check used to follow class methods only, so two cases slipped through and reused stale embeddings after a denoiser change:

  • a helper replaced on the instance (pipe._embed = ...) that reads the denoiser
  • a property or other descriptor that reads the denoiser

Now the check:

  • examines a property's getter like any method (the base pipeline's own _execution_device / device / dtype properties are known not to run a layer)
  • keeps the full LoRA key for any other descriptor, for an instance override of any followed name, and for a function stored on the instance and called from the encode

Repro (custom pipe, transformer-only adapter, strength 0.25 then 0.75, denoiser weight changed to match):

Arm instance-patched helper property reading the denoiser
before this follow-up [0.25, 0.25], 1 encode [0.25, 0.25], 1 encode
now [0.25, 0.75], 2 encodes [0.25, 0.75], 2 encodes

Stock pipelines keep the optimization: over every diffusers 0.42.1 pipeline class with an encode_prompt (225), the check returns the same answer before and after (144 skip the denoiser adapters, 0 moved), and no pipeline's __init__ sets an attribute that shadows a followed name. 3 new tests fail before the follow-up and pass after (44 passed, 1 skipped; same on diffusers 0.41.0).

The prompt cache keyed every entry on the whole attached LoRA selection, so a
strength sweep of a transformer-only adapter re-ran the text encoder for an
unchanged prompt. Leave an adapter out of the key when every component it
patches is a denoiser and the pipeline's encode provably runs no denoiser
(static read of the class body and the self methods it calls). Text-encoder,
mixed and unclassified adapters, and encodes that cannot be proven, keep the
full key. UNSLOTH_DIFFUSION_TE_SCOPED_LORA_KEY=0 restores it everywhere.
@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-08T12:16:07.323450Z 6352cdc 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. Swish!

Reviewed commit: a1be899394

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

…ce overrides

The static check behind the denoiser-only prompt-cache key followed class methods only.
A helper replaced on the instance, or a property or other descriptor reading the denoiser,
escaped it and the scoped key reused stale embeddings. Properties are now examined (the
base pipeline's own device/dtype properties are known inert), other descriptors and
instance overrides of followed names keep the full LoRA key.

[skip ci]
@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. 🎉

Reviewed commit: 6352cdc846

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

Copy link
Copy Markdown
Member Author

Source lint fails on this PR at its Import-hoist / alias-rename safety (changed Python files) step. This is separate from main. The verifier flags a name that is undefined after the change:

=== studio/backend/tests/test_diffusion_prompt_cache.py: BLOCKERS ===
  [BLOCKER] ... UNRESOLVED-NEW '_run' in scope <module>.test_the_static_check_on_real_pipelines._Helper.encode_prompt

return _run(self, prompt) # noqa: F821 in that fixture is deliberate, since the static check should see self handed to something it cannot follow. But verify_import_hoist.py has no opt-out comment, so it reads the name as a dangling alias. Binding it in the test keeps the case just as unprovable for the static check. For example, add a module-level def _run(helper, prompt): ... stub, or _run = object() inside test_the_static_check_on_real_pipelines before the class, and drop the noqa. That should clear the step.

@danielhanchen
danielhanchen merged commit 4db4ac0 into main Nov 8, 2026
@danielhanchen
danielhanchen deleted the studio-prompt-cache-denoiser-lora-key branch November 8, 2026 20:26
danielhanchen added a commit to NilayYadav/unsloth that referenced this pull request Nov 9, 2026
…the no-K/V wrapper, and key callable helpers fully (unslothai#17192)

## What happened

unslothai#17105 made the prompt cache drop denoiser-only LoRA adapters from its
key when a static check proves `encode_prompt` never runs a denoiser, so
a strength sweep on a transformer-only LoRA reuses the text embeddings
instead of re-running the text encoder.

Two gaps showed up on current main:

1. **Qwen-Image-2.1 lost the reuse.** unslothai#17118 later installed an
instance-level `_get_qwen_prompt_embeds` wrapper (it runs the text
encoder with `use_cache=False`) before `prompt_cache.install`. The check
treats any instance-level function as unprovable, so for the real
`QwenImage21Pipeline` it went from `True` to `False` once the wrapper
was installed, and every strength change re-ran the encoder again.
Embeddings stayed correct; only the saving was gone.
2. **Callable objects were not followed.** An instance attribute that is
an object with `__call__`, or an `nn.Module` that contains the denoiser,
was treated as plain data. A helper like that which reads the
transformer returned the first strength's embeddings for every later
strength (`[0.25, 0.25]` with one encode, against `[0.25, 0.75]` with
two encodes before unslothai#17105).

## Fix

- The no-K/V wrapper is marked as forwarding only to the same-named
class method. The check accepts a marked instance attribute only when
the unwrapped target is that instance's own bound class method, then
follows the class method as before. An unmarked wrapper, or a marked one
around anything else, still keeps the full key.
- A callable instance attribute now keeps the full key unless it is an
`nn.Module` that holds no denoiser (text encoders) or a tokenizer /
processor / image processor / feature extractor.

The check runs once when the cache is installed, so render-time cost is
unchanged and nothing compiled is touched.
`UNSLOTH_DIFFUSION_TE_SCOPED_LORA_KEY=0` still turns the scoped key off
entirely.

## Tests

New cases in `studio/backend/tests/test_diffusion_prompt_cache.py`: the
real no-K/V wrapper installed before the cache on a Qwen-Image-2.1
shaped pipeline and on the real `QwenImage21Pipeline` class (one encode
across a strength sweep), unmarked and mis-marked wrappers,
callable-object and denoiser-holding module helpers (two encodes, fresh
values), and a check that each run imports its own tree.

On main 5 of them fail; on this branch the file passes (55 passed, 1
CUDA-only skip, diffusers 0.42.1, CPU).
`test_diffusion_qwenimage21_te_no_kv.py` and
`test_shared_memory_offload_keeps_the_prompt_cache.py` also pass.
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