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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# adopted from
|
| 2 |
+
# https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py
|
| 3 |
+
# and
|
| 4 |
+
# https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
|
| 5 |
+
# and
|
| 6 |
+
# https://github.com/openai/guided-diffusion/blob/0ba878e517b276c45d1195eb29f6f5f72659a05b/guided_diffusion/nn.py
|
| 7 |
+
#
|
| 8 |
+
# thanks!
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
import os
|
| 12 |
+
import math
|
| 13 |
+
import torch
|
| 14 |
+
import torch.nn as nn
|
| 15 |
+
import numpy as np
|
| 16 |
+
from einops import repeat
|
| 17 |
+
|
| 18 |
+
from ldm.util import instantiate_from_config
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def make_beta_schedule(schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
|
| 22 |
+
if schedule == "linear":
|
| 23 |
+
betas = (
|
| 24 |
+
torch.linspace(linear_start ** 0.5, linear_end ** 0.5, n_timestep, dtype=torch.float64) ** 2
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
elif schedule == "cosine":
|
| 28 |
+
timesteps = (
|
| 29 |
+
torch.arange(n_timestep + 1, dtype=torch.float64) / n_timestep + cosine_s
|
| 30 |
+
)
|
| 31 |
+
alphas = timesteps / (1 + cosine_s) * np.pi / 2
|
| 32 |
+
alphas = torch.cos(alphas).pow(2)
|
| 33 |
+
alphas = alphas / alphas[0]
|
| 34 |
+
betas = 1 - alphas[1:] / alphas[:-1]
|
| 35 |
+
betas = np.clip(betas, a_min=0, a_max=0.999)
|
| 36 |
+
|
| 37 |
+
elif schedule == "sqrt_linear":
|
| 38 |
+
betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64)
|
| 39 |
+
elif schedule == "sqrt":
|
| 40 |
+
betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64) ** 0.5
|
| 41 |
+
else:
|
| 42 |
+
raise ValueError(f"schedule '{schedule}' unknown.")
|
| 43 |
+
return betas.numpy()
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def make_ddim_timesteps(ddim_discr_method, num_ddim_timesteps, num_ddpm_timesteps, verbose=True):
|
| 47 |
+
if ddim_discr_method == 'uniform':
|
| 48 |
+
c = num_ddpm_timesteps // num_ddim_timesteps
|
| 49 |
+
ddim_timesteps = np.asarray(list(range(0, num_ddpm_timesteps, c)))
|
| 50 |
+
elif ddim_discr_method == 'quad':
|
| 51 |
+
ddim_timesteps = ((np.linspace(0, np.sqrt(num_ddpm_timesteps * .8), num_ddim_timesteps)) ** 2).astype(int)
|
| 52 |
+
else:
|
| 53 |
+
raise NotImplementedError(f'There is no ddim discretization method called "{ddim_discr_method}"')
|
| 54 |
+
|
| 55 |
+
# assert ddim_timesteps.shape[0] == num_ddim_timesteps
|
| 56 |
+
# add one to get the final alpha values right (the ones from first scale to data during sampling)
|
| 57 |
+
steps_out = ddim_timesteps + 1
|
| 58 |
+
if verbose:
|
| 59 |
+
print(f'Selected timesteps for ddim sampler: {steps_out}')
|
| 60 |
+
return steps_out
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def make_ddim_sampling_parameters(alphacums, ddim_timesteps, eta, verbose=True):
|
| 64 |
+
# select alphas for computing the variance schedule
|
| 65 |
+
alphas = alphacums[ddim_timesteps]
|
| 66 |
+
alphas_prev = np.asarray([alphacums[0]] + alphacums[ddim_timesteps[:-1]].tolist())
|
| 67 |
+
|
| 68 |
+
# according the the formula provided in https://arxiv.org/abs/2010.02502
|
| 69 |
+
sigmas = eta * np.sqrt((1 - alphas_prev) / (1 - alphas) * (1 - alphas / alphas_prev))
|
| 70 |
+
if verbose:
|
| 71 |
+
print(f'Selected alphas for ddim sampler: a_t: {alphas}; a_(t-1): {alphas_prev}')
|
| 72 |
+
print(f'For the chosen value of eta, which is {eta}, '
|
| 73 |
+
f'this results in the following sigma_t schedule for ddim sampler {sigmas}')
|
| 74 |
+
return sigmas, alphas, alphas_prev
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999):
|
| 78 |
+
"""
|
| 79 |
+
Create a beta schedule that discretizes the given alpha_t_bar function,
|
| 80 |
+
which defines the cumulative product of (1-beta) over time from t = [0,1].
|
| 81 |
+
:param num_diffusion_timesteps: the number of betas to produce.
|
| 82 |
+
:param alpha_bar: a lambda that takes an argument t from 0 to 1 and
|
| 83 |
+
produces the cumulative product of (1-beta) up to that
|
| 84 |
+
part of the diffusion process.
|
| 85 |
+
:param max_beta: the maximum beta to use; use values lower than 1 to
|
| 86 |
+
prevent singularities.
|
| 87 |
+
"""
|
| 88 |
+
betas = []
|
| 89 |
+
for i in range(num_diffusion_timesteps):
|
| 90 |
+
t1 = i / num_diffusion_timesteps
|
| 91 |
+
t2 = (i + 1) / num_diffusion_timesteps
|
| 92 |
+
betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta))
|
| 93 |
+
return np.array(betas)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def extract_into_tensor(a, t, x_shape):
|
| 97 |
+
b, *_ = t.shape
|
| 98 |
+
out = a.gather(-1, t)
|
| 99 |
+
return out.reshape(b, *((1,) * (len(x_shape) - 1)))
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def checkpoint(func, inputs, params, flag):
|
| 103 |
+
"""
|
| 104 |
+
Evaluate a function without caching intermediate activations, allowing for
|
| 105 |
+
reduced memory at the expense of extra compute in the backward pass.
|
| 106 |
+
:param func: the function to evaluate.
|
| 107 |
+
:param inputs: the argument sequence to pass to `func`.
|
| 108 |
+
:param params: a sequence of parameters `func` depends on but does not
|
| 109 |
+
explicitly take as arguments.
|
| 110 |
+
:param flag: if False, disable gradient checkpointing.
|
| 111 |
+
"""
|
| 112 |
+
if flag:
|
| 113 |
+
args = tuple(inputs) + tuple(params)
|
| 114 |
+
return CheckpointFunction.apply(func, len(inputs), *args)
|
| 115 |
+
else:
|
| 116 |
+
return func(*inputs)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class CheckpointFunction(torch.autograd.Function):
|
| 120 |
+
@staticmethod
|
| 121 |
+
def forward(ctx, run_function, length, *args):
|
| 122 |
+
ctx.run_function = run_function
|
| 123 |
+
ctx.input_tensors = list(args[:length])
|
| 124 |
+
ctx.input_params = list(args[length:])
|
| 125 |
+
|
| 126 |
+
with torch.no_grad():
|
| 127 |
+
output_tensors = ctx.run_function(*ctx.input_tensors)
|
| 128 |
+
return output_tensors
|
| 129 |
+
|
| 130 |
+
@staticmethod
|
| 131 |
+
def backward(ctx, *output_grads):
|
| 132 |
+
ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors]
|
| 133 |
+
with torch.enable_grad():
|
| 134 |
+
# Fixes a bug where the first op in run_function modifies the
|
| 135 |
+
# Tensor storage in place, which is not allowed for detach()'d
|
| 136 |
+
# Tensors.
|
| 137 |
+
shallow_copies = [x.view_as(x) for x in ctx.input_tensors]
|
| 138 |
+
output_tensors = ctx.run_function(*shallow_copies)
|
| 139 |
+
input_grads = torch.autograd.grad(
|
| 140 |
+
output_tensors,
|
| 141 |
+
ctx.input_tensors + ctx.input_params,
|
| 142 |
+
output_grads,
|
| 143 |
+
allow_unused=True,
|
| 144 |
+
)
|
| 145 |
+
del ctx.input_tensors
|
| 146 |
+
del ctx.input_params
|
| 147 |
+
del output_tensors
|
| 148 |
+
return (None, None) + input_grads
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False):
|
| 152 |
+
"""
|
| 153 |
+
Create sinusoidal timestep embeddings.
|
| 154 |
+
:param timesteps: a 1-D Tensor of N indices, one per batch element.
|
| 155 |
+
These may be fractional.
|
| 156 |
+
:param dim: the dimension of the output.
|
| 157 |
+
:param max_period: controls the minimum frequency of the embeddings.
|
| 158 |
+
:return: an [N x dim] Tensor of positional embeddings.
|
| 159 |
+
"""
|
| 160 |
+
if not repeat_only:
|
| 161 |
+
half = dim // 2
|
| 162 |
+
freqs = torch.exp(
|
| 163 |
+
-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
|
| 164 |
+
).to(device=timesteps.device)
|
| 165 |
+
args = timesteps[:, None].float() * freqs[None]
|
| 166 |
+
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
| 167 |
+
if dim % 2:
|
| 168 |
+
embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
|
| 169 |
+
else:
|
| 170 |
+
embedding = repeat(timesteps, 'b -> b d', d=dim)
|
| 171 |
+
return embedding
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def zero_module(module):
|
| 175 |
+
"""
|
| 176 |
+
Zero out the parameters of a module and return it.
|
| 177 |
+
"""
|
| 178 |
+
for p in module.parameters():
|
| 179 |
+
p.detach().zero_()
|
| 180 |
+
return module
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def scale_module(module, scale):
|
| 184 |
+
"""
|
| 185 |
+
Scale the parameters of a module and return it.
|
| 186 |
+
"""
|
| 187 |
+
for p in module.parameters():
|
| 188 |
+
p.detach().mul_(scale)
|
| 189 |
+
return module
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def mean_flat(tensor):
|
| 193 |
+
"""
|
| 194 |
+
Take the mean over all non-batch dimensions.
|
| 195 |
+
"""
|
| 196 |
+
return tensor.mean(dim=list(range(1, len(tensor.shape))))
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def normalization(channels):
|
| 200 |
+
"""
|
| 201 |
+
Make a standard normalization layer.
|
| 202 |
+
:param channels: number of input channels.
|
| 203 |
+
:return: an nn.Module for normalization.
|
| 204 |
+
"""
|
| 205 |
+
return GroupNorm32(32, channels)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
# PyTorch 1.7 has SiLU, but we support PyTorch 1.5.
|
| 209 |
+
class SiLU(nn.Module):
|
| 210 |
+
def forward(self, x):
|
| 211 |
+
return x * torch.sigmoid(x)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
class GroupNorm32(nn.GroupNorm):
|
| 215 |
+
def forward(self, x):
|
| 216 |
+
return super().forward(x.float()).type(x.dtype)
|
| 217 |
+
|
| 218 |
+
def conv_nd(dims, *args, **kwargs):
|
| 219 |
+
"""
|
| 220 |
+
Create a 1D, 2D, or 3D convolution module.
|
| 221 |
+
"""
|
| 222 |
+
if dims == 1:
|
| 223 |
+
return nn.Conv1d(*args, **kwargs)
|
| 224 |
+
elif dims == 2:
|
| 225 |
+
return nn.Conv2d(*args, **kwargs)
|
| 226 |
+
elif dims == 3:
|
| 227 |
+
return nn.Conv3d(*args, **kwargs)
|
| 228 |
+
raise ValueError(f"unsupported dimensions: {dims}")
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def linear(*args, **kwargs):
|
| 232 |
+
"""
|
| 233 |
+
Create a linear module.
|
| 234 |
+
"""
|
| 235 |
+
return nn.Linear(*args, **kwargs)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def avg_pool_nd(dims, *args, **kwargs):
|
| 239 |
+
"""
|
| 240 |
+
Create a 1D, 2D, or 3D average pooling module.
|
| 241 |
+
"""
|
| 242 |
+
if dims == 1:
|
| 243 |
+
return nn.AvgPool1d(*args, **kwargs)
|
| 244 |
+
elif dims == 2:
|
| 245 |
+
return nn.AvgPool2d(*args, **kwargs)
|
| 246 |
+
elif dims == 3:
|
| 247 |
+
return nn.AvgPool3d(*args, **kwargs)
|
| 248 |
+
raise ValueError(f"unsupported dimensions: {dims}")
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
class HybridConditioner(nn.Module):
|
| 252 |
+
|
| 253 |
+
def __init__(self, c_concat_config, c_crossattn_config):
|
| 254 |
+
super().__init__()
|
| 255 |
+
self.concat_conditioner = instantiate_from_config(c_concat_config)
|
| 256 |
+
self.crossattn_conditioner = instantiate_from_config(c_crossattn_config)
|
| 257 |
+
|
| 258 |
+
def forward(self, c_concat, c_crossattn):
|
| 259 |
+
c_concat = self.concat_conditioner(c_concat)
|
| 260 |
+
c_crossattn = self.crossattn_conditioner(c_crossattn)
|
| 261 |
+
return {'c_concat': [c_concat], 'c_crossattn': [c_crossattn]}
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def noise_like(shape, device, repeat=False):
|
| 265 |
+
repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat(shape[0], *((1,) * (len(shape) - 1)))
|
| 266 |
+
noise = lambda: torch.randn(shape, device=device)
|
| 267 |
+
return repeat_noise() if repeat else noise()
|