1: """Generate random images using the techniques described in the paper
2: "Elucidating the Design Space of Diffusion-Based Generative Models"."""
3: 
4: import os
5: import re
6: import click
7: import tqdm
8: import pickle
9: import numpy as np
10: import torch
11: import PIL.Image
12: import dnnlib
13: from torch_utils import distributed as dist
14: 
15: 
16: # ----------------------------------------------------------------------------
17: # Proposed EDM sampler (Algorithm 2).
18: 
19: def edm_sampler(
20:         net, latents, class_labels=None, randn_like=torch.randn_like,
21:         num_steps=18, sigma_min=0.002, sigma_max=80, rho=7,
22:         S_churn=0, S_min=0, S_max=float('inf'), S_noise=1,
23: ):
24:     # Adjust noise levels based on what's supported by the network.
25:     sigma_min = max(sigma_min, net.sigma_min)
26:     sigma_max = min(sigma_max, net.sigma_max)
27: 
28:     # Time step discretization.
29:     step_indices = torch.arange(num_steps, dtype=torch.float64, device=latents.device)
30:     t_steps = (sigma_max ** (1 / rho) + step_indices / (num_steps - 1) * (
31:                 sigma_min ** (1 / rho) - sigma_max ** (1 / rho))) ** rho
32:     t_steps = torch.cat([net.round_sigma(t_steps), torch.zeros_like(t_steps[:1])])  # t_N = 0
33: 
34:     # Main sampling loop.
35:     x_next = latents.to(torch.float64) * t_steps[0]
36:     for i, (t_cur, t_next) in enumerate(zip(t_steps[:-1], t_steps[1:])):  # 0, ..., N-1
37:         x_cur = x_next
38: 
39:         # Increase noise temporarily.
40:         gamma = min(S_churn / num_steps, np.sqrt(2) - 1) if S_min <= t_cur <= S_max else 0
41:         t_hat = net.round_sigma(t_cur + gamma * t_cur)
42:         x_hat = x_cur + (t_hat ** 2 - t_cur ** 2).sqrt() * S_noise * randn_like(x_cur)
43: 
44:         # Euler step.
45:         denoised = net(x_hat, t_hat, class_labels).to(torch.float64)
46:         d_cur = (x_hat - denoised) / t_hat
47:         x_next = x_hat + (t_next - t_hat) * d_cur
48: 
49:         # Apply 2nd order correction.
50:         if i < num_steps - 1:
51:             denoised = net(x_next, t_next, class_labels).to(torch.float64)
52:             d_prime = (x_next - denoised) / t_next
53:             x_next = x_hat + (t_next - t_hat) * (0.5 * d_cur + 0.5 * d_prime)
54: 
55:     return x_next
56: 
57: 
58: def ablation_sampler(
59:         net, latents, class_labels=None, randn_like=torch.randn_like,
60:         num_steps=18, sigma_min=None, sigma_max=None, rho=7,
61:         solver='heun', discretization='edm', schedule='linear', scaling='none',
62:         epsilon_s=1e-3, C_1=0.001, C_2=0.008, M=1000, alpha=1,
63:         S_churn=0, S_min=0, S_max=float('inf'), S_noise=1,
64: ):
65:     assert solver in ['euler', 'heun']
66:     assert discretization in ['vp', 've', 'iddpm', 'edm']
67:     assert schedule in ['vp', 've', 'linear']
68:     assert scaling in ['vp', 'none']
69: 
70:     # Helper functions for VP & VE noise level schedules.
71:     vp_sigma = lambda beta_d, beta_min: lambda t: (np.e ** (0.5 * beta_d * (t ** 2) + beta_min * t) - 1) ** 0.5
72:     vp_sigma_deriv = lambda beta_d, beta_min: lambda t: 0.5 * (beta_min + beta_d * t) * (sigma(t) + 1 / sigma(t))
73:     vp_sigma_inv = lambda beta_d, beta_min: lambda sigma: ((beta_min ** 2 + 2 * beta_d * (
74:                 sigma ** 2 + 1).log()).sqrt() - beta_min) / beta_d
75:     ve_sigma = lambda t: t.sqrt()
76:     ve_sigma_deriv = lambda t: 0.5 / t.sqrt()
77:     ve_sigma_inv = lambda sigma: sigma ** 2
78: 
79:     # Select default noise level range based on the specified time step discretization.
80:     if sigma_min is None:
81:         vp_def = vp_sigma(beta_d=19.1, beta_min=0.1)(t=epsilon_s)
82:         sigma_min = {'vp': vp_def, 've': 0.02, 'iddpm': 0.002, 'edm': 0.002}[discretization]
83:     if sigma_max is None:
84:         vp_def = vp_sigma(beta_d=19.1, beta_min=0.1)(t=1)
85:         sigma_max = {'vp': vp_def, 've': 100, 'iddpm': 81, 'edm': 80}[discretization]
86: 
87:     # Adjust noise levels based on what's supported by the network.
88:     sigma_min = max(sigma_min, net.sigma_min)
89:     sigma_max = min(sigma_max, net.sigma_max)
90: 
91:     # Compute corresponding betas for VP.
92:     vp_beta_d = 2 * (np.log(sigma_min ** 2 + 1) / epsilon_s - np.log(sigma_max ** 2 + 1)) / (epsilon_s - 1)
93:     vp_beta_min = np.log(sigma_max ** 2 + 1) - 0.5 * vp_beta_d
94: 
95:     # Define time steps in terms of noise level.
96:     step_indices = torch.arange(num_steps, dtype=torch.float64, device=latents.device)
97:     if discretization == 'vp':
98:         orig_t_steps = 1 + step_indices / (num_steps - 1) * (epsilon_s - 1)
99:         sigma_steps = vp_sigma(vp_beta_d, vp_beta_min)(orig_t_steps)
100:     elif discretization == 've':
101:         orig_t_steps = (sigma_max ** 2) * ((sigma_min ** 2 / sigma_max ** 2) ** (step_indices / (num_steps - 1)))
102:         sigma_steps = ve_sigma(orig_t_steps)
103:     elif discretization == 'iddpm':
104:         u = torch.zeros(M + 1, dtype=torch.float64, device=latents.device)
105:         alpha_bar = lambda j: (0.5 * np.pi * j / M / (C_2 + 1)).sin() ** 2
106:         for j in torch.arange(M, 0, -1, device=latents.device):  # M, ..., 1
107:             u[j - 1] = ((u[j] ** 2 + 1) / (alpha_bar(j - 1) / alpha_bar(j)).clip(min=C_1) - 1).sqrt()
108:         u_filtered = u[torch.logical_and(u >= sigma_min, u <= sigma_max)]
109:         sigma_steps = u_filtered[((len(u_filtered) - 1) / (num_steps - 1) * step_indices).round().to(torch.int64)]
110:     else:
111:         assert discretization == 'edm'
112:         sigma_steps = (sigma_max ** (1 / rho) + step_indices / (num_steps - 1) * (
113:                     sigma_min ** (1 / rho) - sigma_max ** (1 / rho))) ** rho
114: 
115:     # Define noise level schedule.
116:     if schedule == 'vp':
117:         sigma = vp_sigma(vp_beta_d, vp_beta_min)
118:         sigma_deriv = vp_sigma_deriv(vp_beta_d, vp_beta_min)
119:         sigma_inv = vp_sigma_inv(vp_beta_d, vp_beta_min)
120:     elif schedule == 've':
121:         sigma = ve_sigma
122:         sigma_deriv = ve_sigma_deriv
123:         sigma_inv = ve_sigma_inv
124:     else:
125:         assert schedule == 'linear'
126:         sigma = lambda t: t
127:         sigma_deriv = lambda t: 1
128:         sigma_inv = lambda sigma: sigma
129: 
130:     # Define scaling schedule.
131:     if scaling == 'vp':
132:         s = lambda t: 1 / (1 + sigma(t) ** 2).sqrt()
133:         s_deriv = lambda t: -sigma(t) * sigma_deriv(t) * (s(t) ** 3)
134:     else:
135:         assert scaling == 'none'
136:         s = lambda t: 1
137:         s_deriv = lambda t: 0
138: 
139:     # Compute final time steps based on the corresponding noise levels.
140:     t_steps = sigma_inv(net.round_sigma(sigma_steps))
141:     t_steps = torch.cat([t_steps, torch.zeros_like(t_steps[:1])])  # t_N = 0
142: 
143:     # Main sampling loop.
144:     t_next = t_steps[0]
145:     x_next = latents.to(torch.float64) * (sigma(t_next) * s(t_next))
146:     for i, (t_cur, t_next) in enumerate(zip(t_steps[:-1], t_steps[1:])):  # 0, ..., N-1
147:         x_cur = x_next
148: 
149:         # Increase noise temporarily.
150:         gamma = min(S_churn / num_steps, np.sqrt(2) - 1) if S_min <= sigma(t_cur) <= S_max else 0
151:         t_hat = sigma_inv(net.round_sigma(sigma(t_cur) + gamma * sigma(t_cur)))
152:         x_hat = s(t_hat) / s(t_cur) * x_cur + (sigma(t_hat) ** 2 - sigma(t_cur) ** 2).clip(min=0).sqrt() * s(
153:             t_hat) * S_noise * randn_like(x_cur)
154: 
155:         # Euler step.
156:         h = t_next - t_hat
157:         denoised = net(x_hat / s(t_hat), sigma(t_hat), class_labels).to(torch.float64)
158:         d_cur = (sigma_deriv(t_hat) / sigma(t_hat) + s_deriv(t_hat) / s(t_hat)) * x_hat - sigma_deriv(t_hat) * s(
159:             t_hat) / sigma(t_hat) * denoised
160:         x_prime = x_hat + alpha * h * d_cur
161:         t_prime = t_hat + alpha * h
162: 
163:         # Apply 2nd order correction.
164:         if solver == 'euler' or i == num_steps - 1:
165:             x_next = x_hat + h * d_cur
166:         else:
167:             assert solver == 'heun'
168:             denoised = net(x_prime / s(t_prime), sigma(t_prime), class_labels).to(torch.float64)
169:             d_prime = (sigma_deriv(t_prime) / sigma(t_prime) + s_deriv(t_prime) / s(t_prime)) * x_prime - sigma_deriv(
170:                 t_prime) * s(t_prime) / sigma(t_prime) * denoised
171:             x_next = x_hat + h * ((1 - 1 / (2 * alpha)) * d_cur + 1 / (2 * alpha) * d_prime)
172: 
173:     return x_next
174: 
175: 
176: class StackedRandomGenerator:
177:     def __init__(self, device, seeds):
178:         super().__init__()
179:         self.generators = [torch.Generator(device).manual_seed(int(seed) % (1 << 32)) for seed in seeds]
180: 
181:     def randn(self, size, **kwargs):
182:         assert size[0] == len(self.generators)
183:         return torch.stack([torch.randn(size[1:], generator=gen, **kwargs) for gen in self.generators])
184: 
185:     def randn_like(self, input):
186:         return self.randn(input.shape, dtype=input.dtype, layout=input.layout, device=input.device)
187: 
188:     def randint(self, *args, size, **kwargs):
189:         assert size[0] == len(self.generators)
190:         return torch.stack([torch.randint(*args, size=size[1:], generator=gen, **kwargs) for gen in self.generators])
191: 
192: 
193: def parse_int_list(s):
194:     if isinstance(s, list): return s
195:     ranges = []
196:     range_re = re.compile(r'^(\d+)-(\d+)$')
197:     repeat_re = re.compile(r'^(\d+)x(\d+)$')
198:     dup_re = re.compile(r'^d(\d+)$')
199:     num_dup = 1
200:     for p in s.split(','):
201:         m_dup = dup_re.match(p)
202:         m_range = range_re.match(p)
203:         m_repeat = repeat_re.match(p)
204:         if m_dup:
205:             num_dup = int(m_dup.group(1))
206:             continue
207:         if m_range:
208:             low = int(m_range.group(1))
209:             high = int(m_range.group(2)) + 1
210:             for num in range(low, high):
211:                 ranges.extend([num] * num_dup)
212:         elif m_repeat:
213:             num = int(m_repeat.group(1))
214:             num_rep = int(m_repeat.group(2))
215:             ranges.extend([num] * (num_dup * num_rep))
216:         else:
217:             ranges.extend([int(p)] * num_dup)
218:     return ranges
219: 
220: 
221: @click.command()
222: @click.option('--network', 'network_pkl', help='Network pickle filename', metavar='PATH|URL', type=str, required=True)
223: @click.option('--outdir', help='Where to save the output images', metavar='DIR', type=str, required=True)
224: @click.option('--seeds', help='Random seeds (e.g. 1,2,5-10)', metavar='LIST', type=parse_int_list, default='0-63',
225:               show_default=True)
226: @click.option('--subdirs', help='Create subdirectory for every 1000 seeds', is_flag=True)
227: @click.option('--batch', 'max_batch_size', help='Maximum batch size', metavar='INT', type=click.IntRange(min=1),
228:               default=64, show_default=True)
229: @click.option('--class_num', 'class_num', help='Number of the class', metavar='INT', type=click.IntRange(min=1),
230:               default=10, show_default=True)
231: @click.option('--steps', 'num_steps', help='Number of sampling steps', metavar='INT', type=click.IntRange(min=1),
232:               default=18, show_default=True)
233: @click.option('--sigma_min', help='Lowest noise level  [default: varies]', metavar='FLOAT',
234:               type=click.FloatRange(min=0, min_open=True))
235: @click.option('--sigma_max', help='Highest noise level  [default: varies]', metavar='FLOAT',
236:               type=click.FloatRange(min=0, min_open=True))
237: @click.option('--rho', help='Time step exponent', metavar='FLOAT', type=click.FloatRange(min=0, min_open=True),
238:               default=7, show_default=True)
239: @click.option('--S_churn', 'S_churn', help='Stochasticity strength', metavar='FLOAT', type=click.FloatRange(min=0),
240:               default=0, show_default=True)
241: @click.option('--S_min', 'S_min', help='Stoch. min noise level', metavar='FLOAT', type=click.FloatRange(min=0),
242:               default=0, show_default=True)
243: @click.option('--S_max', 'S_max', help='Stoch. max noise level', metavar='FLOAT', type=click.FloatRange(min=0),
244:               default='inf', show_default=True)
245: @click.option('--S_noise', 'S_noise', help='Stoch. noise inflation', metavar='FLOAT', type=float, default=1,
246:               show_default=True)
247: @click.option('--solver', help='Ablate ODE solver', metavar='euler|heun', type=click.Choice(['euler', 'heun']))
248: @click.option('--disc', 'discretization', help='Ablate time step discretization {t_i}', metavar='vp|ve|iddpm|edm',
249:               type=click.Choice(['vp', 've', 'iddpm', 'edm']))
250: @click.option('--schedule', help='Ablate noise schedule sigma(t)', metavar='vp|ve|linear',
251:               type=click.Choice(['vp', 've', 'linear']))
252: @click.option('--scaling', help='Ablate signal scaling s(t)', metavar='vp|none', type=click.Choice(['vp', 'none']))
253: def main(network_pkl, outdir, subdirs, seeds, class_num, max_batch_size, device=torch.device('cuda'), **sampler_kwargs):
254:     dist.init()
255:     print(f'seeds starts with: {seeds[:256]}')
256:     num_batches = ((len(seeds) - 1) // (max_batch_size * dist.get_world_size()) + 1) * dist.get_world_size()
257:     print(f'num_batchs: {num_batches}')
258:     # all_batches = torch.as_tensor(seeds).tensor_split(num_batches)
259:     all_batches = torch.as_tensor(seeds).split(max_batch_size, dim=0)
260:     rank_batches = all_batches[dist.get_rank():: dist.get_world_size()]
261: 
262:     # Rank 0 goes first.
263:     if dist.get_rank() != 0:
264:         torch.distributed.barrier()
265: 
266:     # Load network.
267:     dist.print0(f'Loading network from "{network_pkl}"...')
268:     with dnnlib.util.open_url(network_pkl, verbose=(dist.get_rank() == 0)) as f:
269:         net = pickle.load(f)['ema'].to(device)
270: 
271:     # Other ranks follow.
272:     if dist.get_rank() == 0:
273:         torch.distributed.barrier()
274: 
275:         # make dir
276:         os.makedirs(outdir, exist_ok=True)
277: 
278:     # Loop over batches.
279:     dist.print0(f'Generating {len(seeds)} images to "{outdir}"...')
280: 
281:     # final output.
282:     class_idx = 0
283:     other_idx = 1
284:     n_augs = 8
285: 
286:     for i_batch, batch_seeds in enumerate(tqdm.tqdm(rank_batches, unit='batch', disable=(dist.get_rank() != 0))):
287:         if os.path.exists(os.path.join(outdir, f'{i_batch}.pth')):
288:             continue
289: 
290:         torch.distributed.barrier()
291:         batch_size = len(batch_seeds)
292:         if batch_size == 0:
293:             continue
294:         assert batch_size % n_augs == 0
295: 
296:         # Pick latents and labels.
297:         rnd = StackedRandomGenerator(device, batch_seeds)
298:         latents = rnd.randn([batch_size, net.img_channels, net.img_resolution, net.img_resolution], device=device)
299:         class_labels = torch.zeros(batch_size, net.label_dim, device=device)
300:         class_others = torch.zeros(batch_size, net.label_dim, device=device)
301:         lams = torch.zeros(batch_size, 1, device=device)
302:         fns = []
303: 
304:         for sample_i in range(0, batch_size, n_augs):
305:             class_labels[sample_i: sample_i+n_augs, class_idx] = 1.0
306:             class_others[sample_i: sample_i+n_augs, other_idx] = 1.0
307:             lams[sample_i: sample_i+n_augs, 0] = torch.linspace(0, 1, n_augs, device=device)
308:             for aug_i in range(n_augs):
309:                 fns.append(f'{batch_seeds[sample_i+aug_i]}_{class_idx}_{other_idx}_{lams[aug_i].item()}.png')
310:             other_idx += 1
311:             if other_idx == net.label_dim:
312:                 class_idx += 1
313:                 other_idx = class_idx + 1
314:                 if class_idx == net.label_dim - 1:
315:                     class_idx = 0
316:                     other_idx = 1
317:         class_labels = lams * class_labels + (1 - lams) * class_others
318: 
319:         # Generate images.
320:         sampler_kwargs = {key: value for key, value in sampler_kwargs.items() if value is not None}
321:         have_ablation_kwargs = any(x in sampler_kwargs for x in ['solver', 'discretization', 'schedule', 'scaling'])
322:         sampler_fn = ablation_sampler if have_ablation_kwargs else edm_sampler
323:         images = sampler_fn(net, latents, class_labels, randn_like=rnd.randn_like, **sampler_kwargs)
324: 
325:         # Save images.
326:         images_np = (images * 127.5 + 128).clip(0, 255).to(torch.uint8).permute(0, 2, 3, 1).contiguous()
327: 
328:         images_np_list = [torch.zeros_like(images_np) for _ in range(dist.get_world_size())]
329:         torch.distributed.all_gather(images_np_list, images_np)
330:         total_image_np = np.concatenate([i.cpu().numpy() for i in images_np_list])
331: 
332:         # assert we only use single gpu
333:         batch_all_out = {}
334:         for fn, image_np in zip(fns, total_image_np):
335:             batch_all_out[fn] = image_np
336:         torch.save(batch_all_out, os.path.join(outdir, f'{i_batch}.pth'))
337: 
338: 
339:     # Done.
340:     torch.distributed.barrier()
341:     #if dist.get_rank() == 0:
342:     #    np.save(os.path.join(outdir, f'{class_idx}.npy'), np.concatenate(total_image_np))
343:     dist.print0('Done.')
344: 
345: 
346: # ----------------------------------------------------------------------------
347: 
348: if __name__ == "__main__":
349:     main()
350: 
351: # ----------------------------------------------------------------------------
352: 