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: cache text-encoder outputs so repeat prompts skip the encoder (#11844)

Daniel Han0df4178c0a74
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 89d88ebd30d..28cecbb4b9f 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -148,6 +148,7 @@ from .diffusion_attention import (
)
from . import diffusion_compile_cache as compile_cache
from . import diffusion_cond_cache as cond_cache
+from . import diffusion_prompt_cache as prompt_cache
from . import diffusion_gguf_compile as gguf_compile
from . import diffusion_cuda_graph as cuda_graph
from .diffusion_batched import (
@@ -5786,6 +5787,18 @@ class DiffusionBackend:
te_quant = te_quant,
logger = logger,
)
+ # Outermost, so a repeat skips both the disk cache and the encoders.
+ prompt_cache.install(
+ pipe,
+ identity = {
+ "family": fam.name,
+ "repo": str(repo_id),
+ "base": str(base or repo_id),
+ "dtype": str(dtype),
+ "te_quant": str(te_quant),
+ },
+ logger = logger,
+ )
# Apply the planned placement; apply_memory_plan returns what ACTUALLY engaged so status stays
# honest.
@@ -6655,6 +6668,16 @@ class DiffusionBackend:
import diffusers
pipe = self._from_pipe_no_recast(state.pipe, getattr(diffusers, class_name))
+ prompt_cache.install(
+ pipe,
+ identity = {
+ "family": state.family.name,
+ "repo": str(state.repo_id),
+ "workflow": class_name,
+ },
+ lora_owner = state.pipe,
+ logger = logger,
+ )
# Publish to the shared aux cache only if THIS load is still current: from_pipe runs without _lock, so an
# unload can null _state and caching would hand out stale modules.
with self._lock:
@@ -6729,6 +6752,17 @@ class DiffusionBackend:
pipe = self._from_pipe_no_recast(
state.pipe, getattr(diffusers, pipe_cls_name), controlnet = cn_model
)
+ # from_pipe copies components, not the base pipe's wrapped encode_prompt.
+ prompt_cache.install(
+ pipe,
+ identity = {
+ "family": fam.name,
+ "repo": str(getattr(state, "repo_id", "")),
+ "workflow": pipe_cls_name,
+ },
+ lora_owner = state.pipe,
+ logger = logger,
+ )
with self._lock:
# Same race as the model cache: an unload may have cleared _cn_pipes while from_pipe ran.
if cancel.is_set() or self._state is not state:
@@ -7869,6 +7903,9 @@ class DiffusionBackend:
compile_cache.restore(state.compile_cache_ctx, logger = logger)
# Before clear_gpu_cache(), or the graph pool stays reserved for the life of the process.
cuda_graph.uninstall_all(state.cuda_graphs)
+ prompt_cache.release(state.pipe)
+ for aux in (*self._aux_pipes.values(), *self._cn_pipes.values()):
+ prompt_cache.release(aux)
gguf_compile.uninstall_all()
if state.eager_patched:
# Lazy import to keep diffusion.py torch-free to import.
diff --git a/studio/backend/core/inference/diffusion_prompt_cache.py b/studio/backend/core/inference/diffusion_prompt_cache.py
new file mode 100644
index 00000000000..02572af0757
--- /dev/null
+++ b/studio/backend/core/inference/diffusion_prompt_cache.py
@@ -0,0 +1,408 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""In-memory, host-RAM LRU of text-encoder outputs for diffusion/video pipes.
+
+``UNSLOTH_DIFFUSION_PROMPT_CACHE=0`` disables; ``UNSLOTH_DIFFUSION_PROMPT_CACHE_MB`` (default 256, capped on
+small hosts) bounds it. Hits return fresh copies so in-place edits cannot poison later renders.
+"""
+
+from __future__ import annotations
+
+import collections
+import hashlib
+import inspect
+import json
+import os
+import threading
+import weakref
+from typing import Any, Optional
+
+_ENV_ENABLE = "UNSLOTH_DIFFUSION_PROMPT_CACHE"
+_ENV_BUDGET_MB = "UNSLOTH_DIFFUSION_PROMPT_CACHE_MB"
+_DEFAULT_BUDGET_MB = 256
+_FALSE_TOKENS = ("0", "false", "no", "off")
+
+_KEY_EXCLUDED_ARGS = frozenset({"device", "generator"})
+_TEXT_ENCODER_ATTRS = ("text_encoder", "text_encoder_2", "text_encoder_3", "text_encoder_4")
+
+
+def enabled() -> bool:
+ return (os.environ.get(_ENV_ENABLE) or "").strip().lower() not in _FALSE_TOKENS
+
+
+def budget_bytes() -> int:
+ raw = (os.environ.get(_ENV_BUDGET_MB) or "").strip()
+ try:
+ mb = float(raw) if raw else float(_DEFAULT_BUDGET_MB)
+ except ValueError:
+ mb = float(_DEFAULT_BUDGET_MB)
+ raw = "" # malformed = unset, so the automatic cap still applies
+ budget = int(max(0.0, mb) * 1024 * 1024)
+ if not raw:
+ total = _host_ram_bytes()
+ if total:
+ budget = min(budget, max(16 * 1024 * 1024, total // 64))
+ return budget
+
+
+def _host_ram_bytes() -> int:
+ """Entries live in host RAM, so an enforcing cgroup limit caps the budget too."""
+ try:
+ total = int(os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES"))
+ except (AttributeError, ValueError, OSError):
+ total = 0
+ try:
+ from .diffusion_memory import _cgroup_memory_limit_mib
+ limit_mib = _cgroup_memory_limit_mib()
+ except Exception: # noqa: BLE001 - unreadable means no limit
+ limit_mib = None
+ if limit_mib:
+ limit = int(limit_mib) * 1024 * 1024
+ total = min(total, limit) if total else limit
+ return total
+
+
+def _torch():
+ import torch
+ return torch
+
+
+def _plain(value: Any) -> Any:
+ if value is None or isinstance(value, (bool, int, float, str)):
+ return value
+ if isinstance(value, (list, tuple)):
+ return [_plain(v) for v in value]
+ if isinstance(value, dict):
+ return {str(k): _plain(v) for k, v in value.items()}
+ torch = _torch()
+ if isinstance(value, (torch.dtype, torch.device)):
+ return str(value)
+ raise TypeError(type(value).__name__)
+
+
+def _is_tensor(obj: Any) -> bool:
+ return hasattr(obj, "detach") and hasattr(obj, "clone") and hasattr(obj, "element_size")
+
+
+def _map_tensors(obj: Any, fn: Any) -> Any:
+ if _is_tensor(obj):
+ return fn(obj)
+ if isinstance(obj, tuple):
+ return tuple(_map_tensors(o, fn) for o in obj)
+ if isinstance(obj, list):
+ return [_map_tensors(o, fn) for o in obj]
+ if isinstance(obj, dict) and type(obj) is dict:
+ return {k: _map_tensors(v, fn) for k, v in obj.items()}
+ if obj is None or isinstance(obj, (bool, int, float, str)):
+ return obj
+ raise TypeError(type(obj).__name__)
+
+
+def _nbytes(obj: Any) -> int:
+ total = [0]
+
+ def count(t: Any) -> Any:
+ total[0] += int(t.numel()) * int(t.element_size())
+ return t
+
+ _map_tensors(obj, count)
+ return total[0]
+
+
+class PromptCache:
+ def __init__(self, budget: Optional[int] = None) -> None:
+ self.budget = budget_bytes() if budget is None else int(budget)
+ self._entries: "collections.OrderedDict[str, tuple[Any, int]]" = collections.OrderedDict()
+ self._lock = threading.Lock()
+ self.bytes = 0
+ self.stats = {"hits": 0, "misses": 0, "bypassed": 0, "evictions": 0, "stored": 0}
+
+ def get(self, key: str, device: Any) -> Any:
+ with self._lock:
+ entry = self._entries.get(key)
+ if entry is None:
+ return None
+ self._entries.move_to_end(key)
+ self.stats["hits"] += 1
+ stored = entry[0]
+ return _map_tensors(stored, lambda t: _fresh(t, device))
+
+ def put(self, key: str, result: Any) -> bool:
+ try:
+ size = _nbytes(result)
+ except TypeError:
+ return False
+ if size <= 0 or size > self.budget:
+ return False
+ stored = _map_tensors(result, _store_copy)
+ with self._lock:
+ old = self._entries.pop(key, None)
+ if old is not None:
+ self.bytes -= old[1]
+ self._entries[key] = (stored, size)
+ self.bytes += size
+ self.stats["stored"] += 1
+ while self.bytes > self.budget and self._entries:
+ _, (_, dropped) = self._entries.popitem(last = False)
+ self.bytes -= dropped
+ self.stats["evictions"] += 1
+ return True
+
+ def clear(self) -> None:
+ with self._lock:
+ self._entries.clear()
+ self.bytes = 0
+
+ def __len__(self) -> int:
+ return len(self._entries)
+
+ def describe(self) -> dict:
+ with self._lock:
+ return {
+ "entries": len(self._entries),
+ "bytes": self.bytes,
+ "budget": self.budget,
+ **self.stats,
+ }
+
+
+def _store_copy(t: Any) -> Any:
+ t = t.detach()
+ device = t.device
+ # Not pinned: pin_memory() is a fresh cudaHostAlloc per entry (60 ms to 1.6 s for 4 MB on a busy host) to save
+ # ~0.3 ms per hit.
+ stored = t.to("cpu", copy = True)
+ stored._unsloth_src_device = device
+ return stored
+
+
+def _fresh(t: Any, device: Any) -> Any:
+ target = device if device is not None else getattr(t, "_unsloth_src_device", t.device)
+ torch = _torch()
+ target = torch.device(target)
+ if target.type == t.device.type and (target.index is None or target.index == t.device.index):
+ return t.clone()
+ return t.to(target, copy = True)
+
+
+def _encoder_identity(pipe: Any) -> list:
+ ident = []
+ for attr in _TEXT_ENCODER_ATTRS:
+ module = getattr(pipe, attr, None)
+ if module is not None:
+ ident.append([attr, type(module).__name__, id(module)])
+ return ident
+
+
+def _lora_state(pipe: Any) -> Any:
+ try:
+ return _plain(tuple(getattr(pipe, "_unsloth_loras", ()) or ()))
+ except TypeError:
+ return None
+
+
+def _hash(payload: dict) -> str:
+ raw = json.dumps(payload, sort_keys = True, separators = (",", ":"))
+ return hashlib.sha256(raw.encode("utf-8")).hexdigest()
+
+
+def cache_for(pipe: Any) -> Optional[PromptCache]:
+ return getattr(pipe, "_unsloth_prompt_cache", None)
+
+
+def install(
+ pipe: Any,
+ *,
+ identity: Optional[dict] = None,
+ lora_owner: Any = None,
+ logger: Any = None,
+) -> bool:
+ """``lora_owner``: the ``from_pipe`` source that tracks adapters; its store is shared."""
+ if not enabled() or pipe is None:
+ return False
+ if cache_for(pipe) is not None:
+ return True
+ cache = cache_for(lora_owner) if lora_owner is not None else None
+ try:
+ if cache is None:
+ cache = PromptCache()
+ except Exception as exc: # noqa: BLE001 - optimisation only
+ _warn(logger, "setup", exc)
+ return False
+ if cache.budget <= 0:
+ return False
+ load_fp = _plain(identity or {})
+ wrapped = _wrap_encode_prompt(pipe, cache, load_fp, lora_owner or pipe, logger)
+ registered = _register_h3(pipe, cache, load_fp, logger)
+ if not (wrapped or registered):
+ return False
+ try:
+ pipe._unsloth_prompt_cache = cache
+ except Exception as exc: # noqa: BLE001
+ _warn(logger, "attach", exc)
+ return False
+ if logger is not None:
+ logger.info(
+ "diffusion.prompt_cache: on (%.0f MB budget; %s)",
+ cache.budget / 1024**2,
+ "encode_prompt" if wrapped else "modular text encoder",
+ )
+ return True
+
+
+def release(pipe: Any) -> None:
+ cache = cache_for(pipe)
+ if cache is not None:
+ cache.clear()
+
+
+def _wrap_encode_prompt(
+ pipe: Any, cache: PromptCache, load_fp: Any, lora_owner: Any, logger: Any
+) -> bool:
+ encode = getattr(pipe, "encode_prompt", None)
+ if not callable(encode):
+ return False
+ try:
+ signature = inspect.signature(encode)
+ except (TypeError, ValueError):
+ return False
+
+ def cached_encode_prompt(*args: Any, **kwargs: Any) -> Any:
+ try:
+ bound = signature.bind(*args, **kwargs)
+ bound.apply_defaults()
+ keyed = {
+ k: _plain(v) for k, v in bound.arguments.items() if k not in _KEY_EXCLUDED_ARGS
+ }
+ key = _hash(
+ {
+ "load": load_fp,
+ "encoders": _encoder_identity(pipe),
+ "loras": _lora_state(lora_owner),
+ "args": keyed,
+ }
+ )
+ hit = cache.get(key, bound.arguments.get("device"))
+ except TypeError:
+ cache.stats["bypassed"] += 1
+ return encode(*args, **kwargs)
+ except Exception as exc: # noqa: BLE001 - never fail a render over the cache
+ _warn(logger, "lookup", exc)
+ return encode(*args, **kwargs)
+ if hit is not None:
+ return hit
+ result = encode(*args, **kwargs)
+ cache.stats["misses"] += 1
+ try:
+ cache.put(key, result)
+ except Exception as exc: # noqa: BLE001 - a failed store only skips reuse
+ _warn(logger, "store", exc)
+ return result
+
+ cached_encode_prompt.__signature__ = signature
+ cached_encode_prompt.__wrapped__ = encode
+ pipe.encode_prompt = cached_encode_prompt
+ return True
+
+
+# MiniMax-H3 steps call this module global, so it is shimmed process-wide and routed per text encoder.
+_H3_MODULE = "diffusers.modular_pipelines.minimax_h3.encoders"
+_H3_FUNC = "get_qwen3vl_prompt_embeds"
+_H3_REGISTRY: "weakref.WeakKeyDictionary" = weakref.WeakKeyDictionary()
+_H3_LOCK = threading.Lock()
+
+
+def _register_h3(pipe: Any, cache: PromptCache, load_fp: Any, logger: Any) -> bool:
+ text_encoder = _modular_text_encoder(pipe)
+ if text_encoder is None:
+ return False
+ try:
+ import importlib
+ module = importlib.import_module(_H3_MODULE)
+ except Exception: # noqa: BLE001 - not an H3-capable diffusers
+ return False
+ with _H3_LOCK:
+ original = getattr(module, _H3_FUNC, None)
+ if not callable(original):
+ return False
+ if not getattr(original, "_unsloth_prompt_cache_shim", False):
+ shim = _make_h3_shim(original, logger)
+ setattr(module, _H3_FUNC, shim)
+ try:
+ _H3_REGISTRY[text_encoder] = (cache, load_fp)
+ except TypeError:
+ return False
+ return True
+
+
+def _modular_text_encoder(pipe: Any) -> Any:
+ if callable(getattr(pipe, "encode_prompt", None)):
+ return None
+ if not hasattr(pipe, "blocks") and "Modular" not in type(pipe).__name__:
+ return None
+ try:
+ return getattr(pipe, "text_encoder", None)
+ except Exception: # noqa: BLE001 - a lazy component that is not loaded
+ return None
+
+
+def _make_h3_shim(original: Any, logger: Any) -> Any:
+ try:
+ signature = inspect.signature(original)
+ except (TypeError, ValueError):
+ signature = None
+
+ def get_qwen3vl_prompt_embeds(*args: Any, **kwargs: Any) -> Any:
+ if signature is None:
+ return original(*args, **kwargs)
+ try:
+ bound = signature.bind(*args, **kwargs)
+ bound.apply_defaults()
+ arguments = bound.arguments
+ text_encoder = arguments.get("text_encoder")
+ registered = _H3_REGISTRY.get(text_encoder) if text_encoder is not None else None
+ except Exception: # noqa: BLE001
+ registered = None
+ if registered is None:
+ return original(*args, **kwargs)
+ cache, load_fp = registered
+ try:
+ if arguments.get("vision_inputs"):
+ raise TypeError("vision inputs")
+ key = _hash(
+ {
+ "load": load_fp,
+ "encoder": [type(text_encoder).__name__, id(text_encoder)],
+ "token_ids": _plain(list(arguments.get("token_ids") or ())),
+ "layer": _plain(arguments.get("text_encoder_layer")),
+ "dtype": _plain(arguments.get("dtype")),
+ }
+ )
+ hit = cache.get(key, arguments.get("device"))
+ except TypeError:
+ cache.stats["bypassed"] += 1
+ return original(*args, **kwargs)
+ except Exception as exc: # noqa: BLE001
+ _warn(logger, "h3 lookup", exc)
+ return original(*args, **kwargs)
+ if hit is not None:
+ return hit
+ result = original(*args, **kwargs)
+ cache.stats["misses"] += 1
+ try:
+ cache.put(key, result)
+ except Exception as exc: # noqa: BLE001
+ _warn(logger, "h3 store", exc)
+ return result
+
+ get_qwen3vl_prompt_embeds._unsloth_prompt_cache_shim = True
+ get_qwen3vl_prompt_embeds.__wrapped__ = original
+ if signature is not None:
+ get_qwen3vl_prompt_embeds.__signature__ = signature
+ return get_qwen3vl_prompt_embeds
+
+
+def _warn(logger: Any, what: str, exc: Any) -> None:
+ if logger is not None:
+ logger.warning("diffusion.prompt_cache: %s failed: %s", what, exc)
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 58c06f7f3f4..79045d828e1 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -4629,6 +4629,19 @@ class VideoBackend:
}
)
+ from . import diffusion_prompt_cache
+
+ diffusion_prompt_cache.install(
+ pipe,
+ identity = {
+ "family": fam.name,
+ "repo": str(repo_id),
+ "base": str(base),
+ "dtype": str(dtype),
+ "te_quant": str(text_encoder_quant_engaged),
+ },
+ logger = logger,
+ )
with self._lock:
if _load_token is not None and _load_token != self._load_token:
del pipe
@@ -5376,6 +5389,20 @@ class VideoBackend:
),
}
)
+ from . import diffusion_prompt_cache
+
+ diffusion_prompt_cache.install(
+ pipe,
+ identity = {
+ "family": fam.name,
+ "repo": str(repo_id),
+ "base": str(base),
+ "dtype": str(dtype),
+ "workflow": str(workflow),
+ "te_quant": str(text_encoder_quant_engaged),
+ },
+ logger = logger,
+ )
with self._lock:
if _load_token is not None and _load_token != self._load_token:
del pipe
@@ -6926,6 +6953,9 @@ class VideoBackend:
from . import diffusion_cuda_graph
diffusion_gguf_compile.uninstall_all()
+ from . import diffusion_prompt_cache
+
+ diffusion_prompt_cache.release(getattr(state, "pipe", None))
# Before clear_gpu_cache(), or the graph pool stays reserved.
diffusion_cuda_graph.uninstall_all(
getattr(getattr(state, "pipe", None), "_unsloth_cuda_graphs", ()) or ()
diff --git a/studio/backend/tests/test_diffusion_prompt_cache.py b/studio/backend/tests/test_diffusion_prompt_cache.py
new file mode 100644
index 00000000000..b3c2434b1ac
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_prompt_cache.py
@@ -0,0 +1,391 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""CPU tests for ``diffusion_prompt_cache.py`` with stub pipes."""
+
+from __future__ import annotations
+
+import sys
+import types
+
+import pytest
+
+torch = pytest.importorskip("torch")
+
+from core.inference import diffusion_cond_cache as cond_cache
+from core.inference import diffusion_prompt_cache as prompt_cache
+
+from .test_diffusion_backend import fake_runtime # noqa: E402,F401
+
+
+class _EncodePipe:
+ def __init__(self, width = 4):
+ self.calls = 0
+ self.width = width
+ self._execution_device = torch.device("cpu")
+ self.text_encoder = torch.nn.Linear(2, 2)
+
+ def encode_prompt(
+ self,
+ prompt,
+ negative_prompt = None,
+ device = None,
+ num_images_per_prompt = 1,
+ max_sequence_length = 256,
+ prompt_embeds = None,
+ image = None,
+ dtype = None,
+ ):
+ if prompt_embeds is not None:
+ return (prompt_embeds, None)
+ self.calls += 1
+ value = float(sum(map(ord, str(prompt)))) + max_sequence_length
+ embeds = torch.full((num_images_per_prompt, self.width), value)
+ neg = None if negative_prompt is None else torch.full((1, self.width), -value)
+ return (
+ embeds,
+ torch.ones(num_images_per_prompt, self.width, dtype = torch.bool),
+ [neg] if neg is not None else None,
+ )
+
+
[email protected](autouse = True)
+def _env(monkeypatch):
+ monkeypatch.delenv("UNSLOTH_DIFFUSION_PROMPT_CACHE", raising = False)
+ monkeypatch.delenv("UNSLOTH_DIFFUSION_PROMPT_CACHE_MB", raising = False)
+ monkeypatch.delenv("UNSLOTH_DIFFUSION_COND_CACHE_DIR", raising = False)
+
+
+def test_repeat_prompt_skips_the_encoder_and_matches_exactly():
+ pipe = _EncodePipe()
+ assert prompt_cache.install(pipe, identity = {"repo": "r"})
+ first = pipe.encode_prompt("a cat", device = "cpu")
+ second = pipe.encode_prompt("a cat", device = "cpu")
+ assert pipe.calls == 1
+ assert torch.equal(first[0], second[0]) and torch.equal(first[1], second[1])
+ assert first[2] is None and second[2] is None
+ assert pipe._unsloth_prompt_cache.describe()["hits"] == 1
+
+
+def test_every_argument_keys_the_entry():
+ pipe = _EncodePipe()
+ prompt_cache.install(pipe)
+ pipe.encode_prompt("a cat")
+ pipe.encode_prompt("a dog")
+ pipe.encode_prompt("a cat", max_sequence_length = 128)
+ pipe.encode_prompt("a cat", num_images_per_prompt = 2)
+ pipe.encode_prompt("a cat", negative_prompt = "blurry")
+ pipe.encode_prompt("a cat", negative_prompt = "ugly")
+ pipe.encode_prompt("a cat", dtype = torch.float16)
+ assert pipe.calls == 7
+ neg = pipe.encode_prompt("a cat", negative_prompt = "blurry")
+ assert pipe.calls == 7 and neg[2][0] is not None
+
+
+def test_device_is_placement_not_key():
+ pipe = _EncodePipe()
+ prompt_cache.install(pipe)
+ pipe.encode_prompt("a cat", device = "cpu")
+ pipe.encode_prompt("a cat", device = torch.device("cpu"))
+ assert pipe.calls == 1
+
+
+def test_hit_returns_fresh_tensors_so_in_place_edits_cannot_poison():
+ pipe = _EncodePipe()
+ prompt_cache.install(pipe)
+ first = pipe.encode_prompt("a cat")
+ reference = first[0].clone()
+ first[0].mul_(0)
+ second = pipe.encode_prompt("a cat")
+ assert torch.equal(second[0], reference)
+ second[0].add_(5)
+ third = pipe.encode_prompt("a cat")
+ assert torch.equal(third[0], reference)
+ assert pipe.calls == 1
+
+
+def test_non_plain_arguments_bypass():
+ pipe = _EncodePipe()
+ prompt_cache.install(pipe)
+ pipe.encode_prompt("a cat", image = object())
+ pipe.encode_prompt("a cat", image = object())
+ assert pipe.calls == 2
+ embeds = torch.zeros(1, 4)
+ out = pipe.encode_prompt("a cat", prompt_embeds = embeds)
+ assert out[0] is embeds
+ assert pipe._unsloth_prompt_cache.describe()["bypassed"] == 3
+
+
+def test_lru_is_bounded_by_bytes(monkeypatch):
+ # Entry = 1024 B float32 embeds + 256 B bool mask = 1280 B.
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_PROMPT_CACHE_MB", str(3000 / 1024 / 1024))
+ pipe = _EncodePipe(width = 256)
+ prompt_cache.install(pipe)
+ cache = pipe._unsloth_prompt_cache
+ pipe.encode_prompt("a")
+ pipe.encode_prompt("b")
+ assert len(cache) == 2 and cache.bytes == 2560
+ pipe.encode_prompt("a") # refresh a, so b is the eviction victim
+ pipe.encode_prompt("c")
+ assert len(cache) == 2 and cache.bytes <= cache.budget
+ assert cache.describe()["evictions"] == 1
+ calls = pipe.calls
+ pipe.encode_prompt("a")
+ assert pipe.calls == calls
+ pipe.encode_prompt("b")
+ assert pipe.calls == calls + 1
+
+
+def test_entry_larger_than_budget_is_not_stored(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_PROMPT_CACHE_MB", str(100 / 1024 / 1024))
+ pipe = _EncodePipe(width = 256)
+ prompt_cache.install(pipe)
+ pipe.encode_prompt("a")
+ pipe.encode_prompt("a")
+ assert pipe.calls == 2 and len(pipe._unsloth_prompt_cache) == 0
+
+
+def test_lora_change_misses_and_text_encoder_swap_misses():
+ pipe = _EncodePipe()
+ prompt_cache.install(pipe)
+ pipe.encode_prompt("a cat")
+ pipe._unsloth_loras = (("style", "/x/style.safetensors", 0.8),)
+ pipe.encode_prompt("a cat")
+ assert pipe.calls == 2
+ pipe._unsloth_loras = (("style", "/x/style.safetensors", 0.5),)
+ pipe.encode_prompt("a cat")
+ assert pipe.calls == 3
+ pipe._unsloth_loras = ()
+ pipe.encode_prompt("a cat")
+ assert pipe.calls == 3
+ pipe.text_encoder = torch.nn.Linear(2, 2)
+ pipe.encode_prompt("a cat")
+ assert pipe.calls == 4
+
+
+def test_lora_owner_is_read_for_workflow_pipes():
+ owner = _EncodePipe()
+ aux = _EncodePipe()
+ prompt_cache.install(aux, lora_owner = owner)
+ aux.encode_prompt("a cat")
+ owner._unsloth_loras = (("style", "/x", 1.0),)
+ aux.encode_prompt("a cat")
+ assert aux.calls == 2
+
+
+def test_workflow_pipes_share_the_owner_budget():
+ owner = _EncodePipe()
+ aux = _EncodePipe()
+ assert prompt_cache.install(owner, identity = {"family": "f"})
+ assert prompt_cache.install(
+ aux, identity = {"family": "f", "workflow": "Img2Img"}, lora_owner = owner
+ )
+ assert prompt_cache.cache_for(aux) is prompt_cache.cache_for(owner)
+ owner.encode_prompt("a cat")
+ aux.encode_prompt("a cat")
+ assert owner.calls == 1 and aux.calls == 1
+ assert len(prompt_cache.cache_for(owner)) == 2
+
+
+def test_release_and_disable(monkeypatch):
+ pipe = _EncodePipe()
+ prompt_cache.install(pipe)
+ pipe.encode_prompt("a cat")
+ prompt_cache.release(pipe)
+ assert len(pipe._unsloth_prompt_cache) == 0
+ pipe.encode_prompt("a cat")
+ assert pipe.calls == 2
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_PROMPT_CACHE", "0")
+ other = _EncodePipe()
+ assert not prompt_cache.install(other)
+ other.encode_prompt("a")
+ other.encode_prompt("a")
+ assert other.calls == 2
+
+
+def test_install_is_idempotent_and_signature_preserved():
+ import inspect
+
+ pipe = _EncodePipe()
+ prompt_cache.install(pipe)
+ wrapped = pipe.encode_prompt
+ prompt_cache.install(pipe)
+ assert pipe.encode_prompt is wrapped
+ assert "max_sequence_length" in inspect.signature(pipe.encode_prompt).parameters
+
+
+def test_composes_with_the_disk_cache(tmp_path, monkeypatch):
+ pytest.importorskip("safetensors")
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_COND_CACHE_DIR", str(tmp_path))
+ pipe = _EncodePipe()
+ assert cond_cache.install(pipe, family = "fam", repo_id = "r", dtype = torch.float32)
+ assert prompt_cache.install(pipe)
+ pipe.encode_prompt("a cat")
+ pipe.encode_prompt("a cat")
+ assert pipe.calls == 1
+ assert pipe._unsloth_cond_cache_stats["misses"] == 1
+ assert pipe._unsloth_cond_cache_stats["hits"] == 0 # the memory hit never reached the disk
+ fresh = _EncodePipe()
+ cond_cache.install(fresh, family = "fam", repo_id = "r", dtype = torch.float32)
+ prompt_cache.install(fresh)
+ fresh.encode_prompt("a cat")
+ assert fresh.calls == 0 and fresh._unsloth_cond_cache_stats["hits"] == 1
+
+
+def test_h3_shim_caches_text_only_calls(monkeypatch):
+ calls = {"n": 0}
+
+ def get_qwen3vl_prompt_embeds(
+ text_encoder,
+ processor,
+ token_ids,
+ vision_inputs = None,
+ text_encoder_layer = 50,
+ device = None,
+ dtype = None,
+ ):
+ calls["n"] += 1
+ return torch.full((1, len(token_ids), 3), float(sum(token_ids)))
+
+ module = types.ModuleType("diffusers.modular_pipelines.minimax_h3.encoders")
+ module.get_qwen3vl_prompt_embeds = get_qwen3vl_prompt_embeds
+ monkeypatch.setitem(sys.modules, "diffusers.modular_pipelines.minimax_h3.encoders", module)
+
+ class _Modular:
+ blocks = ()
+
+ def __init__(self):
+ self.text_encoder = torch.nn.Linear(2, 2)
+
+ pipe = _Modular()
+ assert prompt_cache.install(pipe)
+ shim = module.get_qwen3vl_prompt_embeds
+ assert shim is not get_qwen3vl_prompt_embeds
+ a = shim(
+ pipe.text_encoder,
+ None,
+ [1, 2, 3],
+ {},
+ text_encoder_layer = 50,
+ device = "cpu",
+ dtype = torch.float32,
+ )
+ b = shim(
+ pipe.text_encoder,
+ None,
+ [1, 2, 3],
+ {},
+ text_encoder_layer = 50,
+ device = "cpu",
+ dtype = torch.float32,
+ )
+ assert calls["n"] == 1 and torch.equal(a, b) and a.data_ptr() != b.data_ptr()
+ shim(pipe.text_encoder, None, [1, 2, 4], {}, 50, "cpu", torch.float32)
+ assert calls["n"] == 2
+ shim(
+ pipe.text_encoder,
+ None,
+ [1, 2, 3],
+ {"pixel_values": torch.zeros(1)},
+ 50,
+ "cpu",
+ torch.float32,
+ )
+ shim(torch.nn.Linear(2, 2), None, [1, 2, 3], {}, 50, "cpu", torch.float32)
+ assert calls["n"] == 4
+ other = _Modular()
+ prompt_cache.install(other)
+ assert module.get_qwen3vl_prompt_embeds is shim
+
+
[email protected](not torch.cuda.is_available(), reason = "needs CUDA")
+def test_cuda_hit_lands_on_the_source_device():
+ class _CudaPipe(_EncodePipe):
+ def encode_prompt(
+ self,
+ prompt,
+ device = None,
+ **kw,
+ ):
+ out = super().encode_prompt(prompt, **kw)
+ return tuple(o.cuda() if torch.is_tensor(o) else o for o in out)
+
+ pipe = _CudaPipe()
+ prompt_cache.install(pipe)
+ first = pipe.encode_prompt("a cat")
+ second = pipe.encode_prompt("a cat")
+ assert second[0].is_cuda and torch.equal(first[0], second[0]) and pipe.calls == 1
+
+
+def test_load_installs_the_prompt_cache_and_unload_releases_it(fake_runtime, tmp_path, monkeypatch):
+ from core.inference import diffusion as diff_mod
+
+ from .test_diffusion_backend import _loaded_backend
+
+ calls = {"install": [], "release": []}
+ monkeypatch.setattr(
+ diff_mod.prompt_cache, "install", lambda pipe, **k: calls["install"].append(pipe) or True
+ )
+ monkeypatch.setattr(
+ diff_mod.prompt_cache, "release", lambda pipe: calls["release"].append(pipe)
+ )
+ backend = _loaded_backend(tmp_path)
+ pipe = backend._state.pipe
+ assert calls["install"] == [pipe]
+ backend.unload()
+ assert pipe in calls["release"]
+
+
+def test_budget_respects_a_cgroup_memory_limit(monkeypatch):
+ # Entries count against memory.max, so the budget is RAM/64 of the 2 GiB limit, not the host.
+ from core.inference import diffusion_memory
+
+ monkeypatch.delenv(prompt_cache._ENV_BUDGET_MB, raising = False)
+ monkeypatch.setattr(diffusion_memory, "_cgroup_memory_limit_mib", lambda: 2048)
+ assert prompt_cache.budget_bytes() == 32 * 1024 * 1024
+ monkeypatch.setenv(prompt_cache._ENV_BUDGET_MB, "100")
+ assert prompt_cache.budget_bytes() == 100 * 1024 * 1024
+ monkeypatch.setenv(prompt_cache._ENV_BUDGET_MB, "lots") # malformed: default, still capped
+ assert prompt_cache.budget_bytes() == 32 * 1024 * 1024
+ monkeypatch.delenv(prompt_cache._ENV_BUDGET_MB)
+ monkeypatch.setattr(diffusion_memory, "_cgroup_memory_limit_mib", lambda: None)
+ host = prompt_cache._host_ram_bytes() # 0 where sysconf is missing (Windows): no cap
+ expected = 256 * 1024 * 1024
+ if host:
+ expected = min(expected, max(16 * 1024 * 1024, host // 64))
+ assert prompt_cache.budget_bytes() == expected
+
+
+def test_controlnet_pipe_gets_the_prompt_cache(monkeypatch):
+ import threading
+
+ from core.inference import diffusion_controlnet as dc
+ from core.inference.diffusion import DiffusionBackend
+
+ from . import test_diffusion_controlnet as tcn
+
+ calls = []
+
+ class _EncodingCNPipe(tcn._FakeCNPipe):
+ def encode_prompt(
+ self,
+ prompt,
+ device = None,
+ ):
+ calls.append(prompt)
+ return torch.ones(1, 3, 4)
+
+ fake = tcn._fake_diffusers()
+ fake.FluxControlNetPipeline = _EncodingCNPipe
+ monkeypatch.setitem(sys.modules, "diffusers", fake)
+ tcn._allow_cn_security(monkeypatch)
+ backend = DiffusionBackend()
+ state = tcn._state()
+ backend._state = state
+ pipe = backend._controlnet_pipe(
+ state, dc.ResolvedControlNet("flux-union-pro", "repo/id", is_local = False), threading.Event()
+ )
+ assert prompt_cache.cache_for(pipe) is not None
+ first = pipe.encode_prompt("a sloth", device = "cpu")
+ again = pipe.encode_prompt("a sloth", device = "cpu")
+ assert calls == ["a sloth"] and torch.equal(first, again)