util.py 9.3 KB

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