forked from nelson1425/EfficientAD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
benchmark.py
86 lines (75 loc) · 2.65 KB
/
benchmark.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
from time import time
import numpy as np
import torch.cuda
from torch import nn
def get_pdn(out=384):
return nn.Sequential(
nn.Conv2d(3, 256, 4), nn.ReLU(inplace=True),
nn.AvgPool2d(2, 2),
nn.Conv2d(256, 512, 4), nn.ReLU(inplace=True),
nn.AvgPool2d(2, 2),
nn.Conv2d(512, 512, 1), nn.ReLU(inplace=True),
nn.Conv2d(512, 512, 3), nn.ReLU(inplace=True),
nn.Conv2d(512, out, 4), nn.ReLU(inplace=True),
nn.Conv2d(out, out, 1)
)
def get_ae():
return nn.Sequential(
# encoder
nn.Conv2d(3, 32, 4, 2, 1), nn.ReLU(inplace=True),
nn.Conv2d(32, 32, 4, 2, 1), nn.ReLU(inplace=True),
nn.Conv2d(32, 64, 4, 2, 1), nn.ReLU(inplace=True),
nn.Conv2d(64, 64, 4, 2, 1), nn.ReLU(inplace=True),
nn.Conv2d(64, 64, 4, 2, 1), nn.ReLU(inplace=True),
nn.Conv2d(64, 64, 8),
# decoder
nn.Upsample(3, mode='bilinear'),
nn.Conv2d(64, 64, 4, 1, 2), nn.ReLU(inplace=True),
nn.Upsample(8, mode='bilinear'),
nn.Conv2d(64, 64, 4, 1, 2), nn.ReLU(inplace=True),
nn.Upsample(15, mode='bilinear'),
nn.Conv2d(64, 64, 4, 1, 2), nn.ReLU(inplace=True),
nn.Upsample(32, mode='bilinear'),
nn.Conv2d(64, 64, 4, 1, 2), nn.ReLU(inplace=True),
nn.Upsample(63, mode='bilinear'),
nn.Conv2d(64, 64, 4, 1, 2), nn.ReLU(inplace=True),
nn.Upsample(127, mode='bilinear'),
nn.Conv2d(64, 64, 4, 1, 2), nn.ReLU(inplace=True),
nn.Upsample(56, mode='bilinear'),
nn.Conv2d(64, 64, 3, 1, 1), nn.ReLU(inplace=True),
nn.Conv2d(64, 384, 3, 1, 1)
)
gpu = torch.cuda.is_available()
autoencoder = get_ae()
teacher = get_pdn(384)
student = get_pdn(768)
autoencoder = autoencoder.eval()
teacher = teacher.eval()
student = student.eval()
if gpu:
autoencoder.half().cuda()
teacher.half().cuda()
student.half().cuda()
quant_mult = torch.e
quant_add = torch.pi
with torch.no_grad():
times = []
for rep in range(2000):
image = torch.randn(1, 3, 256, 256, dtype=torch.float16 if gpu else torch.float32)
start = time()
if gpu:
image = image.cuda()
t = teacher(image)
s = student(image)
st_map = torch.mean((t - s[:, :384]) ** 2, dim=1)
ae = autoencoder(image)
ae_map = torch.mean((ae - s[:, 384:]) ** 2, dim=1)
st_map = st_map * quant_mult + quant_add
ae_map = ae_map * quant_mult + quant_add
result_map = st_map + ae_map
result_on_cpu = result_map.cpu().numpy()
timed = time() - start
times.append(timed)
print(np.mean(times[-1000:]))