test_multiprocess_dataloader_exception.py 8.1 KB
Newer Older
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
# 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 os
import sys
import six
import time
import unittest
import multiprocessing
import numpy as np

import paddle.fluid as fluid
26
import paddle.fluid.core as core
27
from paddle.io import Dataset, IterableDataset, BatchSampler, DataLoader
28 29
from paddle.fluid.dygraph.nn import Linear
from paddle.fluid.dygraph.base import to_variable
30
from paddle.fluid.dataloader.dataloader_iter import _worker_loop
31 32 33


class RandomDataset(Dataset):
34

35 36 37 38 39 40 41 42 43 44 45 46 47 48
    def __init__(self, sample_num):
        self.sample_num = sample_num

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

    def __len__(self):
        return self.sample_num


class TestDataLoaderAssert(unittest.TestCase):
49

50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
    def test_main(self):
        place = fluid.cpu_places()[0]
        with fluid.dygraph.guard(place):
            dataset = RandomDataset(100)
            batch_sampler = BatchSampler(dataset=dataset, batch_size=4)

            # dataset is not instance of Dataset
            try:
                loader = DataLoader(dataset=batch_sampler, places=place)
                self.assertTrue(False)
            except AssertionError:
                pass

            # places is None
            try:
                loader = DataLoader(dataset=dataset, places=None)
                self.assertTrue(False)
            except AssertionError:
                pass

            # num_workers < 0
            try:
72 73 74
                loader = DataLoader(dataset=dataset,
                                    places=place,
                                    num_workers=-1)
75 76 77 78 79 80 81 82 83 84 85 86 87
                self.assertTrue(False)
            except AssertionError:
                pass

            # timeout < 0
            try:
                loader = DataLoader(dataset=dataset, places=place, timeout=-1)
                self.assertTrue(False)
            except AssertionError:
                pass

            # set batch_sampler and shuffle/batch_size/drop_last
            try:
88 89 90 91 92
                loader = DataLoader(dataset=dataset,
                                    places=place,
                                    batch_sampler=batch_sampler,
                                    shuffle=True,
                                    drop_last=True)
93 94 95 96 97 98
                self.assertTrue(False)
            except AssertionError:
                pass

            # set batch_sampler correctly
            try:
99 100 101
                loader = DataLoader(dataset=dataset,
                                    places=place,
                                    batch_sampler=batch_sampler)
102 103 104 105 106
                self.assertTrue(True)
            except AssertionError:
                self.assertTrue(False)


107
class TestDatasetRuntimeError(unittest.TestCase):
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
    def test_main(self):
        dataset = Dataset()

        # __getitem__ not implement
        try:
            d = dataset[0]
            self.assertTrue(False)
        except NotImplementedError:
            pass

        # __len__ not implement
        try:
            l = len(dataset)
            self.assertTrue(False)
        except NotImplementedError:
            pass

        dataset = IterableDataset()

        # __iter__ not implement
        try:
            d = iter(dataset)
            self.assertTrue(False)
        except NotImplementedError:
            pass

        # __getitem__ runtime error
        try:
            d = dataset[0]
            self.assertTrue(False)
        except RuntimeError:
            pass

        # __len__ runtime error
        try:
            l = len(dataset)
            self.assertTrue(False)
        except RuntimeError:
            pass


150 151
# CI Converage cannot record stub in subprocess,
# HACK a _worker_loop in main process call here
152 153
@unittest.skipIf(not core.is_compiled_with_cuda(),
                 "core is not compiled with CUDA")
154
class TestDataLoaderWorkerLoop(unittest.TestCase):
155

156 157 158 159 160 161 162 163 164 165 166 167 168
    def run_without_worker_done(self, use_shared_memory=True):
        try:
            place = fluid.cpu_places()[0]
            with fluid.dygraph.guard(place):
                dataset = RandomDataset(800)

                # test init_fn
                def _init_fn(worker_id):
                    pass

                # test collate_fn
                def _collate_fn(sample_list):
                    return [
169
                        np.stack(s, axis=0) for s in list(zip(*sample_list))
170 171
                    ]

172 173 174 175
                loader = DataLoader(dataset,
                                    num_workers=1,
                                    places=place,
                                    use_shared_memory=use_shared_memory)
176 177 178 179 180 181 182 183
                assert loader.num_workers > 0, \
                    "go to AssertionError and pass in Mac and Windows"
                loader = iter(loader)
                print("loader length", len(loader))
                indices_queue = multiprocessing.Queue()
                for i in range(10):
                    indices_queue.put([i, i + 10])
                indices_queue.put(None)
184
                base_seed = 1234
185 186
                _worker_loop(loader._dataset, 0, indices_queue,
                             loader._data_queue, loader._workers_done_event,
187
                             True, _collate_fn, True, _init_fn, 0, 1,
188
                             loader._use_shared_memory, base_seed)
189 190 191
                self.assertTrue(False)
        except AssertionError:
            pass
192 193 194 195
        except Exception as e:
            print("Exception", e)
            import sys
            sys.stdout.flush()
196 197 198 199
            self.assertTrue(False)

    def run_with_worker_done(self, use_shared_memory=True):
        try:
200
            place = fluid.CPUPlace()
201 202 203 204 205 206 207 208 209 210
            with fluid.dygraph.guard(place):
                dataset = RandomDataset(800)

                # test init_fn
                def _init_fn(worker_id):
                    pass

                # test collate_fn
                def _collate_fn(sample_list):
                    return [
211
                        np.stack(s, axis=0) for s in list(zip(*sample_list))
212 213
                    ]

214 215 216 217
                loader = DataLoader(dataset,
                                    num_workers=1,
                                    places=place,
                                    use_shared_memory=use_shared_memory)
218 219 220 221 222 223 224 225 226
                assert loader.num_workers > 0, \
                    "go to AssertionError and pass in Mac and Windows"
                loader = iter(loader)
                print("loader length", len(loader))
                indices_queue = multiprocessing.Queue()
                for i in range(10):
                    indices_queue.put([i, i + 10])
                indices_queue.put(None)
                loader._workers_done_event.set()
227
                base_seed = 1234
228 229
                _worker_loop(loader._dataset, 0, indices_queue,
                             loader._data_queue, loader._workers_done_event,
230
                             True, _collate_fn, True, _init_fn, 0, 1,
231
                             loader._use_shared_memory, base_seed)
232 233 234 235 236 237 238
                self.assertTrue(True)
        except AssertionError:
            pass
        except Exception:
            self.assertTrue(False)

    def test_main(self):
239 240
        # only HACK a subprocess call here, do not need to use_shared_memory
        for use_shared_memory in [False]:
241 242 243 244 245 246
            self.run_without_worker_done(use_shared_memory)
            self.run_with_worker_done(use_shared_memory)


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