Source code for diffusion_models.gaussian_diffusion.ddimm_diffuser

  1from enum import Enum
  2from typing import List
  3from typing import Tuple
  4
  5import numpy as np
  6import torch
  7from tqdm import tqdm
  8
  9from diffusion_models.gaussian_diffusion.base_diffuser import BaseDiffuser
 10from diffusion_models.gaussian_diffusion.beta_schedulers import (
 11  BaseBetaScheduler,
 12)
 13from diffusion_models.models.base_diffusion_model import BaseDiffusionModel
 14from diffusion_models.utils.schemas import (
 15  Checkpoint,
 16  PredictionType,
 17  Timestep,
 18)
 19
 20
[docs] 21class DenoisingMode(str, Enum): 22 @classmethod 23 def _missing_(cls, value): 24 # Configs saved in checkpoints spell enums by member name ("Trailing"). 25 if isinstance(value, str): 26 for member in cls: 27 if value.lower() == member.name.lower(): 28 return member 29 return None 30
[docs] 31 Linear = "linear"
[docs] 32 Quadratic = "quadratic"
[docs] 33 Trailing = "trailing"
34 """Evenly spaced steps that end on the last (pure noise) timestep. 35 36 Needed to sample models trained with zero terminal SNR properly; linear and 37 quadratic spacing never reach the final timestep."""
38 39
[docs] 40class DdimDiffuser(BaseDiffuser): 41 def __init__( 42 self, 43 beta_scheduler: BaseBetaScheduler, 44 mode: DenoisingMode = DenoisingMode.Quadratic, 45 number_of_steps: int = 20, 46 prediction_type: PredictionType = PredictionType.Epsilon, 47 ): 48 """Initializes the class instance. 49 50 Args: 51 beta_scheduler (BaseBetaScheduler): The beta scheduler instance to be used. 52 mode: How the sampling timesteps are spaced. 53 number_of_steps: Number of denoising steps. 54 prediction_type: Whether the model predicts the noise or the velocity. 55 56 """ 57 super().__init__(beta_scheduler, prediction_type) 58
[docs] 59 self.number_of_steps = number_of_steps
60 """Number of steps to use in the denoising process.""" 61
[docs] 62 self.mode = DenoisingMode(mode)
63 """Linear or Quadratic sampling.""" 64
[docs] 65 self.device: str = "cpu"
66 """The device to use. Defaults to cpu.""" 67 68 @property
[docs] 69 def steps(self) -> List[int]: 70 if self.mode == DenoisingMode.Trailing: 71 stride = self.beta_scheduler.steps / self.number_of_steps 72 time_steps = ( 73 np.round(np.arange(1, self.number_of_steps + 1) * stride).astype(int) 74 - 1 75 ) 76 # Unlike the other modes there is no +1 shift: the last step is the 77 # final timestep, ``steps - 1``. 78 self._time_steps = time_steps 79 self._time_steps_prev = np.concatenate([[0], time_steps[:-1]]) 80 return list(range(self.number_of_steps))[::-1] 81 if self.mode == DenoisingMode.Linear: 82 a = self.beta_scheduler.steps // self.number_of_steps 83 time_steps = np.asarray(list(range(0, self.beta_scheduler.steps, a))) 84 else: 85 time_steps = ( 86 np.linspace( 87 0, np.sqrt(self.beta_scheduler.steps * 0.8), self.number_of_steps 88 ) 89 ** 2 90 ).astype(int) 91 self._time_steps = time_steps + 1 92 self._time_steps_prev = np.concatenate([[0], self._time_steps[:-1]]) 93 return list(range(self.number_of_steps))[::-1]
94
[docs] 95 def get_timestep(self, number_of_images: int, idx: int) -> Timestep: 96 timestep = torch.full( 97 (number_of_images,), self._time_steps[idx], device=self.device 98 ) 99 timestep_prev = torch.full( 100 (number_of_images,), self._time_steps_prev[idx], device=self.device 101 ) 102 return Timestep( 103 current=timestep, 104 previous=timestep_prev, 105 )
106 107 @classmethod
[docs] 108 def from_checkpoint(cls, checkpoint: Checkpoint) -> "DdimDiffuser": 109 """Instantiate a DDIM Diffuser from a training checkpoint. 110 111 Args: 112 checkpoint: The training checkpoint object containing 113 the trained model's parameters and configuration. 114 115 Returns: 116 An instance of the DdimDiffuser class initialized with the parameters 117 loaded from the given checkpoint. 118 """ 119 return cls( 120 beta_scheduler=BaseBetaScheduler.from_tensors( 121 steps=checkpoint.beta_scheduler_config.steps, 122 betas=checkpoint.beta_scheduler_config.betas, 123 alpha_bars=checkpoint.beta_scheduler_config.alpha_bars, 124 ), 125 prediction_type=PredictionType(checkpoint.prediction_type), 126 )
127
[docs] 128 def to(self, device: str = "cpu"): 129 """Moves the data to the specified device. 130 131 This performs a similar behaviour to the `to` method of PyTorch. moving the 132 GaussianDiffuser and the BetaScheduler to the specified device. 133 134 Args: 135 device: The device to which the method should move the object. 136 Default is "cpu". 137 138 Example: 139 >>> ddim_diffuser = DdimDiffuser() 140 >>> ddim_diffuser = ddim_diffuser.to(device="cuda") 141 """ 142 self.device = device 143 self.beta_scheduler = self.beta_scheduler.to(self.device) 144 return self
145 146 def _diffuse_batch( 147 self, images: torch.Tensor, timesteps: torch.Tensor 148 ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: 149 noise = torch.randn_like(images, device=self.device) 150 151 alpha_bar_t = self.beta_scheduler.alpha_bars.gather(dim=0, index=timesteps) 152 153 alpha_bar_t = alpha_bar_t.reshape((-1, *((1,) * (len(images.shape) - 1)))) 154 155 mu = torch.sqrt(alpha_bar_t) 156 sigma = torch.sqrt(1 - alpha_bar_t) 157 images = mu * images + sigma * noise 158 return images, noise, timesteps 159
[docs] 160 def diffuse_batch( 161 self, images: torch.Tensor 162 ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: 163 """Diffuse a batch of images. 164 165 Diffuse the given batch of images by adding noise based on the beta scheduler. 166 167 Args: 168 images: Batch of images to diffuse.\n 169 Shape should be ``(B, C, H, W)``. 170 171 Returns: 172 A tuple containing three tensors 173 174 - images: Diffused batch of images. 175 - noise: Noise added to the images. 176 - timesteps: Timesteps used for diffusion. 177 """ 178 timesteps = torch.randint( 179 0, self.beta_scheduler.steps, (images.shape[0],), device=self.device 180 ) 181 return self._diffuse_batch(images, timesteps)
182 183 @torch.no_grad() 184 def _denoise_step( 185 self, 186 images: torch.Tensor, 187 model: torch.nn.Module, 188 timestep: Timestep, 189 eta: float = 0.0, 190 ) -> torch.Tensor: 191 current_timestep = timestep.current 192 previous_timestep = timestep.previous 193 194 output = model(images, current_timestep) 195 epsilon_theta, x0_theta = self.to_epsilon_and_x0( 196 output, images, current_timestep 197 ) 198 199 alpha_bar_t = self.beta_scheduler.alpha_bars.gather( 200 dim=0, index=current_timestep 201 ).reshape(-1, 1, 1, 1) 202 203 alpha_bar_t_prev = self.beta_scheduler.alpha_bars.gather( # ty: ignore[no-matching-overload] 204 dim=0, index=previous_timestep 205 ).reshape(-1, 1, 1, 1) 206 207 sigma = eta * torch.sqrt( 208 (1 - alpha_bar_t_prev) 209 / (1 - alpha_bar_t) 210 * (1 - alpha_bar_t / alpha_bar_t_prev) 211 ) 212 213 epsilon_t = torch.randn_like(images) 214 215 if x0_theta is not None: 216 # Division free form, valid where alpha_bar_t == 0. 217 mu = ( 218 torch.sqrt(alpha_bar_t_prev) * x0_theta 219 + torch.sqrt(1 - alpha_bar_t_prev - sigma**2) * epsilon_theta 220 ) 221 return mu + sigma * epsilon_t 222 223 mu = ( 224 torch.sqrt(alpha_bar_t_prev / alpha_bar_t) * images 225 + ( 226 torch.sqrt(1 - alpha_bar_t_prev - sigma**2) 227 - torch.sqrt((alpha_bar_t_prev * (1 - alpha_bar_t)) / alpha_bar_t) 228 ) 229 * epsilon_theta 230 ) 231 return mu + sigma * epsilon_t 232
[docs] 233 def denoise_batch( 234 self, 235 images: torch.Tensor, 236 model: "BaseDiffusionModel", 237 ) -> List[torch.Tensor]: 238 """Denoise a batch of images. 239 240 This denoises a batch images. This is the image generation process. 241 242 Args: 243 images: A batch of noisy images. 244 model: The model to be used for denoising. 245 246 Returns: 247 A list of tensors containing a batch of denoised images. 248 """ 249 denoised_images = [] 250 for i in tqdm(self.steps, desc="Denoising"): 251 timestep = self.get_timestep(images.shape[0], idx=i) 252 253 images = self._denoise_step( 254 images, 255 model=model, 256 timestep=timestep, 257 ) 258 images = torch.clamp(images, -1.0, 1.0) 259 denoised_images.append(images) 260 return denoised_images