2022-10-02 15:03:39 +03:00
|
|
|
import os
|
|
|
|
import sys
|
|
|
|
import traceback
|
|
|
|
|
|
|
|
import torch
|
|
|
|
import tqdm
|
|
|
|
import html
|
|
|
|
import datetime
|
2022-10-13 00:36:29 +03:00
|
|
|
import csv
|
2022-10-02 15:03:39 +03:00
|
|
|
|
2022-10-12 15:15:35 +03:00
|
|
|
from PIL import Image, PngImagePlugin
|
2022-10-02 22:41:21 +03:00
|
|
|
|
2022-10-25 09:22:58 +03:00
|
|
|
from modules import shared, devices, sd_hijack, processing, sd_models, images
|
2022-10-02 15:03:39 +03:00
|
|
|
import modules.textual_inversion.dataset
|
2022-10-12 20:49:47 +03:00
|
|
|
from modules.textual_inversion.learn_schedule import LearnRateScheduler
|
2022-10-02 15:03:39 +03:00
|
|
|
|
2022-10-12 15:15:35 +03:00
|
|
|
from modules.textual_inversion.image_embedding import (embedding_to_b64, embedding_from_b64,
|
|
|
|
insert_image_data_embed, extract_image_data_embed,
|
|
|
|
caption_image_overlay)
|
2022-10-02 15:03:39 +03:00
|
|
|
|
|
|
|
class Embedding:
|
|
|
|
def __init__(self, vec, name, step=None):
|
|
|
|
self.vec = vec
|
|
|
|
self.name = name
|
|
|
|
self.step = step
|
|
|
|
self.cached_checksum = None
|
2022-10-02 20:15:25 +03:00
|
|
|
self.sd_checkpoint = None
|
|
|
|
self.sd_checkpoint_name = None
|
2022-10-02 15:03:39 +03:00
|
|
|
|
|
|
|
def save(self, filename):
|
|
|
|
embedding_data = {
|
|
|
|
"string_to_token": {"*": 265},
|
|
|
|
"string_to_param": {"*": self.vec},
|
|
|
|
"name": self.name,
|
|
|
|
"step": self.step,
|
2022-10-02 20:15:25 +03:00
|
|
|
"sd_checkpoint": self.sd_checkpoint,
|
|
|
|
"sd_checkpoint_name": self.sd_checkpoint_name,
|
2022-10-02 15:03:39 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
torch.save(embedding_data, filename)
|
|
|
|
|
|
|
|
def checksum(self):
|
|
|
|
if self.cached_checksum is not None:
|
|
|
|
return self.cached_checksum
|
|
|
|
|
|
|
|
def const_hash(a):
|
|
|
|
r = 0
|
|
|
|
for v in a:
|
|
|
|
r = (r * 281 ^ int(v) * 997) & 0xFFFFFFFF
|
|
|
|
return r
|
|
|
|
|
|
|
|
self.cached_checksum = f'{const_hash(self.vec.reshape(-1) * 100) & 0xffff:04x}'
|
|
|
|
return self.cached_checksum
|
|
|
|
|
2022-10-02 20:15:25 +03:00
|
|
|
|
2022-10-02 15:03:39 +03:00
|
|
|
class EmbeddingDatabase:
|
|
|
|
def __init__(self, embeddings_dir):
|
|
|
|
self.ids_lookup = {}
|
|
|
|
self.word_embeddings = {}
|
|
|
|
self.dir_mtime = None
|
|
|
|
self.embeddings_dir = embeddings_dir
|
|
|
|
|
|
|
|
def register_embedding(self, embedding, model):
|
|
|
|
|
|
|
|
self.word_embeddings[embedding.name] = embedding
|
|
|
|
|
|
|
|
ids = model.cond_stage_model.tokenizer([embedding.name], add_special_tokens=False)['input_ids'][0]
|
|
|
|
|
|
|
|
first_id = ids[0]
|
|
|
|
if first_id not in self.ids_lookup:
|
|
|
|
self.ids_lookup[first_id] = []
|
2022-10-02 19:56:37 +03:00
|
|
|
|
|
|
|
self.ids_lookup[first_id] = sorted(self.ids_lookup[first_id] + [(ids, embedding)], key=lambda x: len(x[0]), reverse=True)
|
2022-10-02 15:03:39 +03:00
|
|
|
|
|
|
|
return embedding
|
|
|
|
|
|
|
|
def load_textual_inversion_embeddings(self):
|
|
|
|
mt = os.path.getmtime(self.embeddings_dir)
|
|
|
|
if self.dir_mtime is not None and mt <= self.dir_mtime:
|
|
|
|
return
|
|
|
|
|
|
|
|
self.dir_mtime = mt
|
|
|
|
self.ids_lookup.clear()
|
|
|
|
self.word_embeddings.clear()
|
|
|
|
|
|
|
|
def process_file(path, filename):
|
|
|
|
name = os.path.splitext(filename)[0]
|
|
|
|
|
2022-10-09 07:38:38 +03:00
|
|
|
data = []
|
|
|
|
|
2022-10-14 20:23:20 +03:00
|
|
|
if os.path.splitext(filename.upper())[-1] in ['.PNG', '.WEBP', '.JXL', '.AVIF']:
|
2022-10-09 07:38:38 +03:00
|
|
|
embed_image = Image.open(path)
|
2022-10-14 20:23:20 +03:00
|
|
|
if hasattr(embed_image, 'text') and 'sd-ti-embedding' in embed_image.text:
|
2022-10-11 21:50:50 +03:00
|
|
|
data = embedding_from_b64(embed_image.text['sd-ti-embedding'])
|
2022-10-12 15:15:35 +03:00
|
|
|
name = data.get('name', name)
|
2022-10-10 17:34:49 +03:00
|
|
|
else:
|
2022-10-11 21:50:50 +03:00
|
|
|
data = extract_image_data_embed(embed_image)
|
2022-10-12 15:15:35 +03:00
|
|
|
name = data.get('name', name)
|
2022-10-09 07:38:38 +03:00
|
|
|
else:
|
|
|
|
data = torch.load(path, map_location="cpu")
|
2022-10-02 15:03:39 +03:00
|
|
|
|
|
|
|
# textual inversion embeddings
|
|
|
|
if 'string_to_param' in data:
|
|
|
|
param_dict = data['string_to_param']
|
|
|
|
if hasattr(param_dict, '_parameters'):
|
|
|
|
param_dict = getattr(param_dict, '_parameters') # fix for torch 1.12.1 loading saved file from torch 1.11
|
|
|
|
assert len(param_dict) == 1, 'embedding file has multiple terms in it'
|
|
|
|
emb = next(iter(param_dict.items()))[1]
|
|
|
|
# diffuser concepts
|
|
|
|
elif type(data) == dict and type(next(iter(data.values()))) == torch.Tensor:
|
|
|
|
assert len(data.keys()) == 1, 'embedding file has multiple terms in it'
|
|
|
|
|
|
|
|
emb = next(iter(data.values()))
|
|
|
|
if len(emb.shape) == 1:
|
|
|
|
emb = emb.unsqueeze(0)
|
|
|
|
else:
|
|
|
|
raise Exception(f"Couldn't identify {filename} as neither textual inversion embedding nor diffuser concept.")
|
|
|
|
|
|
|
|
vec = emb.detach().to(devices.device, dtype=torch.float32)
|
|
|
|
embedding = Embedding(vec, name)
|
|
|
|
embedding.step = data.get('step', None)
|
2022-10-29 20:49:29 +03:00
|
|
|
embedding.sd_checkpoint = data.get('sd_checkpoint', None)
|
2022-10-02 20:15:25 +03:00
|
|
|
embedding.sd_checkpoint_name = data.get('sd_checkpoint_name', None)
|
2022-10-02 15:03:39 +03:00
|
|
|
self.register_embedding(embedding, shared.sd_model)
|
|
|
|
|
|
|
|
for fn in os.listdir(self.embeddings_dir):
|
|
|
|
try:
|
|
|
|
fullfn = os.path.join(self.embeddings_dir, fn)
|
|
|
|
|
|
|
|
if os.stat(fullfn).st_size == 0:
|
|
|
|
continue
|
|
|
|
|
|
|
|
process_file(fullfn, fn)
|
|
|
|
except Exception:
|
|
|
|
print(f"Error loading emedding {fn}:", file=sys.stderr)
|
|
|
|
print(traceback.format_exc(), file=sys.stderr)
|
|
|
|
continue
|
|
|
|
|
|
|
|
print(f"Loaded a total of {len(self.word_embeddings)} textual inversion embeddings.")
|
2022-10-16 22:28:15 +03:00
|
|
|
print("Embeddings:", ', '.join(self.word_embeddings.keys()))
|
2022-10-02 15:03:39 +03:00
|
|
|
|
|
|
|
def find_embedding_at_position(self, tokens, offset):
|
|
|
|
token = tokens[offset]
|
|
|
|
possible_matches = self.ids_lookup.get(token, None)
|
|
|
|
|
|
|
|
if possible_matches is None:
|
2022-10-02 19:40:51 +03:00
|
|
|
return None, None
|
2022-10-02 15:03:39 +03:00
|
|
|
|
|
|
|
for ids, embedding in possible_matches:
|
|
|
|
if tokens[offset:offset + len(ids)] == ids:
|
2022-10-02 19:40:51 +03:00
|
|
|
return embedding, len(ids)
|
2022-10-02 15:03:39 +03:00
|
|
|
|
2022-10-02 19:40:51 +03:00
|
|
|
return None, None
|
2022-10-02 15:03:39 +03:00
|
|
|
|
|
|
|
|
2022-10-20 02:10:59 +03:00
|
|
|
def create_embedding(name, num_vectors_per_token, overwrite_old, init_text='*'):
|
2022-10-02 15:03:39 +03:00
|
|
|
cond_model = shared.sd_model.cond_stage_model
|
|
|
|
embedding_layer = cond_model.wrapped.transformer.text_model.embeddings
|
|
|
|
|
2022-10-26 09:44:02 +03:00
|
|
|
with devices.autocast():
|
|
|
|
cond_model([""]) # will send cond model to GPU if lowvram/medvram is active
|
|
|
|
|
2022-10-02 15:03:39 +03:00
|
|
|
ids = cond_model.tokenizer(init_text, max_length=num_vectors_per_token, return_tensors="pt", add_special_tokens=False)["input_ids"]
|
2022-10-02 19:40:51 +03:00
|
|
|
embedded = embedding_layer.token_embedding.wrapped(ids.to(devices.device)).squeeze(0)
|
2022-10-02 15:03:39 +03:00
|
|
|
vec = torch.zeros((num_vectors_per_token, embedded.shape[1]), device=devices.device)
|
|
|
|
|
|
|
|
for i in range(num_vectors_per_token):
|
|
|
|
vec[i] = embedded[i * int(embedded.shape[0]) // num_vectors_per_token]
|
|
|
|
|
2022-10-25 09:38:07 +03:00
|
|
|
# Remove illegal characters from name.
|
|
|
|
name = "".join( x for x in name if (x.isalnum() or x in "._- "))
|
2022-10-02 15:03:39 +03:00
|
|
|
fn = os.path.join(shared.cmd_opts.embeddings_dir, f"{name}.pt")
|
2022-10-20 02:10:59 +03:00
|
|
|
if not overwrite_old:
|
|
|
|
assert not os.path.exists(fn), f"file {fn} already exists"
|
2022-10-02 15:03:39 +03:00
|
|
|
|
|
|
|
embedding = Embedding(vec, name)
|
|
|
|
embedding.step = 0
|
|
|
|
embedding.save(fn)
|
|
|
|
|
|
|
|
return fn
|
|
|
|
|
|
|
|
|
2022-10-14 22:43:55 +03:00
|
|
|
def write_loss(log_directory, filename, step, epoch_len, values):
|
|
|
|
if shared.opts.training_write_csv_every == 0:
|
|
|
|
return
|
|
|
|
|
2022-10-28 16:48:08 +03:00
|
|
|
if (step + 1) % shared.opts.training_write_csv_every != 0:
|
2022-10-14 22:43:55 +03:00
|
|
|
return
|
|
|
|
write_csv_header = False if os.path.exists(os.path.join(log_directory, filename)) else True
|
|
|
|
|
|
|
|
with open(os.path.join(log_directory, filename), "a+", newline='') as fout:
|
|
|
|
csv_writer = csv.DictWriter(fout, fieldnames=["step", "epoch", "epoch_step", *(values.keys())])
|
|
|
|
|
|
|
|
if write_csv_header:
|
|
|
|
csv_writer.writeheader()
|
|
|
|
|
|
|
|
epoch = step // epoch_len
|
2022-10-28 16:48:08 +03:00
|
|
|
epoch_step = step % epoch_len
|
2022-10-14 22:43:55 +03:00
|
|
|
|
|
|
|
csv_writer.writerow({
|
|
|
|
"step": step + 1,
|
2022-10-28 16:48:08 +03:00
|
|
|
"epoch": epoch,
|
2022-10-14 22:43:55 +03:00
|
|
|
"epoch_step": epoch_step + 1,
|
|
|
|
**values,
|
|
|
|
})
|
|
|
|
|
2022-10-29 14:09:17 +03:00
|
|
|
def validate_train_inputs(model_name, learn_rate, batch_size, data_root, template_file, steps, save_model_every, create_image_every, log_directory, name="embedding"):
|
|
|
|
assert model_name, f"{name} not selected"
|
|
|
|
assert learn_rate, "Learning rate is empty or 0"
|
|
|
|
assert isinstance(batch_size, int), "Batch size must be integer"
|
|
|
|
assert batch_size > 0, "Batch size must be positive"
|
|
|
|
assert data_root, "Dataset directory is empty"
|
|
|
|
assert os.path.isdir(data_root), "Dataset directory doesn't exist"
|
|
|
|
assert os.listdir(data_root), "Dataset directory is empty"
|
|
|
|
assert template_file, "Prompt template file is empty"
|
|
|
|
assert os.path.isfile(template_file), "Prompt template file doesn't exist"
|
|
|
|
assert steps, "Max steps is empty or 0"
|
|
|
|
assert isinstance(steps, int), "Max steps must be integer"
|
|
|
|
assert steps > 0 , "Max steps must be positive"
|
|
|
|
assert isinstance(save_model_every, int), "Save {name} must be integer"
|
|
|
|
assert save_model_every >= 0 , "Save {name} must be positive or 0"
|
|
|
|
assert isinstance(create_image_every, int), "Create image must be integer"
|
|
|
|
assert create_image_every >= 0 , "Create image must be positive or 0"
|
|
|
|
if save_model_every or create_image_every:
|
|
|
|
assert log_directory, "Log directory is empty"
|
2022-10-14 22:43:55 +03:00
|
|
|
|
2022-10-15 09:24:59 +03:00
|
|
|
def train_embedding(embedding_name, learn_rate, batch_size, data_root, log_directory, training_width, training_height, steps, create_image_every, save_embedding_every, template_file, 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):
|
2022-10-29 14:09:17 +03:00
|
|
|
save_embedding_every = save_embedding_every or 0
|
|
|
|
create_image_every = create_image_every or 0
|
|
|
|
validate_train_inputs(embedding_name, learn_rate, batch_size, data_root, template_file, steps, save_embedding_every, create_image_every, log_directory, name="embedding")
|
2022-10-02 15:03:39 +03:00
|
|
|
|
|
|
|
shared.state.textinfo = "Initializing textual inversion training..."
|
|
|
|
shared.state.job_count = steps
|
|
|
|
|
|
|
|
filename = os.path.join(shared.cmd_opts.embeddings_dir, f'{embedding_name}.pt')
|
|
|
|
|
2022-10-03 13:10:03 +03:00
|
|
|
log_directory = os.path.join(log_directory, datetime.datetime.now().strftime("%Y-%m-%d"), embedding_name)
|
2022-10-31 14:26:08 +03:00
|
|
|
unload = shared.opts.unload_models_when_training
|
2022-10-02 15:03:39 +03:00
|
|
|
|
|
|
|
if save_embedding_every > 0:
|
|
|
|
embedding_dir = os.path.join(log_directory, "embeddings")
|
|
|
|
os.makedirs(embedding_dir, exist_ok=True)
|
|
|
|
else:
|
|
|
|
embedding_dir = None
|
|
|
|
|
|
|
|
if create_image_every > 0:
|
|
|
|
images_dir = os.path.join(log_directory, "images")
|
|
|
|
os.makedirs(images_dir, exist_ok=True)
|
|
|
|
else:
|
|
|
|
images_dir = None
|
|
|
|
|
2022-10-10 02:07:52 +03:00
|
|
|
if create_image_every > 0 and save_image_with_stored_embedding:
|
|
|
|
images_embeds_dir = os.path.join(log_directory, "image_embeddings")
|
|
|
|
os.makedirs(images_embeds_dir, exist_ok=True)
|
|
|
|
else:
|
|
|
|
images_embeds_dir = None
|
2022-10-29 14:09:17 +03:00
|
|
|
|
2022-10-02 15:03:39 +03:00
|
|
|
cond_model = shared.sd_model.cond_stage_model
|
|
|
|
|
2022-10-29 14:09:17 +03:00
|
|
|
hijack = sd_hijack.model_hijack
|
|
|
|
|
|
|
|
embedding = hijack.embedding_db.word_embeddings[embedding_name]
|
2022-10-29 20:49:29 +03:00
|
|
|
checkpoint = sd_models.select_checkpoint()
|
2022-10-29 14:09:17 +03:00
|
|
|
|
|
|
|
ititial_step = embedding.step or 0
|
2022-10-29 20:54:59 +03:00
|
|
|
if ititial_step >= steps:
|
2022-10-29 14:09:17 +03:00
|
|
|
shared.state.textinfo = f"Model has already been trained beyond specified max steps"
|
|
|
|
return embedding, filename
|
|
|
|
|
|
|
|
scheduler = LearnRateScheduler(learn_rate, steps, ititial_step)
|
|
|
|
|
|
|
|
# dataset loading may take a while, so input validations and early returns should be done before this
|
2022-10-02 15:03:39 +03:00
|
|
|
shared.state.textinfo = f"Preparing dataset from {html.escape(data_root)}..."
|
|
|
|
with torch.autocast("cuda"):
|
2022-10-15 09:24:59 +03:00
|
|
|
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, device=devices.device, template_file=template_file, batch_size=batch_size)
|
2022-10-31 14:26:08 +03:00
|
|
|
if unload:
|
|
|
|
shared.sd_model.first_stage_model.to(devices.cpu)
|
2022-10-02 15:03:39 +03:00
|
|
|
|
|
|
|
embedding.vec.requires_grad = True
|
2022-10-29 14:09:17 +03:00
|
|
|
optimizer = torch.optim.AdamW([embedding.vec], lr=scheduler.learn_rate)
|
2022-10-02 15:03:39 +03:00
|
|
|
|
|
|
|
losses = torch.zeros((32,))
|
|
|
|
|
|
|
|
last_saved_file = "<none>"
|
|
|
|
last_saved_image = "<none>"
|
2022-10-25 09:22:58 +03:00
|
|
|
forced_filename = "<none>"
|
2022-10-14 16:55:05 +03:00
|
|
|
embedding_yet_to_be_embedded = False
|
2022-10-02 15:03:39 +03:00
|
|
|
|
|
|
|
pbar = tqdm.tqdm(enumerate(ds), total=steps-ititial_step)
|
2022-10-15 09:24:59 +03:00
|
|
|
for i, entries in pbar:
|
2022-10-02 15:03:39 +03:00
|
|
|
embedding.step = i + ititial_step
|
|
|
|
|
2022-10-12 20:49:47 +03:00
|
|
|
scheduler.apply(optimizer, embedding.step)
|
|
|
|
if scheduler.finished:
|
|
|
|
break
|
2022-10-02 15:03:39 +03:00
|
|
|
|
|
|
|
if shared.state.interrupted:
|
|
|
|
break
|
|
|
|
|
|
|
|
with torch.autocast("cuda"):
|
2022-10-15 09:24:59 +03:00
|
|
|
c = cond_model([entry.cond_text for entry in entries])
|
|
|
|
x = torch.stack([entry.latent for entry in entries]).to(devices.device)
|
|
|
|
loss = shared.sd_model(x, c)[0]
|
2022-10-02 22:59:01 +03:00
|
|
|
del x
|
2022-10-02 15:03:39 +03:00
|
|
|
|
|
|
|
losses[embedding.step % losses.shape[0]] = loss.item()
|
|
|
|
|
|
|
|
optimizer.zero_grad()
|
|
|
|
loss.backward()
|
|
|
|
optimizer.step()
|
|
|
|
|
2022-10-28 16:48:08 +03:00
|
|
|
steps_done = embedding.step + 1
|
2022-10-02 15:03:39 +03:00
|
|
|
|
2022-10-11 11:32:46 +03:00
|
|
|
epoch_num = embedding.step // len(ds)
|
2022-10-28 16:48:08 +03:00
|
|
|
epoch_step = embedding.step % len(ds)
|
2022-10-10 11:07:46 +03:00
|
|
|
|
2022-10-28 16:48:08 +03:00
|
|
|
pbar.set_description(f"[Epoch {epoch_num}: {epoch_step+1}/{len(ds)}]loss: {losses.mean():.7f}")
|
2022-10-02 15:03:39 +03:00
|
|
|
|
2022-10-28 16:48:08 +03:00
|
|
|
if embedding_dir is not None and steps_done % save_embedding_every == 0:
|
2022-10-25 09:38:07 +03:00
|
|
|
# Before saving, change name to match current checkpoint.
|
2022-10-29 20:49:29 +03:00
|
|
|
embedding_name_every = f'{embedding_name}-{steps_done}'
|
|
|
|
last_saved_file = os.path.join(embedding_dir, f'{embedding_name_every}.pt')
|
|
|
|
save_embedding(embedding, checkpoint, embedding_name_every, last_saved_file, remove_cached_checksum=True)
|
2022-10-14 16:55:05 +03:00
|
|
|
embedding_yet_to_be_embedded = True
|
2022-10-02 15:03:39 +03:00
|
|
|
|
2022-10-14 22:43:55 +03:00
|
|
|
write_loss(log_directory, "textual_inversion_loss.csv", embedding.step, len(ds), {
|
|
|
|
"loss": f"{losses.mean():.7f}",
|
|
|
|
"learn_rate": scheduler.learn_rate
|
|
|
|
})
|
2022-10-13 00:36:29 +03:00
|
|
|
|
2022-10-28 16:48:08 +03:00
|
|
|
if images_dir is not None and steps_done % create_image_every == 0:
|
|
|
|
forced_filename = f'{embedding_name}-{steps_done}'
|
2022-10-25 09:22:58 +03:00
|
|
|
last_saved_image = os.path.join(images_dir, forced_filename)
|
2022-10-31 14:26:08 +03:00
|
|
|
|
|
|
|
shared.sd_model.first_stage_model.to(devices.device)
|
|
|
|
|
2022-10-02 15:03:39 +03:00
|
|
|
p = processing.StableDiffusionProcessingTxt2Img(
|
|
|
|
sd_model=shared.sd_model,
|
|
|
|
do_not_save_grid=True,
|
|
|
|
do_not_save_samples=True,
|
2022-10-16 08:51:24 +03:00
|
|
|
do_not_reload_embeddings=True,
|
2022-10-02 15:03:39 +03:00
|
|
|
)
|
|
|
|
|
2022-10-14 20:31:49 +03:00
|
|
|
if preview_from_txt2img:
|
|
|
|
p.prompt = preview_prompt
|
|
|
|
p.negative_prompt = preview_negative_prompt
|
|
|
|
p.steps = preview_steps
|
|
|
|
p.sampler_index = preview_sampler_index
|
|
|
|
p.cfg_scale = preview_cfg_scale
|
|
|
|
p.seed = preview_seed
|
|
|
|
p.width = preview_width
|
|
|
|
p.height = preview_height
|
|
|
|
else:
|
2022-10-15 09:24:59 +03:00
|
|
|
p.prompt = entries[0].cond_text
|
2022-10-14 20:31:49 +03:00
|
|
|
p.steps = 20
|
|
|
|
p.width = training_width
|
|
|
|
p.height = training_height
|
|
|
|
|
|
|
|
preview_text = p.prompt
|
|
|
|
|
2022-10-02 15:03:39 +03:00
|
|
|
processed = processing.process_images(p)
|
|
|
|
image = processed.images[0]
|
|
|
|
|
2022-10-31 14:26:08 +03:00
|
|
|
if unload:
|
|
|
|
shared.sd_model.first_stage_model.to(devices.cpu)
|
|
|
|
|
2022-10-02 15:03:39 +03:00
|
|
|
shared.state.current_image = image
|
2022-10-09 07:38:38 +03:00
|
|
|
|
2022-10-14 16:55:05 +03:00
|
|
|
if save_image_with_stored_embedding and os.path.exists(last_saved_file) and embedding_yet_to_be_embedded:
|
2022-10-12 15:15:35 +03:00
|
|
|
|
2022-10-28 16:48:08 +03:00
|
|
|
last_saved_image_chunks = os.path.join(images_embeds_dir, f'{embedding_name}-{steps_done}.png')
|
2022-10-10 02:07:52 +03:00
|
|
|
|
2022-10-09 07:38:38 +03:00
|
|
|
info = PngImagePlugin.PngInfo()
|
2022-10-09 23:58:14 +03:00
|
|
|
data = torch.load(last_saved_file)
|
2022-10-11 21:50:50 +03:00
|
|
|
info.add_text("sd-ti-embedding", embedding_to_b64(data))
|
2022-10-09 23:58:14 +03:00
|
|
|
|
2022-10-12 15:15:35 +03:00
|
|
|
title = "<{}>".format(data.get('name', '???'))
|
2022-10-14 16:50:25 +03:00
|
|
|
|
|
|
|
try:
|
|
|
|
vectorSize = list(data['string_to_param'].values())[0].shape[0]
|
|
|
|
except Exception as e:
|
|
|
|
vectorSize = '?'
|
|
|
|
|
2022-10-10 00:14:50 +03:00
|
|
|
checkpoint = sd_models.select_checkpoint()
|
2022-10-10 02:07:52 +03:00
|
|
|
footer_left = checkpoint.model_name
|
|
|
|
footer_mid = '[{}]'.format(checkpoint.hash)
|
2022-10-28 16:48:08 +03:00
|
|
|
footer_right = '{}v {}s'.format(vectorSize, steps_done)
|
2022-10-10 02:07:52 +03:00
|
|
|
|
2022-10-12 15:15:35 +03:00
|
|
|
captioned_image = caption_image_overlay(image, title, footer_left, footer_mid, footer_right)
|
|
|
|
captioned_image = insert_image_data_embed(captioned_image, data)
|
2022-10-10 02:07:52 +03:00
|
|
|
|
|
|
|
captioned_image.save(last_saved_image_chunks, "PNG", pnginfo=info)
|
2022-10-14 16:55:05 +03:00
|
|
|
embedding_yet_to_be_embedded = False
|
2022-10-12 15:15:35 +03:00
|
|
|
|
2022-10-25 10:04:25 +03:00
|
|
|
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)
|
2022-10-11 14:53:02 +03:00
|
|
|
last_saved_image += f", prompt: {preview_text}"
|
2022-10-02 15:03:39 +03:00
|
|
|
|
|
|
|
shared.state.job_no = embedding.step
|
|
|
|
|
|
|
|
shared.state.textinfo = f"""
|
|
|
|
<p>
|
|
|
|
Loss: {losses.mean():.7f}<br/>
|
|
|
|
Step: {embedding.step}<br/>
|
2022-10-15 09:24:59 +03:00
|
|
|
Last prompt: {html.escape(entries[0].cond_text)}<br/>
|
2022-10-02 15:03:39 +03:00
|
|
|
Last saved embedding: {html.escape(last_saved_file)}<br/>
|
|
|
|
Last saved image: {html.escape(last_saved_image)}<br/>
|
|
|
|
</p>
|
|
|
|
"""
|
|
|
|
|
2022-10-29 20:49:29 +03:00
|
|
|
filename = os.path.join(shared.cmd_opts.embeddings_dir, f'{embedding_name}.pt')
|
|
|
|
save_embedding(embedding, checkpoint, embedding_name, filename, remove_cached_checksum=True)
|
2022-10-31 17:07:12 +03:00
|
|
|
shared.sd_model.first_stage_model.to(devices.device)
|
2022-10-02 15:03:39 +03:00
|
|
|
|
|
|
|
return embedding, filename
|
2022-10-29 20:49:29 +03:00
|
|
|
|
|
|
|
def save_embedding(embedding, checkpoint, embedding_name, filename, remove_cached_checksum=True):
|
|
|
|
old_embedding_name = embedding.name
|
|
|
|
old_sd_checkpoint = embedding.sd_checkpoint if hasattr(embedding, "sd_checkpoint") else None
|
|
|
|
old_sd_checkpoint_name = embedding.sd_checkpoint_name if hasattr(embedding, "sd_checkpoint_name") else None
|
|
|
|
old_cached_checksum = embedding.cached_checksum if hasattr(embedding, "cached_checksum") else None
|
|
|
|
try:
|
|
|
|
embedding.sd_checkpoint = checkpoint.hash
|
|
|
|
embedding.sd_checkpoint_name = checkpoint.model_name
|
|
|
|
if remove_cached_checksum:
|
|
|
|
embedding.cached_checksum = None
|
|
|
|
embedding.name = embedding_name
|
|
|
|
embedding.save(filename)
|
|
|
|
except:
|
|
|
|
embedding.sd_checkpoint = old_sd_checkpoint
|
|
|
|
embedding.sd_checkpoint_name = old_sd_checkpoint_name
|
|
|
|
embedding.name = old_embedding_name
|
|
|
|
embedding.cached_checksum = old_cached_checksum
|
|
|
|
raise
|