test_multiprocess_dataloader_dataset.py 16.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import division

import unittest
import numpy as np

import paddle
import paddle.fluid as fluid
22
from paddle.io import Dataset, IterableDataset, TensorDataset, \
23
        ComposeDataset, ChainDataset, DataLoader, random_split, Subset
W
wanghuancoder 已提交
24
from paddle.fluid.framework import _test_eager_guard, _in_legacy_dygraph
25

26 27 28 29
IMAGE_SIZE = 32


class RandomDataset(Dataset):
30

31 32 33 34 35 36 37 38 39 40 41 42 43 44
    def __init__(self, sample_num):
        self.sample_num = sample_num

    def __len__(self):
        return self.sample_num

    def __getitem__(self, idx):
        np.random.seed(idx)
        image = np.random.random([IMAGE_SIZE]).astype('float32')
        label = np.random.randint(0, 9, (1, )).astype('int64')
        return image, label


class RandomIterableDataset(IterableDataset):
45

46 47 48 49 50 51 52 53 54 55
    def __init__(self, sample_num):
        self.sample_num = sample_num

    def __iter__(self):
        for i in range(self.sample_num):
            np.random.seed(i)
            image = np.random.random([IMAGE_SIZE]).astype('float32')
            label = np.random.randint(0, 9, (1, )).astype('int64')
            yield image, label

56 57

class TestTensorDataset(unittest.TestCase):
58

59
    def run_main(self, num_workers, places):
60 61 62
        paddle.static.default_startup_program().random_seed = 1
        paddle.static.default_main_program().random_seed = 1
        place = paddle.CPUPlace()
63 64
        with fluid.dygraph.guard(place):
            input_np = np.random.random([16, 3, 4]).astype('float32')
65
            input = paddle.to_tensor(input_np)
66
            label_np = np.random.random([16, 1]).astype('int32')
67
            label = paddle.to_tensor(label_np)
68 69 70

            dataset = TensorDataset([input, label])
            assert len(dataset) == 16
71 72 73 74 75
            dataloader = DataLoader(dataset,
                                    places=place,
                                    num_workers=num_workers,
                                    batch_size=1,
                                    drop_last=True)
76 77 78 79 80 81

            for i, (input, label) in enumerate(dataloader()):
                assert len(input) == 1
                assert len(label) == 1
                assert input.shape == [1, 3, 4]
                assert label.shape == [1, 1]
W
wanghuancoder 已提交
82 83 84 85
                assert isinstance(input,
                                  (fluid.core.VarBase, fluid.core.eager.Tensor))
                assert isinstance(label,
                                  (fluid.core.VarBase, fluid.core.eager.Tensor))
86 87 88
                assert np.allclose(input.numpy(), input_np[i])
                assert np.allclose(label.numpy(), label_np[i])

W
wanghuancoder 已提交
89
    def func_test_main(self):
90 91 92
        places = [paddle.CPUPlace()]
        if paddle.is_compiled_with_cuda():
            places.append(paddle.CUDAPlace(0))
93
        for p in places:
94 95
            self.run_main(num_workers=0, places=p)

W
wanghuancoder 已提交
96 97 98 99 100
    def test_main(self):
        with _test_eager_guard():
            self.func_test_main()
        self.func_test_main()

101 102

class TestComposeDataset(unittest.TestCase):
103

W
wanghuancoder 已提交
104
    def func_test_main(self):
105 106
        paddle.static.default_startup_program().random_seed = 1
        paddle.static.default_main_program().random_seed = 1
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121

        dataset1 = RandomDataset(10)
        dataset2 = RandomDataset(10)
        dataset = ComposeDataset([dataset1, dataset2])
        assert len(dataset) == 10

        for i in range(len(dataset)):
            input1, label1, input2, label2 = dataset[i]
            input1_t, label1_t = dataset1[i]
            input2_t, label2_t = dataset2[i]
            assert np.allclose(input1, input1_t)
            assert np.allclose(label1, label1_t)
            assert np.allclose(input2, input2_t)
            assert np.allclose(label2, label2_t)

W
wanghuancoder 已提交
122 123 124 125 126
    def test_main(self):
        with _test_eager_guard():
            self.func_test_main()
        self.func_test_main()

127

128
class TestRandomSplitApi(unittest.TestCase):
129

W
wanghuancoder 已提交
130
    def func_test_main(self):
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
        paddle.static.default_startup_program().random_seed = 1
        paddle.static.default_main_program().random_seed = 1

        dataset1, dataset2 = paddle.io.random_split(range(5), [1, 4])

        self.assertTrue(len(dataset1) == 1)
        self.assertTrue(len(dataset2) == 4)

        elements_list = list(range(5))

        for _, val in enumerate(dataset1):
            elements_list.remove(val)

        for _, val in enumerate(dataset2):
            elements_list.remove(val)

        self.assertTrue(len(elements_list) == 0)

W
wanghuancoder 已提交
149 150 151 152 153
    def test_main(self):
        with _test_eager_guard():
            self.func_test_main()
        self.func_test_main()

154 155

class TestRandomSplitError(unittest.TestCase):
156

W
wanghuancoder 已提交
157
    def func_test_errors(self):
158 159 160 161 162 163 164
        paddle.static.default_startup_program().random_seed = 1
        paddle.static.default_main_program().random_seed = 1

        self.assertRaises(ValueError, paddle.io.random_split, range(5), [3, 8])
        self.assertRaises(ValueError, paddle.io.random_split, range(5), [8])
        self.assertRaises(ValueError, paddle.io.random_split, range(5), [])

W
wanghuancoder 已提交
165 166 167 168 169
    def test_errors(self):
        with _test_eager_guard():
            self.func_test_errors()
        self.func_test_errors()

170 171

class TestSubsetDataset(unittest.TestCase):
172

173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
    def run_main(self, num_workers, places):
        paddle.static.default_startup_program().random_seed = 1
        paddle.static.default_main_program().random_seed = 1

        input_np = np.random.random([5, 3, 4]).astype('float32')
        input = paddle.to_tensor(input_np)
        label_np = np.random.random([5, 1]).astype('int32')
        label = paddle.to_tensor(label_np)

        dataset = TensorDataset([input, label])
        even_subset = paddle.io.Subset(dataset, [0, 2, 4])
        odd_subset = paddle.io.Subset(dataset, [1, 3])

        assert len(dataset) == 5

        def prepare_dataloader(dataset):
189 190 191 192 193
            return DataLoader(dataset,
                              places=places,
                              num_workers=num_workers,
                              batch_size=1,
                              drop_last=True)
194 195 196 197 198 199 200 201 202 203

        dataloader = prepare_dataloader(dataset)
        dataloader_even = prepare_dataloader(even_subset)
        dataloader_odd = prepare_dataloader(odd_subset)

        def assert_basic(input, label):
            assert len(input) == 1
            assert len(label) == 1
            assert input.shape == [1, 3, 4]
            assert label.shape == [1, 1]
W
wanghuancoder 已提交
204 205 206 207
            assert isinstance(input,
                              (fluid.core.VarBase, fluid.core.eager.Tensor))
            assert isinstance(label,
                              (fluid.core.VarBase, fluid.core.eager.Tensor))
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224

        elements_list = list()
        for _, (input, label) in enumerate(dataloader()):
            assert_basic(input, label)
            elements_list.append(label)

        for _, (input, label) in enumerate(dataloader_even()):
            assert_basic(input, label)
            elements_list.remove(label)

        odd_list = list()
        for _, (input, label) in enumerate(dataloader_odd()):
            assert_basic(input, label)
            odd_list.append(label)

        self.assertEqual(odd_list, elements_list)

W
wanghuancoder 已提交
225
    def func_test_main(self):
226 227 228 229 230 231 232 233 234
        paddle.static.default_startup_program().random_seed = 1
        paddle.static.default_main_program().random_seed = 1

        places = [paddle.CPUPlace()]
        if paddle.is_compiled_with_cuda():
            places.append(paddle.CUDAPlace(0))
        for p in places:
            self.run_main(num_workers=0, places=p)

W
wanghuancoder 已提交
235 236 237 238 239
    def test_main(self):
        with _test_eager_guard():
            self.func_test_main()
        self.func_test_main()

240

241
class TestChainDataset(unittest.TestCase):
242

243
    def run_main(self, num_workers, places):
244 245
        paddle.static.default_startup_program().random_seed = 1
        paddle.static.default_main_program().random_seed = 1
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265

        dataset1 = RandomIterableDataset(10)
        dataset2 = RandomIterableDataset(10)
        dataset = ChainDataset([dataset1, dataset2])

        samples = []
        for data in iter(dataset):
            samples.append(data)
        assert len(samples) == 20

        idx = 0
        for image, label in iter(dataset1):
            assert np.allclose(image, samples[idx][0])
            assert np.allclose(label, samples[idx][1])
            idx += 1
        for image, label in iter(dataset2):
            assert np.allclose(image, samples[idx][0])
            assert np.allclose(label, samples[idx][1])
            idx += 1

W
wanghuancoder 已提交
266
    def func_test_main(self):
267 268 269
        places = [paddle.CPUPlace()]
        if paddle.is_compiled_with_cuda():
            places.append(paddle.CUDAPlace(0))
270
        for p in places:
271
            self.run_main(num_workers=0, places=p)
272

W
wanghuancoder 已提交
273 274 275 276 277
    def test_main(self):
        with _test_eager_guard():
            self.func_test_main()
        self.func_test_main()

278

279
class NumpyMixTensorDataset(Dataset):
280

281 282 283 284 285 286 287 288 289 290 291 292 293 294
    def __init__(self, sample_num):
        self.sample_num = sample_num

    def __len__(self):
        return self.sample_num

    def __getitem__(self, idx):
        np.random.seed(idx)
        image = np.random.random([IMAGE_SIZE]).astype('float32')
        label = np.random.randint(0, 9, (1, )).astype('int64')
        return paddle.to_tensor(image, place=paddle.CPUPlace()), label


class TestNumpyMixTensorDataset(TestTensorDataset):
295

296 297 298 299 300 301 302
    def run_main(self, num_workers, places):
        paddle.static.default_startup_program().random_seed = 1
        paddle.static.default_main_program().random_seed = 1
        place = paddle.CPUPlace()
        with fluid.dygraph.guard(place):
            dataset = NumpyMixTensorDataset(16)
            assert len(dataset) == 16
303 304 305 306 307
            dataloader = DataLoader(dataset,
                                    places=place,
                                    num_workers=num_workers,
                                    batch_size=1,
                                    drop_last=True)
308 309 310 311 312 313

            for i, (input, label) in enumerate(dataloader()):
                assert len(input) == 1
                assert len(label) == 1
                assert input.shape == [1, IMAGE_SIZE]
                assert label.shape == [1, 1]
W
wanghuancoder 已提交
314 315 316 317
                assert isinstance(input,
                                  (fluid.core.VarBase, fluid.core.eager.Tensor))
                assert isinstance(label,
                                  (fluid.core.VarBase, fluid.core.eager.Tensor))
318 319


320
class ComplextDataset(Dataset):
321

322 323 324 325 326 327 328
    def __init__(self, sample_num):
        self.sample_num = sample_num

    def __len__(self):
        return self.sample_num

    def __getitem__(self, idx):
329 330 331 332
        return (3.1, 'abc',
                paddle.to_tensor(np.random.random([IMAGE_SIZE
                                                   ]).astype('float32'),
                                 place=paddle.CPUPlace()),
333 334 335 336 337 338 339
                [1, np.random.random([2]).astype('float32')], {
                    'a': 2.0,
                    'b': np.random.random([2]).astype('float32')
                })


class TestComplextDataset(unittest.TestCase):
340

341 342 343 344 345 346 347
    def run_main(self, num_workers):
        paddle.static.default_startup_program().random_seed = 1
        paddle.static.default_main_program().random_seed = 1
        place = paddle.CPUPlace()
        with fluid.dygraph.guard(place):
            dataset = ComplextDataset(16)
            assert len(dataset) == 16
348 349 350 351 352
            dataloader = DataLoader(dataset,
                                    places=place,
                                    num_workers=num_workers,
                                    batch_size=2,
                                    drop_last=True)
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373

            for i, data in enumerate(dataloader()):
                assert len(data) == 5
                # data[0]: collate 3.1
                assert data[0].shape == [2]
                assert isinstance(data[1], list)
                # data[1]: collate 'abc'
                assert len(data[1]) == 2
                assert isinstance(data[1][0], str)
                assert isinstance(data[1][1], str)
                # data[2]: collate tensor
                assert data[2].shape == [2, IMAGE_SIZE]
                # data[3]: collate list
                assert isinstance(data[3], list)
                assert data[3][0].shape == [2]
                assert data[3][1].shape == [2, 2]
                # data[4]: collate dict
                assert isinstance(data[4], dict)
                assert data[4]['a'].shape == [2]
                assert data[4]['b'].shape == [2, 2]

W
wanghuancoder 已提交
374
    def func_test_main(self):
375 376 377
        for num_workers in [0, 2]:
            self.run_main(num_workers)

W
wanghuancoder 已提交
378 379 380 381 382
    def test_main(self):
        with _test_eager_guard():
            self.func_test_main()
        self.func_test_main()

383

384
class SingleFieldDataset(Dataset):
385

386 387 388 389 390 391 392 393 394 395 396
    def __init__(self, sample_num):
        self.sample_num = sample_num

    def __len__(self):
        return self.sample_num

    def __getitem__(self, idx):
        return np.random.random((2, 3)).astype('float32')


class TestSingleFieldDataset(unittest.TestCase):
397

398 399 400 401 402 403 404 405 406 407
    def init_dataset(self):
        self.sample_num = 16
        self.dataset = SingleFieldDataset(self.sample_num)

    def run_main(self, num_workers):
        paddle.static.default_startup_program().random_seed = 1
        paddle.static.default_main_program().random_seed = 1
        place = paddle.CPUPlace()
        with fluid.dygraph.guard(place):
            self.init_dataset()
408 409 410 411 412
            dataloader = DataLoader(self.dataset,
                                    places=place,
                                    num_workers=num_workers,
                                    batch_size=2,
                                    drop_last=True)
413 414

            for i, data in enumerate(dataloader()):
W
wanghuancoder 已提交
415 416
                assert isinstance(data,
                                  (fluid.core.VarBase, fluid.core.eager.Tensor))
417 418
                assert data.shape == [2, 2, 3]

W
wanghuancoder 已提交
419
    def func_test_main(self):
420 421 422
        for num_workers in [0, 2]:
            self.run_main(num_workers)

W
wanghuancoder 已提交
423 424 425 426 427
    def test_main(self):
        with _test_eager_guard():
            self.func_test_main()
        self.func_test_main()

428 429

class SingleFieldIterableDataset(IterableDataset):
430

431 432 433 434 435 436 437 438 439
    def __init__(self, sample_num):
        self.sample_num = sample_num

    def __iter__(self):
        for _ in range(self.sample_num):
            yield np.random.random((2, 3)).astype('float32')


class TestSingleFieldIterableDataset(TestSingleFieldDataset):
440

441 442 443 444 445
    def init_dataset(self):
        self.sample_num = 16
        self.dataset = SingleFieldIterableDataset(self.sample_num)


446
class TestDataLoaderGenerateStates(unittest.TestCase):
447

448 449 450 451 452 453
    def setUp(self):
        self.inputs = [(0, 1), (0, 2), (1, 3)]
        self.outputs = [[1835504127, 1731038949, 1320224556, 2330041505],
                        [2834126987, 2358157858, 1860244682, 1437227251],
                        [457190280, 2660306227, 859341110, 354512857]]

W
wanghuancoder 已提交
454
    def func_test_main(self):
455 456 457 458 459
        from paddle.fluid.dataloader.worker import _generate_states
        for inp, outp in zip(self.inputs, self.outputs):
            out = _generate_states(*inp)
            assert out == outp

W
wanghuancoder 已提交
460 461 462 463 464
    def test_main(self):
        with _test_eager_guard():
            self.func_test_main()
        self.func_test_main()

465

466
class TestDatasetWithDropLast(unittest.TestCase):
467

468 469 470 471 472
    def run_main(self, dataset, num_samples, batch_size):
        for num_workers in [0, 1]:
            for drop_last in [True, False]:
                steps = (num_samples + (1 - int(drop_last)) * \
                        (batch_size - 1)) // batch_size
473 474 475 476
                dataloader = DataLoader(dataset,
                                        batch_size=batch_size,
                                        drop_last=drop_last,
                                        num_workers=num_workers)
477 478 479 480 481
                datas = []
                for data in dataloader:
                    datas.append(data)
                assert len(datas) == steps

W
wanghuancoder 已提交
482
    def func_test_map_dataset(self):
483 484 485
        dataset = RandomDataset(10)
        self.run_main(dataset, 10, 3)

W
wanghuancoder 已提交
486 487 488 489 490 491
    def test_map_dataset(self):
        with _test_eager_guard():
            self.func_test_map_dataset()
        self.func_test_map_dataset()

    def func_test_iterable_dataset(self):
492 493 494
        dataset = RandomIterableDataset(10)
        self.run_main(dataset, 10, 3)

W
wanghuancoder 已提交
495 496 497 498 499
    def test_iterable_dataset(self):
        with _test_eager_guard():
            self.func_test_iterable_dataset()
        self.func_test_iterable_dataset()

500

501 502
if __name__ == '__main__':
    unittest.main()