-
Notifications
You must be signed in to change notification settings - Fork 227
/
__main__.py
420 lines (359 loc) · 13.1 KB
/
__main__.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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# Copyright (c) 2021-2022, InterDigital Communications, Inc
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted (subject to the limitations in the disclaimer
# below) provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of InterDigital Communications, Inc nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY
# THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
# CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
Evaluate an end-to-end compression model on an image dataset.
"""
import argparse
import json
import math
import sys
import time
from collections import defaultdict
from pathlib import Path
from typing import Any, Dict, List
import torch
import torch.nn as nn
import torch.nn.functional as F
from PIL import Image
from pytorch_msssim import ms_ssim
from torchvision import transforms
import compressai
from compressai.ops import compute_padding
from compressai.zoo import image_models as pretrained_models
from compressai.zoo.image import model_architectures as architectures
torch.backends.cudnn.deterministic = True
torch.set_num_threads(1)
# from torchvision.datasets.folder
IMG_EXTENSIONS = (
".jpg",
".jpeg",
".png",
".ppm",
".bmp",
".pgm",
".tif",
".tiff",
".webp",
)
def collect_images(rootpath: str) -> List[str]:
image_files = []
for ext in IMG_EXTENSIONS:
image_files.extend(Path(rootpath).rglob(f"*{ext}"))
return sorted(image_files)
def psnr(a: torch.Tensor, b: torch.Tensor, max_val: int = 255) -> float:
return 20 * math.log10(max_val) - 10 * torch.log10((a - b).pow(2).mean())
def compute_metrics(
org: torch.Tensor, rec: torch.Tensor, max_val: int = 255
) -> Dict[str, Any]:
metrics: Dict[str, Any] = {}
org = (org * max_val).clamp(0, max_val).round()
rec = (rec * max_val).clamp(0, max_val).round()
metrics["psnr"] = psnr(org, rec).item()
metrics["ms-ssim"] = ms_ssim(org, rec, data_range=max_val).item()
return metrics
def read_image(filepath: str) -> torch.Tensor:
assert filepath.is_file()
img = Image.open(filepath).convert("RGB")
return transforms.ToTensor()(img)
@torch.no_grad()
def inference(model, x):
x = x.unsqueeze(0)
h, w = x.size(2), x.size(3)
pad, unpad = compute_padding(h, w, min_div=2**6) # pad to allow 6 strides of 2
x_padded = F.pad(x, pad, mode="constant", value=0)
start = time.time()
out_enc = model.compress(x_padded)
enc_time = time.time() - start
start = time.time()
out_dec = model.decompress(out_enc["strings"], out_enc["shape"])
dec_time = time.time() - start
out_dec["x_hat"] = F.pad(out_dec["x_hat"], unpad)
# input images are 8bit RGB for now
metrics = compute_metrics(x, out_dec["x_hat"], 255)
num_pixels = x.size(0) * x.size(2) * x.size(3)
bpp = sum(len(s[0]) for s in out_enc["strings"]) * 8.0 / num_pixels
return {
"psnr": metrics["psnr"],
"ms-ssim": metrics["ms-ssim"],
"bpp": bpp,
"encoding_time": enc_time,
"decoding_time": dec_time,
}
@torch.no_grad()
def inference_entropy_estimation(model, x):
x = x.unsqueeze(0)
start = time.time()
out_net = model.forward(x)
elapsed_time = time.time() - start
# input images are 8bit RGB for now
metrics = compute_metrics(x, out_net["x_hat"], 255)
num_pixels = x.size(0) * x.size(2) * x.size(3)
bpp = sum(
(torch.log(likelihoods).sum() / (-math.log(2) * num_pixels))
for likelihoods in out_net["likelihoods"].values()
)
return {
"psnr": metrics["psnr"],
"ms-ssim": metrics["ms-ssim"],
"bpp": bpp.item(),
"encoding_time": elapsed_time / 2.0, # broad estimation
"decoding_time": elapsed_time / 2.0,
}
def load_pretrained(model: str, metric: str, quality: int) -> nn.Module:
return pretrained_models[model](
quality=quality, metric=metric, pretrained=True, progress=False
).eval()
def load_checkpoint(arch: str, no_update: bool, checkpoint_path: str) -> nn.Module:
# update model if need be
checkpoint = torch.load(checkpoint_path, map_location="cpu")
state_dict = checkpoint
# compatibility with 'not updated yet' trained nets
for key in ["network", "state_dict", "model_state_dict"]:
if key in checkpoint:
state_dict = checkpoint[key]
model_cls = architectures[arch]
net = model_cls.from_state_dict(state_dict)
if not no_update:
net.update(force=True)
return net.eval()
def eval_model(
model: nn.Module,
outputdir: Path,
inputdir: Path,
filepaths,
entropy_estimation: bool = False,
trained_net: str = "",
description: str = "",
**args: Any,
) -> Dict[str, Any]:
device = next(model.parameters()).device
metrics = defaultdict(float)
for filepath in filepaths:
x = read_image(filepath).to(device)
if not entropy_estimation:
if args["half"]:
model = model.half()
x = x.half()
rv = inference(model, x)
else:
rv = inference_entropy_estimation(model, x)
for k, v in rv.items():
metrics[k] += v
if args["per_image"]:
if not Path(outputdir).is_dir():
raise FileNotFoundError("Please specify output directory")
output_subdir = Path(outputdir) / Path(filepath).parent.relative_to(
inputdir
)
output_subdir.mkdir(parents=True, exist_ok=True)
image_metrics_path = output_subdir / f"{filepath.stem}-{trained_net}.json"
with image_metrics_path.open("wb") as f:
output = {
"source": filepath.stem,
"name": args["architecture"],
"description": f"Inference ({description})",
"results": rv,
}
f.write(json.dumps(output, indent=2).encode())
for k, v in metrics.items():
metrics[k] = v / len(filepaths)
return metrics
def setup_args():
# Common options.
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument("dataset", type=str, help="dataset path")
parent_parser.add_argument(
"-a",
"--architecture",
type=str,
choices=pretrained_models.keys(),
help="model architecture",
required=True,
)
parent_parser.add_argument(
"-c",
"--entropy-coder",
choices=compressai.available_entropy_coders(),
default=compressai.available_entropy_coders()[0],
help="entropy coder (default: %(default)s)",
)
parent_parser.add_argument(
"--cuda",
action="store_true",
help="enable CUDA",
)
parent_parser.add_argument(
"--half",
action="store_true",
help="convert model to half floating point (fp16)",
)
parent_parser.add_argument(
"--entropy-estimation",
action="store_true",
help="use evaluated entropy estimation (no entropy coding)",
)
parent_parser.add_argument(
"-v",
"--verbose",
action="store_true",
help="verbose mode",
)
parent_parser.add_argument(
"-m",
"--metric",
type=str,
choices=["mse", "ms-ssim"],
default="mse",
help="metric trained against (default: %(default)s)",
)
parent_parser.add_argument(
"-d",
"--output_directory",
type=str,
default="",
help="path of output directory. Optional, required for output json file, results per image. Default will just print the output results.",
)
parent_parser.add_argument(
"-o",
"--output-file",
type=str,
default="",
help="output json file name, (default: architecture-entropy_coder.json)",
)
parent_parser.add_argument(
"--per-image",
action="store_true",
help="store results for each image of the dataset, separately",
)
parser = argparse.ArgumentParser(
description="Evaluate a model on an image dataset.", add_help=True
)
subparsers = parser.add_subparsers(help="model source", dest="source")
# Options for pretrained models
pretrained_parser = subparsers.add_parser("pretrained", parents=[parent_parser])
pretrained_parser.add_argument(
"-q",
"--quality",
dest="qualities",
type=str,
default="1",
help="Pretrained model qualities. (example: '1,2,3,4') (default: %(default)s)",
)
checkpoint_parser = subparsers.add_parser("checkpoint", parents=[parent_parser])
checkpoint_parser.add_argument(
"-p",
"--path",
dest="checkpoint_paths",
type=str,
nargs="*",
required=True,
help="checkpoint path",
)
checkpoint_parser.add_argument(
"--no-update",
action="store_true",
help="Disable the default update of the model entropy parameters before eval",
)
return parser
def main(argv):
parser = setup_args()
args = parser.parse_args(argv)
if args.source not in ["checkpoint", "pretrained"]:
print("Error: missing 'checkpoint' or 'pretrained' source.", file=sys.stderr)
parser.print_help()
raise SystemExit(1)
description = (
"entropy-estimation" if args.entropy_estimation else args.entropy_coder
)
filepaths = collect_images(args.dataset)
if len(filepaths) == 0:
print("Error: no images found in directory.", file=sys.stderr)
raise SystemExit(1)
compressai.set_entropy_coder(args.entropy_coder)
# create output directory
if args.output_directory:
Path(args.output_directory).mkdir(parents=True, exist_ok=True)
if args.source == "pretrained":
args.qualities = [int(q) for q in args.qualities.split(",") if q]
runs = sorted(args.qualities)
opts = (args.architecture, args.metric)
load_func = load_pretrained
log_fmt = "\rEvaluating {0} | {run:d}"
else:
runs = args.checkpoint_paths
opts = (args.architecture, args.no_update)
load_func = load_checkpoint
log_fmt = "\rEvaluating {run:s}"
results = defaultdict(list)
for run in runs:
if args.verbose:
sys.stderr.write(log_fmt.format(*opts, run=run))
sys.stderr.flush()
model = load_func(*opts, run)
if args.source == "pretrained":
trained_net = f"{args.architecture}-{args.metric}-{run}-{description}"
else:
cpt_name = Path(run).name[: -len(".tar.pth")] # removesuffix() python3.9
trained_net = f"{cpt_name}-{description}"
print(f"Using trained model {trained_net}", file=sys.stderr)
if args.cuda and torch.cuda.is_available():
model = model.to("cuda")
args_dict = vars(args)
metrics = eval_model(
model,
args.output_directory,
args.dataset,
filepaths,
trained_net=trained_net,
description=description,
**args_dict,
)
for k, v in metrics.items():
results[k].append(v)
if args.verbose:
sys.stderr.write("\n")
sys.stderr.flush()
description = (
"entropy estimation" if args.entropy_estimation else args.entropy_coder
)
output = {
"name": f"{args.architecture}-{args.metric}",
"description": f"Inference ({description})",
"results": results,
}
if args.output_directory:
output_file = (
args.output_file
if args.output_file
else f"{args.architecture}-{description}"
)
with (Path(f"{args.output_directory}/{output_file}").with_suffix(".json")).open(
"wb"
) as f:
f.write(json.dumps(output, indent=2).encode())
print(json.dumps(output, indent=2))
if __name__ == "__main__":
main(sys.argv[1:])