Dhenenjay commited on
Commit
ca82763
·
verified ·
1 Parent(s): 97b55e6

Upload diffusion.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. diffusion.py +322 -0
diffusion.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """E3Diff Gaussian Diffusion - exact copy from original with fixed imports."""
2
+
3
+ import math
4
+ import torch
5
+ from torch import nn
6
+ import torch.nn.functional as F
7
+ from inspect import isfunction
8
+ from functools import partial
9
+ import numpy as np
10
+
11
+
12
+ def _warmup_beta(linear_start, linear_end, n_timestep, warmup_frac):
13
+ betas = linear_end * np.ones(n_timestep, dtype=np.float64)
14
+ warmup_time = int(n_timestep * warmup_frac)
15
+ betas[:warmup_time] = np.linspace(
16
+ linear_start, linear_end, warmup_time, dtype=np.float64)
17
+ return betas
18
+
19
+
20
+ def make_beta_schedule(schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
21
+ if schedule == 'quad':
22
+ betas = np.linspace(linear_start ** 0.5, linear_end ** 0.5,
23
+ n_timestep, dtype=np.float64) ** 2
24
+ elif schedule == 'linear':
25
+ betas = np.linspace(linear_start, linear_end,
26
+ n_timestep, dtype=np.float64)
27
+ elif schedule == 'warmup10':
28
+ betas = _warmup_beta(linear_start, linear_end, n_timestep, 0.1)
29
+ elif schedule == 'warmup50':
30
+ betas = _warmup_beta(linear_start, linear_end, n_timestep, 0.5)
31
+ elif schedule == 'const':
32
+ betas = linear_end * np.ones(n_timestep, dtype=np.float64)
33
+ elif schedule == 'jsd':
34
+ betas = 1. / np.linspace(n_timestep, 1, n_timestep, dtype=np.float64)
35
+ elif schedule == "cosine":
36
+ timesteps = (
37
+ torch.arange(n_timestep + 1, dtype=torch.float64) /
38
+ n_timestep + cosine_s
39
+ )
40
+ alphas = timesteps / (1 + cosine_s) * math.pi / 2
41
+ alphas = torch.cos(alphas).pow(2)
42
+ alphas = alphas / alphas[0]
43
+ betas = 1 - alphas[1:] / alphas[:-1]
44
+ betas = betas.clamp(max=0.999)
45
+ else:
46
+ raise NotImplementedError(schedule)
47
+ return betas
48
+
49
+
50
+ def exists(x):
51
+ return x is not None
52
+
53
+
54
+ def default(val, d):
55
+ if exists(val):
56
+ return val
57
+ return d() if isfunction(d) else d
58
+
59
+
60
+ class GaussianDiffusion(nn.Module):
61
+ def __init__(
62
+ self,
63
+ denoise_fn,
64
+ image_size,
65
+ channels=3,
66
+ loss_type='l1',
67
+ conditional=True,
68
+ schedule_opt=None,
69
+ xT_noise_r=0.1,
70
+ seed=1,
71
+ opt=None
72
+ ):
73
+ super().__init__()
74
+ self.lq_noiselevel_val = schedule_opt["lq_noiselevel"]
75
+ self.opt = opt
76
+ self.channels = channels
77
+ self.image_size = image_size
78
+ self.denoise_fn = denoise_fn
79
+ self.loss_type = loss_type
80
+ self.conditional = conditional
81
+ self.ddim = schedule_opt['ddim']
82
+ self.xT_noise_r = xT_noise_r
83
+ self.seed = seed
84
+
85
+ def set_loss(self, device):
86
+ if self.loss_type == 'l1':
87
+ self.loss_func = nn.L1Loss(reduction='sum').to(device)
88
+ elif self.loss_type == 'l2':
89
+ self.loss_func = nn.MSELoss(reduction='sum').to(device)
90
+ else:
91
+ raise NotImplementedError()
92
+
93
+ def set_new_noise_schedule(self, schedule_opt, device, num_train_timesteps=1000):
94
+ self.ddim = schedule_opt['ddim']
95
+ self.num_train_timesteps = num_train_timesteps
96
+ to_torch = partial(torch.tensor, dtype=torch.float32, device=device)
97
+
98
+ betas = make_beta_schedule(
99
+ schedule=schedule_opt['schedule'],
100
+ n_timestep=num_train_timesteps,
101
+ linear_start=schedule_opt['linear_start'],
102
+ linear_end=schedule_opt['linear_end'])
103
+ betas = betas.detach().cpu().numpy() if isinstance(
104
+ betas, torch.Tensor) else betas
105
+ alphas = 1. - betas
106
+ alphas_cumprod = np.cumprod(alphas, axis=0)
107
+ alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1])
108
+ self.sqrt_alphas_cumprod_prev = np.sqrt(
109
+ np.append(1., alphas_cumprod))
110
+
111
+ timesteps, = betas.shape
112
+ self.num_timesteps = int(timesteps)
113
+ self.register_buffer('betas', to_torch(betas))
114
+ self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
115
+ self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev))
116
+
117
+ # calculations for diffusion q(x_t | x_{t-1}) and others
118
+ self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
119
+ self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
120
+ self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod)))
121
+ self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod)))
122
+ self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1)))
123
+
124
+ # calculations for posterior q(x_{t-1} | x_t, x_0)
125
+ posterior_variance = betas * (1. - alphas_cumprod_prev) / (1. - alphas_cumprod)
126
+ self.register_buffer('posterior_variance', to_torch(posterior_variance))
127
+ self.register_buffer('posterior_log_variance_clipped', to_torch(
128
+ np.log(np.maximum(posterior_variance, 1e-20))))
129
+ self.register_buffer('posterior_mean_coef1', to_torch(
130
+ betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod)))
131
+ self.register_buffer('posterior_mean_coef2', to_torch(
132
+ (1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod)))
133
+
134
+ self.schedule_type = schedule_opt['schedule']
135
+ if self.ddim > 0:
136
+ self.ddim_num_steps = schedule_opt['n_timestep']
137
+
138
+ def predict_start_from_noise(self, x_t, t, noise):
139
+ return self.sqrt_recip_alphas_cumprod[t] * x_t - \
140
+ self.sqrt_recipm1_alphas_cumprod[t] * noise
141
+
142
+ def q_posterior(self, x_start, x_t, t):
143
+ posterior_mean = self.posterior_mean_coef1[t] * \
144
+ x_start + self.posterior_mean_coef2[t] * x_t
145
+ posterior_log_variance_clipped = self.posterior_log_variance_clipped[t]
146
+ return posterior_mean, posterior_log_variance_clipped
147
+
148
+ def p_mean_variance(self, x, t, clip_denoised: bool, condition_x=None):
149
+ batch_size = x.shape[0]
150
+ noise_level = torch.FloatTensor(
151
+ [self.sqrt_alphas_cumprod_prev[t+1]]).repeat(batch_size, 1).to(x.device)
152
+ if condition_x is not None:
153
+ x_recon = self.predict_start_from_noise(
154
+ x, t=t, noise=self.denoise_fn(torch.cat([condition_x, x], dim=1), noise_level, t))
155
+ else:
156
+ x_recon = self.predict_start_from_noise(
157
+ x, t=t, noise=self.denoise_fn(x, noise_level))
158
+
159
+ if clip_denoised:
160
+ x_recon.clamp_(-1., 1.)
161
+
162
+ model_mean, posterior_log_variance = self.q_posterior(
163
+ x_start=x_recon, x_t=x, t=t)
164
+ return model_mean, posterior_log_variance, x_recon
165
+
166
+ def ddim_sample(self, condition_x, img_or_shape, device, seed=1, img_s1=None):
167
+ if self.schedule_type == 'linear':
168
+ self.ddim_sampling_eta = 0.8
169
+ simple_var = False
170
+ threshold_x = False
171
+ elif self.schedule_type == 'cosine':
172
+ self.ddim_sampling_eta = 0.8
173
+ simple_var = False
174
+ threshold_x = False
175
+
176
+ batch, total_timesteps, sampling_timesteps, eta = \
177
+ img_or_shape[0], self.num_train_timesteps, \
178
+ self.ddim_num_steps, self.ddim_sampling_eta
179
+
180
+ noisy_img_s1 = None
181
+
182
+ if simple_var:
183
+ eta = 1
184
+ ts = torch.linspace(total_timesteps, 0, (sampling_timesteps + 1)).to(device).to(torch.long)
185
+
186
+ x = torch.randn(img_or_shape).to(device)
187
+ batch_size = x.shape[0]
188
+ imgs = [x]
189
+ img_onestep = [condition_x[:, :self.channels, ...]]
190
+
191
+ tbar = range(1, sampling_timesteps + 1)
192
+ for i in tbar:
193
+ cur_t = ts[i - 1] - 1
194
+ prev_t = ts[i] - 1
195
+ noise_level = torch.FloatTensor(
196
+ [self.sqrt_alphas_cumprod_prev[cur_t]]).repeat(batch_size, 1).to(x.device)
197
+
198
+ alpha_prod_t = self.alphas_cumprod[cur_t]
199
+ alpha_prod_t_prev = self.alphas_cumprod[prev_t] if prev_t >= 0 else 1
200
+ beta_prod_t = 1 - alpha_prod_t
201
+
202
+ # pred noise
203
+ model_output = self.denoise_fn(torch.cat([condition_x, x], dim=1), noise_level)
204
+
205
+ sigma_2 = eta * (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * (1 - alpha_prod_t / alpha_prod_t_prev)
206
+ noise = torch.randn_like(x)
207
+
208
+ pred_original_sample = (x - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5)
209
+
210
+ if threshold_x:
211
+ pred_original_sample = self._threshold_sample(pred_original_sample)
212
+ else:
213
+ pred_original_sample = pred_original_sample.clamp(-1, 1)
214
+
215
+ pred_sample_direction = (1 - alpha_prod_t_prev - sigma_2) ** (0.5) * model_output
216
+
217
+ if simple_var:
218
+ third_term = (1 - alpha_prod_t / alpha_prod_t_prev) ** 0.5 * noise
219
+ else:
220
+ third_term = sigma_2 ** 0.5 * noise
221
+
222
+ x = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction + third_term
223
+ imgs.append(x)
224
+ img_onestep.append(pred_original_sample)
225
+
226
+ imgs = torch.concat(imgs, dim=0)
227
+ img_onestep = torch.concat(img_onestep, dim=0)
228
+
229
+ return imgs, img_onestep
230
+
231
+ @torch.no_grad()
232
+ def p_sample(self, x, t, clip_denoised=True, condition_x=None):
233
+ model_mean, model_log_variance, x_recon = self.p_mean_variance(
234
+ x=x, t=t, clip_denoised=clip_denoised, condition_x=condition_x)
235
+ noise = torch.randn_like(x) if t > 0 else torch.zeros_like(x)
236
+ return model_mean + noise * (0.5 * model_log_variance).exp(), x_recon
237
+
238
+ @torch.no_grad()
239
+ def p_sample_loop(self, x_in, continous=False, seed=1, img_s1=None):
240
+ device = self.betas.device
241
+ sample_inter = 1
242
+
243
+ if not self.conditional:
244
+ shape = x_in
245
+ img = torch.randn(shape, device=device)
246
+ ret_img = img
247
+ if not self.ddim:
248
+ for i in reversed(range(0, self.num_timesteps)):
249
+ img, x_recon = self.p_sample(img, i)
250
+ if i % sample_inter == 0:
251
+ ret_img = torch.cat([ret_img, img], dim=0)
252
+ else:
253
+ for i in range(0, len(self.ddim_timesteps)):
254
+ ddim_t = self.ddim_timesteps[i]
255
+ img = self.ddim_sample(img, ddim_t)
256
+ if i % sample_inter == 0:
257
+ ret_img = torch.cat([ret_img, img], dim=0)
258
+ else:
259
+ x = x_in
260
+ shape = (x.shape[0], self.channels, x.shape[-2], x.shape[-1])
261
+
262
+ if self.xT_noise_r > 0:
263
+ img0 = torch.randn(shape, device=device)
264
+ x_start = x_in[:, 0:1, ...]
265
+ continuous_sqrt_alpha_cumprod = torch.FloatTensor(
266
+ np.random.uniform(
267
+ self.sqrt_alphas_cumprod_prev[self.num_timesteps-1],
268
+ self.sqrt_alphas_cumprod_prev[self.num_timesteps],
269
+ size=x_start.shape[0]
270
+ )).to(x_start.device)
271
+ continuous_sqrt_alpha_cumprod = continuous_sqrt_alpha_cumprod.view(x_start.shape[0], -1)
272
+
273
+ noise = default(x_start, lambda: torch.randn_like(x_start))
274
+ img = self.q_sample(
275
+ x_start=x_start, continuous_sqrt_alpha_cumprod=continuous_sqrt_alpha_cumprod.view(-1, 1, 1, 1), noise=noise)
276
+ img = self.xT_noise_r * img + (1 - self.xT_noise_r) * img0
277
+ else:
278
+ img = torch.randn(shape, device=device)
279
+
280
+ ret_img = x
281
+ img_onestep = x
282
+
283
+ if self.opt['stage'] != 2:
284
+ if not self.ddim:
285
+ for i in reversed(range(0, self.num_timesteps)):
286
+ img, x_recon = self.p_sample(img, i, condition_x=x)
287
+ if i % sample_inter == 0:
288
+ ret_img = torch.cat([ret_img[:, :self.channels, ...], img], dim=0)
289
+ if i % sample_inter == 0 or i == self.num_timesteps - 1:
290
+ img_onestep = torch.cat([img_onestep[:, :self.channels, ...], x_recon], dim=0)
291
+ else:
292
+ ret_img, img_onestep = self.ddim_sample(condition_x=x, img_or_shape=shape, device=device, seed=seed, img_s1=img_s1)
293
+
294
+ if continous:
295
+ return ret_img, img_onestep
296
+ else:
297
+ return ret_img[-x_in.shape[0]:], img_onestep
298
+ else:
299
+ self.ddim_num_steps = self.opt['ddim_steps']
300
+ ret_img, img_onestep = self.ddim_sample(condition_x=x, img_or_shape=shape, device=device, seed=seed, img_s1=img_s1)
301
+
302
+ if continous:
303
+ return ret_img, img_onestep
304
+ else:
305
+ return ret_img[-x_in.shape[0]:], img_onestep
306
+
307
+ @torch.no_grad()
308
+ def sample(self, batch_size=1, continous=False):
309
+ image_size = self.image_size
310
+ channels = self.channels
311
+ return self.p_sample_loop((batch_size, channels, image_size, image_size), continous)
312
+
313
+ @torch.no_grad()
314
+ def super_resolution(self, x_in, continous=False, seed=1, img_s1=None):
315
+ return self.p_sample_loop(x_in, continous, seed=seed, img_s1=img_s1)
316
+
317
+ def q_sample(self, x_start, continuous_sqrt_alpha_cumprod, noise=None):
318
+ noise = default(noise, lambda: torch.randn_like(x_start))
319
+ return (
320
+ continuous_sqrt_alpha_cumprod * x_start +
321
+ (1 - continuous_sqrt_alpha_cumprod ** 2).sqrt() * noise
322
+ )