jadechoghari commited on
Commit
a4ba549
·
verified ·
1 Parent(s): 5537459

Create util.py

Browse files
Files changed (1) hide show
  1. unet/util.py +300 -0
unet/util.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # adopted from
2
+ # https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py
3
+ # and
4
+ # https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
5
+ # and
6
+ # https://github.com/openai/guided-diffusion/blob/0ba878e517b276c45d1195eb29f6f5f72659a05b/guided_diffusion/nn.py
7
+ #
8
+ # thanks!
9
+
10
+
11
+ import os
12
+ import math
13
+ import torch
14
+ import torch.nn as nn
15
+ import numpy as np
16
+ from einops import repeat
17
+
18
+ def instantiate_from_config(config):
19
+ if not "target" in config:
20
+ if config == '__is_first_stage__':
21
+ return None
22
+ elif config == "__is_unconditional__":
23
+ return None
24
+ raise KeyError("Expected key `target` to instantiate.")
25
+ return get_obj_from_str(config["target"])(**config.get("params", dict()))
26
+
27
+
28
+ def make_beta_schedule(schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
29
+ if schedule == "linear":
30
+ betas = (
31
+ torch.linspace(linear_start ** 0.5, linear_end ** 0.5, n_timestep, dtype=torch.float64) ** 2
32
+ )
33
+
34
+ elif schedule == "cosine":
35
+ timesteps = (
36
+ torch.arange(n_timestep + 1, dtype=torch.float64) / n_timestep + cosine_s
37
+ )
38
+ alphas = timesteps / (1 + cosine_s) * np.pi / 2
39
+ alphas = torch.cos(alphas).pow(2)
40
+ alphas = alphas / alphas[0]
41
+ betas = 1 - alphas[1:] / alphas[:-1]
42
+ betas = np.clip(betas, a_min=0, a_max=0.999)
43
+
44
+ elif schedule == "sqrt_linear":
45
+ betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64)
46
+ elif schedule == "sqrt":
47
+ betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64) ** 0.5
48
+ else:
49
+ raise ValueError(f"schedule '{schedule}' unknown.")
50
+ return betas.numpy()
51
+
52
+
53
+ def make_ddim_timesteps(ddim_discr_method, num_ddim_timesteps, num_ddpm_timesteps, verbose=True):
54
+ verbose = True
55
+ if ddim_discr_method == 'uniform':
56
+ c = num_ddpm_timesteps // num_ddim_timesteps
57
+ ddim_timesteps = np.asarray(list(range(0, num_ddpm_timesteps, c)))
58
+ elif ddim_discr_method == 'quad':
59
+ ddim_timesteps = ((np.linspace(0, np.sqrt(num_ddim_timesteps), num_ddim_timesteps)) ** 2).astype(int)
60
+ ddim_timesteps = ddim_timesteps.max() - ddim_timesteps
61
+ ddim_timesteps.sort()
62
+ else:
63
+ raise NotImplementedError(f'There is no ddim discretization method called "{ddim_discr_method}"')
64
+
65
+ # assert ddim_timesteps.shape[0] == num_ddim_timesteps
66
+ # add one to get the final alpha values right (the ones from first scale to data during sampling)
67
+ steps_out = ddim_timesteps + 1 if ddim_timesteps[-1] != (num_ddpm_timesteps-1) else ddim_timesteps
68
+ if verbose:
69
+ print(f'Selected timesteps for ddim sampler: {steps_out}')
70
+ print(f"using {ddim_discr_method} discretization method")
71
+ return steps_out
72
+
73
+
74
+ def make_ddim_sampling_parameters(alphacums, ddim_timesteps, eta, verbose=True):
75
+ try:
76
+ # select alphas for computing the variance schedule
77
+ alphas = alphacums[ddim_timesteps]
78
+ alphas_prev = np.asarray([alphacums[0]] + alphacums[ddim_timesteps[:-1]].tolist())
79
+ except:
80
+ breakpoint()
81
+
82
+ # according the the formula provided in https://arxiv.org/abs/2010.02502
83
+ sigmas = eta * np.sqrt((1 - alphas_prev) / (1 - alphas) * (1 - alphas / alphas_prev))
84
+ if verbose:
85
+ print(f'Selected alphas for ddim sampler: a_t: {alphas}; a_(t-1): {alphas_prev}')
86
+ print(f'For the chosen value of eta, which is {eta}, '
87
+ f'this results in the following sigma_t schedule for ddim sampler {sigmas}')
88
+ return sigmas, alphas, alphas_prev
89
+
90
+
91
+ def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999):
92
+ """
93
+ Create a beta schedule that discretizes the given alpha_t_bar function,
94
+ which defines the cumulative product of (1-beta) over time from t = [0,1].
95
+ :param num_diffusion_timesteps: the number of betas to produce.
96
+ :param alpha_bar: a lambda that takes an argument t from 0 to 1 and
97
+ produces the cumulative product of (1-beta) up to that
98
+ part of the diffusion process.
99
+ :param max_beta: the maximum beta to use; use values lower than 1 to
100
+ prevent singularities.
101
+ """
102
+ betas = []
103
+ for i in range(num_diffusion_timesteps):
104
+ t1 = i / num_diffusion_timesteps
105
+ t2 = (i + 1) / num_diffusion_timesteps
106
+ betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta))
107
+ return np.array(betas)
108
+
109
+
110
+ def extract_into_tensor(a, t, x_shape):
111
+ b, *_ = t.shape
112
+ out = a.gather(-1, t)
113
+ return out.reshape(b, *((1,) * (len(x_shape) - 1)))
114
+
115
+
116
+ def checkpoint(func, inputs, params, flag):
117
+ """
118
+ Evaluate a function without caching intermediate activations, allowing for
119
+ reduced memory at the expense of extra compute in the backward pass.
120
+ :param func: the function to evaluate.
121
+ :param inputs: the argument sequence to pass to `func`.
122
+ :param params: a sequence of parameters `func` depends on but does not
123
+ explicitly take as arguments.
124
+ :param flag: if False, disable gradient checkpointing.
125
+ """
126
+ if False: # disabled checkpointing to allow requires_grad = False for main model
127
+ args = tuple(inputs) + tuple(params)
128
+ return CheckpointFunction.apply(func, len(inputs), *args)
129
+ else:
130
+ return func(*inputs)
131
+
132
+
133
+ class CheckpointFunction(torch.autograd.Function):
134
+ @staticmethod
135
+ def forward(ctx, run_function, length, *args):
136
+ ctx.run_function = run_function
137
+ ctx.input_tensors = list(args[:length])
138
+ ctx.input_params = list(args[length:])
139
+
140
+ with torch.no_grad():
141
+ output_tensors = ctx.run_function(*ctx.input_tensors)
142
+ return output_tensors
143
+
144
+ @staticmethod
145
+ def backward(ctx, *output_grads):
146
+ try:
147
+ # ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors]
148
+ ctx_input_tensors = []
149
+ for x in ctx.input_tensors:
150
+ if x.requires_grad:
151
+ ctx_input_tensors.append(x.detach().requires_grad_(True))
152
+ else:
153
+ ctx_input_tensors.append(x.detach())
154
+ ctx.input_tensors = ctx_input_tensors
155
+ except:
156
+ breakpoint()
157
+
158
+ with torch.enable_grad():
159
+ # Fixes a bug where the first op in run_function modifies the
160
+ # Tensor storage in place, which is not allowed for detach()'d
161
+ # Tensors.
162
+ shallow_copies = [x.view_as(x) for x in ctx.input_tensors]
163
+ output_tensors = ctx.run_function(*shallow_copies)
164
+
165
+ input_grads = torch.autograd.grad(
166
+ output_tensors,
167
+ ctx.input_tensors + ctx.input_params,
168
+ output_grads,
169
+ allow_unused=True,
170
+ )
171
+
172
+
173
+ del ctx.input_tensors
174
+ del ctx.input_params
175
+ del output_tensors
176
+ return (None, None) + input_grads
177
+
178
+
179
+ def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False):
180
+ """
181
+ Create sinusoidal timestep embeddings.
182
+ :param timesteps: a 1-D Tensor of N indices, one per batch element.
183
+ These may be fractional.
184
+ :param dim: the dimension of the output.
185
+ :param max_period: controls the minimum frequency of the embeddings.
186
+ :return: an [N x dim] Tensor of positional embeddings.
187
+ """
188
+ if not repeat_only:
189
+ half = dim // 2
190
+ freqs = torch.exp(
191
+ -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
192
+ ).to(device=timesteps.device)
193
+ args = timesteps[:, None].float() * freqs[None]
194
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
195
+ if dim % 2:
196
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
197
+ else:
198
+ embedding = repeat(timesteps, 'b -> b d', d=dim)
199
+ return embedding
200
+
201
+
202
+ def zero_module(module):
203
+ """
204
+ Zero out the parameters of a module and return it.
205
+ """
206
+ for p in module.parameters():
207
+ p.detach().zero_()
208
+ return module
209
+
210
+
211
+ def scale_module(module, scale):
212
+ """
213
+ Scale the parameters of a module and return it.
214
+ """
215
+ for p in module.parameters():
216
+ p.detach().mul_(scale)
217
+ return module
218
+
219
+
220
+ def mean_flat(tensor):
221
+ """
222
+ Take the mean over all non-batch dimensions.
223
+ """
224
+ return tensor.mean(dim=list(range(1, len(tensor.shape))))
225
+
226
+
227
+ def normalization(channels):
228
+ """
229
+ Make a standard normalization layer.
230
+ :param channels: number of input channels.
231
+ :return: an nn.Module for normalization.
232
+ """
233
+ return GroupNorm32(32, channels)
234
+
235
+
236
+ # PyTorch 1.7 has SiLU, but we support PyTorch 1.5.
237
+ class SiLU(nn.Module):
238
+ def forward(self, x):
239
+ return x * torch.sigmoid(x)
240
+
241
+
242
+ class GroupNorm32(nn.GroupNorm):
243
+ def forward(self, x):
244
+ return super().forward(x.float()).type(x.dtype)
245
+
246
+ def conv_nd(dims, *args, **kwargs):
247
+ """
248
+ Create a 1D, 2D, or 3D convolution module.
249
+ """
250
+ if dims == 1:
251
+ return nn.Conv1d(*args, **kwargs)
252
+ elif dims == 2:
253
+ return nn.Conv2d(*args, **kwargs)
254
+ elif dims == 3:
255
+ return nn.Conv3d(*args, **kwargs)
256
+ raise ValueError(f"unsupported dimensions: {dims}")
257
+
258
+
259
+ def linear(*args, **kwargs):
260
+ """
261
+ Create a linear module.
262
+ """
263
+ return nn.Linear(*args, **kwargs)
264
+
265
+
266
+ def avg_pool_nd(dims, *args, **kwargs):
267
+ """
268
+ Create a 1D, 2D, or 3D average pooling module.
269
+ """
270
+ if dims == 1:
271
+ return nn.AvgPool1d(*args, **kwargs)
272
+ elif dims == 2:
273
+ return nn.AvgPool2d(*args, **kwargs)
274
+ elif dims == 3:
275
+ return nn.AvgPool3d(*args, **kwargs)
276
+ raise ValueError(f"unsupported dimensions: {dims}")
277
+
278
+
279
+ class HybridConditioner(nn.Module):
280
+
281
+ def __init__(self, c_concat_config, c_crossattn_config):
282
+ super().__init__()
283
+ self.concat_conditioner = instantiate_from_config(c_concat_config)
284
+ self.crossattn_conditioner = instantiate_from_config(c_crossattn_config)
285
+
286
+ def forward(self, c_concat, c_crossattn):
287
+ c_concat = self.concat_conditioner(c_concat)
288
+ c_crossattn = self.crossattn_conditioner(c_crossattn)
289
+ return {'c_concat': [c_concat], 'c_crossattn': [c_crossattn]}
290
+
291
+
292
+ def noise_like(shape, device, repeat=False):
293
+ repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat(shape[0], *((1,) * (len(shape) - 1)))
294
+ noise = lambda: torch.randn(shape, device=device)
295
+ return repeat_noise() if repeat else noise()
296
+
297
+ if __name__ == "__main__":
298
+ timesteps = torch.randint(0, 1000, (6,)).long()
299
+ breakpoint()
300
+ t_emb = timestep_embedding(timesteps, 320, repeat_only=False)