2022-10-02 06:03:39 -06:00
|
|
|
import os
|
|
|
|
import numpy as np
|
|
|
|
import PIL
|
|
|
|
import torch
|
2023-01-10 14:31:58 -07:00
|
|
|
from torch.utils.data import Dataset, DataLoader, Sampler
|
2022-10-02 06:03:39 -06:00
|
|
|
from torchvision import transforms
|
2023-01-10 14:31:58 -07:00
|
|
|
from collections import defaultdict
|
|
|
|
from random import shuffle, choices
|
2022-10-02 06:03:39 -06:00
|
|
|
|
|
|
|
import random
|
|
|
|
import tqdm
|
2024-03-04 09:14:53 -07:00
|
|
|
from modules import devices, shared, images
|
2022-10-03 23:52:11 -06:00
|
|
|
import re
|
|
|
|
|
2022-11-19 20:35:26 -07:00
|
|
|
from ldm.modules.distributions.distributions import DiagonalGaussianDistribution
|
|
|
|
|
2022-10-12 11:49:47 -06:00
|
|
|
re_numbers_at_start = re.compile(r"^[-\d]+\s*")
|
|
|
|
|
|
|
|
|
|
|
|
class DatasetEntry:
|
2023-01-12 07:29:19 -07:00
|
|
|
def __init__(self, filename=None, filename_text=None, latent_dist=None, latent_sample=None, cond=None, cond_text=None, pixel_values=None, weight=None):
|
2022-10-12 11:49:47 -06:00
|
|
|
self.filename = filename
|
|
|
|
self.filename_text = filename_text
|
2023-01-12 07:29:19 -07:00
|
|
|
self.weight = weight
|
2022-11-19 20:35:26 -07:00
|
|
|
self.latent_dist = latent_dist
|
|
|
|
self.latent_sample = latent_sample
|
|
|
|
self.cond = cond
|
|
|
|
self.cond_text = cond_text
|
|
|
|
self.pixel_values = pixel_values
|
2022-10-02 06:03:39 -06:00
|
|
|
|
|
|
|
|
|
|
|
class PersonalizedBase(Dataset):
|
2023-01-12 08:29:00 -07:00
|
|
|
def __init__(self, data_root, width, height, repeats, flip_p=0.5, placeholder_token="*", model=None, cond_model=None, device=None, template_file=None, include_cond=False, batch_size=1, gradient_step=1, shuffle_tags=False, tag_drop_out=0, latent_sampling_method='once', varsize=False, use_weight=False):
|
2023-06-02 05:58:10 -06:00
|
|
|
re_word = re.compile(shared.opts.dataset_filename_word_regex) if shared.opts.dataset_filename_word_regex else None
|
2022-12-14 19:01:32 -07:00
|
|
|
|
2022-10-02 06:03:39 -06:00
|
|
|
self.placeholder_token = placeholder_token
|
|
|
|
|
|
|
|
self.flip = transforms.RandomHorizontalFlip(p=flip_p)
|
|
|
|
|
|
|
|
self.dataset = []
|
|
|
|
|
|
|
|
with open(template_file, "r") as file:
|
|
|
|
lines = [x.strip() for x in file.readlines()]
|
|
|
|
|
|
|
|
self.lines = lines
|
|
|
|
|
|
|
|
assert data_root, 'dataset directory not specified'
|
2022-10-29 06:44:05 -06:00
|
|
|
assert os.path.isdir(data_root), "Dataset directory doesn't exist"
|
|
|
|
assert os.listdir(data_root), "Dataset directory is empty"
|
2022-10-02 06:03:39 -06:00
|
|
|
|
2022-10-11 02:32:46 -06:00
|
|
|
self.image_paths = [os.path.join(data_root, file_path) for file_path in os.listdir(data_root)]
|
2022-11-19 20:35:26 -07:00
|
|
|
|
|
|
|
self.shuffle_tags = shuffle_tags
|
|
|
|
self.tag_drop_out = tag_drop_out
|
2023-01-10 14:31:58 -07:00
|
|
|
groups = defaultdict(list)
|
2022-11-19 20:35:26 -07:00
|
|
|
|
2022-10-02 06:03:39 -06:00
|
|
|
print("Preparing dataset...")
|
|
|
|
for path in tqdm.tqdm(self.image_paths):
|
2023-01-12 07:29:19 -07:00
|
|
|
alpha_channel = None
|
2022-11-19 20:35:26 -07:00
|
|
|
if shared.state.interrupted:
|
2022-12-14 19:01:32 -07:00
|
|
|
raise Exception("interrupted")
|
2022-10-11 02:32:46 -06:00
|
|
|
try:
|
2024-03-04 09:14:53 -07:00
|
|
|
image = images.read(path)
|
2023-01-12 07:29:19 -07:00
|
|
|
#Currently does not work for single color transparency
|
|
|
|
#We would need to read image.info['transparency'] for that
|
2023-01-12 08:29:00 -07:00
|
|
|
if use_weight and 'A' in image.getbands():
|
2023-01-12 07:29:19 -07:00
|
|
|
alpha_channel = image.getchannel('A')
|
|
|
|
image = image.convert('RGB')
|
2023-01-07 10:34:52 -07:00
|
|
|
if not varsize:
|
2023-01-07 06:07:27 -07:00
|
|
|
image = image.resize((width, height), PIL.Image.BICUBIC)
|
2022-10-11 02:32:46 -06:00
|
|
|
except Exception:
|
|
|
|
continue
|
2022-10-02 06:03:39 -06:00
|
|
|
|
2023-05-09 13:17:58 -06:00
|
|
|
text_filename = f"{os.path.splitext(path)[0]}.txt"
|
2022-10-02 06:03:39 -06:00
|
|
|
filename = os.path.basename(path)
|
2022-10-12 11:49:47 -06:00
|
|
|
|
|
|
|
if os.path.exists(text_filename):
|
|
|
|
with open(text_filename, "r", encoding="utf8") as file:
|
|
|
|
filename_text = file.read()
|
|
|
|
else:
|
|
|
|
filename_text = os.path.splitext(filename)[0]
|
|
|
|
filename_text = re.sub(re_numbers_at_start, '', filename_text)
|
|
|
|
if re_word:
|
|
|
|
tokens = re_word.findall(filename_text)
|
|
|
|
filename_text = (shared.opts.dataset_filename_join_string or "").join(tokens)
|
2022-10-02 06:03:39 -06:00
|
|
|
|
|
|
|
npimage = np.array(image).astype(np.uint8)
|
|
|
|
npimage = (npimage / 127.5 - 1.0).astype(np.float32)
|
|
|
|
|
2022-11-19 20:35:26 -07:00
|
|
|
torchdata = torch.from_numpy(npimage).permute(2, 0, 1).to(device=device, dtype=torch.float32)
|
|
|
|
latent_sample = None
|
|
|
|
|
2022-11-28 19:36:35 -07:00
|
|
|
with devices.autocast():
|
2022-11-19 20:35:26 -07:00
|
|
|
latent_dist = model.encode_first_stage(torchdata.unsqueeze(dim=0))
|
|
|
|
|
2023-01-12 07:29:19 -07:00
|
|
|
#Perform latent sampling, even for random sampling.
|
|
|
|
#We need the sample dimensions for the weights
|
|
|
|
if latent_sampling_method == "deterministic":
|
|
|
|
if isinstance(latent_dist, DiagonalGaussianDistribution):
|
|
|
|
# Works only for DiagonalGaussianDistribution
|
|
|
|
latent_dist.std = 0
|
|
|
|
else:
|
|
|
|
latent_sampling_method = "once"
|
|
|
|
latent_sample = model.get_first_stage_encoding(latent_dist).squeeze().to(devices.cpu)
|
|
|
|
|
2023-01-12 08:29:00 -07:00
|
|
|
if use_weight and alpha_channel is not None:
|
2023-01-12 07:29:19 -07:00
|
|
|
channels, *latent_size = latent_sample.shape
|
|
|
|
weight_img = alpha_channel.resize(latent_size)
|
|
|
|
npweight = np.array(weight_img).astype(np.float32)
|
|
|
|
#Repeat for every channel in the latent sample
|
|
|
|
weight = torch.tensor([npweight] * channels).reshape([channels] + latent_size)
|
|
|
|
#Normalize the weight to a minimum of 0 and a mean of 1, that way the loss will be comparable to default.
|
|
|
|
weight -= weight.min()
|
|
|
|
weight /= weight.mean()
|
2023-01-12 08:29:00 -07:00
|
|
|
elif use_weight:
|
2023-01-12 07:29:19 -07:00
|
|
|
#If an image does not have a alpha channel, add a ones weight map anyway so we can stack it later
|
2023-02-19 02:44:56 -07:00
|
|
|
weight = torch.ones(latent_sample.shape)
|
2023-01-12 08:29:00 -07:00
|
|
|
else:
|
|
|
|
weight = None
|
2023-05-11 09:28:15 -06:00
|
|
|
|
2023-01-12 07:29:19 -07:00
|
|
|
if latent_sampling_method == "random":
|
|
|
|
entry = DatasetEntry(filename=path, filename_text=filename_text, latent_dist=latent_dist, weight=weight)
|
|
|
|
else:
|
|
|
|
entry = DatasetEntry(filename=path, filename_text=filename_text, latent_sample=latent_sample, weight=weight)
|
2022-11-19 20:35:26 -07:00
|
|
|
|
|
|
|
if not (self.tag_drop_out != 0 or self.shuffle_tags):
|
2022-10-12 11:49:47 -06:00
|
|
|
entry.cond_text = self.create_text(filename_text)
|
2022-10-11 10:03:08 -06:00
|
|
|
|
2022-11-19 20:35:26 -07:00
|
|
|
if include_cond and not (self.tag_drop_out != 0 or self.shuffle_tags):
|
2022-11-28 19:36:35 -07:00
|
|
|
with devices.autocast():
|
2022-11-19 20:35:26 -07:00
|
|
|
entry.cond = cond_model([entry.cond_text]).to(devices.cpu).squeeze(0)
|
2023-01-10 14:31:58 -07:00
|
|
|
groups[image.size].append(len(self.dataset))
|
2022-11-19 20:35:26 -07:00
|
|
|
self.dataset.append(entry)
|
|
|
|
del torchdata
|
|
|
|
del latent_dist
|
|
|
|
del latent_sample
|
2023-01-12 07:29:19 -07:00
|
|
|
del weight
|
2022-10-02 06:03:39 -06:00
|
|
|
|
2022-11-19 20:35:26 -07:00
|
|
|
self.length = len(self.dataset)
|
2023-01-10 14:31:58 -07:00
|
|
|
self.groups = list(groups.values())
|
2022-11-19 20:35:26 -07:00
|
|
|
assert self.length > 0, "No images have been found in the dataset."
|
|
|
|
self.batch_size = min(batch_size, self.length)
|
|
|
|
self.gradient_step = min(gradient_step, self.length // self.batch_size)
|
|
|
|
self.latent_sampling_method = latent_sampling_method
|
2022-10-02 06:03:39 -06:00
|
|
|
|
2023-01-13 04:32:15 -07:00
|
|
|
if len(groups) > 1:
|
|
|
|
print("Buckets:")
|
|
|
|
for (w, h), ids in sorted(groups.items(), key=lambda x: x[0]):
|
|
|
|
print(f" {w}x{h}: {len(ids)}")
|
|
|
|
print()
|
|
|
|
|
2022-10-12 11:49:47 -06:00
|
|
|
def create_text(self, filename_text):
|
2022-10-11 10:03:08 -06:00
|
|
|
text = random.choice(self.lines)
|
2022-11-10 18:29:55 -07:00
|
|
|
tags = filename_text.split(',')
|
2022-11-19 20:35:26 -07:00
|
|
|
if self.tag_drop_out != 0:
|
|
|
|
tags = [t for t in tags if random.random() > self.tag_drop_out]
|
|
|
|
if self.shuffle_tags:
|
2022-11-01 08:29:12 -06:00
|
|
|
random.shuffle(tags)
|
2022-11-10 18:29:55 -07:00
|
|
|
text = text.replace("[filewords]", ','.join(tags))
|
2022-11-13 12:44:27 -07:00
|
|
|
text = text.replace("[name]", self.placeholder_token)
|
2022-10-11 10:03:08 -06:00
|
|
|
return text
|
|
|
|
|
2022-10-02 06:03:39 -06:00
|
|
|
def __len__(self):
|
|
|
|
return self.length
|
|
|
|
|
|
|
|
def __getitem__(self, i):
|
2022-11-19 20:35:26 -07:00
|
|
|
entry = self.dataset[i]
|
|
|
|
if self.tag_drop_out != 0 or self.shuffle_tags:
|
|
|
|
entry.cond_text = self.create_text(entry.filename_text)
|
|
|
|
if self.latent_sampling_method == "random":
|
2022-11-20 00:14:27 -07:00
|
|
|
entry.latent_sample = shared.sd_model.get_first_stage_encoding(entry.latent_dist).to(devices.cpu)
|
2022-11-19 20:35:26 -07:00
|
|
|
return entry
|
|
|
|
|
2023-01-13 04:32:15 -07:00
|
|
|
|
2023-01-10 14:31:58 -07:00
|
|
|
class GroupedBatchSampler(Sampler):
|
|
|
|
def __init__(self, data_source: PersonalizedBase, batch_size: int):
|
2023-01-13 04:32:15 -07:00
|
|
|
super().__init__(data_source)
|
|
|
|
|
2023-01-10 14:31:58 -07:00
|
|
|
n = len(data_source)
|
|
|
|
self.groups = data_source.groups
|
|
|
|
self.len = n_batch = n // batch_size
|
|
|
|
expected = [len(g) / n * n_batch * batch_size for g in data_source.groups]
|
|
|
|
self.base = [int(e) // batch_size for e in expected]
|
|
|
|
self.n_rand_batches = nrb = n_batch - sum(self.base)
|
|
|
|
self.probs = [e%batch_size/nrb/batch_size if nrb>0 else 0 for e in expected]
|
|
|
|
self.batch_size = batch_size
|
2023-01-13 04:32:15 -07:00
|
|
|
|
2023-01-10 14:31:58 -07:00
|
|
|
def __len__(self):
|
|
|
|
return self.len
|
2023-01-13 04:32:15 -07:00
|
|
|
|
2023-01-10 14:31:58 -07:00
|
|
|
def __iter__(self):
|
|
|
|
b = self.batch_size
|
2023-01-13 04:32:15 -07:00
|
|
|
|
2023-01-10 14:31:58 -07:00
|
|
|
for g in self.groups:
|
|
|
|
shuffle(g)
|
2023-01-13 04:32:15 -07:00
|
|
|
|
2023-01-10 14:31:58 -07:00
|
|
|
batches = []
|
|
|
|
for g in self.groups:
|
|
|
|
batches.extend(g[i*b:(i+1)*b] for i in range(len(g) // b))
|
|
|
|
for _ in range(self.n_rand_batches):
|
|
|
|
rand_group = choices(self.groups, self.probs)[0]
|
|
|
|
batches.append(choices(rand_group, k=b))
|
2023-01-13 04:32:15 -07:00
|
|
|
|
2023-01-10 14:31:58 -07:00
|
|
|
shuffle(batches)
|
2023-01-13 04:32:15 -07:00
|
|
|
|
2023-01-10 14:31:58 -07:00
|
|
|
yield from batches
|
|
|
|
|
2023-01-13 04:32:15 -07:00
|
|
|
|
2022-11-19 20:35:26 -07:00
|
|
|
class PersonalizedDataLoader(DataLoader):
|
2022-11-20 18:15:46 -07:00
|
|
|
def __init__(self, dataset, latent_sampling_method="once", batch_size=1, pin_memory=False):
|
2023-01-10 14:31:58 -07:00
|
|
|
super(PersonalizedDataLoader, self).__init__(dataset, batch_sampler=GroupedBatchSampler(dataset, batch_size), pin_memory=pin_memory)
|
2022-11-20 18:15:46 -07:00
|
|
|
if latent_sampling_method == "random":
|
|
|
|
self.collate_fn = collate_wrapper_random
|
|
|
|
else:
|
|
|
|
self.collate_fn = collate_wrapper
|
2022-12-14 19:01:32 -07:00
|
|
|
|
2022-11-19 20:35:26 -07:00
|
|
|
|
|
|
|
class BatchLoader:
|
|
|
|
def __init__(self, data):
|
|
|
|
self.cond_text = [entry.cond_text for entry in data]
|
|
|
|
self.cond = [entry.cond for entry in data]
|
|
|
|
self.latent_sample = torch.stack([entry.latent_sample for entry in data]).squeeze(1)
|
2023-01-12 08:29:00 -07:00
|
|
|
if all(entry.weight is not None for entry in data):
|
|
|
|
self.weight = torch.stack([entry.weight for entry in data]).squeeze(1)
|
|
|
|
else:
|
|
|
|
self.weight = None
|
2022-11-20 18:15:46 -07:00
|
|
|
#self.emb_index = [entry.emb_index for entry in data]
|
|
|
|
#print(self.latent_sample.device)
|
2022-11-19 20:35:26 -07:00
|
|
|
|
|
|
|
def pin_memory(self):
|
|
|
|
self.latent_sample = self.latent_sample.pin_memory()
|
|
|
|
return self
|
|
|
|
|
|
|
|
def collate_wrapper(batch):
|
2022-11-20 18:15:46 -07:00
|
|
|
return BatchLoader(batch)
|
|
|
|
|
|
|
|
class BatchLoaderRandom(BatchLoader):
|
|
|
|
def __init__(self, data):
|
|
|
|
super().__init__(data)
|
|
|
|
|
|
|
|
def pin_memory(self):
|
|
|
|
return self
|
|
|
|
|
|
|
|
def collate_wrapper_random(batch):
|
2023-05-11 09:28:15 -06:00
|
|
|
return BatchLoaderRandom(batch)
|