-
Notifications
You must be signed in to change notification settings - Fork 152
/
test_engine.py
219 lines (182 loc) · 7.23 KB
/
test_engine.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
# Copyright (c) 2021, Zhiqiang Wang. All Rights Reserved.
import pytest
from pathlib import Path
import torch
from torch import Tensor
from torchvision.io import read_image
import pytorch_lightning as pl
from yolort.data import COCOEvaluator, DetectionDataModule, _helper as data_helper
from yolort.models import yolov5s
from yolort.models.yolo import yolov5_darknet_pan_s_r31
from yolort.models.transform import nested_tensor_from_tensor_list
from typing import Dict
def default_loader(img_name, is_half=False):
"""
Read Image using TorchVision.io Here
"""
img = read_image(img_name)
img = img.half() if is_half else img.float() # uint8 to fp16/32
img /= 255. # 0 - 255 to 0.0 - 1.0
return img
def test_train_with_vanilla_model():
# Do forward over image
img_name = "test/assets/zidane.jpg"
img_tensor = default_loader(img_name)
assert img_tensor.ndim == 3
# Add a dummy image to train
img_dummy = torch.rand((3, 416, 360), dtype=torch.float32)
images = nested_tensor_from_tensor_list([img_tensor, img_dummy])
targets = torch.tensor([[0, 7, 0.3790, 0.5487, 0.3220, 0.2047],
[0, 2, 0.2680, 0.5386, 0.2200, 0.1779],
[0, 3, 0.1720, 0.5403, 0.1960, 0.1409],
[0, 4, 0.2240, 0.4547, 0.1520, 0.0705]], dtype=torch.float)
model = yolov5_darknet_pan_s_r31(num_classes=12)
model.train()
out = model(images, targets)
assert isinstance(out, Dict)
assert isinstance(out["cls_logits"], Tensor)
assert isinstance(out["bbox_regression"], Tensor)
assert isinstance(out["objectness"], Tensor)
def test_train_with_vanilla_module():
"""
For issue #86: <https://github.com/zhiqwang/yolov5-rt-stack/issues/86>
"""
# Define the device
device = torch.device('cpu')
train_dataloader = data_helper.get_dataloader(data_root='data-bin', mode='train')
# Sample a pair of images/targets
images, targets = next(iter(train_dataloader))
images = [img.to(device) for img in images]
targets = [{k: v.to(device) for k, v in t.items()} for t in targets]
# Define the model
model = yolov5s(num_classes=80)
model.train()
out = model(images, targets)
assert isinstance(out, Dict)
assert isinstance(out["cls_logits"], Tensor)
assert isinstance(out["bbox_regression"], Tensor)
assert isinstance(out["objectness"], Tensor)
@pytest.mark.skip("Currently it is not well supported.")
def test_training_step():
# Setup the DataModule
data_path = 'data-bin'
train_dataset = data_helper.get_dataset(data_root=data_path, mode='train')
val_dataset = data_helper.get_dataset(data_root=data_path, mode='val')
data_module = DetectionDataModule(train_dataset, val_dataset, batch_size=16)
# Load model
model = yolov5s()
model.train()
# Trainer
trainer = pl.Trainer(max_epochs=1)
trainer.fit(model, data_module)
def test_vanilla_coco_evaluator():
# Acquire the images and labels from the coco128 dataset
val_dataloader = data_helper.get_dataloader(data_root='data-bin', mode='val')
coco = data_helper.get_coco_api_from_dataset(val_dataloader.dataset)
coco_evaluator = COCOEvaluator(coco)
# Load model
model = yolov5s(pretrained=True, score_thresh=0.001)
model.eval()
for images, targets in val_dataloader:
preds = model(images)
coco_evaluator.update(preds, targets)
results = coco_evaluator.compute()
assert results['AP'] > 38.1
assert results['AP50'] > 59.9
def test_test_epoch_end():
# Acquire the annotation file
data_path = Path('data-bin')
coco128_dirname = 'coco128'
data_helper.prepare_coco128(data_path, dirname=coco128_dirname)
annotation_file = data_path / coco128_dirname / 'annotations' / 'instances_train2017.json'
# Get dataloader to test
val_dataloader = data_helper.get_dataloader(data_root=data_path, mode='val')
# Load model
model = yolov5s(pretrained=True, score_thresh=0.001, annotation_path=annotation_file)
# test step
trainer = pl.Trainer(max_epochs=1)
trainer.test(model, test_dataloaders=val_dataloader)
# test epoch end
results = model.evaluator.compute()
assert results['AP'] > 38.1
assert results['AP50'] > 59.9
def test_predict_with_vanilla_model():
# Set image inputs
img_name = "test/assets/zidane.jpg"
img_input = default_loader(img_name)
assert img_input.ndim == 3
# Load model
model = yolov5s(pretrained=True)
model.eval()
# Perform inference on a list of tensors
out = model([img_input])
assert isinstance(out, list)
assert len(out) == 1
assert isinstance(out[0], Dict)
assert isinstance(out[0]["boxes"], Tensor)
assert isinstance(out[0]["labels"], Tensor)
assert isinstance(out[0]["scores"], Tensor)
def test_predict_with_tensor():
# Set image inputs
img_name = "test/assets/zidane.jpg"
img_tensor = default_loader(img_name)
assert img_tensor.ndim == 3
# Load model
model = yolov5s(pretrained=True)
model.eval()
# Perform inference on a list of image files
predictions = model.predict(img_tensor)
assert isinstance(predictions, list)
assert len(predictions) == 1
assert isinstance(predictions[0], Dict)
assert isinstance(predictions[0]["boxes"], Tensor)
assert isinstance(predictions[0]["labels"], Tensor)
assert isinstance(predictions[0]["scores"], Tensor)
def test_predict_with_tensors():
# Set image inputs
img_tensor1 = default_loader("test/assets/zidane.jpg")
assert img_tensor1.ndim == 3
img_tensor2 = default_loader("test/assets/bus.jpg")
assert img_tensor2.ndim == 3
img_tensors = [img_tensor1, img_tensor2]
# Load model
model = yolov5s(pretrained=True)
model.eval()
# Perform inference on a list of image files
predictions = model.predict(img_tensors)
assert isinstance(predictions, list)
assert len(predictions) == 2
assert isinstance(predictions[0], Dict)
assert isinstance(predictions[0]["boxes"], Tensor)
assert isinstance(predictions[0]["labels"], Tensor)
assert isinstance(predictions[0]["scores"], Tensor)
def test_predict_with_image_file():
# Set image inputs
img_name = "test/assets/zidane.jpg"
# Load model
model = yolov5s(pretrained=True)
model.eval()
# Perform inference on an image file
predictions = model.predict(img_name)
assert isinstance(predictions, list)
assert len(predictions) == 1
assert isinstance(predictions[0], Dict)
assert isinstance(predictions[0]["boxes"], Tensor)
assert isinstance(predictions[0]["labels"], Tensor)
assert isinstance(predictions[0]["scores"], Tensor)
def test_predict_with_image_files():
# Set image inputs
img_name1 = "test/assets/zidane.jpg"
img_name2 = "test/assets/bus.jpg"
img_names = [img_name1, img_name2]
# Load model
model = yolov5s(pretrained=True)
model.eval()
# Perform inference on a list of image files
predictions = model.predict(img_names)
assert isinstance(predictions, list)
assert len(predictions) == 2
assert isinstance(predictions[0], Dict)
assert isinstance(predictions[0]["boxes"], Tensor)
assert isinstance(predictions[0]["labels"], Tensor)
assert isinstance(predictions[0]["scores"], Tensor)