-
Notifications
You must be signed in to change notification settings - Fork 8
/
tester.py
140 lines (117 loc) · 4.25 KB
/
tester.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
import torch
import torch.nn.functional as F
import numpy as np
import timer
import wandb
from torchmetrics import IoU, Accuracy
# project
import probspec_routines as ps_routines
from optim import CLASSES_DATASET
# typing
from omegaconf import OmegaConf
def test(
model: torch.nn.Module,
test_loader: torch.utils.data.DataLoader,
cfg: OmegaConf,
name: str = None,
**kwargs,
):
test_function = {
"AddProblem": ps_routines.add_problem_test,
"CopyMemory": ps_routines.copy_problem_test,
"SpeechCommands": classification_test,
"CharTrajectories": classification_test,
"MNIST": classification_test,
"sMNIST": classification_test,
"CIFAR10": classification_test,
"sCIFAR10": classification_test,
"CIFAR100": classification_test,
"Imagenet": classification_test,
"Imagenet64": classification_test,
"Imagenet32": classification_test,
"Imagenet16": classification_test,
"Imagenet8": classification_test,
"STL": classification_test,
}[cfg.dataset]
return test_function(model, test_loader, cfg, name=name)
def classification_test(
model: torch.nn.Module,
test_loader: torch.utils.data.DataLoader,
cfg: OmegaConf,
log: bool = False,
epoch: int = None,
name: str = None,
):
# send model to device
device = cfg.device
model.eval()
model.to(device)
# Summarize results
correct = 0
total = 0
# Permuter for psMNIST
if cfg.dataset == "sMNIST" and cfg.dataset_params.permuted:
# Check if the config file has the key, otherwise create the permutation. #TODO: Not supported by hydra
# if "permutation" in cfg.dataset_params:
# permutation = cfg.dataset_params.permutation
# else:
permutation = torch.Tensor(np.random.permutation(784).astype(np.float64)).long()
# Noise for noise-padded sCIFAR10
if cfg.dataset == "sCIFAR10" and cfg.dataset_params.noise_padded:
rands = torch.randn(1, 1000 - 32, 96)
if cfg.train.report_top5_acc:
top5 = Accuracy(
num_classes=CLASSES_DATASET[cfg.dataset],
top_k=5,
compute_on_step=False,
)
with torch.no_grad():
# Iterate through data
for data in test_loader:
# DALI has a different dataloader output format
if cfg.dataset == "Imagenet":
data = (data[0]["data"], data[0]["label"].squeeze(1))
inputs, labels = data
# Add padding if noise_padding
if cfg.dataset_params.noise_padded and cfg.dataset == "sCIFAR10":
inputs = torch.cat(
(
inputs.permute(0, 2, 1, 3).reshape(inputs.shape[0], 32, 96),
rands.repeat(inputs.shape[0], 1, 1),
),
dim=1,
).permute(0, 2, 1)
else:
# Make sequential if sMNIST or sCIFAR10
if cfg.dataset in ["sMNIST", "sCIFAR10"]:
_, in_channels, x, y = inputs.shape
inputs = inputs.view(-1, in_channels, x * y)
# Permute if psMNIST
if cfg.dataset_params.permuted and cfg.dataset == "sMNIST":
inputs = inputs[:, :, permutation]
inputs = inputs.to(device)
labels = labels.to(device)
outputs = model(inputs)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
if cfg.train.report_top5_acc:
pred_sm = torch.nn.functional.softmax(outputs, dim=1)
# torchmetrics.Accuracy requires everything to be on CPU
top5(pred_sm.to("cpu"), labels.to("cpu"))
# Print results
test_acc = correct / total
print(
"Accuracy of the network on the {} test samples: {}".format(
total, (100 * test_acc)
)
)
test_top5 = 0.0
if cfg.train.report_top5_acc:
test_top5 = top5.compute()
print(
"Top-5 accuracy of the network on the {} test samples: {}".format(
total, (100 * test_top5)
)
)
return test_acc, test_top5