mirror of
https://github.com/wassname/denoising-diffusion-pytorch.git
synced 2026-09-12 12:22:11 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8b30be8042 | ||
|
|
f2f3994b92 | ||
|
|
8ec4ea56a5 | ||
|
|
99cf9b5b96 | ||
|
|
ecc6f30901 | ||
|
|
f900f40f14 | ||
|
|
479f60c178 |
@@ -6,6 +6,8 @@ Implementation of <a href="https://arxiv.org/abs/2006.11239">Denoising Diffusion
|
|||||||
|
|
||||||
This implementation was transcribed from the official Tensorflow version <a href="https://github.com/hojonathanho/diffusion">here</a>
|
This implementation was transcribed from the official Tensorflow version <a href="https://github.com/hojonathanho/diffusion">here</a>
|
||||||
|
|
||||||
|
Youtube AI Educators - <a href="https://www.youtube.com/watch?v=W-O7AZNzbzQ">Yannic Kilcher</a> | <a href="https://www.youtube.com/watch?v=344w5h24-h8">AI Coffeebreak with Letitia</a> | <a href="https://www.youtube.com/watch?v=HoKDTa5jHvg">Outlier</a>
|
||||||
|
|
||||||
<a href="https://huggingface.co/blog/annotated-diffusion">Annotated code</a> by Research Scientists / Engineers from <a href="https://huggingface.co/">🤗 Huggingface</a>
|
<a href="https://huggingface.co/blog/annotated-diffusion">Annotated code</a> by Research Scientists / Engineers from <a href="https://huggingface.co/">🤗 Huggingface</a>
|
||||||
|
|
||||||
<img src="./sample.png" width="500px"><img>
|
<img src="./sample.png" width="500px"><img>
|
||||||
@@ -121,3 +123,13 @@ Samples and model checkpoints will be logged to `./results` periodically
|
|||||||
url = {https://openreview.net/forum?id=2LdBqxc1Yv}
|
url = {https://openreview.net/forum?id=2LdBqxc1Yv}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
```bibtex
|
||||||
|
@article{Choi2022PerceptionPT,
|
||||||
|
title = {Perception Prioritized Training of Diffusion Models},
|
||||||
|
author = {Jooyoung Choi and Jungbeom Lee and Chaehun Shin and Sungwon Kim and Hyunwoo J. Kim and Sung-Hoon Yoon},
|
||||||
|
journal = {ArXiv},
|
||||||
|
year = {2022},
|
||||||
|
volume = {abs/2204.00227}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import torch.nn.functional as F
|
|||||||
from torch.special import expm1
|
from torch.special import expm1
|
||||||
|
|
||||||
from tqdm import tqdm
|
from tqdm import tqdm
|
||||||
from einops import rearrange, repeat
|
from einops import rearrange, repeat, reduce
|
||||||
from einops.layers.torch import Rearrange
|
from einops.layers.torch import Rearrange
|
||||||
|
|
||||||
# helpers
|
# helpers
|
||||||
@@ -66,7 +66,7 @@ def beta_linear_log_snr(t):
|
|||||||
return -log(expm1(1e-4 + 10 * (t ** 2)))
|
return -log(expm1(1e-4 + 10 * (t ** 2)))
|
||||||
|
|
||||||
def alpha_cosine_log_snr(t, s = 0.008):
|
def alpha_cosine_log_snr(t, s = 0.008):
|
||||||
return -log((torch.cos((t + s) / (1 + s) * torch.pi * 0.5) ** -2) - 1)
|
return -log((torch.cos((t + s) / (1 + s) * torch.pi * 0.5) ** -2) - 1, eps = 1e-5)
|
||||||
|
|
||||||
class learned_noise_schedule(nn.Module):
|
class learned_noise_schedule(nn.Module):
|
||||||
""" described in section H and then I.2 of the supplementary material for variational ddpm paper """
|
""" described in section H and then I.2 of the supplementary material for variational ddpm paper """
|
||||||
@@ -120,7 +120,9 @@ class ContinuousTimeGaussianDiffusion(nn.Module):
|
|||||||
num_sample_steps = 500,
|
num_sample_steps = 500,
|
||||||
clip_sample_denoised = True,
|
clip_sample_denoised = True,
|
||||||
learned_schedule_net_hidden_dim = 1024,
|
learned_schedule_net_hidden_dim = 1024,
|
||||||
learned_noise_schedule_frac_gradient = 1. # between 0 and 1, determines what percentage of gradients go back, so one can update the learned noise schedule more slowly
|
learned_noise_schedule_frac_gradient = 1., # between 0 and 1, determines what percentage of gradients go back, so one can update the learned noise schedule more slowly
|
||||||
|
p2_loss_weight_gamma = 0., # p2 loss weight, from https://arxiv.org/abs/2204.00227 - 0 is equivalent to weight of 1 across time
|
||||||
|
p2_loss_weight_k = 1
|
||||||
):
|
):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
assert not denoise_fn.sinusoidal_cond_mlp
|
assert not denoise_fn.sinusoidal_cond_mlp
|
||||||
@@ -157,6 +159,14 @@ class ContinuousTimeGaussianDiffusion(nn.Module):
|
|||||||
self.num_sample_steps = num_sample_steps
|
self.num_sample_steps = num_sample_steps
|
||||||
self.clip_sample_denoised = clip_sample_denoised
|
self.clip_sample_denoised = clip_sample_denoised
|
||||||
|
|
||||||
|
# p2 loss weight
|
||||||
|
# proposed https://arxiv.org/abs/2204.00227
|
||||||
|
|
||||||
|
assert p2_loss_weight_gamma <= 2, 'in paper, they noticed any gamma greater than 2 is harmful'
|
||||||
|
|
||||||
|
self.p2_loss_weight_gamma = p2_loss_weight_gamma # recommended to be 0.5 or 1
|
||||||
|
self.p2_loss_weight_k = p2_loss_weight_k
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def device(self):
|
def device(self):
|
||||||
return next(self.denoise_fn.parameters()).device
|
return next(self.denoise_fn.parameters()).device
|
||||||
@@ -255,9 +265,17 @@ class ContinuousTimeGaussianDiffusion(nn.Module):
|
|||||||
noise = default(noise, lambda: torch.randn_like(x_start))
|
noise = default(noise, lambda: torch.randn_like(x_start))
|
||||||
|
|
||||||
x, log_snr = self.q_sample(x_start = x_start, times = times, noise = noise)
|
x, log_snr = self.q_sample(x_start = x_start, times = times, noise = noise)
|
||||||
|
|
||||||
model_out = self.denoise_fn(x, log_snr)
|
model_out = self.denoise_fn(x, log_snr)
|
||||||
return self.loss_fn(model_out, noise)
|
|
||||||
|
losses = self.loss_fn(model_out, noise, reduction = 'none')
|
||||||
|
losses = reduce(losses, 'b ... -> b', 'mean')
|
||||||
|
|
||||||
|
if self.p2_loss_weight_gamma >= 0:
|
||||||
|
# following eq 8. in https://arxiv.org/abs/2204.00227
|
||||||
|
loss_weight = (self.p2_loss_weight_k + log_snr.exp()) ** -self.p2_loss_weight_gamma
|
||||||
|
losses = losses * loss_weight
|
||||||
|
|
||||||
|
return losses.mean()
|
||||||
|
|
||||||
def forward(self, img, *args, **kwargs):
|
def forward(self, img, *args, **kwargs):
|
||||||
b, c, h, w, device, img_size, = *img.shape, img.device, self.image_size
|
b, c, h, w, device, img_size, = *img.shape, img.device, self.image_size
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ from inspect import isfunction
|
|||||||
from functools import partial
|
from functools import partial
|
||||||
|
|
||||||
from torch.utils import data
|
from torch.utils import data
|
||||||
|
from multiprocessing import cpu_count
|
||||||
from torch.cuda.amp import autocast, GradScaler
|
from torch.cuda.amp import autocast, GradScaler
|
||||||
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -15,7 +16,7 @@ from torchvision import transforms, utils
|
|||||||
from PIL import Image
|
from PIL import Image
|
||||||
|
|
||||||
from tqdm import tqdm
|
from tqdm import tqdm
|
||||||
from einops import rearrange
|
from einops import rearrange, reduce
|
||||||
from einops.layers.torch import Rearrange
|
from einops.layers.torch import Rearrange
|
||||||
|
|
||||||
# helpers functions
|
# helpers functions
|
||||||
@@ -366,7 +367,9 @@ class GaussianDiffusion(nn.Module):
|
|||||||
timesteps = 1000,
|
timesteps = 1000,
|
||||||
loss_type = 'l1',
|
loss_type = 'l1',
|
||||||
objective = 'pred_noise',
|
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__()
|
super().__init__()
|
||||||
assert not (type(self) == GaussianDiffusion and denoise_fn.channels != denoise_fn.out_dim)
|
assert not (type(self) == GaussianDiffusion and denoise_fn.channels != denoise_fn.out_dim)
|
||||||
@@ -421,6 +424,10 @@ 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))
|
||||||
|
|
||||||
|
# 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):
|
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 -
|
||||||
@@ -527,8 +534,11 @@ class GaussianDiffusion(nn.Module):
|
|||||||
else:
|
else:
|
||||||
raise ValueError(f'unknown objective {self.objective}')
|
raise ValueError(f'unknown objective {self.objective}')
|
||||||
|
|
||||||
loss = self.loss_fn(model_out, target)
|
loss = self.loss_fn(model_out, target, reduction = 'none')
|
||||||
return loss
|
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):
|
def forward(self, img, *args, **kwargs):
|
||||||
b, c, h, w, device, img_size, = *img.shape, img.device, self.image_size
|
b, c, h, w, device, img_size, = *img.shape, img.device, self.image_size
|
||||||
@@ -541,7 +551,7 @@ class GaussianDiffusion(nn.Module):
|
|||||||
# dataset classes
|
# dataset classes
|
||||||
|
|
||||||
class Dataset(data.Dataset):
|
class Dataset(data.Dataset):
|
||||||
def __init__(self, folder, image_size, exts = ['jpg', 'jpeg', 'png']):
|
def __init__(self, folder, image_size, exts = ['jpg', 'jpeg', 'png'], augment_horizontal_flip = False):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.folder = folder
|
self.folder = folder
|
||||||
self.image_size = image_size
|
self.image_size = image_size
|
||||||
@@ -549,7 +559,7 @@ class Dataset(data.Dataset):
|
|||||||
|
|
||||||
self.transform = transforms.Compose([
|
self.transform = transforms.Compose([
|
||||||
transforms.Resize(image_size),
|
transforms.Resize(image_size),
|
||||||
transforms.RandomHorizontalFlip(),
|
transforms.RandomHorizontalFlip() if augment_horizontal_flip else nn.Identity(),
|
||||||
transforms.CenterCrop(image_size),
|
transforms.CenterCrop(image_size),
|
||||||
transforms.ToTensor()
|
transforms.ToTensor()
|
||||||
])
|
])
|
||||||
@@ -580,7 +590,8 @@ class Trainer(object):
|
|||||||
step_start_ema = 2000,
|
step_start_ema = 2000,
|
||||||
update_ema_every = 10,
|
update_ema_every = 10,
|
||||||
save_and_sample_every = 1000,
|
save_and_sample_every = 1000,
|
||||||
results_folder = './results'
|
results_folder = './results',
|
||||||
|
augment_horizontal_flip = True
|
||||||
):
|
):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.model = diffusion_model
|
self.model = diffusion_model
|
||||||
@@ -596,8 +607,8 @@ class Trainer(object):
|
|||||||
self.gradient_accumulate_every = gradient_accumulate_every
|
self.gradient_accumulate_every = gradient_accumulate_every
|
||||||
self.train_num_steps = train_num_steps
|
self.train_num_steps = train_num_steps
|
||||||
|
|
||||||
self.ds = Dataset(folder, image_size)
|
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.opt = Adam(diffusion_model.parameters(), lr=train_lr)
|
||||||
|
|
||||||
self.step = 0
|
self.step = 0
|
||||||
|
|||||||
@@ -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.17.7',
|
version = '0.18.4',
|
||||||
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