|
|
|
@@ -7,6 +7,7 @@ from inspect import isfunction
|
|
|
|
|
from functools import partial
|
|
|
|
|
|
|
|
|
|
from torch.utils import data
|
|
|
|
|
from multiprocessing import cpu_count
|
|
|
|
|
from torch.cuda.amp import autocast, GradScaler
|
|
|
|
|
|
|
|
|
|
from pathlib import Path
|
|
|
|
@@ -15,7 +16,7 @@ from torchvision import transforms, utils
|
|
|
|
|
from PIL import Image
|
|
|
|
|
|
|
|
|
|
from tqdm import tqdm
|
|
|
|
|
from einops import rearrange
|
|
|
|
|
from einops import rearrange, reduce
|
|
|
|
|
from einops.layers.torch import Rearrange
|
|
|
|
|
|
|
|
|
|
# helpers functions
|
|
|
|
@@ -242,7 +243,7 @@ class Unet(nn.Module):
|
|
|
|
|
|
|
|
|
|
self.channels = channels
|
|
|
|
|
|
|
|
|
|
init_dim = default(init_dim, dim // 3 * 2)
|
|
|
|
|
init_dim = default(init_dim, dim)
|
|
|
|
|
self.init_conv = nn.Conv2d(channels, init_dim, 7, padding = 3)
|
|
|
|
|
|
|
|
|
|
dims = [init_dim, *map(lambda m: dim * m, dim_mults)]
|
|
|
|
@@ -287,8 +288,8 @@ class Unet(nn.Module):
|
|
|
|
|
self.mid_attn = Residual(PreNorm(mid_dim, Attention(mid_dim)))
|
|
|
|
|
self.mid_block2 = block_klass(mid_dim, mid_dim, time_emb_dim = time_dim)
|
|
|
|
|
|
|
|
|
|
for ind, (dim_in, dim_out) in enumerate(reversed(in_out[1:])):
|
|
|
|
|
is_last = ind >= (num_resolutions - 1)
|
|
|
|
|
for ind, (dim_in, dim_out) in enumerate(reversed(in_out)):
|
|
|
|
|
is_last = ind == (len(in_out) - 1)
|
|
|
|
|
|
|
|
|
|
self.ups.append(nn.ModuleList([
|
|
|
|
|
block_klass(dim_out * 2, dim_in, time_emb_dim = time_dim),
|
|
|
|
@@ -301,12 +302,14 @@ class Unet(nn.Module):
|
|
|
|
|
self.out_dim = default(out_dim, default_out_dim)
|
|
|
|
|
|
|
|
|
|
self.final_conv = nn.Sequential(
|
|
|
|
|
block_klass(dim, dim),
|
|
|
|
|
block_klass(dim * 2, dim),
|
|
|
|
|
nn.Conv2d(dim, self.out_dim, 1)
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
def forward(self, x, time):
|
|
|
|
|
x = self.init_conv(x)
|
|
|
|
|
r = x.clone()
|
|
|
|
|
|
|
|
|
|
t = self.time_mlp(time)
|
|
|
|
|
|
|
|
|
|
h = []
|
|
|
|
@@ -323,12 +326,13 @@ class Unet(nn.Module):
|
|
|
|
|
x = self.mid_block2(x, t)
|
|
|
|
|
|
|
|
|
|
for block1, block2, attn, upsample in self.ups:
|
|
|
|
|
x = torch.cat((x, h.pop()), dim=1)
|
|
|
|
|
x = torch.cat((x, h.pop()), dim = 1)
|
|
|
|
|
x = block1(x, t)
|
|
|
|
|
x = block2(x, t)
|
|
|
|
|
x = attn(x)
|
|
|
|
|
x = upsample(x)
|
|
|
|
|
|
|
|
|
|
x = torch.cat((x, r), dim = 1)
|
|
|
|
|
return self.final_conv(x)
|
|
|
|
|
|
|
|
|
|
# gaussian diffusion trainer class
|
|
|
|
@@ -366,7 +370,9 @@ class GaussianDiffusion(nn.Module):
|
|
|
|
|
timesteps = 1000,
|
|
|
|
|
loss_type = 'l1',
|
|
|
|
|
objective = 'pred_noise',
|
|
|
|
|
beta_schedule = 'cosine'
|
|
|
|
|
beta_schedule = 'cosine',
|
|
|
|
|
p2_loss_weight_gamma = 0., # p2 loss weight, from https://arxiv.org/abs/2204.00227 - 0 is equivalent to weight of 1 across time - 1. is recommended
|
|
|
|
|
p2_loss_weight_k = 1
|
|
|
|
|
):
|
|
|
|
|
super().__init__()
|
|
|
|
|
assert not (type(self) == GaussianDiffusion and denoise_fn.channels != denoise_fn.out_dim)
|
|
|
|
@@ -421,6 +427,10 @@ class GaussianDiffusion(nn.Module):
|
|
|
|
|
register_buffer('posterior_mean_coef1', betas * torch.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod))
|
|
|
|
|
register_buffer('posterior_mean_coef2', (1. - alphas_cumprod_prev) * torch.sqrt(alphas) / (1. - alphas_cumprod))
|
|
|
|
|
|
|
|
|
|
# calculate p2 reweighting
|
|
|
|
|
|
|
|
|
|
register_buffer('p2_loss_weight', (p2_loss_weight_k + alphas_cumprod / (1 - alphas_cumprod)) ** -p2_loss_weight_gamma)
|
|
|
|
|
|
|
|
|
|
def predict_start_from_noise(self, x_t, t, noise):
|
|
|
|
|
return (
|
|
|
|
|
extract(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
|
|
|
|
@@ -527,8 +537,11 @@ class GaussianDiffusion(nn.Module):
|
|
|
|
|
else:
|
|
|
|
|
raise ValueError(f'unknown objective {self.objective}')
|
|
|
|
|
|
|
|
|
|
loss = self.loss_fn(model_out, target)
|
|
|
|
|
return loss
|
|
|
|
|
loss = self.loss_fn(model_out, target, reduction = 'none')
|
|
|
|
|
loss = reduce(loss, 'b ... -> b (...)', 'mean')
|
|
|
|
|
|
|
|
|
|
loss = loss * extract(self.p2_loss_weight, t, loss.shape)
|
|
|
|
|
return loss.mean()
|
|
|
|
|
|
|
|
|
|
def forward(self, img, *args, **kwargs):
|
|
|
|
|
b, c, h, w, device, img_size, = *img.shape, img.device, self.image_size
|
|
|
|
@@ -598,7 +611,7 @@ class Trainer(object):
|
|
|
|
|
self.train_num_steps = train_num_steps
|
|
|
|
|
|
|
|
|
|
self.ds = Dataset(folder, image_size, augment_horizontal_flip = augment_horizontal_flip)
|
|
|
|
|
self.dl = cycle(data.DataLoader(self.ds, batch_size = train_batch_size, shuffle=True, pin_memory=True))
|
|
|
|
|
self.dl = cycle(data.DataLoader(self.ds, batch_size = train_batch_size, shuffle = True, pin_memory = True, num_workers = cpu_count()))
|
|
|
|
|
self.opt = Adam(diffusion_model.parameters(), lr=train_lr)
|
|
|
|
|
|
|
|
|
|
self.step = 0
|
|
|
|
|