Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

model_patcher.py 16 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
  1. import torch
  2. import copy
  3. import inspect
  4. import ldm_patched.modules.utils
  5. import ldm_patched.modules.model_management
  6. class ModelPatcher:
  7. def __init__(self, model, load_device, offload_device, size=0, current_device=None, weight_inplace_update=False):
  8. self.size = size
  9. self.model = model
  10. self.patches = {}
  11. self.backup = {}
  12. self.object_patches = {}
  13. self.object_patches_backup = {}
  14. self.model_options = {"transformer_options":{}}
  15. self.model_size()
  16. self.load_device = load_device
  17. self.offload_device = offload_device
  18. if current_device is None:
  19. self.current_device = self.offload_device
  20. else:
  21. self.current_device = current_device
  22. self.weight_inplace_update = weight_inplace_update
  23. def model_size(self):
  24. if self.size > 0:
  25. return self.size
  26. model_sd = self.model.state_dict()
  27. self.size = ldm_patched.modules.model_management.module_size(self.model)
  28. self.model_keys = set(model_sd.keys())
  29. return self.size
  30. def clone(self):
  31. n = ModelPatcher(self.model, self.load_device, self.offload_device, self.size, self.current_device, weight_inplace_update=self.weight_inplace_update)
  32. n.patches = {}
  33. for k in self.patches:
  34. n.patches[k] = self.patches[k][:]
  35. n.object_patches = self.object_patches.copy()
  36. n.model_options = copy.deepcopy(self.model_options)
  37. n.model_keys = self.model_keys
  38. return n
  39. def is_clone(self, other):
  40. if hasattr(other, 'model') and self.model is other.model:
  41. return True
  42. return False
  43. def memory_required(self, input_shape):
  44. return self.model.memory_required(input_shape=input_shape)
  45. def set_model_sampler_cfg_function(self, sampler_cfg_function, disable_cfg1_optimization=False):
  46. if len(inspect.signature(sampler_cfg_function).parameters) == 3:
  47. self.model_options["sampler_cfg_function"] = lambda args: sampler_cfg_function(args["cond"], args["uncond"], args["cond_scale"]) #Old way
  48. else:
  49. self.model_options["sampler_cfg_function"] = sampler_cfg_function
  50. if disable_cfg1_optimization:
  51. self.model_options["disable_cfg1_optimization"] = True
  52. def set_model_sampler_post_cfg_function(self, post_cfg_function, disable_cfg1_optimization=False):
  53. self.model_options["sampler_post_cfg_function"] = self.model_options.get("sampler_post_cfg_function", []) + [post_cfg_function]
  54. if disable_cfg1_optimization:
  55. self.model_options["disable_cfg1_optimization"] = True
  56. def set_model_unet_function_wrapper(self, unet_wrapper_function):
  57. self.model_options["model_function_wrapper"] = unet_wrapper_function
  58. def set_model_patch(self, patch, name):
  59. to = self.model_options["transformer_options"]
  60. if "patches" not in to:
  61. to["patches"] = {}
  62. to["patches"][name] = to["patches"].get(name, []) + [patch]
  63. def set_model_patch_replace(self, patch, name, block_name, number, transformer_index=None):
  64. to = self.model_options["transformer_options"]
  65. if "patches_replace" not in to:
  66. to["patches_replace"] = {}
  67. if name not in to["patches_replace"]:
  68. to["patches_replace"][name] = {}
  69. if transformer_index is not None:
  70. block = (block_name, number, transformer_index)
  71. else:
  72. block = (block_name, number)
  73. to["patches_replace"][name][block] = patch
  74. def set_model_attn1_patch(self, patch):
  75. self.set_model_patch(patch, "attn1_patch")
  76. def set_model_attn2_patch(self, patch):
  77. self.set_model_patch(patch, "attn2_patch")
  78. def set_model_attn1_replace(self, patch, block_name, number, transformer_index=None):
  79. self.set_model_patch_replace(patch, "attn1", block_name, number, transformer_index)
  80. def set_model_attn2_replace(self, patch, block_name, number, transformer_index=None):
  81. self.set_model_patch_replace(patch, "attn2", block_name, number, transformer_index)
  82. def set_model_attn1_output_patch(self, patch):
  83. self.set_model_patch(patch, "attn1_output_patch")
  84. def set_model_attn2_output_patch(self, patch):
  85. self.set_model_patch(patch, "attn2_output_patch")
  86. def set_model_input_block_patch(self, patch):
  87. self.set_model_patch(patch, "input_block_patch")
  88. def set_model_input_block_patch_after_skip(self, patch):
  89. self.set_model_patch(patch, "input_block_patch_after_skip")
  90. def set_model_output_block_patch(self, patch):
  91. self.set_model_patch(patch, "output_block_patch")
  92. def add_object_patch(self, name, obj):
  93. self.object_patches[name] = obj
  94. def model_patches_to(self, device):
  95. to = self.model_options["transformer_options"]
  96. if "patches" in to:
  97. patches = to["patches"]
  98. for name in patches:
  99. patch_list = patches[name]
  100. for i in range(len(patch_list)):
  101. if hasattr(patch_list[i], "to"):
  102. patch_list[i] = patch_list[i].to(device)
  103. if "patches_replace" in to:
  104. patches = to["patches_replace"]
  105. for name in patches:
  106. patch_list = patches[name]
  107. for k in patch_list:
  108. if hasattr(patch_list[k], "to"):
  109. patch_list[k] = patch_list[k].to(device)
  110. if "model_function_wrapper" in self.model_options:
  111. wrap_func = self.model_options["model_function_wrapper"]
  112. if hasattr(wrap_func, "to"):
  113. self.model_options["model_function_wrapper"] = wrap_func.to(device)
  114. def model_dtype(self):
  115. if hasattr(self.model, "get_dtype"):
  116. return self.model.get_dtype()
  117. def add_patches(self, patches, strength_patch=1.0, strength_model=1.0):
  118. p = set()
  119. for k in patches:
  120. if k in self.model_keys:
  121. p.add(k)
  122. current_patches = self.patches.get(k, [])
  123. current_patches.append((strength_patch, patches[k], strength_model))
  124. self.patches[k] = current_patches
  125. return list(p)
  126. def get_key_patches(self, filter_prefix=None):
  127. ldm_patched.modules.model_management.unload_model_clones(self)
  128. model_sd = self.model_state_dict()
  129. p = {}
  130. for k in model_sd:
  131. if filter_prefix is not None:
  132. if not k.startswith(filter_prefix):
  133. continue
  134. if k in self.patches:
  135. p[k] = [model_sd[k]] + self.patches[k]
  136. else:
  137. p[k] = (model_sd[k],)
  138. return p
  139. def model_state_dict(self, filter_prefix=None):
  140. sd = self.model.state_dict()
  141. keys = list(sd.keys())
  142. if filter_prefix is not None:
  143. for k in keys:
  144. if not k.startswith(filter_prefix):
  145. sd.pop(k)
  146. return sd
  147. def patch_model(self, device_to=None, patch_weights=True):
  148. for k in self.object_patches:
  149. old = getattr(self.model, k)
  150. if k not in self.object_patches_backup:
  151. self.object_patches_backup[k] = old
  152. setattr(self.model, k, self.object_patches[k])
  153. if patch_weights:
  154. model_sd = self.model_state_dict()
  155. for key in self.patches:
  156. if key not in model_sd:
  157. print("could not patch. key doesn't exist in model:", key)
  158. continue
  159. weight = model_sd[key]
  160. inplace_update = self.weight_inplace_update
  161. if key not in self.backup:
  162. self.backup[key] = weight.to(device=self.offload_device, copy=inplace_update)
  163. if device_to is not None:
  164. temp_weight = ldm_patched.modules.model_management.cast_to_device(weight, device_to, torch.float32, copy=True)
  165. else:
  166. temp_weight = weight.to(torch.float32, copy=True)
  167. out_weight = self.calculate_weight(self.patches[key], temp_weight, key).to(weight.dtype)
  168. if inplace_update:
  169. ldm_patched.modules.utils.copy_to_param(self.model, key, out_weight)
  170. else:
  171. ldm_patched.modules.utils.set_attr(self.model, key, out_weight)
  172. del temp_weight
  173. if device_to is not None:
  174. self.model.to(device_to)
  175. self.current_device = device_to
  176. return self.model
  177. def calculate_weight(self, patches, weight, key):
  178. for p in patches:
  179. alpha = p[0]
  180. v = p[1]
  181. strength_model = p[2]
  182. if strength_model != 1.0:
  183. weight *= strength_model
  184. if isinstance(v, list):
  185. v = (self.calculate_weight(v[1:], v[0].clone(), key), )
  186. if len(v) == 1:
  187. patch_type = "diff"
  188. elif len(v) == 2:
  189. patch_type = v[0]
  190. v = v[1]
  191. if patch_type == "diff":
  192. w1 = v[0]
  193. if alpha != 0.0:
  194. if w1.shape != weight.shape:
  195. print("WARNING SHAPE MISMATCH {} WEIGHT NOT MERGED {} != {}".format(key, w1.shape, weight.shape))
  196. else:
  197. weight += alpha * ldm_patched.modules.model_management.cast_to_device(w1, weight.device, weight.dtype)
  198. elif patch_type == "lora": #lora/locon
  199. mat1 = ldm_patched.modules.model_management.cast_to_device(v[0], weight.device, torch.float32)
  200. mat2 = ldm_patched.modules.model_management.cast_to_device(v[1], weight.device, torch.float32)
  201. if v[2] is not None:
  202. alpha *= v[2] / mat2.shape[0]
  203. if v[3] is not None:
  204. #locon mid weights, hopefully the math is fine because I didn't properly test it
  205. mat3 = ldm_patched.modules.model_management.cast_to_device(v[3], weight.device, torch.float32)
  206. final_shape = [mat2.shape[1], mat2.shape[0], mat3.shape[2], mat3.shape[3]]
  207. mat2 = torch.mm(mat2.transpose(0, 1).flatten(start_dim=1), mat3.transpose(0, 1).flatten(start_dim=1)).reshape(final_shape).transpose(0, 1)
  208. try:
  209. weight += (alpha * torch.mm(mat1.flatten(start_dim=1), mat2.flatten(start_dim=1))).reshape(weight.shape).type(weight.dtype)
  210. except Exception as e:
  211. print("ERROR", key, e)
  212. elif patch_type == "lokr":
  213. w1 = v[0]
  214. w2 = v[1]
  215. w1_a = v[3]
  216. w1_b = v[4]
  217. w2_a = v[5]
  218. w2_b = v[6]
  219. t2 = v[7]
  220. dim = None
  221. if w1 is None:
  222. dim = w1_b.shape[0]
  223. w1 = torch.mm(ldm_patched.modules.model_management.cast_to_device(w1_a, weight.device, torch.float32),
  224. ldm_patched.modules.model_management.cast_to_device(w1_b, weight.device, torch.float32))
  225. else:
  226. w1 = ldm_patched.modules.model_management.cast_to_device(w1, weight.device, torch.float32)
  227. if w2 is None:
  228. dim = w2_b.shape[0]
  229. if t2 is None:
  230. w2 = torch.mm(ldm_patched.modules.model_management.cast_to_device(w2_a, weight.device, torch.float32),
  231. ldm_patched.modules.model_management.cast_to_device(w2_b, weight.device, torch.float32))
  232. else:
  233. w2 = torch.einsum('i j k l, j r, i p -> p r k l',
  234. ldm_patched.modules.model_management.cast_to_device(t2, weight.device, torch.float32),
  235. ldm_patched.modules.model_management.cast_to_device(w2_b, weight.device, torch.float32),
  236. ldm_patched.modules.model_management.cast_to_device(w2_a, weight.device, torch.float32))
  237. else:
  238. w2 = ldm_patched.modules.model_management.cast_to_device(w2, weight.device, torch.float32)
  239. if len(w2.shape) == 4:
  240. w1 = w1.unsqueeze(2).unsqueeze(2)
  241. if v[2] is not None and dim is not None:
  242. alpha *= v[2] / dim
  243. try:
  244. weight += alpha * torch.kron(w1, w2).reshape(weight.shape).type(weight.dtype)
  245. except Exception as e:
  246. print("ERROR", key, e)
  247. elif patch_type == "loha":
  248. w1a = v[0]
  249. w1b = v[1]
  250. if v[2] is not None:
  251. alpha *= v[2] / w1b.shape[0]
  252. w2a = v[3]
  253. w2b = v[4]
  254. if v[5] is not None: #cp decomposition
  255. t1 = v[5]
  256. t2 = v[6]
  257. m1 = torch.einsum('i j k l, j r, i p -> p r k l',
  258. ldm_patched.modules.model_management.cast_to_device(t1, weight.device, torch.float32),
  259. ldm_patched.modules.model_management.cast_to_device(w1b, weight.device, torch.float32),
  260. ldm_patched.modules.model_management.cast_to_device(w1a, weight.device, torch.float32))
  261. m2 = torch.einsum('i j k l, j r, i p -> p r k l',
  262. ldm_patched.modules.model_management.cast_to_device(t2, weight.device, torch.float32),
  263. ldm_patched.modules.model_management.cast_to_device(w2b, weight.device, torch.float32),
  264. ldm_patched.modules.model_management.cast_to_device(w2a, weight.device, torch.float32))
  265. else:
  266. m1 = torch.mm(ldm_patched.modules.model_management.cast_to_device(w1a, weight.device, torch.float32),
  267. ldm_patched.modules.model_management.cast_to_device(w1b, weight.device, torch.float32))
  268. m2 = torch.mm(ldm_patched.modules.model_management.cast_to_device(w2a, weight.device, torch.float32),
  269. ldm_patched.modules.model_management.cast_to_device(w2b, weight.device, torch.float32))
  270. try:
  271. weight += (alpha * m1 * m2).reshape(weight.shape).type(weight.dtype)
  272. except Exception as e:
  273. print("ERROR", key, e)
  274. elif patch_type == "glora":
  275. if v[4] is not None:
  276. alpha *= v[4] / v[0].shape[0]
  277. a1 = ldm_patched.modules.model_management.cast_to_device(v[0].flatten(start_dim=1), weight.device, torch.float32)
  278. a2 = ldm_patched.modules.model_management.cast_to_device(v[1].flatten(start_dim=1), weight.device, torch.float32)
  279. b1 = ldm_patched.modules.model_management.cast_to_device(v[2].flatten(start_dim=1), weight.device, torch.float32)
  280. b2 = ldm_patched.modules.model_management.cast_to_device(v[3].flatten(start_dim=1), weight.device, torch.float32)
  281. weight += ((torch.mm(b2, b1) + torch.mm(torch.mm(weight.flatten(start_dim=1), a2), a1)) * alpha).reshape(weight.shape).type(weight.dtype)
  282. else:
  283. print("patch type not recognized", patch_type, key)
  284. return weight
  285. def unpatch_model(self, device_to=None):
  286. keys = list(self.backup.keys())
  287. if self.weight_inplace_update:
  288. for k in keys:
  289. ldm_patched.modules.utils.copy_to_param(self.model, k, self.backup[k])
  290. else:
  291. for k in keys:
  292. ldm_patched.modules.utils.set_attr(self.model, k, self.backup[k])
  293. self.backup = {}
  294. if device_to is not None:
  295. self.model.to(device_to)
  296. self.current_device = device_to
  297. keys = list(self.object_patches_backup.keys())
  298. for k in keys:
  299. setattr(self.model, k, self.object_patches_backup[k])
  300. self.object_patches_backup = {}
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...