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edDict
|
| 6 |
+
from typing import List, Optional
|
| 7 |
+
|
| 8 |
+
from PIL import Image
|
| 9 |
+
from PIL.ImageOps import exif_transpose
|
| 10 |
+
|
| 11 |
+
from toolkit.basic import flush
|
| 12 |
+
from toolkit.models.RRDB import RRDBNet as ESRGAN, esrgan_safetensors_keys
|
| 13 |
+
from safetensors.torch import save_file, load_file
|
| 14 |
+
from torch.utils.data import DataLoader, ConcatDataset
|
| 15 |
+
import torch
|
| 16 |
+
from torch import nn
|
| 17 |
+
from torchvision.transforms import transforms
|
| 18 |
+
|
| 19 |
+
from jobs.process import BaseTrainProcess
|
| 20 |
+
from toolkit.data_loader import AugmentedImageDataset
|
| 21 |
+
from toolkit.esrgan_utils import convert_state_dict_to_basicsr, convert_basicsr_state_dict_to_save_format
|
| 22 |
+
from toolkit.losses import ComparativeTotalVariation, get_gradient_penalty, PatternLoss
|
| 23 |
+
from toolkit.metadata import get_meta_for_safetensors
|
| 24 |
+
from toolkit.optimizer import get_optimizer
|
| 25 |
+
from toolkit.style import get_style_model_and_losses
|
| 26 |
+
from toolkit.train_tools import get_torch_dtype
|
| 27 |
+
from diffusers import AutoencoderKL
|
| 28 |
+
from tqdm import tqdm
|
| 29 |
+
import time
|
| 30 |
+
import numpy as np
|
| 31 |
+
from .models.vgg19_critic import Critic
|
| 32 |
+
|
| 33 |
+
IMAGE_TRANSFORMS = transforms.Compose(
|
| 34 |
+
[
|
| 35 |
+
transforms.ToTensor(),
|
| 36 |
+
# transforms.Normalize([0.5], [0.5]),
|
| 37 |
+
]
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class TrainESRGANProcess(BaseTrainProcess):
|
| 42 |
+
def __init__(self, process_id: int, job, config: OrderedDict):
|
| 43 |
+
super().__init__(process_id, job, config)
|
| 44 |
+
self.data_loader = None
|
| 45 |
+
self.model: ESRGAN = None
|
| 46 |
+
self.device = self.get_conf('device', self.job.device)
|
| 47 |
+
self.pretrained_path = self.get_conf('pretrained_path', 'None')
|
| 48 |
+
self.datasets_objects = self.get_conf('datasets', required=True)
|
| 49 |
+
self.batch_size = self.get_conf('batch_size', 1, as_type=int)
|
| 50 |
+
self.resolution = self.get_conf('resolution', 256, as_type=int)
|
| 51 |
+
self.learning_rate = self.get_conf('learning_rate', 1e-6, as_type=float)
|
| 52 |
+
self.sample_every = self.get_conf('sample_every', None)
|
| 53 |
+
self.optimizer_type = self.get_conf('optimizer', 'adam')
|
| 54 |
+
self.epochs = self.get_conf('epochs', None, as_type=int)
|
| 55 |
+
self.max_steps = self.get_conf('max_steps', None, as_type=int)
|
| 56 |
+
self.save_every = self.get_conf('save_every', None)
|
| 57 |
+
self.upscale_sample = self.get_conf('upscale_sample', 4)
|
| 58 |
+
self.dtype = self.get_conf('dtype', 'float32')
|
| 59 |
+
self.sample_sources = self.get_conf('sample_sources', None)
|
| 60 |
+
self.log_every = self.get_conf('log_every', 100, as_type=int)
|
| 61 |
+
self.style_weight = self.get_conf('style_weight', 0, as_type=float)
|
| 62 |
+
self.content_weight = self.get_conf('content_weight', 0, as_type=float)
|
| 63 |
+
self.mse_weight = self.get_conf('mse_weight', 1e0, as_type=float)
|
| 64 |
+
self.zoom = self.get_conf('zoom', 4, as_type=int)
|
| 65 |
+
self.tv_weight = self.get_conf('tv_weight', 1e0, as_type=float)
|
| 66 |
+
self.critic_weight = self.get_conf('critic_weight', 1, as_type=float)
|
| 67 |
+
self.pattern_weight = self.get_conf('pattern_weight', 1, as_type=float)
|
| 68 |
+
self.optimizer_params = self.get_conf('optimizer_params', {})
|
| 69 |
+
self.augmentations = self.get_conf('augmentations', {})
|
| 70 |
+
self.torch_dtype = get_torch_dtype(self.dtype)
|
| 71 |
+
if self.torch_dtype == torch.bfloat16:
|
| 72 |
+
self.esrgan_dtype = torch.float32
|
| 73 |
+
else:
|
| 74 |
+
self.esrgan_dtype = torch.float32
|
| 75 |
+
|
| 76 |
+
self.vgg_19 = None
|
| 77 |
+
self.style_weight_scalers = []
|
| 78 |
+
self.content_weight_scalers = []
|
| 79 |
+
|
| 80 |
+
# throw error if zoom if not divisible by 2
|
| 81 |
+
if self.zoom % 2 != 0:
|
| 82 |
+
raise ValueError('zoom must be divisible by 2')
|
| 83 |
+
|
| 84 |
+
self.step_num = 0
|
| 85 |
+
self.epoch_num = 0
|
| 86 |
+
|
| 87 |
+
self.use_critic = self.get_conf('use_critic', False, as_type=bool)
|
| 88 |
+
self.critic = None
|
| 89 |
+
|
| 90 |
+
if self.use_critic:
|
| 91 |
+
self.critic = Critic(
|
| 92 |
+
device=self.device,
|
| 93 |
+
dtype=self.dtype,
|
| 94 |
+
process=self,
|
| 95 |
+
**self.get_conf('critic', {}) # pass any other params
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
if self.sample_every is not None and self.sample_sources is None:
|
| 99 |
+
raise ValueError('sample_every is specified but sample_sources is not')
|
| 100 |
+
|
| 101 |
+
if self.epochs is None and self.max_steps is None:
|
| 102 |
+
raise ValueError('epochs or max_steps must be specified')
|
| 103 |
+
|
| 104 |
+
self.data_loaders = []
|
| 105 |
+
# check datasets
|
| 106 |
+
assert isinstance(self.datasets_objects, list)
|
| 107 |
+
for dataset in self.datasets_objects:
|
| 108 |
+
if 'path' not in dataset:
|
| 109 |
+
raise ValueError('dataset must have a path')
|
| 110 |
+
# check if is dir
|
| 111 |
+
if not os.path.isdir(dataset['path']):
|
| 112 |
+
raise ValueError(f"dataset path does is not a directory: {dataset['path']}")
|
| 113 |
+
|
| 114 |
+
# make training folder
|
| 115 |
+
if not os.path.exists(self.save_root):
|
| 116 |
+
os.makedirs(self.save_root, exist_ok=True)
|
| 117 |
+
|
| 118 |
+
self._pattern_loss = None
|
| 119 |
+
|
| 120 |
+
# build augmentation transforms
|
| 121 |
+
aug_transforms = []
|
| 122 |
+
|
| 123 |
+
def update_training_metadata(self):
|
| 124 |
+
self.add_meta(OrderedDict({"training_info": self.get_training_info()}))
|
| 125 |
+
|
| 126 |
+
def get_training_info(self):
|
| 127 |
+
info = OrderedDict({
|
| 128 |
+
'step': self.step_num,
|
| 129 |
+
'epoch': self.epoch_num,
|
| 130 |
+
})
|
| 131 |
+
return info
|
| 132 |
+
|
| 133 |
+
def load_datasets(self):
|
| 134 |
+
if self.data_loader is None:
|
| 135 |
+
print(f"Loading datasets")
|
| 136 |
+
datasets = []
|
| 137 |
+
for dataset in self.datasets_objects:
|
| 138 |
+
print(f" - Dataset: {dataset['path']}")
|
| 139 |
+
ds = copy.copy(dataset)
|
| 140 |
+
ds['resolution'] = self.resolution
|
| 141 |
+
|
| 142 |
+
if 'augmentations' not in ds:
|
| 143 |
+
ds['augmentations'] = self.augmentations
|
| 144 |
+
|
| 145 |
+
# add the resize down augmentation
|
| 146 |
+
ds['augmentations'] = [{
|
| 147 |
+
'method': 'Resize',
|
| 148 |
+
'params': {
|
| 149 |
+
'width': int(self.resolution // self.zoom),
|
| 150 |
+
'height': int(self.resolution // self.zoom),
|
| 151 |
+
# downscale interpolation, string will be evaluated
|
| 152 |
+
'interpolation': 'cv2.INTER_AREA'
|
| 153 |
+
}
|
| 154 |
+
}] + ds['augmentations']
|
| 155 |
+
|
| 156 |
+
image_dataset = AugmentedImageDataset(ds)
|
| 157 |
+
datasets.append(image_dataset)
|
| 158 |
+
|
| 159 |
+
concatenated_dataset = ConcatDataset(datasets)
|
| 160 |
+
self.data_loader = DataLoader(
|
| 161 |
+
concatenated_dataset,
|
| 162 |
+
batch_size=self.batch_size,
|
| 163 |
+
shuffle=True,
|
| 164 |
+
num_workers=6
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
def setup_vgg19(self):
|
| 168 |
+
if self.vgg_19 is None:
|
| 169 |
+
self.vgg_19, self.style_losses, self.content_losses, self.vgg19_pool_4 = get_style_model_and_losses(
|
| 170 |
+
single_target=True,
|
| 171 |
+
device=self.device,
|
| 172 |
+
output_layer_name='pool_4',
|
| 173 |
+
dtype=self.torch_dtype
|
| 174 |
+
)
|
| 175 |
+
self.vgg_19.to(self.device, dtype=self.torch_dtype)
|
| 176 |
+
self.vgg_19.requires_grad_(False)
|
| 177 |
+
|
| 178 |
+
# we run random noise through first to get layer scalers to normalize the loss per layer
|
| 179 |
+
# bs of 2 because we run pred and target through stacked
|
| 180 |
+
noise = torch.randn((2, 3, self.resolution, self.resolution), device=self.device, dtype=self.torch_dtype)
|
| 181 |
+
self.vgg_19(noise)
|
| 182 |
+
for style_loss in self.style_losses:
|
| 183 |
+
# get a scaler to normalize to 1
|
| 184 |
+
scaler = 1 / torch.mean(style_loss.loss).item()
|
| 185 |
+
self.style_weight_scalers.append(scaler)
|
| 186 |
+
for content_loss in self.content_losses:
|
| 187 |
+
# get a scaler to normalize to 1
|
| 188 |
+
scaler = 1 / torch.mean(content_loss.loss).item()
|
| 189 |
+
# if is nan, set to 1
|
| 190 |
+
if scaler != scaler:
|
| 191 |
+
scaler = 1
|
| 192 |
+
print(f"Warning: content loss scaler is nan, setting to 1")
|
| 193 |
+
self.content_weight_scalers.append(scaler)
|
| 194 |
+
|
| 195 |
+
self.print(f"Style weight scalers: {self.style_weight_scalers}")
|
| 196 |
+
self.print(f"Content weight scalers: {self.content_weight_scalers}")
|
| 197 |
+
|
| 198 |
+
def get_style_loss(self):
|
| 199 |
+
if self.style_weight > 0:
|
| 200 |
+
# scale all losses with loss scalers
|
| 201 |
+
loss = torch.sum(
|
| 202 |
+
torch.stack([loss.loss * scaler for loss, scaler in zip(self.style_losses, self.style_weight_scalers)]))
|
| 203 |
+
return loss
|
| 204 |
+
else:
|
| 205 |
+
return torch.tensor(0.0, device=self.device)
|
| 206 |
+
|
| 207 |
+
def get_content_loss(self):
|
| 208 |
+
if self.content_weight > 0:
|
| 209 |
+
# scale all losses with loss scalers
|
| 210 |
+
loss = torch.sum(torch.stack(
|
| 211 |
+
[loss.loss * scaler for loss, scaler in zip(self.content_losses, self.content_weight_scalers)]))
|
| 212 |
+
return loss
|
| 213 |
+
else:
|
| 214 |
+
return torch.tensor(0.0, device=self.device)
|
| 215 |
+
|
| 216 |
+
def get_mse_loss(self, pred, target):
|
| 217 |
+
if self.mse_weight > 0:
|
| 218 |
+
loss_fn = nn.MSELoss()
|
| 219 |
+
loss = loss_fn(pred, target)
|
| 220 |
+
return loss
|
| 221 |
+
else:
|
| 222 |
+
return torch.tensor(0.0, device=self.device)
|
| 223 |
+
|
| 224 |
+
def get_tv_loss(self, pred, target):
|
| 225 |
+
if self.tv_weight > 0:
|
| 226 |
+
get_tv_loss = ComparativeTotalVariation()
|
| 227 |
+
loss = get_tv_loss(pred, target)
|
| 228 |
+
return loss
|
| 229 |
+
else:
|
| 230 |
+
return torch.tensor(0.0, device=self.device)
|
| 231 |
+
|
| 232 |
+
def get_pattern_loss(self, pred, target):
|
| 233 |
+
if self._pattern_loss is None:
|
| 234 |
+
self._pattern_loss = PatternLoss(
|
| 235 |
+
pattern_size=self.zoom,
|
| 236 |
+
dtype=self.torch_dtype
|
| 237 |
+
).to(self.device, dtype=self.torch_dtype)
|
| 238 |
+
self._pattern_loss = self._pattern_loss.to(self.device, dtype=self.torch_dtype)
|
| 239 |
+
loss = torch.mean(self._pattern_loss(pred, target))
|
| 240 |
+
return loss
|
| 241 |
+
|
| 242 |
+
def save(self, step=None):
|
| 243 |
+
if not os.path.exists(self.save_root):
|
| 244 |
+
os.makedirs(self.save_root, exist_ok=True)
|
| 245 |
+
|
| 246 |
+
step_num = ''
|
| 247 |
+
if step is not None:
|
| 248 |
+
# zeropad 9 digits
|
| 249 |
+
step_num = f"_{str(step).zfill(9)}"
|
| 250 |
+
|
| 251 |
+
self.update_training_metadata()
|
| 252 |
+
# filename = f'{self.job.name}{step_num}.safetensors'
|
| 253 |
+
filename = f'{self.job.name}{step_num}.pth'
|
| 254 |
+
# prepare meta
|
| 255 |
+
save_meta = get_meta_for_safetensors(self.meta, self.job.name)
|
| 256 |
+
|
| 257 |
+
# state_dict = self.model.state_dict()
|
| 258 |
+
|
| 259 |
+
# state has the original state dict keys so we can save what we started from
|
| 260 |
+
save_state_dict = self.model.state_dict()
|
| 261 |
+
|
| 262 |
+
for key in list(save_state_dict.keys()):
|
| 263 |
+
v = save_state_dict[key]
|
| 264 |
+
v = v.detach().clone().to("cpu").to(torch.float32)
|
| 265 |
+
save_state_dict[key] = v
|
| 266 |
+
|
| 267 |
+
# most things wont use safetensors, save as torch
|
| 268 |
+
# save_file(save_state_dict, os.path.join(self.save_root, filename), save_meta)
|
| 269 |
+
torch.save(save_state_dict, os.path.join(self.save_root, filename))
|
| 270 |
+
|
| 271 |
+
self.print(f"Saved to {os.path.join(self.save_root, filename)}")
|
| 272 |
+
|
| 273 |
+
if self.use_critic:
|
| 274 |
+
self.critic.save(step)
|
| 275 |
+
|
| 276 |
+
def sample(self, step=None, batch: Optional[List[torch.Tensor]] = None):
|
| 277 |
+
sample_folder = os.path.join(self.save_root, 'samples')
|
| 278 |
+
if not os.path.exists(sample_folder):
|
| 279 |
+
os.makedirs(sample_folder, exist_ok=True)
|
| 280 |
+
batch_sample_folder = os.path.join(self.save_root, 'samples_batch')
|
| 281 |
+
|
| 282 |
+
batch_targets = None
|
| 283 |
+
batch_inputs = None
|
| 284 |
+
if batch is not None and not os.path.exists(batch_sample_folder):
|
| 285 |
+
os.makedirs(batch_sample_folder, exist_ok=True)
|
| 286 |
+
|
| 287 |
+
self.model.eval()
|
| 288 |
+
|
| 289 |
+
def process_and_save(img, target_img, save_path):
|
| 290 |
+
img = img.to(self.device, dtype=self.esrgan_dtype)
|
| 291 |
+
output = self.model(img)
|
| 292 |
+
# output = (output / 2 + 0.5).clamp(0, 1)
|
| 293 |
+
output = output.clamp(0, 1)
|
| 294 |
+
img = img.clamp(0, 1)
|
| 295 |
+
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
|
| 296 |
+
output = output.cpu().permute(0, 2, 3, 1).squeeze(0).float().numpy()
|
| 297 |
+
img = img.cpu().permute(0, 2, 3, 1).squeeze(0).float().numpy()
|
| 298 |
+
|
| 299 |
+
# convert to pillow image
|
| 300 |
+
output = Image.fromarray((output * 255).astype(np.uint8))
|
| 301 |
+
img = Image.fromarray((img * 255).astype(np.uint8))
|
| 302 |
+
|
| 303 |
+
if isinstance(target_img, torch.Tensor):
|
| 304 |
+
# convert to pil
|
| 305 |
+
target_img = target_img.cpu().permute(0, 2, 3, 1).squeeze(0).float().numpy()
|
| 306 |
+
target_img = Image.fromarray((target_img * 255).astype(np.uint8))
|
| 307 |
+
|
| 308 |
+
# upscale to size * self.upscale_sample while maintaining pixels
|
| 309 |
+
output = output.resize(
|
| 310 |
+
(self.resolution * self.upscale_sample, self.resolution * self.upscale_sample),
|
| 311 |
+
resample=Image.NEAREST
|
| 312 |
+
)
|
| 313 |
+
img = img.resize(
|
| 314 |
+
(self.resolution * self.upscale_sample, self.resolution * self.upscale_sample),
|
| 315 |
+
resample=Image.NEAREST
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
width, height = output.size
|
| 319 |
+
|
| 320 |
+
# stack input image and decoded image
|
| 321 |
+
target_image = target_img.resize((width, height))
|
| 322 |
+
output = output.resize((width, height))
|
| 323 |
+
img = img.resize((width, height))
|
| 324 |
+
|
| 325 |
+
output_img = Image.new('RGB', (width * 3, height))
|
| 326 |
+
|
| 327 |
+
output_img.paste(img, (0, 0))
|
| 328 |
+
output_img.paste(output, (width, 0))
|
| 329 |
+
output_img.paste(target_image, (width * 2, 0))
|
| 330 |
+
|
| 331 |
+
output_img.save(save_path)
|
| 332 |
+
|
| 333 |
+
with torch.no_grad():
|
| 334 |
+
for i, img_url in enumerate(self.sample_sources):
|
| 335 |
+
img = exif_transpose(Image.open(img_url))
|
| 336 |
+
img = img.convert('RGB')
|
| 337 |
+
# crop if not square
|
| 338 |
+
if img.width != img.height:
|
| 339 |
+
min_dim = min(img.width, img.height)
|
| 340 |
+
img = img.crop((0, 0, min_dim, min_dim))
|
| 341 |
+
# resize
|
| 342 |
+
img = img.resize((self.resolution * self.zoom, self.resolution * self.zoom), resample=Image.BICUBIC)
|
| 343 |
+
|
| 344 |
+
target_image = img
|
| 345 |
+
# downscale the image input
|
| 346 |
+
img = img.resize((self.resolution, self.resolution), resample=Image.BICUBIC)
|
| 347 |
+
|
| 348 |
+
# downscale the image input
|
| 349 |
+
|
| 350 |
+
img = IMAGE_TRANSFORMS(img).unsqueeze(0).to(self.device, dtype=self.esrgan_dtype)
|
| 351 |
+
img = img
|
| 352 |
+
|
| 353 |
+
step_num = ''
|
| 354 |
+
if step is not None:
|
| 355 |
+
# zero-pad 9 digits
|
| 356 |
+
step_num = f"_{str(step).zfill(9)}"
|
| 357 |
+
seconds_since_epoch = int(time.time())
|
| 358 |
+
# zero-pad 2 digits
|
| 359 |
+
i_str = str(i).zfill(2)
|
| 360 |
+
filename = f"{seconds_since_epoch}{step_num}_{i_str}.jpg"
|
| 361 |
+
process_and_save(img, target_image, os.path.join(sample_folder, filename))
|
| 362 |
+
|
| 363 |
+
if batch is not None:
|
| 364 |
+
batch_targets = batch[0].detach()
|
| 365 |
+
batch_inputs = batch[1].detach()
|
| 366 |
+
batch_targets = torch.chunk(batch_targets, batch_targets.shape[0], dim=0)
|
| 367 |
+
batch_inputs = torch.chunk(batch_inputs, batch_inputs.shape[0], dim=0)
|
| 368 |
+
|
| 369 |
+
for i in range(len(batch_inputs)):
|
| 370 |
+
if step is not None:
|
| 371 |
+
# zero-pad 9 digits
|
| 372 |
+
step_num = f"_{str(step).zfill(9)}"
|
| 373 |
+
seconds_since_epoch = int(time.time())
|
| 374 |
+
# zero-pad 2 digits
|
| 375 |
+
i_str = str(i).zfill(2)
|
| 376 |
+
filename = f"{seconds_since_epoch}{step_num}_{i_str}.jpg"
|
| 377 |
+
process_and_save(batch_inputs[i], batch_targets[i], os.path.join(batch_sample_folder, filename))
|
| 378 |
+
|
| 379 |
+
self.model.train()
|
| 380 |
+
|
| 381 |
+
def load_model(self):
|
| 382 |
+
state_dict = None
|
| 383 |
+
path_to_load = self.pretrained_path
|
| 384 |
+
# see if we have a checkpoint in out output to resume from
|
| 385 |
+
self.print(f"Looking for latest checkpoint in {self.save_root}")
|
| 386 |
+
files = glob.glob(os.path.join(self.save_root, f"{self.job.name}*.safetensors"))
|
| 387 |
+
files += glob.glob(os.path.join(self.save_root, f"{self.job.name}*.pth"))
|
| 388 |
+
if files and len(files) > 0:
|
| 389 |
+
latest_file = max(files, key=os.path.getmtime)
|
| 390 |
+
print(f" - Latest checkpoint is: {latest_file}")
|
| 391 |
+
path_to_load = latest_file
|
| 392 |
+
# todo update step and epoch count
|
| 393 |
+
elif self.pretrained_path is None:
|
| 394 |
+
self.print(f" - No checkpoint found, starting from scratch")
|
| 395 |
+
else:
|
| 396 |
+
self.print(f" - No checkpoint found, loading pretrained model")
|
| 397 |
+
self.print(f" - path: {path_to_load}")
|
| 398 |
+
|
| 399 |
+
if path_to_load is not None:
|
| 400 |
+
self.print(f" - Loading pretrained checkpoint: {path_to_load}")
|
| 401 |
+
# if ends with pth then assume pytorch checkpoint
|
| 402 |
+
if path_to_load.endswith('.pth') or path_to_load.endswith('.pt'):
|
| 403 |
+
state_dict = torch.load(path_to_load, map_location=self.device)
|
| 404 |
+
elif path_to_load.endswith('.safetensors'):
|
| 405 |
+
state_dict_raw = load_file(path_to_load)
|
| 406 |
+
# make ordered dict as most things need it
|
| 407 |
+
state_dict = OrderedDict()
|
| 408 |
+
for key in esrgan_safetensors_keys:
|
| 409 |
+
state_dict[key] = state_dict_raw[key]
|
| 410 |
+
else:
|
| 411 |
+
raise Exception(f"Unknown file extension for checkpoint: {path_to_load}")
|
| 412 |
+
|
| 413 |
+
# todo determine architecture from checkpoint
|
| 414 |
+
self.model = ESRGAN(
|
| 415 |
+
state_dict
|
| 416 |
+
).to(self.device, dtype=self.esrgan_dtype)
|
| 417 |
+
|
| 418 |
+
# set the model to training mode
|
| 419 |
+
self.model.train()
|
| 420 |
+
self.model.requires_grad_(True)
|
| 421 |
+
|
| 422 |
+
def run(self):
|
| 423 |
+
super().run()
|
| 424 |
+
self.load_datasets()
|
| 425 |
+
steps_per_step = (self.critic.num_critic_per_gen + 1)
|
| 426 |
+
|
| 427 |
+
max_step_epochs = self.max_steps // (len(self.data_loader) // steps_per_step)
|
| 428 |
+
num_epochs = self.epochs
|
| 429 |
+
if num_epochs is None or num_epochs > max_step_epochs:
|
| 430 |
+
num_epochs = max_step_epochs
|
| 431 |
+
|
| 432 |
+
max_epoch_steps = len(self.data_loader) * num_epochs * steps_per_step
|
| 433 |
+
num_steps = self.max_steps
|
| 434 |
+
if num_steps is None or num_steps > max_epoch_steps:
|
| 435 |
+
num_steps = max_epoch_steps
|
| 436 |
+
self.max_steps = num_steps
|
| 437 |
+
self.epochs = num_epochs
|
| 438 |
+
start_step = self.step_num
|
| 439 |
+
self.first_step = start_step
|
| 440 |
+
|
| 441 |
+
self.print(f"Training ESRGAN model:")
|
| 442 |
+
self.print(f" - Training folder: {self.training_folder}")
|
| 443 |
+
self.print(f" - Batch size: {self.batch_size}")
|
| 444 |
+
self.print(f" - Learning rate: {self.learning_rate}")
|
| 445 |
+
self.print(f" - Epochs: {num_epochs}")
|
| 446 |
+
self.print(f" - Max steps: {self.max_steps}")
|
| 447 |
+
|
| 448 |
+
# load model
|
| 449 |
+
self.load_model()
|
| 450 |
+
|
| 451 |
+
params = self.model.parameters()
|
| 452 |
+
|
| 453 |
+
if self.style_weight > 0 or self.content_weight > 0 or self.use_critic:
|
| 454 |
+
self.setup_vgg19()
|
| 455 |
+
self.vgg_19.requires_grad_(False)
|
| 456 |
+
self.vgg_19.eval()
|
| 457 |
+
if self.use_critic:
|
| 458 |
+
self.critic.setup()
|
| 459 |
+
|
| 460 |
+
optimizer = get_optimizer(params, self.optimizer_type, self.learning_rate,
|
| 461 |
+
optimizer_params=self.optimizer_params)
|
| 462 |
+
|
| 463 |
+
# setup scheduler
|
| 464 |
+
# todo allow other schedulers
|
| 465 |
+
scheduler = torch.optim.lr_scheduler.ConstantLR(
|
| 466 |
+
optimizer,
|
| 467 |
+
total_iters=num_steps,
|
| 468 |
+
factor=1,
|
| 469 |
+
verbose=False
|
| 470 |
+
)
|
| 471 |
+
|
| 472 |
+
# setup tqdm progress bar
|
| 473 |
+
self.progress_bar = tqdm(
|
| 474 |
+
total=num_steps,
|
| 475 |
+
desc='Training ESRGAN',
|
| 476 |
+
leave=True
|
| 477 |
+
)
|
| 478 |
+
|
| 479 |
+
blank_losses = OrderedDict({
|
| 480 |
+
"total": [],
|
| 481 |
+
"style": [],
|
| 482 |
+
"content": [],
|
| 483 |
+
"mse": [],
|
| 484 |
+
"kl": [],
|
| 485 |
+
"tv": [],
|
| 486 |
+
"ptn": [],
|
| 487 |
+
"crD": [],
|
| 488 |
+
"crG": [],
|
| 489 |
+
})
|
| 490 |
+
epoch_losses = copy.deepcopy(blank_losses)
|
| 491 |
+
log_losses = copy.deepcopy(blank_losses)
|
| 492 |
+
print("Generating baseline samples")
|
| 493 |
+
self.sample(step=0)
|
| 494 |
+
# range start at self.epoch_num go to self.epochs
|
| 495 |
+
critic_losses = []
|
| 496 |
+
for epoch in range(self.epoch_num, self.epochs, 1):
|
| 497 |
+
if self.step_num >= self.max_steps:
|
| 498 |
+
break
|
| 499 |
+
flush()
|
| 500 |
+
for targets, inputs in self.data_loader:
|
| 501 |
+
if self.step_num >= self.max_steps:
|
| 502 |
+
break
|
| 503 |
+
with torch.no_grad():
|
| 504 |
+
is_critic_only_step = False
|
| 505 |
+
if self.use_critic and 1 / (self.critic.num_critic_per_gen + 1) < np.random.uniform():
|
| 506 |
+
is_critic_only_step = True
|
| 507 |
+
|
| 508 |
+
targets = targets.to(self.device, dtype=self.esrgan_dtype).clamp(0, 1).detach()
|
| 509 |
+
inputs = inputs.to(self.device, dtype=self.esrgan_dtype).clamp(0, 1).detach()
|
| 510 |
+
|
| 511 |
+
optimizer.zero_grad()
|
| 512 |
+
# dont do grads here for critic step
|
| 513 |
+
do_grad = not is_critic_only_step
|
| 514 |
+
with torch.set_grad_enabled(do_grad):
|
| 515 |
+
pred = self.model(inputs)
|
| 516 |
+
|
| 517 |
+
pred = pred.to(self.device, dtype=self.torch_dtype).clamp(0, 1)
|
| 518 |
+
targets = targets.to(self.device, dtype=self.torch_dtype).clamp(0, 1)
|
| 519 |
+
if torch.isnan(pred).any():
|
| 520 |
+
raise ValueError('pred has nan values')
|
| 521 |
+
if torch.isnan(targets).any():
|
| 522 |
+
raise ValueError('targets has nan values')
|
| 523 |
+
|
| 524 |
+
# Run through VGG19
|
| 525 |
+
if self.style_weight > 0 or self.content_weight > 0 or self.use_critic:
|
| 526 |
+
stacked = torch.cat([pred, targets], dim=0)
|
| 527 |
+
# stacked = (stacked / 2 + 0.5).clamp(0, 1)
|
| 528 |
+
stacked = stacked.clamp(0, 1)
|
| 529 |
+
self.vgg_19(stacked)
|
| 530 |
+
# make sure we dont have nans
|
| 531 |
+
if torch.isnan(self.vgg19_pool_4.tensor).any():
|
| 532 |
+
raise ValueError('vgg19_pool_4 has nan values')
|
| 533 |
+
|
| 534 |
+
if is_critic_only_step:
|
| 535 |
+
critic_d_loss = self.critic.step(self.vgg19_pool_4.tensor.detach())
|
| 536 |
+
critic_losses.append(critic_d_loss)
|
| 537 |
+
# don't do generator step
|
| 538 |
+
continue
|
| 539 |
+
else:
|
| 540 |
+
# doing a regular step
|
| 541 |
+
if len(critic_losses) == 0:
|
| 542 |
+
critic_d_loss = 0
|
| 543 |
+
else:
|
| 544 |
+
critic_d_loss = sum(critic_losses) / len(critic_losses)
|
| 545 |
+
|
| 546 |
+
style_loss = self.get_style_loss() * self.style_weight
|
| 547 |
+
content_loss = self.get_content_loss() * self.content_weight
|
| 548 |
+
|
| 549 |
+
mse_loss = self.get_mse_loss(pred, targets) * self.mse_weight
|
| 550 |
+
tv_loss = self.get_tv_loss(pred, targets) * self.tv_weight
|
| 551 |
+
pattern_loss = self.get_pattern_loss(pred, targets) * self.pattern_weight
|
| 552 |
+
if self.use_critic:
|
| 553 |
+
critic_gen_loss = self.critic.get_critic_loss(self.vgg19_pool_4.tensor) * self.critic_weight
|
| 554 |
+
else:
|
| 555 |
+
critic_gen_loss = torch.tensor(0.0, device=self.device, dtype=self.torch_dtype)
|
| 556 |
+
|
| 557 |
+
loss = style_loss + content_loss + mse_loss + tv_loss + critic_gen_loss + pattern_loss
|
| 558 |
+
# make sure non nan
|
| 559 |
+
if torch.isnan(loss):
|
| 560 |
+
raise ValueError('loss is nan')
|
| 561 |
+
|
| 562 |
+
# Backward pass and optimization
|
| 563 |
+
loss.backward()
|
| 564 |
+
torch.nn.utils.clip_grad_norm_(self.model.parameters(), 1.0)
|
| 565 |
+
optimizer.step()
|
| 566 |
+
scheduler.step()
|
| 567 |
+
|
| 568 |
+
# update progress bar
|
| 569 |
+
loss_value = loss.item()
|
| 570 |
+
# get exponent like 3.54e-4
|
| 571 |
+
loss_string = f"loss: {loss_value:.2e}"
|
| 572 |
+
if self.content_weight > 0:
|
| 573 |
+
loss_string += f" cnt: {content_loss.item():.2e}"
|
| 574 |
+
if self.style_weight > 0:
|
| 575 |
+
loss_string += f" sty: {style_loss.item():.2e}"
|
| 576 |
+
if self.mse_weight > 0:
|
| 577 |
+
loss_string += f" mse: {mse_loss.item():.2e}"
|
| 578 |
+
if self.tv_weight > 0:
|
| 579 |
+
loss_string += f" tv: {tv_loss.item():.2e}"
|
| 580 |
+
if self.pattern_weight > 0:
|
| 581 |
+
loss_string += f" ptn: {pattern_loss.item():.2e}"
|
| 582 |
+
if self.use_critic and self.critic_weight > 0:
|
| 583 |
+
loss_string += f" crG: {critic_gen_loss.item():.2e}"
|
| 584 |
+
if self.use_critic:
|
| 585 |
+
loss_string += f" crD: {critic_d_loss:.2e}"
|
| 586 |
+
|
| 587 |
+
if self.optimizer_type.startswith('dadaptation') or self.optimizer_type.startswith('prodigy'):
|
| 588 |
+
learning_rate = (
|
| 589 |
+
optimizer.param_groups[0]["d"] *
|
| 590 |
+
optimizer.param_groups[0]["lr"]
|
| 591 |
+
)
|
| 592 |
+
else:
|
| 593 |
+
learning_rate = optimizer.param_groups[0]['lr']
|
| 594 |
+
|
| 595 |
+
lr_critic_string = ''
|
| 596 |
+
if self.use_critic:
|
| 597 |
+
lr_critic = self.critic.get_lr()
|
| 598 |
+
lr_critic_string = f" lrC: {lr_critic:.1e}"
|
| 599 |
+
|
| 600 |
+
self.progress_bar.set_postfix_str(f"lr: {learning_rate:.1e}{lr_critic_string} {loss_string}")
|
| 601 |
+
self.progress_bar.set_description(f"E: {epoch}")
|
| 602 |
+
self.progress_bar.update(1)
|
| 603 |
+
|
| 604 |
+
epoch_losses["total"].append(loss_value)
|
| 605 |
+
epoch_losses["style"].append(style_loss.item())
|
| 606 |
+
epoch_losses["content"].append(content_loss.item())
|
| 607 |
+
epoch_losses["mse"].append(mse_loss.item())
|
| 608 |
+
epoch_losses["tv"].append(tv_loss.item())
|
| 609 |
+
epoch_losses["ptn"].append(pattern_loss.item())
|
| 610 |
+
epoch_losses["crG"].append(critic_gen_loss.item())
|
| 611 |
+
epoch_losses["crD"].append(critic_d_loss)
|
| 612 |
+
|
| 613 |
+
log_losses["total"].append(loss_value)
|
| 614 |
+
log_losses["style"].append(style_loss.item())
|
| 615 |
+
log_losses["content"].append(content_loss.item())
|
| 616 |
+
log_losses["mse"].append(mse_loss.item())
|
| 617 |
+
log_losses["tv"].append(tv_loss.item())
|
| 618 |
+
log_losses["ptn"].append(pattern_loss.item())
|
| 619 |
+
log_losses["crG"].append(critic_gen_loss.item())
|
| 620 |
+
log_losses["crD"].append(critic_d_loss)
|
| 621 |
+
|
| 622 |
+
# don't do on first step
|
| 623 |
+
if self.step_num != start_step:
|
| 624 |
+
if self.sample_every and self.step_num % self.sample_every == 0:
|
| 625 |
+
# print above the progress bar
|
| 626 |
+
self.print(f"Sampling at step {self.step_num}")
|
| 627 |
+
self.sample(self.step_num, batch=[targets, inputs])
|
| 628 |
+
|
| 629 |
+
if self.save_every and self.step_num % self.save_every == 0:
|
| 630 |
+
# print above the progress bar
|
| 631 |
+
self.print(f"Saving at step {self.step_num}")
|
| 632 |
+
self.save(self.step_num)
|
| 633 |
+
|
| 634 |
+
if self.log_every and self.step_num % self.log_every == 0:
|
| 635 |
+
# log to tensorboard
|
| 636 |
+
if self.writer is not None:
|
| 637 |
+
# get avg loss
|
| 638 |
+
for key in log_losses:
|
| 639 |
+
log_losses[key] = sum(log_losses[key]) / (len(log_losses[key]) + 1e-6)
|
| 640 |
+
# if log_losses[key] > 0:
|
| 641 |
+
self.writer.add_scalar(f"loss/{key}", log_losses[key], self.step_num)
|
| 642 |
+
# reset log losses
|
| 643 |
+
log_losses = copy.deepcopy(blank_losses)
|
| 644 |
+
|
| 645 |
+
self.step_num += 1
|
| 646 |
+
# end epoch
|
| 647 |
+
if self.writer is not None:
|
| 648 |
+
eps = 1e-6
|
| 649 |
+
# get avg loss
|
| 650 |
+
for key in epoch_losses:
|
| 651 |
+
epoch_losses[key] = sum(log_losses[key]) / (len(log_losses[key]) + eps)
|
| 652 |
+
if epoch_losses[key] > 0:
|
| 653 |
+
self.writer.add_scalar(f"epoch loss/{key}", epoch_losses[key], epoch)
|
| 654 |
+
# reset epoch losses
|
| 655 |
+
epoch_losses = copy.deepcopy(blank_losses)
|
| 656 |
+
|
| 657 |
+
self.save()
|