-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathbenchmark_compress.py
174 lines (157 loc) · 6.68 KB
/
benchmark_compress.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
import io
import gzip
import bz2
import lzma
import numpy as np
from utils.torch.modules import ImageNet
import os
from PIL.PngImagePlugin import getchunks
from torchvision import datasets, transforms
import PIL.Image as pimg
# code that applies benchmark compressors on the three datasets (MNIST, CIFAR-10 and ImageNet)
# heavily based on benchmark_compressors.py from https://github.com/bits-back/bits-back
# seed (for reproducibility MUST be the same for the whole project on the same machine)
np.random.seed(100)
# method to extract maximum amount of pixel-blocks of certain size from certain image
def extract_blocks(arr, block_size=(32, 32)):
nrows, ncols = block_size
h, w, c = arr.shape
if h % nrows != 0:
h -= h % nrows
arr = arr[:h]
if w % ncols != 0:
w -= w % ncols
arr = arr[:,:w]
return (arr.reshape(h//nrows, nrows, -1, ncols, c)
.swapaxes(1,2)
.reshape(-1, nrows, ncols, c)), h, w
# method to reconstruct image from the extracted pixel-blocks
# note: this returns the original images being cropped to multiples of 32 pixels on each side
def unextract_blocks(arr, h, w):
n, nrows, ncols, c = arr.shape
return (arr.reshape(h//nrows, -1, nrows, ncols, c)
.swapaxes(1,2)
.reshape(h, w, c))
class ToInt:
def __call__(self, pic):
return pic * 255
def mnist(exp):
transform_ops = transforms.Compose([transforms.ToTensor(), ToInt()])
mnist = datasets.MNIST(root="model/data/mnist", train=False, transform=transform_ops, download=True)
return mnist.test_data.numpy()[np.random.choice(len(mnist.test_data), size=(100, 100), replace=False)[exp]]
def cifar(exp):
transform_ops = transforms.Compose([transforms.ToTensor(), ToInt()])
cifar = datasets.CIFAR10(root="model/data/cifar", train=False, transform=transform_ops, download=True)
return cifar.test_data[np.random.choice(len(cifar.test_data), size=(100, 100), replace=False)[exp]]
def imagenet(exp):
transform_ops = transforms.Compose([transforms.ToTensor(), ToInt()])
data = ImageNet(root='model/data/imagenet/test', file='test.npy', transform=transform_ops)
if not os.path.exists("bitstreams/imagenet/indices"):
randindices = np.random.choice(len(data.dataset), size=(100, 100), replace=False)
np.save("bitstreams/imagenet/indices", randindices)
else:
randindices = np.load("bitstreams/imagenet/indices")
return data.dataset[randindices[exp]]
def gzip_compress(images):
images = np.packbits(images) if images.dtype is np.dtype(bool) else images
assert images.dtype == np.dtype('uint8')
return gzip.compress(images.tobytes())
def bz2_compress(images):
images = np.packbits(images) if images.dtype is np.dtype(bool) else images
assert images.dtype == np.dtype('uint8')
return bz2.compress(images.tobytes())
def lzma_compress(images):
images = np.packbits(images) if images.dtype is np.dtype(bool) else images
assert images.dtype == np.dtype('uint8')
return lzma.compress(images.tobytes())
def pimg_compress(format='PNG', **params):
def compress_fun(images):
compressed_data = bytearray()
for n, image in enumerate(images):
img = pimg.fromarray(image)
if format == 'PNG':
for chunk_type, chunk_data, crc in getchunks(img, optimize=True):
if chunk_type == b'IDAT':
compressed_data.extend(chunk_data)
else:
img_bytes = io.BytesIO()
img.save(img_bytes, format=format, **params)
compressed_data.extend(img_bytes.getvalue())
return compressed_data
return compress_fun
def gz_and_pimg(images, format='PNG', **params):
pimg_compressed_data = pimg_compress(images, format, **params)
return gzip.compress(pimg_compressed_data)
def bench_compressor(compress_fun, images):
byts = compress_fun(images)
n_bits = len(byts) * 8
bitsperdim = n_bits / np.size(images)
return bitsperdim
if __name__ == "__main__":
gzip_list = []
bz2_list = []
lzma_list = []
png_list = []
webp_list = []
# MNIST
print(f"Compressing MNIST test set")
for exp in range(100):
images = mnist(exp)
gzip_list.append(bench_compressor(gzip_compress, images))
bz2_list.append(bench_compressor(bz2_compress, images))
lzma_list.append(bench_compressor(lzma_compress, images))
png_list.append(bench_compressor(
pimg_compress("PNG", optimize=True), images))
webp_list.append(bench_compressor(
pimg_compress('WebP', lossless=True, quality=100), images))
print(f"gzip: {np.mean(gzip_list):.2f} bits/dim")
print(f"bz2: {np.mean(bz2_list):.2f} bits/dim")
print(f"lzma: {np.mean(lzma_list):.2f} bits/dim")
print(f"png: {np.mean(png_list):.2f} bits/dim")
print(f"webp: {np.mean(webp_list):.2f} bits/dim")
print("")
gzip_list = []
bz2_list = []
lzma_list = []
png_list = []
webp_list = []
print(f"Compressing CIFAR-10 test set")
for exp in range(100):
# CIFAR-10
images = cifar(exp)
# MNIST
gzip_list.append(bench_compressor(gzip_compress, images))
bz2_list.append(bench_compressor(bz2_compress, images))
lzma_list.append(bench_compressor(lzma_compress, images))
png_list.append(bench_compressor(
pimg_compress("PNG", optimize=True), images))
webp_list.append(bench_compressor(
pimg_compress('WebP', lossless=True, quality=100), images))
print(f"gzip: {np.mean(gzip_list):.2f} bits/dim")
print(f"bz2: {np.mean(bz2_list):.2f} bits/dim")
print(f"lzma: {np.mean(lzma_list):.2f} bits/dim")
print(f"png: {np.mean(png_list):.2f} bits/dim")
print(f"webp: {np.mean(webp_list):.2f} bits/dim")
print("")
gzip_list = []
bz2_list = []
lzma_list = []
png_list = []
webp_list = []
print(f"Compressing 10000 images from ImageNet test set")
for exp in range(100):
# ImageNet
images = imagenet(exp)
gzip_list.append(bench_compressor(gzip_compress, images))
bz2_list.append(bench_compressor(bz2_compress, images))
lzma_list.append(bench_compressor(lzma_compress, images))
png_list.append(bench_compressor(
pimg_compress("PNG", optimize=True), images))
webp_list.append(bench_compressor(
pimg_compress('WebP', lossless=True, quality=100), images))
print(f"gzip: {np.mean(gzip_list):.2f} bits/dim")
print(f"bz2: {np.mean(bz2_list):.2f} bits/dim")
print(f"lzma: {np.mean(lzma_list):.2f} bits/dim")
print(f"png: {np.mean(png_list):.2f} bits/dim")
print(f"webp: {np.mean(webp_list):.2f} bits/dim")
print("")