Spaces:
Running
on
Zero
Running
on
Zero
Create lora_loading_patch.py
Browse files- lora_loading_patch.py +116 -0
lora_loading_patch.py
ADDED
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from diffusers.utils import (
|
2 |
+
convert_unet_state_dict_to_peft,
|
3 |
+
get_peft_kwargs,
|
4 |
+
is_peft_version,
|
5 |
+
get_adapter_name,
|
6 |
+
logging,
|
7 |
+
)
|
8 |
+
|
9 |
+
logger = logging.get_logger(__name__)
|
10 |
+
|
11 |
+
|
12 |
+
# patching inject_adapter_in_model and load_peft_state_dict with low_cpu_mem_usage=True until it's merged into diffusers
|
13 |
+
def load_lora_into_transformer(
|
14 |
+
cls, state_dict, network_alphas, transformer, adapter_name=None, _pipeline=None
|
15 |
+
):
|
16 |
+
"""
|
17 |
+
This will load the LoRA layers specified in `state_dict` into `transformer`.
|
18 |
+
|
19 |
+
Parameters:
|
20 |
+
state_dict (`dict`):
|
21 |
+
A standard state dict containing the lora layer parameters. The keys can either be indexed directly
|
22 |
+
into the unet or prefixed with an additional `unet` which can be used to distinguish between text
|
23 |
+
encoder lora layers.
|
24 |
+
network_alphas (`Dict[str, float]`):
|
25 |
+
The value of the network alpha used for stable learning and preventing underflow. This value has the
|
26 |
+
same meaning as the `--network_alpha` option in the kohya-ss trainer script. Refer to [this
|
27 |
+
link](https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning).
|
28 |
+
transformer (`SD3Transformer2DModel`):
|
29 |
+
The Transformer model to load the LoRA layers into.
|
30 |
+
adapter_name (`str`, *optional*):
|
31 |
+
Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
|
32 |
+
`default_{i}` where i is the total number of adapters being loaded.
|
33 |
+
"""
|
34 |
+
from peft import LoraConfig, inject_adapter_in_model, set_peft_model_state_dict
|
35 |
+
|
36 |
+
keys = list(state_dict.keys())
|
37 |
+
|
38 |
+
transformer_keys = [k for k in keys if k.startswith(cls.transformer_name)]
|
39 |
+
state_dict = {
|
40 |
+
k.replace(f"{cls.transformer_name}.", ""): v
|
41 |
+
for k, v in state_dict.items()
|
42 |
+
if k in transformer_keys
|
43 |
+
}
|
44 |
+
|
45 |
+
if len(state_dict.keys()) > 0:
|
46 |
+
# check with first key if is not in peft format
|
47 |
+
first_key = next(iter(state_dict.keys()))
|
48 |
+
if "lora_A" not in first_key:
|
49 |
+
state_dict = convert_unet_state_dict_to_peft(state_dict)
|
50 |
+
|
51 |
+
if adapter_name in getattr(transformer, "peft_config", {}):
|
52 |
+
raise ValueError(
|
53 |
+
f"Adapter name {adapter_name} already in use in the transformer - please select a new adapter name."
|
54 |
+
)
|
55 |
+
|
56 |
+
rank = {}
|
57 |
+
for key, val in state_dict.items():
|
58 |
+
if "lora_B" in key:
|
59 |
+
rank[key] = val.shape[1]
|
60 |
+
|
61 |
+
if network_alphas is not None and len(network_alphas) >= 1:
|
62 |
+
prefix = cls.transformer_name
|
63 |
+
alpha_keys = [
|
64 |
+
k
|
65 |
+
for k in network_alphas.keys()
|
66 |
+
if k.startswith(prefix) and k.split(".")[0] == prefix
|
67 |
+
]
|
68 |
+
network_alphas = {
|
69 |
+
k.replace(f"{prefix}.", ""): v
|
70 |
+
for k, v in network_alphas.items()
|
71 |
+
if k in alpha_keys
|
72 |
+
}
|
73 |
+
|
74 |
+
lora_config_kwargs = get_peft_kwargs(
|
75 |
+
rank, network_alpha_dict=network_alphas, peft_state_dict=state_dict
|
76 |
+
)
|
77 |
+
if "use_dora" in lora_config_kwargs:
|
78 |
+
if lora_config_kwargs["use_dora"] and is_peft_version("<", "0.9.0"):
|
79 |
+
raise ValueError(
|
80 |
+
"You need `peft` 0.9.0 at least to use DoRA-enabled LoRAs. Please upgrade your installation of `peft`."
|
81 |
+
)
|
82 |
+
else:
|
83 |
+
lora_config_kwargs.pop("use_dora")
|
84 |
+
lora_config = LoraConfig(**lora_config_kwargs)
|
85 |
+
|
86 |
+
# adapter_name
|
87 |
+
if adapter_name is None:
|
88 |
+
adapter_name = get_adapter_name(transformer)
|
89 |
+
|
90 |
+
# In case the pipeline has been already offloaded to CPU - temporarily remove the hooks
|
91 |
+
# otherwise loading LoRA weights will lead to an error
|
92 |
+
is_model_cpu_offload, is_sequential_cpu_offload = (
|
93 |
+
cls._optionally_disable_offloading(_pipeline)
|
94 |
+
)
|
95 |
+
|
96 |
+
inject_adapter_in_model(
|
97 |
+
lora_config, transformer, adapter_name=adapter_name, low_cpu_mem_usage=True
|
98 |
+
)
|
99 |
+
incompatible_keys = set_peft_model_state_dict(
|
100 |
+
transformer, state_dict, adapter_name, low_cpu_mem_usage=True
|
101 |
+
)
|
102 |
+
|
103 |
+
if incompatible_keys is not None:
|
104 |
+
# check only for unexpected keys
|
105 |
+
unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
|
106 |
+
if unexpected_keys:
|
107 |
+
logger.warning(
|
108 |
+
f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
|
109 |
+
f" {unexpected_keys}. "
|
110 |
+
)
|
111 |
+
|
112 |
+
# Offload back.
|
113 |
+
if is_model_cpu_offload:
|
114 |
+
_pipeline.enable_model_cpu_offload()
|
115 |
+
elif is_sequential_cpu_offload:
|
116 |
+
_pipeline.enable_sequential_cpu_offload()
|