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

Upload sdxl_lora_elemental_tune.py

Browse files
Files changed (1) hide show
  1. sdxl_lora_elemental_tune.py +178 -0
sdxl_lora_elemental_tune.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ 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()