PennyJX commited on
Commit
8e573dc
1 Parent(s): be98f44

Upload 2 files

Browse files
modules/hypernetworks/hypernetwork.py ADDED
@@ -0,0 +1,782 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import glob
3
+ import html
4
+ import os
5
+ import inspect
6
+ from contextlib import closing
7
+
8
+ import modules.textual_inversion.dataset
9
+ import torch
10
+ import tqdm
11
+ from einops import rearrange, repeat
12
+ from ldm.util import default
13
+ from modules import devices, sd_models, shared, sd_samplers, hashes, sd_hijack_checkpoint, errors
14
+ from modules.textual_inversion import textual_inversion, logging
15
+ from modules.textual_inversion.learn_schedule import LearnRateScheduler
16
+ from torch import einsum
17
+ from torch.nn.init import normal_, xavier_normal_, xavier_uniform_, kaiming_normal_, kaiming_uniform_, zeros_
18
+
19
+ from collections import deque
20
+ from statistics import stdev, mean
21
+
22
+
23
+ optimizer_dict = {optim_name : cls_obj for optim_name, cls_obj in inspect.getmembers(torch.optim, inspect.isclass) if optim_name != "Optimizer"}
24
+
25
+ class HypernetworkModule(torch.nn.Module):
26
+ activation_dict = {
27
+ "linear": torch.nn.Identity,
28
+ "relu": torch.nn.ReLU,
29
+ "leakyrelu": torch.nn.LeakyReLU,
30
+ "elu": torch.nn.ELU,
31
+ "swish": torch.nn.Hardswish,
32
+ "tanh": torch.nn.Tanh,
33
+ "sigmoid": torch.nn.Sigmoid,
34
+ }
35
+ activation_dict.update({cls_name.lower(): cls_obj for cls_name, cls_obj in inspect.getmembers(torch.nn.modules.activation) if inspect.isclass(cls_obj) and cls_obj.__module__ == 'torch.nn.modules.activation'})
36
+
37
+ def __init__(self, dim, state_dict=None, layer_structure=None, activation_func=None, weight_init='Normal',
38
+ add_layer_norm=False, activate_output=False, dropout_structure=None):
39
+ super().__init__()
40
+
41
+ self.multiplier = 1.0
42
+
43
+ assert layer_structure is not None, "layer_structure must not be None"
44
+ assert layer_structure[0] == 1, "Multiplier Sequence should start with size 1!"
45
+ assert layer_structure[-1] == 1, "Multiplier Sequence should end with size 1!"
46
+
47
+ linears = []
48
+ for i in range(len(layer_structure) - 1):
49
+
50
+ # Add a fully-connected layer
51
+ linears.append(torch.nn.Linear(int(dim * layer_structure[i]), int(dim * layer_structure[i+1])))
52
+
53
+ # Add an activation func except last layer
54
+ if activation_func == "linear" or activation_func is None or (i >= len(layer_structure) - 2 and not activate_output):
55
+ pass
56
+ elif activation_func in self.activation_dict:
57
+ linears.append(self.activation_dict[activation_func]())
58
+ else:
59
+ raise RuntimeError(f'hypernetwork uses an unsupported activation function: {activation_func}')
60
+
61
+ # Add layer normalization
62
+ if add_layer_norm:
63
+ linears.append(torch.nn.LayerNorm(int(dim * layer_structure[i+1])))
64
+
65
+ # Everything should be now parsed into dropout structure, and applied here.
66
+ # Since we only have dropouts after layers, dropout structure should start with 0 and end with 0.
67
+ if dropout_structure is not None and dropout_structure[i+1] > 0:
68
+ assert 0 < dropout_structure[i+1] < 1, "Dropout probability should be 0 or float between 0 and 1!"
69
+ linears.append(torch.nn.Dropout(p=dropout_structure[i+1]))
70
+ # Code explanation : [1, 2, 1] -> dropout is missing when last_layer_dropout is false. [1, 2, 2, 1] -> [0, 0.3, 0, 0], when its True, [0, 0.3, 0.3, 0].
71
+
72
+ self.linear = torch.nn.Sequential(*linears)
73
+
74
+ if state_dict is not None:
75
+ self.fix_old_state_dict(state_dict)
76
+ self.load_state_dict(state_dict)
77
+ else:
78
+ for layer in self.linear:
79
+ if type(layer) == torch.nn.Linear or type(layer) == torch.nn.LayerNorm:
80
+ w, b = layer.weight.data, layer.bias.data
81
+ if weight_init == "Normal" or type(layer) == torch.nn.LayerNorm:
82
+ normal_(w, mean=0.0, std=0.01)
83
+ normal_(b, mean=0.0, std=0)
84
+ elif weight_init == 'XavierUniform':
85
+ xavier_uniform_(w)
86
+ zeros_(b)
87
+ elif weight_init == 'XavierNormal':
88
+ xavier_normal_(w)
89
+ zeros_(b)
90
+ elif weight_init == 'KaimingUniform':
91
+ kaiming_uniform_(w, nonlinearity='leaky_relu' if 'leakyrelu' == activation_func else 'relu')
92
+ zeros_(b)
93
+ elif weight_init == 'KaimingNormal':
94
+ kaiming_normal_(w, nonlinearity='leaky_relu' if 'leakyrelu' == activation_func else 'relu')
95
+ zeros_(b)
96
+ else:
97
+ raise KeyError(f"Key {weight_init} is not defined as initialization!")
98
+ self.to(devices.device)
99
+
100
+ def fix_old_state_dict(self, state_dict):
101
+ changes = {
102
+ 'linear1.bias': 'linear.0.bias',
103
+ 'linear1.weight': 'linear.0.weight',
104
+ 'linear2.bias': 'linear.1.bias',
105
+ 'linear2.weight': 'linear.1.weight',
106
+ }
107
+
108
+ for fr, to in changes.items():
109
+ x = state_dict.get(fr, None)
110
+ if x is None:
111
+ continue
112
+
113
+ del state_dict[fr]
114
+ state_dict[to] = x
115
+
116
+ def forward(self, x):
117
+ return x + self.linear(x) * (self.multiplier if not self.training else 1)
118
+
119
+ def trainables(self):
120
+ layer_structure = []
121
+ for layer in self.linear:
122
+ if type(layer) == torch.nn.Linear or type(layer) == torch.nn.LayerNorm:
123
+ layer_structure += [layer.weight, layer.bias]
124
+ return layer_structure
125
+
126
+
127
+ #param layer_structure : sequence used for length, use_dropout : controlling boolean, last_layer_dropout : for compatibility check.
128
+ def parse_dropout_structure(layer_structure, use_dropout, last_layer_dropout):
129
+ if layer_structure is None:
130
+ layer_structure = [1, 2, 1]
131
+ if not use_dropout:
132
+ return [0] * len(layer_structure)
133
+ dropout_values = [0]
134
+ dropout_values.extend([0.3] * (len(layer_structure) - 3))
135
+ if last_layer_dropout:
136
+ dropout_values.append(0.3)
137
+ else:
138
+ dropout_values.append(0)
139
+ dropout_values.append(0)
140
+ return dropout_values
141
+
142
+
143
+ class Hypernetwork:
144
+ filename = None
145
+ name = None
146
+
147
+ def __init__(self, name=None, enable_sizes=None, layer_structure=None, activation_func=None, weight_init=None, add_layer_norm=False, use_dropout=False, activate_output=False, **kwargs):
148
+ self.filename = None
149
+ self.name = name
150
+ self.layers = {}
151
+ self.step = 0
152
+ self.sd_checkpoint = None
153
+ self.sd_checkpoint_name = None
154
+ self.layer_structure = layer_structure
155
+ self.activation_func = activation_func
156
+ self.weight_init = weight_init
157
+ self.add_layer_norm = add_layer_norm
158
+ self.use_dropout = use_dropout
159
+ self.activate_output = activate_output
160
+ self.last_layer_dropout = kwargs.get('last_layer_dropout', True)
161
+ self.dropout_structure = kwargs.get('dropout_structure', None)
162
+ if self.dropout_structure is None:
163
+ self.dropout_structure = parse_dropout_structure(self.layer_structure, self.use_dropout, self.last_layer_dropout)
164
+ self.optimizer_name = None
165
+ self.optimizer_state_dict = None
166
+ self.optional_info = None
167
+
168
+ for size in enable_sizes or []:
169
+ self.layers[size] = (
170
+ HypernetworkModule(size, None, self.layer_structure, self.activation_func, self.weight_init,
171
+ self.add_layer_norm, self.activate_output, dropout_structure=self.dropout_structure),
172
+ HypernetworkModule(size, None, self.layer_structure, self.activation_func, self.weight_init,
173
+ self.add_layer_norm, self.activate_output, dropout_structure=self.dropout_structure),
174
+ )
175
+ self.eval()
176
+
177
+ def weights(self):
178
+ res = []
179
+ for layers in self.layers.values():
180
+ for layer in layers:
181
+ res += layer.parameters()
182
+ return res
183
+
184
+ def train(self, mode=True):
185
+ for layers in self.layers.values():
186
+ for layer in layers:
187
+ layer.train(mode=mode)
188
+ for param in layer.parameters():
189
+ param.requires_grad = mode
190
+
191
+ def to(self, device):
192
+ for layers in self.layers.values():
193
+ for layer in layers:
194
+ layer.to(device)
195
+
196
+ return self
197
+
198
+ def set_multiplier(self, multiplier):
199
+ for layers in self.layers.values():
200
+ for layer in layers:
201
+ layer.multiplier = multiplier
202
+
203
+ return self
204
+
205
+ def eval(self):
206
+ for layers in self.layers.values():
207
+ for layer in layers:
208
+ layer.eval()
209
+ for param in layer.parameters():
210
+ param.requires_grad = False
211
+
212
+ def save(self, filename):
213
+ state_dict = {}
214
+ optimizer_saved_dict = {}
215
+
216
+ for k, v in self.layers.items():
217
+ state_dict[k] = (v[0].state_dict(), v[1].state_dict())
218
+
219
+ state_dict['step'] = self.step
220
+ state_dict['name'] = self.name
221
+ state_dict['layer_structure'] = self.layer_structure
222
+ state_dict['activation_func'] = self.activation_func
223
+ state_dict['is_layer_norm'] = self.add_layer_norm
224
+ state_dict['weight_initialization'] = self.weight_init
225
+ state_dict['sd_checkpoint'] = self.sd_checkpoint
226
+ state_dict['sd_checkpoint_name'] = self.sd_checkpoint_name
227
+ state_dict['activate_output'] = self.activate_output
228
+ state_dict['use_dropout'] = self.use_dropout
229
+ state_dict['dropout_structure'] = self.dropout_structure
230
+ state_dict['last_layer_dropout'] = (self.dropout_structure[-2] != 0) if self.dropout_structure is not None else self.last_layer_dropout
231
+ state_dict['optional_info'] = self.optional_info if self.optional_info else None
232
+
233
+ if self.optimizer_name is not None:
234
+ optimizer_saved_dict['optimizer_name'] = self.optimizer_name
235
+
236
+ torch.save(state_dict, filename)
237
+ if shared.opts.save_optimizer_state and self.optimizer_state_dict:
238
+ optimizer_saved_dict['hash'] = self.shorthash()
239
+ optimizer_saved_dict['optimizer_state_dict'] = self.optimizer_state_dict
240
+ torch.save(optimizer_saved_dict, filename + '.optim')
241
+
242
+ def load(self, filename):
243
+ self.filename = filename
244
+ if self.name is None:
245
+ self.name = os.path.splitext(os.path.basename(filename))[0]
246
+
247
+ state_dict = torch.load(filename, map_location='cpu')
248
+
249
+ self.layer_structure = state_dict.get('layer_structure', [1, 2, 1])
250
+ self.optional_info = state_dict.get('optional_info', None)
251
+ self.activation_func = state_dict.get('activation_func', None)
252
+ self.weight_init = state_dict.get('weight_initialization', 'Normal')
253
+ self.add_layer_norm = state_dict.get('is_layer_norm', False)
254
+ self.dropout_structure = state_dict.get('dropout_structure', None)
255
+ self.use_dropout = True if self.dropout_structure is not None and any(self.dropout_structure) else state_dict.get('use_dropout', False)
256
+ self.activate_output = state_dict.get('activate_output', True)
257
+ self.last_layer_dropout = state_dict.get('last_layer_dropout', False)
258
+ # Dropout structure should have same length as layer structure, Every digits should be in [0,1), and last digit must be 0.
259
+ if self.dropout_structure is None:
260
+ self.dropout_structure = parse_dropout_structure(self.layer_structure, self.use_dropout, self.last_layer_dropout)
261
+
262
+ if shared.opts.print_hypernet_extra:
263
+ if self.optional_info is not None:
264
+ print(f" INFO:\n {self.optional_info}\n")
265
+
266
+ print(f" Layer structure: {self.layer_structure}")
267
+ print(f" Activation function: {self.activation_func}")
268
+ print(f" Weight initialization: {self.weight_init}")
269
+ print(f" Layer norm: {self.add_layer_norm}")
270
+ print(f" Dropout usage: {self.use_dropout}" )
271
+ print(f" Activate last layer: {self.activate_output}")
272
+ print(f" Dropout structure: {self.dropout_structure}")
273
+
274
+ optimizer_saved_dict = torch.load(self.filename + '.optim', map_location='cpu') if os.path.exists(self.filename + '.optim') else {}
275
+
276
+ if self.shorthash() == optimizer_saved_dict.get('hash', None):
277
+ self.optimizer_state_dict = optimizer_saved_dict.get('optimizer_state_dict', None)
278
+ else:
279
+ self.optimizer_state_dict = None
280
+ if self.optimizer_state_dict:
281
+ self.optimizer_name = optimizer_saved_dict.get('optimizer_name', 'AdamW')
282
+ if shared.opts.print_hypernet_extra:
283
+ print("Loaded existing optimizer from checkpoint")
284
+ print(f"Optimizer name is {self.optimizer_name}")
285
+ else:
286
+ self.optimizer_name = "AdamW"
287
+ if shared.opts.print_hypernet_extra:
288
+ print("No saved optimizer exists in checkpoint")
289
+
290
+ for size, sd in state_dict.items():
291
+ if type(size) == int:
292
+ self.layers[size] = (
293
+ HypernetworkModule(size, sd[0], self.layer_structure, self.activation_func, self.weight_init,
294
+ self.add_layer_norm, self.activate_output, self.dropout_structure),
295
+ HypernetworkModule(size, sd[1], self.layer_structure, self.activation_func, self.weight_init,
296
+ self.add_layer_norm, self.activate_output, self.dropout_structure),
297
+ )
298
+
299
+ self.name = state_dict.get('name', self.name)
300
+ self.step = state_dict.get('step', 0)
301
+ self.sd_checkpoint = state_dict.get('sd_checkpoint', None)
302
+ self.sd_checkpoint_name = state_dict.get('sd_checkpoint_name', None)
303
+ self.eval()
304
+
305
+ def shorthash(self):
306
+ sha256 = hashes.sha256(self.filename, f'hypernet/{self.name}')
307
+
308
+ return sha256[0:10] if sha256 else None
309
+
310
+
311
+ def list_hypernetworks(path):
312
+ res = {}
313
+ for filename in sorted(glob.iglob(os.path.join(path, '**/*.pt'), recursive=True), key=str.lower):
314
+ name = os.path.splitext(os.path.basename(filename))[0]
315
+ # Prevent a hypothetical "None.pt" from being listed.
316
+ if name != "None":
317
+ res[name] = filename
318
+ return res
319
+
320
+
321
+ def load_hypernetwork(name):
322
+ path = shared.hypernetworks.get(name, None)
323
+
324
+ if path is None:
325
+ return None
326
+
327
+ try:
328
+ hypernetwork = Hypernetwork()
329
+ hypernetwork.load(path)
330
+ return hypernetwork
331
+ except Exception:
332
+ errors.report(f"Error loading hypernetwork {path}", exc_info=True)
333
+ return None
334
+
335
+
336
+ def load_hypernetworks(names, multipliers=None):
337
+ already_loaded = {}
338
+
339
+ for hypernetwork in shared.loaded_hypernetworks:
340
+ if hypernetwork.name in names:
341
+ already_loaded[hypernetwork.name] = hypernetwork
342
+
343
+ shared.loaded_hypernetworks.clear()
344
+
345
+ for i, name in enumerate(names):
346
+ hypernetwork = already_loaded.get(name, None)
347
+ if hypernetwork is None:
348
+ hypernetwork = load_hypernetwork(name)
349
+
350
+ if hypernetwork is None:
351
+ continue
352
+
353
+ hypernetwork.set_multiplier(multipliers[i] if multipliers else 1.0)
354
+ shared.loaded_hypernetworks.append(hypernetwork)
355
+
356
+
357
+ def apply_single_hypernetwork(hypernetwork, context_k, context_v, layer=None):
358
+ hypernetwork_layers = (hypernetwork.layers if hypernetwork is not None else {}).get(context_k.shape[2], None)
359
+
360
+ if hypernetwork_layers is None:
361
+ return context_k, context_v
362
+
363
+ if layer is not None:
364
+ layer.hyper_k = hypernetwork_layers[0]
365
+ layer.hyper_v = hypernetwork_layers[1]
366
+
367
+ context_k = devices.cond_cast_unet(hypernetwork_layers[0](devices.cond_cast_float(context_k)))
368
+ context_v = devices.cond_cast_unet(hypernetwork_layers[1](devices.cond_cast_float(context_v)))
369
+ return context_k, context_v
370
+
371
+
372
+ def apply_hypernetworks(hypernetworks, context, layer=None):
373
+ context_k = context
374
+ context_v = context
375
+ for hypernetwork in hypernetworks:
376
+ context_k, context_v = apply_single_hypernetwork(hypernetwork, context_k, context_v, layer)
377
+
378
+ return context_k, context_v
379
+
380
+
381
+ def attention_CrossAttention_forward(self, x, context=None, mask=None, **kwargs):
382
+ h = self.heads
383
+
384
+ q = self.to_q(x)
385
+ context = default(context, x)
386
+
387
+ context_k, context_v = apply_hypernetworks(shared.loaded_hypernetworks, context, self)
388
+ k = self.to_k(context_k)
389
+ v = self.to_v(context_v)
390
+
391
+ q, k, v = (rearrange(t, 'b n (h d) -> (b h) n d', h=h) for t in (q, k, v))
392
+
393
+ sim = einsum('b i d, b j d -> b i j', q, k) * self.scale
394
+
395
+ if mask is not None:
396
+ mask = rearrange(mask, 'b ... -> b (...)')
397
+ max_neg_value = -torch.finfo(sim.dtype).max
398
+ mask = repeat(mask, 'b j -> (b h) () j', h=h)
399
+ sim.masked_fill_(~mask, max_neg_value)
400
+
401
+ # attention, what we cannot get enough of
402
+ attn = sim.softmax(dim=-1)
403
+
404
+ out = einsum('b i j, b j d -> b i d', attn, v)
405
+ out = rearrange(out, '(b h) n d -> b n (h d)', h=h)
406
+ return self.to_out(out)
407
+
408
+
409
+ def stack_conds(conds):
410
+ if len(conds) == 1:
411
+ return torch.stack(conds)
412
+
413
+ # same as in reconstruct_multicond_batch
414
+ token_count = max([x.shape[0] for x in conds])
415
+ for i in range(len(conds)):
416
+ if conds[i].shape[0] != token_count:
417
+ last_vector = conds[i][-1:]
418
+ last_vector_repeated = last_vector.repeat([token_count - conds[i].shape[0], 1])
419
+ conds[i] = torch.vstack([conds[i], last_vector_repeated])
420
+
421
+ return torch.stack(conds)
422
+
423
+
424
+ def statistics(data):
425
+ if len(data) < 2:
426
+ std = 0
427
+ else:
428
+ std = stdev(data)
429
+ total_information = f"loss:{mean(data):.3f}" + u"\u00B1" + f"({std/ (len(data) ** 0.5):.3f})"
430
+ recent_data = data[-32:]
431
+ if len(recent_data) < 2:
432
+ std = 0
433
+ else:
434
+ std = stdev(recent_data)
435
+ recent_information = f"recent 32 loss:{mean(recent_data):.3f}" + u"\u00B1" + f"({std / (len(recent_data) ** 0.5):.3f})"
436
+ return total_information, recent_information
437
+
438
+
439
+ def create_hypernetwork(name, enable_sizes, overwrite_old, layer_structure=None, activation_func=None, weight_init=None, add_layer_norm=False, use_dropout=False, dropout_structure=None):
440
+ # Remove illegal characters from name.
441
+ name = "".join( x for x in name if (x.isalnum() or x in "._- "))
442
+ assert name, "Name cannot be empty!"
443
+
444
+ fn = os.path.join(shared.cmd_opts.hypernetwork_dir, f"{name}.pt")
445
+ if not overwrite_old:
446
+ assert not os.path.exists(fn), f"file {fn} already exists"
447
+
448
+ if type(layer_structure) == str:
449
+ layer_structure = [float(x.strip()) for x in layer_structure.split(",")]
450
+
451
+ if use_dropout and dropout_structure and type(dropout_structure) == str:
452
+ dropout_structure = [float(x.strip()) for x in dropout_structure.split(",")]
453
+ else:
454
+ dropout_structure = [0] * len(layer_structure)
455
+
456
+ hypernet = modules.hypernetworks.hypernetwork.Hypernetwork(
457
+ name=name,
458
+ enable_sizes=[int(x) for x in enable_sizes],
459
+ layer_structure=layer_structure,
460
+ activation_func=activation_func,
461
+ weight_init=weight_init,
462
+ add_layer_norm=add_layer_norm,
463
+ use_dropout=use_dropout,
464
+ dropout_structure=dropout_structure
465
+ )
466
+ hypernet.save(fn)
467
+
468
+ shared.reload_hypernetworks()
469
+
470
+
471
+ def train_hypernetwork(id_task, hypernetwork_name: str, learn_rate: float, batch_size: int, gradient_step: int, data_root: str, log_directory: str, training_width: int, training_height: int, varsize: bool, steps: int, clip_grad_mode: str, clip_grad_value: float, shuffle_tags: bool, tag_drop_out: bool, latent_sampling_method: str, use_weight: bool, create_image_every: int, save_hypernetwork_every: int, template_filename: str, preview_from_txt2img: bool, preview_prompt: str, preview_negative_prompt: str, preview_steps: int, preview_sampler_name: str, preview_cfg_scale: float, preview_seed: int, preview_width: int, preview_height: int):
472
+ from modules import images, processing
473
+
474
+ save_hypernetwork_every = save_hypernetwork_every or 0
475
+ create_image_every = create_image_every or 0
476
+ template_file = textual_inversion.textual_inversion_templates.get(template_filename, None)
477
+ textual_inversion.validate_train_inputs(hypernetwork_name, learn_rate, batch_size, gradient_step, data_root, template_file, template_filename, steps, save_hypernetwork_every, create_image_every, log_directory, name="hypernetwork")
478
+ template_file = template_file.path
479
+
480
+ path = shared.hypernetworks.get(hypernetwork_name, None)
481
+ hypernetwork = Hypernetwork()
482
+ hypernetwork.load(path)
483
+ shared.loaded_hypernetworks = [hypernetwork]
484
+
485
+ shared.state.job = "train-hypernetwork"
486
+ shared.state.textinfo = "Initializing hypernetwork training..."
487
+ shared.state.job_count = steps
488
+
489
+ hypernetwork_name = hypernetwork_name.rsplit('(', 1)[0]
490
+ filename = os.path.join(shared.cmd_opts.hypernetwork_dir, f'{hypernetwork_name}.pt')
491
+
492
+ log_directory = os.path.join(log_directory, datetime.datetime.now().strftime("%Y-%m-%d"), hypernetwork_name)
493
+ unload = shared.opts.unload_models_when_training
494
+
495
+ if save_hypernetwork_every > 0:
496
+ hypernetwork_dir = os.path.join(log_directory, "hypernetworks")
497
+ os.makedirs(hypernetwork_dir, exist_ok=True)
498
+ else:
499
+ hypernetwork_dir = None
500
+
501
+ if create_image_every > 0:
502
+ images_dir = os.path.join(log_directory, "images")
503
+ os.makedirs(images_dir, exist_ok=True)
504
+ else:
505
+ images_dir = None
506
+
507
+ checkpoint = sd_models.select_checkpoint()
508
+
509
+ initial_step = hypernetwork.step or 0
510
+ if initial_step >= steps:
511
+ shared.state.textinfo = "Model has already been trained beyond specified max steps"
512
+ return hypernetwork, filename
513
+
514
+ scheduler = LearnRateScheduler(learn_rate, steps, initial_step)
515
+
516
+ clip_grad = torch.nn.utils.clip_grad_value_ if clip_grad_mode == "value" else torch.nn.utils.clip_grad_norm_ if clip_grad_mode == "norm" else None
517
+ if clip_grad:
518
+ clip_grad_sched = LearnRateScheduler(clip_grad_value, steps, initial_step, verbose=False)
519
+
520
+ if shared.opts.training_enable_tensorboard:
521
+ tensorboard_writer = textual_inversion.tensorboard_setup(log_directory)
522
+
523
+ # dataset loading may take a while, so input validations and early returns should be done before this
524
+ shared.state.textinfo = f"Preparing dataset from {html.escape(data_root)}..."
525
+
526
+ pin_memory = shared.opts.pin_memory
527
+
528
+ ds = modules.textual_inversion.dataset.PersonalizedBase(data_root=data_root, width=training_width, height=training_height, repeats=shared.opts.training_image_repeats_per_epoch, placeholder_token=hypernetwork_name, model=shared.sd_model, cond_model=shared.sd_model.cond_stage_model, device=devices.device, template_file=template_file, include_cond=True, batch_size=batch_size, gradient_step=gradient_step, shuffle_tags=shuffle_tags, tag_drop_out=tag_drop_out, latent_sampling_method=latent_sampling_method, varsize=varsize, use_weight=use_weight)
529
+
530
+ if shared.opts.save_training_settings_to_txt:
531
+ saved_params = dict(
532
+ model_name=checkpoint.model_name, model_hash=checkpoint.shorthash, num_of_dataset_images=len(ds),
533
+ **{field: getattr(hypernetwork, field) for field in ['layer_structure', 'activation_func', 'weight_init', 'add_layer_norm', 'use_dropout', ]}
534
+ )
535
+ logging.save_settings_to_file(log_directory, {**saved_params, **locals()})
536
+
537
+ latent_sampling_method = ds.latent_sampling_method
538
+
539
+ dl = modules.textual_inversion.dataset.PersonalizedDataLoader(ds, latent_sampling_method=latent_sampling_method, batch_size=ds.batch_size, pin_memory=pin_memory)
540
+
541
+ old_parallel_processing_allowed = shared.parallel_processing_allowed
542
+
543
+ if unload:
544
+ shared.parallel_processing_allowed = False
545
+ shared.sd_model.cond_stage_model.to(devices.cpu)
546
+ shared.sd_model.first_stage_model.to(devices.cpu)
547
+
548
+ weights = hypernetwork.weights()
549
+ hypernetwork.train()
550
+
551
+ # Here we use optimizer from saved HN, or we can specify as UI option.
552
+ if hypernetwork.optimizer_name in optimizer_dict:
553
+ optimizer = optimizer_dict[hypernetwork.optimizer_name](params=weights, lr=scheduler.learn_rate)
554
+ optimizer_name = hypernetwork.optimizer_name
555
+ else:
556
+ print(f"Optimizer type {hypernetwork.optimizer_name} is not defined!")
557
+ optimizer = torch.optim.AdamW(params=weights, lr=scheduler.learn_rate)
558
+ optimizer_name = 'AdamW'
559
+
560
+ if hypernetwork.optimizer_state_dict: # This line must be changed if Optimizer type can be different from saved optimizer.
561
+ try:
562
+ optimizer.load_state_dict(hypernetwork.optimizer_state_dict)
563
+ except RuntimeError as e:
564
+ print("Cannot resume from saved optimizer!")
565
+ print(e)
566
+
567
+ scaler = torch.cuda.amp.GradScaler()
568
+
569
+ batch_size = ds.batch_size
570
+ gradient_step = ds.gradient_step
571
+ # n steps = batch_size * gradient_step * n image processed
572
+ steps_per_epoch = len(ds) // batch_size // gradient_step
573
+ max_steps_per_epoch = len(ds) // batch_size - (len(ds) // batch_size) % gradient_step
574
+ loss_step = 0
575
+ _loss_step = 0 #internal
576
+ # size = len(ds.indexes)
577
+ # loss_dict = defaultdict(lambda : deque(maxlen = 1024))
578
+ loss_logging = deque(maxlen=len(ds) * 3) # this should be configurable parameter, this is 3 * epoch(dataset size)
579
+ # losses = torch.zeros((size,))
580
+ # previous_mean_losses = [0]
581
+ # previous_mean_loss = 0
582
+ # print("Mean loss of {} elements".format(size))
583
+
584
+ steps_without_grad = 0
585
+
586
+ last_saved_file = "<none>"
587
+ last_saved_image = "<none>"
588
+ forced_filename = "<none>"
589
+
590
+ pbar = tqdm.tqdm(total=steps - initial_step)
591
+ try:
592
+ sd_hijack_checkpoint.add()
593
+
594
+ for _ in range((steps-initial_step) * gradient_step):
595
+ if scheduler.finished:
596
+ break
597
+ if shared.state.interrupted:
598
+ break
599
+ for j, batch in enumerate(dl):
600
+ # works as a drop_last=True for gradient accumulation
601
+ if j == max_steps_per_epoch:
602
+ break
603
+ scheduler.apply(optimizer, hypernetwork.step)
604
+ if scheduler.finished:
605
+ break
606
+ if shared.state.interrupted:
607
+ break
608
+
609
+ if clip_grad:
610
+ clip_grad_sched.step(hypernetwork.step)
611
+
612
+ with devices.autocast():
613
+ x = batch.latent_sample.to(devices.device, non_blocking=pin_memory)
614
+ if use_weight:
615
+ w = batch.weight.to(devices.device, non_blocking=pin_memory)
616
+ if tag_drop_out != 0 or shuffle_tags:
617
+ shared.sd_model.cond_stage_model.to(devices.device)
618
+ c = shared.sd_model.cond_stage_model(batch.cond_text).to(devices.device, non_blocking=pin_memory)
619
+ shared.sd_model.cond_stage_model.to(devices.cpu)
620
+ else:
621
+ c = stack_conds(batch.cond).to(devices.device, non_blocking=pin_memory)
622
+ if use_weight:
623
+ loss = shared.sd_model.weighted_forward(x, c, w)[0] / gradient_step
624
+ del w
625
+ else:
626
+ loss = shared.sd_model.forward(x, c)[0] / gradient_step
627
+ del x
628
+ del c
629
+
630
+ _loss_step += loss.item()
631
+ scaler.scale(loss).backward()
632
+
633
+ # go back until we reach gradient accumulation steps
634
+ if (j + 1) % gradient_step != 0:
635
+ continue
636
+ loss_logging.append(_loss_step)
637
+ if clip_grad:
638
+ clip_grad(weights, clip_grad_sched.learn_rate)
639
+
640
+ scaler.step(optimizer)
641
+ scaler.update()
642
+ hypernetwork.step += 1
643
+ pbar.update()
644
+ optimizer.zero_grad(set_to_none=True)
645
+ loss_step = _loss_step
646
+ _loss_step = 0
647
+
648
+ steps_done = hypernetwork.step + 1
649
+
650
+ epoch_num = hypernetwork.step // steps_per_epoch
651
+ epoch_step = hypernetwork.step % steps_per_epoch
652
+
653
+ description = f"Training hypernetwork [Epoch {epoch_num}: {epoch_step+1}/{steps_per_epoch}]loss: {loss_step:.7f}"
654
+ pbar.set_description(description)
655
+ if hypernetwork_dir is not None and steps_done % save_hypernetwork_every == 0:
656
+ # Before saving, change name to match current checkpoint.
657
+ hypernetwork_name_every = f'{hypernetwork_name}-{steps_done}'
658
+ last_saved_file = os.path.join(hypernetwork_dir, f'{hypernetwork_name_every}.pt')
659
+ hypernetwork.optimizer_name = optimizer_name
660
+ if shared.opts.save_optimizer_state:
661
+ hypernetwork.optimizer_state_dict = optimizer.state_dict()
662
+ save_hypernetwork(hypernetwork, checkpoint, hypernetwork_name, last_saved_file)
663
+ hypernetwork.optimizer_state_dict = None # dereference it after saving, to save memory.
664
+
665
+
666
+
667
+ if shared.opts.training_enable_tensorboard:
668
+ epoch_num = hypernetwork.step // len(ds)
669
+ epoch_step = hypernetwork.step - (epoch_num * len(ds)) + 1
670
+ mean_loss = sum(loss_logging) / len(loss_logging)
671
+ textual_inversion.tensorboard_add(tensorboard_writer, loss=mean_loss, global_step=hypernetwork.step, step=epoch_step, learn_rate=scheduler.learn_rate, epoch_num=epoch_num)
672
+
673
+ textual_inversion.write_loss(log_directory, "hypernetwork_loss.csv", hypernetwork.step, steps_per_epoch, {
674
+ "loss": f"{loss_step:.7f}",
675
+ "learn_rate": scheduler.learn_rate
676
+ })
677
+
678
+ if images_dir is not None and steps_done % create_image_every == 0:
679
+ forced_filename = f'{hypernetwork_name}-{steps_done}'
680
+ last_saved_image = os.path.join(images_dir, forced_filename)
681
+ hypernetwork.eval()
682
+ rng_state = torch.get_rng_state()
683
+ cuda_rng_state = None
684
+ if torch.cuda.is_available():
685
+ cuda_rng_state = torch.cuda.get_rng_state_all()
686
+ shared.sd_model.cond_stage_model.to(devices.device)
687
+ shared.sd_model.first_stage_model.to(devices.device)
688
+
689
+ p = processing.StableDiffusionProcessingTxt2Img(
690
+ sd_model=shared.sd_model,
691
+ do_not_save_grid=True,
692
+ do_not_save_samples=True,
693
+ )
694
+
695
+ p.disable_extra_networks = True
696
+
697
+ if preview_from_txt2img:
698
+ p.prompt = preview_prompt
699
+ p.negative_prompt = preview_negative_prompt
700
+ p.steps = preview_steps
701
+ p.sampler_name = sd_samplers.samplers_map[preview_sampler_name.lower()]
702
+ p.cfg_scale = preview_cfg_scale
703
+ p.seed = preview_seed
704
+ p.width = preview_width
705
+ p.height = preview_height
706
+ else:
707
+ p.prompt = batch.cond_text[0]
708
+ p.steps = 20
709
+ p.width = training_width
710
+ p.height = training_height
711
+
712
+ preview_text = p.prompt
713
+
714
+ with closing(p):
715
+ processed = processing.process_images(p)
716
+ image = processed.images[0] if len(processed.images) > 0 else None
717
+
718
+ if unload:
719
+ shared.sd_model.cond_stage_model.to(devices.cpu)
720
+ shared.sd_model.first_stage_model.to(devices.cpu)
721
+ torch.set_rng_state(rng_state)
722
+ if torch.cuda.is_available():
723
+ torch.cuda.set_rng_state_all(cuda_rng_state)
724
+ hypernetwork.train()
725
+ if image is not None:
726
+ shared.state.assign_current_image(image)
727
+ if shared.opts.training_enable_tensorboard and shared.opts.training_tensorboard_save_images:
728
+ textual_inversion.tensorboard_add_image(tensorboard_writer,
729
+ f"Validation at epoch {epoch_num}", image,
730
+ hypernetwork.step)
731
+ last_saved_image, last_text_info = images.save_image(image, images_dir, "", p.seed, p.prompt, shared.opts.samples_format, processed.infotexts[0], p=p, forced_filename=forced_filename, save_to_dirs=False)
732
+ last_saved_image += f", prompt: {preview_text}"
733
+
734
+ shared.state.job_no = hypernetwork.step
735
+
736
+ shared.state.textinfo = f"""
737
+ <p>
738
+ Loss: {loss_step:.7f}<br/>
739
+ Step: {steps_done}<br/>
740
+ Last prompt: {html.escape(batch.cond_text[0])}<br/>
741
+ Last saved hypernetwork: {html.escape(last_saved_file)}<br/>
742
+ Last saved image: {html.escape(last_saved_image)}<br/>
743
+ </p>
744
+ """
745
+ except Exception:
746
+ errors.report("Exception in training hypernetwork", exc_info=True)
747
+ finally:
748
+ pbar.leave = False
749
+ pbar.close()
750
+ hypernetwork.eval()
751
+ sd_hijack_checkpoint.remove()
752
+
753
+
754
+
755
+ filename = os.path.join(shared.cmd_opts.hypernetwork_dir, f'{hypernetwork_name}.pt')
756
+ hypernetwork.optimizer_name = optimizer_name
757
+ if shared.opts.save_optimizer_state:
758
+ hypernetwork.optimizer_state_dict = optimizer.state_dict()
759
+ save_hypernetwork(hypernetwork, checkpoint, hypernetwork_name, filename)
760
+
761
+ del optimizer
762
+ hypernetwork.optimizer_state_dict = None # dereference it after saving, to save memory.
763
+ shared.sd_model.cond_stage_model.to(devices.device)
764
+ shared.sd_model.first_stage_model.to(devices.device)
765
+ shared.parallel_processing_allowed = old_parallel_processing_allowed
766
+
767
+ return hypernetwork, filename
768
+
769
+ def save_hypernetwork(hypernetwork, checkpoint, hypernetwork_name, filename):
770
+ old_hypernetwork_name = hypernetwork.name
771
+ old_sd_checkpoint = hypernetwork.sd_checkpoint if hasattr(hypernetwork, "sd_checkpoint") else None
772
+ old_sd_checkpoint_name = hypernetwork.sd_checkpoint_name if hasattr(hypernetwork, "sd_checkpoint_name") else None
773
+ try:
774
+ hypernetwork.sd_checkpoint = checkpoint.shorthash
775
+ hypernetwork.sd_checkpoint_name = checkpoint.model_name
776
+ hypernetwork.name = hypernetwork_name
777
+ hypernetwork.save(filename)
778
+ except:
779
+ hypernetwork.sd_checkpoint = old_sd_checkpoint
780
+ hypernetwork.sd_checkpoint_name = old_sd_checkpoint_name
781
+ hypernetwork.name = old_hypernetwork_name
782
+ raise
modules/hypernetworks/ui.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import html
2
+
3
+ import gradio as gr
4
+ import modules.hypernetworks.hypernetwork
5
+ from modules import devices, sd_hijack, shared
6
+
7
+ not_available = ["hardswish", "multiheadattention"]
8
+ keys = [x for x in modules.hypernetworks.hypernetwork.HypernetworkModule.activation_dict if x not in not_available]
9
+
10
+
11
+ def create_hypernetwork(name, enable_sizes, overwrite_old, layer_structure=None, activation_func=None, weight_init=None, add_layer_norm=False, use_dropout=False, dropout_structure=None):
12
+ filename = modules.hypernetworks.hypernetwork.create_hypernetwork(name, enable_sizes, overwrite_old, layer_structure, activation_func, weight_init, add_layer_norm, use_dropout, dropout_structure)
13
+
14
+ return gr.Dropdown.update(choices=sorted(shared.hypernetworks)), f"Created: {filename}", ""
15
+
16
+
17
+ def train_hypernetwork(*args):
18
+ shared.loaded_hypernetworks = []
19
+
20
+ assert not shared.cmd_opts.lowvram, 'Training models with lowvram is not possible'
21
+
22
+ try:
23
+ sd_hijack.undo_optimizations()
24
+
25
+ hypernetwork, filename = modules.hypernetworks.hypernetwork.train_hypernetwork(*args)
26
+
27
+ res = f"""
28
+ Training {'interrupted' if shared.state.interrupted else 'finished'} at {hypernetwork.step} steps.
29
+ Hypernetwork saved to {html.escape(filename)}
30
+ """
31
+ return res, ""
32
+ except Exception:
33
+ raise
34
+ finally:
35
+ shared.sd_model.cond_stage_model.to(devices.device)
36
+ shared.sd_model.first_stage_model.to(devices.device)
37
+ sd_hijack.apply_optimizations()
38
+