Source code for diffusion_models.gaussian_diffusion.gaussian_diffuser

  1from typing import TYPE_CHECKING, List, Tuple
  2
  3import torch
  4from tqdm import tqdm
  5
  6from diffusion_models.gaussian_diffusion.base_diffuser import BaseDiffuser
  7from diffusion_models.gaussian_diffusion.beta_schedulers import (
  8  BaseBetaScheduler,
  9)
 10from diffusion_models.utils.schemas import (
 11  Checkpoint,
 12  PredictionType,
 13  Timestep,
 14)
 15
 16if TYPE_CHECKING:
 17  from diffusion_models.models.base_diffusion_model import BaseDiffusionModel
 18
 19
[docs] 20class GaussianDiffuser(BaseDiffuser): 21 def __init__( 22 self, 23 beta_scheduler: BaseBetaScheduler, 24 prediction_type: PredictionType = PredictionType.Epsilon, 25 ): 26 """Initializes the class instance. 27 28 Args: 29 beta_scheduler (BaseBetaScheduler): The beta scheduler instance to be used. 30 31 """ 32 super().__init__(beta_scheduler, prediction_type)
[docs] 33 self.device: str = "cpu"
34 """The device to use. Defaults to cpu.""" 35 36 @property
[docs] 37 def steps(self) -> List[int]: 38 return list(range(self.beta_scheduler.steps))[::-1]
39
[docs] 40 def get_timestep(self, number_of_images: int, idx: int): 41 timestep = torch.full((number_of_images,), idx, device=self.device) 42 return Timestep( 43 current=timestep, 44 )
45 46 @classmethod
[docs] 47 def from_checkpoint(cls, checkpoint: Checkpoint) -> "GaussianDiffuser": 48 """Instantiate a Gaussian Diffuser from a training checkpoint. 49 50 Args: 51 checkpoint: The training checkpoint object containing 52 the trained model's parameters and configuration. 53 54 Returns: 55 An instance of the GaussianDiffuser class initialized with the parameters 56 loaded from the given checkpoint. 57 """ 58 return cls( 59 beta_scheduler=BaseBetaScheduler.from_tensors( 60 steps=checkpoint.beta_scheduler_config.steps, 61 betas=checkpoint.beta_scheduler_config.betas, 62 alpha_bars=checkpoint.beta_scheduler_config.alpha_bars, 63 ), 64 prediction_type=PredictionType(checkpoint.prediction_type), 65 )
66
[docs] 67 def to(self, device: str = "cpu"): 68 """Moves the data to the specified device. 69 70 This performs a similar behaviour to the `to` method of PyTorch. moving the 71 GaussianDiffuser and the BetaScheduler to the specified device. 72 73 Args: 74 device: The device to which the method should move the object. 75 Default is "cpu". 76 77 Example: 78 >>> gaussian_diffuser = GaussianDiffuser() 79 >>> gaussian_diffuser = gaussian_diffuser.to(device="cuda") 80 """ 81 self.device = device 82 self.beta_scheduler = self.beta_scheduler.to(self.device) 83 return self
84 85 def _diffuse_batch( 86 self, images: torch.Tensor, timesteps: torch.Tensor 87 ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: 88 noise = torch.randn_like(images, device=self.device) 89 90 alpha_bar_t = self.beta_scheduler.alpha_bars.gather(dim=0, index=timesteps) 91 92 alpha_bar_t = alpha_bar_t.reshape((-1, *((1,) * (len(images.shape) - 1)))) 93 94 mu = torch.sqrt(alpha_bar_t) 95 sigma = torch.sqrt(1 - alpha_bar_t) 96 images = mu * images + sigma * noise 97 return images, noise, timesteps 98
[docs] 99 def diffuse_batch( 100 self, images: torch.Tensor 101 ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: 102 """Diffuse a batch of images. 103 104 Diffuse the given batch of images by adding noise based on the beta scheduler. 105 106 Args: 107 images: Batch of images to diffuse.\n 108 Shape should be ``(B, C, H, W)``. 109 110 Returns: 111 A tuple containing three tensors 112 113 - images: Diffused batch of images. 114 - noise: Noise added to the images. 115 - timesteps: Timesteps used for diffusion. 116 """ 117 timesteps = torch.randint( 118 0, self.beta_scheduler.steps, (images.shape[0],), device=self.device 119 ) 120 return self._diffuse_batch(images, timesteps)
121 122 @torch.no_grad() 123 def _denoise_step( 124 self, images: torch.Tensor, model: torch.nn.Module, timestep: Timestep 125 ) -> torch.Tensor: 126 current_timestep = timestep.current 127 beta_t = self.beta_scheduler.betas[current_timestep].reshape(-1, 1, 1, 1) 128 alpha_t = 1 - beta_t 129 alpha_bar_t = self.beta_scheduler.alpha_bars.gather( 130 dim=0, index=current_timestep 131 ).reshape(-1, 1, 1, 1) 132 epsilon, _ = self.to_epsilon_and_x0( 133 model(images, current_timestep), images, current_timestep 134 ) 135 mu = (1 / torch.sqrt(alpha_t)) * ( 136 images - epsilon * (beta_t / torch.sqrt(1 - alpha_bar_t)) 137 ) 138 139 if current_timestep[0] == 0: 140 return mu 141 else: 142 sigma = torch.sqrt(beta_t) * torch.randn_like(images) 143 return mu + sigma 144
[docs] 145 def denoise_batch( 146 self, 147 images: torch.Tensor, 148 model: "BaseDiffusionModel", 149 ) -> List[torch.Tensor]: 150 """Denoise a batch of images. 151 152 This denoises a batch images. This is the image generation process. 153 154 Args: 155 images: A batch of noisy images. 156 model: The model to be used for denoising. 157 158 Returns: 159 A list of tensors containing a batch of denoised images. 160 """ 161 denoised_images = [] 162 for i in tqdm(self.steps, desc="Denoising"): 163 timestep = self.get_timestep(images.shape[0], idx=i) 164 images = self._denoise_step(images, model=model, timestep=timestep) 165 images = torch.clamp(images, -1.0, 1.0) 166 denoised_images.append(images) 167 return denoised_images