giulio98 commited on
Commit
58fde87
·
verified ·
1 Parent(s): 39a379c

Create scheduler/sde_ve_scheduler.py

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