Skip to content

refactor(lora): recognize a LoRA's family once instead of per-class exclusion lists - #10445

Merged
joshistoast merged 5 commits into
mainfrom
fix-issue-10303
Dec 3, 2026
Merged

joshistoast merged 5 commits into
mainfrom
fix-issue-10303

Conversation

@joshistoast

@joshistoast joshistoast commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Each LoRA config class used to recognize its own family by ruling the other families out by name, and LoRALoader decided the family a second time in a 17-branch if-chain. Adding a family meant editing other families' classes, and which family wins for a file was spread across those negations.

Now one ordered table, LORA_FAMILIES in invokeai/backend/patches/lora_conversions/lora_families.py, holds each family's fingerprint, refusal and converter. recognize_lora asks the families in order; the first that owns a state dict decides, accepting it under a base or refusing it, and no later family is asked. Precedence replaces the exclusion lists.

  • The 34 LoRA_*_Config and 2 ControlLoRA_*_Config classes stay as the records of the AnyModelConfig union and keep their from_model_on_disk seam. They read one memoized recognition per model on disk. configs/lora.py goes from 2,412 to about 610 lines; the predicate bodies moved unchanged next to their family's *_lora_constants.py.
  • LoRALoader converts with the family registered for the stored type and base (297 to about 110 lines). The if-chain and the _model_base side effect are gone. The "registered by an earlier version, re-identify" refusals are declared by the newer family (registered_earlier_as), so FLUX and Z-Image no longer name FLUX.3 and MOSS-Image.
  • Guards that state a fact about a family's own transformer and keep unsupported architectures out stay with that family (Qwen-Image has no attn1 and no single-stream blocks, Stable Diffusion's UNet has no DiT blocks.N modules, the foreign-name lists in the LTX-2, Wan and MiniMax H3 constants). They need no edit when a family is added.
  • The eight test_*_lora_probe_independence.py files (about 2,850 lines) are replaced by one corpus test: every key layout is claimed by exactly one family, refused with its recorded reason, or claimed by none.

Identification through the LoRA classes does less work, because one recognition replaces a probe per class (ms per file, base → this PR, measured on a loaded machine):

Input Keys Base This PR
FLUX kohya LoRA 912 29.7 8.6
FLUX DoRA (OneTrainer) 2,024 95.1 17.3
SD 3 kohya LoRA 789 45.5 15.8
SDXL UNet main model (not a LoRA) 1,680 45.9 21.6

Related Issues / Discussions

Closes #10303

QA Instructions

Results for real inputs are unchanged. Before any production change I recorded what the base commit (ed418f3d2a) does, then compared this branch against it:

  • 966 distinct inputs (every input the existing suites probe a LoRA config class with, plus all lora_state_dicts fixtures), each through all 36 LoRA config classes: 0 differences, including every InvalidMatchError text.
  • All 124 tests/model_identification/stripped_models fixtures through the 36 classes and the whole ModelConfigFactory: 0 differences.
  • 3,767 LoRALoader._load_model runs (each input under the bases it identifies as; representatives and real files under every base, type and format), comparing converted layer keys and classes or the error text: 0 differences.
  • No input is accepted by two classes.
  • The JSON schema of AnyModelConfig and of the 36 classes is byte-identical to the base.

The comparison harness is not part of the PR. In the repo:

  • pytest tests/backend/model_manager/configs/test_lora_family_corpus.py: 269 cases. The same file passes on the base commit, so it is a baseline of today's behaviour, not of this change.
  • pytest tests/backend/model_manager/configs tests/backend/model_manager/load tests/backend/patches/lora_conversions tests/app/invocations: 9,649 passed; the 25 failures and 10 errors are fixtures stored in git-lfs that are pointer files on my machine, and fail the same way on the base commit and at each commit of this branch.
  • ruff check and ruff format --check: clean.

Not run: tests/model_identification through pytest locally (git-lfs pointers; the fixtures were compared as described above, CI runs the suite itself), a family E2E run, loads on a GPU.

Behaviour that does change:

  1. Files mixing two families' keys. The first owner in the list decides. Today the outcome depends on which class happens to have a guard, and for some inputs on set iteration order. Over 3,094 artificial unions of two corpus inputs: 2,432 unchanged, 90 that two classes accept today now go to the earlier family, the rest move from "claimed by a class without a guard" to "refused by the owner". None becomes newly claimed. No trainer writes such files.
  2. Diffusers LoRA folders are identified from pytorch_lora_weights.* and that file's header. An SD, SDXL or FLUX folder with a checkpoint-*/ copy beside the main file used to fail with "Multiple weight files" and install as unknown; it now identifies, as SD 3 folders already did. Three FLUX folder shapes no longer register (ai-toolkit-style keys under a header that is not ai-toolkit's, a folder without pytorch_lora_weights.*, a FLUX.2 folder whose file is in no FLUX format). The loader refuses every Diffusers-format FLUX record in both versions, so these go from "registered, fails at generation" to "unknown". Identification and loading now read the same file, .safetensors before .bin; identification used to prefer .bin, so a folder holding both is now identified from the file the loader converts.
  3. A fingerprint that raises (an integer key or a non-tensor value, which only a pickle can hold) is logged as a warning and ends recognition: the file is left unidentified, and no later family is asked. On the base the exception failed only the class that raised, so a later class could still claim the file. The load-time "registered by an earlier version" check reports the same failure instead of raising the fingerprint's own exception.

Review

Findings resolved:

  • An exception in one family's fingerprint left the outcome to whichever later family accepted the file, so a malformed MOSS-Image or Ideogram 4 file could register as Z-Image. A raising fingerprint now leaves the file unidentified, at identification and in the load-time check (item 3 above), with tests on integer-key Z-Image and Anima files and a malformed Ideogram 4 file.
  • Stable Diffusion's guard against Cosmos-style block names had been left to precedence, which let a file with such names plus SD text-encoder keys be claimed as SD 1. The guard is back as a fact about SD's own UNet, with corpus cases.
  • The family table imported conversion modules at import time. They are imported when used again, so importing the config factory loads no *_lora_conversion_utils module, as on the base.
  • Two orderings real files depend on (Krea-2 and Qwen-Image-2.1 before Qwen-Image) were not pinned; corpus cases now fail when either moves. Converter bindings and dispatch by the stored base were not pinned; a dispatch table test covers every family, the FLUX layouts and loads whose stored base differs from what the recognizer says.
  • Two cheap checks now run before expensive ones (Krea-2's explicit-base path, the OMI header).

Remaining limits:

  • FLUX's sub-layout is still detected separately at identification (flux_format_from_state_dict) and at load (the converter chain), in different orders and without the header at load. Aligning them changes which converter runs for some files and needs its own verification.
  • SimpleTuner's flat lycoris_ layout keeps its own module table in lycoris_flat_lora_constants.py, which the loader consults before the family's converter. A new family with flat-layout files still edits that table.
  • LoRA_Diffusers_ZImage_Config never matches, as before.

Compatibility / Rollout

No API, openapi.json or stored-record change: class names, fields, literals and tags are unchanged, and loading dispatches on the stored type and base, so records registered under a base on purpose (Krea-2's explicit base, a Klein 4B LoRA stored as FLUX.1) load as before.

Checklist

  • The PR has a short but descriptive title, suitable for a changelog
  • Meaningful regression coverage added / updated where needed; obsolete tests/code removed
  • Persisted-state and API changes include required migrations / compatibility validation
  • Relevant performance/efficiency opportunities considered; material claims have evidence
  • Material review findings resolved and relevant checks rerun
  • Documentation added / updated (if applicable)
  • Updated What's New copy (if doing a release after this PR)

Open in [code]smith · Need help on this PR? Tag @codesmith-bot with what you need.

One parametrized test runs every LoRA config class on each key layout and expects exactly one family, its recorded refusal, or no claim.
It replaces the eight per-family probe-independence files, whose inputs it covers; the assertions that were not classification move to the tests that own that code.
… table

LORA_FAMILIES holds each family's fingerprint, refusal and converter; the first family that owns a state dict decides, so precedence replaces the per-class exclusion lists.
The config classes stay as records that read one memoized recognition per model on disk; their predicates move next to their family's constants unchanged.
A Diffusers LoRA folder is identified from pytorch_lora_weights alone, so a checkpoint copy beside it no longer leaves SD and FLUX folders unidentified.
LoRALoader converts with the family registered for the stored type and base instead of an if-chain over bases, and no longer remembers the base between calls.
A family declares the bases earlier versions registered its files under, which drives the re-identify refusal.
Adding a LoRA family is one LORA_FAMILIES entry placed by precedence, a record class and corpus cases; no other family's probe is edited.
@github-actions github-actions Bot added python PRs that change python files backend PRs that change backend files python-tests PRs that change python tests docs labels Dec 1, 2026
@Pfannkuchensack Pfannkuchensack self-assigned this Dec 1, 2026
@Pfannkuchensack
Pfannkuchensack self-requested a review December 1, 2026 19:14

@Pfannkuchensack Pfannkuchensack left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I ran this against every LoRA we have locally, comparing the merge base (ed418f3) with e5265d3. No blockers from my side.

The corpus is 85 files plus 16 diffusers folders built from them (plain and with a checkpoint-100/ copy). The files are LoRAs and control LoRAs for SD1, SDXL, SD3, FLUX, FLUX.2, FLUX.3, Krea-2 (incl. control), Qwen-Image, Qwen-Image-2.1, Z-Image, Anima, ERNIE-Image, Ideogram 4, MOSS-Image, Wan, LTX-2 and MiniMax H3, in kohya, PEFT/diffusers, LyCORIS (LoKr/LoHa/DoRA) and flat layouts.

  • Identification: the factory result is the same for every file and folder, including the InvalidMatchError texts.
  • Conversion: all 92 conversions the base could do produce byte-identical layers under the PR. That is every layer tensor and attribute hashed, MiniMax H3's 312 layers included.
  • Differences: only the folders with a checkpoint-*/ copy.
    • The two FLUX folders go from Unknown to LoRA_Diffusers_FLUX and still fail to load with "unsupported FLUX format: Diffusers", as the description says.
    • The others change only the "Multiple weight files" detail text.
  • Speed: identifying the whole corpus with a warm page cache takes 6.1 s instead of 9.7 s.

The tests pass locally apart from LFS-pointer fixtures. I also reordered and disabled parts of LORA_FAMILIES against the family tests: almost every precedence edge and refusal is pinned, and registered_earlier_as is covered by the FLUX.3 and MOSS re-identify tests. Two gaps are listed below.

Low

  1. A fingerprint that raises hands the file to a later family (lora_families.py:773-778). recognize_lora logs the exception and moves on, so a MOSS-Image or Ideogram 4 file whose owns trips over an odd tensor can end up registered as Z-Image, which matches on generic module names. At load time, raise_if_registered_by_an_earlier_version calls family.owns(probe) without the try (:795), so the same exception comes back as a load error instead of the re-identify message. Treating a raising fingerprint as "this file is unidentifiable" would keep the first-owner rule honest and avoid the silent misregistration. Alternatively, at least wrap the second call the same way.
  2. The FLUX.3-before-FLUX order is not pinned. The comment at :620 says FLUX's BFL probes would admit FLUX.3 keys, but moving FLUX.3 directly after FLUX leaves all LoRA tests green. A FLUX.3 fixture that FLUX's probes also accept would pin it.
  3. The Wan foreign-architecture guard is not pinned. With has_non_wan_architecture_keys stubbed to False (_judge_wan, :350-354), the Wan and corpus tests still pass. Either a case is missing, or the guard no longer guards anything now that families earlier in the order own those files.
  4. Diffusers folders: identification and loading pick different files when both exist. _diffusers_weight_file prefers .bin (configs/lora.py:504-509), while the loader prefers .safetensors (load/model_loaders/lora.py:100). This is carried over from the old _get_weight_file_or_raise, but now that one recognition decides the family, the file it reads and the file the loader converts should be the same. Our folders only ship safetensors.

Nits

  • assert family is not None in _raise_unless_recognized_as (configs/lora.py:121) runs inside the factory's per-class except, so a config class missing from the table shows up as a quiet non-match rather than a crash. A table-completeness test over all LoRA config classes would catch that at test time.
  • registered_earlier_as mixes display names: FLUX.3 uses BaseModelType.Flux.value ("flux"), MOSS uses "Z-Image", so the two refusals read differently.
  • Refusals that aren't final are no longer asserted by reason anywhere I could find, e.g. "malformed MiniMax H3 LoRA". They only show up in the factory details, but a typo in one would go unnoticed.
  • Some cross-family references remain: formats.py imports QWEN_IMAGE_ONLY_MODULE_RE, and lycoris_flat_lora_constants.py imports Ideogram 4 and SD3 helpers. Fine for this PR, just not yet "one family, one place".

Stop recognition when a fingerprint fails and report failures in legacy load checks.
Use one weight selector for Diffusers LoRAs and cover family precedence and refusals.

@Pfannkuchensack Pfannkuchensack left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rechecked at fe06202 against the same corpus (85 LoRA files, 16 diffusers folders). Identification and all 92 conversions are unchanged from the previous head, MiniMax H3's 312 layers included, and no file hits the new "fingerprint raised" path.

The follow-ups look good to me:

  • A raising fingerprint now ends recognition in both places, so the first-owner rule holds and the load-time check gives the same answer as identification.
  • The FLUX.3-before-FLUX order and the Wan foreign-architecture guard are pinned now: moving FLUX.3 after FLUX fails 3 tests, and stubbing has_non_wan_architecture_keys fails the new corpus case.
  • Config and loader read the same weight file via diffusers_lora_weight_file.
  • The table-completeness test, the MiniMax refusal reason and the unified display names cover the nits.

One behaviour change worth a line in the description: a fingerprint that raises used to fall through to later families and now leaves the file unidentified. That is the safer outcome, and none of our files is affected.

Tests pass locally apart from the LFS-pointer fixtures. No further findings from my side.

@Pfannkuchensack Pfannkuchensack left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The head hasn't changed since my last pass (fe06202), and CI is green. Approving.

One thing left in the description: item 3 under "Behaviour that does change" and the first "Findings resolved" bullet still describe the earlier handling, where a raising fingerprint counts as "not this family's" and a later family can claim the file. Since fe06202 a raising fingerprint ends recognition and leaves the file unidentified (recognize_lora returns None). Worth updating so the description matches the code.

@joshistoast
joshistoast added this pull request to the merge queue Dec 3, 2026
Merged via the queue into main with commit 516d161 Dec 3, 2026
38 checks passed
@joshistoast
joshistoast deleted the fix-issue-10303 branch December 3, 2026 01:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend PRs that change backend files docs python PRs that change python files python-tests PRs that change python tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Recognize a LoRA's family once instead of per-class exclusion lists

2 participants