Mehdi Cherti commited on
Commit
eb17c34
1 Parent(s): 9916e2b
Files changed (4) hide show
  1. app.py +1 -2
  2. clip_encoder.py +3 -11
  3. test_ddgan.py +0 -1
  4. test_ddgan_old.py +685 -0
app.py CHANGED
@@ -80,5 +80,4 @@ iface = gr.Interface(
80
  ],
81
  outputs="image"
82
  )
83
- #iface.launch(debug=True)
84
- iface.queue(concurrency_count=8, max_size=100).launch(max_threads=8, debug=True)
 
80
  ],
81
  outputs="image"
82
  )
83
+ iface.launch(debug=True)
 
clip_encoder.py CHANGED
@@ -17,23 +17,15 @@ class CLIPEncoder(nn.Module):
17
  if os.path.exists(fname):
18
  print(fname)
19
  pretrained = fname
20
- #model = "ViT-B-32"
21
- #pretrained = "openai"
22
-
23
  self.model = model
24
-
25
  self.pretrained = pretrained
26
- #self.model, _, _ = open_clip.create_model_and_transforms(model)#, pretrained=pretrained)
27
- #print(self.model)
28
- self.output_size = 1024
29
- #self.output_size = self.model.transformer.width
30
 
31
  def forward(self, texts, return_only_pooled=False):
32
- return torch.randn(len(texts), self.output_size), torch.randn(len(texts), 77, self.output_size), torch.ones(len(texts), 77).bool()
33
-
34
  device = next(self.parameters()).device
35
  toks = open_clip.tokenize(texts).to(device)
36
- x = self.model.token_embedding(toks) # [batch_size, n_ctx, d_model]
37
  x = x + self.model.positional_embedding
38
  x = x.permute(1, 0, 2) # NLD -> LND
39
  x = self.model.transformer(x, attn_mask=self.model.attn_mask)
 
17
  if os.path.exists(fname):
18
  print(fname)
19
  pretrained = fname
 
 
 
20
  self.model = model
 
21
  self.pretrained = pretrained
22
+ self.model, _, _ = open_clip.create_model_and_transforms(model, pretrained=pretrained)
23
+ self.output_size = self.model.transformer.width
 
 
24
 
25
  def forward(self, texts, return_only_pooled=False):
 
 
26
  device = next(self.parameters()).device
27
  toks = open_clip.tokenize(texts).to(device)
28
+ x = self.model.token_embedding(toks)
29
  x = x + self.model.positional_embedding
30
  x = x.permute(1, 0, 2) # NLD -> LND
31
  x = self.model.transformer(x, attn_mask=self.model.attn_mask)
test_ddgan.py CHANGED
@@ -394,7 +394,6 @@ def load_model(config, path, device="cpu"):
394
  print(text_encoder)
395
  config.cond_size = text_encoder.output_size
396
  netG = NCSNpp(config)
397
- #print(netG)
398
  print(path, os.path.exists(path))
399
  ckpt = torch.load(path, map_location="cpu")
400
  print("CK", ckpt)
 
394
  print(text_encoder)
395
  config.cond_size = text_encoder.output_size
396
  netG = NCSNpp(config)
 
397
  print(path, os.path.exists(path))
398
  ckpt = torch.load(path, map_location="cpu")
399
  print("CK", ckpt)
test_ddgan_old.py ADDED
@@ -0,0 +1,685 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ---------------------------------------------------------------
2
+ # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
3
+ #
4
+ # This work is licensed under the NVIDIA Source Code License
5
+ # for Denoising Diffusion GAN. To view a copy of this license, see the LICENSE file.
6
+ # ---------------------------------------------------------------
7
+ import argparse
8
+ import torch
9
+ import numpy as np
10
+ import time
11
+ import os
12
+ import json
13
+ import torchvision
14
+ from score_sde.models.ncsnpp_generator_adagn import NCSNpp
15
+ from encoder import build_encoder
16
+
17
+ #%% Diffusion coefficients
18
+ def var_func_vp(t, beta_min, beta_max):
19
+ log_mean_coeff = -0.25 * t ** 2 * (beta_max - beta_min) - 0.5 * t * beta_min
20
+ var = 1. - torch.exp(2. * log_mean_coeff)
21
+ return var
22
+
23
+ def var_func_geometric(t, beta_min, beta_max):
24
+ return beta_min * ((beta_max / beta_min) ** t)
25
+
26
+ def extract(input, t, shape):
27
+ out = torch.gather(input, 0, t)
28
+ reshape = [shape[0]] + [1] * (len(shape) - 1)
29
+ out = out.reshape(*reshape)
30
+
31
+ return out
32
+
33
+ def get_time_schedule(args, device):
34
+ n_timestep = args.num_timesteps
35
+ eps_small = 1e-3
36
+ t = np.arange(0, n_timestep + 1, dtype=np.float64)
37
+ t = t / n_timestep
38
+ t = torch.from_numpy(t) * (1. - eps_small) + eps_small
39
+ return t.to(device)
40
+
41
+ def get_sigma_schedule(args, device):
42
+ n_timestep = args.num_timesteps
43
+ beta_min = args.beta_min
44
+ beta_max = args.beta_max
45
+ eps_small = 1e-3
46
+
47
+ t = np.arange(0, n_timestep + 1, dtype=np.float64)
48
+ t = t / n_timestep
49
+ t = torch.from_numpy(t) * (1. - eps_small) + eps_small
50
+
51
+ if args.use_geometric:
52
+ var = var_func_geometric(t, beta_min, beta_max)
53
+ else:
54
+ var = var_func_vp(t, beta_min, beta_max)
55
+ alpha_bars = 1.0 - var
56
+ betas = 1 - alpha_bars[1:] / alpha_bars[:-1]
57
+
58
+ first = torch.tensor(1e-8)
59
+ betas = torch.cat((first[None], betas)).to(device)
60
+ betas = betas.type(torch.float32)
61
+ sigmas = betas**0.5
62
+ a_s = torch.sqrt(1-betas)
63
+ return sigmas, a_s, betas
64
+
65
+ #%% posterior sampling
66
+ class Posterior_Coefficients():
67
+ def __init__(self, args, device):
68
+
69
+ _, _, self.betas = get_sigma_schedule(args, device=device)
70
+
71
+ #we don't need the zeros
72
+ self.betas = self.betas.type(torch.float32)[1:]
73
+
74
+ self.alphas = 1 - self.betas
75
+ self.alphas_cumprod = torch.cumprod(self.alphas, 0)
76
+ self.alphas_cumprod_prev = torch.cat(
77
+ (torch.tensor([1.], dtype=torch.float32,device=device), self.alphas_cumprod[:-1]), 0
78
+ )
79
+ self.posterior_variance = self.betas * (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod)
80
+
81
+ self.sqrt_alphas_cumprod = torch.sqrt(self.alphas_cumprod)
82
+ self.sqrt_recip_alphas_cumprod = torch.rsqrt(self.alphas_cumprod)
83
+ self.sqrt_recipm1_alphas_cumprod = torch.sqrt(1 / self.alphas_cumprod - 1)
84
+
85
+ self.posterior_mean_coef1 = (self.betas * torch.sqrt(self.alphas_cumprod_prev) / (1 - self.alphas_cumprod))
86
+ self.posterior_mean_coef2 = ((1 - self.alphas_cumprod_prev) * torch.sqrt(self.alphas) / (1 - self.alphas_cumprod))
87
+
88
+ self.posterior_log_variance_clipped = torch.log(self.posterior_variance.clamp(min=1e-20))
89
+
90
+ def predict_q_posterior(coefficients, x_0, x_t, t):
91
+ mean = (
92
+ extract(coefficients.posterior_mean_coef1, t, x_t.shape) * x_0
93
+ + extract(coefficients.posterior_mean_coef2, t, x_t.shape) * x_t
94
+ )
95
+ var = extract(coefficients.posterior_variance, t, x_t.shape)
96
+ log_var_clipped = extract(coefficients.posterior_log_variance_clipped, t, x_t.shape)
97
+ return mean, var, log_var_clipped
98
+
99
+
100
+
101
+ def sample_posterior(coefficients, x_0,x_t, t):
102
+
103
+ def q_posterior(x_0, x_t, t):
104
+ mean = (
105
+ extract(coefficients.posterior_mean_coef1, t, x_t.shape) * x_0
106
+ + extract(coefficients.posterior_mean_coef2, t, x_t.shape) * x_t
107
+ )
108
+ var = extract(coefficients.posterior_variance, t, x_t.shape)
109
+ log_var_clipped = extract(coefficients.posterior_log_variance_clipped, t, x_t.shape)
110
+ return mean, var, log_var_clipped
111
+
112
+
113
+ def p_sample(x_0, x_t, t):
114
+ mean, _, log_var = q_posterior(x_0, x_t, t)
115
+
116
+ noise = torch.randn_like(x_t)
117
+
118
+ nonzero_mask = (1 - (t == 0).type(torch.float32))
119
+
120
+ return mean + nonzero_mask[:,None,None,None] * torch.exp(0.5 * log_var) * noise
121
+
122
+ sample_x_pos = p_sample(x_0, x_t, t)
123
+
124
+ return sample_x_pos
125
+
126
+ def sample_from_model(coefficients, generator, n_time, x_init, T, opt, cond=None):
127
+ x = x_init
128
+ with torch.no_grad():
129
+ for i in reversed(range(n_time)):
130
+ t = torch.full((x.size(0),), i, dtype=torch.int64).to(x.device)
131
+
132
+ t_time = t
133
+ latent_z = torch.randn(x.size(0), opt.nz, device=x.device)#.to(x.device)
134
+ x_0 = generator(x, t_time, latent_z, cond=cond)
135
+ x_new = sample_posterior(coefficients, x_0, x, t)
136
+ x = x_new.detach()
137
+
138
+ return x
139
+
140
+
141
+ def sample_from_model_classifier_free_guidance(coefficients, generator, n_time, x_init, T, opt, text_encoder, cond=None, guidance_scale=0):
142
+ x = x_init
143
+ null = text_encoder([""] * len(x_init), return_only_pooled=False)
144
+ #latent_z = torch.randn(x.size(0), opt.nz, device=x.device)
145
+ with torch.no_grad():
146
+ for i in reversed(range(n_time)):
147
+ t = torch.full((x.size(0),), i, dtype=torch.int64).to(x.device)
148
+ t_time = t
149
+
150
+ latent_z = torch.randn(x.size(0), opt.nz, device=x.device)
151
+
152
+ x_0_uncond = generator(x, t_time, latent_z, cond=null)
153
+
154
+ #latent_z = torch.randn(x.size(0), opt.nz, device=x.device)
155
+
156
+ x_0_cond = generator(x, t_time, latent_z, cond=cond)
157
+
158
+ eps_uncond = (x - torch.sqrt(coefficients.alphas_cumprod[i]) * x_0_uncond) / torch.sqrt(1 - coefficients.alphas_cumprod[i])
159
+ eps_cond = (x - torch.sqrt(coefficients.alphas_cumprod[i]) * x_0_cond) / torch.sqrt(1 - coefficients.alphas_cumprod[i])
160
+
161
+ # eps = eps_uncond + guidance_scale * (eps_cond - eps_uncond)
162
+ eps = eps_uncond * (1 - guidance_scale) + eps_cond * guidance_scale
163
+ x_0 = (1/torch.sqrt(coefficients.alphas_cumprod[i])) * (x - torch.sqrt(1 - coefficients.alphas_cumprod[i]) * eps)
164
+ #x_0 = x_0_uncond * (1 - guidance_scale) + x_0_cond * guidance_scale
165
+
166
+ # Dynamic thresholding
167
+ q = opt.dynamic_thresholding_quantile
168
+ #print("Before", x_0.min(), x_0.max())
169
+ if q:
170
+ shape = x_0.shape
171
+ x_0_v = x_0.view(shape[0], -1)
172
+ d = torch.quantile(torch.abs(x_0_v), q, dim=1, keepdim=True)
173
+ d.clamp_(min=1)
174
+ x_0_v = x_0_v.clamp(-d, d) / d
175
+ x_0 = x_0_v.view(shape)
176
+ #print("After", x_0.min(), x_0.max())
177
+
178
+ x_new = sample_posterior(coefficients, x_0, x, t)
179
+
180
+ # Dynamic thresholding
181
+ # q = args.dynamic_thresholding_percentile
182
+ # shape = x_new.shape
183
+ # x_new_v = x_new.view(shape[0], -1)
184
+ # d = torch.quantile(torch.abs(x_new_v), q, dim=1, keepdim=True)
185
+ # d = torch.maximum(d, torch.ones_like(d))
186
+ # d.clamp_(min = 1.)
187
+ # x_new_v = torch.clamp(x_new_v, -d, d) / d
188
+ # x_new = x_new_v.view(shape)
189
+ x = x_new.detach()
190
+
191
+ return x
192
+
193
+
194
+ def sample_from_model_classifier_free_guidance_convolutional(coefficients, generator, n_time, x_init, T, opt, text_encoder, cond=None, guidance_scale=0, split_input_params=None):
195
+ x = x_init
196
+ null = text_encoder([""] * len(x_init), return_only_pooled=False)
197
+ #latent_z = torch.randn(x.size(0), opt.nz, device=x.device)
198
+ ks = split_input_params["ks"] # eg. (128, 128)
199
+ stride = split_input_params["stride"] # eg. (64, 64)
200
+ uf = split_input_params["vqf"]
201
+ with torch.no_grad():
202
+ for i in reversed(range(n_time)):
203
+ t = torch.full((x.size(0),), i, dtype=torch.int64).to(x.device)
204
+ t_time = t
205
+ latent_z = torch.randn(x.size(0), opt.nz, device=x.device)
206
+
207
+ fold, unfold, normalization, weighting = get_fold_unfold(x, ks, stride, split_input_params, uf=uf)
208
+ x = unfold(x)
209
+ x = x.view((x.shape[0], -1, ks[0], ks[1], x.shape[-1]))
210
+ x_new_list = []
211
+ for j in range(x.shape[-1]):
212
+ x_0_uncond = generator(x[:,:,:,:,j], t_time, latent_z, cond=null)
213
+ x_0_cond = generator(x[:,:,:,:,j], t_time, latent_z, cond=cond)
214
+
215
+ eps_uncond = (x[:,:,:,:,j] - torch.sqrt(coefficients.alphas_cumprod[i]) * x_0_uncond) / torch.sqrt(1 - coefficients.alphas_cumprod[i])
216
+ eps_cond = (x[:,:,:,:,j] - torch.sqrt(coefficients.alphas_cumprod[i]) * x_0_cond) / torch.sqrt(1 - coefficients.alphas_cumprod[i])
217
+
218
+ eps = eps_uncond * (1 - guidance_scale) + eps_cond * guidance_scale
219
+ x_0 = (1/torch.sqrt(coefficients.alphas_cumprod[i])) * (x[:,:,:,:,j] - torch.sqrt(1 - coefficients.alphas_cumprod[i]) * eps)
220
+ q = args.dynamic_thresholding_quantile
221
+ if q:
222
+ shape = x_0.shape
223
+ x_0_v = x_0.view(shape[0], -1)
224
+ d = torch.quantile(torch.abs(x_0_v), q, dim=1, keepdim=True)
225
+ d.clamp_(min=1)
226
+ x_0_v = x_0_v.clamp(-d, d) / d
227
+ x_0 = x_0_v.view(shape)
228
+ x_new = sample_posterior(coefficients, x_0, x[:,:,:,:,j], t)
229
+ x_new_list.append(x_new)
230
+
231
+ o = torch.stack(x_new_list, axis=-1)
232
+ #o = o * weighting
233
+ o = o.view((o.shape[0], -1, o.shape[-1]))
234
+ decoded = fold(o)
235
+ decoded = decoded / normalization
236
+ x = decoded.detach()
237
+
238
+ return x
239
+
240
+ def sample_from_model_clip_guidance(coefficients, generator, clip_model, n_time, x_init, T, opt, texts, cond=None, guidance_scale=0):
241
+ x = x_init
242
+ text_features = torch.nn.functional.normalize(clip_model.forward_text(texts), dim=1)
243
+ n_time = 16
244
+ for i in reversed(range(n_time)):
245
+ t = torch.full((x.size(0),), i%4, dtype=torch.int64).to(x.device)
246
+ t_time = t
247
+ latent_z = torch.randn(x.size(0), opt.nz, device=x.device)
248
+ x.requires_grad = True
249
+ x_0 = generator(x, t_time, latent_z, cond=cond)
250
+ x_new = sample_posterior(coefficients, x_0, x, t)
251
+ x_new_n = (x_new + 1) / 2
252
+ image_features = torch.nn.functional.normalize(clip_model.forward_image(x_new_n), dim=1)
253
+ loss = (image_features*text_features).sum(dim=1).mean()
254
+ x_grad, = torch.autograd.grad(loss, x)
255
+ lr = 3000
256
+ x = x.detach()
257
+ print(x.min(),x.max(), lr*x_grad.min(), lr*x_grad.max())
258
+ x += x_grad * lr
259
+
260
+ with torch.no_grad():
261
+ x_0 = generator(x, t_time, latent_z, cond=cond)
262
+ x_new = sample_posterior(coefficients, x_0, x, t)
263
+
264
+ x = x_new.detach()
265
+ print(i)
266
+ return x
267
+
268
+ def meshgrid(h, w):
269
+ y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1)
270
+ x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1)
271
+
272
+ arr = torch.cat([y, x], dim=-1)
273
+ return arr
274
+ def delta_border(h, w):
275
+ """
276
+ :param h: height
277
+ :param w: width
278
+ :return: normalized distance to image border,
279
+ wtith min distance = 0 at border and max dist = 0.5 at image center
280
+ """
281
+ lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2)
282
+ arr = meshgrid(h, w) / lower_right_corner
283
+ dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0]
284
+ dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0]
285
+ edge_dist = torch.min(torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1)[0]
286
+ return edge_dist
287
+
288
+ def get_weighting(h, w, Ly, Lx, device, split_input_params):
289
+ weighting = delta_border(h, w)
290
+ weighting = torch.clip(weighting, split_input_params["clip_min_weight"],
291
+ split_input_params["clip_max_weight"], )
292
+ weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device)
293
+
294
+ if split_input_params["tie_braker"]:
295
+ L_weighting = delta_border(Ly, Lx)
296
+ L_weighting = torch.clip(L_weighting,
297
+ split_input_params["clip_min_tie_weight"],
298
+ split_input_params["clip_max_tie_weight"])
299
+
300
+ L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device)
301
+ weighting = weighting * L_weighting
302
+ return weighting
303
+
304
+ def get_fold_unfold(x, kernel_size, stride, split_input_params, uf=1, df=1): # todo load once not every time, shorten code
305
+ """
306
+ :param x: img of size (bs, c, h, w)
307
+ :return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1])
308
+ """
309
+ bs, nc, h, w = x.shape
310
+
311
+ # number of crops in image
312
+ Ly = (h - kernel_size[0]) // stride[0] + 1
313
+ Lx = (w - kernel_size[1]) // stride[1] + 1
314
+
315
+ if uf == 1 and df == 1:
316
+ fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
317
+ unfold = torch.nn.Unfold(**fold_params)
318
+
319
+ fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params)
320
+
321
+ weighting = get_weighting(kernel_size[0], kernel_size[1], Ly, Lx, x.device, split_input_params).to(x.dtype)
322
+ normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap
323
+ weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx))
324
+
325
+ elif uf > 1 and df == 1:
326
+ fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
327
+ unfold = torch.nn.Unfold(**fold_params)
328
+
329
+ fold_params2 = dict(kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf),
330
+ dilation=1, padding=0,
331
+ stride=(stride[0] * uf, stride[1] * uf))
332
+ fold = torch.nn.Fold(output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2)
333
+
334
+ weighting = get_weighting(kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device, split_input_params).to(x.dtype)
335
+ normalization = fold(weighting).view(1, 1, h * uf, w * uf) # normalizes the overlap
336
+ weighting = weighting.view((1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx))
337
+
338
+ elif df > 1 and uf == 1:
339
+ fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
340
+ unfold = torch.nn.Unfold(**fold_params)
341
+
342
+ fold_params2 = dict(kernel_size=(kernel_size[0] // df, kernel_size[0] // df),
343
+ dilation=1, padding=0,
344
+ stride=(stride[0] // df, stride[1] // df))
345
+ fold = torch.nn.Fold(output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2)
346
+
347
+ weighting = get_weighting(kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device, split_input_params).to(x.dtype)
348
+ normalization = fold(weighting).view(1, 1, h // df, w // df) # normalizes the overlap
349
+ weighting = weighting.view((1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx))
350
+
351
+ else:
352
+ raise NotImplementedError
353
+
354
+ return fold, unfold, normalization, weighting
355
+
356
+
357
+
358
+ #%%
359
+ def sample_and_test(args):
360
+ torch.manual_seed(args.seed)
361
+
362
+ device = 'cuda:0'
363
+ text_encoder =build_encoder(name=args.text_encoder, masked_mean=args.masked_mean).to(device)
364
+ args.cond_size = text_encoder.output_size
365
+ if args.dataset == 'cifar10':
366
+ real_img_dir = 'pytorch_fid/cifar10_train_stat.npy'
367
+ elif args.dataset == 'celeba_256':
368
+ real_img_dir = 'pytorch_fid/celeba_256_stat.npy'
369
+ elif args.dataset == 'lsun':
370
+ real_img_dir = 'pytorch_fid/lsun_church_stat.npy'
371
+ else:
372
+ real_img_dir = args.real_img_dir
373
+
374
+ to_range_0_1 = lambda x: (x + 1.) / 2.
375
+
376
+ print(vars(args))
377
+ netG = NCSNpp(args).to(device)
378
+
379
+ if args.epoch_id == -1:
380
+ epochs = range(1000)
381
+ else:
382
+ epochs = [args.epoch_id]
383
+
384
+ for epoch in epochs:
385
+ args.epoch_id = epoch
386
+ path = './saved_info/dd_gan/{}/{}/netG_{}.pth'.format(args.dataset, args.exp, args.epoch_id)
387
+ next_next_path = './saved_info/dd_gan/{}/{}/netG_{}.pth'.format(args.dataset, args.exp, args.epoch_id+2)
388
+ if not os.path.exists(path):
389
+ continue
390
+ if not os.path.exists(next_next_path):
391
+ break
392
+ print(path)
393
+
394
+ #if not os.path.exists(next_path):
395
+ # print(f"STOP at {epoch}")
396
+ # break
397
+ try:
398
+ ckpt = torch.load(path, map_location=device)
399
+ except Exception:
400
+ continue
401
+ suffix = '_' + args.eval_name if args.eval_name else ""
402
+ dest = './saved_info/dd_gan/{}/{}/eval_{}{}.json'.format(args.dataset, args.exp, args.epoch_id, suffix)
403
+ next_dest = './saved_info/dd_gan/{}/{}/eval_{}{}.json'.format(args.dataset, args.exp, args.epoch_id+1, suffix)
404
+
405
+ if (args.compute_fid or args.compute_clip_score) and os.path.exists(dest):
406
+ continue
407
+ print("Eval Epoch", args.epoch_id)
408
+ #loading weights from ddp in single gpu
409
+ #print(ckpt.keys())
410
+ for key in list(ckpt.keys()):
411
+ if key.startswith("module"):
412
+ ckpt[key[7:]] = ckpt.pop(key)
413
+ netG.load_state_dict(ckpt)
414
+ netG.eval()
415
+
416
+
417
+ T = get_time_schedule(args, device)
418
+
419
+ pos_coeff = Posterior_Coefficients(args, device)
420
+
421
+
422
+ save_dir = "./generated_samples/{}".format(args.dataset)
423
+
424
+ if not os.path.exists(save_dir):
425
+ os.makedirs(save_dir)
426
+
427
+ if args.compute_fid or args.compute_clip_score:
428
+ from torch.nn.functional import adaptive_avg_pool2d
429
+ from pytorch_fid.fid_score import calculate_activation_statistics, calculate_fid_given_paths, ImagePathDataset, compute_statistics_of_path, calculate_frechet_distance
430
+ from pytorch_fid.inception import InceptionV3
431
+ import random
432
+ random.seed(args.seed)
433
+ texts = open(args.cond_text).readlines()
434
+ texts = [t.strip() for t in texts]
435
+ if args.nb_images_for_fid:
436
+ random.shuffle(texts)
437
+ texts = texts[0:args.nb_images_for_fid]
438
+ #iters_needed = len(texts) // args.batch_size
439
+ #texts = list(map(lambda s:s.strip(), texts))
440
+ #ntimes = max(30000 // len(texts), 1)
441
+ #texts = texts * ntimes
442
+ print("Text size:", len(texts))
443
+ #print("Iters:", iters_needed)
444
+ i = 0
445
+
446
+ if args.compute_fid:
447
+ dims = 2048
448
+ block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[dims]
449
+ inceptionv3 = InceptionV3([block_idx]).to(device)
450
+
451
+ if args.compute_clip_score:
452
+ import clip
453
+ CLIP_MEAN = [0.48145466, 0.4578275, 0.40821073]
454
+ CLIP_STD = [0.26862954, 0.26130258, 0.27577711]
455
+ clip_model, preprocess = clip.load(args.clip_model, device)
456
+ clip_mean = torch.Tensor(CLIP_MEAN).view(1,-1,1,1).to(device)
457
+ clip_std = torch.Tensor(CLIP_STD).view(1,-1,1,1).to(device)
458
+
459
+ if args.compute_fid:
460
+ if not args.real_img_dir.endswith("npz"):
461
+ real_mu, real_sigma = compute_statistics_of_path(
462
+ args.real_img_dir, inceptionv3, args.batch_size, dims, device,
463
+ resize=args.image_size,
464
+ )
465
+ np.savez("inception_statistics.npz", mu=real_mu, sigma=real_sigma)
466
+ else:
467
+ stats = np.load(args.real_img_dir)
468
+ real_mu = stats['mu']
469
+ real_sigma = stats['sigma']
470
+
471
+ fake_features = []
472
+
473
+ if args.compute_clip_score:
474
+ clip_scores = []
475
+
476
+ for b in range(0, len(texts), args.batch_size):
477
+ text = texts[b:b+args.batch_size]
478
+ with torch.no_grad():
479
+ cond = text_encoder(text, return_only_pooled=False)
480
+ bs = len(text)
481
+ t0 = time.time()
482
+ x_t_1 = torch.randn(bs, args.num_channels,args.image_size, args.image_size).to(device)
483
+ if args.guidance_scale:
484
+ fake_sample = sample_from_model_classifier_free_guidance(pos_coeff, netG, args.num_timesteps, x_t_1,T, args, text_encoder, cond=cond, guidance_scale=args.guidance_scale)
485
+ else:
486
+ fake_sample = sample_from_model(pos_coeff, netG, args.num_timesteps, x_t_1,T, args, cond=cond)
487
+ fake_sample = to_range_0_1(fake_sample)
488
+ """
489
+ for j, x in enumerate(fake_sample):
490
+ index = i * args.batch_size + j
491
+ torchvision.utils.save_image(x, './generated_samples/{}/{}.jpg'.format(args.dataset, index))
492
+ """
493
+
494
+ if args.compute_fid:
495
+ with torch.no_grad():
496
+ pred = inceptionv3(fake_sample)[0]
497
+ # If model output is not scalar, apply global spatial average pooling.
498
+ # This happens if you choose a dimensionality not equal 2048.
499
+ if pred.size(2) != 1 or pred.size(3) != 1:
500
+ pred = adaptive_avg_pool2d(pred, output_size=(1, 1))
501
+ pred = pred.squeeze(3).squeeze(2).cpu().numpy()
502
+ fake_features.append(pred)
503
+
504
+ if args.compute_clip_score:
505
+ with torch.no_grad():
506
+ clip_ims = torch.nn.functional.interpolate(fake_sample, (224, 224), mode="bicubic")
507
+ clip_ims = (clip_ims - clip_mean) / clip_std
508
+ clip_txt = clip.tokenize(text, truncate=True).to(device)
509
+ imf = clip_model.encode_image(clip_ims)
510
+ txtf = clip_model.encode_text(clip_txt)
511
+ imf = torch.nn.functional.normalize(imf, dim=1)
512
+ txtf = torch.nn.functional.normalize(txtf, dim=1)
513
+ clip_scores.append(((imf * txtf).sum(dim=1)).cpu())
514
+
515
+ if i % 10 == 0:
516
+ print('evaluating batch ', i, time.time() - t0)
517
+ i += 1
518
+
519
+ results = {}
520
+ if args.compute_fid:
521
+ fake_features = np.concatenate(fake_features)
522
+ fake_mu = np.mean(fake_features, axis=0)
523
+ fake_sigma = np.cov(fake_features, rowvar=False)
524
+ fid = calculate_frechet_distance(real_mu, real_sigma, fake_mu, fake_sigma)
525
+ results['fid'] = fid
526
+ if args.compute_clip_score:
527
+ clip_score = torch.cat(clip_scores).mean().item()
528
+ results['clip_score'] = clip_score
529
+ results.update(vars(args))
530
+ with open(dest, "w") as fd:
531
+ json.dump(results, fd)
532
+ print(results)
533
+ else:
534
+ if args.cond_text.endswith(".txt"):
535
+ texts = open(args.cond_text).readlines()
536
+ texts = [t.strip() for t in texts]
537
+ else:
538
+ texts = [args.cond_text] * args.batch_size
539
+ clip_guidance = False
540
+ if clip_guidance:
541
+ from clip_encoder import CLIPImageEncoder
542
+ cond = text_encoder(texts, return_only_pooled=False)
543
+ clip_image_model = CLIPImageEncoder().to(device)
544
+ x_t_1 = torch.randn(len(texts), args.num_channels,args.image_size*args.scale_factor_h, args.image_size*args.scale_factor_w).to(device)
545
+ fake_sample = sample_from_model_clip_guidance(pos_coeff, netG, clip_image_model, args.num_timesteps, x_t_1,T, args, texts, cond=cond, guidance_scale=args.guidance_scale)
546
+ fake_sample = to_range_0_1(fake_sample)
547
+ torchvision.utils.save_image(fake_sample, './samples_{}.jpg'.format(args.dataset))
548
+
549
+ else:
550
+ cond = text_encoder(texts, return_only_pooled=False)
551
+ x_t_1 = torch.randn(len(texts), args.num_channels,args.image_size*args.scale_factor_h, args.image_size*args.scale_factor_w).to(device)
552
+ t0 = time.time()
553
+ if args.guidance_scale:
554
+ if args.scale_factor_h > 1 or args.scale_factor_w > 1:
555
+ if args.scale_method == "convolutional":
556
+ split_input_params = {
557
+ "ks": (args.image_size, args.image_size),
558
+ "stride": (150, 150),
559
+ "clip_max_tie_weight": 0.5,
560
+ "clip_min_tie_weight": 0.01,
561
+ "clip_max_weight": 0.5,
562
+ "clip_min_weight": 0.01,
563
+
564
+ "tie_braker": True,
565
+ 'vqf': 1,
566
+ }
567
+ fake_sample = sample_from_model_classifier_free_guidance_convolutional(pos_coeff, netG, args.num_timesteps, x_t_1,T, args, text_encoder, cond=cond, guidance_scale=args.guidance_scale, split_input_params=split_input_params)
568
+ elif args.scale_method == "larger_input":
569
+ netG.attn_resolutions = [r * args.scale_factor_w for r in netG.attn_resolutions]
570
+ fake_sample = sample_from_model_classifier_free_guidance(pos_coeff, netG, args.num_timesteps, x_t_1,T, args, text_encoder, cond=cond, guidance_scale=args.guidance_scale)
571
+ else:
572
+ fake_sample = sample_from_model_classifier_free_guidance(pos_coeff, netG, args.num_timesteps, x_t_1,T, args, text_encoder, cond=cond, guidance_scale=args.guidance_scale)
573
+ else:
574
+ fake_sample = sample_from_model(pos_coeff, netG, args.num_timesteps, x_t_1,T, args, cond=cond)
575
+
576
+ print(time.time() - t0)
577
+ fake_sample = to_range_0_1(fake_sample)
578
+ torchvision.utils.save_image(fake_sample, './samples_{}.jpg'.format(args.dataset))
579
+
580
+
581
+
582
+
583
+
584
+
585
+
586
+ if __name__ == '__main__':
587
+ parser = argparse.ArgumentParser('ddgan parameters')
588
+ parser.add_argument('--seed', type=int, default=1024,
589
+ help='seed used for initialization')
590
+ parser.add_argument('--compute_fid', action='store_true', default=False,
591
+ help='whether or not compute FID')
592
+ parser.add_argument('--compute_clip_score', action='store_true', default=False,
593
+ help='whether or not compute CLIP score')
594
+ parser.add_argument('--clip_model', type=str,default="ViT-L/14")
595
+ parser.add_argument('--eval_name', type=str,default="")
596
+
597
+ parser.add_argument('--epoch_id', type=int,default=1000)
598
+ parser.add_argument('--guidance_scale', type=float,default=0)
599
+ parser.add_argument('--dynamic_thresholding_quantile', type=float,default=0)
600
+ parser.add_argument('--cond_text', type=str,default="0")
601
+ parser.add_argument('--scale_factor_h', type=int,default=1)
602
+ parser.add_argument('--scale_factor_w', type=int,default=1)
603
+ parser.add_argument('--scale_method', type=str,default="convolutional")
604
+
605
+ parser.add_argument('--cross_attention', action='store_true',default=False)
606
+
607
+
608
+ parser.add_argument('--num_channels', type=int, default=3,
609
+ help='channel of image')
610
+ parser.add_argument('--centered', action='store_false', default=True,
611
+ help='-1,1 scale')
612
+ parser.add_argument('--use_geometric', action='store_true',default=False)
613
+ parser.add_argument('--beta_min', type=float, default= 0.1,
614
+ help='beta_min for diffusion')
615
+ parser.add_argument('--beta_max', type=float, default=20.,
616
+ help='beta_max for diffusion')
617
+
618
+
619
+ parser.add_argument('--num_channels_dae', type=int, default=128,
620
+ help='number of initial channels in denosing model')
621
+ parser.add_argument('--n_mlp', type=int, default=3,
622
+ help='number of mlp layers for z')
623
+ parser.add_argument('--ch_mult', nargs='+', type=int,
624
+ help='channel multiplier')
625
+
626
+ parser.add_argument('--num_res_blocks', type=int, default=2,
627
+ help='number of resnet blocks per scale')
628
+ parser.add_argument('--attn_resolutions', default=(16,),
629
+ help='resolution of applying attention')
630
+ parser.add_argument('--dropout', type=float, default=0.,
631
+ help='drop-out rate')
632
+ parser.add_argument('--resamp_with_conv', action='store_false', default=True,
633
+ help='always up/down sampling with conv')
634
+ parser.add_argument('--conditional', action='store_false', default=True,
635
+ help='noise conditional')
636
+ parser.add_argument('--fir', action='store_false', default=True,
637
+ help='FIR')
638
+ parser.add_argument('--fir_kernel', default=[1, 3, 3, 1],
639
+ help='FIR kernel')
640
+ parser.add_argument('--skip_rescale', action='store_false', default=True,
641
+ help='skip rescale')
642
+ parser.add_argument('--resblock_type', default='biggan',
643
+ help='tyle of resnet block, choice in biggan and ddpm')
644
+ parser.add_argument('--progressive', type=str, default='none', choices=['none', 'output_skip', 'residual'],
645
+ help='progressive type for output')
646
+ parser.add_argument('--progressive_input', type=str, default='residual', choices=['none', 'input_skip', 'residual'],
647
+ help='progressive type for input')
648
+ parser.add_argument('--progressive_combine', type=str, default='sum', choices=['sum', 'cat'],
649
+ help='progressive combine method.')
650
+
651
+ parser.add_argument('--embedding_type', type=str, default='positional', choices=['positional', 'fourier'],
652
+ help='type of time embedding')
653
+ parser.add_argument('--fourier_scale', type=float, default=16.,
654
+ help='scale of fourier transform')
655
+ parser.add_argument('--not_use_tanh', action='store_true',default=False)
656
+
657
+ #geenrator and training
658
+ parser.add_argument('--exp', default='experiment_cifar_default', help='name of experiment')
659
+ parser.add_argument('--real_img_dir', default='./pytorch_fid/cifar10_train_stat.npy', help='directory to real images for FID computation')
660
+
661
+ parser.add_argument('--dataset', default='cifar10', help='name of dataset')
662
+ parser.add_argument('--image_size', type=int, default=32,
663
+ help='size of image')
664
+
665
+ parser.add_argument('--nz', type=int, default=100)
666
+ parser.add_argument('--num_timesteps', type=int, default=4)
667
+
668
+
669
+ parser.add_argument('--z_emb_dim', type=int, default=256)
670
+ parser.add_argument('--t_emb_dim', type=int, default=256)
671
+ parser.add_argument('--batch_size', type=int, default=200, help='sample generating batch size')
672
+ parser.add_argument('--text_encoder', type=str, default="google/t5-v1_1-base")
673
+ parser.add_argument('--masked_mean', action='store_true',default=False)
674
+ parser.add_argument('--nb_images_for_fid', type=int, default=0)
675
+
676
+
677
+
678
+
679
+
680
+ args = parser.parse_args()
681
+
682
+ sample_and_test(args)
683
+
684
+
685
+