test_generator_dataloader.py 7.6 KB
Newer Older
Z
Zeng Jinle 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# 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 time
import unittest
17 18 19 20 21

import numpy as np

import paddle
import paddle.fluid as fluid
Z
Zeng Jinle 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
from paddle.fluid.reader import DataLoaderBase

EPOCH_NUM = 20
BATCH_SIZE = 32
BATCH_NUM = 20
CLASS_NUM = 10


def random_reader():
    np.random.seed(1)
    for i in range(BATCH_SIZE * BATCH_NUM):
        image = np.random.random([784])
        label = np.random.random_integers(low=0, high=CLASS_NUM - 1)
        yield image, label


def simple_fc_net(places, use_legacy_py_reader, use_double_buffer):
C
cnn 已提交
39
    paddle.seed(1)
L
Leo Chen 已提交
40
    paddle.framework.random._manual_program_seed(1)
Z
Zeng Jinle 已提交
41 42 43 44 45
    startup_prog = fluid.Program()
    main_prog = fluid.Program()

    with fluid.unique_name.guard():
        with fluid.program_guard(main_prog, startup_prog):
G
GGBond8488 已提交
46 47 48 49 50
            image = paddle.static.data(
                name='image', shape=[-1, 784], dtype='float32'
            )
            label = paddle.static.data(
                name='label', shape=[-1, 1], dtype='int64'
51
            )
Z
Zeng Jinle 已提交
52 53 54 55
            py_reader = fluid.io.DataLoader.from_generator(
                feed_list=[image, label],
                capacity=4,
                iterable=not use_legacy_py_reader,
56 57
                use_double_buffer=use_double_buffer,
            )
Z
Zeng Jinle 已提交
58 59
            hidden = image
            for hidden_size in [10, 20, 30]:
C
Charles-hit 已提交
60
                hidden = paddle.static.nn.fc(
Z
Zeng Jinle 已提交
61 62
                    hidden,
                    size=hidden_size,
C
Charles-hit 已提交
63
                    activation='tanh',
Z
Zeng Jinle 已提交
64
                    bias_attr=fluid.ParamAttr(
65 66 67
                        initializer=fluid.initializer.Constant(value=1.0)
                    ),
                )
Z
Zeng Jinle 已提交
68

C
Charles-hit 已提交
69 70
            predict_label = paddle.static.nn.fc(
                hidden, size=CLASS_NUM, activation='softmax'
71
            )
72
            loss = paddle.mean(
73 74 75 76 77 78
                paddle.nn.functional.cross_entropy(
                    input=predict_label,
                    label=label,
                    reduction='none',
                    use_softmax=False,
                )
79
            )
Z
Zeng Jinle 已提交
80 81 82 83 84 85 86

            optimizer = fluid.optimizer.Adam()
            optimizer.minimize(loss)
    return startup_prog, main_prog, py_reader, loss


class TestBase(unittest.TestCase):
87 88 89 90 91 92 93
    def run_main(
        self,
        use_legacy_py_reader,
        with_data_parallel,
        places,
        use_double_buffer,
    ):
Z
Zeng Jinle 已提交
94 95 96
        scope = fluid.Scope()
        with fluid.scope_guard(scope):
            startup_prog, main_prog, py_reader, loss = simple_fc_net(
97 98
                places, use_legacy_py_reader, use_double_buffer
            )
Z
Zeng Jinle 已提交
99 100 101 102 103 104

            reader = paddle.batch(random_reader, batch_size=BATCH_SIZE)

            ps = places if use_double_buffer else fluid.cpu_places(len(places))

            py_reader.set_sample_list_generator(
105 106
                reader, places=ps if py_reader.iterable else None
            )
Z
Zeng Jinle 已提交
107 108 109 110 111 112

            exe = fluid.Executor(place=places[0])
            exe.run(startup_prog)

            prog = fluid.CompiledProgram(main_prog)
            if with_data_parallel:
113 114 115
                prog = prog.with_data_parallel(
                    loss_name=loss.name, places=places
                )
Z
Zeng Jinle 已提交
116 117 118 119 120 121

            step = 0
            step_list = []
            loss_list = []
            start_t = time.time()
            if not py_reader.iterable:
122
                for _ in range(EPOCH_NUM):
Z
Zeng Jinle 已提交
123 124 125 126
                    step = 0
                    py_reader.start()
                    while True:
                        try:
127 128 129 130 131
                            (L,) = exe.run(
                                program=prog,
                                fetch_list=[loss],
                                use_program_cache=True,
                            )
Z
Zeng Jinle 已提交
132 133 134 135 136 137 138
                            loss_list.append(np.mean(L))
                            step += 1
                        except fluid.core.EOFException:
                            py_reader.reset()
                            break
                    step_list.append(step)
            else:
139
                for _ in range(EPOCH_NUM):
Z
Zeng Jinle 已提交
140 141 142
                    step = 0
                    for d in py_reader():
                        assert len(d) == len(places), "{} != {}".format(
143 144
                            len(d), len(places)
                        )
Z
Zeng Jinle 已提交
145 146 147 148 149
                        for i, item in enumerate(d):
                            image = item['image']
                            label = item['label']
                            assert image.shape() == [BATCH_SIZE, 784]
                            assert label.shape() == [BATCH_SIZE, 1]
150 151
                            assert image._place()._equals(ps[i])
                            assert label._place()._equals(ps[i])
152 153 154 155 156 157
                        (L,) = exe.run(
                            program=prog,
                            feed=d,
                            fetch_list=[loss],
                            use_program_cache=True,
                        )
Z
Zeng Jinle 已提交
158 159 160 161 162 163 164
                        loss_list.append(np.mean(L))
                        step += 1
                    step_list.append(step)
            end_t = time.time()
            ret = {
                "time": end_t - start_t,
                "step": step_list,
165
                "loss": np.array(loss_list),
Z
Zeng Jinle 已提交
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
            }
            return ret

    def prepare_places(self, with_data_parallel, with_cpu=True, with_gpu=True):
        places = []
        if with_cpu:
            places.append([fluid.CPUPlace()])
            if with_data_parallel:
                places.append([fluid.CPUPlace()] * 2)

        if with_gpu and fluid.core.is_compiled_with_cuda():
            tmp = fluid.cuda_places()
            assert len(tmp) > 0, "no gpu detected"
            if with_data_parallel:
                places.append(tmp)
            places.append([tmp[0]])
        return places

    def test_main(self):
        for with_data_parallel in [True, False]:
            for p in self.prepare_places(with_data_parallel):
                for use_double_buffer in [False, True]:
                    results = []
                    for use_legacy_py_reader in [False, True]:
                        print(p, use_double_buffer, use_legacy_py_reader)
                        ret = self.run_main(
                            use_legacy_py_reader=use_legacy_py_reader,
                            with_data_parallel=with_data_parallel,
                            places=p,
195 196
                            use_double_buffer=use_double_buffer,
                        )
Z
Zeng Jinle 已提交
197 198 199
                        results.append(ret)
                    if not use_double_buffer:
                        diff = np.max(
200 201
                            np.abs(results[0]['loss'] - results[1]['loss'])
                        )
Z
Zeng Jinle 已提交
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
                        self.assertLess(diff, 1e-3)


class TestDataLoaderBaseAbstract(unittest.TestCase):
    def test_main(self):
        loader = DataLoaderBase()
        try:
            loader.__iter__()
            self.assertTrue(False)
        except NotImplementedError:
            self.assertTrue(True)

        try:
            loader.__next__()
            self.assertTrue(False)
        except NotImplementedError:
            self.assertTrue(True)


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