[Issue]: Stale prompt embeddings after text-encoder LoRA changes or reloads
Issue Description
Repeating a prompt can reuse stale embeddings after adding/removing a text-encoder LoRA, changing its scalar strength, or reloading text encoders with quantization. The prompt-encode cache in modules/sd_hijack_te.py checks checkpoint identity but omits encoding component identities and adapter strengths. The same checkpoint-info object can survive a reload. sd_models.clear_caches() also omits this cache.
To reproduce the encoder-reload case without the local LoRA fixture, start a fresh SD.Next API server with debug logging, Freepik/flux.1-lite-8B downloaded and registered, bf16, balanced offload and SDPA. Run this with the server at http://127.0.0.1:7860:
import base64
import json
from pathlib import Path
from urllib.parse import urlencode
from urllib.request import Request, urlopen
url = "http://127.0.0.1:7860"
out = Path("tmp/tecache-repro")
out.mkdir(parents=True, exist_ok=True)
def call(method, path, payload=None):
data = None if payload is None else json.dumps(payload).encode()
request = Request(url + path, data=data, method=method,
headers={"Content-Type": "application/json"})
with urlopen(request, timeout=3600) as response:
return json.load(response)
model = next(m["title"] for m in call("GET", "/sdapi/v1/sd-models")
if "Freepik/flux.1-lite-8B" in m["title"])
request = {"prompt": "a pencil sketch of an old sailing ship in a storm gt01",
"negative_prompt": "", "width": 768, "height": 768, "steps": 12,
"seed": 11, "cfg_scale": 3.5, "sampler_name": "Default"}
def generate(name):
result = call("POST", "/sdapi/v1/txt2img", request)
assert result.get("images"), result
image = result["images"][0].split(",", 1)[-1]
(out / (name + ".png")).write_bytes(base64.b64decode(image))
call("POST", "/sdapi/v1/options",
{"sdnq_quantize_weights": [], "layerwise_quantization": [],
"sdnq_modules_to_not_convert": "", "sd_textencoder_cache_size": 4})
reload_path = "/sdapi/v1/checkpoint?" + urlencode(
{"sd_model_checkpoint": model, "force": "true"})
call("POST", reload_path)
generate("bf16")
generate("bf16-repeat")
call("POST", "/sdapi/v1/options",
{"sdnq_quantize_weights": ["TE"], "sdnq_quantize_weights_mode": "int8"})
call("POST", reload_path)
generate("int8-warm")
generate("int8-repeat")
Expected: the int8 reload re-encodes the prompt using the new encoders. Observed on unpatched b0bd587b: T5 contains SDNQLinear after reload, but the prompt still hits the old cache and produces the bf16 image. When I ran the script above on a fresh unpatched server, int8-warm.png was pixel-identical to bf16.png (MAD 0.000); with the linked PR applied they differed by MAD 3.230, and each repeat matched its first image. For a cold comparison, restart with the int8 settings retained and submit the same generation request before generating that prompt in any other state. A checkpoint reload alone is not a reliable cold-cache control on the unpatched tree.
The LoRA checks used sd2_fluxte, a local synthetic rank-8 TE-only adapter with 96 modules covering CLIP-L and T5. Native fusion was disabled (lora_fuse_native=false, SD_LORA_FUSE unset); logs confirm mode=backup. The sequence was Q1 without LoRA → Q1 at 1.0 → Q1 at 0.5, then fresh Q2 at 1.0 → Q2 without LoRA. Q1 was a pencil sketch of an old sailing ship in a storm gt01; Q2 was a studio photo of a ceramic teapot with blue glaze gt02. All used 768×768, 12 steps, seed 11, CFG 3.5 and the Default sampler.
The earlier checkpoint-switch and failed transformer-LoRA controls are retired. The current unpatched cold-control run used a fresh server and verified cache misses, with 48 filler prompts to evict entries between relevant states. The quantization result is stale reuse of pre-reload embeddings, not a failure to quantize T5.
The source inventory is 48 pipeline files, 55 loader functions, and three hook sites in two core files. Hook presence does not prove active use for every model. Boogu/OmniGen2 use mllm; Anima also uses llm_adapter; combined/modular pipelines need separate owner verification. These three model families were not run on GPU.
PR #4987 addressed the other cache (prompt_parser_diffusers). Nearby symptom reports #5132, #4558 and #4472 are related context, without an established duplicate diagnosis. Commit b7aa4b895 ("prompt cache prevent clear on task change") changed pipeline identity to checkpoint identity; this is code history, not an executed bisect or a release-regression claim. Reuse across task changes retaining checkpoint, encoders and adapter state should continue working.
GPU validation compared unpatched b0bd587b7cebd17d7f976b51d48dc233549593da with the two-file patch. Run A retained the default outer-cache size of 4 and lora_force_reload=false. Run A2 used sd_textencoder_cache_size=0 to expose the inner cache and lora_force_reload=true for the Diffusers segment. The following results are from A2:
| Check | Unpatched | Patched |
|---|---|---|
| Plain repeat | HIT; identical image | HIT; identical image |
| Native TE LoRA added at 1.0 | Stale HIT; identical to no-LoRA image; MAD 16.698 from cold control | MISS; MAD 0.575 from cold control |
| Native strength 1.0 → 0.5 | Stale HIT despite te=[0.5]; MAD 9.120 from cold control |
MISS; MAD 0.615 from cold control |
| Native removal in backup mode | Stale HIT; identical to Q2 with LoRA; MAD 8.484 from pristine control | MISS; MAD 0.211 from pristine control; Q1 restoration bit-exact to its same-process base |
| TE int8 reload | Encoder IDs change and T5 is quantized, but stale HIT; identical to bf16; MAD 3.227 from cold int8 control | MISS, then HIT on unchanged repeat; MAD 0.658 from cold int8 control |
| Diffusers strength 0.75 → repeat → 0.25 → repeat | 0.25 is a stale HIT, identical to 0.75; MAD 7.672 from cold 0.25 control | MISS / HIT / MISS / HIT; MAD 0.632 from cold 0.25 control |
| txt2img → img2img → txt2img with unchanged encoder state | HIT | HIT; encoder IDs unchanged |
clear_caches(full=False) / clear_caches(full=True) |
Both leave 4 entries; next prompt HIT | Both clear 1 → 0 entries; next prompt MISS |
| Checkpoint force reload | HIT | MISS |
Run A also reproduces stale native add/remove/strength, int8 reload and cache-clear behavior on the unpatched tree and fresh encoding after those transitions with the patch. Exact repeats and task switches at the default outer-cache size are served before the inner cache is consulted, so the direct inner-cache reuse result comes from A2. Setting sd_textencoder_cache_size=0 disables only the outer cache; it is not a workaround for this defect.
The successful Diffusers strength result above requires lora_force_reload=true. At its default false, both trees encounter the separate Adapter with name sd2_fluxte already exists / not loaded failure; the adapter becomes inactive. A cache miss in that case does not mean strength 0.25 was applied. This patch does not fix that loader failure.
MAD is mean absolute difference in decoded 8-bit RGB values. Patched-to-cold comparisons are 0.211–0.658; same-state cross-process controls measured approximately 0.11–0.46 (maximum channel differences 5–14). These are not bit-exact comparisons, and some exceed that measured range. Same-process repeats and backup-mode restoration were bit-exact. Unpatched A arrays were overwritten by A2; A's in-process comparisons remain recorded.
Version Platform Description
GPU run: SD.Next dev b0bd587b7cebd17d7f976b51d48dc233549593da, unpatched versus patched; Linux x86_64, kernel 6.6.122+, Colab RTX PRO 6000 Blackwell Server Edition (sm_120), driver 580.82.07, CUDA 13.0; Python 3.13.15; torch 2.14.1+cu130; diffusers 0.41.0.dev0; transformers 5.14.0.dev0; peft 0.21.2; SDNQ 0.2.9. Model: hub/Freepik/flux.1-lite-8B [16b9373dd3]. Interface: API. SDPA, balanced offload 0.2–0.8, bf16, cuDNN benchmark=True, fresh /root/data_gate per server. The same diagnostic extension inspected cache/encoder/adapter state on both trees and exposed the explicit cache-clear calls.
The full SD.Next test suite and UI were not run.
Relevant log output
Excerpts from A2 for Q1 addition and strength change; the zero-length prompt="None" encode calls are not the measured Q1:
Unpatched, add sd2_fluxte:1.0:
Encode: length=54 cache=1 prompt="a pencil sketch of an old sailing ship in a storm gt01"
Patched, add sd2_fluxte:1.0:
Encode: length=54 prompt="a pencil sketch of an old sailing ship in a storm gt01" hijack=True
Patched, change to sd2_fluxte:0.5:
Encode: prompt cache activate id=(133505770621392, (133504896689760, 133505237937728, 10207264, 10207264, 10207264, 10207264), (('sd2_fluxte', 0.5),), (), ()) depth=0
Encode: length=54 prompt="a pencil sketch of an old sailing ship in a storm gt01" hijack=True
pr merged.