util.py 10 KB

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