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

sdxl_lora_elemental_tune.pyの強度適用する処理修正。

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