mirror of
https://github.com/wassname/denoising-diffusion-pytorch.git
synced 2026-09-10 12:01:08 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ab4c51c72c | ||
|
|
f5916111f8 | ||
|
|
ad9e303ff3 | ||
|
|
ae42f48f6a | ||
|
|
5989f4c77e | ||
|
|
2082046888 | ||
|
|
3c5b7e2d56 | ||
|
|
d4ce9f6c38 | ||
|
|
ff451f697e |
@@ -1,3 +1,6 @@
|
|||||||
|
# Generation results
|
||||||
|
results/
|
||||||
|
|
||||||
# Byte-compiled / optimized / DLL files
|
# Byte-compiled / optimized / DLL files
|
||||||
__pycache__/
|
__pycache__/
|
||||||
*.py[cod]
|
*.py[cod]
|
||||||
|
|||||||
@@ -27,8 +27,9 @@ model = Unet(
|
|||||||
|
|
||||||
diffusion = GaussianDiffusion(
|
diffusion = GaussianDiffusion(
|
||||||
model,
|
model,
|
||||||
|
image_size = 128,
|
||||||
timesteps = 1000, # number of steps
|
timesteps = 1000, # number of steps
|
||||||
loss_type = 'l1' # L1 or L2
|
loss_type = 'l1' # L1 or L2
|
||||||
)
|
)
|
||||||
|
|
||||||
training_images = torch.randn(8, 3, 128, 128)
|
training_images = torch.randn(8, 3, 128, 128)
|
||||||
@@ -36,7 +37,7 @@ loss = diffusion(training_images)
|
|||||||
loss.backward()
|
loss.backward()
|
||||||
# after a lot of training
|
# after a lot of training
|
||||||
|
|
||||||
sampled_images = diffusion.sample(128, batch_size = 4)
|
sampled_images = diffusion.sample(batch_size = 4)
|
||||||
sampled_images.shape # (4, 3, 128, 128)
|
sampled_images.shape # (4, 3, 128, 128)
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -52,6 +53,7 @@ model = Unet(
|
|||||||
|
|
||||||
diffusion = GaussianDiffusion(
|
diffusion = GaussianDiffusion(
|
||||||
model,
|
model,
|
||||||
|
image_size = 128,
|
||||||
timesteps = 1000, # number of steps
|
timesteps = 1000, # number of steps
|
||||||
loss_type = 'l1' # L1 or L2
|
loss_type = 'l1' # L1 or L2
|
||||||
).cuda()
|
).cuda()
|
||||||
@@ -59,10 +61,9 @@ diffusion = GaussianDiffusion(
|
|||||||
trainer = Trainer(
|
trainer = Trainer(
|
||||||
diffusion,
|
diffusion,
|
||||||
'path/to/your/images',
|
'path/to/your/images',
|
||||||
image_size = 128,
|
|
||||||
train_batch_size = 32,
|
train_batch_size = 32,
|
||||||
train_lr = 2e-5,
|
train_lr = 2e-5,
|
||||||
train_num_steps = 100000, # total training steps
|
train_num_steps = 700000, # total training steps
|
||||||
gradient_accumulate_every = 2, # gradient accumulation steps
|
gradient_accumulate_every = 2, # gradient accumulation steps
|
||||||
ema_decay = 0.995, # exponential moving average decay
|
ema_decay = 0.995, # exponential moving average decay
|
||||||
fp16 = True # turn on mixed precision training with apex
|
fp16 = True # turn on mixed precision training with apex
|
||||||
@@ -71,27 +72,28 @@ trainer = Trainer(
|
|||||||
trainer.train()
|
trainer.train()
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Samples and model checkpoints will be logged to `./results` periodically
|
||||||
|
|
||||||
## Citations
|
## Citations
|
||||||
|
|
||||||
```bibtex
|
```bibtex
|
||||||
@misc{ho2020denoising,
|
@misc{ho2020denoising,
|
||||||
title={Denoising Diffusion Probabilistic Models},
|
title = {Denoising Diffusion Probabilistic Models},
|
||||||
author={Jonathan Ho and Ajay Jain and Pieter Abbeel},
|
author = {Jonathan Ho and Ajay Jain and Pieter Abbeel},
|
||||||
year={2020},
|
year = {2020},
|
||||||
eprint={2006.11239},
|
eprint = {2006.11239},
|
||||||
archivePrefix={arXiv},
|
archivePrefix = {arXiv},
|
||||||
primaryClass={cs.LG}
|
primaryClass = {cs.LG}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
```bibtex
|
```bibtex
|
||||||
@inproceedings{
|
@inproceedings{anonymous2021improved,
|
||||||
anonymous2021improved,
|
title = {Improved Denoising Diffusion Probabilistic Models},
|
||||||
title={Improved Denoising Diffusion Probabilistic Models},
|
author = {Anonymous},
|
||||||
author={Anonymous},
|
booktitle = {Submitted to International Conference on Learning Representations},
|
||||||
booktitle={Submitted to International Conference on Learning Representations},
|
year = {2021},
|
||||||
year={2021},
|
url = {https://openreview.net/forum?id=-NEXDKk8gZ},
|
||||||
url={https://openreview.net/forum?id=-NEXDKk8gZ},
|
note = {under review}
|
||||||
note={under review}
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -28,6 +28,9 @@ SAVE_AND_SAMPLE_EVERY = 1000
|
|||||||
UPDATE_EMA_EVERY = 10
|
UPDATE_EMA_EVERY = 10
|
||||||
EXTS = ['jpg', 'jpeg', 'png']
|
EXTS = ['jpg', 'jpeg', 'png']
|
||||||
|
|
||||||
|
RESULTS_FOLDER = Path('./results')
|
||||||
|
RESULTS_FOLDER.mkdir(exist_ok = True)
|
||||||
|
|
||||||
# helpers functions
|
# helpers functions
|
||||||
|
|
||||||
def exists(x):
|
def exists(x):
|
||||||
@@ -178,9 +181,18 @@ class LinearAttention(nn.Module):
|
|||||||
# model
|
# model
|
||||||
|
|
||||||
class Unet(nn.Module):
|
class Unet(nn.Module):
|
||||||
def __init__(self, dim, out_dim = None, dim_mults=(1, 2, 4, 8), groups = 8):
|
def __init__(
|
||||||
|
self,
|
||||||
|
dim,
|
||||||
|
out_dim = None,
|
||||||
|
dim_mults=(1, 2, 4, 8),
|
||||||
|
groups = 8,
|
||||||
|
channels = 3
|
||||||
|
):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
dims = [3, *map(lambda m: dim * m, dim_mults)]
|
self.channels = channels
|
||||||
|
|
||||||
|
dims = [channels, *map(lambda m: dim * m, dim_mults)]
|
||||||
in_out = list(zip(dims[:-1], dims[1:]))
|
in_out = list(zip(dims[:-1], dims[1:]))
|
||||||
|
|
||||||
self.time_pos_emb = SinusoidalPosEmb(dim)
|
self.time_pos_emb = SinusoidalPosEmb(dim)
|
||||||
@@ -219,7 +231,7 @@ 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, 3)
|
out_dim = default(out_dim, channels)
|
||||||
self.final_conv = nn.Sequential(
|
self.final_conv = nn.Sequential(
|
||||||
Block(dim, dim),
|
Block(dim, dim),
|
||||||
nn.Conv2d(dim, out_dim, 1)
|
nn.Conv2d(dim, out_dim, 1)
|
||||||
@@ -276,8 +288,19 @@ def cosine_beta_schedule(timesteps, s = 0.008):
|
|||||||
return np.clip(betas, a_min = 0, a_max = 0.999)
|
return np.clip(betas, a_min = 0, a_max = 0.999)
|
||||||
|
|
||||||
class GaussianDiffusion(nn.Module):
|
class GaussianDiffusion(nn.Module):
|
||||||
def __init__(self, denoise_fn, timesteps=1000, loss_type='l1', betas = None):
|
def __init__(
|
||||||
|
self,
|
||||||
|
denoise_fn,
|
||||||
|
*,
|
||||||
|
image_size,
|
||||||
|
channels = 3,
|
||||||
|
timesteps = 1000,
|
||||||
|
loss_type = 'l1',
|
||||||
|
betas = None
|
||||||
|
):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
self.channels = channels
|
||||||
|
self.image_size = image_size
|
||||||
self.denoise_fn = denoise_fn
|
self.denoise_fn = denoise_fn
|
||||||
|
|
||||||
if exists(betas):
|
if exists(betas):
|
||||||
@@ -368,8 +391,10 @@ class GaussianDiffusion(nn.Module):
|
|||||||
return img
|
return img
|
||||||
|
|
||||||
@torch.no_grad()
|
@torch.no_grad()
|
||||||
def sample(self, image_size, batch_size = 16):
|
def sample(self, batch_size = 16):
|
||||||
return self.p_sample_loop((batch_size, 3, image_size, image_size))
|
image_size = self.image_size
|
||||||
|
channels = self.channels
|
||||||
|
return self.p_sample_loop((batch_size, channels, image_size, image_size))
|
||||||
|
|
||||||
@torch.no_grad()
|
@torch.no_grad()
|
||||||
def interpolate(self, x1, x2, t = None, lam = 0.5):
|
def interpolate(self, x1, x2, t = None, lam = 0.5):
|
||||||
@@ -412,7 +437,8 @@ class GaussianDiffusion(nn.Module):
|
|||||||
return loss
|
return loss
|
||||||
|
|
||||||
def forward(self, x, *args, **kwargs):
|
def forward(self, x, *args, **kwargs):
|
||||||
b, *_, device = *x.shape, x.device
|
b, c, h, w, device, img_size, = *x.shape, x.device, self.image_size
|
||||||
|
assert h == img_size and w == img_size, f'height and width of image must be {img_size}'
|
||||||
t = torch.randint(0, self.num_timesteps, (b,), device=device).long()
|
t = torch.randint(0, self.num_timesteps, (b,), device=device).long()
|
||||||
return self.p_losses(x, t, *args, **kwargs)
|
return self.p_losses(x, t, *args, **kwargs)
|
||||||
|
|
||||||
@@ -429,7 +455,8 @@ class Dataset(data.Dataset):
|
|||||||
transforms.Resize(image_size),
|
transforms.Resize(image_size),
|
||||||
transforms.RandomHorizontalFlip(),
|
transforms.RandomHorizontalFlip(),
|
||||||
transforms.CenterCrop(image_size),
|
transforms.CenterCrop(image_size),
|
||||||
transforms.ToTensor()
|
transforms.ToTensor(),
|
||||||
|
transforms.Lambda(lambda t: (t * 2) - 1)
|
||||||
])
|
])
|
||||||
|
|
||||||
def __len__(self):
|
def __len__(self):
|
||||||
@@ -464,7 +491,7 @@ class Trainer(object):
|
|||||||
self.step_start_ema = step_start_ema
|
self.step_start_ema = step_start_ema
|
||||||
|
|
||||||
self.batch_size = train_batch_size
|
self.batch_size = train_batch_size
|
||||||
self.image_size = image_size
|
self.image_size = diffusion_model.image_size
|
||||||
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
|
||||||
|
|
||||||
@@ -497,10 +524,10 @@ class Trainer(object):
|
|||||||
'model': self.model.state_dict(),
|
'model': self.model.state_dict(),
|
||||||
'ema': self.ema_model.state_dict()
|
'ema': self.ema_model.state_dict()
|
||||||
}
|
}
|
||||||
torch.save(data, f'./model-{milestone}.pt')
|
torch.save(data, str(RESULTS_FOLDER / f'model-{milestone}.pt'))
|
||||||
|
|
||||||
def load(self, milestone):
|
def load(self, milestone):
|
||||||
data = torch.load(f'./model-{milestone}.pt')
|
data = torch.load(str(RESULTS_FOLDER / f'model-{milestone}.pt'))
|
||||||
|
|
||||||
self.step = data['step']
|
self.step = data['step']
|
||||||
self.model.load_state_dict(data['model'])
|
self.model.load_state_dict(data['model'])
|
||||||
@@ -525,9 +552,10 @@ class Trainer(object):
|
|||||||
if self.step != 0 and self.step % SAVE_AND_SAMPLE_EVERY == 0:
|
if self.step != 0 and self.step % SAVE_AND_SAMPLE_EVERY == 0:
|
||||||
milestone = self.step // SAVE_AND_SAMPLE_EVERY
|
milestone = self.step // 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(self.image_size, 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)
|
||||||
utils.save_image(all_images, f'./sample-{milestone}.png', nrow=6)
|
all_images = (all_images * 0.5) + 1
|
||||||
|
utils.save_image(all_images, str(RESULTS_FOLDER / f'sample-{milestone}.png'), nrow = 6)
|
||||||
self.save(milestone)
|
self.save(milestone)
|
||||||
|
|
||||||
self.step += 1
|
self.step += 1
|
||||||
|
|||||||
BIN
Binary file not shown.
|
Before Width: | Height: | Size: 1.3 MiB After Width: | Height: | Size: 842 KiB |
@@ -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.5.0',
|
version = '0.6.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