hypernetwork.py 35 KB

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