Spaces:
Paused
Paused
Update jobs/process/TrainVAEProcess.py
Browse files6 unmodified lines7891011124 unmodified lines1718192021222324252627282930313233347 unmodified lines4243444546474849505152535410 unmodified lines656667686970717273747557 unmodified lines1331341351361371381392 unmodified lines1421431441451461471484 unmodified lines15315415515615715859 unmodified lines21821922022122222353 unmodified lines2772782792802812822835 unmodified lines28929029129229329429529629728 unmodified lines32632732832933033133233333433533633736 unmodified lines3743753763773783798 unmodified lines38838939039139239339439539639739839926 unmodified lines4264274284294304313 unmodified lines4354364374384394401 unmodified line4424434444454464474484491 unmodified line45145245345445545645745845946046146246346446546646746846947047147247347447547647711 unmodified lines4894904914924934944956 unmodified lines50250350450550650750850923 unmodified lines53353453553653753853954021 unmodified lines5625635645655665675 unmodified lines57357457557657757830 unmodified lines6096106116126 unmodified linesfrom PIL import Imagefrom PIL.ImageOps import exif_transposefrom safetensors.torch import save_file, load_filefrom torch.utils.data import DataLoader, ConcatDatasetimport torch4 unmodified linesfrom toolkit.image_utils import show_tensorsfrom toolkit.kohya_model_util import load_vae, convert_diffusers_back_to_ldmfrom toolkit.data_loader import ImageDatasetfrom toolkit.losses import ComparativeTotalVariation, get_gradient_penalty, PatternLossfrom toolkit.metadata import get_meta_for_safetensorsfrom toolkit.optimizer import get_optimizerfrom toolkit.style import get_style_model_and_lossesfrom toolkit.train_tools import get_torch_dtypefrom diffusers import AutoencoderKLfrom tqdm import tqdmimport timeimport numpy as npfrom .models.vgg19_critic import Criticfrom torchvision.transforms import Resizeimport lpipsIMAGE_TRANSFORMS = transforms.Compose([7 unmodified linesreturn (tensor / 2 + 0.5).clamp(0, 1)class TrainVAEProcess(BaseTrainProcess):def __init__(self, process_id: int, job, config: OrderedDict):super().__init__(process_id, job, config)self.data_loader = Noneself.vae = Noneself.device = self.get_conf('device', self.job.device)self.vae_path = self.get_conf('vae_path', required=True)self.datasets_objects = self.get_conf('datasets', required=True)self.batch_size = self.get_conf('batch_size', 1, as_type=int)self.resolution = self.get_conf('resolution', 256, as_type=int)10 unmodified linesself.content_weight = self.get_conf('content_weight', 0, as_type=float)self.kld_weight = self.get_conf('kld_weight', 0, as_type=float)self.mse_weight = self.get_conf('mse_weight', 1e0, as_type=float)self.tv_weight = self.get_conf('tv_weight', 1e0, as_type=float)self.lpips_weight = self.get_conf('lpips_weight', 1e0, as_type=float)self.critic_weight = self.get_conf('critic_weight', 1, as_type=float)self.pattern_weight = self.get_conf('pattern_weight', 1, as_type=float)self.optimizer_params = self.get_conf('optimizer_params', {})self.blocks_to_train = self.get_conf('blocks_to_train', ['all'])self.torch_dtype = get_torch_dtype(self.dtype)57 unmodified linesfor dataset in self.datasets_objects:print(f" - Dataset: {dataset['path']}")ds = copy.copy(dataset)ds['resolution'] = self.resolutionimage_dataset = ImageDataset(ds)datasets.append(image_dataset)2 unmodified linesconcatenated_dataset,batch_size=self.batch_size,shuffle=True,num_workers=6)def remove_oldest_checkpoint(self):4 unmodified linesfor folder in folders[:-max_to_keep]:print(f"Removing {folder}")shutil.rmtree(folder)def setup_vgg19(self):if self.vgg_19 is None:59 unmodified lineselse:return torch.tensor(0.0, device=self.device)def get_tv_loss(self, pred, target):if self.tv_weight > 0:get_tv_loss = ComparativeTotalVariation()53 unmodified linesinput_img = imgimg = IMAGE_TRANSFORMS(img).unsqueeze(0).to(self.device, dtype=self.torch_dtype)img = imgdecoded = self.vae(img).sampledecoded = (decoded / 2 + 0.5).clamp(0, 1)# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16decoded = decoded.cpu().permute(0, 2, 3, 1).squeeze(0).float().numpy()5 unmodified linesinput_img = input_img.resize((self.resolution, self.resolution))decoded = decoded.resize((self.resolution, self.resolution))output_img = Image.new('RGB', (self.resolution * 2, self.resolution))output_img.paste(input_img, (0, 0))output_img.paste(decoded, (self.resolution, 0))scale_up = 2if output_img.height <= 300:28 unmodified linesself.print(f"Loading VAE")self.print(f" - Loading VAE: {path_to_load}")if self.vae is None:self.vae = AutoencoderKL.from_pretrained(path_to_load)# set decoder to trainself.vae.to(self.device, dtype=self.torch_dtype)self.vae.requires_grad_(False)self.vae.eval()self.vae.decoder.train()self.vae_scale_factor = 2 ** (len(self.vae.config['block_out_channels']) - 1)36 unmodified linesif train_all:params = list(self.vae.decoder.parameters())self.vae.decoder.requires_grad_(True)else:# mid_blockif train_all or 'mid_block' in self.blocks_to_train:8 unmodified linesparams += list(self.vae.decoder.conv_out.parameters())self.vae.decoder.conv_out.requires_grad_(True)if self.style_weight > 0 or self.content_weight > 0 or self.use_critic:self.setup_vgg19()self.vgg_19.requires_grad_(False)self.vgg_19.eval()if self.use_critic:self.critic.setup()if self.lpips_weight > 0 and self.lpips_loss is None:# self.lpips_loss = lpips.LPIPS(net='vgg')26 unmodified lines"style": [],"content": [],"mse": [],"kl": [],"tv": [],"ptn": [],3 unmodified linesepoch_losses = copy.deepcopy(blank_losses)log_losses = copy.deepcopy(blank_losses)# range start at self.epoch_num go to self.epochsfor epoch in range(self.epoch_num, self.epochs, 1):if self.step_num >= self.max_steps:break1 unmodified lineif self.step_num >= self.max_steps:breakwith torch.no_grad():batch = batch.to(self.device, dtype=self.torch_dtype)# resize so it matches size of vae evenlyif batch.shape[2] % self.vae_scale_factor != 0 or batch.shape[3] % self.vae_scale_factor != 0:1 unmodified linebatch.shape[3] // self.vae_scale_factor * self.vae_scale_factor))(batch)# forward passdgd = self.vae.encode(batch).latent_distmu, logvar = dgd.mean, dgd.logvarlatents = dgd.sample()latents.detach().requires_grad_(True)pred = self.vae.decode(latents).samplewith torch.no_grad():show_tensors(pred.clamp(-1, 1).clone(),"combined tensor")# Run through VGG19if self.style_weight > 0 or self.content_weight > 0 or self.use_critic:stacked = torch.cat([pred, batch], dim=0)stacked = (stacked / 2 + 0.5).clamp(0, 1)self.vgg_19(stacked)if self.use_critic:critic_d_loss = self.critic.step(self.vgg19_pool_4.tensor.detach())else:critic_d_loss = 0.011 unmodified linestv_loss = self.get_tv_loss(pred, batch) * self.tv_weightpattern_loss = self.get_pattern_loss(pred, batch) * self.pattern_weightif self.use_critic:critic_gen_loss = self.critic.get_critic_loss(self.vgg19_pool_4.tensor) * self.critic_weight# do not let abs critic gen loss be higher than abs lpips * 0.1 if using itif self.lpips_weight > 0:6 unmodified linescritic_gen_loss *= crit_g_scalerelse:critic_gen_loss = torch.tensor(0.0, device=self.device, dtype=self.torch_dtype)loss = style_loss + content_loss + kld_loss + mse_loss + tv_loss + critic_gen_loss + pattern_loss + lpips_loss# Backward pass and optimizationoptimizer.zero_grad()23 unmodified linesloss_string += f" crG: {critic_gen_loss.item():.2e}"if self.use_critic:loss_string += f" crD: {critic_d_loss:.2e}"if self.optimizer_type.startswith('dadaptation') or \self.optimizer_type.lower().startswith('prodigy'):learning_rate = (optimizer.param_groups[0]["d"] *21 unmodified linesepoch_losses["ptn"].append(pattern_loss.item())epoch_losses["crG"].append(critic_gen_loss.item())epoch_losses["crD"].append(critic_d_loss)log_losses["total"].append(loss_value)log_losses["lpips"].append(lpips_loss.item())5 unmodified lineslog_losses["ptn"].append(pattern_loss.item())log_losses["crG"].append(critic_gen_loss.item())log_losses["crD"].append(critic_d_loss)# don't do on first stepif self.step_num != start_step:30 unmodified lines# reset epoch lossesepoch_losses = copy.deepcopy(blank_losses)self.save()6 unmodified lines789101112134 unmodified lines181920212223242526272829303132333435363738397 unmodified lines47484950515253545556575859606162636465666710 unmodified lines7879808182838485868788899091929394959697989910010110257 unmodified lines1601611621631641651661671681691702 unmodified lines1731741751761771781794 unmodified lines18418518618718818919019119219319419519659 unmodified lines25625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631753 unmodified lines3713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084095 unmodified lines41541641741841942042142242342428 unmodified lines45345445545645745845946046146246346446546646746846947047147236 unmodified lines5095105115125135145155165175188 unmodified lines52752852953053153253353453553653753853926 unmodified lines5665675685695705715725735743 unmodified lines5785795805815825835845855861 unmodified line5885895905915925935945955965975985996006016026036046056066071 unmodified line60961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970011 unmodified lines7127137147157167177187196 unmodified lines72672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676723 unmodified lines79179279379479579679779879980080180280380480580680721 unmodified lines8298308318328338348358368375 unmodified lines84384484584684784884985085130 unmodified lines8828838848856 unmodified linesfrom PIL import Imagefrom PIL.ImageOps import exif_transposefrom einops import rearrangefrom safetensors.torch import save_file, load_filefrom torch.utils.data import DataLoader, ConcatDatasetimport torch4 unmodified linesfrom toolkit.image_utils import show_tensorsfrom toolkit.kohya_model_util import load_vae, convert_diffusers_back_to_ldmfrom toolkit.data_loader import ImageDatasetfrom toolkit.losses import ComparativeTotalVariation, get_gradient_penalty, PatternLoss, total_variationfrom toolkit.metadata import get_meta_for_safetensorsfrom toolkit.optimizer import get_optimizerfrom toolkit.style import get_style_model_and_lossesfrom toolkit.train_tools import get_torch_dtypefrom diffusers import AutoencoderKLfrom tqdm import tqdmimport mathimport torchvision.utilsimport timeimport numpy as npfrom .models.critic import Criticfrom torchvision.transforms import Resizeimport lpipsimport randomimport tracebackIMAGE_TRANSFORMS = transforms.Compose([7 unmodified linesreturn (tensor / 2 + 0.5).clamp(0, 1)def channel_dropout(x, p=0.5):keep_prob = 1 - pmask = torch.rand(x.size(0), x.size(1), 1, 1, device=x.device, dtype=x.dtype) < keep_probmask = mask / keep_prob # scalereturn x * maskclass TrainVAEProcess(BaseTrainProcess):def __init__(self, process_id: int, job, config: OrderedDict):super().__init__(process_id, job, config)self.data_loader = Noneself.vae = Noneself.device = self.get_conf('device', self.job.device)self.vae_path = self.get_conf('vae_path', None)self.eq_vae = self.get_conf('eq_vae', False)self.datasets_objects = self.get_conf('datasets', required=True)self.batch_size = self.get_conf('batch_size', 1, as_type=int)self.resolution = self.get_conf('resolution', 256, as_type=int)10 unmodified linesself.content_weight = self.get_conf('content_weight', 0, as_type=float)self.kld_weight = self.get_conf('kld_weight', 0, as_type=float)self.mse_weight = self.get_conf('mse_weight', 1e0, as_type=float)self.mv_loss_weight = self.get_conf('mv_loss_weight', 0, as_type=float)self.tv_weight = self.get_conf('tv_weight', 0, as_type=float)self.ltv_weight = self.get_conf('ltv_weight', 0, as_type=float)self.lpm_weight = self.get_conf('lpm_weight', 0, as_type=float) # latent pixel matchingself.lpips_weight = self.get_conf('lpips_weight', 1e0, as_type=float)self.critic_weight = self.get_conf('critic_weight', 1, as_type=float)self.pattern_weight = self.get_conf('pattern_weight', 0, as_type=float)self.optimizer_params = self.get_conf('optimizer_params', {})self.vae_config = self.get_conf('vae_config', None)self.dropout = self.get_conf('dropout', 0.0, as_type=float)self.train_encoder = self.get_conf('train_encoder', False, as_type=bool)self.random_scaling = self.get_conf('random_scaling', False, as_type=bool)if not self.train_encoder:# remove losses that only target encoderself.kld_weight = 0self.mv_loss_weight = 0self.ltv_weight = 0self.lpm_weight = 0self.blocks_to_train = self.get_conf('blocks_to_train', ['all'])self.torch_dtype = get_torch_dtype(self.dtype)57 unmodified linesfor dataset in self.datasets_objects:print(f" - Dataset: {dataset['path']}")ds = copy.copy(dataset)dataset_res = self.resolutionif self.random_scaling:# scale 2x to allow for random scalingdataset_res = int(dataset_res * 2)ds['resolution'] = dataset_resimage_dataset = ImageDataset(ds)datasets.append(image_dataset)2 unmodified linesconcatenated_dataset,batch_size=self.batch_size,shuffle=True,num_workers=16)def remove_oldest_checkpoint(self):4 unmodified linesfor folder in folders[:-max_to_keep]:print(f"Removing {folder}")shutil.rmtree(folder)# also handle CRITIC_vae_42_000000500.safetensors format for criticcritic_files = glob.glob(os.path.join(self.save_root, f"CRITIC_{self.job.name}*.safetensors"))if len(critic_files) > max_to_keep:critic_files.sort(key=os.path.getmtime)for file in critic_files[:-max_to_keep]:print(f"Removing {file}")os.remove(file)def setup_vgg19(self):if self.vgg_19 is None:59 unmodified lineselse:return torch.tensor(0.0, device=self.device)def get_mean_variance_loss(self, latents: torch.Tensor):if self.mv_loss_weight > 0:# collapse rows into channelslatents_col = rearrange(latents, 'b c h (gw w) -> b (c gw) h w', gw=latents.shape[-1])mean_col = latents_col.mean(dim=(2, 3), keepdim=True)std_col = latents_col.std(dim=(2, 3), keepdim=True, unbiased=False)mean_loss_col = (mean_col ** 2).mean()std_loss_col = ((std_col - 1) ** 2).mean()# collapse columns into channelslatents_row = rearrange(latents, 'b c (gh h) w -> b (c gh) h w', gh=latents.shape[-2])mean_row = latents_row.mean(dim=(2, 3), keepdim=True)std_row = latents_row.std(dim=(2, 3), keepdim=True, unbiased=False)mean_loss_row = (mean_row ** 2).mean()std_loss_row = ((std_row - 1) ** 2).mean()# do a global onemean = latents.mean(dim=(2, 3), keepdim=True)std = latents.std(dim=(2, 3), keepdim=True, unbiased=False)mean_loss_global = (mean ** 2).mean()std_loss_global = ((std - 1) ** 2).mean()return (mean_loss_col + std_loss_col + mean_loss_row + std_loss_row + mean_loss_global + std_loss_global) / 3else:return torch.tensor(0.0, device=self.device)def get_ltv_loss(self, latent):# loss to reduce the latent space varianceif self.ltv_weight > 0:return total_variation(latent).mean()else:return torch.tensor(0.0, device=self.device)def get_latent_pixel_matching_loss(self, latent, pixels):if self.lpm_weight > 0:with torch.no_grad():pixels = pixels.to(latent.device, dtype=latent.dtype)# resize down to latent sizepixels = torch.nn.functional.interpolate(pixels, size=(latent.shape[2], latent.shape[3]), mode='bilinear', align_corners=False)# mean the color channel and then expand to latent sizepixels = pixels.mean(dim=1, keepdim=True)pixels = pixels.repeat(1, latent.shape[1], 1, 1)# match the mean std of latentlatent_mean = latent.mean(dim=(2, 3), keepdim=True)latent_std = latent.std(dim=(2, 3), keepdim=True)pixels_mean = pixels.mean(dim=(2, 3), keepdim=True)pixels_std = pixels.std(dim=(2, 3), keepdim=True)pixels = (pixels - pixels_mean) / (pixels_std + 1e-6) * latent_std + latent_meanreturn torch.nn.functional.mse_loss(latent.float(), pixels.float())else:return torch.tensor(0.0, device=self.device)def get_tv_loss(self, pred, target):if self.tv_weight > 0:get_tv_loss = ComparativeTotalVariation()53 unmodified linesinput_img = imgimg = IMAGE_TRANSFORMS(img).unsqueeze(0).to(self.device, dtype=self.torch_dtype)img = imglatent = self.vae.encode(img).latent_dist.sample()latent_img = latent.clone()bs, ch, h, w = latent_img.shapegrid_size = math.ceil(math.sqrt(ch))pad = grid_size * grid_size - ch# take first item in batchlatent_img = latent_img[0] # shape: (ch, h, w)if pad > 0:padding = torch.zeros((pad, h, w), dtype=latent_img.dtype, device=latent_img.device)latent_img = torch.cat([latent_img, padding], dim=0)# make gridnew_img = torch.zeros((1, grid_size * h, grid_size * w), dtype=latent_img.dtype, device=latent_img.device)for x in range(grid_size):for y in range(grid_size):if x * grid_size + y < ch:new_img[0, x * h:(x + 1) * h, y * w:(y + 1) * w] = latent_img[x * grid_size + y]latent_img = new_img# make rgblatent_img = latent_img.repeat(3, 1, 1).unsqueeze(0)latent_img = (latent_img / 2 + 0.5).clamp(0, 1)# resize to 256x256latent_img = torch.nn.functional.interpolate(latent_img, size=(self.resolution, self.resolution), mode='nearest')latent_img = latent_img.squeeze(0).cpu().permute(1, 2, 0).float().numpy()latent_img = (latent_img * 255).astype(np.uint8)# convert to pillow imagelatent_img = Image.fromarray(latent_img)decoded = self.vae.decode(latent).sampledecoded = (decoded / 2 + 0.5).clamp(0, 1)# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16decoded = decoded.cpu().permute(0, 2, 3, 1).squeeze(0).float().numpy()5 unmodified linesinput_img = input_img.resize((self.resolution, self.resolution))decoded = decoded.resize((self.resolution, self.resolution))output_img = Image.new('RGB', (self.resolution * 3, self.resolution))output_img.paste(input_img, (0, 0))output_img.paste(decoded, (self.resolution, 0))output_img.paste(latent_img, (self.resolution * 2, 0))scale_up = 2if output_img.height <= 300:28 unmodified linesself.print(f"Loading VAE")self.print(f" - Loading VAE: {path_to_load}")if self.vae is None:if path_to_load is not None:self.vae = AutoencoderKL.from_pretrained(path_to_load)elif self.vae_config is not None:self.vae = AutoencoderKL(**self.vae_config)else:raise ValueError('vae_path or ae_config must be specified')# set decoder to trainself.vae.to(self.device, dtype=self.torch_dtype)if self.eq_vae:self.vae.encoder.train()else:self.vae.requires_grad_(False)self.vae.eval()self.vae.decoder.train()self.vae_scale_factor = 2 ** (len(self.vae.config['block_out_channels']) - 1)36 unmodified linesif train_all:params = list(self.vae.decoder.parameters())self.vae.decoder.requires_grad_(True)if self.train_encoder:# encoderparams += list(self.vae.encoder.parameters())self.vae.encoder.requires_grad_(True)else:# mid_blockif train_all or 'mid_block' in self.blocks_to_train:8 unmodified linesparams += list(self.vae.decoder.conv_out.parameters())self.vae.decoder.conv_out.requires_grad_(True)if self.style_weight > 0 or self.content_weight > 0:self.setup_vgg19()# self.vgg_19.requires_grad_(False)self.vgg_19.eval()if self.use_critic:self.critic.setup()if self.lpips_weight > 0 and self.lpips_loss is None:# self.lpips_loss = lpips.LPIPS(net='vgg')26 unmodified lines"style": [],"content": [],"mse": [],"mvl": [],"ltv": [],"lpm": [],"kl": [],"tv": [],"ptn": [],3 unmodified linesepoch_losses = copy.deepcopy(blank_losses)log_losses = copy.deepcopy(blank_losses)# range start at self.epoch_num go to self.epochslatent_size = self.resolution // self.vae_scale_factorfor epoch in range(self.epoch_num, self.epochs, 1):if self.step_num >= self.max_steps:break1 unmodified lineif self.step_num >= self.max_steps:breakwith torch.no_grad():batch = batch.to(self.device, dtype=self.torch_dtype)if self.random_scaling:# only random scale 0.5 of the timeif random.random() < 0.5:# random scale the batchscale_factor = 0.25else:scale_factor = 0.5new_size = (int(batch.shape[2] * scale_factor), int(batch.shape[3] * scale_factor))# make sure it is vae divisiblenew_size = (new_size[0] // self.vae_scale_factor * self.vae_scale_factor,new_size[1] // self.vae_scale_factor * self.vae_scale_factor)# resize so it matches size of vae evenlyif batch.shape[2] % self.vae_scale_factor != 0 or batch.shape[3] % self.vae_scale_factor != 0:1 unmodified linebatch.shape[3] // self.vae_scale_factor * self.vae_scale_factor))(batch)# forward pass# grad only if eq_vaewith torch.set_grad_enabled(self.train_encoder):dgd = self.vae.encode(batch).latent_distmu, logvar = dgd.mean, dgd.logvarlatents = dgd.sample()if self.eq_vae:# process flips, rotate, scalelatent_chunks = list(latents.chunk(latents.shape[0], dim=0))batch_chunks = list(batch.chunk(batch.shape[0], dim=0))out_chunks = []for i in range(len(latent_chunks)):try:do_rotate = random.randint(0, 3)do_flip_x = random.randint(0, 1)do_flip_y = random.randint(0, 1)do_scale = random.randint(0, 1)if do_rotate > 0:latent_chunks[i] = torch.rot90(latent_chunks[i], do_rotate, (2, 3))batch_chunks[i] = torch.rot90(batch_chunks[i], do_rotate, (2, 3))if do_flip_x > 0:latent_chunks[i] = torch.flip(latent_chunks[i], [2])batch_chunks[i] = torch.flip(batch_chunks[i], [2])if do_flip_y > 0:latent_chunks[i] = torch.flip(latent_chunks[i], [3])batch_chunks[i] = torch.flip(batch_chunks[i], [3])# resize latent to fitif latent_chunks[i].shape[2] != latent_size or latent_chunks[i].shape[3] != latent_size:latent_chunks[i] = torch.nn.functional.interpolate(latent_chunks[i], size=(latent_size, latent_size), mode='bilinear', align_corners=False)# if do_scale > 0:# scale = 2# start_latent_h = latent_chunks[i].shape[2]# start_latent_w = latent_chunks[i].shape[3]# start_batch_h = batch_chunks[i].shape[2]# start_batch_w = batch_chunks[i].shape[3]# latent_chunks[i] = torch.nn.functional.interpolate(latent_chunks[i], scale_factor=scale, mode='bilinear', align_corners=False)# batch_chunks[i] = torch.nn.functional.interpolate(batch_chunks[i], scale_factor=scale, mode='bilinear', align_corners=False)# # random crop. latent is smaller than match but crops need to match# latent_x = random.randint(0, latent_chunks[i].shape[2] - start_latent_h)# latent_y = random.randint(0, latent_chunks[i].shape[3] - start_latent_w)# batch_x = latent_x * self.vae_scale_factor# batch_y = latent_y * self.vae_scale_factor# # crop# latent_chunks[i] = latent_chunks[i][:, :, latent_x:latent_x + start_latent_h, latent_y:latent_y + start_latent_w]# batch_chunks[i] = batch_chunks[i][:, :, batch_x:batch_x + start_batch_h, batch_y:batch_y + start_batch_w]except Exception as e:print(f"Error processing image {i}: {e}")traceback.print_exc()raise eout_chunks.append(latent_chunks[i])latents = torch.cat(out_chunks, dim=0)# do dropoutif self.dropout > 0:forward_latents = channel_dropout(latents, self.dropout)else:forward_latents = latents# resize batch to resolution if neededif batch_chunks[0].shape[2] != self.resolution or batch_chunks[0].shape[3] != self.resolution:batch_chunks = [torch.nn.functional.interpolate(b, size=(self.resolution, self.resolution), mode='bilinear', align_corners=False) for b in batch_chunks]batch = torch.cat(batch_chunks, dim=0)else:latents.detach().requires_grad_(True)forward_latents = latentsforward_latents = forward_latents.to(self.device, dtype=self.torch_dtype)if not self.train_encoder:# detach latents if not training encoderforward_latents = forward_latents.detach()pred = self.vae.decode(forward_latents).sample# Run through VGG19if self.style_weight > 0 or self.content_weight > 0:stacked = torch.cat([pred, batch], dim=0)stacked = (stacked / 2 + 0.5).clamp(0, 1)self.vgg_19(stacked)if self.use_critic:stacked = torch.cat([pred, batch], dim=0)critic_d_loss = self.critic.step(stacked.detach())else:critic_d_loss = 0.011 unmodified linestv_loss = self.get_tv_loss(pred, batch) * self.tv_weightpattern_loss = self.get_pattern_loss(pred, batch) * self.pattern_weightif self.use_critic:stacked = torch.cat([pred, batch], dim=0)critic_gen_loss = self.critic.get_critic_loss(stacked) * self.critic_weight# do not let abs critic gen loss be higher than abs lpips * 0.1 if using itif self.lpips_weight > 0:6 unmodified linescritic_gen_loss *= crit_g_scalerelse:critic_gen_loss = torch.tensor(0.0, device=self.device, dtype=self.torch_dtype)if self.mv_loss_weight > 0:mv_loss = self.get_mean_variance_loss(latents) * self.mv_loss_weightelse:mv_loss = torch.tensor(0.0, device=self.device, dtype=self.torch_dtype)if self.ltv_weight > 0:ltv_loss = self.get_ltv_loss(latents) * self.ltv_weightelse:ltv_loss = torch.tensor(0.0, device=self.device, dtype=self.torch_dtype)if self.lpm_weight > 0:lpm_loss = self.get_latent_pixel_matching_loss(latents, batch) * self.lpm_weightelse:lpm_loss = torch.tensor(0.0, device=self.device, dtype=self.torch_dtype)loss = style_loss + content_loss + kld_loss + mse_loss + tv_loss + critic_gen_loss + pattern_loss + lpips_loss + mv_loss + ltv_loss# check if loss is NaN or Infif torch.isnan(loss) or torch.isinf(loss):self.print(f"Loss is NaN or Inf, stopping at step {self.step_num}")self.print(f" - Style loss: {style_loss.item()}")self.print(f" - Content loss: {content_loss.item()}")self.print(f" - KLD loss: {kld_loss.item()}")self.print(f" - MSE loss: {mse_loss.item()}")self.print(f" - LPIPS loss: {lpips_loss.item()}")self.print(f" - TV loss: {tv_loss.item()}")self.print(f" - Pattern loss: {pattern_loss.item()}")self.print(f" - Critic gen loss: {critic_gen_loss.item()}")self.print(f" - Critic D loss: {critic_d_loss}")self.print(f" - Mean variance loss: {mv_loss.item()}")self.print(f" - Latent TV loss: {ltv_loss.item()}")self.print(f" - Latent pixel matching loss: {lpm_loss.item()}")self.print(f" - Total loss: {loss.item()}")self.print(f" - Stopping training")exit(1)# Backward pass and optimizationoptimizer.zero_grad()23 unmodified linesloss_string += f" crG: {critic_gen_loss.item():.2e}"if self.use_critic:loss_string += f" crD: {critic_d_loss:.2e}"if self.mv_loss_weight > 0:loss_string += f" mvl: {mv_loss:.2e}"if self.ltv_weight > 0:loss_string += f" ltv: {ltv_loss:.2e}"if self.lpm_weight > 0:loss_string += f" lpm: {lpm_loss:.2e}"if hasattr(optimizer, 'get_avg_learning_rate'):learning_rate = optimizer.get_avg_learning_rate()elif self.optimizer_type.startswith('dadaptation') or \self.optimizer_type.lower().startswith('prodigy'):learning_rate = (optimizer.param_groups[0]["d"] *21 unmodified linesepoch_losses["ptn"].append(pattern_loss.item())epoch_losses["crG"].append(critic_gen_loss.item())epoch_losses["crD"].append(critic_d_loss)epoch_losses["mvl"].append(mv_loss.item())epoch_losses["ltv"].append(ltv_loss.item())epoch_losses["lpm"].append(lpm_loss.item())log_losses["total"].append(loss_value)log_losses["lpips"].append(lpips_loss.item())5 unmodified lineslog_losses["ptn"].append(pattern_loss.item())log_losses["crG"].append(critic_gen_loss.item())log_losses["crD"].append(critic_d_loss)log_losses["mvl"].append(mv_loss.item())log_losses["ltv"].append(ltv_loss.item())log_losses["lpm"].append(lpm_loss.item())# don't do on first stepif self.step_num != start_step:30 unmodified lines# reset epoch lossesepoch_losses = copy.deepcopy(blank_losses)self.save()
jobs/process/TrainVAEProcess.py+307-34