giulio98 commited on
Commit
558367b
1 Parent(s): dca5ff1

Create scheduler/sde_ve_scheduler.py

Browse files
Files changed (1) hide show
  1. scheduler/sde_ve_scheduler.py +268 -0
scheduler/sde_ve_scheduler.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Optional, Tuple, Union
5
+ import torch
6
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
7
+ from diffusers.utils import BaseOutput
8
+ from diffusers.utils.torch_utils import randn_tensor
9
+ from diffusers.schedulers.scheduling_utils import SchedulerMixin, SchedulerOutput
10
+
11
+ @dataclass
12
+ class SdeVeOutput(BaseOutput):
13
+ """
14
+ Output class for the scheduler's `step` function output.
15
+ Args:
16
+ prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
17
+ Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model input in the
18
+ denoising loop.
19
+ prev_sample_mean (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
20
+ Mean averaged `prev_sample` over previous timesteps.
21
+ """
22
+
23
+ prev_sample: torch.FloatTensor
24
+ prev_sample_mean: torch.FloatTensor
25
+
26
+
27
+ class ScoreSdeVeScheduler(SchedulerMixin, ConfigMixin):
28
+ """
29
+ `ScoreSdeVeScheduler` is a variance exploding stochastic differential equation (SDE) scheduler.
30
+ This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
31
+ methods the library implements for all schedulers such as loading and saving.
32
+ Args:
33
+ num_train_timesteps (`int`, defaults to 1000):
34
+ The number of diffusion steps to train the model.
35
+ snr (`float`, defaults to 0.15):
36
+ A coefficient weighting the step from the `model_output` sample (from the network) to the random noise.
37
+ sigma_min (`float`, defaults to 0.01):
38
+ The initial noise scale for the sigma sequence in the sampling procedure. The minimum sigma should mirror
39
+ the distribution of the data.
40
+ sigma_max (`float`, defaults to 1348.0):
41
+ The maximum value used for the range of continuous timesteps passed into the model.
42
+ sampling_eps (`float`, defaults to 1e-5):
43
+ The end value of sampling where timesteps decrease progressively from 1 to epsilon.
44
+ correct_steps (`int`, defaults to 1):
45
+ The number of correction steps performed on a produced sample.
46
+ """
47
+
48
+ order = 1
49
+
50
+ @register_to_config
51
+ def __init__(
52
+ self,
53
+ num_train_timesteps: int = 2000,
54
+ snr: float = 0.15,
55
+ sigma_min: float = 0.01,
56
+ sigma_max: float = 1348.0,
57
+ sampling_eps: float = 1e-5,
58
+ correct_steps: int = 1,
59
+ ):
60
+ # standard deviation of the initial noise distribution
61
+ self.init_noise_sigma = sigma_max
62
+
63
+ # setable values
64
+ self.timesteps = None
65
+
66
+ self.set_sigmas(num_train_timesteps, sigma_min, sigma_max, sampling_eps)
67
+
68
+ def scale_model_input(self, sample: torch.FloatTensor, timestep: Optional[int] = None) -> torch.FloatTensor:
69
+ """
70
+ Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
71
+ current timestep.
72
+ Args:
73
+ sample (`torch.FloatTensor`):
74
+ The input sample.
75
+ timestep (`int`, *optional*):
76
+ The current timestep in the diffusion chain.
77
+ Returns:
78
+ `torch.FloatTensor`:
79
+ A scaled input sample.
80
+ """
81
+ return sample
82
+
83
+ def set_timesteps(
84
+ self, num_inference_steps: int, sampling_eps: float = None, device: Union[str, torch.device] = None
85
+ ):
86
+ """
87
+ Sets the continuous timesteps used for the diffusion chain (to be run before inference).
88
+ Args:
89
+ num_inference_steps (`int`):
90
+ The number of diffusion steps used when generating samples with a pre-trained model.
91
+ sampling_eps (`float`, *optional*):
92
+ The final timestep value (overrides value given during scheduler instantiation).
93
+ device (`str` or `torch.device`, *optional*):
94
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
95
+ """
96
+ sampling_eps = sampling_eps if sampling_eps is not None else self.config.sampling_eps
97
+
98
+ self.timesteps = torch.linspace(1, sampling_eps, num_inference_steps, device=device)
99
+
100
+ def set_sigmas(
101
+ self, num_inference_steps: int, sigma_min: float = None, sigma_max: float = None, sampling_eps: float = None
102
+ ):
103
+ """
104
+ Sets the noise scales used for the diffusion chain (to be run before inference). The sigmas control the weight
105
+ of the `drift` and `diffusion` components of the sample update.
106
+ Args:
107
+ num_inference_steps (`int`):
108
+ The number of diffusion steps used when generating samples with a pre-trained model.
109
+ sigma_min (`float`, optional):
110
+ The initial noise scale value (overrides value given during scheduler instantiation).
111
+ sigma_max (`float`, optional):
112
+ The final noise scale value (overrides value given during scheduler instantiation).
113
+ sampling_eps (`float`, optional):
114
+ The final timestep value (overrides value given during scheduler instantiation).
115
+ """
116
+ sigma_min = sigma_min if sigma_min is not None else self.config.sigma_min
117
+ sigma_max = sigma_max if sigma_max is not None else self.config.sigma_max
118
+ sampling_eps = sampling_eps if sampling_eps is not None else self.config.sampling_eps
119
+ if self.timesteps is None:
120
+ self.set_timesteps(num_inference_steps, sampling_eps)
121
+
122
+ self.sigmas = sigma_min * (sigma_max / sigma_min) ** (self.timesteps / sampling_eps)
123
+ self.discrete_sigmas = torch.exp(torch.linspace(math.log(sigma_min), math.log(sigma_max), num_inference_steps))
124
+ self.sigmas = torch.tensor([sigma_min * (sigma_max / sigma_min) ** t for t in self.timesteps])
125
+
126
+ def get_adjacent_sigma(self, timesteps, t):
127
+ return torch.where(
128
+ timesteps == 0,
129
+ torch.zeros_like(t.to(timesteps.device)),
130
+ self.discrete_sigmas[timesteps - 1].to(timesteps.device),
131
+ )
132
+
133
+ def step_pred(
134
+ self,
135
+ model_output: torch.FloatTensor,
136
+ timestep: int,
137
+ sample: torch.FloatTensor,
138
+ generator: Optional[torch.Generator] = None,
139
+ return_dict: bool = True,
140
+ ) -> Union[SdeVeOutput, Tuple]:
141
+ """
142
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
143
+ process from the learned model outputs (most often the predicted noise).
144
+ Args:
145
+ model_output (`torch.FloatTensor`):
146
+ The direct output from learned diffusion model.
147
+ timestep (`int`):
148
+ The current discrete timestep in the diffusion chain.
149
+ sample (`torch.FloatTensor`):
150
+ A current instance of a sample created by the diffusion process.
151
+ generator (`torch.Generator`, *optional*):
152
+ A random number generator.
153
+ return_dict (`bool`, *optional*, defaults to `True`):
154
+ Whether or not to return a [`~schedulers.scheduling_sde_ve.SdeVeOutput`] or `tuple`.
155
+ Returns:
156
+ [`~schedulers.scheduling_sde_ve.SdeVeOutput`] or `tuple`:
157
+ If return_dict is `True`, [`~schedulers.scheduling_sde_ve.SdeVeOutput`] is returned, otherwise a tuple
158
+ is returned where the first element is the sample tensor.
159
+ """
160
+ if self.timesteps is None:
161
+ raise ValueError(
162
+ "`self.timesteps` is not set, you need to run 'set_timesteps' after creating the scheduler"
163
+ )
164
+
165
+ timestep = timestep * torch.ones(
166
+ sample.shape[0], device=sample.device
167
+ ) # torch.repeat_interleave(timestep, sample.shape[0])
168
+ timesteps = (timestep * (len(self.timesteps) - 1)).long()
169
+
170
+ # mps requires indices to be in the same device, so we use cpu as is the default with cuda
171
+ timesteps = timesteps.to(self.discrete_sigmas.device)
172
+
173
+ sigma = self.discrete_sigmas[timesteps].to(sample.device)
174
+ adjacent_sigma = self.get_adjacent_sigma(timesteps, timestep).to(sample.device)
175
+ drift = torch.zeros_like(sample)
176
+ diffusion = (sigma**2 - adjacent_sigma**2) ** 0.5
177
+
178
+ # equation 6 in the paper: the model_output modeled by the network is grad_x log pt(x)
179
+ # also equation 47 shows the analog from SDE models to ancestral sampling methods
180
+ diffusion = diffusion.flatten()
181
+ while len(diffusion.shape) < len(sample.shape):
182
+ diffusion = diffusion.unsqueeze(-1)
183
+ drift = drift - diffusion**2 * model_output
184
+
185
+ # equation 6: sample noise for the diffusion term of
186
+ noise = randn_tensor(
187
+ sample.shape, layout=sample.layout, generator=generator, device=sample.device, dtype=sample.dtype
188
+ )
189
+ prev_sample_mean = sample - drift # subtract because `dt` is a small negative timestep
190
+ # TODO is the variable diffusion the correct scaling term for the noise?
191
+ prev_sample = prev_sample_mean + diffusion * noise # add impact of diffusion field g
192
+
193
+ if not return_dict:
194
+ return (prev_sample, prev_sample_mean)
195
+
196
+ return SdeVeOutput(prev_sample=prev_sample, prev_sample_mean=prev_sample_mean)
197
+
198
+ def step_correct(
199
+ self,
200
+ model_output: torch.FloatTensor,
201
+ sample: torch.FloatTensor,
202
+ generator: Optional[torch.Generator] = None,
203
+ return_dict: bool = True,
204
+ ) -> Union[SchedulerOutput, Tuple]:
205
+ """
206
+ Correct the predicted sample based on the `model_output` of the network. This is often run repeatedly after
207
+ making the prediction for the previous timestep.
208
+ Args:
209
+ model_output (`torch.FloatTensor`):
210
+ The direct output from learned diffusion model.
211
+ sample (`torch.FloatTensor`):
212
+ A current instance of a sample created by the diffusion process.
213
+ generator (`torch.Generator`, *optional*):
214
+ A random number generator.
215
+ return_dict (`bool`, *optional*, defaults to `True`):
216
+ Whether or not to return a [`~schedulers.scheduling_sde_ve.SdeVeOutput`] or `tuple`.
217
+ Returns:
218
+ [`~schedulers.scheduling_sde_ve.SdeVeOutput`] or `tuple`:
219
+ If return_dict is `True`, [`~schedulers.scheduling_sde_ve.SdeVeOutput`] is returned, otherwise a tuple
220
+ is returned where the first element is the sample tensor.
221
+ """
222
+ if self.timesteps is None:
223
+ raise ValueError(
224
+ "`self.timesteps` is not set, you need to run 'set_timesteps' after creating the scheduler"
225
+ )
226
+
227
+ # For small batch sizes, the paper "suggest replacing norm(z) with sqrt(d), where d is the dim. of z"
228
+ # sample noise for correction
229
+ noise = randn_tensor(sample.shape, layout=sample.layout, generator=generator, device=sample.device).to(sample.device)
230
+
231
+ # compute step size from the model_output, the noise, and the snr
232
+ grad_norm = torch.norm(model_output.reshape(model_output.shape[0], -1), dim=-1).mean()
233
+ noise_norm = torch.norm(noise.reshape(noise.shape[0], -1), dim=-1).mean()
234
+ step_size = (self.config.snr * noise_norm / grad_norm) ** 2 * 2
235
+ step_size = step_size * torch.ones(sample.shape[0]).to(sample.device)
236
+ # self.repeat_scalar(step_size, sample.shape[0])
237
+
238
+ # compute corrected sample: model_output term and noise term
239
+ step_size = step_size.flatten()
240
+ while len(step_size.shape) < len(sample.shape):
241
+ step_size = step_size.unsqueeze(-1)
242
+ prev_sample_mean = sample + step_size * model_output
243
+ prev_sample = prev_sample_mean + ((step_size * 2) ** 0.5) * noise
244
+
245
+ if not return_dict:
246
+ return (prev_sample,)
247
+
248
+ return SchedulerOutput(prev_sample=prev_sample)
249
+
250
+ def add_noise(
251
+ self,
252
+ original_samples: torch.FloatTensor,
253
+ noise: torch.FloatTensor,
254
+ timesteps: torch.FloatTensor,
255
+ ) -> torch.FloatTensor:
256
+ # Make sure sigmas and timesteps have the same device and dtype as original_samples
257
+ timesteps = timesteps.to(original_samples.device)
258
+ sigmas = self.config.sigma_min * (self.config.sigma_max / self.config.sigma_min) ** timesteps
259
+ noise = (
260
+ noise * sigmas[:, None, None, None]
261
+ if noise is not None
262
+ else torch.randn_like(original_samples) * sigmas[:, None, None, None]
263
+ )
264
+ noisy_samples = noise + original_samples
265
+ return noisy_samples
266
+
267
+ def __len__(self):
268
+ return self.config.num_train_timesteps