Upload extensions_built_in/image_reference_slider_trainer/ImageReferenceSliderTrainerProcess.py with huggingface_hub
Browse files
extensions_built_in/image_reference_slider_trainer/ImageReferenceSliderTrainerProcess.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import random
|
| 3 |
+
from collections import OrderedDict
|
| 4 |
+
import os
|
| 5 |
+
from contextlib import nullcontext
|
| 6 |
+
from typing import Optional, Union, List
|
| 7 |
+
from torch.utils.data import ConcatDataset, DataLoader
|
| 8 |
+
|
| 9 |
+
from toolkit.config_modules import ReferenceDatasetConfig
|
| 10 |
+
from toolkit.data_loader import PairedImageDataset
|
| 11 |
+
from toolkit.prompt_utils import concat_prompt_embeds, split_prompt_embeds
|
| 12 |
+
from toolkit.stable_diffusion_model import StableDiffusion, PromptEmbeds
|
| 13 |
+
from toolkit.train_tools import get_torch_dtype, apply_snr_weight
|
| 14 |
+
import gc
|
| 15 |
+
from toolkit import train_tools
|
| 16 |
+
import torch
|
| 17 |
+
from jobs.process import BaseSDTrainProcess
|
| 18 |
+
import random
|
| 19 |
+
from toolkit.basic import value_map
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def flush():
|
| 23 |
+
torch.cuda.empty_cache()
|
| 24 |
+
gc.collect()
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class ReferenceSliderConfig:
|
| 28 |
+
def __init__(self, **kwargs):
|
| 29 |
+
self.additional_losses: List[str] = kwargs.get('additional_losses', [])
|
| 30 |
+
self.weight_jitter: float = kwargs.get('weight_jitter', 0.0)
|
| 31 |
+
self.datasets: List[ReferenceDatasetConfig] = [ReferenceDatasetConfig(**d) for d in kwargs.get('datasets', [])]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class ImageReferenceSliderTrainerProcess(BaseSDTrainProcess):
|
| 35 |
+
sd: StableDiffusion
|
| 36 |
+
data_loader: DataLoader = None
|
| 37 |
+
|
| 38 |
+
def __init__(self, process_id: int, job, config: OrderedDict, **kwargs):
|
| 39 |
+
super().__init__(process_id, job, config, **kwargs)
|
| 40 |
+
self.prompt_txt_list = None
|
| 41 |
+
self.step_num = 0
|
| 42 |
+
self.start_step = 0
|
| 43 |
+
self.device = self.get_conf('device', self.job.device)
|
| 44 |
+
self.device_torch = torch.device(self.device)
|
| 45 |
+
self.slider_config = ReferenceSliderConfig(**self.get_conf('slider', {}))
|
| 46 |
+
|
| 47 |
+
def load_datasets(self):
|
| 48 |
+
if self.data_loader is None:
|
| 49 |
+
print(f"Loading datasets")
|
| 50 |
+
datasets = []
|
| 51 |
+
for dataset in self.slider_config.datasets:
|
| 52 |
+
print(f" - Dataset: {dataset.pair_folder}")
|
| 53 |
+
config = {
|
| 54 |
+
'path': dataset.pair_folder,
|
| 55 |
+
'size': dataset.size,
|
| 56 |
+
'default_prompt': dataset.target_class,
|
| 57 |
+
'network_weight': dataset.network_weight,
|
| 58 |
+
'pos_weight': dataset.pos_weight,
|
| 59 |
+
'neg_weight': dataset.neg_weight,
|
| 60 |
+
'pos_folder': dataset.pos_folder,
|
| 61 |
+
'neg_folder': dataset.neg_folder,
|
| 62 |
+
}
|
| 63 |
+
image_dataset = PairedImageDataset(config)
|
| 64 |
+
datasets.append(image_dataset)
|
| 65 |
+
|
| 66 |
+
concatenated_dataset = ConcatDataset(datasets)
|
| 67 |
+
self.data_loader = DataLoader(
|
| 68 |
+
concatenated_dataset,
|
| 69 |
+
batch_size=self.train_config.batch_size,
|
| 70 |
+
shuffle=True,
|
| 71 |
+
num_workers=2
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
def before_model_load(self):
|
| 75 |
+
pass
|
| 76 |
+
|
| 77 |
+
def hook_before_train_loop(self):
|
| 78 |
+
self.sd.vae.eval()
|
| 79 |
+
self.sd.vae.to(self.device_torch)
|
| 80 |
+
self.load_datasets()
|
| 81 |
+
|
| 82 |
+
pass
|
| 83 |
+
|
| 84 |
+
def hook_train_loop(self, batch):
|
| 85 |
+
with torch.no_grad():
|
| 86 |
+
imgs, prompts, network_weights = batch
|
| 87 |
+
network_pos_weight, network_neg_weight = network_weights
|
| 88 |
+
|
| 89 |
+
if isinstance(network_pos_weight, torch.Tensor):
|
| 90 |
+
network_pos_weight = network_pos_weight.item()
|
| 91 |
+
if isinstance(network_neg_weight, torch.Tensor):
|
| 92 |
+
network_neg_weight = network_neg_weight.item()
|
| 93 |
+
|
| 94 |
+
# get an array of random floats between -weight_jitter and weight_jitter
|
| 95 |
+
loss_jitter_multiplier = 1.0
|
| 96 |
+
weight_jitter = self.slider_config.weight_jitter
|
| 97 |
+
if weight_jitter > 0.0:
|
| 98 |
+
jitter_list = random.uniform(-weight_jitter, weight_jitter)
|
| 99 |
+
orig_network_pos_weight = network_pos_weight
|
| 100 |
+
network_pos_weight += jitter_list
|
| 101 |
+
network_neg_weight += (jitter_list * -1.0)
|
| 102 |
+
# penalize the loss for its distance from network_pos_weight
|
| 103 |
+
# a jitter_list of abs(3.0) on a weight of 5.0 is a 60% jitter
|
| 104 |
+
# so the loss_jitter_multiplier needs to be 0.4
|
| 105 |
+
loss_jitter_multiplier = value_map(abs(jitter_list), 0.0, weight_jitter, 1.0, 0.0)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
# if items in network_weight list are tensors, convert them to floats
|
| 109 |
+
|
| 110 |
+
dtype = get_torch_dtype(self.train_config.dtype)
|
| 111 |
+
imgs: torch.Tensor = imgs.to(self.device_torch, dtype=dtype)
|
| 112 |
+
# split batched images in half so left is negative and right is positive
|
| 113 |
+
negative_images, positive_images = torch.chunk(imgs, 2, dim=3)
|
| 114 |
+
|
| 115 |
+
positive_latents = self.sd.encode_images(positive_images)
|
| 116 |
+
negative_latents = self.sd.encode_images(negative_images)
|
| 117 |
+
|
| 118 |
+
height = positive_images.shape[2]
|
| 119 |
+
width = positive_images.shape[3]
|
| 120 |
+
batch_size = positive_images.shape[0]
|
| 121 |
+
|
| 122 |
+
if self.train_config.gradient_checkpointing:
|
| 123 |
+
# may get disabled elsewhere
|
| 124 |
+
self.sd.unet.enable_gradient_checkpointing()
|
| 125 |
+
|
| 126 |
+
noise_scheduler = self.sd.noise_scheduler
|
| 127 |
+
optimizer = self.optimizer
|
| 128 |
+
lr_scheduler = self.lr_scheduler
|
| 129 |
+
|
| 130 |
+
self.sd.noise_scheduler.set_timesteps(
|
| 131 |
+
self.train_config.max_denoising_steps, device=self.device_torch
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
timesteps = torch.randint(0, self.train_config.max_denoising_steps, (1,), device=self.device_torch)
|
| 135 |
+
timesteps = timesteps.long()
|
| 136 |
+
|
| 137 |
+
# get noise
|
| 138 |
+
noise_positive = self.sd.get_latent_noise(
|
| 139 |
+
pixel_height=height,
|
| 140 |
+
pixel_width=width,
|
| 141 |
+
batch_size=batch_size,
|
| 142 |
+
noise_offset=self.train_config.noise_offset,
|
| 143 |
+
).to(self.device_torch, dtype=dtype)
|
| 144 |
+
|
| 145 |
+
noise_negative = noise_positive.clone()
|
| 146 |
+
|
| 147 |
+
# Add noise to the latents according to the noise magnitude at each timestep
|
| 148 |
+
# (this is the forward diffusion process)
|
| 149 |
+
noisy_positive_latents = noise_scheduler.add_noise(positive_latents, noise_positive, timesteps)
|
| 150 |
+
noisy_negative_latents = noise_scheduler.add_noise(negative_latents, noise_negative, timesteps)
|
| 151 |
+
|
| 152 |
+
noisy_latents = torch.cat([noisy_positive_latents, noisy_negative_latents], dim=0)
|
| 153 |
+
noise = torch.cat([noise_positive, noise_negative], dim=0)
|
| 154 |
+
timesteps = torch.cat([timesteps, timesteps], dim=0)
|
| 155 |
+
network_multiplier = [network_pos_weight * 1.0, network_neg_weight * -1.0]
|
| 156 |
+
|
| 157 |
+
self.optimizer.zero_grad()
|
| 158 |
+
noisy_latents.requires_grad = False
|
| 159 |
+
|
| 160 |
+
# if training text encoder enable grads, else do context of no grad
|
| 161 |
+
with torch.set_grad_enabled(self.train_config.train_text_encoder):
|
| 162 |
+
# fix issue with them being tuples sometimes
|
| 163 |
+
prompt_list = []
|
| 164 |
+
for prompt in prompts:
|
| 165 |
+
if isinstance(prompt, tuple):
|
| 166 |
+
prompt = prompt[0]
|
| 167 |
+
prompt_list.append(prompt)
|
| 168 |
+
conditional_embeds = self.sd.encode_prompt(prompt_list).to(self.device_torch, dtype=dtype)
|
| 169 |
+
conditional_embeds = concat_prompt_embeds([conditional_embeds, conditional_embeds])
|
| 170 |
+
|
| 171 |
+
# if self.model_config.is_xl:
|
| 172 |
+
# # todo also allow for setting this for low ram in general, but sdxl spikes a ton on back prop
|
| 173 |
+
# network_multiplier_list = network_multiplier
|
| 174 |
+
# noisy_latent_list = torch.chunk(noisy_latents, 2, dim=0)
|
| 175 |
+
# noise_list = torch.chunk(noise, 2, dim=0)
|
| 176 |
+
# timesteps_list = torch.chunk(timesteps, 2, dim=0)
|
| 177 |
+
# conditional_embeds_list = split_prompt_embeds(conditional_embeds)
|
| 178 |
+
# else:
|
| 179 |
+
network_multiplier_list = [network_multiplier]
|
| 180 |
+
noisy_latent_list = [noisy_latents]
|
| 181 |
+
noise_list = [noise]
|
| 182 |
+
timesteps_list = [timesteps]
|
| 183 |
+
conditional_embeds_list = [conditional_embeds]
|
| 184 |
+
|
| 185 |
+
losses = []
|
| 186 |
+
# allow to chunk it out to save vram
|
| 187 |
+
for network_multiplier, noisy_latents, noise, timesteps, conditional_embeds in zip(
|
| 188 |
+
network_multiplier_list, noisy_latent_list, noise_list, timesteps_list, conditional_embeds_list
|
| 189 |
+
):
|
| 190 |
+
with self.network:
|
| 191 |
+
assert self.network.is_active
|
| 192 |
+
|
| 193 |
+
self.network.multiplier = network_multiplier
|
| 194 |
+
|
| 195 |
+
noise_pred = self.sd.predict_noise(
|
| 196 |
+
latents=noisy_latents.to(self.device_torch, dtype=dtype),
|
| 197 |
+
conditional_embeddings=conditional_embeds.to(self.device_torch, dtype=dtype),
|
| 198 |
+
timestep=timesteps,
|
| 199 |
+
)
|
| 200 |
+
noise = noise.to(self.device_torch, dtype=dtype)
|
| 201 |
+
|
| 202 |
+
if self.sd.prediction_type == 'v_prediction':
|
| 203 |
+
# v-parameterization training
|
| 204 |
+
target = noise_scheduler.get_velocity(noisy_latents, noise, timesteps)
|
| 205 |
+
else:
|
| 206 |
+
target = noise
|
| 207 |
+
|
| 208 |
+
loss = torch.nn.functional.mse_loss(noise_pred.float(), target.float(), reduction="none")
|
| 209 |
+
loss = loss.mean([1, 2, 3])
|
| 210 |
+
|
| 211 |
+
if self.train_config.min_snr_gamma is not None and self.train_config.min_snr_gamma > 0.000001:
|
| 212 |
+
# add min_snr_gamma
|
| 213 |
+
loss = apply_snr_weight(loss, timesteps, noise_scheduler, self.train_config.min_snr_gamma)
|
| 214 |
+
|
| 215 |
+
loss = loss.mean() * loss_jitter_multiplier
|
| 216 |
+
|
| 217 |
+
loss_float = loss.item()
|
| 218 |
+
losses.append(loss_float)
|
| 219 |
+
|
| 220 |
+
# back propagate loss to free ram
|
| 221 |
+
loss.backward()
|
| 222 |
+
|
| 223 |
+
# apply gradients
|
| 224 |
+
optimizer.step()
|
| 225 |
+
lr_scheduler.step()
|
| 226 |
+
|
| 227 |
+
# reset network
|
| 228 |
+
self.network.multiplier = 1.0
|
| 229 |
+
|
| 230 |
+
loss_dict = OrderedDict(
|
| 231 |
+
{'loss': sum(losses) / len(losses) if len(losses) > 0 else 0.0}
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
return loss_dict
|
| 235 |
+
# end hook_train_loop
|