justuswill commited on
Commit
86ddd89
·
verified ·
1 Parent(s): 60749be

Upload uqdm.py

Browse files
Files changed (1) hide show
  1. uqdm.py +1585 -0
uqdm.py ADDED
@@ -0,0 +1,1585 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torch.utils.data import Dataset, DataLoader, default_collate
4
+ from torch.distributions import constraints, TransformedDistribution, SigmoidTransform, AffineTransform
5
+ from torch.distributions import Normal, Uniform
6
+ from torch.distributions.kl import kl_divergence
7
+
8
+ # For compression to bits only
9
+ from tensorflow_compression.python.ops import gen_ops
10
+ import tensorflow as tf
11
+
12
+ from itertools import islice
13
+ from ml_collections import ConfigDict
14
+ import numpy as np
15
+ import json
16
+ import os
17
+ from pathlib import Path
18
+ from contextlib import contextmanager
19
+ import zipfile
20
+ from tqdm import tqdm
21
+
22
+ device = torch.device('cuda:0') if torch.cuda.is_available() else torch.device('cpu')
23
+
24
+ DATASET_PATH = {
25
+ 'ImageNet64': 'data/imagenet64/',
26
+ }
27
+
28
+ """
29
+ PyTorch Implementation of 'Progressive Compression with Universally Quantized Diffusion Models', Yang et al., 2025.
30
+ Written with focus on readability for a single GPU.
31
+
32
+ Sections:
33
+ Model: Denoising network
34
+ Data: ImageNet64 data
35
+ UQDM: Diffusion model + codec + simple trainer for the network + saving / loading
36
+
37
+ Major changes from previous work are highlighted in the class UQDM
38
+ """
39
+
40
+ """
41
+ Denoising network, Exponential Moving Average (EMA)
42
+ """
43
+
44
+
45
+ class VDM_Net(torch.nn.Module):
46
+ """
47
+ Based on score Net from
48
+ https://github.com/addtt/variational-diffusion-models/blob/main/vdm_unet.py
49
+ which itself is based on
50
+ https://github.com/google-research/vdm/blob/main/model_vdm.py
51
+ and maps parameters via
52
+
53
+ vdm_unet -> model_vdm
54
+ mcfg.n_attention_heads: 1 (fixed)
55
+ mcfg.embedding_dim: sm_n_embd
56
+ mcfg.n_blocks: sm_n_layer
57
+ mcfg.dropout_prob: sm_pdrop
58
+ mcfg.norm_groups: 32 (fixed, default setting for flax.linen.GroupNorm)
59
+
60
+ In addition to predicting the noise, we (optionally) predict backward variances by doubling the output channels.
61
+ """
62
+
63
+ @staticmethod
64
+ def softplus_inverse(x):
65
+ """Helper which computes the inverse of `tf.nn.softplus`."""
66
+ import math
67
+ import numpy as np
68
+ return math.log(np.expm1(x))
69
+
70
+ def softplus_init1(self, x):
71
+ # Softplus with a shift to bias the output towards 1.0.
72
+ return torch.nn.functional.softplus(x + self.SOFTPLUS_INV1)
73
+
74
+ def __init__(self, config):
75
+ super().__init__()
76
+ self.config = config
77
+ self.mcfg = mcfg = config.model
78
+
79
+ attention_params = dict(
80
+ n_heads=mcfg.n_attention_heads,
81
+ n_channels=mcfg.embedding_dim,
82
+ norm_groups=mcfg.norm_groups,
83
+ )
84
+ resnet_params = dict(
85
+ ch_in=mcfg.embedding_dim,
86
+ ch_out=mcfg.embedding_dim,
87
+ condition_dim=4 * mcfg.embedding_dim,
88
+ dropout_prob=mcfg.dropout_prob,
89
+ norm_groups=mcfg.norm_groups,
90
+ )
91
+ if mcfg.use_fourier_features:
92
+ self.fourier_features = FourierFeatures()
93
+ self.embed_conditioning = nn.Sequential(
94
+ nn.Linear(mcfg.embedding_dim, mcfg.embedding_dim * 4),
95
+ nn.SiLU(),
96
+ nn.Linear(mcfg.embedding_dim * 4, mcfg.embedding_dim * 4),
97
+ nn.SiLU(),
98
+ )
99
+ total_input_ch = mcfg.n_channels
100
+ if mcfg.use_fourier_features:
101
+ total_input_ch *= 1 + self.fourier_features.num_features
102
+ self.conv_in = nn.Conv2d(total_input_ch, mcfg.embedding_dim, 3, padding=1)
103
+
104
+ # Down path: n_blocks blocks with a resnet block and maybe attention.
105
+ self.down_blocks = nn.ModuleList(
106
+ UpDownBlock(
107
+ resnet_block=ResnetBlock(**resnet_params),
108
+ attention_block=AttentionBlock(**attention_params)
109
+ if mcfg.attention_everywhere
110
+ else None,
111
+ )
112
+ for _ in range(mcfg.n_blocks)
113
+ )
114
+
115
+ self.mid_resnet_block_1 = ResnetBlock(**resnet_params)
116
+ self.mid_attn_block = AttentionBlock(**attention_params)
117
+ self.mid_resnet_block_2 = ResnetBlock(**resnet_params)
118
+
119
+ # Up path: n_blocks+1 blocks with a resnet block and maybe attention.
120
+ resnet_params["ch_in"] *= 2 # double input channels due to skip connections
121
+ self.up_blocks = nn.ModuleList(
122
+ UpDownBlock(
123
+ resnet_block=ResnetBlock(**resnet_params),
124
+ attention_block=AttentionBlock(**attention_params)
125
+ if mcfg.attention_everywhere
126
+ else None,
127
+ )
128
+ for _ in range(mcfg.n_blocks + 1)
129
+ )
130
+
131
+ output_channels = mcfg.n_channels
132
+ if config.model.get('learned_prior_scale'):
133
+ output_channels *= 2
134
+
135
+ self.conv_out = nn.Sequential(
136
+ nn.GroupNorm(num_groups=mcfg.norm_groups, num_channels=mcfg.embedding_dim),
137
+ nn.SiLU(),
138
+ zero_init(nn.Conv2d(mcfg.embedding_dim, output_channels, kernel_size=3, padding=1)),
139
+ )
140
+
141
+ self.SOFTPLUS_INV1 = self.softplus_inverse(1.0)
142
+
143
+ def forward(self, z, g_t):
144
+ # Get gamma to shape (B, ).
145
+ g_t = g_t.expand(z.shape[0]) # assume shape () or (1,) or (B,)
146
+ assert g_t.shape == (z.shape[0],)
147
+ # Rescale to [0, 1], but only approximately since gamma0 & gamma1 are not fixed.
148
+ t = (g_t - self.mcfg.gamma_min) / (self.mcfg.gamma_max - self.mcfg.gamma_min)
149
+ t_embedding = get_timestep_embedding(t, self.mcfg.embedding_dim)
150
+ # We will condition on time embedding.
151
+ cond = self.embed_conditioning(t_embedding)
152
+
153
+ h = self.maybe_concat_fourier(z)
154
+ h = self.conv_in(h) # (B, embedding_dim, H, W)
155
+ hs = []
156
+ for down_block in self.down_blocks: # n_blocks times
157
+ hs.append(h)
158
+ h = down_block(h, cond)
159
+ hs.append(h)
160
+ h = self.mid_resnet_block_1(h, cond)
161
+ h = self.mid_attn_block(h)
162
+ h = self.mid_resnet_block_2(h, cond)
163
+ for up_block in self.up_blocks: # n_blocks+1 times
164
+ h = torch.cat([h, hs.pop()], dim=1)
165
+ h = up_block(h, cond)
166
+ h = self.conv_out(h)
167
+
168
+ if self.mcfg.get('learned_prior_scale'):
169
+ # Split the output into a mean and scale component. (B, C, H, W)
170
+ eps_hat, pred_scale_factors = torch.split(h, self.mcfg.n_channels, dim=1)
171
+ pred_scale_factors = self.softplus_init1(pred_scale_factors) # Make positive.
172
+ else:
173
+ eps_hat = h
174
+
175
+ assert eps_hat.shape == z.shape, (eps_hat.shape, z.shape)
176
+ eps_hat = eps_hat + z
177
+
178
+ if self.mcfg.get('learned_prior_scale'):
179
+ return eps_hat, pred_scale_factors
180
+ else:
181
+ return eps_hat
182
+
183
+ def maybe_concat_fourier(self, z):
184
+ if self.mcfg.use_fourier_features:
185
+ return torch.cat([z, self.fourier_features(z)], dim=1)
186
+ return z
187
+
188
+
189
+ @torch.no_grad()
190
+ def zero_init(module: nn.Module) -> nn.Module:
191
+ # Sets to zero all the parameters of a module, and returns the module.
192
+ for p in module.parameters():
193
+ nn.init.zeros_(p.data)
194
+ return module
195
+
196
+
197
+ class ResnetBlock(nn.Module):
198
+ def __init__(
199
+ self,
200
+ ch_in,
201
+ ch_out=None,
202
+ condition_dim=None,
203
+ dropout_prob=0.0,
204
+ norm_groups=32,
205
+ ):
206
+ super().__init__()
207
+ ch_out = ch_in if ch_out is None else ch_out
208
+ self.ch_out = ch_out
209
+ self.condition_dim = condition_dim
210
+ self.net1 = nn.Sequential(
211
+ nn.GroupNorm(num_groups=norm_groups, num_channels=ch_in),
212
+ nn.SiLU(),
213
+ nn.Conv2d(ch_in, ch_out, kernel_size=3, padding=1),
214
+ )
215
+ if condition_dim is not None:
216
+ self.cond_proj = zero_init(nn.Linear(condition_dim, ch_out, bias=False))
217
+ self.net2 = nn.Sequential(
218
+ nn.GroupNorm(num_groups=norm_groups, num_channels=ch_out),
219
+ nn.SiLU(),
220
+ *([nn.Dropout(dropout_prob)] * (dropout_prob > 0.0)),
221
+ zero_init(nn.Conv2d(ch_out, ch_out, kernel_size=3, padding=1)),
222
+ )
223
+ if ch_in != ch_out:
224
+ self.skip_conv = nn.Conv2d(ch_in, ch_out, kernel_size=1)
225
+
226
+ def forward(self, x, condition):
227
+ h = self.net1(x)
228
+ if condition is not None:
229
+ assert condition.shape == (x.shape[0], self.condition_dim)
230
+ condition = self.cond_proj(condition)
231
+ condition = condition[:, :, None, None]
232
+ h = h + condition
233
+ h = self.net2(h)
234
+ if x.shape[1] != self.ch_out:
235
+ x = self.skip_conv(x)
236
+ assert x.shape == h.shape
237
+ return x + h
238
+
239
+
240
+ def get_timestep_embedding(
241
+ timesteps,
242
+ embedding_dim: int,
243
+ dtype=torch.float32,
244
+ max_timescale=10_000,
245
+ min_timescale=1,
246
+ ):
247
+ # Adapted from tensor2tensor and VDM codebase.
248
+ assert timesteps.ndim == 1
249
+ assert embedding_dim % 2 == 0
250
+ timesteps *= 1000.0 # In DDPM the time step is in [0, 1000], here [0, 1]
251
+ num_timescales = embedding_dim // 2
252
+ inv_timescales = torch.logspace( # or exp(-linspace(log(min), log(max), n))
253
+ -np.log10(min_timescale),
254
+ -np.log10(max_timescale),
255
+ num_timescales,
256
+ device=timesteps.device,
257
+ )
258
+ emb = timesteps.to(dtype)[:, None] * inv_timescales[None, :] # (T, D/2)
259
+ return torch.cat([emb.sin(), emb.cos()], dim=1) # (T, D)
260
+
261
+
262
+ class FourierFeatures(nn.Module):
263
+ def __init__(self, first=5.0, last=6.0, step=1.0):
264
+ super().__init__()
265
+ self.freqs_exponent = torch.arange(first, last + 1e-8, step)
266
+
267
+ @property
268
+ def num_features(self):
269
+ return len(self.freqs_exponent) * 2
270
+
271
+ def forward(self, x):
272
+ assert len(x.shape) >= 2
273
+
274
+ # Compute (2pi * 2^n) for n in freqs.
275
+ freqs_exponent = self.freqs_exponent.to(dtype=x.dtype, device=x.device) # (F, )
276
+ freqs = 2.0 ** freqs_exponent * 2 * torch.pi # (F, )
277
+ freqs = freqs.view(-1, *([1] * (x.dim() - 1))) # (F, 1, 1, ...)
278
+
279
+ # Compute (2pi * 2^n * x) for n in freqs.
280
+ features = freqs * x.unsqueeze(1) # (B, F, X1, X2, ...)
281
+ features = features.flatten(1, 2) # (B, F * C, X1, X2, ...)
282
+
283
+ # Output features are cos and sin of above. Shape (B, 2 * F * C, H, W).
284
+ return torch.cat([features.sin(), features.cos()], dim=1)
285
+
286
+
287
+ def attention_inner_heads(qkv, num_heads):
288
+ """Computes attention with heads inside of qkv in the channel dimension.
289
+
290
+ Args:
291
+ qkv: Tensor of shape (B, 3*H*C, T) with Qs, Ks, and Vs, where:
292
+ H = number of heads,
293
+ C = number of channels per head.
294
+ num_heads: number of heads.
295
+
296
+ Returns:
297
+ Attention output of shape (B, H*C, T).
298
+ """
299
+
300
+ bs, width, length = qkv.shape
301
+ ch = width // (3 * num_heads)
302
+
303
+ # Split into (q, k, v) of shape (B, H*C, T).
304
+ q, k, v = qkv.chunk(3, dim=1)
305
+
306
+ # Rescale q and k. This makes them contiguous in memory.
307
+ scale = ch ** (-1 / 4) # scale with 4th root = scaling output by sqrt
308
+ q = q * scale
309
+ k = k * scale
310
+
311
+ # Reshape qkv to (B*H, C, T).
312
+ new_shape = (bs * num_heads, ch, length)
313
+ q = q.view(*new_shape)
314
+ k = k.view(*new_shape)
315
+ v = v.reshape(*new_shape)
316
+
317
+ # Compute attention.
318
+ weight = torch.einsum("bct,bcs->bts", q, k) # (B*H, T, T)
319
+ weight = torch.softmax(weight.float(), dim=-1).to(weight.dtype) # (B*H, T, T)
320
+ out = torch.einsum("bts,bcs->bct", weight, v) # (B*H, C, T)
321
+ return out.reshape(bs, num_heads * ch, length) # (B, H*C, T)
322
+
323
+
324
+ class Attention(nn.Module):
325
+ # Based on https://github.com/openai/guided-diffusion.
326
+
327
+ def __init__(self, n_heads):
328
+ super().__init__()
329
+ self.n_heads = n_heads
330
+
331
+ def forward(self, qkv):
332
+ assert qkv.dim() >= 3, qkv.dim()
333
+ assert qkv.shape[1] % (3 * self.n_heads) == 0
334
+ spatial_dims = qkv.shape[2:]
335
+ qkv = qkv.view(*qkv.shape[:2], -1) # (B, 3*H*C, T)
336
+ out = attention_inner_heads(qkv, self.n_heads) # (B, H*C, T)
337
+ return out.view(*out.shape[:2], *spatial_dims)
338
+
339
+
340
+ class AttentionBlock(nn.Module):
341
+ """Self-attention residual block."""
342
+
343
+ def __init__(self, n_heads, n_channels, norm_groups):
344
+ super().__init__()
345
+ assert n_channels % n_heads == 0
346
+ self.layers = nn.Sequential(
347
+ nn.GroupNorm(num_groups=norm_groups, num_channels=n_channels),
348
+ nn.Conv2d(n_channels, 3 * n_channels, kernel_size=1), # (B, 3 * C, H, W)
349
+ Attention(n_heads),
350
+ zero_init(nn.Conv2d(n_channels, n_channels, kernel_size=1)),
351
+ )
352
+
353
+ def forward(self, x):
354
+ return self.layers(x) + x
355
+
356
+
357
+ class UpDownBlock(nn.Module):
358
+ def __init__(self, resnet_block, attention_block=None):
359
+ super().__init__()
360
+ self.resnet_block = resnet_block
361
+ self.attention_block = attention_block
362
+
363
+ def forward(self, x, cond):
364
+ x = self.resnet_block(x, cond)
365
+ if self.attention_block is not None:
366
+ x = self.attention_block(x)
367
+ return x
368
+
369
+
370
+ class ExponentialMovingAverage:
371
+ """
372
+ Maintains (exponential) moving average of a set of parameters.
373
+
374
+ Code from https://github.com/yang-song/score_sde_pytorch/blob/main/models/ema.py
375
+ which is modified from https://raw.githubusercontent.com/fadel/pytorch_ema/master/torch_ema/ema.py
376
+ and partially based on https://github.com/tensorflow/tensorflow/blob/r1.13/tensorflow/python/training/moving_averages.py
377
+ """
378
+
379
+ def __init__(self, parameters, decay, use_num_updates=True):
380
+ """
381
+ Args:
382
+ parameters: Iterable of `torch.nn.Parameter`; usually the result of
383
+ `model.parameters()`.
384
+ decay: The exponential decay.
385
+ use_num_updates: Whether to use number of updates when computing
386
+ averages.
387
+ """
388
+ if decay < 0.0 or decay > 1.0:
389
+ raise ValueError('Decay must be between 0 and 1')
390
+ self.decay = decay
391
+ self.num_updates = 0 if use_num_updates else None
392
+ self.shadow_params = [p.clone().detach()
393
+ for p in parameters if p.requires_grad]
394
+ self.collected_params = []
395
+
396
+ def update(self, parameters):
397
+ """
398
+ Update currently maintained parameters.
399
+
400
+ Call this every time the parameters are updated, such as the result of
401
+ the `optimizer.step()` call.
402
+
403
+ Args:
404
+ parameters: Iterable of `torch.nn.Parameter`; usually the same set of
405
+ parameters used to initialize this object.
406
+ """
407
+ decay = self.decay
408
+ if self.num_updates is not None:
409
+ self.num_updates += 1
410
+ decay = min(decay, (1 + self.num_updates) / (10 + self.num_updates))
411
+ one_minus_decay = 1.0 - decay
412
+ with torch.no_grad():
413
+ parameters = [p for p in parameters if p.requires_grad]
414
+ for s_param, param in zip(self.shadow_params, parameters):
415
+ s_param.sub_(one_minus_decay * (s_param - param))
416
+
417
+ def copy_to(self, parameters):
418
+ """
419
+ Copy current parameters into given collection of parameters.
420
+
421
+ Args:
422
+ parameters: Iterable of `torch.nn.Parameter`; the parameters to be
423
+ updated with the stored moving averages.
424
+ """
425
+ parameters = [p for p in parameters if p.requires_grad]
426
+ for s_param, param in zip(self.shadow_params, parameters):
427
+ if param.requires_grad:
428
+ param.data.copy_(s_param.data)
429
+
430
+ def store(self, parameters):
431
+ """
432
+ Save the current parameters for restoring later.
433
+
434
+ Args:
435
+ parameters: Iterable of `torch.nn.Parameter`; the parameters to be
436
+ temporarily stored.
437
+ """
438
+ self.collected_params = [param.clone() for param in parameters]
439
+
440
+ def restore(self, parameters):
441
+ """
442
+ Restore the parameters stored with the `store` method.
443
+ Useful to validate the model with EMA parameters without affecting the
444
+ original optimization process. Store the parameters before the
445
+ `copy_to` method. After validation (or model saving), use this to
446
+ restore the former parameters.
447
+
448
+ Args:
449
+ parameters: Iterable of `torch.nn.Parameter`; the parameters to be
450
+ updated with the stored parameters.
451
+ """
452
+ for c_param, param in zip(self.collected_params, parameters):
453
+ param.data.copy_(c_param.data)
454
+
455
+ def state_dict(self):
456
+ return dict(decay=self.decay, num_updates=self.num_updates,
457
+ shadow_params=self.shadow_params)
458
+
459
+ def load_state_dict(self, state_dict):
460
+ self.decay = state_dict['decay']
461
+ self.num_updates = state_dict['num_updates']
462
+ self.shadow_params = state_dict['shadow_params']
463
+
464
+
465
+ """
466
+ Data and Checkpoint Loading
467
+ """
468
+
469
+
470
+ def cycle(iterable):
471
+ while True:
472
+ for x in iterable:
473
+ yield x
474
+
475
+
476
+ class ToIntTensor:
477
+ # for IMAGENET64
478
+ def __call__(self, image):
479
+ image = torch.as_tensor(image.reshape(3, 64, 64), dtype=torch.uint8)
480
+ return image
481
+
482
+
483
+ class NPZLoader(Dataset):
484
+ """
485
+ Load from a batched numpy dataset.
486
+ Keeps one data batch loaded in memory, so load idx sequentially for fast sampling
487
+ """
488
+
489
+ def __init__(self, path, train=True, transform=None, remove_duplicates=True):
490
+ self.path = path
491
+ if train:
492
+ self.files = list(Path(path).glob('*train*.npz'))
493
+ else:
494
+ self.files = list(Path(path).glob('*val*.npz'))
495
+ self.batch_lens = [self.npz_len(f) for f in self.files]
496
+ self.anchors = np.cumsum([0] + self.batch_lens)
497
+ self.removed_idxs = [[] for _ in range(len(self.files))]
498
+ if not train and remove_duplicates:
499
+ removed = np.load(os.path.join(path, 'removed.npy'))
500
+ self.removed_idxs = [
501
+ removed[(removed >= self.anchors[i]) & (removed < self.anchors[i + 1])] - self.anchors[i] for i in
502
+ range(len(self.files))]
503
+ self.anchors -= np.cumsum([0] + [np.size(r) for r in self.removed_idxs])
504
+ self.transform = transform
505
+ self.cache_fid = None
506
+ self.cache_npy = None
507
+
508
+ # https://stackoverflow.com/questions/68224572/how-to-determine-the-shape-size-of-npz-file
509
+ @staticmethod
510
+ def npz_len(npz):
511
+ """
512
+ Takes a path to an .npz file, which is a Zip archive of .npy files and returns the batch size of stored data,
513
+ i.e. of the first .npy found
514
+ """
515
+ with zipfile.ZipFile(npz) as archive:
516
+ for name in archive.namelist():
517
+ if not name.endswith('.npy'):
518
+ continue
519
+ npy = archive.open(name)
520
+ version = np.lib.format.read_magic(npy)
521
+ shape, fortran, dtype = np.lib.format._read_array_header(npy, version)
522
+ return shape[0]
523
+
524
+ def load_npy(self, fid):
525
+ if not fid == self.cache_fid:
526
+ self.cache_fid = fid
527
+ self.cache_npy = np.load(str(self.files[fid]))['data']
528
+ self.cache_npy = np.delete(self.cache_npy, self.removed_idxs[fid], axis=0)
529
+ return self.cache_npy
530
+
531
+ def __len__(self):
532
+ # return sum(self.batch_lens)
533
+ return self.anchors[-1]
534
+
535
+ def __getitem__(self, idx):
536
+ fid = np.argmax(idx < self.anchors) - 1
537
+ idx = idx - self.anchors[fid]
538
+ numpy_array = self.load_npy(fid)[idx]
539
+ if self.transform is not None:
540
+ torch_array = self.transform(numpy_array)
541
+ return torch_array
542
+
543
+
544
+ def load_data(dataspec, cfg):
545
+ """
546
+ Load datasets, with finite eval set and infinitely looping training set
547
+ """
548
+ if not dataspec in DATASET_PATH.keys():
549
+ raise ValueError('Unknown dataset. Add dataspec to load_data() or use one of \n%s' % list(DATASET_PATH.keys()))
550
+
551
+ if dataspec in ['ImageNet64']:
552
+ train_data, eval_data = [NPZLoader(DATASET_PATH[dataspec], train=mode, transform=ToIntTensor()) for mode in
553
+ [True, False]]
554
+ # elif: # Add more datasets here
555
+
556
+ train_iter, eval_iter = [DataLoader(d, batch_size=cfg.batch_size, shuffle=cfg.get('shuffle', False),
557
+ pin_memory=cfg.get('pin_memory', True), num_workers=cfg.get('num_workers', 1))
558
+ for d in [train_data, eval_data]]
559
+ train_iter = cycle(train_iter)
560
+
561
+ return train_iter, eval_iter
562
+
563
+
564
+ def load_checkpoint(path):
565
+ """
566
+ Load model from checkpoint.
567
+
568
+ Input:
569
+ ------
570
+ path: path to a folder containing hyperparameters as config.json and parameters as checkpoint.pt
571
+ """
572
+ with open(os.path.join(path, 'config.json'), 'r') as f:
573
+ config = ConfigDict(json.load(f))
574
+
575
+ model = UQDM(config).to(device)
576
+ cp_path = config.get('restore_ckpt', None)
577
+ if cp_path is not None:
578
+ model.load(os.path.join(path, cp_path))
579
+
580
+ return model
581
+
582
+
583
+ """
584
+ UQDM: Diffusion model, Distributions, Entropy Coding, UQDM
585
+ """
586
+
587
+ @contextmanager
588
+ def local_seed(seed, i=0):
589
+ # Allow for local randomness, use hashing to get unique local seeds for subsequent draws
590
+ if seed is None:
591
+ yield
592
+ else:
593
+ with torch.random.fork_rng():
594
+ local_seed = hash((seed, i)) % (2 ** 32)
595
+ torch.manual_seed(local_seed)
596
+ yield
597
+
598
+
599
+ class LogisticDistribution(TransformedDistribution):
600
+ """
601
+ Creates a logistic distribution parameterized by :attr:`loc` and :attr:`scale`
602
+ that define the affine transform of a standard logistic distribution.
603
+ Patterned after https://github.com/pytorch/pytorch/blob/main/torch/distributions/logistic_normal.py
604
+
605
+ Args:
606
+ loc (float or Tensor): mean of the base distribution
607
+ scale (float or Tensor): standard deviation of the base distribution
608
+
609
+ """
610
+ arg_constraints = {"loc": constraints.real, "scale": constraints.positive}
611
+
612
+ def __init__(self, loc, scale, validate_args=None):
613
+ self.loc = loc
614
+ self.scale = scale
615
+ base_dist = Uniform(torch.tensor(0, dtype=loc.dtype, device=loc.device),
616
+ torch.tensor(1, dtype=loc.dtype, device=loc.device))
617
+ if not base_dist.batch_shape:
618
+ base_dist = base_dist.expand([1])
619
+ transforms = [SigmoidTransform().inv, AffineTransform(loc=loc, scale=scale)]
620
+ super().__init__(
621
+ base_dist, transforms, validate_args=validate_args
622
+ )
623
+
624
+ @property
625
+ def mean(self):
626
+ return self.loc
627
+
628
+ def expand(self, batch_shape, _instance=None):
629
+ new = self._get_checked_instance(LogisticDistribution, _instance)
630
+ return super().expand(batch_shape, _instance=new)
631
+
632
+ def cdf(self, x):
633
+ # Should be numerically more stable than the default.
634
+ return torch.sigmoid((x - self.loc) / self.scale)
635
+
636
+ @staticmethod
637
+ def log_sigmoid(x):
638
+ # A numerically more stable implementation of torch.log(torch.sigmoid(x)).
639
+ # c.f. https://jax.readthedocs.io/en/latest/_autosummary/jax.nn.log_sigmoid.html#jax.nn.log_sigmoid
640
+ return -torch.nn.functional.softplus(-x)
641
+
642
+ def log_cdf(self, x):
643
+ standardized = (x - self.loc) / self.scale
644
+ return self.log_sigmoid(standardized)
645
+
646
+ def log_survival_function(self, x):
647
+ standardized = (x - self.loc) / self.scale
648
+ return self.log_sigmoid(- standardized)
649
+
650
+
651
+ class NormalDistribution(torch.distributions.Normal):
652
+ """
653
+ Overrides the Normal distribution to add a numerically more stable log_cdf
654
+ """
655
+
656
+ def log_cdf(self, x):
657
+ x = (x - self.loc) / self.scale
658
+ # more stable, for float32 ported from JAX, using log(1-x) ~= -x, x >> 1
659
+ # for small x
660
+ x_l = torch.clip(x, max=-10)
661
+ log_scale = -0.5 * x_l ** 2 - torch.log(-x_l) - 0.5 * np.log(2. * np.pi)
662
+ # asymptotic series
663
+ even_sum = torch.zeros_like(x)
664
+ odd_sum = torch.zeros_like(x)
665
+ x_2n = x_l ** 2
666
+ for n in range(1, 3 + 1):
667
+ y = np.prod(np.arange(2 * n - 1, 1, -2)) / x_2n
668
+ if n % 2:
669
+ odd_sum += y
670
+ else:
671
+ even_sum += y
672
+ x_2n *= x_l ** 2
673
+ x_lower = log_scale + torch.log(1 + even_sum - odd_sum)
674
+ return torch.where(
675
+ x > 5, -torch.special.ndtr(-x),
676
+ torch.where(x > -10, torch.special.ndtr(torch.clip(x, min=-10)).log(), x_lower))
677
+
678
+ def log_survival_function(self, x):
679
+ raise NotImplementedError
680
+
681
+
682
+ class UniformNoisyDistribution(torch.distributions.Distribution):
683
+ """
684
+ Add uniform noise U[-delta/2, +delta/2] to a distribution.
685
+ Adapted from https://github.com/tensorflow/compression/blob/master/tensorflow_compression/python/distributions/uniform_noise.py
686
+ Also see https://pytorch.org/docs/stable/_modules/torch/distributions/distribution.html
687
+ """
688
+
689
+ arg_constraints = {}
690
+ # arg_constraints = {"delta": torch.distributions.constraints.nonnegative}
691
+
692
+ def __init__(self, base_dist, delta):
693
+ super().__init__()
694
+ self.base_dist = base_dist
695
+ self.delta = delta # delta is the noise width.
696
+ self.half = delta / 2.
697
+ self.log_delta = torch.log(delta)
698
+
699
+ def sample(self, sample_shape=torch.Size([])):
700
+ x = self.base_dist.sample(sample_shape)
701
+ x += self.delta * torch.rand(x.shape, dtype=x.dtype, device=x.device) - self.half
702
+ return x
703
+
704
+ @property
705
+ def mean(self):
706
+ return self.base_dist.mean
707
+
708
+ def discretize(self, u, tail_mass=2 ** -8):
709
+ """
710
+ Turn the continuous distribution into a discrete one by discretizing to the grid u + k * delta.
711
+ Returns the pmf of k = round((x - p_mean) / delta + u) as this is used for UQ, ignoring outlier values in the tails.
712
+ """
713
+ # For quantiles: Because p(x) = (G(x+d/2) - G(x-d/2))/d,
714
+ # P(X <= x) = 1/d int_{x-d/2}^{x+d/2} G(u) du <= G(x+d/2) or >= G(x-d/2) which might be tighter for small d
715
+ # P(X <= G^-1(a) - d/2) <= a, P(K <= (G^-1(a) - p_mean)/d - 1/2 - p_mean/d + u) <= a
716
+ L = torch.floor((self.base_dist.icdf(tail_mass / 2) - self.base_dist.mean).min() / self.delta - 0.5)
717
+ R = torch.ceil((self.base_dist.icdf(1 - tail_mass / 2) - self.base_dist.mean).max() / self.delta + 0.5)
718
+ x = (torch.arange(L, R + 1, device=u.device).reshape(-1, *4*[1]) - u) * self.delta + self.base_dist.mean
719
+ # Assume pdf is locally linear then ln(p(x+-d/2)) = ln(p(x)*d) = ln(p(x)) + ln(d)
720
+ logits = self.log_prob(x) + torch.log(self.delta)
721
+ return OverflowCategorical(logits=logits, L=L, R=R)
722
+
723
+ def log_prob(self, y):
724
+ # return torch.log(self.base_dist.cdf(y + self.half) - self.base_dist.cdf(y - self.half)) - self.log_delta
725
+ if not hasattr(self.base_dist, "log_cdf"):
726
+ raise NotImplementedError(
727
+ "`log_prob()` is not implemented unless the base distribution implements `log_cdf()`.")
728
+ try:
729
+ return self._log_prob_with_logsf_and_logcdf(y)
730
+ except NotImplementedError:
731
+ return self._log_prob_with_logcdf(y)
732
+
733
+ @staticmethod
734
+ def _logsum_expbig_minus_expsmall(big, small):
735
+ # Numerically stable evaluation of log(exp(big) - exp(small)).
736
+ # https://github.com/tensorflow/compression/blob/a41fc70fc092bc6b72d5075deec34cbb47ef9077/tensorflow_compression/python/distributions/uniform_noise.py#L33
737
+ return torch.where(
738
+ torch.isinf(big), big, torch.log1p(-torch.exp(small - big)) + big
739
+ )
740
+
741
+ def _log_prob_with_logcdf(self, y):
742
+ return self._logsum_expbig_minus_expsmall(
743
+ self.base_dist.log_cdf(y + self.half), self.base_dist.log_cdf(y - self.half)) - self.log_delta
744
+
745
+ def _log_prob_with_logsf_and_logcdf(self, y):
746
+ """Compute log_prob(y) using log survival_function and cdf together."""
747
+ # There are two options that would be equal if we had infinite precision:
748
+ # Log[ sf(y - .5) - sf(y + .5) ]
749
+ # = Log[ exp{logsf(y - .5)} - exp{logsf(y + .5)} ]
750
+ # Log[ cdf(y + .5) - cdf(y - .5) ]
751
+ # = Log[ exp{logcdf(y + .5)} - exp{logcdf(y - .5)} ]
752
+ h = self.half
753
+ base = self.base_dist
754
+ logsf_y_plus = base.log_survival_function(y + h)
755
+ logsf_y_minus = base.log_survival_function(y - h)
756
+ logcdf_y_plus = base.log_cdf(y + h)
757
+ logcdf_y_minus = base.log_cdf(y - h)
758
+
759
+ # Important: Here we use select in a way such that no input is inf, this
760
+ # prevents the troublesome case where the output of select can be finite,
761
+ # but the output of grad(select) will be NaN.
762
+
763
+ # In either case, we are doing Log[ exp{big} - exp{small} ]
764
+ # We want to use the sf items precisely when we are on the right side of the
765
+ # median, which occurs when logsf_y < logcdf_y.
766
+ condition = logsf_y_plus < logcdf_y_plus
767
+ big = torch.where(condition, logsf_y_minus, logcdf_y_plus)
768
+ small = torch.where(condition, logsf_y_plus, logcdf_y_minus)
769
+ return self._logsum_expbig_minus_expsmall(big, small) - self.log_delta
770
+
771
+
772
+ class OverflowCategorical(torch.distributions.Categorical):
773
+ """
774
+ Discrete distribution over [L, L+1, ..., R-1, R] with LaPlace-based tail_masses for values <L and >R.
775
+ """
776
+
777
+ def __init__(self, logits, L, R):
778
+ self.L = L
779
+ self.R = R
780
+ # stable version of log(1 - sum_i exp(logp_i))
781
+ self.overflow = torch.log(torch.clip(- torch.expm1(torch.logsumexp(logits, dim=0)), min=0))
782
+ super().__init__(logits=torch.movedim(torch.cat([logits, self.overflow[None]], dim=0), 0, -1))
783
+
784
+
785
+ class EntropyModel:
786
+ """
787
+ Entropy codec for discrete data based on Arithmetic Coding / Range Coding.
788
+ Adapted from https://github.com/tensorflow/compression.
789
+ For learned backward variances every symbol has a unique coding prior that requires a unique cdf table,
790
+ which is computed in parallel here.
791
+ """
792
+
793
+ def __init__(self, prior, range_coder_precision=16):
794
+ """
795
+
796
+ Inputs:
797
+ -------
798
+ prior - [Categorical or OverflowCategorical] prior model over integers (optionally with allocated tail mass
799
+ which will be encoded via Elias gamma code embedded into the range coder).
800
+ range_coder_precision - precision passed to the range coding op, how accurately prior is quantized.
801
+ """
802
+ super().__init__()
803
+ self.prior = prior
804
+ self.prior_shape = self.prior.probs.shape[:-1]
805
+ self.precision = range_coder_precision
806
+
807
+ # Build quantization tables
808
+ total = 2 ** self.precision
809
+ probs = self.prior.probs.reshape(-1, self.prior.probs.shape[-1])
810
+ quantized_pdf = torch.round(probs * total).to(torch.int32)
811
+ quantized_pdf = torch.clip(quantized_pdf, min=1)
812
+
813
+ # Normalize pdf so that sum pmf_i = 2 ** precision
814
+ while True:
815
+ mask = quantized_pdf.sum(dim=-1) > total
816
+ if not mask.any():
817
+ break
818
+ # m * (log2(v) - log2(v-1))
819
+ penalty = probs[mask] * (torch.log2(1 + 1 / (quantized_pdf[mask] - 1)))
820
+ # inf if v = 1 as intended but handle nan if also pmf = 0
821
+ idx = penalty.nan_to_num(torch.inf).argmin(dim=-1)
822
+ quantized_pdf[mask, idx] -= 1
823
+ while True:
824
+ mask = quantized_pdf.sum(axis=-1) < total
825
+ if not mask.any():
826
+ break
827
+ # m * (log2(v+1) - log2(v))
828
+ penalty = probs[mask] * (torch.log2(1 + 1 / quantized_pdf[mask]))
829
+ idx = penalty.argmax(dim=-1)
830
+ quantized_pdf[mask, idx] += 1
831
+
832
+ quantized_cdf = torch.cumsum(quantized_pdf, dim=-1)
833
+ self.quantized_cdf = torch.cat([
834
+ - self.precision * torch.ones((quantized_pdf.shape[0], 1), device=device),
835
+ torch.zeros((quantized_pdf.shape[0], 1), device=device),
836
+ quantized_cdf
837
+ ], dim=-1).reshape(-1)
838
+ self.indexes = torch.arange(quantized_pdf.shape[0], dtype=torch.int32)
839
+ self.offsets = self.prior.L if type(self.prior) is OverflowCategorical else 0
840
+
841
+ def compress(self, x):
842
+ """
843
+ Compresses a floating-point tensor to a bit string with the discretized prior.
844
+ """
845
+ x = (x - self.offsets).to(torch.int32).reshape(-1).cpu()
846
+ codec = gen_ops.create_range_encoder([], self.quantized_cdf.cpu())
847
+ codec = gen_ops.entropy_encode_index(codec, self.indexes.cpu(), x)
848
+ bits = gen_ops.entropy_encode_finalize(codec).numpy()
849
+ return bits
850
+
851
+ def decompress(self, bits):
852
+ """
853
+ Decompresses a tensor from bit strings. This requires knowledge of the image shape,
854
+ which for arbitrary images sizes needs to be sent as side-information.
855
+ """
856
+ bits = tf.convert_to_tensor(bits, dtype=tf.string)
857
+ codec = gen_ops.create_range_decoder(bits, self.quantized_cdf.cpu())
858
+ codec, x = gen_ops.entropy_decode_index(codec, self.indexes.cpu(), self.indexes.shape, tf.int32)
859
+ # sanity = gen_ops.entropy_decode_finalize(codec)
860
+ x = torch.from_numpy(x.numpy()).reshape(self.prior_shape).to(device).to(torch.float32) + self.offsets
861
+ return x
862
+
863
+
864
+ class Diffusion(torch.nn.Module):
865
+ """
866
+ Progressive Compression with Gaussian Diffusion as in [Ho et al., 2020; Theis et al., 2022].
867
+ """
868
+
869
+ def __init__(self, config):
870
+ """
871
+ Hyperparamters are set via a config dict.
872
+
873
+ config.model
874
+ .n_timesteps - number of diffusion steps, should be the same for training and inference, default:4
875
+ .prior_type - type of base distribution g_t, 'logistic' or 'normal'
876
+ .base_prior_scale - variance of g_t, 'forward_kernel' or 'default'
877
+ .learned_prior_scale - if to learn the variance of g_t, default: true
878
+ .noise_schedule - 'fixed_linear' or 'learned_linear'
879
+ .fix_gamma_max - set if using 'learned_linear' to only learn gamma_min
880
+ .gamma_min - initial start value at t=0
881
+ .gamma_max - initial end value at t=T
882
+ .ema_rate - default: 0.9999
883
+ # network hyperparameters (c.f. VDM_Net.__init__)
884
+ .attention_everywhere -
885
+ .use_fourier_features -
886
+ .n_attention_heads -
887
+ .n_channels - default: 3
888
+ .vocab_size - default: 256
889
+ .embedding_dim -
890
+ .n_blocks -
891
+ .norm_groups -
892
+ .dropout_prob -
893
+ config.data (c.f. torch DataLoader)
894
+ .shuffle - false is recommended for faster loading with naive data loading,
895
+ .pin_memory -
896
+ .batch_size -
897
+ .num_workers -
898
+ .data_spec - "imagenet", add more in data_load
899
+ config.training
900
+ .n_steps - total steps on the training set, if continuing from a checkpoint
901
+ this should be set to desired fine-tuning steps + all previous steps
902
+ .log_metrics_every_steps - default: 1000
903
+ .checkpoint_every_steps - default: 10000
904
+ .eval_every_steps - default: 10000
905
+ .eval_steps_to_run - how many steps to evaluate on, set to None for the full eval set
906
+ config.optim (c.f. torch Adam)
907
+ .weight_decay -
908
+ .beta1 -
909
+ .eps -
910
+ .lr -
911
+ .warmup - linear learning rate warm-up, default: 1000
912
+ .grad_clip_norm - maximal gradient norm per step , default: 1.0
913
+ """
914
+ super().__init__()
915
+ self.config = config
916
+ self.score_net = VDM_Net(config)
917
+ self.gamma = self.get_noise_schedule(config)
918
+ self.ema = ExponentialMovingAverage(self.score_net.parameters(), decay=config.model.ema_rate)
919
+
920
+ # Init optimizer now to allow loading/saving optimizer state from checkpoints
921
+ self.optimizer = torch.optim.Adam(self.parameters(), lr=config.optim.lr, betas=(config.optim.beta1, 0.999),
922
+ eps=config.optim.eps, weight_decay=config.optim.weight_decay)
923
+ self.step = 0
924
+ self.denoised = None
925
+ self.compress_bits = []
926
+
927
+ def sigma2(self, t):
928
+ return torch.sigmoid(self.gamma(t))
929
+
930
+ def sigma(self, t):
931
+ return torch.sqrt(self.sigma2(t))
932
+
933
+ def alpha(self, t):
934
+ return torch.sqrt(torch.sigmoid(-self.gamma(t)))
935
+
936
+ def q_t(self, x, t=1):
937
+ # q(z_t | x) = N(alpha_t x, sigma^2_t).
938
+ return Normal(loc=self.alpha(t) * x, scale=self.sigma(t))
939
+
940
+ def p_1(self):
941
+ # p(z_1) = N(0, 1)
942
+ return Normal(torch.tensor(0.0).to(device), torch.tensor(1.0).to(device))
943
+
944
+ def p_s_t(self, p_loc, p_scale, t, s):
945
+ # p(z_s | z_t) = N(p_loc, p_scale^2)
946
+ if self.config.model.prior_type == 'logistic':
947
+ base_dist = LogisticDistribution(loc=p_loc, scale=p_scale * np.sqrt(3. / np.pi ** 2))
948
+ elif self.config.model.prior_type in ('gaussian', 'normal'):
949
+ base_dist = NormalDistribution(loc=p_loc, scale=p_scale)
950
+ else:
951
+ try:
952
+ base_dist = getattr(torch.distributions, self.config.model.prior_type)
953
+ except AttributeError:
954
+ raise ValueError(f"Unknown prior type {self.config.model.prior_type}")
955
+ return base_dist
956
+
957
+ def q_s_t(self, q_loc, q_scale):
958
+ # q(z_s | z_t, x) = N(q_loc, q_scale^2)
959
+ return NormalDistribution(loc=q_loc, scale=q_scale)
960
+
961
+ def relative_entropy_coding(self, q, p, compress_mode=None):
962
+ # Exponential runtime with naive REC algorithms
963
+ raise NotImplementedError
964
+
965
+ def get_s_t_params(self, z_t, t, s, x=None, clip_denoised=True, cache_denoised=False, deterministic=False):
966
+ """
967
+ Compute the (location, scale) parameters of either q(z_s | z_t, x)
968
+ or the reverse process distribution p(z_s | z_t) = q(z_s | z_t, x=x_hat) for the given z_t and times t, s.
969
+
970
+ Inputs:
971
+ -------
972
+ x - if not None compute the parameters of q(z_t | z, x) instead p(z_s | z_t)
973
+ clip_denoised - if True, will clip the denoised prediction x_hat(z_t) to [-1, 1];
974
+ this might be used to draw better samples.
975
+ cache_denoised - keep the denoised prediction in memory for later use
976
+ deterministic - if True, compute the mean needed for flow-based sampling instead, removing less noise overall
977
+ """
978
+ gamma_t, gamma_s = self.gamma(t), self.gamma(s)
979
+ alpha_t, alpha_s = self.alpha(t), self.alpha(s)
980
+ sigma_t, sigma_s = self.sigma(t), self.sigma(s)
981
+ # expm1 = 1 - alpha_t^2 / alpha_s^2 * sigma_s^2 / sigma_t^2 = sigma_t|s^2 / sigma_t^2
982
+ expm1_term = - torch.special.expm1(gamma_s - gamma_t)
983
+
984
+ # Parameters of q(z_s | z_t, x)
985
+ # q_var = sigma_s^2 * sigma^2_t|s / sigma^2_t, c.f. VDM eq (25)
986
+ # = sigma_s^2 * expm1_term, c.f. VDM eq (33)
987
+ # q_loc = alpha_t / alpha_s * sigma_s^2 / sigma_t^2 * z_t + alpha_s * sigma_t|s^2 / sigma_t^2 * x, c.f. VDM eq (26)
988
+ # = alpha_s * ((1 - expm1_term) / alpha_t * z_t + expm1_term * x)
989
+ # = alpha_s / alpha_t * (z_t - sigma_t|s^2 / sigma_t * eps), c.f. VDM eq (29)
990
+ # = alpha_s / alpha_t * (z_t - sigma_t * expm1_term * eps), c.f. VDM eq (32)
991
+
992
+ # = alpha_s / alpha_t * (z_t - sigma_t * eps) + c * eps,
993
+ # with c = alpha_s / alpha_t * sigma_t * (1 - expm1_term) = alpha_t / alpha_s * sigma_s^2 / sigma_t
994
+ # = alpha_s / alpha_t * x + c * eps,
995
+ # for flow-based set var = 0 and c = sigma_s, c.f. DDIM eq (12)
996
+ # -> loc = alpha_s / alpha_t * z_t + (sigma_s - alpha_s / alpha_t * sigma_t) * eps
997
+ # = alpha_s / alpha_t * z_t + (sigma_s - alpha_s / alpha_t * sigma_t) * (z_t - alpha_t * x) / sigma_t
998
+ # = alpha_s / alpha_t * z_t + (sigma_s / sigma_t - alpha_s / alpha_t) * (z_t - alpha_t * x)
999
+ # = (alpha_s / alpha_t + sigma_s / sigma_t - alpha_s / alpha_t) * z_t - alpha_t * (sigma_s / sigma_t - alpha_s / alpha_t) * x
1000
+ # = sigma_s / sigma_t * z_t - (alpha_t * sigma_s / sigma_t - alpha_s) * x
1001
+
1002
+ # Set x = x_hat or eps = eps_hat for p(z_s | z_t)
1003
+ if x is None:
1004
+ if self.config.model.get('learned_prior_scale'):
1005
+ eps_hat, pred_scale_factors = self.score_net(z_t, gamma_t)
1006
+ else:
1007
+ eps_hat = self.score_net(z_t, gamma_t)
1008
+ # Compute denoised prediction only if necessary
1009
+ if clip_denoised or cache_denoised:
1010
+ x = (z_t - sigma_t * eps_hat) / alpha_t # c.f. VDM eq (30)
1011
+ if clip_denoised:
1012
+ x.clamp_(-1.0, 1.0)
1013
+ if cache_denoised:
1014
+ self.denoised = x
1015
+
1016
+ # Variance of q(z_s | z_t, x)
1017
+ scale = sigma_s * torch.sqrt(expm1_term)
1018
+ # Additional modifications for p(z_s | z_t)
1019
+ if self.config.model.get('base_prior_scale', 'forward_kernel') == 'forward_kernel':
1020
+ # use sigma_t|s^2, the variance of q(z_t | z_s) instead
1021
+ scale = sigma_t * torch.sqrt(expm1_term)
1022
+ if self.config.model.get('learned_prior_scale'):
1023
+ scale = scale * pred_scale_factors
1024
+ else:
1025
+ scale = sigma_s * torch.sqrt(expm1_term)
1026
+
1027
+ # Mean of q(z_s | z_t, x)
1028
+ if x is not None:
1029
+ if deterministic:
1030
+ loc = sigma_s / sigma_t * z_t - (alpha_t * sigma_s / sigma_t - alpha_s) * x
1031
+ else:
1032
+ loc = alpha_s * ((1 - expm1_term) / alpha_t * z_t + expm1_term * x)
1033
+ else:
1034
+ if deterministic:
1035
+ loc = alpha_s / alpha_t * z_t + (sigma_s - alpha_s / alpha_t * sigma_t) * eps_hat
1036
+ else:
1037
+ loc = alpha_s / alpha_t * (z_t - sigma_t * expm1_term * eps_hat)
1038
+
1039
+ return loc, scale
1040
+
1041
+ def transmit_q_s_t(self, x, z_t, t, s, compress_mode=None, cache_denoised=False):
1042
+ """
1043
+ Perform a single transmission step of drawing a sample of z_t given z_s from q(z_t | z_s, x),
1044
+ under the conditional prior p(z_t | z_s).
1045
+ This will be approximated by REC/channel simulation at test time for actual compression.
1046
+
1047
+ Inputs:
1048
+ -------
1049
+ x - the continuous data; belongs to the diffusion space (usually scaled to [-1, 1])
1050
+ z_t - the previously communicated latent state
1051
+ t, s - the previous and current time steps, in [0, 1]; s < t.
1052
+ compress_mode - if to compress to bits in inference mode (which is slower), one of [None, 'encode', 'decode']
1053
+
1054
+ Returns:
1055
+ --------
1056
+ z_s - the new latent state
1057
+ rate - (estimate of) the KL divergence between q(z_s | z_t, x) and p(z_s | z_t)
1058
+ """
1059
+ # Compute parameters of q(z_s | z_t, x) and the prior p(z_s | z_t)
1060
+ p_loc, p_scale = self.get_s_t_params(z_t, t, s, cache_denoised=cache_denoised)
1061
+ q_loc, q_scale = self.get_s_t_params(z_t, t, s, x=x)
1062
+ p_s_t = self.p_s_t(p_loc, p_scale, t, s)
1063
+ q_s_t = self.q_s_t(q_loc, q_scale)
1064
+ z_s, rate = self.relative_entropy_coding(q_s_t, p_s_t, compress_mode=compress_mode)
1065
+ return z_s, rate
1066
+
1067
+ def transmit_image(self, z_0, x_raw, compress_mode=None):
1068
+ if compress_mode in ['encode', 'decode']:
1069
+ p = torch.distributions.Categorical(logits=self.log_probs_x_z0(z_0=z_0))
1070
+ if compress_mode == 'decode':
1071
+ # consume bits
1072
+ x_raw = self.entropy_decode(self.compress_bits.pop(0), p)
1073
+ elif compress_mode == 'encode':
1074
+ # accumulate bits
1075
+ self.compress_bits += [self.entropy_encode(x_raw, p)]
1076
+ return x_raw
1077
+
1078
+ def forward(self, x_raw, z_1=None, recon_method=None, compress_mode=None, seed=None):
1079
+ """
1080
+ Run a given data batch through the encoding/decoding path and compute the loss and other metrics.
1081
+
1082
+ Inputs:
1083
+ -------
1084
+ x - batch of shape [B, C, H, W]
1085
+ z_1 - if provided, will use this as the topmost latent state instead of sampling from q(z_1 | x).
1086
+ recon_method - (optional) one of ['ancestral', 'denoise', 'flow-based']; determines how a progressive
1087
+ reconstruction will be computed based on an intermediate latent state.
1088
+ compress_mode - if to compress to bits in inference mode (which is slower), one of [None, 'encode', 'decode']
1089
+ seed - allow for common randomness
1090
+ """
1091
+ rescale_to_bpd = 1. / (np.prod(x_raw.shape[1:]) * np.log(2.))
1092
+
1093
+ # Transform from uint8 in [0, 255] to float in [-1, 1]; the first r.v. of the diffusion process.
1094
+ x = 2 * ((x_raw.float() + .5) / self.config.model.vocab_size) - 1
1095
+
1096
+ # 1. PRIOR/LATENT LOSS
1097
+ # KL z1 with N(0,1) prior; should be close to 0.
1098
+ if z_1 is None and not torch.is_inference_mode_enabled():
1099
+ # During training me might want to optimize the noise schedule so use the full NELBO
1100
+ q_1 = self.q_t(x)
1101
+ p_1 = self.p_1()
1102
+ with local_seed(seed, i=0):
1103
+ z_1 = q_1.sample()
1104
+ loss_prior = kl_divergence(q_1, p_1).sum(dim=[1, 2, 3])
1105
+ else:
1106
+ # In actual compression, we can't do REC for the Gaussian q(z_1|x) under p(z_1), so
1107
+ # instead both encoder/decoder will draw from p(z_1).
1108
+ if z_1 is None:
1109
+ p_1 = self.p_1()
1110
+ with local_seed(seed, i=0):
1111
+ z_1 = p_1.sample(x.shape)
1112
+ loss_prior = torch.zeros(x.shape[0], device=device)
1113
+
1114
+ # 2. DIFFUSION LOSS
1115
+ # Sample through the hierarchy and sum together KL[q(z_s | z_t, x)||p(z_s | z_t)) for the diffusion loss.
1116
+ z_s = z_1
1117
+ rate_s = loss_prior
1118
+ loss_diff = 0.
1119
+ times = torch.linspace(1, 0, self.config.model.n_timesteps + 1, device=device)
1120
+ assert len(times) >= 2, "Need at least one diffusion step."
1121
+ metrics = []
1122
+ for i in range(len(times) - 1):
1123
+ z_t = z_s
1124
+ rate_t = rate_s
1125
+ t, s = times[i], times[i + 1]
1126
+ with local_seed(seed, i=i + 1):
1127
+ z_s, rate_s = self.transmit_q_s_t(x, z_t, t, s, compress_mode=compress_mode,
1128
+ cache_denoised=recon_method == 'denoise')
1129
+ loss_diff += rate_s
1130
+
1131
+ if recon_method is not None:
1132
+ x_hat_t = self.denoise_z_t(z_t, recon_method, times=times[i:])
1133
+ metrics += [{
1134
+ 'prog_bpds': rate_t.cpu() * rescale_to_bpd,
1135
+ 'prog_x_hats': x_hat_t.detach().cpu(),
1136
+ 'prog_mses': torch.mean((x_hat_t - x_raw).float() ** 2, dim=[1, 2, 3]).cpu(),
1137
+ }]
1138
+
1139
+ z_0 = z_s
1140
+ if recon_method is not None:
1141
+ if recon_method == 'ancestral':
1142
+ x_hat_t = self.decode_p_x_z_0(z_0=z_0, method='sample')
1143
+ else:
1144
+ x_hat_t = self.decode_p_x_z_0(z_0=z_0, method='argmax')
1145
+ metrics += [{
1146
+ 'prog_bpds': rate_s.cpu() * rescale_to_bpd,
1147
+ 'prog_x_hats': x_hat_t.detach().cpu(),
1148
+ 'prog_mses': torch.mean((x_hat_t - x_raw).float() ** 2, dim=[1, 2, 3]).cpu(),
1149
+ }]
1150
+
1151
+ # 3. RECONSTRUCTION LOSS.
1152
+ # Using the same likelihood model as in VDM.
1153
+ log_probs = self.log_probs_x_z0(z_0=z_0, x_raw=x_raw)
1154
+ loss_recon = -log_probs.sum(dim=[1, 2, 3])
1155
+ x_raw = self.transmit_image(z_0, x_raw, compress_mode=compress_mode)
1156
+ if recon_method is not None:
1157
+ metrics += [{
1158
+ 'prog_bpds': loss_recon.cpu() * rescale_to_bpd,
1159
+ 'prog_x_hats': x_raw.cpu(),
1160
+ 'prog_mses': torch.zeros(x.shape[:1]),
1161
+ }]
1162
+ metrics = default_collate(metrics)
1163
+ else:
1164
+ metrics = {}
1165
+
1166
+ bpd_latent = torch.mean(loss_prior) * rescale_to_bpd
1167
+ bpd_recon = torch.mean(loss_recon) * rescale_to_bpd
1168
+ bpd_diff = torch.mean(loss_diff) * rescale_to_bpd
1169
+ loss = bpd_recon + bpd_latent + bpd_diff
1170
+ metrics.update({
1171
+ "bpd": loss,
1172
+ "bpd_latent": bpd_latent,
1173
+ "bpd_recon": bpd_recon,
1174
+ "bpd_diff": bpd_diff,
1175
+ })
1176
+
1177
+ return loss, metrics
1178
+
1179
+ @torch.no_grad()
1180
+ def sample(self, init_z=None, shape=None, times=None, deterministic=False,
1181
+ clip_samples=False, decode_method='argmax', return_hist=False):
1182
+ """
1183
+ Perform ancestral / flow-based sampling.
1184
+
1185
+ Inputs:
1186
+ -------
1187
+ init_z - latent state [B, C, H, W]
1188
+ shape - if no init_z is given specify the shape of z instead
1189
+ times - (optional) provide a custom (e.g. partial) sequence of steps
1190
+ deterministic - use flow-based sampling instead of ancestral sampling
1191
+ clip_samples - clip latents to [-1, 1]
1192
+ decode_method - 'argmax' or 'sample'
1193
+ return_hist - if set return full history of latent states
1194
+ """
1195
+ if init_z is None:
1196
+ assert shape is not None
1197
+ p_1 = self.p_1()
1198
+ z = p_1.sample(shape)
1199
+ else:
1200
+ z = init_z
1201
+ if return_hist:
1202
+ samples = [z]
1203
+ if times is None:
1204
+ times = torch.linspace(1.0, 0.0, self.config.model.n_timesteps + 1, device=device)
1205
+
1206
+ # for i in trange(len(times) - 1, desc="sampling"):
1207
+ for i in range(len(times) - 1):
1208
+ t, s = times[i], times[i + 1]
1209
+ p_loc, p_scale = self.get_s_t_params(z, t, s, clip_denoised=clip_samples, deterministic=deterministic)
1210
+ if deterministic:
1211
+ z = p_loc
1212
+ else:
1213
+ z = self.p_s_t(p_loc, p_scale, t, s).sample()
1214
+ if return_hist:
1215
+ samples.append(z)
1216
+ x_raw = self.decode_p_x_z_0(z_0=z, method=decode_method)
1217
+
1218
+ if return_hist:
1219
+ return x_raw, samples + [x_raw]
1220
+ else:
1221
+ return x_raw
1222
+
1223
+ def entropy_encode(self, k, p):
1224
+ """
1225
+ Encode integer array k to bits using a prior / coding distribution p.
1226
+ We might want to quantize scale for determinism and added stability across multiple machines.
1227
+ """
1228
+ # When using a scalar prior it would be better to quantize u as in tfc.UniversalBatchedEntropyModel
1229
+ assert self.config.model.learned_prior_scale
1230
+ em = EntropyModel(p)
1231
+ bitstring = em.compress(k)
1232
+ return bitstring
1233
+
1234
+ def entropy_decode(self, bits, p):
1235
+ """
1236
+ Decode integer array from bits using the prior p.
1237
+ """
1238
+ assert self.config.model.learned_prior_scale
1239
+ em = EntropyModel(p)
1240
+ k = em.decompress(bits)
1241
+ return k
1242
+
1243
+ @torch.inference_mode()
1244
+ def compress(self, image):
1245
+ # return the bits for each step
1246
+ self.compress_bits = []
1247
+ # accumulate bits
1248
+ self.forward(image.to(device), compress_mode='encode', seed=0)
1249
+ return self.compress_bits
1250
+
1251
+ @torch.inference_mode()
1252
+ def decompress(self, bits, image_shape, recon_method='denoise'):
1253
+ # consume the bits for each step, return the intermediate reconstructions for each step
1254
+ self.compress_bits = bits.copy()
1255
+ # consume the bits for each step
1256
+ _, metrics = self.forward(torch.zeros(image_shape, device=device), compress_mode='decode',
1257
+ recon_method=recon_method, seed=0)
1258
+ return metrics['prog_x_hats']
1259
+
1260
+ def log_probs_x_z0(self, z_0, x_raw=None):
1261
+ """
1262
+ Computes log p(x_raw | z_0), under the Gaussian approximation of q(z_0|x) introduced in VDM, section 3.3.
1263
+ If `x_raw` is not provided, this method computes the log probs of every
1264
+ possible value of x_raw under a factorized categorical distribution; otherwise,
1265
+ it will evaluate the log probs of the given `x_raw`.
1266
+
1267
+ Internally we compute p(x_i | z_0i), with i = pixel index, for all possible values
1268
+ of x_i in the vocabulary. We approximate this with q(z_0i | x_i).
1269
+ Un-normalized logits are: -1/2 SNR_0 (z_0 / alpha_0 - k)^2
1270
+ where k takes all possible x_i values. Logits are then normalized to logprobs.
1271
+
1272
+ If `x_raw` is None, the method returns a tensor of shape (B, C, H, W,
1273
+ vocab_size) containing, for each pixel, the log probabilities for all
1274
+ `vocab_size` possible values of that pixel. The output sums to 1 over
1275
+ the last dimension. Otherwise, we will select the log probs of the given `x_raw`.
1276
+
1277
+ Inputs:
1278
+ -------
1279
+ z_0 - z_0 to be decoded, shape (B, C, H, W).
1280
+ x_raw - Input uint8 image, shape (B, C, H, W).
1281
+
1282
+ Returns:
1283
+ --------
1284
+ log_probs - Log probabilities [B, C, H, W, vocab_size] if `x_raw` is None else [B, C, H, W]
1285
+ """
1286
+ gamma_0 = self.gamma(torch.tensor([0.0], device=device))
1287
+ z_0_rescaled = z_0 / torch.sqrt(torch.sigmoid(-gamma_0))
1288
+ # Compute a tensor of log p(x | z) for all possible values of x.
1289
+ # Logits are exact if there are no dependencies between dimensions of x
1290
+ x_vals = torch.arange(self.config.model.vocab_size, device=z_0_rescaled.device)
1291
+ x_vals = 2 * ((x_vals + .5) / self.config.model.vocab_size) - 1
1292
+ x_vals = torch.reshape(x_vals, [1] * z_0_rescaled.ndim + [-1])
1293
+ z = z_0_rescaled.unsqueeze(-1) # (B, D1, ..., D_n) -> (B, D1, ..., D_n, 1) for broadcasting
1294
+ logits = -0.5 * torch.exp(-gamma_0) * (z - x_vals) ** 2 # (B, D1, ..., D_n, V)
1295
+ logprobs = torch.log_softmax(logits, dim=-1) # (B, C, H, W, V)
1296
+
1297
+ if x_raw is None:
1298
+ # Has an extra dimension for vocab_size.
1299
+ return logprobs
1300
+ else:
1301
+ # elementwise log prob, same shape as x_raw
1302
+ x_one_hot = nn.functional.one_hot(x_raw.long(), num_classes=self.config.model.vocab_size)
1303
+ # Select the correct log probabilities.
1304
+ log_probs = (x_one_hot * logprobs).sum(-1) # (B, C, H, W)
1305
+ return log_probs
1306
+
1307
+ def decode_p_x_z_0(self, z_0, method='argmax'):
1308
+ """
1309
+ Decode the given latent state z_0 to the data space,
1310
+ using the observation model p(x | z_0).
1311
+
1312
+ Inputs:
1313
+ -------
1314
+ z_0 - the latent state [B, C, H, W]
1315
+ method - 'argmax' or 'sample'
1316
+
1317
+ Returns:
1318
+ --------
1319
+ x_raw - the decoded x, mapped to data (integer) space
1320
+ """
1321
+ logprobs = self.log_probs_x_z0(z_0=z_0) # (B, C, H, W, vocab_size)
1322
+ if method == 'argmax':
1323
+ x_raw = torch.argmax(logprobs, dim=-1) # (B, C, H, W)
1324
+ elif method == 'sample':
1325
+ x_raw = torch.distributions.Categorical(logits=logprobs).sample()
1326
+ else:
1327
+ raise ValueError(f"Unknown decoding method {method}")
1328
+ return x_raw
1329
+
1330
+ def denoise_z_t(self, z_t, recon_method, times=None):
1331
+ """
1332
+ Make a progressive data reconstruction based on z_t and compute its reconstruction quality.
1333
+
1334
+ Inputs:
1335
+ -------
1336
+ z_t - noisy diffusion latent variable
1337
+ recon_method - one of 'denoise', 'ancestral', 'flow_based'
1338
+ times - remaining time steps including current t, for ancestral / flow-based sampling
1339
+ """
1340
+ if recon_method == 'ancestral':
1341
+ x_hat_t = self.sample(
1342
+ times=times, init_z=z_t,
1343
+ clip_samples=True, decode_method='argmax', return_hist=False
1344
+ )
1345
+ elif recon_method == 'flow_based':
1346
+ x_hat_t = self.sample(
1347
+ times=times, init_z=z_t, deterministic=True,
1348
+ clip_samples=False, decode_method='argmax', return_hist=False
1349
+ )
1350
+ elif recon_method == 'denoise':
1351
+ # Load from cache
1352
+ assert self.denoised is not None
1353
+ # Map to data space
1354
+ x_hat_t = self.decode_p_x_z_0(z_0=self.denoised, method='argmax')
1355
+ self.denoised = None
1356
+ else:
1357
+ raise ValueError(f"Unknown progressive reconstruction method {recon_method}")
1358
+
1359
+ return x_hat_t
1360
+
1361
+ @staticmethod
1362
+ def get_noise_schedule(config):
1363
+ # gamma is the negative log-snr as in VDM eq (3)
1364
+ gamma_min, gamma_max, schedule = [getattr(config.model, k) for k in
1365
+ ['gamma_min', 'gamma_max', 'noise_schedule']]
1366
+ assert gamma_max > gamma_min, "SNR should be decreasing in time"
1367
+ if schedule == "fixed_linear":
1368
+ gamma = Diffusion.FixedLinearSchedule(gamma_min, gamma_max)
1369
+ elif schedule == "learned_linear":
1370
+ gamma = Diffusion.LearnedLinearSchedule(gamma_min, gamma_max, config.model.get('fix_gamma_max'))
1371
+ # elif: # add different noise schedules here
1372
+ else:
1373
+ raise ValueError('Unknown noise schedule %s' % schedule)
1374
+ return gamma
1375
+
1376
+ class FixedLinearSchedule(torch.nn.Module):
1377
+ def __init__(self, gamma_min, gamma_max):
1378
+ super().__init__()
1379
+ self.gamma_min = gamma_min
1380
+ self.gamma_max = gamma_max
1381
+
1382
+ def forward(self, t):
1383
+ return self.gamma_min + (self.gamma_max - self.gamma_min) * t
1384
+
1385
+ class LearnedLinearSchedule(torch.nn.Module):
1386
+ def __init__(self, gamma_min, gamma_max, fix_gamma_max=False):
1387
+ super().__init__()
1388
+ self.fix_gamma_max = fix_gamma_max
1389
+ if fix_gamma_max:
1390
+ self.gamma_max = torch.tensor(gamma_max)
1391
+ else:
1392
+ self.b = torch.nn.Parameter(torch.tensor(gamma_min))
1393
+ self.w = torch.nn.Parameter(torch.tensor(gamma_max - gamma_min))
1394
+
1395
+ def forward(self, t):
1396
+ w = self.w.abs()
1397
+ if self.fix_gamma_max:
1398
+ return w * (t - 1.) + self.gamma_max
1399
+ else:
1400
+ return self.b + w * t
1401
+
1402
+ def save(self):
1403
+ torch.save({
1404
+ 'model': self.score_net.state_dict(),
1405
+ 'ema': self.ema.state_dict(),
1406
+ 'optimizer': self.optimizer.state_dict(),
1407
+ 'step': self.step
1408
+ }, self.self.config.checkpoint_path)
1409
+
1410
+ def load(self, path):
1411
+ cp = torch.load(path, map_location=device, weights_only=False)
1412
+ # score_net + gamma
1413
+ self.score_net.load_state_dict(cp['model'])
1414
+ self.ema.load_state_dict(cp['ema'])
1415
+ self.optimizer.load_state_dict(cp['optimizer'])
1416
+ self.step = cp['step']
1417
+
1418
+ def trainer(self, train_iter, eval_iter=None):
1419
+ """
1420
+ Train UQDM for a specified number of steps on a train set.
1421
+ Hyperparameters are set via self.config.training, self.config.eval, and self.config.optim.
1422
+ """
1423
+
1424
+ if self.step >= self.config.training.n_steps:
1425
+ print('Skipping training, increase training.n_steps if more steps are desired.')
1426
+
1427
+ while self.step < self.config.training.n_steps:
1428
+ # Parameter update step
1429
+ batch = next(train_iter).to(device)
1430
+ self.optimizer.zero_grad()
1431
+ model.train()
1432
+ loss, metrics = self(batch)
1433
+ loss.backward()
1434
+ if self.config.optim.warmup > 0:
1435
+ for g in self.optimizer.param_groups:
1436
+ g['lr'] = self.config.optim.lr * np.minimum(self.step / self.config.optim.warmup, 1.0)
1437
+ if self.config.optim.grad_clip_norm >= 0:
1438
+ torch.nn.utils.clip_grad_norm_(self.parameters(), max_norm=self.config.optim.grad_clip_norm)
1439
+ self.optimizer.step()
1440
+ self.step += 1
1441
+ self.ema.update(model.parameters())
1442
+
1443
+ last = self.step == self.config.training.n_steps
1444
+ # Save model checkpoint
1445
+ if self.step % self.config.training.log_metrics_every_steps == 0 or last:
1446
+ self.save()
1447
+ # Print train metrics
1448
+ if self.step % self.config.training.log_metrics_every_steps == 0 or last:
1449
+ print(metrics)
1450
+ # Compute and print validation metrics
1451
+ if eval_iter is not None and (self.step % self.config.training.eval_every_steps == 0 or last):
1452
+ n_batches = self.config.training.eval_steps_to_run
1453
+ res = []
1454
+ for batch in tqdm(islice(eval_iter, n_batches), total=n_batches or len(eval_iter),
1455
+ desc='Evaluating on test set'):
1456
+ batch = batch.to(device)
1457
+ with torch.inference_mode():
1458
+ self.ema.store(model.parameters())
1459
+ self.ema.copy_to(model.parameters())
1460
+ model.eval()
1461
+ _, ths_metrics = self(batch)
1462
+ self.ema.restore(model.parameters())
1463
+ res += [ths_metrics]
1464
+ res = default_collate(res)
1465
+ print({k: v.mean().item() for k, v in res.items()})
1466
+
1467
+ @staticmethod
1468
+ def mse_to_psnr(mse, max_val):
1469
+ with np.errstate(divide='ignore'):
1470
+ return -10 * (np.log10(mse) - 2 * np.log10(max_val))
1471
+
1472
+ @torch.inference_mode()
1473
+ def evaluate(self, eval_iter, n_batches=None, seed=None):
1474
+ """
1475
+ Evaluate rate-distortion on the test set.
1476
+
1477
+ Inputs:
1478
+ -------
1479
+ n_batches - (optionally) give a number of batches to evaluate
1480
+ """
1481
+
1482
+ res = []
1483
+ for X in tqdm(islice(eval_iter, n_batches), total=n_batches or len(eval_iter), desc='Evaluating UQDM'):
1484
+ X = X.to(device)
1485
+ ths_res = {}
1486
+ for recon_method in ('denoise', 'ancestral', 'flow_based'):
1487
+ # If evaluating bpds as file sizes:
1488
+ # self.compress_bits = []
1489
+ # loss, metrics = self(X, recon_method=recon_method, seed=seed, compress_mode='encode')
1490
+ # bpds = np.cumsum([len(b) * 8 for b in self.compress_bits]) / np.prod(X.shape)
1491
+ loss, metrics = self(X, recon_method=recon_method, seed=seed)
1492
+ bpds = np.cumsum(metrics['prog_bpds'].mean(dim=1))
1493
+ psnrs = self.mse_to_psnr(metrics['prog_mses'].mean(dim=1), max_val=255.)
1494
+ ths_res[recon_method] = dict(bpds=bpds, psnrs=psnrs)
1495
+ res += [ths_res]
1496
+ res = default_collate(res)
1497
+
1498
+ for recon_method in res.keys():
1499
+ bpps = np.round(3 * res[recon_method]['bpds'].mean(axis=0).numpy(), 4)
1500
+ psnrs = np.round(res[recon_method]['psnrs'].mean(axis=0).numpy(), 4)
1501
+ print('Reconstructions via: %s\nbpps: %s\npsnrs: %s\n' % (recon_method, bpps, psnrs))
1502
+
1503
+
1504
+ class UQDM(Diffusion):
1505
+ """
1506
+ Making Progressive Compression tractable with Universal Quantization.
1507
+ """
1508
+
1509
+ def __init__(self, config):
1510
+ """
1511
+ See Diffusion.__init__ for hyperparameters.
1512
+ """
1513
+ super().__init__(config)
1514
+ self.compress_bits = None
1515
+
1516
+ def p_s_t(self, p_loc, p_scale, t, s):
1517
+ # p(z_s | z_t) is a convolution of g_t and U(+- d_t), d_t = sqrt(12) * sigma_s * sqrt(exmp1term)
1518
+ delta_t = self.sigma(s) * torch.sqrt(- 12 * torch.special.expm1(self.gamma(s) - self.gamma(t)))
1519
+ base_dist = super().p_s_t(p_loc, p_scale, t, s)
1520
+ return UniformNoisyDistribution(base_dist, delta_t)
1521
+
1522
+ def q_s_t(self, q_loc, q_scale):
1523
+ # q(z_s | z_t, x) = U(q_loc +- sqrt(3) * q_scale)
1524
+ return Uniform(low=q_loc - np.sqrt(3) * q_scale, high=q_loc + np.sqrt(3) * q_scale)
1525
+
1526
+ def relative_entropy_coding(self, q, p, compress_mode=None):
1527
+ # Transmit sample z_s ~ q(z_s | z_t, x)
1528
+ if not torch.is_inference_mode_enabled():
1529
+ z_s = q.sample()
1530
+ else:
1531
+ # Apply universal quantization
1532
+ # shared U(-0.5, 0.5), seeds have already been set in self.forward
1533
+ u = torch.rand(q.mean.shape, device=q.mean.device) - 0.5
1534
+
1535
+ # very slow, ~ 25 symbols/s
1536
+ # cp = tfc.NoisyLogistic(loc=0.0, scale=(p.base_dist.scale / p.delta).cpu().numpy())
1537
+ # em2 = tfc.UniversalBatchedEntropyModel(cp, coding_rank=4, compression=True, num_noise_levels=30)
1538
+ # k = (q.mean - p.mean) / p.delta
1539
+ # bitstring = em2.compress(k.cpu())
1540
+ # k_hat = em2.decompress(bitstring, [])
1541
+
1542
+ if compress_mode in ['encode', 'decode']:
1543
+ p_discrete = p.discretize(u)
1544
+ if compress_mode == 'decode':
1545
+ # consume bits
1546
+ quantized = self.entropy_decode(self.compress_bits.pop(0), p_discrete)
1547
+ else:
1548
+ # Add dither U(-delta/2, delta/2)
1549
+ # Transmit residual q - p for greater numerical stability
1550
+ quantized = torch.round((q.mean - p.mean + p.delta * u) / p.delta)
1551
+ if compress_mode == 'encode':
1552
+ # accumulate bits
1553
+ self.compress_bits += [self.entropy_encode(quantized, p_discrete)]
1554
+ # Subtract the same (pseudo-random) dither using shared randomness
1555
+ z_s = quantized * p.delta + p.mean - p.delta * u
1556
+
1557
+ # Evaluate z_s under log (posterior/prior) to get MC estimate of KL.
1558
+ rate = - p.log_prob(z_s) - torch.log(p.delta)
1559
+ rate = torch.sum(rate, dim=[1, 2, 3])
1560
+ return z_s, rate
1561
+
1562
+
1563
+ if __name__ == '__main__':
1564
+ seed = 0
1565
+ np.random.seed(seed)
1566
+ torch.manual_seed(seed)
1567
+ torch.use_deterministic_algorithms(True)
1568
+
1569
+ # model = load_checkpoint('checkpoints/uqdm-tiny')
1570
+ # model = load_checkpoint('checkpoints/uqdm-small')
1571
+ model = load_checkpoint('checkpoints/uqdm-medium')
1572
+ # model = load_checkpoint('checkpoints/uqdm-big')
1573
+ train_iter, eval_iter = load_data('ImageNet64', model.config.data)
1574
+
1575
+ # model.trainer(train_iter, eval_iter)
1576
+ model.evaluate(eval_iter, n_batches=10, seed=seed)
1577
+
1578
+ # Compress one image
1579
+ image = next(iter(eval_iter))
1580
+ compressed = model.compress(image)
1581
+ bits = [len(b) * 8 for b in compressed]
1582
+ reconstructions = model.decompress(compressed, image.shape, recon_method='denoise')
1583
+ assert (reconstructions[-1] == image).all()
1584
+ print('Reconstructions via: denoise, compression to bits\nbpps: %s'
1585
+ % np.round(np.cumsum(bits) / np.prod(image.shape) * 3, 4))