mirror of
https://github.com/wassname/denoising-diffusion-pytorch.git
synced 2026-09-10 12:01:08 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
caa5af170d | ||
|
|
55c658b967 | ||
|
|
e0f26677d6 | ||
|
|
e147839d74 | ||
|
|
62e8490385 | ||
|
|
d412d8816b |
@@ -1 +1,2 @@
|
|||||||
from denoising_diffusion_pytorch.denoising_diffusion_pytorch import GaussianDiffusion, Unet, Trainer
|
from denoising_diffusion_pytorch.denoising_diffusion_pytorch import GaussianDiffusion, Unet, Trainer
|
||||||
|
from denoising_diffusion_pytorch.learned_gaussian_diffusion import LearnedGaussianDiffusion
|
||||||
|
|||||||
@@ -40,6 +40,12 @@ def num_to_groups(num, divisor):
|
|||||||
arr.append(remainder)
|
arr.append(remainder)
|
||||||
return arr
|
return arr
|
||||||
|
|
||||||
|
def normalize_to_neg_one_to_one(img):
|
||||||
|
return img * 2 - 1
|
||||||
|
|
||||||
|
def unnormalize_to_zero_to_one(t):
|
||||||
|
return (t + 1) * 0.5
|
||||||
|
|
||||||
# small helper modules
|
# small helper modules
|
||||||
|
|
||||||
class EMA():
|
class EMA():
|
||||||
@@ -204,7 +210,8 @@ class Unet(nn.Module):
|
|||||||
dim_mults=(1, 2, 4, 8),
|
dim_mults=(1, 2, 4, 8),
|
||||||
channels = 3,
|
channels = 3,
|
||||||
with_time_emb = True,
|
with_time_emb = True,
|
||||||
resnet_block_groups = 8
|
resnet_block_groups = 8,
|
||||||
|
learned_variance = False
|
||||||
):
|
):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
@@ -265,10 +272,12 @@ class Unet(nn.Module):
|
|||||||
Upsample(dim_in) if not is_last else nn.Identity()
|
Upsample(dim_in) if not is_last else nn.Identity()
|
||||||
]))
|
]))
|
||||||
|
|
||||||
out_dim = default(out_dim, channels)
|
default_out_dim = channels * (1 if not learned_variance else 2)
|
||||||
|
self.out_dim = default(out_dim, default_out_dim)
|
||||||
|
|
||||||
self.final_conv = nn.Sequential(
|
self.final_conv = nn.Sequential(
|
||||||
block_klass(dim, dim),
|
block_klass(dim, dim),
|
||||||
nn.Conv2d(dim, out_dim, 1)
|
nn.Conv2d(dim, self.out_dim, 1)
|
||||||
)
|
)
|
||||||
|
|
||||||
def forward(self, x, time):
|
def forward(self, x, time):
|
||||||
@@ -320,7 +329,7 @@ def cosine_beta_schedule(timesteps, s = 0.008):
|
|||||||
alphas_cumprod = torch.cos(((x / timesteps) + s) / (1 + s) * torch.pi * 0.5) ** 2
|
alphas_cumprod = torch.cos(((x / timesteps) + s) / (1 + s) * torch.pi * 0.5) ** 2
|
||||||
alphas_cumprod = alphas_cumprod / alphas_cumprod[0]
|
alphas_cumprod = alphas_cumprod / alphas_cumprod[0]
|
||||||
betas = 1 - (alphas_cumprod[1:] / alphas_cumprod[:-1])
|
betas = 1 - (alphas_cumprod[1:] / alphas_cumprod[:-1])
|
||||||
return torch.clip(betas, 0, 0.9999)
|
return torch.clip(betas, 0, 0.999)
|
||||||
|
|
||||||
class GaussianDiffusion(nn.Module):
|
class GaussianDiffusion(nn.Module):
|
||||||
def __init__(
|
def __init__(
|
||||||
@@ -333,6 +342,8 @@ class GaussianDiffusion(nn.Module):
|
|||||||
loss_type = 'l1'
|
loss_type = 'l1'
|
||||||
):
|
):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
assert not (type(self) == GaussianDiffusion and denoise_fn.channels != denoise_fn.out_dim)
|
||||||
|
|
||||||
self.channels = channels
|
self.channels = channels
|
||||||
self.image_size = image_size
|
self.image_size = image_size
|
||||||
self.denoise_fn = denoise_fn
|
self.denoise_fn = denoise_fn
|
||||||
@@ -377,12 +388,6 @@ class GaussianDiffusion(nn.Module):
|
|||||||
register_buffer('posterior_mean_coef1', betas * torch.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod))
|
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))
|
register_buffer('posterior_mean_coef2', (1. - alphas_cumprod_prev) * torch.sqrt(alphas) / (1. - alphas_cumprod))
|
||||||
|
|
||||||
def q_mean_variance(self, x_start, t):
|
|
||||||
mean = extract(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start
|
|
||||||
variance = extract(1. - self.alphas_cumprod, t, x_start.shape)
|
|
||||||
log_variance = extract(self.log_one_minus_alphas_cumprod, t, x_start.shape)
|
|
||||||
return mean, variance, log_variance
|
|
||||||
|
|
||||||
def predict_start_from_noise(self, x_t, t, noise):
|
def predict_start_from_noise(self, x_t, t, noise):
|
||||||
return (
|
return (
|
||||||
extract(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
|
extract(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
|
||||||
@@ -457,6 +462,15 @@ class GaussianDiffusion(nn.Module):
|
|||||||
extract(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise
|
extract(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def loss_fn(self):
|
||||||
|
if self.loss_type == 'l1':
|
||||||
|
return F.l1_loss
|
||||||
|
elif self.loss_type == 'l2':
|
||||||
|
return F.mse_loss
|
||||||
|
else:
|
||||||
|
raise ValueError(f'invalid loss type {self.loss_type}')
|
||||||
|
|
||||||
def p_losses(self, x_start, t, noise = None):
|
def p_losses(self, x_start, t, noise = None):
|
||||||
b, c, h, w = x_start.shape
|
b, c, h, w = x_start.shape
|
||||||
noise = default(noise, lambda: torch.randn_like(x_start))
|
noise = default(noise, lambda: torch.randn_like(x_start))
|
||||||
@@ -464,13 +478,7 @@ class GaussianDiffusion(nn.Module):
|
|||||||
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
|
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
|
||||||
x_recon = self.denoise_fn(x_noisy, t)
|
x_recon = self.denoise_fn(x_noisy, t)
|
||||||
|
|
||||||
if self.loss_type == 'l1':
|
loss = self.loss_fn(noise, x_recon)
|
||||||
loss = (noise - x_recon).abs().mean()
|
|
||||||
elif self.loss_type == 'l2':
|
|
||||||
loss = F.mse_loss(noise, x_recon)
|
|
||||||
else:
|
|
||||||
raise NotImplementedError()
|
|
||||||
|
|
||||||
return loss
|
return loss
|
||||||
|
|
||||||
def forward(self, x, *args, **kwargs):
|
def forward(self, x, *args, **kwargs):
|
||||||
@@ -493,7 +501,7 @@ class Dataset(data.Dataset):
|
|||||||
transforms.RandomHorizontalFlip(),
|
transforms.RandomHorizontalFlip(),
|
||||||
transforms.CenterCrop(image_size),
|
transforms.CenterCrop(image_size),
|
||||||
transforms.ToTensor(),
|
transforms.ToTensor(),
|
||||||
transforms.Lambda(lambda t: (t * 2) - 1)
|
transforms.Lambda(normalize_to_neg_one_to_one)
|
||||||
])
|
])
|
||||||
|
|
||||||
def __len__(self):
|
def __len__(self):
|
||||||
@@ -597,11 +605,13 @@ class Trainer(object):
|
|||||||
self.step_ema()
|
self.step_ema()
|
||||||
|
|
||||||
if self.step != 0 and self.step % self.save_and_sample_every == 0:
|
if self.step != 0 and self.step % self.save_and_sample_every == 0:
|
||||||
|
self.ema_model.eval()
|
||||||
|
|
||||||
milestone = self.step // self.save_and_sample_every
|
milestone = self.step // self.save_and_sample_every
|
||||||
batches = num_to_groups(36, self.batch_size)
|
batches = num_to_groups(36, self.batch_size)
|
||||||
all_images_list = list(map(lambda n: self.ema_model.sample(batch_size=n), batches))
|
all_images_list = list(map(lambda n: self.ema_model.sample(batch_size=n), batches))
|
||||||
all_images = torch.cat(all_images_list, dim=0)
|
all_images = torch.cat(all_images_list, dim=0)
|
||||||
all_images = (all_images + 1) * 0.5
|
all_images = unnormalize_to_zero_to_one(all_images)
|
||||||
utils.save_image(all_images, str(self.results_folder / f'sample-{milestone}.png'), nrow = 6)
|
utils.save_image(all_images, str(self.results_folder / f'sample-{milestone}.png'), nrow = 6)
|
||||||
self.save(milestone)
|
self.save(milestone)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,132 @@
|
|||||||
|
import torch
|
||||||
|
from math import pi, sqrt, log as ln
|
||||||
|
from inspect import isfunction
|
||||||
|
from torch import nn, einsum
|
||||||
|
from einops import rearrange
|
||||||
|
|
||||||
|
from denoising_diffusion_pytorch.denoising_diffusion_pytorch import GaussianDiffusion, extract, unnormalize_to_zero_to_one
|
||||||
|
|
||||||
|
# constants
|
||||||
|
|
||||||
|
NAT = 1. / ln(2)
|
||||||
|
|
||||||
|
# helper functions
|
||||||
|
|
||||||
|
def exists(x):
|
||||||
|
return x is not None
|
||||||
|
|
||||||
|
def default(val, d):
|
||||||
|
if exists(val):
|
||||||
|
return val
|
||||||
|
return d() if isfunction(d) else d
|
||||||
|
|
||||||
|
# tensor helpers
|
||||||
|
|
||||||
|
def log(t, eps = 1e-12):
|
||||||
|
return torch.log(t.clamp(min = eps))
|
||||||
|
|
||||||
|
def meanflat(x):
|
||||||
|
return x.mean(dim = tuple(range(1, len(x.shape))))
|
||||||
|
|
||||||
|
def normal_kl(mean1, logvar1, mean2, logvar2):
|
||||||
|
"""
|
||||||
|
KL divergence between normal distributions parameterized by mean and log-variance.
|
||||||
|
"""
|
||||||
|
return 0.5 * (-1.0 + logvar2 - logvar1 + torch.exp(logvar1 - logvar2) + ((mean1 - mean2) ** 2) * torch.exp(-logvar2))
|
||||||
|
|
||||||
|
def approx_standard_normal_cdf(x):
|
||||||
|
return 0.5 * (1.0 + torch.tanh(sqrt(2.0 / pi) * (x + 0.044715 * (x ** 3))))
|
||||||
|
|
||||||
|
def discretized_gaussian_log_likelihood(x, *, means, log_scales, thres = 0.999):
|
||||||
|
assert x.shape == means.shape == log_scales.shape
|
||||||
|
|
||||||
|
centered_x = x - means
|
||||||
|
inv_stdv = torch.exp(-log_scales)
|
||||||
|
plus_in = inv_stdv * (centered_x + 1. / 255.)
|
||||||
|
cdf_plus = approx_standard_normal_cdf(plus_in)
|
||||||
|
min_in = inv_stdv * (centered_x - 1. / 255.)
|
||||||
|
cdf_min = approx_standard_normal_cdf(min_in)
|
||||||
|
log_cdf_plus = log(cdf_plus)
|
||||||
|
log_one_minus_cdf_min = log(1. - cdf_min)
|
||||||
|
cdf_delta = cdf_plus - cdf_min
|
||||||
|
|
||||||
|
log_probs = torch.where(x < -thres,
|
||||||
|
log_cdf_plus,
|
||||||
|
torch.where(x > thres,
|
||||||
|
log_one_minus_cdf_min,
|
||||||
|
log(cdf_delta)))
|
||||||
|
|
||||||
|
return log_probs
|
||||||
|
|
||||||
|
# https://arxiv.org/abs/2102.09672
|
||||||
|
|
||||||
|
# i thought the results were questionable, if one were to focus only on FID
|
||||||
|
# but may as well get this in here for others to try, as GLIDE is using it (and DALL-E2 first stage of cascade)
|
||||||
|
# gaussian diffusion for learned variance + hybrid eps simple + vb loss
|
||||||
|
|
||||||
|
class LearnedGaussianDiffusion(GaussianDiffusion):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
denoise_fn,
|
||||||
|
vb_loss_weight = 0.001, # lambda was 0.001 in the paper
|
||||||
|
*args,
|
||||||
|
**kwargs
|
||||||
|
):
|
||||||
|
super().__init__(denoise_fn, *args, **kwargs)
|
||||||
|
assert denoise_fn.out_dim == (denoise_fn.channels * 2), 'dimension out of unet must be twice the number of channels for learned variance - you can also set the `learned_variance` keyword argument on the Unet to be `True`'
|
||||||
|
self.vb_loss_weight = vb_loss_weight
|
||||||
|
|
||||||
|
def p_mean_variance(self, *, x, t, clip_denoised, model_output = None):
|
||||||
|
model_output = default(model_output, lambda: self.denoise_fn(x, t))
|
||||||
|
pred_noise, var_interp_frac_unnormalized = model_output.chunk(2, dim = 1)
|
||||||
|
|
||||||
|
min_log = extract(self.posterior_log_variance_clipped, t, x.shape)
|
||||||
|
max_log = extract(torch.log(self.betas), t, x.shape)
|
||||||
|
var_interp_frac = unnormalize_to_zero_to_one(var_interp_frac_unnormalized)
|
||||||
|
|
||||||
|
model_log_variance = var_interp_frac * max_log + (1 - var_interp_frac) * min_log
|
||||||
|
model_variance = model_log_variance.exp()
|
||||||
|
|
||||||
|
x_start = self.predict_start_from_noise(x, t, pred_noise)
|
||||||
|
|
||||||
|
if clip_denoised:
|
||||||
|
x_start.clamp_(-1., 1.)
|
||||||
|
|
||||||
|
model_mean, _, _ = self.q_posterior(x_start, x, t)
|
||||||
|
|
||||||
|
return model_mean, model_variance, model_log_variance
|
||||||
|
|
||||||
|
def p_losses(self, x_start, t, noise = None, clip_denoised = False):
|
||||||
|
noise = default(noise, lambda: torch.randn_like(x_start))
|
||||||
|
x_t = self.q_sample(x_start = x_start, t = t, noise = noise)
|
||||||
|
|
||||||
|
# model output
|
||||||
|
|
||||||
|
model_output = self.denoise_fn(x_t, t)
|
||||||
|
|
||||||
|
# calculating kl loss for learned variance (interpolation)
|
||||||
|
|
||||||
|
true_mean, _, true_log_variance_clipped = self.q_posterior(x_start = x_start, x_t = x_t, t = t)
|
||||||
|
model_mean, _, model_log_variance = self.p_mean_variance(x = x_t, t = t, clip_denoised = clip_denoised, model_output = model_output)
|
||||||
|
|
||||||
|
# kl loss with detached model predicted mean, for stability reasons as in paper
|
||||||
|
|
||||||
|
detached_model_mean = model_mean.detach()
|
||||||
|
|
||||||
|
kl = normal_kl(true_mean, true_log_variance_clipped, detached_model_mean, model_log_variance)
|
||||||
|
kl = meanflat(kl) * NAT
|
||||||
|
|
||||||
|
decoder_nll = -discretized_gaussian_log_likelihood(x_start, means = detached_model_mean, log_scales = 0.5 * model_log_variance)
|
||||||
|
decoder_nll = meanflat(decoder_nll) * NAT
|
||||||
|
|
||||||
|
# at the first timestep return the decoder NLL, otherwise return KL(q(x_{t-1}|x_t,x_0) || p(x_{t-1}|x_t))
|
||||||
|
|
||||||
|
vb_losses = torch.where(t == 0, decoder_nll, kl)
|
||||||
|
|
||||||
|
# simple loss - predicting noise, x0, or x_prev
|
||||||
|
|
||||||
|
pred_noise, _ = model_output.chunk(2, dim = 1)
|
||||||
|
|
||||||
|
simple_losses = self.loss_fn(pred_noise, noise)
|
||||||
|
|
||||||
|
return simple_losses + vb_losses.mean() * self.vb_loss_weight
|
||||||
@@ -3,7 +3,7 @@ from setuptools import setup, find_packages
|
|||||||
setup(
|
setup(
|
||||||
name = 'denoising-diffusion-pytorch',
|
name = 'denoising-diffusion-pytorch',
|
||||||
packages = find_packages(),
|
packages = find_packages(),
|
||||||
version = '0.12.1',
|
version = '0.14.3',
|
||||||
license='MIT',
|
license='MIT',
|
||||||
description = 'Denoising Diffusion Probabilistic Models - Pytorch',
|
description = 'Denoising Diffusion Probabilistic Models - Pytorch',
|
||||||
author = 'Phil Wang',
|
author = 'Phil Wang',
|
||||||
|
|||||||
Reference in New Issue
Block a user