jiuface commited on
Commit
ffc1f89
1 Parent(s): cb1c43b

Create lora_loading_patch.py

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