giulio98 commited on
Commit
7e77599
·
verified ·
1 Parent(s): 11b35f8

Create scoresdeve_scheduler.py

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