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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import glob
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
from safetensors.torch import load_file, save_file
|
| 8 |
+
|
| 9 |
+
from toolkit.losses import get_gradient_penalty
|
| 10 |
+
from toolkit.metadata import get_meta_for_safetensors
|
| 11 |
+
from toolkit.optimizer import get_optimizer
|
| 12 |
+
from toolkit.train_tools import get_torch_dtype
|
| 13 |
+
|
| 14 |
+
from typing import TYPE_CHECKING, Union
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class MeanReduce(nn.Module):
|
| 18 |
+
def __init__(self):
|
| 19 |
+
super(MeanReduce, self).__init__()
|
| 20 |
+
|
| 21 |
+
def forward(self, inputs):
|
| 22 |
+
return torch.mean(inputs, dim=(1, 2, 3), keepdim=True)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class Vgg19Critic(nn.Module):
|
| 26 |
+
def __init__(self):
|
| 27 |
+
# vgg19 input (bs, 3, 512, 512)
|
| 28 |
+
# pool1 (bs, 64, 256, 256)
|
| 29 |
+
# pool2 (bs, 128, 128, 128)
|
| 30 |
+
# pool3 (bs, 256, 64, 64)
|
| 31 |
+
# pool4 (bs, 512, 32, 32) <- take this input
|
| 32 |
+
|
| 33 |
+
super(Vgg19Critic, self).__init__()
|
| 34 |
+
self.main = nn.Sequential(
|
| 35 |
+
# input (bs, 512, 32, 32)
|
| 36 |
+
# nn.Conv2d(512, 1024, kernel_size=3, stride=2, padding=1),
|
| 37 |
+
nn.utils.spectral_norm( # SN keeps D’s scale in check
|
| 38 |
+
nn.Conv2d(512, 1024, kernel_size=3, stride=2, padding=1)
|
| 39 |
+
),
|
| 40 |
+
nn.LeakyReLU(0.2), # (bs, 512, 16, 16)
|
| 41 |
+
# nn.Conv2d(1024, 1024, kernel_size=3, stride=2, padding=1),
|
| 42 |
+
nn.utils.spectral_norm(
|
| 43 |
+
nn.Conv2d(1024, 1024, kernel_size=3, stride=2, padding=1)
|
| 44 |
+
),
|
| 45 |
+
nn.LeakyReLU(0.2), # (bs, 512, 8, 8)
|
| 46 |
+
# nn.Conv2d(1024, 1024, kernel_size=3, stride=2, padding=1),
|
| 47 |
+
nn.utils.spectral_norm(
|
| 48 |
+
nn.Conv2d(1024, 1024, kernel_size=3, stride=2, padding=1)
|
| 49 |
+
),
|
| 50 |
+
# (bs, 1, 4, 4)
|
| 51 |
+
MeanReduce(), # (bs, 1, 1, 1)
|
| 52 |
+
nn.Flatten(), # (bs, 1)
|
| 53 |
+
|
| 54 |
+
# nn.Flatten(), # (128*8*8) = 8192
|
| 55 |
+
# nn.Linear(128 * 8 * 8, 1)
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
def forward(self, inputs):
|
| 59 |
+
# return self.main(inputs)
|
| 60 |
+
with torch.cuda.amp.autocast(False):
|
| 61 |
+
return self.main(inputs.float())
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
if TYPE_CHECKING:
|
| 65 |
+
from jobs.process.TrainVAEProcess import TrainVAEProcess
|
| 66 |
+
from jobs.process.TrainESRGANProcess import TrainESRGANProcess
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class Critic:
|
| 70 |
+
process: Union['TrainVAEProcess', 'TrainESRGANProcess']
|
| 71 |
+
|
| 72 |
+
def __init__(
|
| 73 |
+
self,
|
| 74 |
+
learning_rate=1e-5,
|
| 75 |
+
device='cpu',
|
| 76 |
+
optimizer='adam',
|
| 77 |
+
num_critic_per_gen=1,
|
| 78 |
+
dtype='float32',
|
| 79 |
+
lambda_gp=10,
|
| 80 |
+
start_step=0,
|
| 81 |
+
warmup_steps=1000,
|
| 82 |
+
process=None,
|
| 83 |
+
optimizer_params=None,
|
| 84 |
+
):
|
| 85 |
+
self.learning_rate = learning_rate
|
| 86 |
+
self.device = device
|
| 87 |
+
self.optimizer_type = optimizer
|
| 88 |
+
self.num_critic_per_gen = num_critic_per_gen
|
| 89 |
+
self.dtype = dtype
|
| 90 |
+
self.torch_dtype = get_torch_dtype(self.dtype)
|
| 91 |
+
self.process = process
|
| 92 |
+
self.model = None
|
| 93 |
+
self.optimizer = None
|
| 94 |
+
self.scheduler = None
|
| 95 |
+
self.warmup_steps = warmup_steps
|
| 96 |
+
self.start_step = start_step
|
| 97 |
+
self.lambda_gp = lambda_gp
|
| 98 |
+
|
| 99 |
+
if optimizer_params is None:
|
| 100 |
+
optimizer_params = {}
|
| 101 |
+
self.optimizer_params = optimizer_params
|
| 102 |
+
self.print = self.process.print
|
| 103 |
+
print(f" Critic config: {self.__dict__}")
|
| 104 |
+
|
| 105 |
+
def setup(self):
|
| 106 |
+
self.model = Vgg19Critic().to(self.device)
|
| 107 |
+
self.load_weights()
|
| 108 |
+
self.model.train()
|
| 109 |
+
self.model.requires_grad_(True)
|
| 110 |
+
params = self.model.parameters()
|
| 111 |
+
self.optimizer = get_optimizer(params, self.optimizer_type, self.learning_rate,
|
| 112 |
+
optimizer_params=self.optimizer_params)
|
| 113 |
+
self.scheduler = torch.optim.lr_scheduler.ConstantLR(
|
| 114 |
+
self.optimizer,
|
| 115 |
+
total_iters=self.process.max_steps * self.num_critic_per_gen,
|
| 116 |
+
factor=1,
|
| 117 |
+
verbose=False
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
def load_weights(self):
|
| 121 |
+
path_to_load = None
|
| 122 |
+
self.print(f"Critic: Looking for latest checkpoint in {self.process.save_root}")
|
| 123 |
+
files = glob.glob(os.path.join(self.process.save_root, f"CRITIC_{self.process.job.name}*.safetensors"))
|
| 124 |
+
if files and len(files) > 0:
|
| 125 |
+
latest_file = max(files, key=os.path.getmtime)
|
| 126 |
+
print(f" - Latest checkpoint is: {latest_file}")
|
| 127 |
+
path_to_load = latest_file
|
| 128 |
+
else:
|
| 129 |
+
self.print(f" - No checkpoint found, starting from scratch")
|
| 130 |
+
if path_to_load:
|
| 131 |
+
self.model.load_state_dict(load_file(path_to_load))
|
| 132 |
+
|
| 133 |
+
def save(self, step=None):
|
| 134 |
+
self.process.update_training_metadata()
|
| 135 |
+
save_meta = get_meta_for_safetensors(self.process.meta, self.process.job.name)
|
| 136 |
+
step_num = ''
|
| 137 |
+
if step is not None:
|
| 138 |
+
# zeropad 9 digits
|
| 139 |
+
step_num = f"_{str(step).zfill(9)}"
|
| 140 |
+
save_path = os.path.join(self.process.save_root, f"CRITIC_{self.process.job.name}{step_num}.safetensors")
|
| 141 |
+
save_file(self.model.state_dict(), save_path, save_meta)
|
| 142 |
+
self.print(f"Saved critic to {save_path}")
|
| 143 |
+
|
| 144 |
+
def get_critic_loss(self, vgg_output):
|
| 145 |
+
if self.start_step > self.process.step_num:
|
| 146 |
+
return torch.tensor(0.0, dtype=self.torch_dtype, device=self.device)
|
| 147 |
+
|
| 148 |
+
warmup_scaler = 1.0
|
| 149 |
+
# we need a warmup when we come on of 1000 steps
|
| 150 |
+
# we want to scale the loss by 0.0 at self.start_step steps and 1.0 at self.start_step + warmup_steps
|
| 151 |
+
if self.process.step_num < self.start_step + self.warmup_steps:
|
| 152 |
+
warmup_scaler = (self.process.step_num - self.start_step) / self.warmup_steps
|
| 153 |
+
# set model to not train for generator loss
|
| 154 |
+
self.model.eval()
|
| 155 |
+
self.model.requires_grad_(False)
|
| 156 |
+
# vgg_pred, vgg_target = torch.chunk(vgg_output, 2, dim=0)
|
| 157 |
+
vgg_pred, vgg_target = torch.chunk(vgg_output.float(), 2, dim=0)
|
| 158 |
+
|
| 159 |
+
# run model
|
| 160 |
+
stacked_output = self.model(vgg_pred)
|
| 161 |
+
|
| 162 |
+
return (-torch.mean(stacked_output)) * warmup_scaler
|
| 163 |
+
|
| 164 |
+
def step(self, vgg_output):
|
| 165 |
+
|
| 166 |
+
# train critic here
|
| 167 |
+
self.model.train()
|
| 168 |
+
self.model.requires_grad_(True)
|
| 169 |
+
self.optimizer.zero_grad()
|
| 170 |
+
|
| 171 |
+
critic_losses = []
|
| 172 |
+
# inputs = vgg_output.detach()
|
| 173 |
+
# inputs = inputs.to(self.device, dtype=self.torch_dtype)
|
| 174 |
+
inputs = vgg_output.detach().to(self.device, dtype=torch.float32)
|
| 175 |
+
self.optimizer.zero_grad()
|
| 176 |
+
|
| 177 |
+
vgg_pred, vgg_target = torch.chunk(inputs, 2, dim=0)
|
| 178 |
+
|
| 179 |
+
# stacked_output = self.model(inputs).float()
|
| 180 |
+
# out_pred, out_target = torch.chunk(stacked_output, 2, dim=0)
|
| 181 |
+
|
| 182 |
+
# # Compute gradient penalty
|
| 183 |
+
# gradient_penalty = get_gradient_penalty(self.model, vgg_target, vgg_pred, self.device)
|
| 184 |
+
|
| 185 |
+
# # Compute WGAN-GP critic loss
|
| 186 |
+
# critic_loss = -(torch.mean(out_target) - torch.mean(out_pred)) + self.lambda_gp * gradient_penalty
|
| 187 |
+
|
| 188 |
+
stacked_output = self.model(inputs).float()
|
| 189 |
+
out_pred, out_target = torch.chunk(stacked_output, 2, dim=0)
|
| 190 |
+
|
| 191 |
+
# ── hinge loss ──
|
| 192 |
+
loss_real = torch.relu(1.0 - out_target).mean()
|
| 193 |
+
loss_fake = torch.relu(1.0 + out_pred).mean()
|
| 194 |
+
|
| 195 |
+
# gradient penalty (unchanged helper)
|
| 196 |
+
gradient_penalty = get_gradient_penalty(self.model, vgg_target, vgg_pred, self.device)
|
| 197 |
+
|
| 198 |
+
critic_loss = loss_real + loss_fake + self.lambda_gp * gradient_penalty
|
| 199 |
+
|
| 200 |
+
critic_loss.backward()
|
| 201 |
+
torch.nn.utils.clip_grad_norm_(self.model.parameters(), 1.0)
|
| 202 |
+
self.optimizer.step()
|
| 203 |
+
self.scheduler.step()
|
| 204 |
+
critic_losses.append(critic_loss.item())
|
| 205 |
+
|
| 206 |
+
# avg loss
|
| 207 |
+
loss = np.mean(critic_losses)
|
| 208 |
+
return loss
|
| 209 |
+
|
| 210 |
+
def get_lr(self):
|
| 211 |
+
if self.optimizer_type.startswith('dadaptation'):
|
| 212 |
+
learning_rate = (
|
| 213 |
+
self.optimizer.param_groups[0]["d"] *
|
| 214 |
+
self.optimizer.param_groups[0]["lr"]
|
| 215 |
+
)
|
| 216 |
+
else:
|
| 217 |
+
learning_rate = self.optimizer.param_groups[0]['lr']
|
| 218 |
+
|
| 219 |
+
return learning_rate
|
| 220 |
+
|