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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio video: cache Wan text encodes per text so an unchanged negative prompt is encoded once (#15166)
Daniel Hana218851e3826
diff --git a/studio/backend/core/inference/diffusion_prompt_cache.py b/studio/backend/core/inference/diffusion_prompt_cache.pyindex a8df329df67..1a759d4bf6e 100644--- a/studio/backend/core/inference/diffusion_prompt_cache.py+++ b/studio/backend/core/inference/diffusion_prompt_cache.py@@ -24,6 +24,9 @@ _DEFAULT_BUDGET_MB = 256_FALSE_TOKENS = ("0", "false", "no", "off")_KEY_EXCLUDED_ARGS = frozenset({"device", "generator"})+# Wan encodes prompt and negative separately; caching per text reuses the unchanged negative. "0" = pair key only.+_ENV_PER_TEXT = "UNSLOTH_DIFFUSION_PROMPT_CACHE_PER_TEXT"+_PER_TEXT_METHODS = {"Wan": "_get_t5_prompt_embeds"}_TEXT_ENCODER_ATTRS = ("text_encoder", "text_encoder_2", "text_encoder_3", "text_encoder_4")@@ -255,6 +258,9 @@ def install(return Falseload_fp = _plain(identity or {})wrapped = _wrap_encode_prompt(pipe, cache, load_fp, lora_owner or pipe, logger)+ per_text = _per_text_method(pipe)+ if wrapped and per_text is not None:+ _wrap_encode_prompt(pipe, cache, load_fp, lora_owner or pipe, logger, name = per_text)registered = _register_h3(pipe, cache, load_fp, logger)if not (wrapped or registered):return False@@ -278,10 +284,26 @@ def release(pipe: Any) -> None:cache.clear()+def _per_text_method(pipe: Any) -> Optional[str]:+ if (os.environ.get(_ENV_PER_TEXT) or "").strip().lower() in _FALSE_TOKENS:+ return None+ cls = type(pipe).__name__+ for prefix, name in _PER_TEXT_METHODS.items():+ if cls.startswith(prefix) and callable(getattr(pipe, name, None)):+ return name+ return None++def _wrap_encode_prompt(- pipe: Any, cache: PromptCache, load_fp: Any, lora_owner: Any, logger: Any+ pipe: Any,+ cache: PromptCache,+ load_fp: Any,+ lora_owner: Any,+ logger: Any,+ *,+ name: str = "encode_prompt",) -> bool:- encode = getattr(pipe, "encode_prompt", None)+ encode = getattr(pipe, name, None)if not callable(encode):return Falsetry:@@ -303,6 +325,8 @@ def _wrap_encode_prompt("loras": _lora_state(lora_owner),"args": keyed,}+ if name != "encode_prompt":+ payload["method"] = name# Textual-inversion embeddings change what the same text encodes to; absent = the unchanged key.embeddings = _embedding_state(pipe)if embeddings:@@ -330,7 +354,7 @@ def _wrap_encode_prompt(cached_encode_prompt.__signature__ = signaturecached_encode_prompt.__wrapped__ = encode- pipe.encode_prompt = cached_encode_prompt+ setattr(pipe, name, cached_encode_prompt)return Truediff --git a/studio/backend/tests/test_diffusion_prompt_cache.py b/studio/backend/tests/test_diffusion_prompt_cache.pyindex 86304bfa479..e31d54dba03 100644--- a/studio/backend/tests/test_diffusion_prompt_cache.py+++ b/studio/backend/tests/test_diffusion_prompt_cache.py@@ -492,3 +492,62 @@ def test_failed_lookup_encoder_error_is_not_chained(monkeypatch):with pytest.raises(RuntimeError) as info:pipe.encode_prompt("a cat")assert info.value.__context__ is None+++class WanStubPipeline:+ """Wan's shape: encode_prompt calls _get_t5_prompt_embeds once per text (prompt, then negative)."""++ def __init__(self):+ self.t5_calls = []+ self._execution_device = torch.device("cpu")+ self.text_encoder = torch.nn.Linear(2, 2)++ def _get_t5_prompt_embeds(+ self,+ prompt = None,+ num_videos_per_prompt = 1,+ max_sequence_length = 226,+ device = None,+ dtype = None,+ ):+ self.t5_calls.append(prompt)+ return torch.full((num_videos_per_prompt, 3), float(sum(map(ord, str(prompt)))))++ def encode_prompt(+ self,+ prompt,+ negative_prompt = None,+ do_classifier_free_guidance = True,+ device = None,+ dtype = None,+ ):+ pos = self._get_t5_prompt_embeds(prompt = prompt, device = device, dtype = dtype)+ neg = self._get_t5_prompt_embeds(prompt = negative_prompt, device = device, dtype = dtype)+ return pos, neg+++def test_wan_negative_prompt_is_encoded_once_across_new_prompts():+ pipe = WanStubPipeline()+ assert prompt_cache.install(pipe)+ want = WanStubPipeline()+ for text in ("a cat", "a dog", "a boat"):+ got = pipe.encode_prompt(text, negative_prompt = "blurry")+ ref = want.encode_prompt(text, negative_prompt = "blurry")+ assert all(torch.equal(a, b) for a, b in zip(got, ref))+ assert pipe.t5_calls == ["a cat", "blurry", "a dog", "a boat"]+++def test_wan_per_text_cache_kill_switch(monkeypatch):+ monkeypatch.setenv("UNSLOTH_DIFFUSION_PROMPT_CACHE_PER_TEXT", "0")+ pipe = WanStubPipeline()+ assert prompt_cache.install(pipe)+ for text in ("a cat", "a dog"):+ pipe.encode_prompt(text, negative_prompt = "blurry")+ assert pipe.t5_calls == ["a cat", "blurry", "a dog", "blurry"]+++def test_per_text_cache_is_wan_only():+ pipe = _EncodePipe()+ pipe._get_t5_prompt_embeds = lambda **kw: None+ assert prompt_cache._per_text_method(pipe) is None+ assert prompt_cache._per_text_method(WanStubPipeline()) == "_get_t5_prompt_embeds"