Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio Qwen-Image-2.1: encode prompts without the text encoder's unused K/V cache (#17118)

Daniel Hanbc8d97074077
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index a0b070dde73..3d0c22fbb72 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -11128,6 +11128,9 @@ class DiffusionBackend:
from .diffusion_qwenimage21_vision import configure_vision_attention
configure_vision_attention(pipe, family = fam.name, target = target, logger = logger)
+ from .diffusion_qwenimage21_te import skip_text_encoder_kv_cache
+
+ skip_text_encoder_kv_cache(pipe, logger = logger)
# After the TE quant, so the cache key reflects the encoders that run.
cond_cache.install(
diff --git a/studio/backend/core/inference/diffusion_qwenimage21_te.py b/studio/backend/core/inference/diffusion_qwenimage21_te.py
new file mode 100644
index 00000000000..b826be4875d
--- /dev/null
+++ b/studio/backend/core/inference/diffusion_qwenimage21_te.py
@@ -0,0 +1,61 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Qwen-Image-2.1 prompt encoding without the text encoder's K/V cache (UNSLOTH_QWEN21_TE_NO_KV=0 disables): the
+pipeline's one hidden-state forward never passes ``use_cache``, so the config default built a cache nobody reads."""
+
+from __future__ import annotations
+
+import functools
+import os
+from typing import Any
+
+_ENV = "UNSLOTH_QWEN21_TE_NO_KV"
+_MARK = "_unsloth_te_no_kv"
+
+
+def _enabled() -> bool:
+ return (os.environ.get(_ENV) or "1").strip().lower() not in ("0", "false", "off", "no")
+
+
+def _no_cache(module: Any, args: tuple, kwargs: dict) -> tuple:
+ kwargs["use_cache"] = False
+ return args, kwargs
+
+
+def skip_text_encoder_kv_cache(pipe: Any, logger: Any = None) -> bool:
+ """Wrap ``pipe._get_qwen_prompt_embeds`` so its encoder forward runs with ``use_cache=False``. Idempotent."""
+ if not _enabled():
+ return False
+ encoder = getattr(pipe, "text_encoder", None)
+ original = getattr(pipe, "_get_qwen_prompt_embeds", None)
+ if (
+ encoder is None
+ or not callable(original)
+ or not type(encoder).__name__.startswith("Qwen3VL")
+ ):
+ return False
+ if getattr(original, _MARK, False):
+ return True
+ if not hasattr(encoder, "register_forward_pre_hook"):
+ return False
+
+ @functools.wraps(original)
+ def _get_qwen_prompt_embeds(*args: Any, **kwargs: Any) -> Any:
+ # read at call time: a later load step may swap in a quantised copy
+ current = getattr(pipe, "text_encoder", None)
+ if not hasattr(current, "register_forward_pre_hook"):
+ return original(*args, **kwargs)
+ handle = current.register_forward_pre_hook(_no_cache, with_kwargs = True)
+ try:
+ return original(*args, **kwargs)
+ finally:
+ handle.remove()
+
+ setattr(_get_qwen_prompt_embeds, _MARK, True)
+ pipe._get_qwen_prompt_embeds = _get_qwen_prompt_embeds
+ if logger is not None:
+ logger.info(
+ "diffusion.qwen_image_21: prompt encoding skips the text encoder's unused K/V cache"
+ )
+ return True
diff --git a/studio/backend/tests/test_diffusion_qwenimage21_te_no_kv.py b/studio/backend/tests/test_diffusion_qwenimage21_te_no_kv.py
new file mode 100644
index 00000000000..fbba2690f36
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_qwenimage21_te_no_kv.py
@@ -0,0 +1,145 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Qwen-Image-2.1 prompt encoding builds no text-encoder K/V cache and returns the same embeddings. Runs on CPU."""
+
+from __future__ import annotations
+
+import pytest
+
+torch = pytest.importorskip("torch")
+pytest.importorskip("transformers.models.qwen3_vl")
+q21 = pytest.importorskip("diffusers.pipelines.qwenimage21.pipeline_qwenimage21")
+
+from core.inference import diffusion_qwenimage21_te as te # noqa: E402
+
+VOCAB, HIDDEN, IMG_PAD = 512, 128, 7
+
+
+def _encoder():
+ from transformers import Qwen3VLForConditionalGeneration
+ from transformers.models.qwen3_vl.configuration_qwen3_vl import (
+ Qwen3VLConfig,
+ Qwen3VLTextConfig,
+ Qwen3VLVisionConfig,
+ )
+
+ config = Qwen3VLConfig(
+ vision_config = Qwen3VLVisionConfig(
+ depth = 1,
+ hidden_size = 32,
+ intermediate_size = 64,
+ num_heads = 4,
+ out_hidden_size = HIDDEN,
+ deepstack_visual_indexes = [],
+ ).to_dict(),
+ text_config = Qwen3VLTextConfig(
+ hidden_size = HIDDEN,
+ intermediate_size = 256,
+ num_hidden_layers = 3,
+ num_attention_heads = 4,
+ num_key_value_heads = 2,
+ head_dim = 32,
+ vocab_size = VOCAB,
+ use_cache = True,
+ rope_scaling = {
+ "rope_type": "default",
+ "mrope_section": [8, 4, 4],
+ "mrope_interleaved": True,
+ },
+ ).to_dict(),
+ )
+ config._attn_implementation = "sdpa"
+ torch.manual_seed(0)
+ return Qwen3VLForConditionalGeneration(config).eval()
+
+
+class _Inputs(dict):
+ def __getattr__(self, name):
+ try:
+ return self[name]
+ except KeyError:
+ raise AttributeError(name) from None
+
+ def to(self, device):
+ return self
+
+
+class _Processor:
+ def __call__(self, text, **kwargs):
+ ids = torch.stack([(torch.arange(40) * (7 + len(t)) % (VOCAB - 10)) + 10 for t in text])
+ return _Inputs(input_ids = ids, attention_mask = torch.ones_like(ids))
+
+
+class _Pipe:
+ """The real pipeline's encoding methods on a hand-built instance (no transformer / VAE / scheduler)."""
+
+ _get_qwen_prompt_embeds = q21.QwenImage21Pipeline._get_qwen_prompt_embeds
+ _extract_masked_hidden = q21.QwenImage21Pipeline._extract_masked_hidden
+
+ def __init__(self):
+ self.text_encoder = _encoder()
+ self.processor = _Processor()
+ self.prompt_template_t2i = "<s>{}</s>"
+ self._drop_idx = 4
+ self._img_token_id = IMG_PAD
+
+
[email protected](autouse = True)
+def _env(monkeypatch):
+ monkeypatch.delenv(te._ENV, raising = False)
+
+
+def _encode(pipe):
+ caches = []
+ hook = pipe.text_encoder.register_forward_hook(
+ lambda module, args, output: caches.append(getattr(output, "past_key_values", None))
+ )
+ try:
+ with torch.no_grad():
+ out = pipe._get_qwen_prompt_embeds(
+ ["a red fox", "a long prompt about a city"], device = "cpu"
+ )
+ finally:
+ hook.remove()
+ return out, caches
+
+
+def test_prompt_encoding_builds_no_kv_cache_and_keeps_the_embeddings_bitwise():
+ pipe = _Pipe()
+ (embeds, mask, pad), caches = _encode(pipe)
+ assert caches[0] is not None # the stock call builds a cache the pipeline never reads
+
+ assert te.skip_text_encoder_kv_cache(pipe) is True
+ (embeds2, mask2, pad2), caches2 = _encode(pipe)
+ assert caches2 == [None]
+ assert torch.equal(embeds2.view(torch.int32), embeds.view(torch.int32))
+ assert torch.equal(mask2, mask) and torch.equal(pad2, pad)
+ # only this call: a direct forward of the same encoder still caches as configured
+ with torch.no_grad():
+ direct = pipe.text_encoder(input_ids = torch.tensor([[11, 12, 13]]))
+ assert direct.past_key_values is not None
+
+
+def test_install_is_idempotent_and_the_kill_switch_keeps_the_stock_call(monkeypatch):
+ pipe = _Pipe()
+ assert te.skip_text_encoder_kv_cache(pipe) is True
+ wrapped = pipe._get_qwen_prompt_embeds
+ assert te.skip_text_encoder_kv_cache(pipe) is True and pipe._get_qwen_prompt_embeds is wrapped
+
+ monkeypatch.setenv(te._ENV, "0")
+ stock = _Pipe()
+ assert te.skip_text_encoder_kv_cache(stock) is False
+ assert _encode(stock)[1][0] is not None
+
+
+def test_other_pipelines_are_left_alone():
+ class _Other:
+ text_encoder = torch.nn.Linear(2, 2)
+
+ def _get_qwen_prompt_embeds(self):
+ return None
+
+ other = _Other()
+ assert te.skip_text_encoder_kv_cache(other) is False
+ assert te.skip_text_encoder_kv_cache(object()) is False