-
Notifications
You must be signed in to change notification settings - Fork 79
/
Copy pathcompression_utils.py
389 lines (300 loc) · 12.9 KB
/
compression_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
import torch
import math
import numpy as np
import functools
import os
import autograd.numpy as np
from autograd import make_vjp
from autograd.extend import vspace, VSpace
from collections import namedtuple
from src.helpers import utils
from src.compression import entropy_coding
# Random bits for fencing in bitstream
_MAGIC_VALUE_SEP = b'\x46\xE2\x84\x92'
PATCH_SIZE = entropy_coding.PATCH_SIZE
CompressionOutput = namedtuple("CompressionOutput",
["hyperlatents_encoded",
"latents_encoded",
"hyperlatent_spatial_shape",
"batch_shape",
"spatial_shape",
"hyper_coding_shape",
"latent_coding_shape"]
)
def estimate_tails(cdf, target, shape, dtype=torch.float32, extra_counts=24):
"""
Estimates approximate tail quantiles.
This runs a simple Adam iteration to determine tail quantiles. The
objective is to find an `x` such that: [[[ cdf(x) == target ]]]
Note that `cdf` is assumed to be monotonic. When each tail estimate has passed the
optimal value of `x`, the algorithm does `extra_counts` (default 10) additional
iterations and then stops.
This operation is vectorized. The tensor shape of `x` is given by `shape`, and
`target` must have a shape that is broadcastable to the output of `func(x)`.
Arguments:
cdf: A callable that computes cumulative distribution function, survival
function, or similar.
target: The desired target value.
shape: The shape of the tensor representing `x`.
Returns:
A `torch.Tensor` representing the solution (`x`).
"""
# A bit hacky
lr, eps = 1e-2, 1e-8
beta_1, beta_2 = 0.9, 0.99
# Tails should be monotonically increasing
device = utils.get_device()
tails = torch.zeros(shape, dtype=dtype, requires_grad=True, device=device)
m = torch.zeros(shape, dtype=dtype)
v = torch.ones(shape, dtype=dtype)
counts = torch.zeros(shape, dtype=torch.int32)
while torch.min(counts) < extra_counts:
loss = abs(cdf(tails) - target)
loss.backward(torch.ones_like(tails))
tgrad = tails.grad.cpu()
with torch.no_grad():
m = beta_1 * m + (1. - beta_1) * tgrad
v = beta_2 * v + (1. - beta_2) * torch.square(tgrad)
tails -= (lr * m / (torch.sqrt(v) + eps)).to(device)
# Condition assumes tails init'd at zero
counts = torch.where(torch.logical_or(counts > 0, tgrad.cpu() * tails.cpu() > 0),
counts+1, counts)
tails.grad.zero_()
return tails
def view_update(data, view_fun):
view_vjp, item = make_vjp(view_fun)(data)
item_vs = vspace(item)
def update(new_item):
assert item_vs == vspace(new_item), \
"Please ensure new_item shape and dtype match the data view."
diff = view_vjp(item_vs.add(new_item,
item_vs.scalar_mul(item, -np.uint64(1))))
return vspace(data).add(data, diff)
return item, update
def decompose(x, n_channels, patch_size=PATCH_SIZE):
# Decompose input x into spatial patches
if isinstance(x, torch.Tensor) is False:
x = torch.Tensor(x)
y = x.unfold(1, n_channels, n_channels).unfold(2, *patch_size).unfold(3, *patch_size)
unfolded_shape = tuple(y.size())
y = torch.reshape(y, (-1, n_channels, *patch_size)) # (n_patches, n_channels, *patch_size)
return y.cpu().numpy().astype(np.int32), unfolded_shape
def reconstitute(x, original_shape, unfolded_shape, patch_size=PATCH_SIZE):
# Reconstitute patches into original input
if isinstance(x, torch.Tensor) is False:
x = torch.Tensor(x)
B, n_channels, *_ = original_shape
x_re = torch.reshape(x,
(B, 1, unfolded_shape[2], unfolded_shape[3], n_channels, *patch_size))
x_re = x_re.permute(0, 1, 4, 2, 5, 3, 6).contiguous().view(original_shape)
return x_re.cpu().numpy().astype(np.int32)
def check_argument_shapes(cdf, cdf_length, cdf_offset):
if (len(cdf.size()) != 2 or cdf.size(1) < 3):
raise ValueError("'cdf' should be 2-D and cdf.dim_size(1) >= 3: ", cdf.size())
if (len(cdf_length.size()) != 1 or cdf_length.size(0) != cdf.size(0)):
raise ValueError("'cdf_length' should be 1-D and its length "
"should match the number of rows in 'cdf': ", cdf_length.size())
if (len(cdf_offset.size()) != 1 or cdf_offset.size(0) != cdf.size(0)):
raise ValueError("'cdf_offset' should be 1-D and its length "
"should match the number of rows in 'cdf': ", cdf_offset.size())
def ans_compress(symbols, indices, cdf, cdf_length, cdf_offset, coding_shape,
precision, vectorize=False, block_encode=True):
if vectorize is True: # Inputs must be identically shaped
encoded = entropy_coding.vec_ans_index_encoder(
symbols=symbols, # [N, C, H, W]
indices=indices, # [N, C, H, W]
cdf=cdf, # [n_scales, max_length + 2]
cdf_length=cdf_length, # [n_scales]
cdf_offset=cdf_offset, # [n_scales]
precision=precision,
coding_shape=coding_shape,
)
else:
if block_encode is True:
encoded = entropy_coding.ans_index_encoder(
symbols=symbols, # [N, C, H, W]
indices=indices, # [N, C, H, W]
cdf=cdf, # [n_scales, max_length + 2]
cdf_length=cdf_length, # [n_scales]
cdf_offset=cdf_offset, # [n_scales]
precision=precision,
coding_shape=coding_shape,
)
else:
encoded = []
for i in range(symbols.shape[0]):
coded_string = entropy_coding.ans_index_encoder(
symbols=symbols[i], # [C, H, W]
indices=indices[i], # [C, H, W]
cdf=cdf, # [n_scales, max_length + 2]
cdf_length=cdf_length, # [n_scales]
cdf_offset=cdf_offset, # [n_scales]
precision=precision,
coding_shape=coding_shape,
)
encoded.append(coded_string)
return encoded
def ans_decompress(encoded, indices, cdf, cdf_length, cdf_offset, coding_shape,
precision, vectorize=False, block_decode=True):
if vectorize is True: # Inputs must be identically shaped
decoded = entropy_coding.vec_ans_index_decoder(
encoded,
indices=indices,
cdf=cdf,
cdf_length=cdf_length,
cdf_offset=cdf_offset,
precision=precision,
coding_shape=coding_shape,
)
else:
if block_decode is True:
decoded = entropy_coding.ans_index_decoder(
encoded,
indices=indices, # [N, C, H, W]
cdf=cdf, # [n_scales, max_length + 2]
cdf_length=cdf_length, # [n_scales]
cdf_offset=cdf_offset, # [n_scales]
precision=precision,
coding_shape=coding_shape,
)
else:
decoded = []
assert len(encoded) == batch_shape, (
f'Encoded batch dim {len(encoded)} != batch size {batch_shape}')
for i in range(batch_shape):
coded_string = entropy_coding.ans_index_decoder(
encoded[i], # [C, H, W]
indices=indices[i], # [C, H, W]
cdf=cdf, # [n_scales, max_length + 2]
cdf_length=cdf_length, # [n_scales]
cdf_offset=cdf_offset, # [n_scales]
precision=precision,
coding_shape=coding_shape,
)
decoded.append(coded_string)
decoded = np.stack(decoded, axis=0)
return decoded
def compose(*args):
"""
:param args: a list of functions
:return: composition of the functions
"""
def compose2(f1, f2):
def composed(*args_c, **kwargs_c):
return f1(f2(*args_c, **kwargs_c))
return composed
return functools.reduce(compose2, args)
def return_list(f):
""" Can be used to decorate generator functions. """
return compose(list, f)
def write_coding_shape(shape, fout):
"""
Write tuple (C,H,W) to file.
"""
assert len(shape) == 3, shape
assert shape[0] < 2**16, shape
assert shape[1] < 2**16, shape
assert shape[2] < 2**16, shape
write_bytes(fout, [np.uint16, np.uint16, np.uint16], shape)
return 6 # number of bytes written
def write_shapes(shape, fout):
"""
Write tuple (H,W) or (C,H,W) to file.
"""
for s in shape:
assert s < 2**16, s
write_bytes(fout, [np.uint16]*len(shape), shape)
return 2*len(shape) # number of bytes written
def read_shapes(fin, shape_len):
return tuple(map(int, read_bytes(fin, [np.uint16]*shape_len)))
def write_num_bytes_encoded(num_bytes, fout):
assert num_bytes < 2**32
write_bytes(fout, [np.uint32], [num_bytes])
return 4 # number of bytes written
def read_num_bytes_encoded(fin):
return int(read_bytes(fin, [np.uint32])[0])
def write_bytes(f, ts, xs):
for t, x in zip(ts, xs):
f.write(t(x).tobytes())
@return_list
def read_bytes(f, ts):
for t in ts:
num_bytes_to_read = t().itemsize
yield np.frombuffer(f.read(num_bytes_to_read), t, count=1)
def message_to_bytes(f_out, message):
# Message should be of type np.int32
# with open(p, 'wb') as f:
f_out.write(message.tobytes())
def message_from_bytes(f_in, num_bytes, t=np.uint32):
message = np.frombuffer(f_in.read(num_bytes), t, count=-1)
return message
def save_compressed_format(compression_output, out_path):
# Saves compressed output to disk at `out_path`, together with
# necessary meta-information
# See format of compressed output in `hyperprior.py`
entropy_coding_bytes = []
with open(out_path, 'wb') as f_out:
# Write meta information
write_shapes(compression_output.hyperlatent_spatial_shape, f_out) # (H,W)
write_shapes(compression_output.spatial_shape, f_out) # (H,W)
write_shapes(compression_output.hyper_coding_shape, f_out) # (C,H,W)
write_shapes(compression_output.latent_coding_shape, f_out) # (C,H,W)
write_shapes([compression_output.batch_shape], f_out) # (B)
f_out.write(_MAGIC_VALUE_SEP)
# Write hyperlatents
enc_hyperlatents = compression_output.hyperlatents_encoded # np.uint32
write_num_bytes_encoded(len(enc_hyperlatents) * 4, f_out)
message_to_bytes(f_out, enc_hyperlatents)
f_out.write(_MAGIC_VALUE_SEP)
# Write latents
enc_latents = compression_output.latents_encoded
write_num_bytes_encoded(len(enc_latents) * 4, f_out)
message_to_bytes(f_out, enc_latents)
f_out.write(_MAGIC_VALUE_SEP)
actual_num_bytes = os.path.getsize(out_path)
actual_bpp = 8. * float(actual_num_bytes) / np.prod(compression_output.spatial_shape)
try:
theoretical_bpp = float(compression_output.total_bpp.item())
except AttributeError:
theoretical_bpp = float(compression_output.total_bpp)
return actual_bpp, theoretical_bpp
def load_compressed_format(in_path):
# Loads necessary meta-information and compressed format from binary
# format on disk
with open(in_path, 'rb') as f_in:
# Read meta information
hyperlatent_spatial_shape = read_shapes(f_in, 2)
spatial_shape = read_shapes(f_in, 2)
hyper_coding_shape = read_shapes(f_in, 3)
latent_coding_shape = read_shapes(f_in, 3)
batch_shape = read_shapes(f_in, 1)
assert f_in.read(4) == _MAGIC_VALUE_SEP # assert valid file
# Read hyperlatents
num_bytes = read_num_bytes_encoded(f_in)
hyperlatents_encoded = message_from_bytes(f_in, num_bytes)
assert f_in.read(4) == _MAGIC_VALUE_SEP # assert valid file
# Read latents
num_bytes = read_num_bytes_encoded(f_in)
latents_encoded = message_from_bytes(f_in, num_bytes)
assert f_in.read(4) == _MAGIC_VALUE_SEP # assert valid file
compression_output = CompressionOutput(
hyperlatents_encoded=hyperlatents_encoded,
latents_encoded=latents_encoded,
hyperlatent_spatial_shape=hyperlatent_spatial_shape, # 2D
spatial_shape=spatial_shape, # 2D
hyper_coding_shape=hyper_coding_shape, # C,H,W
latent_coding_shape=latent_coding_shape, # C,H,W
batch_shape=batch_shape[0])
return compression_output
if __name__ == '__main__':
import random
quantile = 0.42 + random.randint(0,50)/100
norm_cdf = lambda x: 0.5 * (1. + torch.erf(x / math.sqrt(2)))
tails = estimate_tails(norm_cdf, quantile, shape=10)
print('Normal:')
print(f"OPT: {norm_cdf(torch.ones(1)*tails[0]).item()}, TRUE {quantile}")
quantile = 0.69 + random.randint(0,31)/100
norm_cdf = torch.sigmoid
tails = estimate_tails(norm_cdf, quantile, shape=10)
print('logistic:')
print(f"OPT: {norm_cdf(torch.ones(1)*tails[0]).item()}, TRUE {quantile}")