textual_inversion.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. import os
  2. from collections import namedtuple
  3. from contextlib import closing
  4. import torch
  5. import tqdm
  6. import html
  7. import datetime
  8. import csv
  9. import safetensors.torch
  10. import numpy as np
  11. from PIL import Image, PngImagePlugin
  12. from torch.utils.tensorboard import SummaryWriter
  13. from modules import shared, devices, sd_hijack, processing, sd_models, images, sd_samplers, sd_hijack_checkpoint, errors, hashes
  14. import modules.textual_inversion.dataset
  15. from modules.textual_inversion.learn_schedule import LearnRateScheduler
  16. from modules.textual_inversion.image_embedding import embedding_to_b64, embedding_from_b64, insert_image_data_embed, extract_image_data_embed, caption_image_overlay
  17. from modules.textual_inversion.logging import save_settings_to_file
  18. TextualInversionTemplate = namedtuple("TextualInversionTemplate", ["name", "path"])
  19. textual_inversion_templates = {}
  20. def list_textual_inversion_templates():
  21. textual_inversion_templates.clear()
  22. for root, _, fns in os.walk(shared.cmd_opts.textual_inversion_templates_dir):
  23. for fn in fns:
  24. path = os.path.join(root, fn)
  25. textual_inversion_templates[fn] = TextualInversionTemplate(fn, path)
  26. return textual_inversion_templates
  27. class Embedding:
  28. def __init__(self, vec, name, step=None):
  29. self.vec = vec
  30. self.name = name
  31. self.step = step
  32. self.shape = None
  33. self.vectors = 0
  34. self.cached_checksum = None
  35. self.sd_checkpoint = None
  36. self.sd_checkpoint_name = None
  37. self.optimizer_state_dict = None
  38. self.filename = None
  39. self.hash = None
  40. self.shorthash = None
  41. def save(self, filename):
  42. embedding_data = {
  43. "string_to_token": {"*": 265},
  44. "string_to_param": {"*": self.vec},
  45. "name": self.name,
  46. "step": self.step,
  47. "sd_checkpoint": self.sd_checkpoint,
  48. "sd_checkpoint_name": self.sd_checkpoint_name,
  49. }
  50. torch.save(embedding_data, filename)
  51. if shared.opts.save_optimizer_state and self.optimizer_state_dict is not None:
  52. optimizer_saved_dict = {
  53. 'hash': self.checksum(),
  54. 'optimizer_state_dict': self.optimizer_state_dict,
  55. }
  56. torch.save(optimizer_saved_dict, f"{filename}.optim")
  57. def checksum(self):
  58. if self.cached_checksum is not None:
  59. return self.cached_checksum
  60. def const_hash(a):
  61. r = 0
  62. for v in a:
  63. r = (r * 281 ^ int(v) * 997) & 0xFFFFFFFF
  64. return r
  65. self.cached_checksum = f'{const_hash(self.vec.reshape(-1) * 100) & 0xffff:04x}'
  66. return self.cached_checksum
  67. def set_hash(self, v):
  68. self.hash = v
  69. self.shorthash = self.hash[0:12]
  70. class DirWithTextualInversionEmbeddings:
  71. def __init__(self, path):
  72. self.path = path
  73. self.mtime = None
  74. def has_changed(self):
  75. if not os.path.isdir(self.path):
  76. return False
  77. mt = os.path.getmtime(self.path)
  78. if self.mtime is None or mt > self.mtime:
  79. return True
  80. def update(self):
  81. if not os.path.isdir(self.path):
  82. return
  83. self.mtime = os.path.getmtime(self.path)
  84. class EmbeddingDatabase:
  85. def __init__(self):
  86. self.ids_lookup = {}
  87. self.word_embeddings = {}
  88. self.skipped_embeddings = {}
  89. self.expected_shape = -1
  90. self.embedding_dirs = {}
  91. self.previously_displayed_embeddings = ()
  92. def add_embedding_dir(self, path):
  93. self.embedding_dirs[path] = DirWithTextualInversionEmbeddings(path)
  94. def clear_embedding_dirs(self):
  95. self.embedding_dirs.clear()
  96. def register_embedding(self, embedding, model):
  97. return self.register_embedding_by_name(embedding, model, embedding.name)
  98. def register_embedding_by_name(self, embedding, model, name):
  99. ids = model.cond_stage_model.tokenize([name])[0]
  100. first_id = ids[0]
  101. if first_id not in self.ids_lookup:
  102. self.ids_lookup[first_id] = []
  103. if name in self.word_embeddings:
  104. # remove old one from the lookup list
  105. lookup = [x for x in self.ids_lookup[first_id] if x[1].name!=name]
  106. else:
  107. lookup = self.ids_lookup[first_id]
  108. if embedding is not None:
  109. lookup += [(ids, embedding)]
  110. self.ids_lookup[first_id] = sorted(lookup, key=lambda x: len(x[0]), reverse=True)
  111. if embedding is None:
  112. # unregister embedding with specified name
  113. if name in self.word_embeddings:
  114. del self.word_embeddings[name]
  115. if len(self.ids_lookup[first_id])==0:
  116. del self.ids_lookup[first_id]
  117. return None
  118. self.word_embeddings[name] = embedding
  119. return embedding
  120. def get_expected_shape(self):
  121. vec = shared.sd_model.cond_stage_model.encode_embedding_init_text(",", 1)
  122. return vec.shape[1]
  123. def load_from_file(self, path, filename):
  124. name, ext = os.path.splitext(filename)
  125. ext = ext.upper()
  126. if ext in ['.PNG', '.WEBP', '.JXL', '.AVIF']:
  127. _, second_ext = os.path.splitext(name)
  128. if second_ext.upper() == '.PREVIEW':
  129. return
  130. embed_image = Image.open(path)
  131. if hasattr(embed_image, 'text') and 'sd-ti-embedding' in embed_image.text:
  132. data = embedding_from_b64(embed_image.text['sd-ti-embedding'])
  133. name = data.get('name', name)
  134. else:
  135. data = extract_image_data_embed(embed_image)
  136. if data:
  137. name = data.get('name', name)
  138. else:
  139. # if data is None, means this is not an embeding, just a preview image
  140. return
  141. elif ext in ['.BIN', '.PT']:
  142. data = torch.load(path, map_location="cpu")
  143. elif ext in ['.SAFETENSORS']:
  144. data = safetensors.torch.load_file(path, device="cpu")
  145. else:
  146. return
  147. # textual inversion embeddings
  148. if 'string_to_param' in data:
  149. param_dict = data['string_to_param']
  150. param_dict = getattr(param_dict, '_parameters', param_dict) # fix for torch 1.12.1 loading saved file from torch 1.11
  151. assert len(param_dict) == 1, 'embedding file has multiple terms in it'
  152. emb = next(iter(param_dict.items()))[1]
  153. # diffuser concepts
  154. elif type(data) == dict and type(next(iter(data.values()))) == torch.Tensor:
  155. assert len(data.keys()) == 1, 'embedding file has multiple terms in it'
  156. emb = next(iter(data.values()))
  157. if len(emb.shape) == 1:
  158. emb = emb.unsqueeze(0)
  159. else:
  160. raise Exception(f"Couldn't identify {filename} as neither textual inversion embedding nor diffuser concept.")
  161. vec = emb.detach().to(devices.device, dtype=torch.float32)
  162. embedding = Embedding(vec, name)
  163. embedding.step = data.get('step', None)
  164. embedding.sd_checkpoint = data.get('sd_checkpoint', None)
  165. embedding.sd_checkpoint_name = data.get('sd_checkpoint_name', None)
  166. embedding.vectors = vec.shape[0]
  167. embedding.shape = vec.shape[-1]
  168. embedding.filename = path
  169. embedding.set_hash(hashes.sha256(embedding.filename, "textual_inversion/" + name) or '')
  170. if self.expected_shape == -1 or self.expected_shape == embedding.shape:
  171. self.register_embedding(embedding, shared.sd_model)
  172. else:
  173. self.skipped_embeddings[name] = embedding
  174. def load_from_dir(self, embdir):
  175. if not os.path.isdir(embdir.path):
  176. return
  177. for root, _, fns in os.walk(embdir.path, followlinks=True):
  178. for fn in fns:
  179. try:
  180. fullfn = os.path.join(root, fn)
  181. if os.stat(fullfn).st_size == 0:
  182. continue
  183. self.load_from_file(fullfn, fn)
  184. except Exception:
  185. errors.report(f"Error loading embedding {fn}", exc_info=True)
  186. continue
  187. def load_textual_inversion_embeddings(self, force_reload=False):
  188. if not force_reload:
  189. need_reload = False
  190. for embdir in self.embedding_dirs.values():
  191. if embdir.has_changed():
  192. need_reload = True
  193. break
  194. if not need_reload:
  195. return
  196. self.ids_lookup.clear()
  197. self.word_embeddings.clear()
  198. self.skipped_embeddings.clear()
  199. self.expected_shape = self.get_expected_shape()
  200. for embdir in self.embedding_dirs.values():
  201. self.load_from_dir(embdir)
  202. embdir.update()
  203. # re-sort word_embeddings because load_from_dir may not load in alphabetic order.
  204. # using a temporary copy so we don't reinitialize self.word_embeddings in case other objects have a reference to it.
  205. sorted_word_embeddings = {e.name: e for e in sorted(self.word_embeddings.values(), key=lambda e: e.name.lower())}
  206. self.word_embeddings.clear()
  207. self.word_embeddings.update(sorted_word_embeddings)
  208. displayed_embeddings = (tuple(self.word_embeddings.keys()), tuple(self.skipped_embeddings.keys()))
  209. if shared.opts.textual_inversion_print_at_load and self.previously_displayed_embeddings != displayed_embeddings:
  210. self.previously_displayed_embeddings = displayed_embeddings
  211. print(f"Textual inversion embeddings loaded({len(self.word_embeddings)}): {', '.join(self.word_embeddings.keys())}")
  212. if self.skipped_embeddings:
  213. print(f"Textual inversion embeddings skipped({len(self.skipped_embeddings)}): {', '.join(self.skipped_embeddings.keys())}")
  214. def find_embedding_at_position(self, tokens, offset):
  215. token = tokens[offset]
  216. possible_matches = self.ids_lookup.get(token, None)
  217. if possible_matches is None:
  218. return None, None
  219. for ids, embedding in possible_matches:
  220. if tokens[offset:offset + len(ids)] == ids:
  221. return embedding, len(ids)
  222. return None, None
  223. def create_embedding(name, num_vectors_per_token, overwrite_old, init_text='*'):
  224. cond_model = shared.sd_model.cond_stage_model
  225. with devices.autocast():
  226. cond_model([""]) # will send cond model to GPU if lowvram/medvram is active
  227. #cond_model expects at least some text, so we provide '*' as backup.
  228. embedded = cond_model.encode_embedding_init_text(init_text or '*', num_vectors_per_token)
  229. vec = torch.zeros((num_vectors_per_token, embedded.shape[1]), device=devices.device)
  230. #Only copy if we provided an init_text, otherwise keep vectors as zeros
  231. if init_text:
  232. for i in range(num_vectors_per_token):
  233. vec[i] = embedded[i * int(embedded.shape[0]) // num_vectors_per_token]
  234. # Remove illegal characters from name.
  235. name = "".join( x for x in name if (x.isalnum() or x in "._- "))
  236. fn = os.path.join(shared.cmd_opts.embeddings_dir, f"{name}.pt")
  237. if not overwrite_old:
  238. assert not os.path.exists(fn), f"file {fn} already exists"
  239. embedding = Embedding(vec, name)
  240. embedding.step = 0
  241. embedding.save(fn)
  242. return fn
  243. def write_loss(log_directory, filename, step, epoch_len, values):
  244. if shared.opts.training_write_csv_every == 0:
  245. return
  246. if step % shared.opts.training_write_csv_every != 0:
  247. return
  248. write_csv_header = False if os.path.exists(os.path.join(log_directory, filename)) else True
  249. with open(os.path.join(log_directory, filename), "a+", newline='') as fout:
  250. csv_writer = csv.DictWriter(fout, fieldnames=["step", "epoch", "epoch_step", *(values.keys())])
  251. if write_csv_header:
  252. csv_writer.writeheader()
  253. epoch = (step - 1) // epoch_len
  254. epoch_step = (step - 1) % epoch_len
  255. csv_writer.writerow({
  256. "step": step,
  257. "epoch": epoch,
  258. "epoch_step": epoch_step,
  259. **values,
  260. })
  261. def tensorboard_setup(log_directory):
  262. os.makedirs(os.path.join(log_directory, "tensorboard"), exist_ok=True)
  263. return SummaryWriter(
  264. log_dir=os.path.join(log_directory, "tensorboard"),
  265. flush_secs=shared.opts.training_tensorboard_flush_every)
  266. def tensorboard_add(tensorboard_writer, loss, global_step, step, learn_rate, epoch_num):
  267. tensorboard_add_scaler(tensorboard_writer, "Loss/train", loss, global_step)
  268. tensorboard_add_scaler(tensorboard_writer, f"Loss/train/epoch-{epoch_num}", loss, step)
  269. tensorboard_add_scaler(tensorboard_writer, "Learn rate/train", learn_rate, global_step)
  270. tensorboard_add_scaler(tensorboard_writer, f"Learn rate/train/epoch-{epoch_num}", learn_rate, step)
  271. def tensorboard_add_scaler(tensorboard_writer, tag, value, step):
  272. tensorboard_writer.add_scalar(tag=tag,
  273. scalar_value=value, global_step=step)
  274. def tensorboard_add_image(tensorboard_writer, tag, pil_image, step):
  275. # Convert a pil image to a torch tensor
  276. img_tensor = torch.as_tensor(np.array(pil_image, copy=True))
  277. img_tensor = img_tensor.view(pil_image.size[1], pil_image.size[0],
  278. len(pil_image.getbands()))
  279. img_tensor = img_tensor.permute((2, 0, 1))
  280. tensorboard_writer.add_image(tag, img_tensor, global_step=step)
  281. def validate_train_inputs(model_name, learn_rate, batch_size, gradient_step, data_root, template_file, template_filename, steps, save_model_every, create_image_every, log_directory, name="embedding"):
  282. assert model_name, f"{name} not selected"
  283. assert learn_rate, "Learning rate is empty or 0"
  284. assert isinstance(batch_size, int), "Batch size must be integer"
  285. assert batch_size > 0, "Batch size must be positive"
  286. assert isinstance(gradient_step, int), "Gradient accumulation step must be integer"
  287. assert gradient_step > 0, "Gradient accumulation step must be positive"
  288. assert data_root, "Dataset directory is empty"
  289. assert os.path.isdir(data_root), "Dataset directory doesn't exist"
  290. assert os.listdir(data_root), "Dataset directory is empty"
  291. assert template_filename, "Prompt template file not selected"
  292. assert template_file, f"Prompt template file {template_filename} not found"
  293. assert os.path.isfile(template_file.path), f"Prompt template file {template_filename} doesn't exist"
  294. assert steps, "Max steps is empty or 0"
  295. assert isinstance(steps, int), "Max steps must be integer"
  296. assert steps > 0, "Max steps must be positive"
  297. assert isinstance(save_model_every, int), "Save {name} must be integer"
  298. assert save_model_every >= 0, "Save {name} must be positive or 0"
  299. assert isinstance(create_image_every, int), "Create image must be integer"
  300. assert create_image_every >= 0, "Create image must be positive or 0"
  301. if save_model_every or create_image_every:
  302. assert log_directory, "Log directory is empty"
  303. def train_embedding(id_task, embedding_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_embedding_every, template_filename, save_image_with_stored_embedding, preview_from_txt2img, preview_prompt, preview_negative_prompt, preview_steps, preview_sampler_index, preview_cfg_scale, preview_seed, preview_width, preview_height):
  304. save_embedding_every = save_embedding_every or 0
  305. create_image_every = create_image_every or 0
  306. template_file = textual_inversion_templates.get(template_filename, None)
  307. validate_train_inputs(embedding_name, learn_rate, batch_size, gradient_step, data_root, template_file, template_filename, steps, save_embedding_every, create_image_every, log_directory, name="embedding")
  308. template_file = template_file.path
  309. shared.state.job = "train-embedding"
  310. shared.state.textinfo = "Initializing textual inversion training..."
  311. shared.state.job_count = steps
  312. filename = os.path.join(shared.cmd_opts.embeddings_dir, f'{embedding_name}.pt')
  313. log_directory = os.path.join(log_directory, datetime.datetime.now().strftime("%Y-%m-%d"), embedding_name)
  314. unload = shared.opts.unload_models_when_training
  315. if save_embedding_every > 0:
  316. embedding_dir = os.path.join(log_directory, "embeddings")
  317. os.makedirs(embedding_dir, exist_ok=True)
  318. else:
  319. embedding_dir = None
  320. if create_image_every > 0:
  321. images_dir = os.path.join(log_directory, "images")
  322. os.makedirs(images_dir, exist_ok=True)
  323. else:
  324. images_dir = None
  325. if create_image_every > 0 and save_image_with_stored_embedding:
  326. images_embeds_dir = os.path.join(log_directory, "image_embeddings")
  327. os.makedirs(images_embeds_dir, exist_ok=True)
  328. else:
  329. images_embeds_dir = None
  330. hijack = sd_hijack.model_hijack
  331. embedding = hijack.embedding_db.word_embeddings[embedding_name]
  332. checkpoint = sd_models.select_checkpoint()
  333. initial_step = embedding.step or 0
  334. if initial_step >= steps:
  335. shared.state.textinfo = "Model has already been trained beyond specified max steps"
  336. return embedding, filename
  337. scheduler = LearnRateScheduler(learn_rate, steps, initial_step)
  338. clip_grad = torch.nn.utils.clip_grad_value_ if clip_grad_mode == "value" else \
  339. torch.nn.utils.clip_grad_norm_ if clip_grad_mode == "norm" else \
  340. None
  341. if clip_grad:
  342. clip_grad_sched = LearnRateScheduler(clip_grad_value, steps, initial_step, verbose=False)
  343. # dataset loading may take a while, so input validations and early returns should be done before this
  344. shared.state.textinfo = f"Preparing dataset from {html.escape(data_root)}..."
  345. old_parallel_processing_allowed = shared.parallel_processing_allowed
  346. if shared.opts.training_enable_tensorboard:
  347. tensorboard_writer = tensorboard_setup(log_directory)
  348. pin_memory = shared.opts.pin_memory
  349. 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=embedding_name, model=shared.sd_model, cond_model=shared.sd_model.cond_stage_model, device=devices.device, template_file=template_file, 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)
  350. if shared.opts.save_training_settings_to_txt:
  351. save_settings_to_file(log_directory, {**dict(model_name=checkpoint.model_name, model_hash=checkpoint.shorthash, num_of_dataset_images=len(ds), num_vectors_per_token=len(embedding.vec)), **locals()})
  352. latent_sampling_method = ds.latent_sampling_method
  353. dl = modules.textual_inversion.dataset.PersonalizedDataLoader(ds, latent_sampling_method=latent_sampling_method, batch_size=ds.batch_size, pin_memory=pin_memory)
  354. if unload:
  355. shared.parallel_processing_allowed = False
  356. shared.sd_model.first_stage_model.to(devices.cpu)
  357. embedding.vec.requires_grad = True
  358. optimizer = torch.optim.AdamW([embedding.vec], lr=scheduler.learn_rate, weight_decay=0.0)
  359. if shared.opts.save_optimizer_state:
  360. optimizer_state_dict = None
  361. if os.path.exists(f"{filename}.optim"):
  362. optimizer_saved_dict = torch.load(f"{filename}.optim", map_location='cpu')
  363. if embedding.checksum() == optimizer_saved_dict.get('hash', None):
  364. optimizer_state_dict = optimizer_saved_dict.get('optimizer_state_dict', None)
  365. if optimizer_state_dict is not None:
  366. optimizer.load_state_dict(optimizer_state_dict)
  367. print("Loaded existing optimizer from checkpoint")
  368. else:
  369. print("No saved optimizer exists in checkpoint")
  370. scaler = torch.cuda.amp.GradScaler()
  371. batch_size = ds.batch_size
  372. gradient_step = ds.gradient_step
  373. # n steps = batch_size * gradient_step * n image processed
  374. steps_per_epoch = len(ds) // batch_size // gradient_step
  375. max_steps_per_epoch = len(ds) // batch_size - (len(ds) // batch_size) % gradient_step
  376. loss_step = 0
  377. _loss_step = 0 #internal
  378. last_saved_file = "<none>"
  379. last_saved_image = "<none>"
  380. forced_filename = "<none>"
  381. embedding_yet_to_be_embedded = False
  382. is_training_inpainting_model = shared.sd_model.model.conditioning_key in {'hybrid', 'concat'}
  383. img_c = None
  384. pbar = tqdm.tqdm(total=steps - initial_step)
  385. try:
  386. sd_hijack_checkpoint.add()
  387. for _ in range((steps-initial_step) * gradient_step):
  388. if scheduler.finished:
  389. break
  390. if shared.state.interrupted:
  391. break
  392. for j, batch in enumerate(dl):
  393. # works as a drop_last=True for gradient accumulation
  394. if j == max_steps_per_epoch:
  395. break
  396. scheduler.apply(optimizer, embedding.step)
  397. if scheduler.finished:
  398. break
  399. if shared.state.interrupted:
  400. break
  401. if clip_grad:
  402. clip_grad_sched.step(embedding.step)
  403. with devices.autocast():
  404. x = batch.latent_sample.to(devices.device, non_blocking=pin_memory)
  405. if use_weight:
  406. w = batch.weight.to(devices.device, non_blocking=pin_memory)
  407. c = shared.sd_model.cond_stage_model(batch.cond_text)
  408. if is_training_inpainting_model:
  409. if img_c is None:
  410. img_c = processing.txt2img_image_conditioning(shared.sd_model, c, training_width, training_height)
  411. cond = {"c_concat": [img_c], "c_crossattn": [c]}
  412. else:
  413. cond = c
  414. if use_weight:
  415. loss = shared.sd_model.weighted_forward(x, cond, w)[0] / gradient_step
  416. del w
  417. else:
  418. loss = shared.sd_model.forward(x, cond)[0] / gradient_step
  419. del x
  420. _loss_step += loss.item()
  421. scaler.scale(loss).backward()
  422. # go back until we reach gradient accumulation steps
  423. if (j + 1) % gradient_step != 0:
  424. continue
  425. if clip_grad:
  426. clip_grad(embedding.vec, clip_grad_sched.learn_rate)
  427. scaler.step(optimizer)
  428. scaler.update()
  429. embedding.step += 1
  430. pbar.update()
  431. optimizer.zero_grad(set_to_none=True)
  432. loss_step = _loss_step
  433. _loss_step = 0
  434. steps_done = embedding.step + 1
  435. epoch_num = embedding.step // steps_per_epoch
  436. epoch_step = embedding.step % steps_per_epoch
  437. description = f"Training textual inversion [Epoch {epoch_num}: {epoch_step+1}/{steps_per_epoch}] loss: {loss_step:.7f}"
  438. pbar.set_description(description)
  439. if embedding_dir is not None and steps_done % save_embedding_every == 0:
  440. # Before saving, change name to match current checkpoint.
  441. embedding_name_every = f'{embedding_name}-{steps_done}'
  442. last_saved_file = os.path.join(embedding_dir, f'{embedding_name_every}.pt')
  443. save_embedding(embedding, optimizer, checkpoint, embedding_name_every, last_saved_file, remove_cached_checksum=True)
  444. embedding_yet_to_be_embedded = True
  445. write_loss(log_directory, "textual_inversion_loss.csv", embedding.step, steps_per_epoch, {
  446. "loss": f"{loss_step:.7f}",
  447. "learn_rate": scheduler.learn_rate
  448. })
  449. if images_dir is not None and steps_done % create_image_every == 0:
  450. forced_filename = f'{embedding_name}-{steps_done}'
  451. last_saved_image = os.path.join(images_dir, forced_filename)
  452. shared.sd_model.first_stage_model.to(devices.device)
  453. p = processing.StableDiffusionProcessingTxt2Img(
  454. sd_model=shared.sd_model,
  455. do_not_save_grid=True,
  456. do_not_save_samples=True,
  457. do_not_reload_embeddings=True,
  458. )
  459. if preview_from_txt2img:
  460. p.prompt = preview_prompt
  461. p.negative_prompt = preview_negative_prompt
  462. p.steps = preview_steps
  463. p.sampler_name = sd_samplers.samplers[preview_sampler_index].name
  464. p.cfg_scale = preview_cfg_scale
  465. p.seed = preview_seed
  466. p.width = preview_width
  467. p.height = preview_height
  468. else:
  469. p.prompt = batch.cond_text[0]
  470. p.steps = 20
  471. p.width = training_width
  472. p.height = training_height
  473. preview_text = p.prompt
  474. with closing(p):
  475. processed = processing.process_images(p)
  476. image = processed.images[0] if len(processed.images) > 0 else None
  477. if unload:
  478. shared.sd_model.first_stage_model.to(devices.cpu)
  479. if image is not None:
  480. shared.state.assign_current_image(image)
  481. 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)
  482. last_saved_image += f", prompt: {preview_text}"
  483. if shared.opts.training_enable_tensorboard and shared.opts.training_tensorboard_save_images:
  484. tensorboard_add_image(tensorboard_writer, f"Validation at epoch {epoch_num}", image, embedding.step)
  485. if save_image_with_stored_embedding and os.path.exists(last_saved_file) and embedding_yet_to_be_embedded:
  486. last_saved_image_chunks = os.path.join(images_embeds_dir, f'{embedding_name}-{steps_done}.png')
  487. info = PngImagePlugin.PngInfo()
  488. data = torch.load(last_saved_file)
  489. info.add_text("sd-ti-embedding", embedding_to_b64(data))
  490. title = f"<{data.get('name', '???')}>"
  491. try:
  492. vectorSize = list(data['string_to_param'].values())[0].shape[0]
  493. except Exception:
  494. vectorSize = '?'
  495. checkpoint = sd_models.select_checkpoint()
  496. footer_left = checkpoint.model_name
  497. footer_mid = f'[{checkpoint.shorthash}]'
  498. footer_right = f'{vectorSize}v {steps_done}s'
  499. captioned_image = caption_image_overlay(image, title, footer_left, footer_mid, footer_right)
  500. captioned_image = insert_image_data_embed(captioned_image, data)
  501. captioned_image.save(last_saved_image_chunks, "PNG", pnginfo=info)
  502. embedding_yet_to_be_embedded = False
  503. 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)
  504. last_saved_image += f", prompt: {preview_text}"
  505. shared.state.job_no = embedding.step
  506. shared.state.textinfo = f"""
  507. <p>
  508. Loss: {loss_step:.7f}<br/>
  509. Step: {steps_done}<br/>
  510. Last prompt: {html.escape(batch.cond_text[0])}<br/>
  511. Last saved embedding: {html.escape(last_saved_file)}<br/>
  512. Last saved image: {html.escape(last_saved_image)}<br/>
  513. </p>
  514. """
  515. filename = os.path.join(shared.cmd_opts.embeddings_dir, f'{embedding_name}.pt')
  516. save_embedding(embedding, optimizer, checkpoint, embedding_name, filename, remove_cached_checksum=True)
  517. except Exception:
  518. errors.report("Error training embedding", exc_info=True)
  519. finally:
  520. pbar.leave = False
  521. pbar.close()
  522. shared.sd_model.first_stage_model.to(devices.device)
  523. shared.parallel_processing_allowed = old_parallel_processing_allowed
  524. sd_hijack_checkpoint.remove()
  525. return embedding, filename
  526. def save_embedding(embedding, optimizer, checkpoint, embedding_name, filename, remove_cached_checksum=True):
  527. old_embedding_name = embedding.name
  528. old_sd_checkpoint = embedding.sd_checkpoint if hasattr(embedding, "sd_checkpoint") else None
  529. old_sd_checkpoint_name = embedding.sd_checkpoint_name if hasattr(embedding, "sd_checkpoint_name") else None
  530. old_cached_checksum = embedding.cached_checksum if hasattr(embedding, "cached_checksum") else None
  531. try:
  532. embedding.sd_checkpoint = checkpoint.shorthash
  533. embedding.sd_checkpoint_name = checkpoint.model_name
  534. if remove_cached_checksum:
  535. embedding.cached_checksum = None
  536. embedding.name = embedding_name
  537. embedding.optimizer_state_dict = optimizer.state_dict()
  538. embedding.save(filename)
  539. except:
  540. embedding.sd_checkpoint = old_sd_checkpoint
  541. embedding.sd_checkpoint_name = old_sd_checkpoint_name
  542. embedding.name = old_embedding_name
  543. embedding.cached_checksum = old_cached_checksum
  544. raise