This repository has been archived by the owner on Jul 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 275
/
Copy pathdataset_classy_dataset_test.py
265 lines (216 loc) · 9.19 KB
/
dataset_classy_dataset_test.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
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import multiprocessing as mp
import unittest
import unittest.mock as mock
import classy_vision.dataset.classy_dataset as classy_dataset
import torch
from classy_vision.dataset import build_dataset, register_dataset
from classy_vision.dataset.core import ListDataset
from test.generic.utils import compare_batches, compare_samples
from torch.utils.data import DataLoader
DUMMY_SAMPLES_1 = [
{"input": torch.tensor([[[0, 1], [2, 3]]]), "target": torch.tensor([[0]])}
]
DUMMY_SAMPLES_2 = [
{"input": torch.tensor([[[0, 1], [2, 3]]]), "target": torch.tensor([[0]])},
{"input": torch.tensor([[[4, 5], [6, 7]]]), "target": torch.tensor([[1]])},
]
BATCHED_DUMMY_SAMPLES_2 = [
{
"input": torch.tensor([[[[0, 1], [2, 3]]], [[[4, 5], [6, 7]]]]),
"target": torch.tensor([[[0]], [[1]]]),
}
]
DUMMY_CONFIG = {"name": "test_dataset", "dummy0": 0, "dummy1": 1}
OTHER_DUMMY_CONFIG = {"name": "other_test_dataset", "dummy0": 0, "dummy1": 1}
def mock_get_world_size():
return 2
def mock_get_rank():
return 1
@register_dataset("test_dataset")
class TestDataset(classy_dataset.ClassyDataset):
"""Test dataset for validating registry functions"""
def __init__(
self,
samples,
batchsize_per_replica=1,
num_samples=None,
shuffle=False,
transform=None,
):
input_tensors = [sample["input"] for sample in samples]
target_tensors = [sample["target"] for sample in samples]
dataset = ListDataset(input_tensors, target_tensors, loader=lambda x: x)
super().__init__(
dataset=dataset,
batchsize_per_replica=batchsize_per_replica,
shuffle=shuffle,
transform=transform,
num_samples=len(samples) if num_samples is None else num_samples,
)
@classmethod
def from_config(cls, config, *args, **kwargs):
return cls(*args, **kwargs)
@register_dataset("other_test_dataset")
class OtherTestDataset(classy_dataset.ClassyDataset):
"""
Test dataset for validating registry functions that has a different
type than TestDataset
"""
def __init__(self, samples, batchsize_per_replica=1):
input_tensors = [sample["input"] for sample in samples]
target_tensors = [sample["target"] for sample in samples]
dataset = ListDataset(input_tensors, target_tensors, loader=lambda x: x)
super().__init__(
dataset=dataset,
batchsize_per_replica=batchsize_per_replica,
shuffle=False,
transform=None,
num_samples=len(samples),
)
@classmethod
def from_config(cls, config, *args, **kwargs):
return cls(*args, **kwargs)
class TestRegistryFunctions(unittest.TestCase):
"""
Tests functions that use registry
"""
def test_build_model(self):
dataset = build_dataset(DUMMY_CONFIG, DUMMY_SAMPLES_1)
self.assertTrue(isinstance(dataset, TestDataset))
class TestClassyDataset(unittest.TestCase):
"""
Tests member functions of ClassyDataset. Note, NotImplemented
functions are mocked in TestDataset class.
"""
def setUp(self):
self.dataset1 = build_dataset(DUMMY_CONFIG, DUMMY_SAMPLES_1)
self.dataset2 = build_dataset(DUMMY_CONFIG, DUMMY_SAMPLES_2)
def _compare_samples(self, sample1, sample2):
compare_samples(self, sample1, sample2)
def _compare_batches(self, batch1, batch2):
compare_batches(self, batch1, batch2)
def test_init(self):
self.assertTrue(self.dataset1 is not None)
self.assertTrue(self.dataset2 is not None)
def test_len(self):
self.assertEqual(len(self.dataset1), 1)
self.assertEqual(len(self.dataset2), 2)
def test_getitem(self):
sample = self.dataset1[0]
self._compare_samples(sample, DUMMY_SAMPLES_1[0])
for idx in range(len(self.dataset2)):
sample = self.dataset2[idx]
self._compare_samples(sample, DUMMY_SAMPLES_2[idx])
def test_get_iterator(self):
# Verifies that we can retrieve samples with iterators
dl = self.dataset1.iterator(num_workers=0)
assert isinstance(
dl, DataLoader
), "Classy Iterator should return instance of PyTorch Dataloader"
next(iter(dl))
# We should be able to set num_workers to zero while also passing a mp context
dl = self.dataset1.iterator(
num_workers=0, multiprocessing_context=mp.get_context()
)
assert isinstance(
dl, DataLoader
), "Classy Iterator should return instance of PyTorch Dataloader"
next(iter(dl))
dl = self.dataset1.iterator(num_workers=2)
assert isinstance(
dl, DataLoader
), "Classy Iterator should return instance of PyTorch Dataloader"
it = iter(dl)
next(it)
# Because we use multiprocessing we delete the iterable to
# shutdown workers
del it
def test_batch_logic(self):
dataset = TestDataset(DUMMY_SAMPLES_2, batchsize_per_replica=2)
dl = dataset.iterator(num_workers=0)
batch = next(iter(dl))
self.assertEqual(batch["input"].size()[0], 2)
self._compare_batches(batch, BATCHED_DUMMY_SAMPLES_2[0])
@mock.patch(
"classy_vision.dataset.classy_dataset.get_world_size", mock_get_world_size
)
@mock.patch("classy_vision.dataset.classy_dataset.get_rank", mock_get_rank)
def test_shard_logic(self):
# This test uses a world size of 2, rank 1 to verify that the
# second sample is returned by the dataloader
dataset = TestDataset(DUMMY_SAMPLES_2, batchsize_per_replica=1)
dl = dataset.iterator(num_workers=0)
sample = next(iter(dl))
self._compare_batches(sample, DUMMY_SAMPLES_2[1])
def test_num_samples_logic(self):
dataset = TestDataset(DUMMY_SAMPLES_2)
self.assertEqual(len(dataset), 2)
dataset = TestDataset(DUMMY_SAMPLES_2, num_samples=1)
# Verify len returns right value for dataset
self.assertEqual(len(dataset), 1)
# Verify len returns right value for iterator
self.assertEqual(len(dataset.iterator(num_workers=0)), 1)
# Verify iterator returns correct number of samples
it = iter(dataset.iterator(num_workers=0))
num_samples = 0
while True:
try:
next(it)
num_samples += 1
except StopIteration:
break
self.assertEqual(num_samples, 1)
# Check assert for num_samples > length of base dataset
dataset = TestDataset(DUMMY_SAMPLES_2, num_samples=3)
with self.assertRaises(AssertionError):
len(dataset)
def test_shuffle_logic(self):
# Simple samples to test shuffling, just a single value tensor
# so we know how things were shuffled
dummy_samples_10 = [
{"input": torch.tensor([[0]]), "target": torch.tensor([0])},
{"input": torch.tensor([[1]]), "target": torch.tensor([0])},
{"input": torch.tensor([[2]]), "target": torch.tensor([0])},
{"input": torch.tensor([[3]]), "target": torch.tensor([0])},
{"input": torch.tensor([[4]]), "target": torch.tensor([0])},
{"input": torch.tensor([[5]]), "target": torch.tensor([0])},
{"input": torch.tensor([[6]]), "target": torch.tensor([0])},
{"input": torch.tensor([[7]]), "target": torch.tensor([0])},
{"input": torch.tensor([[8]]), "target": torch.tensor([0])},
{"input": torch.tensor([[9]]), "target": torch.tensor([0])},
]
dataset = TestDataset(dummy_samples_10, shuffle=True)
def unpack_tensors(tensor_list):
return [t["input"].item() for t in tensor_list]
# Epoch 0
iterator = dataset.iterator(num_workers=0, current_phase_id=0)
it = iter(iterator)
epoch_0_list = [sample for sample in it]
epoch_0_list = unpack_tensors(epoch_0_list)
# Epoch 1
iterator = dataset.iterator(num_workers=0, current_phase_id=1)
it = iter(iterator)
epoch_1_list = [sample for sample in it]
epoch_1_list = unpack_tensors(epoch_1_list)
# Should be same length, should be shuffled, should be
# different shuffles for each epoch
self.assertEqual(len(epoch_0_list), len(epoch_1_list))
self.assertTrue(epoch_0_list != [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
self.assertTrue(epoch_0_list != epoch_1_list)
# Test different shuffle seeds
iterator = dataset.iterator(num_workers=0, current_phase_id=0, shuffle_seed=10)
it = iter(iterator)
epoch_0_seed_10_list = [sample for sample in it]
epoch_0_seed_10_list = unpack_tensors(epoch_0_seed_10_list)
self.assertTrue(epoch_0_seed_10_list != epoch_0_list)
def test_transform_logic(self):
def _return_1_transform(sample):
return 1
dataset = TestDataset(DUMMY_SAMPLES_2, transform=_return_1_transform)
sample = dataset[0]
self.assertEqual(sample, 1)