Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(krea2): load LoRAs with diff_b/diff keys and fal base_model.model.* native keys (#10376)

Бат-Орших03d40c55be48
diff --git a/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx b/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx
index fe8cdd69cb..1d722ab3c3 100644
--- a/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx
@@ -301,6 +301,10 @@ Qwen-Image LoRAs, LoKR and LoHA files also load in ComfyUI's `diffusion_model.`
`lora_transformer_transformer_blocks_…` layouts, when they train the blocks' modulation or MLP layers; see the
[family page](/users-guide/models/local-models/qwen-image/#lora).
+Krea-2 LoRAs also load in ComfyUI's `diffusion_model.` layout, including full (`diff`) layers and `diff_b` bias
+deltas, and in the fal trainer's PEFT layout (`base_model.model.` followed by the native module names); see the
+[family page](/users-guide/models/local-models/krea-2/#lora).
+
Qwen-Image LoRAs also patch the Qwen2.5-VL encoder when the file has text-encoder layers; see the same page.
A Krea-2 Control LoRA is one `.safetensors` file in the layout of
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx
index ad70bac7a8..2589b5c75f 100644
--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx
@@ -195,9 +195,11 @@ feeding the **Style Reference** input of **Denoise - Krea-2**.
## LoRA
-Krea-2 LoRAs (diffusers PEFT format) are supported and apply to both the transformer and — where the
-LoRA includes text-encoder layers — the Qwen3-VL encoder. On quantized builds (GGUF, int8, int4, NVFP4) the LoRA
-is applied alongside the packed weights rather than merged into them. LoRAs trained to edit an input image
+Krea-2 LoRAs are supported in the diffusers PEFT, ComfyUI (`diffusion_model.`), fal trainer
+(`base_model.model.` on the native module names) and kohya/LyCORIS layouts, including LoKR and DoRA. Full (`diff`)
+layers and `diff_b` bias deltas, as in Comfy-Org's Turbo LoRA, are applied too. LoRAs apply to both the transformer
+and — where the LoRA includes text-encoder layers — the Qwen3-VL encoder. On quantized builds (GGUF, int8, int4,
+NVFP4) the LoRA is applied alongside the packed weights rather than merged into them. LoRAs trained to edit an input image
need reference images; see [Edit LoRAs](#edit-loras-and-reference-images).
## Edit LoRAs and reference images
diff --git a/invokeai/backend/model_manager/configs/lora.py b/invokeai/backend/model_manager/configs/lora.py
index 3805cb4fe7..30b483fc54 100644
--- a/invokeai/backend/model_manager/configs/lora.py
+++ b/invokeai/backend/model_manager/configs/lora.py
@@ -1562,6 +1562,14 @@ _KREA2_SUPPORTED_LORA_PREFIXES = (
"diffusion_model.txtmlp.",
"diffusion_model.last.linear.",
"base_model.model.transformer.transformer_blocks.",
+ # The fal / Krea trainer's PEFT keys on the native module names.
+ "base_model.model.blocks.",
+ "base_model.model.txtfusion.",
+ "base_model.model.first.",
+ "base_model.model.tmlp.",
+ "base_model.model.tproj.",
+ "base_model.model.txtmlp.",
+ "base_model.model.last.linear.",
"text_encoder.",
"base_model.model.text_encoder.",
)
diff --git a/invokeai/backend/patches/lora_conversions/krea2_lora_conversion_utils.py b/invokeai/backend/patches/lora_conversions/krea2_lora_conversion_utils.py
index 1208e35629..1480e6a076 100644
--- a/invokeai/backend/patches/lora_conversions/krea2_lora_conversion_utils.py
+++ b/invokeai/backend/patches/lora_conversions/krea2_lora_conversion_utils.py
@@ -16,6 +16,8 @@ from typing import Dict
import torch
from invokeai.backend.patches.layers.base_layer_patch import BaseLayerPatch
+from invokeai.backend.patches.layers.lora_layer_base import LoRALayerBase
+from invokeai.backend.patches.layers.param_shape_utils import get_param_shape
from invokeai.backend.patches.layers.utils import any_lora_layer_from_state_dict
from invokeai.backend.patches.lora_conversions.krea2_lora_constants import (
KREA2_LORA_QWEN3VL_PREFIX,
@@ -91,6 +93,15 @@ def _native_krea2_key_to_diffusers(key: str) -> str:
return key
+def _strip_peft_prefix_from_native_key(key: str) -> str:
+ # The fal / Krea trainer saves PEFT keys on the native module names (``base_model.model.first.lora_A``). Give
+ # them the ``diffusion_model.`` prefix so they take the native rename and the transformer prefix stripping.
+ prefix = "base_model.model."
+ if not key.startswith(prefix) or key.startswith((f"{prefix}transformer.", f"{prefix}text_encoder.")):
+ return key
+ return "diffusion_model." + key[len(prefix) :]
+
+
def _maybe_convert_native_krea2_state_dict(
state_dict: Dict[str, torch.Tensor],
) -> Dict[str, torch.Tensor]:
@@ -103,7 +114,7 @@ def _maybe_convert_native_krea2_state_dict(
# `.pt`/`.ckpt` sources can carry non-string keys. They are never native Krea-2 keys, but the
# substring tests in `_looks_like_native_krea2_key` raise TypeError rather than returning False.
is_native = isinstance(key, str) and _looks_like_native_krea2_key(key)
- converted_key = _native_krea2_key_to_diffusers(key) if is_native else key
+ converted_key = _native_krea2_key_to_diffusers(_strip_peft_prefix_from_native_key(key)) if is_native else key
if converted_key in converted_state_dict:
raise ValueError(
f"Krea-2 LoRA has conflicting layers that normalize to the same target '{converted_key}'. "
@@ -118,7 +129,7 @@ def _maybe_convert_kohya_krea2_state_dict(
) -> Dict[str, torch.Tensor]:
"""Rewrite kohya/LyCORIS flattened Krea-2 keys to the dotted native layout, leaving all others untouched."""
# Whether a module can be converted is a property of the *module*, not of each key on its own. A LyCORIS
- # module this converter has no handler for (``hada_w1_a``, ``diff``) has to stay verbatim — see below; LoKr
+ # module this converter has no handler for (``hada_w1_a``) has to stay verbatim — see below; LoKr
# is the exception, its ``lokr_*`` suffixes are known and convert like any other — but LyCORIS also saves
# a sibling ``.alpha`` (and ``.dora_scale`` for the weight-decomposed variants), whose suffix this
# converter *does* recognize. Deciding per key rewrites that sibling alone and splits one module across
@@ -149,7 +160,7 @@ def _maybe_convert_kohya_krea2_state_dict(
# dots into the module path, and the grouper's fallback for an unknown suffix is a blind
# ``rsplit(".", 2)`` — on a dotted path that cuts *inside the module name*, fusing two modules
# into one bogus layer that aborts the whole load. LyCORIS suffixes without a handler here, such as
- # ``.hada_w1_a`` or ``.diff``, hit exactly that. Flattened, they have no interior dot and group
+ # ``.hada_w1_a``, hit exactly that. Flattened, they have no interior dot and group
# harmlessly, so leaving them verbatim keeps them at the pre-existing warn-and-skip behaviour.
if module_path is not None and flat_path in fully_convertible_flat_paths:
converted_key = f"{module_path}{dot}{weight_suffix}"
@@ -231,11 +242,41 @@ def lora_model_from_krea2_state_dict(state_dict: Dict[str, torch.Tensor], alpha:
"(e.g. both a 'transformer.' and a 'diffusion_model.' alias for one logical layer). "
"This mixed layout is unsupported - refusing to silently drop one of the layers."
)
- layers[final_key] = any_lora_layer_from_state_dict(values)
+ layers[final_key] = _layer_from_values(values)
return ModelPatchRaw(layers=layers)
+class _BiasDiffLayer(LoRALayerBase):
+ """A module that only carries a ``diff_b`` bias delta: the weight is left as is."""
+
+ def __init__(self, bias: torch.Tensor):
+ super().__init__(alpha=None, bias=bias)
+
+ def _rank(self) -> int | None:
+ return None
+
+ def get_weight(self, orig_weight: torch.Tensor) -> torch.Tensor:
+ assert self.bias is not None
+ return torch.zeros(get_param_shape(orig_weight), device=self.bias.device, dtype=self.bias.dtype)
+
+
+def _layer_from_values(values: dict[str, torch.Tensor]) -> BaseLayerPatch:
+ # ``FullLayer`` reads ``diff_b`` next to ``diff``. Next to a low-rank pair, or on its own, the layer factory has
+ # no slot for this dense bias delta, so it is attached as the layer's bias here.
+ if "diff" in values or "diff_b" not in values:
+ return any_lora_layer_from_state_dict(values)
+ values = dict(values)
+ diff_b = values.pop("diff_b")
+ if not values:
+ return _BiasDiffLayer(diff_b)
+ layer = any_lora_layer_from_state_dict(values)
+ assert isinstance(layer, LoRALayerBase)
+ # The layers scale their bias by ``alpha / rank`` like the weight, but a ``diff_b`` is stored unscaled.
+ layer.bias = diff_b / layer.scale()
+ return layer
+
+
def _get_lora_layer_values(
layer_key: str, layer_dict: dict[str, torch.Tensor], alpha: float | None
) -> dict[str, torch.Tensor]:
@@ -250,9 +291,10 @@ def _get_lora_layer_values(
"lora_down.weight": layer_dict["lora_A.weight"],
"lora_up.weight": layer_dict["lora_B.weight"],
}
- for magnitude_key in ("dora_scale", "dora_magnitude"):
- if magnitude_key in layer_dict:
- values[magnitude_key] = layer_dict[magnitude_key]
+ # The magnitudes and the ``diff_b`` / ``diff`` deltas keep their names; ``_layer_from_values`` reads them.
+ for passthrough_key in ("dora_scale", "dora_magnitude", "diff_b", "diff"):
+ if passthrough_key in layer_dict:
+ values[passthrough_key] = layer_dict[passthrough_key]
if "alpha" in layer_dict:
values["alpha"] = layer_dict["alpha"]
if alpha is not None:
@@ -281,6 +323,8 @@ _SUFFIX_TO_VALUE_KEY = {
".lora_magnitude_vector.weight": "dora_magnitude",
".magnitude": "dora_magnitude",
".alpha": "alpha",
+ ".diff_b": "diff_b",
+ ".diff": "diff",
**{f".{key}": key for key in LOKR_WEIGHT_KEYS},
}
diff --git a/tests/backend/model_manager/configs/test_krea2_lora_config.py b/tests/backend/model_manager/configs/test_krea2_lora_config.py
index fe7fa05231..efd072978d 100644
--- a/tests/backend/model_manager/configs/test_krea2_lora_config.py
+++ b/tests/backend/model_manager/configs/test_krea2_lora_config.py
@@ -373,6 +373,21 @@ def test_explicit_krea2_override_accepts_single_module_native_lora(_raise_if_not
assert config.base is BaseModelType.Krea2
+@patch("invokeai.backend.model_manager.configs.lora.raise_if_not_file")
+def test_explicit_krea2_override_accepts_fal_peft_native_lora(_raise_if_not_file) -> None:
+ # The fal / Krea trainer writes PEFT keys on the native module names. Block attention alone carries none of the
+ # auto-detection keys, so it must install under an explicit base like its `diffusion_model.` spelling does.
+ mod = MagicMock()
+ mod.load_state_dict.return_value = {
+ "base_model.model.blocks.0.attn.wq.lora_A.weight": object(),
+ "base_model.model.blocks.0.attn.wq.lora_B.weight": object(),
+ }
+
+ config = LoRA_LyCORIS_Krea2_Config.from_model_on_disk(mod, {**_REQUIRED_FIELDS, "base": BaseModelType.Krea2})
+
+ assert config.base is BaseModelType.Krea2
+
+
_LOKR_MODULE = "diffusion_model.txtfusion.layerwise_blocks.0.attn.wq"
diff --git a/tests/backend/patches/lora_conversions/test_krea2_lora_conversion_utils.py b/tests/backend/patches/lora_conversions/test_krea2_lora_conversion_utils.py
index 5bc132c56c..e1decab7df 100644
--- a/tests/backend/patches/lora_conversions/test_krea2_lora_conversion_utils.py
+++ b/tests/backend/patches/lora_conversions/test_krea2_lora_conversion_utils.py
@@ -5,6 +5,7 @@ from diffusers import Krea2Transformer2DModel
from invokeai.backend.model_manager.load.model_loaders.krea2 import KREA2_TRANSFORMER_CONFIG
from invokeai.backend.patches.layers.dora_layer import DoRALayer
+from invokeai.backend.patches.layers.full_layer import FullLayer
from invokeai.backend.patches.layers.lokr_layer import LoKRLayer
from invokeai.backend.patches.layers.lora_layer import LoRALayer
from invokeai.backend.patches.lora_conversions.krea2_lora_constants import (
@@ -373,11 +374,11 @@ def test_unrecognized_kohya_flattened_keys_are_left_untouched(flat_module: str)
@pytest.mark.parametrize(
("lycoris_suffixes", "expected_second_layer"),
[
- # LoKr is a layout this converter understands, so its module un-flattens like any other and the
- # adapter actually applies. The other algorithms below have no handler, so they stay verbatim.
+ # LoKr and full (`diff`) are layouts this converter understands, so the module un-flattens like any other
+ # and the adapter actually applies. LoHa has no handler, so it stays verbatim.
(("lokr_w1", "lokr_w2"), "transformer_blocks.6.attn.to_q"),
(("hada_w1_a", "hada_w1_b", "hada_w2_a", "hada_w2_b"), "lora_unet_blocks_6_attn_wq"),
- (("diff", "diff_b"), "lora_unet_blocks_6_attn_wq"),
+ (("diff", "diff_b"), "transformer_blocks.6.attn.to_q"),
# LyCORIS saves an `alpha` per module, so this is the realistic on-disk shape rather than an
# edge case — see this repo's own captured fixtures. `.alpha` is a suffix the converter knows,
# so deciding per key rewrote it while its siblings stayed verbatim, splitting one module into
@@ -592,3 +593,108 @@ def test_kohya_flattened_lokr_converts_onto_its_real_module() -> None:
assert isinstance(layer, LoKRLayer)
torch.testing.assert_close(layer.get_weight(torch.empty(6, 8)), torch.kron(w1, w2_a @ w2_b))
assert layer.scale() == 4.0 / w2_b.shape[0]
+
+
+def test_native_lora_with_diff_b_applies_the_bias_delta_unscaled() -> None:
+ # ComfyUI-saved LoRAs (e.g. the Krea-2 Turbo LoRA) carry a `diff_b` bias delta next to the low-rank pair.
+ # The delta is stored as is, so the layer's `alpha / rank` scale must not apply to it.
+ diff_b = torch.arange(4, dtype=torch.float32)
+ state_dict = {
+ "diffusion_model.first.lora_down.weight": torch.ones(2, 3),
+ "diffusion_model.first.lora_up.weight": torch.ones(4, 2),
+ "diffusion_model.first.alpha": torch.tensor(1.0),
+ "diffusion_model.first.diff_b": diff_b,
+ }
+
+ model = lora_model_from_krea2_state_dict(state_dict)
+
+ layer = model.layers[f"{KREA2_LORA_TRANSFORMER_PREFIX}img_in"]
+ assert isinstance(layer, LoRALayer)
+ params = layer.get_parameters({"weight": torch.zeros(4, 3), "bias": torch.zeros(4)}, weight=0.5)
+ assert torch.allclose(params["weight"], torch.full((4, 3), 0.5))
+ assert torch.allclose(params["bias"], diff_b * 0.5)
+
+
+def test_native_diff_b_only_module_patches_only_the_bias() -> None:
+ diff_b = torch.arange(4, dtype=torch.float32)
+ state_dict = {
+ "diffusion_model.blocks.0.attn.wq.lora_down.weight": torch.ones(2, 3),
+ "diffusion_model.blocks.0.attn.wq.lora_up.weight": torch.ones(4, 2),
+ "diffusion_model.first.diff_b": diff_b,
+ }
+
+ model = lora_model_from_krea2_state_dict(state_dict)
+
+ layer = model.layers[f"{KREA2_LORA_TRANSFORMER_PREFIX}img_in"]
+ params = layer.get_parameters({"weight": torch.ones(4, 3), "bias": torch.ones(4)}, weight=0.5)
+ assert torch.equal(params["weight"], torch.zeros(4, 3))
+ assert torch.allclose(params["bias"], diff_b * 0.5)
+
+
+def test_native_diff_module_loads_as_a_full_layer() -> None:
+ diff = torch.ones(4, 3)
+ diff_b = torch.ones(4)
+ model = lora_model_from_krea2_state_dict(
+ {"diffusion_model.blocks.0.attn.wq.diff": diff, "diffusion_model.blocks.0.attn.wq.diff_b": diff_b}
+ )
+
+ layer = model.layers[f"{KREA2_LORA_TRANSFORMER_PREFIX}transformer_blocks.0.attn.to_q"]
+ assert isinstance(layer, FullLayer)
+ assert torch.equal(layer.weight, diff)
+ assert layer.bias is not None and torch.equal(layer.bias, diff_b)
+
+
+def test_fal_peft_keys_on_native_modules_match_the_diffusers_layout() -> None:
+ # The fal / Krea trainer writes PEFT keys on the native module names under `base_model.model.`.
+ modules = {"first": "img_in", "blocks.0.attn.wq": "transformer_blocks.0.attn.to_q"}
+ state_dict = {
+ f"base_model.model.{native}.{suffix}.weight": torch.ones(2, 2)
+ for native in modules
+ for suffix in ("lora_A", "lora_B")
+ }
+
+ model = lora_model_from_krea2_state_dict(state_dict)
+
+ assert set(model.layers) == {f"{KREA2_LORA_TRANSFORMER_PREFIX}{diffusers}" for diffusers in modules.values()}
+
+
+ ("module", "layer_key"),
+ [
+ ("diffusion_model.first", "img_in"),
+ ("transformer.transformer_blocks.0.attn.to_q", "transformer_blocks.0.attn.to_q"),
+ ("base_model.model.first", "img_in"),
+ ],
+)
+def test_peft_lora_with_diff_b_keeps_the_bias_delta(module: str, layer_key: str) -> None:
+ diff_b = torch.arange(4, dtype=torch.float32)
+ state_dict = {
+ f"{module}.lora_A.weight": torch.ones(2, 3),
+ f"{module}.lora_B.weight": torch.ones(4, 2),
+ f"{module}.alpha": torch.tensor(1.0),
+ f"{module}.diff_b": diff_b,
+ }
+
+ model = lora_model_from_krea2_state_dict(state_dict)
+
+ layer = model.layers[f"{KREA2_LORA_TRANSFORMER_PREFIX}{layer_key}"]
+ assert isinstance(layer, LoRALayer)
+ params = layer.get_parameters({"weight": torch.zeros(4, 3), "bias": torch.zeros(4)}, weight=0.5)
+ assert torch.allclose(params["weight"], torch.full((4, 3), 0.5))
+ assert torch.allclose(params["bias"], diff_b * 0.5)
+
+
+def test_peft_dora_with_diff_b_keeps_the_bias_delta() -> None:
+ diff_b = torch.arange(4, dtype=torch.float32)
+ state_dict = {
+ "diffusion_model.first.lora_A.weight": torch.ones(2, 3),
+ "diffusion_model.first.lora_B.weight": torch.ones(4, 2),
+ "diffusion_model.first.lora_magnitude_vector.weight": torch.ones(4),
+ "diffusion_model.first.diff_b": diff_b,
+ }
+
+ model = lora_model_from_krea2_state_dict(state_dict)
+
+ layer = model.layers[f"{KREA2_LORA_TRANSFORMER_PREFIX}img_in"]
+ assert isinstance(layer, DoRALayer)
+ assert layer.bias is not None and torch.equal(layer.bias, diff_b)