test_dataset_dataloader.py 8.0 KB
Newer Older
Z
Zeng Jinle 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Copyright (c) 2019 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.

import os
16
import tempfile
17 18 19
import unittest

import numpy as np
Z
Zeng Jinle 已提交
20 21
from simple_nets import simple_fc_net_with_inputs

22 23 24
import paddle
import paddle.fluid as fluid

Z
Zeng Jinle 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
BATCH_SIZE = 32
BATCH_NUM = 10
EPOCH_NUM = 4

IMAGE_SHAPE = [2, 3]
LABEL_SHAPE = [1]


def get_place_string(p):
    if isinstance(p, (fluid.CPUPlace or fluid.CUDAPlace)):
        tmp = fluid.core.Place()
        tmp.set_place(p)
        p = tmp

    if p._type() == fluid.CPUPlace()._type():
        return 'CPUPlace()'
    else:
        return 'CUDAPlace()'


def write_reader_data_to_file(filename, reader):
    with open(filename, 'w') as fid:
        for instance_list in reader():
            for i, instance in enumerate(instance_list):
49 50 51 52 53 54
                instance = np.reshape(
                    instance,
                    [
                        instance.size,
                    ],
                )
Z
Zeng Jinle 已提交
55 56 57 58 59 60 61 62 63 64 65
                fid.write(str(instance.size) + ' ')
                fid.write(' '.join(map(str, instance)))
                fid.write(' ')

            fid.write('\n')


def fake_reader(batch_size=BATCH_SIZE, batch_num=BATCH_NUM):
    def __reader__():
        iteration = BATCH_SIZE * BATCH_NUM
        iteration = int(iteration + BATCH_SIZE / 2)
66
        for _ in range(iteration):
Z
Zeng Jinle 已提交
67
            image = np.random.random(size=IMAGE_SHAPE).astype('float32')
68 69 70
            label = np.random.random_integers(
                size=LABEL_SHAPE, low=0, high=9
            ).astype('int64')
Z
Zeng Jinle 已提交
71 72 73 74 75 76 77 78 79
            yield image, label

    return __reader__


class DatasetLoaderTestBase(unittest.TestCase):
    def setUp(self):
        self.dataset_name = "QueueDataset"
        self.drop_last = False
80
        self.temp_dir = tempfile.TemporaryDirectory()
Z
Zeng Jinle 已提交
81 82

    def tearDown(self):
83
        self.temp_dir.cleanup()
Z
Zeng Jinle 已提交
84 85 86 87 88

    def build_network(self):
        main_prog = fluid.Program()
        startup_prog = fluid.Program()
        with fluid.program_guard(main_prog, startup_prog):
89 90 91 92 93 94
            image = fluid.layers.data(
                name='image', shape=IMAGE_SHAPE, dtype='float32'
            )
            label = fluid.layers.data(
                name='label', shape=LABEL_SHAPE, dtype='int64'
            )
Z
Zeng Jinle 已提交
95 96 97 98 99 100 101

            simple_fc_net_with_inputs(image, label)

        return main_prog, startup_prog, [image, label]

    def check_batch_number(self, place, randomize_batch_num=False):
        main_prog, startup_prog, feeds = self.build_network()
102 103 104 105 106
        if self.dataset_name == "QueueDataset":
            dataset = paddle.distributed.QueueDataset()
        else:
            dataset = paddle.distributed.InMemoryDataset()
        dataset._set_batch_size(BATCH_SIZE)
Z
Zeng Jinle 已提交
107 108 109 110 111 112 113 114 115 116 117 118 119 120

        if isinstance(place, fluid.CPUPlace):
            file_num = 10
            os.environ['CPU_NUM'] = str(file_num)
            places = fluid.cpu_places()
            use_cuda = False
        else:
            file_num = fluid.core.get_cuda_device_count()
            places = fluid.cuda_places()
            use_cuda = True

        filelist = []
        if file_num > 1 and randomize_batch_num:
            random_delta_batch_size = np.random.random_integers(
121 122
                low=-BATCH_NUM / 2, high=BATCH_NUM / 2, size=[file_num]
            )
Z
Zeng Jinle 已提交
123
            random_delta_batch_size[-1] = -int(
124 125
                np.sum(random_delta_batch_size[0:-1])
            )
Z
Zeng Jinle 已提交
126 127 128
        else:
            random_delta_batch_size = np.zeros(shape=[file_num])

129
        for i in range(file_num):
130 131 132
            filename = os.path.join(
                self.temp_dir.name, 'dataset_test_{}.txt'.format(i)
            )
Z
Zeng Jinle 已提交
133 134 135
            filelist.append(filename)
            write_reader_data_to_file(
                filename,
136 137
                fake_reader(batch_num=BATCH_NUM + random_delta_batch_size[i]),
            )
Z
Zeng Jinle 已提交
138 139

        dataset.set_filelist(filelist)
140 141
        dataset._set_use_var(feeds)
        dataset._set_pipe_command("cat")
Z
Zeng Jinle 已提交
142 143 144
        if self.dataset_name == 'InMemoryDataset':
            dataset.load_into_memory()

145 146 147
        dataloader = fluid.io.DataLoader.from_dataset(
            dataset=dataset, places=places, drop_last=self.drop_last
        )
Z
Zeng Jinle 已提交
148 149 150 151 152
        prog = fluid.CompiledProgram(main_prog).with_data_parallel()
        exe = fluid.Executor(place)

        exe.run(startup_prog)

153
        for _ in range(EPOCH_NUM):
Z
Zeng Jinle 已提交
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
            has_complete_batch = False
            for batch_id, data in enumerate(dataloader):
                self.assertEquals(len(places), len(data))
                for idx, data_on_each_device in enumerate(data):
                    image = data_on_each_device["image"]
                    label = data_on_each_device["label"]

                    if self.drop_last:
                        batch_size = BATCH_SIZE
                    else:
                        if batch_id == BATCH_NUM:
                            batch_size = BATCH_SIZE / 2
                        else:
                            batch_size = BATCH_SIZE

                    self.assertEquals(image.shape()[1:], IMAGE_SHAPE)
170 171 172 173 174 175
                    self.assertTrue(
                        image._place()._equals(places[idx]),
                        msg=get_place_string(image._place())
                        + ' vs '
                        + get_place_string(places[idx]),
                    )
Z
Zeng Jinle 已提交
176 177 178
                    if self.drop_last:
                        self.assertEquals(image.shape()[0], BATCH_SIZE)
                    else:
179 180 181 182
                        self.assertTrue(
                            image.shape()[0] == BATCH_SIZE
                            or image.shape()[0] == BATCH_SIZE / 2
                        )
Z
Zeng Jinle 已提交
183 184 185 186 187 188

                    self.assertEquals(label.shape()[1:], LABEL_SHAPE)
                    self.assertTrue(label._place()._equals(places[idx]))
                    if self.drop_last:
                        self.assertEquals(label.shape()[0], BATCH_SIZE)
                    else:
189 190 191 192
                        self.assertTrue(
                            label.shape()[0] == BATCH_SIZE
                            or label.shape()[0] == BATCH_SIZE / 2
                        )
Z
Zeng Jinle 已提交
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

                    self.assertEquals(image.shape()[0], label.shape()[0])

                    if image.shape()[0] == BATCH_SIZE:
                        has_complete_batch = True

                exe.run(prog, feed=data)

            self.assertTrue(has_complete_batch)

    def get_all_places(self):
        p = [fluid.CPUPlace()]
        if fluid.is_compiled_with_cuda():
            p.append(fluid.CUDAPlace(0))
        return p

    def test_batch_number_with_same_length_files(self):
        for p in self.get_all_places():
            with fluid.scope_guard(fluid.Scope()):
                self.check_batch_number(place=p, randomize_batch_num=False)

    def test_batch_number_with_different_length_files(self):
        for p in self.get_all_places():
            with fluid.scope_guard(fluid.Scope()):
                self.check_batch_number(place=p, randomize_batch_num=True)


class QueueDatasetTestWithoutDropLast(DatasetLoaderTestBase):
    def setUp(self):
        self.dataset_name = "QueueDataset"
        self.drop_last = True
224
        self.temp_dir = tempfile.TemporaryDirectory()
Z
Zeng Jinle 已提交
225 226 227 228 229 230


class InMemoryDatasetTestWithoutDropLast(DatasetLoaderTestBase):
    def setUp(self):
        self.dataset_name = "InMemoryDataset"
        self.drop_last = False
231
        self.temp_dir = tempfile.TemporaryDirectory()
Z
Zeng Jinle 已提交
232 233 234 235 236 237


class InMemoryDatasetTestWithDropLast(DatasetLoaderTestBase):
    def setUp(self):
        self.dataset_name = "InMemoryDataset"
        self.drop_last = True
238
        self.temp_dir = tempfile.TemporaryDirectory()
Z
Zeng Jinle 已提交
239 240 241 242


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