automatic icon indicating copy to clipboard operation
automatic copied to clipboard

[Issue]: Native loader rejects prefixed PEFT LoRA keys despite successful image generation

Open Jackmeson1 opened this issue 1 month ago • 2 comments

Issue Description

A FLUX.1 adapter saved with keys such as transformer.transformer_blocks.0.attn.to_q.lora_A.weight and the matching lora_B.weight is not applied despite successful image generation through the generic native loader at b0bd587b. In the isolated GPU run below, SD_LORA_DEBUG=1 makes the loader raise an unmatched-key error; no adapter modules are loaded, but the API returns HTTP 200 with an image identical to the baseline.

The prefixed branch of load_safetensors consumes weight, but leaves lora_A/lora_B attached to the module key. Those module names fail lookup. The existing unprefixed PEFT branch is bypassed.

Reproduction:

  1. Use SD.Next dev at b0bd587b7cebd17d7f976b51d48dc233549593da, with Disty0/FLUX.1-schnell-SDNQ-uint4-svd-r32 installed and listed by the checkpoint API. Install multimodalart/flux-tarot-v1 as flux_tarot_v1_lora.safetensors and the kohya control strangerzonehf/Flux-Super-Realism-LoRA as super-realism.safetensors in the configured LoRA directory.
  2. Start the server with SD_LORA_FUSE absent and SD_LORA_DEBUG=1, for example env -u SD_LORA_FUSE SD_LORA_DEBUG=1 ./webui.sh --debug --port 7860. Use bf16 and SDPA. The validation used balanced offload at 0.2–0.8.
  3. In another shell, activate the SD.Next venv and run this API reproduction. It uses the same schnell prompt, seed, resolution, steps, and CFG as the GPU validation. Each case forces a pristine checkpoint reload:
source venv/bin/activate
python - <<'PY'
import base64
import io
import json
import urllib.parse
import urllib.request

import numpy as np
from PIL import Image

url = "http://127.0.0.1:7860"

def call(method, path, payload=None):
    data = None if payload is None else json.dumps(payload).encode()
    req = urllib.request.Request(
        url + path, data=data, method=method,
        headers={"Content-Type": "application/json"},
    )
    with urllib.request.urlopen(req, timeout=3600) as response:
        body = response.read()
    return json.loads(body) if body else None

models = call("GET", "/sdapi/v1/sd-models")
matches = [m["title"] for m in models
           if "FLUX.1-schnell-SDNQ-uint4-svd-r32" in m["title"]]
assert len(matches) == 1, matches
call("POST", "/sdapi/v1/refresh-loras")
names = {item["name"] for item in call("GET", "/sdapi/v1/loras")}
assert {"flux_tarot_v1_lora", "super-realism"} <= names, names
call("POST", "/sdapi/v1/options", {
    "lora_force_diffusers": False, "lora_fuse_native": False,
    "lora_fuse_diffusers": False, "lora_force_reload": True,
    "lora_stack_mode": "sum", "lora_sdnq_apply": "exact",
    "sdnq_quantize_weights": [], "layerwise_quantization": [],
    "sdnq_modules_to_not_convert": "",
    "cross_attention_optimization": "Scaled-Dot-Product",
    "diffusers_offload_mode": "balanced",
    "diffusers_offload_min_gpu_memory": 0.2,
    "diffusers_offload_max_gpu_memory": 0.8,
})
query = urllib.parse.urlencode({
    "sd_model_checkpoint": matches[0], "force": "true",
})
prompt = "a portrait of a woman reading a book in a cafe pk02"
images = {}
for label, adapter, use_diffusers in (
    ("base", "", False),
    ("tarot_native", "flux_tarot_v1_lora", False),
    ("kohya_native", "super-realism", False),
    ("tarot_diffusers", "flux_tarot_v1_lora", True),
):
    call("POST", "/sdapi/v1/options",
         {"lora_force_diffusers": use_diffusers})
    assert call("POST", "/sdapi/v1/checkpoint?" + query)["ok"]
    result = call("POST", "/sdapi/v1/txt2img", {
        "prompt": prompt + (f" <lora:{adapter}:1>" if adapter else ""),
        "negative_prompt": "", "width": 768, "height": 768,
        "steps": 4, "cfg_scale": 0, "seed": 5, "sampler_name": "Default",
    })
    assert result.get("images"), result
    data = base64.b64decode(result["images"][0].split(",", 1)[-1])
    images[label] = np.asarray(Image.open(io.BytesIO(data)).convert("RGB"))
    mad = np.abs(images[label].astype(np.float64)
                 - images["base"].astype(np.float64)).mean()
    print(label, "MAD from base:", float(mad))
call("POST", "/sdapi/v1/options", {"lora_force_diffusers": False})
PY

On the unpatched build, native tarot loads no modules and its image is bit-identical to the baseline; the kohya control and Diffusers-method tarot both have an effect. My run of the block above printed tarot_native MAD from base: 0.0, kohya_native 33.557 and tarot_diffusers 28.011 unpatched, and tarot_native 27.998 with the linked PR applied. With SD_LORA_DEBUG=1, the first failed lookup aborts loading before the aggregate unmatched=N matched=M warning, so this run has no unpatched unmatched count. Without that environment flag, the source accumulates unmatched keys and reports the adapter as not loaded.

Workaround: enable LoRA load using Diffusers method (lora_force_diffusers=true). This selects the pipeline's adapter loader. The workaround has an effect on the tested schnell model; it is not a semantic reference for tarot on that model.

GPU validation on 2026-10-20 compared unpatched b0bd587b with only the two-line suffix fix applied. Each adapter load followed a forced checkpoint reload, with both fuse options false and SD_LORA_FUSE absent. The same instrumentation extension recorded loaded modules and dumped tensors in both runs. MAD below is the mean absolute difference over decoded uint8 RGB pixels.

Check Unpatched Patched
Flux-lite synthetic A/B layout 0 modules; image equals baseline 84 modules, backup mode; effect MAD 26.9409
Flux-lite synthetic down/up layout 84 modules; effect MAD 26.9444 84 modules; effect MAD 26.9409
Flux-lite A/B versus down/up MAD 26.9444 84/84 modules have equal loaded tensors and scale metadata, matching canonical fp32 delta hashes and target-weight hashes; images bit-identical
SDNQ schnell synthetic A/B layout 0 modules; image equals baseline 84 modules; exact SDNQ application on 84 layers, factor mode; effect MAD 8.2368
SDNQ schnell synthetic down/up layout 84 modules; effect MAD 8.2317 84 modules; effect MAD 8.2368; same 84/84 comparisons and bit-identical image as A/B
Schnell native tarot 0 modules; image equals baseline 494 modules; exact SDNQ application on 493 layers, backup mode; effect MAD 27.9977
Schnell kohya super-realism control 494 modules, 493 exact SDNQ layers; effect MAD 33.5576 Same counts; effect MAD 33.5579
Schnell Diffusers-method tarot Effect MAD 28.0060 Effect MAD 28.0113

The synthetic files contain the same deterministic rank-8 tensors: 8 double-block attn.to_q targets, 38 single-block attn.to_q targets, and 38 single-block proj_out targets. All 168 renamed tensor pairs are equal after reloading the files. There is no explicit alpha or adapter metadata. FLUX.1 single blocks have no attn.to_out.0; that target was not used. Flux-lite requests used 768×768, 12 steps, CFG 3.5, seed 5; schnell used 768×768, 4 steps, CFG 0, seed 5.

Baseline repeats, the Flux-lite down/up repeat, Flux-lite removal restores, and the schnell restore after kohya removal are bit-exact within each run. The equality claim is between layouts within each run, not between separate unpatched and patched server processes. In factor mode the target-weight hash covers stored quantized weights, not a merged effective weight.

Tarot's native and Diffusers-method images differ by MAD 8.3732 on the patched schnell model. This establishes loading and an effect, not real-file semantic correctness. Tarot was not tested on its trained FLUX.1-dev base: the available dev snapshot contained only text_encoder_2.

The results, module comparisons, server logs and environment captures are local validation artifacts; the module comparisons were computed on the GPU host. All 32 saved image comparisons were also recomputed from the 30 saved RGB arrays.

Nearby reports are #4877 (old Chroma LoRAs) and #4841 (Flux.2 native adapters). Chroma and Flux.2 use separate architecture dispatch entries in the current source; this report concerns FLUX.1's generic parser. #5042 (a Krea2 LoRA, “LoRA that loads on ComfyUI doesn't on SDNext”) was closed on 2026-08-21 as solved on dev; the LoRA fixes merged that week did not touch modules/lora/lora_load.py, which the linked PR changes.

Version Platform Description

SD.Next dev b0bd587b7cebd17d7f976b51d48dc233549593da, unpatched versus the two-line suffix fix in the linked PR.

GPU validation: Colab, Linux x86_64 kernel 6.6.122+, NVIDIA 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 (35337772), Triton 3.8.0. Diffusers and Transformers source revisions are not included in the saved gate artifacts. SDPA, bf16, balanced offload 0.2–0.8, cuDNN benchmark=True; a fresh /root/data_gate per server.

Models: hub/Freepik/flux.1-lite-8B [16b9373dd3] and hub/Disty0/FLUX.1-schnell-SDNQ-uint4-svd-r32 [dd7d3aa9fb].

Form selections: Linux / nVidia CUDA / API / Dev / Other image model. The full SD.Next test suite, complete CI/pre-commit workflow, and UI were not run.

Relevant log output

Selected excerpts from the unpatched and patched server logs; line wrapping is collapsed and omitted fields are marked ...:

Unpatched synthetic A/B:
RuntimeError: LoRA key not found in network_layer_mapping: key=lora_transformer_single_transformer_blocks_0_attn_to_q_lora_A mapping=...

Unpatched tarot:
RuntimeError: LoRA key not found in network_layer_mapping: key=lora_transformer_single_transformer_blocks_0_attn_to_k_lora_A mapping=...

Patched Flux-lite synthetic A/B:
Network load: type=LoRA name="gate_peft_ab" type={'ModuleTypeLora'} keys=84 ... fuse=False:False
Network status: type=LoRA networks=['gate_peft_ab'] method=native(default) mode=backup stack=sum ...

Patched SDNQ schnell synthetic A/B:
Network load: type=LoRA quant=sdnq apply=exact layers=84
Network status: type=LoRA networks=['gate_peft_ab'] method=native(default) mode=factor stack=sum ...

Patched SDNQ schnell tarot:
Network load: type=LoRA name="flux_tarot_v1_lora" type={'ModuleTypeLora'} keys=494 ... fuse=False:False
Network load: type=LoRA quant=sdnq apply=exact layers=493
Network status: type=LoRA networks=['flux_tarot_v1_lora'] method=native(default) mode=backup stack=sum ...

Jackmeson1 avatar Oct 21 '26 16:10 Jackmeson1

cc @CalamitousFelicitousness

vladmandic avatar Oct 21 '26 18:10 vladmandic

should be fixed in dev branch with latest updates.

vladmandic avatar Oct 26 '26 07:10 vladmandic