2vXpSwA7 commited on
Commit
c1a5584
·
verified ·
1 Parent(s): a77578c

Upload sdxl_lora_elemental_tune.py

Browse files
Files changed (1) hide show
  1. sdxl_lora_elemental_tune.py +167 -158
sdxl_lora_elemental_tune.py CHANGED
@@ -7,178 +7,187 @@ from safetensors import safe_open
7
  import math
8
 
9
  def parse_key(key):
10
- match = re.match(r"lora_unet_(input|output|up|down)_blocks_(\d+(?:_\d+)?)_(.+)\.(?:alpha|lora_(?:down|up)\.weight)", key)
11
- if match:
12
- return "unet", match.group(1) + "_blocks", match.group(2), match.group(3)
13
 
14
- match = re.match(r"lora_unet_(mid_block)_(resnets|attentions)_(\d+)_(.+)\.(?:alpha|lora_(?:down|up)\.weight)", key)
15
- if match:
16
- return "unet", match.group(1), f"{match.group(2)}_{match.group(3)}", match.group(4)
17
 
18
- match = re.match(r"lora_unet_(middle_block)_(\d+)_(.+)\.(?:alpha|lora_(?:down|up)\.weight)", key)
19
- if match:
20
- return "unet", match.group(1), match.group(2), match.group(3)
21
 
22
- match = re.match(r"lora_te\d+_text_model_encoder_(.+)\.(?:alpha|lora_(?:down|up)\.weight)", key)
23
- if match:
24
- return "text_encoder", "encoder_layers", match.group(1).split("_")[0], "_".join(match.group(1).split("_")[1:])
25
 
26
- return None, None, None, None
27
 
28
  def extract_lora_hierarchy(lora_tensors, mode="extract"):
29
- lora_hierarchy = {}
30
- lora_key_groups = {"unet": {}, "text_encoder": {}} if mode == "adjust" else None
31
-
32
- for key in lora_tensors:
33
- if key.startswith("lora_unet_"):
34
- model_type, block_type, block_num, layer_key = parse_key(key)
35
-
36
- if model_type and block_type and layer_key:
37
- parts = layer_key.split("_")
38
- if "transformer_blocks" in layer_key:
39
- grouped_key = "_".join(parts[:3] + [parts[3] if len(parts) > 5 else ""])
40
- elif "attentions" in layer_key:
41
- grouped_key = "_".join(parts[:3] + [parts[3] if len(parts) > 5 else ""])
42
- elif "resnets" in layer_key:
43
- grouped_key = "_".join(parts[:3])
44
- else:
45
- grouped_key = layer_key
46
-
47
- if model_type not in lora_hierarchy:
48
- lora_hierarchy[model_type] = {}
49
- if block_type not in lora_hierarchy[model_type]:
50
- lora_hierarchy[model_type][block_type] = {}
51
- if block_num not in lora_hierarchy[model_type][block_type]:
52
- lora_hierarchy[model_type][block_type][block_num] = {}
53
- lora_hierarchy[model_type][block_type][block_num][grouped_key] = 1.0
54
-
55
- if mode == "adjust":
56
- group_key = f"..unet___"
57
- if group_key not in lora_key_groups["unet"]:
58
- lora_key_groups["unet"][group_key] = []
59
- lora_key_groups["unet"][group_key].append(key)
60
-
61
- elif key.startswith("lora_te"):
62
- match = re.match(r"(lora_te\d+)_text_model_encoder_layers_(\d+)_(.+)\.(?:alpha|lora_(?:down|up)\.weight)", key)
63
- if match:
64
- model_section = match.group(1)
65
- block_type = "encoder"
66
- block_num = match.group(2)
67
- layer_key = match.group(3)
68
-
69
- grouped_key = f"layers___"
70
-
71
- if model_section not in lora_hierarchy:
72
- lora_hierarchy[model_section] = {}
73
- if block_type not in lora_hierarchy[model_section]:
74
- lora_hierarchy[model_section][block_type] = {}
75
- lora_hierarchy[model_section][block_type][grouped_key] = 1.0
76
-
77
- if mode == "adjust":
78
- group_key = f"..__"
79
- lora_key_groups["text_encoder"][group_key] = [key]
80
-
81
- return lora_hierarchy if mode == "extract" else lora_key_groups
82
 
83
 
84
  def adjust_lora_weights(lora_path, toml_path, output_path, multiplier=1.0, remove_zero_weight_keys=True):
85
- try:
86
- lora_tensors = load_file(lora_path)
87
- with safe_open(lora_path, framework="pt") as f:
88
- metadata = f.metadata()
89
- except Exception as e:
90
- raise Exception(f"Error loading LoRA model: ")
91
-
92
- try:
93
- with open(toml_path, "r") as f:
94
- lora_config = toml.load(f)
95
- except Exception as e:
96
- raise Exception(f"Error loading TOML file: ")
97
-
98
-
99
- lora_key_groups = extract_lora_hierarchy(lora_tensors, mode="adjust")
100
- adjusted_tensors = {}
101
-
102
- for model_section, model_config in lora_config.items():
103
- if model_section.startswith("lora_te"):
104
- for block_type, layers in model_config.items():
105
- for layer_key, weight in layers.items():
106
- block_num, layer_name = layer_key.replace("layers_", "").split("__")
107
- group_key = f"..__"
108
- if group_key in lora_key_groups["text_encoder"]:
109
- final_weight = weight * multiplier
110
- if not remove_zero_weight_keys or final_weight != 0.0:
111
- for target_key in lora_key_groups["text_encoder"][group_key]:
112
- adjusted_tensors[target_key] = lora_tensors[target_key] * final_weight
113
-
114
- else: # unet
115
- for block_type, block_nums in model_config.items():
116
- for block_num, layer_keys in block_nums.items():
117
- for grouped_key, weight in layer_keys.items():
118
- group_key = f"..unet___"
119
- if group_key in lora_key_groups["unet"]:
120
- for target_key in lora_key_groups["unet"][group_key]:
121
- if target_key in lora_tensors:
122
- if target_key.endswith(".alpha"):
123
- # .alpha は変更しない
124
- adjusted_tensors[target_key] = lora_tensors[target_key]
125
- else:
126
- # lora_down.weight, lora_up.weight は平方根を適用
127
- final_weight = weight * multiplier
128
- if not remove_zero_weight_keys or final_weight != 0.0:
129
- adjusted_tensors[target_key] = lora_tensors[target_key] * math.sqrt(final_weight)
130
-
131
-
132
- try:
133
- save_file(adjusted_tensors, output_path, metadata)
134
- except Exception as e:
135
- raise Exception(f"Error saving adjusted model: ")
 
 
 
 
 
 
 
 
 
136
 
137
 
138
  def write_toml(lora_hierarchy, output_path):
139
- try:
140
- with open(output_path, "w") as f:
141
- toml.dump(lora_hierarchy, f)
142
- except Exception as e:
143
- raise Exception(f"Error writing TOML file: ")
144
 
145
 
146
  def main():
147
- parser = argparse.ArgumentParser(description="Extract or adjust LoRA weights based on a TOML config.")
148
- subparsers = parser.add_subparsers(dest="mode", help="Choose mode: 'extract' or 'adjust'")
149
-
150
- # Extract mode
151
- parser_extract = subparsers.add_parser("extract", help="Extract LoRA hierarchy to a TOML file")
152
- parser_extract.add_argument("--lora_path", required=True, help="Path to the LoRA safetensors file")
153
- parser_extract.add_argument("--output_path", required=True, help="Path to the output TOML file")
154
-
155
- # Adjust mode
156
- parser_adjust = subparsers.add_parser("adjust", help="Adjust LoRA weights based on a TOML config.")
157
- parser_adjust.add_argument("--lora_path", required=True, help="Path to the LoRA safetensors file")
158
- parser_adjust.add_argument("--toml_path", required=True, help="Path to the TOML config file")
159
- parser_adjust.add_argument("--output_path", required=True, help="Path to the output safetensors file")
160
- parser_adjust.add_argument("--multiplier", type=float, default=1.0, help="Global multiplier for the LoRA weights")
161
- parser_adjust.add_argument("--remove_zero_weight_keys", action="store_true",
162
- help="Remove keys with resulting weight of 0. Useful for reducing file size.")
163
-
164
- args = parser.parse_args()
165
-
166
- try:
167
- if args.mode == "extract":
168
- lora_tensors = load_file(args.lora_path)
169
- lora_hierarchy = extract_lora_hierarchy(lora_tensors)
170
- write_toml(lora_hierarchy, args.output_path)
171
- print(f"Successfully extracted LoRA hierarchy to {args.output_path}")
172
-
173
- elif args.mode == "adjust":
174
- adjust_lora_weights(args.lora_path, args.toml_path, args.output_path, args.multiplier, args.remove_zero_weight_keys)
175
- print(f"Successfully adjusted LoRA weights and saved to {args.output_path}")
176
-
177
- else:
178
- parser.print_help()
179
-
180
- except Exception as e:
181
- print(f"An error occurred: ")
182
 
183
  if __name__ == "__main__":
184
- main()
 
7
  import math
8
 
9
  def parse_key(key):
10
+ match = re.match(r"lora_unet_(input|output|up|down)_blocks_(\d+(?:_\d+)?)_(.+)\.(?:alpha|lora_(?:down|up)\.weight)", key)
11
+ if match:
12
+ return "unet", match.group(1) + "_blocks", match.group(2), match.group(3)
13
 
14
+ match = re.match(r"lora_unet_(mid_block)_(resnets|attentions)_(\d+)_(.+)\.(?:alpha|lora_(?:down|up)\.weight)", key)
15
+ if match:
16
+ return "unet", match.group(1), f"{match.group(2)}_{match.group(3)}", match.group(4)
17
 
18
+ match = re.match(r"lora_unet_(middle_block)_(\d+)_(.+)\.(?:alpha|lora_(?:down|up)\.weight)", key)
19
+ if match:
20
+ return "unet", match.group(1), match.group(2), match.group(3)
21
 
22
+ match = re.match(r"lora_te\d+_text_model_encoder_(.+)\.(?:alpha|lora_(?:down|up)\.weight)", key)
23
+ if match:
24
+ return "text_encoder", "encoder_layers", match.group(1).split("_")[0], "_".join(match.group(1).split("_")[1:])
25
 
26
+ return None, None, None, None
27
 
28
  def extract_lora_hierarchy(lora_tensors, mode="extract"):
29
+ lora_hierarchy = {}
30
+ lora_key_groups = {"unet": {}, "text_encoder": {}} if mode == "adjust" else None
31
+
32
+ for key in lora_tensors:
33
+ if key.startswith("lora_unet_"):
34
+ model_type, block_type, block_num, layer_key = parse_key(key)
35
+
36
+ if model_type and block_type and layer_key:
37
+ parts = layer_key.split("_")
38
+ if "transformer_blocks" in layer_key:
39
+ grouped_key = "_".join(parts[:3] + [parts[3] if len(parts) > 5 else ""])
40
+ elif "attentions" in layer_key:
41
+ grouped_key = "_".join(parts[:3] + [parts[3] if len(parts) > 5 else ""])
42
+ elif "resnets" in layer_key:
43
+ grouped_key = "_".join(parts[:3])
44
+ else:
45
+ grouped_key = layer_key
46
+
47
+ if model_type not in lora_hierarchy:
48
+ lora_hierarchy[model_type] = {}
49
+ if block_type not in lora_hierarchy[model_type]:
50
+ lora_hierarchy[model_type][block_type] = {}
51
+ if block_num not in lora_hierarchy[model_type][block_type]:
52
+ lora_hierarchy[model_type][block_type][block_num] = {}
53
+ lora_hierarchy[model_type][block_type][block_num][grouped_key] = 1.0
54
+
55
+ if mode == "adjust":
56
+ group_key = f"..unet_{block_type}_{block_num}_{grouped_key}"
57
+ if group_key not in lora_key_groups["unet"]:
58
+ lora_key_groups["unet"][group_key] = []
59
+ lora_key_groups["unet"][group_key].append(key)
60
+
61
+ elif key.startswith("lora_te"):
62
+ match = re.match(r"(lora_te\d+)_text_model_encoder_layers_(\d+)_(.+)\.(?:alpha|lora_(?:down|up)\.weight)", key)
63
+ if match:
64
+ model_section = match.group(1)
65
+ block_type = "encoder"
66
+ block_num = match.group(2)
67
+ layer_key = match.group(3)
68
+
69
+ grouped_key = f"layers_{block_num}__{layer_key}"
70
+
71
+ if model_section not in lora_hierarchy:
72
+ lora_hierarchy[model_section] = {}
73
+ if block_type not in lora_hierarchy[model_section]:
74
+ lora_hierarchy[model_section][block_type] = {}
75
+ lora_hierarchy[model_section][block_type][grouped_key] = 1.0
76
+
77
+ if mode == "adjust":
78
+ group_key = f"..{model_section}_{block_num}_{layer_key}"
79
+ lora_key_groups["text_encoder"][group_key] = [key]
80
+
81
+ return lora_hierarchy if mode == "extract" else lora_key_groups
82
 
83
 
84
  def adjust_lora_weights(lora_path, toml_path, output_path, multiplier=1.0, remove_zero_weight_keys=True):
85
+ try:
86
+ lora_tensors = load_file(lora_path)
87
+ with safe_open(lora_path, framework="pt") as f:
88
+ metadata = f.metadata()
89
+ except Exception as e:
90
+ raise Exception(f"Error loading LoRA model: {e}")
91
+
92
+ try:
93
+ with open(toml_path, "r") as f:
94
+ lora_config = toml.load(f)
95
+ except Exception as e:
96
+ raise Exception(f"Error loading TOML file: {e}")
97
+
98
+
99
+ lora_key_groups = extract_lora_hierarchy(lora_tensors, mode="adjust")
100
+ adjusted_tensors = {}
101
+
102
+ for model_section, model_config in lora_config.items():
103
+ if model_section.startswith("lora_te"):
104
+ for block_type, layers in model_config.items():
105
+ for layer_key, weight in layers.items():
106
+ block_num, layer_name = layer_key.replace("layers_", "").split("__")
107
+ group_key = f"..{model_section}_{block_num}_{layer_name}"
108
+ if group_key in lora_key_groups["text_encoder"]:
109
+ final_weight = weight * multiplier
110
+ if not remove_zero_weight_keys or final_weight != 0.0:
111
+ for target_key in lora_key_groups["text_encoder"][group_key]:
112
+ if target_key.endswith(".alpha"):
113
+ final_weight = weight * multiplier
114
+ if not remove_zero_weight_keys or final_weight != 0.0:
115
+ adjusted_tensors[target_key] = lora_tensors[target_key]
116
+ else:
117
+ final_weight = weight * multiplier
118
+ if not remove_zero_weight_keys or final_weight != 0.0:
119
+ adjusted_tensors[target_key] = lora_tensors[target_key] * math.sqrt(final_weight)
120
+
121
+ else: # unet
122
+ for block_type, block_nums in model_config.items():
123
+ for block_num, layer_keys in block_nums.items():
124
+ for grouped_key, weight in layer_keys.items():
125
+ group_key = f"..unet_{block_type}_{block_num}_{grouped_key}"
126
+ if group_key in lora_key_groups["unet"]:
127
+ final_weight = weight * multiplier
128
+ if not remove_zero_weight_keys or final_weight != 0.0:
129
+ for target_key in lora_key_groups["unet"][group_key]:
130
+ if target_key.endswith(".alpha"):
131
+ final_weight = weight * multiplier
132
+ if not remove_zero_weight_keys or final_weight != 0.0:
133
+ adjusted_tensors[target_key] = lora_tensors[target_key]
134
+ else:
135
+ final_weight = weight * multiplier
136
+ if not remove_zero_weight_keys or final_weight != 0.0:
137
+ adjusted_tensors[target_key] = lora_tensors[target_key] * math.sqrt(final_weight)
138
+
139
+
140
+
141
+ try:
142
+ save_file(adjusted_tensors, output_path, metadata)
143
+ except Exception as e:
144
+ raise Exception(f"Error saving adjusted model: {e}")
145
 
146
 
147
  def write_toml(lora_hierarchy, output_path):
148
+ try:
149
+ with open(output_path, "w") as f:
150
+ toml.dump(lora_hierarchy, f)
151
+ except Exception as e:
152
+ raise Exception(f"Error writing TOML file: {e}")
153
 
154
 
155
  def main():
156
+ parser = argparse.ArgumentParser(description="Extract or adjust LoRA weights based on a TOML config.")
157
+ subparsers = parser.add_subparsers(dest="mode", help="Choose mode: 'extract' or 'adjust'")
158
+
159
+ # Extract mode
160
+ parser_extract = subparsers.add_parser("extract", help="Extract LoRA hierarchy to a TOML file")
161
+ parser_extract.add_argument("--lora_path", required=True, help="Path to the LoRA safetensors file")
162
+ parser_extract.add_argument("--output_path", required=True, help="Path to the output TOML file")
163
+
164
+ # Adjust mode
165
+ parser_adjust = subparsers.add_parser("adjust", help="Adjust LoRA weights based on a TOML config.")
166
+ parser_adjust.add_argument("--lora_path", required=True, help="Path to the LoRA safetensors file")
167
+ parser_adjust.add_argument("--toml_path", required=True, help="Path to the TOML config file")
168
+ parser_adjust.add_argument("--output_path", required=True, help="Path to the output safetensors file")
169
+ parser_adjust.add_argument("--multiplier", type=float, default=1.0, help="Global multiplier for the LoRA weights")
170
+ parser_adjust.add_argument("--remove_zero_weight_keys", action="store_true",
171
+ help="Remove keys with resulting weight of 0. Useful for reducing file size.")
172
+
173
+ args = parser.parse_args()
174
+
175
+ try:
176
+ if args.mode == "extract":
177
+ lora_tensors = load_file(args.lora_path)
178
+ lora_hierarchy = extract_lora_hierarchy(lora_tensors)
179
+ write_toml(lora_hierarchy, args.output_path)
180
+ print(f"Successfully extracted LoRA hierarchy to {args.output_path}")
181
+
182
+ elif args.mode == "adjust":
183
+ adjust_lora_weights(args.lora_path, args.toml_path, args.output_path, args.multiplier, args.remove_zero_weight_keys)
184
+ print(f"Successfully adjusted LoRA weights and saved to {args.output_path}")
185
+
186
+ else:
187
+ parser.print_help()
188
+
189
+ except Exception as e:
190
+ print(f"An error occurred: {e}")
191
 
192
  if __name__ == "__main__":
193
+ main()