1import abc
2from typing import List, Optional, TYPE_CHECKING
3from typing import Tuple
4
5import torch
6
7from diffusion_models.gaussian_diffusion.beta_schedulers import (
8 BaseBetaScheduler,
9)
10from diffusion_models.utils.schemas import PredictionType, Timestep
11
12if TYPE_CHECKING:
13 from diffusion_models.models.base_diffusion_model import BaseDiffusionModel
14
15
[docs]
16class BaseDiffuser(abc.ABC):
17 def __init__(
18 self,
19 beta_scheduler: BaseBetaScheduler,
20 prediction_type: PredictionType = PredictionType.Epsilon,
21 ):
22 """Initializes the object with the specified beta scheduler.
23
24 BaseDiffuser is an abstract base class for different diffuser
25 implementations. It defines the interface that all diffusers should adhere
26 to.
27
28 Args:
29 beta_scheduler: The beta scheduler used by the diffuser.
30 prediction_type: What the model is trained to predict, either the added
31 noise (``"epsilon"``) or the velocity (``"v"``, see `"Progressive
32 Distillation for Fast Sampling of Diffusion Models"
33 <https://arxiv.org/abs/2202.00512>`_).
34
35 Warnings:
36 Do not instantiate this class directly. Instead, build your own Diffuser
37 by inheriting from BaseDiffuser.
38 (see :class:`~.gaussian_diffuser.GaussianDiffuser`)
39
40 """
[docs]
41 self.beta_scheduler: BaseBetaScheduler = beta_scheduler
42 """The beta scheduler used by the diffuser."""
[docs]
43 self.prediction_type: PredictionType = PredictionType(prediction_type)
44 """What the model predicts: the noise (epsilon) or the velocity (v)."""
45
46 def _alpha_bar(self, timesteps: torch.Tensor, ndim: int = 4) -> torch.Tensor:
47 alpha_bar = self.beta_scheduler.alpha_bars.gather(dim=0, index=timesteps)
48 return alpha_bar.reshape((-1, *((1,) * (ndim - 1))))
49
[docs]
50 def get_target(
51 self, images: torch.Tensor, noise: torch.Tensor, timesteps: torch.Tensor
52 ) -> torch.Tensor:
53 """The regression target of the model for the configured prediction type.
54
55 Args:
56 images: The clean images.
57 noise: The noise that was added to them (from :meth:`diffuse_batch`).
58 timesteps: The timesteps used for diffusion.
59
60 Returns:
61 The noise for ``"epsilon"``, or the velocity
62 :math:`v = \\sqrt{\\bar{\\alpha}_t}\\epsilon - \\sqrt{1 - \\bar{\\alpha}_t}x_0`
63 for ``"v"``.
64 """
65 if self.prediction_type == PredictionType.Epsilon:
66 return noise
67 alpha_bar = self._alpha_bar(timesteps, images.ndim)
68 return torch.sqrt(alpha_bar) * noise - torch.sqrt(1 - alpha_bar) * images
69
[docs]
70 def to_epsilon_and_x0(
71 self,
72 output: torch.Tensor,
73 images: torch.Tensor,
74 timesteps: torch.Tensor,
75 ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
76 """Convert a model output into a noise estimate and a clean-image estimate.
77
78 Args:
79 output: The model prediction.
80 images: The noisy images the model was given.
81 timesteps: The timesteps the model was given.
82
83 Returns:
84 ``(epsilon, x0)``. ``x0`` is ``None`` for ``"epsilon"`` models, as it
85 cannot be computed where :math:`\\bar{\\alpha}_t = 0`.
86 """
87 if self.prediction_type == PredictionType.Epsilon:
88 return output, None
89 alpha_bar = self._alpha_bar(timesteps, images.ndim)
90 epsilon = (
91 torch.sqrt(1 - alpha_bar) * images + torch.sqrt(alpha_bar) * output
92 )
93 x0 = torch.sqrt(alpha_bar) * images - torch.sqrt(1 - alpha_bar) * output
94 return epsilon, x0
95
96 @property
97 @abc.abstractmethod
[docs]
98 def steps(self) -> List[int]:
99 """Returns the list of steps used in the denoising process."""
100 raise NotImplementedError
101
102 @abc.abstractmethod
[docs]
103 def get_timestep(self, number_of_images: int, idx: int) -> Timestep:
104 """Get timestep information used for denoising."""
105 raise NotImplementedError
106
107 def _denoise_step(
108 self, images: torch.Tensor, model: torch.nn.Module, timestep: Timestep
109 ) -> torch.Tensor:
110 """Denoise a batch of images by a single step.
111
112 Used to step through generation one timestep at a time (see
113 :meth:`~.DiffusionInference.get_generator`). Diffusers that support it
114 override this method.
115
116 Args:
117 images: A tensor containing a batch of images to denoise.
118 model: The model to be used for denoising.
119 timestep: The current and previous timesteps.
120
121 Returns:
122 The images, denoised by one step.
123 """
124 raise NotImplementedError()
125
126 @abc.abstractmethod
[docs]
127 def diffuse_batch(
128 self, images: torch.Tensor
129 ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
130 """Diffuse a batch of images.
131
132 Args:
133 images: A tensor containing a batch of images.
134
135 Returns:
136 A tuple containing three tensors
137
138 - images: Diffused batch of images.
139 - noise: Noise added to the images.
140 - timesteps: Timesteps used for diffusion.
141 """
142 raise NotImplementedError()
143
144 @abc.abstractmethod
[docs]
145 def denoise_batch(
146 self, images: torch.Tensor, model: "BaseDiffusionModel"
147 ) -> List[torch.Tensor]:
148 """Denoise a batch of images.
149
150 Args:
151 images: A tensor containing a batch of images to denoise.
152 model: The model to be used for denoising.
153
154 Returns:
155 A list of tensors containing a batch of denoised images.
156 """
157 raise NotImplementedError()
158
159 @abc.abstractmethod
[docs]
160 def to(self, device: str = "cpu"):
161 """Moves the data to the specified device.
162
163 This performs a similar behaviour to the `to` method of PyTorch.
164
165 Args:
166 device: The device to which the method should move the data.
167 It should be a string indicating the desired device.
168 Default is "cpu".
169 """
170 raise NotImplementedError()