test_model.py 16.9 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
from __future__ import print_function

import unittest

import os
import numpy as np
import shutil
import tempfile

from paddle import fluid
26
from paddle.nn import Conv2d, Pool2D, Linear, ReLU, Sequential
27 28
from paddle.fluid.dygraph.base import to_variable

29 30
import paddle.incubate.hapi as hapi
from paddle.incubate.hapi import Model, Input
31
from paddle.nn.layer.loss import CrossEntropyLoss
32 33 34 35 36 37 38
from paddle.incubate.hapi.metrics import Accuracy
from paddle.incubate.hapi.datasets import MNIST
from paddle.incubate.hapi.vision.models import LeNet
from paddle.incubate.hapi.distributed import DistributedBatchSampler, prepare_distributed_context


class LeNetDygraph(fluid.dygraph.Layer):
39
    def __init__(self, num_classes=10, classifier_activation=None):
40 41 42
        super(LeNetDygraph, self).__init__()
        self.num_classes = num_classes
        self.features = Sequential(
43
            Conv2d(
44
                1, 6, 3, stride=1, padding=1),
L
LielinJiang 已提交
45
            ReLU(),
46
            Pool2D(2, 'max', 2),
47
            Conv2d(
48
                6, 16, 5, stride=1, padding=0),
L
LielinJiang 已提交
49
            ReLU(),
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
            Pool2D(2, 'max', 2))

        if num_classes > 0:
            self.fc = Sequential(
                Linear(400, 120),
                Linear(120, 84),
                Linear(
                    84, 10, act=classifier_activation))

    def forward(self, inputs):
        x = self.features(inputs)

        if self.num_classes > 0:
            x = fluid.layers.flatten(x, 1)
            x = self.fc(x)
        return x


class MnistDataset(MNIST):
    def __init__(self, mode, return_label=True, sample_num=None):
        super(MnistDataset, self).__init__(mode=mode)
        self.return_label = return_label
        if sample_num:
            self.images = self.images[:sample_num]
            self.labels = self.labels[:sample_num]

    def __getitem__(self, idx):
        img, label = self.images[idx], self.labels[idx]
        img = np.reshape(img, [1, 28, 28])
        if self.return_label:
            return img, np.array(self.labels[idx]).astype('int64')
        return img,

    def __len__(self):
        return len(self.images)


def compute_acc(pred, label):
    pred = np.argmax(pred, -1)
    label = np.array(label)
    correct = pred[:, np.newaxis] == label
    return np.sum(correct) / correct.shape[0]


def dynamic_train(model, dataloader):
    optim = fluid.optimizer.Adam(
        learning_rate=0.001, parameter_list=model.parameters())
    model.train()
    for inputs, labels in dataloader:
        outputs = model(inputs)
100
        loss = CrossEntropyLoss(reduction="sum")(outputs, labels)
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
        avg_loss = fluid.layers.reduce_sum(loss)
        avg_loss.backward()
        optim.minimize(avg_loss)
        model.clear_gradients()


def dynamic_evaluate(model, dataloader):
    with fluid.dygraph.no_grad():
        model.eval()
        cnt = 0
        for inputs, labels in dataloader:
            outputs = model(inputs)

            cnt += (np.argmax(outputs.numpy(), -1)[:, np.newaxis] ==
                    labels.numpy()).astype('int').sum()

    return cnt / len(dataloader.dataset)


@unittest.skipIf(not fluid.is_compiled_with_cuda(),
                 'CPU testing is not supported')
class TestModel(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        if not fluid.is_compiled_with_cuda():
            self.skipTest('module not tested when ONLY_CPU compling')
127
        cls.device = hapi.set_device('gpu')
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
        fluid.enable_dygraph(cls.device)

        sp_num = 1280
        cls.train_dataset = MnistDataset(mode='train', sample_num=sp_num)
        cls.val_dataset = MnistDataset(mode='test', sample_num=sp_num)
        cls.test_dataset = MnistDataset(
            mode='test', return_label=False, sample_num=sp_num)

        cls.train_loader = fluid.io.DataLoader(
            cls.train_dataset, places=cls.device, batch_size=64)
        cls.val_loader = fluid.io.DataLoader(
            cls.val_dataset, places=cls.device, batch_size=64)
        cls.test_loader = fluid.io.DataLoader(
            cls.test_dataset, places=cls.device, batch_size=64)

        seed = 333
        fluid.default_startup_program().random_seed = seed
        fluid.default_main_program().random_seed = seed

        dy_lenet = LeNetDygraph()
        cls.init_param = dy_lenet.state_dict()
        dynamic_train(dy_lenet, cls.train_loader)

        cls.acc1 = dynamic_evaluate(dy_lenet, cls.val_loader)

153 154
        cls.inputs = [Input([-1, 1, 28, 28], 'float32', 'image')]
        cls.labels = [Input([None, 1], 'int64', 'label')]
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171

        cls.save_dir = tempfile.mkdtemp()
        cls.weight_path = os.path.join(cls.save_dir, 'lenet')
        fluid.dygraph.save_dygraph(dy_lenet.state_dict(), cls.weight_path)

        fluid.disable_dygraph()

    @classmethod
    def tearDownClass(cls):
        shutil.rmtree(cls.save_dir)

    def test_fit_dygraph(self):
        self.fit(True)

    def test_fit_static(self):
        self.fit(False)

172 173 174 175 176 177
    def test_fit_dynamic_with_rank(self):
        self.fit(True, 2, 0)

    def test_fit_static_with_rank(self):
        self.fit(False, 2, 0)

178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
    def test_evaluate_dygraph(self):
        self.evaluate(True)

    def test_evaluate_static(self):
        self.evaluate(False)

    def test_predict_dygraph(self):
        self.predict(True)

    def test_predict_static(self):
        self.predict(False)

    def test_prepare_context(self):
        prepare_distributed_context()

193
    def fit(self, dynamic, num_replicas=None, rank=None):
194 195 196 197 198
        fluid.enable_dygraph(self.device) if dynamic else None
        seed = 333
        fluid.default_startup_program().random_seed = seed
        fluid.default_main_program().random_seed = seed

199
        net = LeNet(classifier_activation=None)
200
        optim_new = fluid.optimizer.Adam(
201 202
            learning_rate=0.001, parameter_list=net.parameters())
        model = Model(net, inputs=self.inputs, labels=self.labels)
203 204
        model.prepare(
            optim_new,
205
            loss_function=CrossEntropyLoss(reduction="sum"),
206
            metrics=Accuracy())
207 208 209 210 211 212
        model.fit(self.train_dataset, batch_size=64, shuffle=False)

        result = model.evaluate(self.val_dataset, batch_size=64)
        np.testing.assert_allclose(result['acc'], self.acc1)

        train_sampler = DistributedBatchSampler(
213 214 215 216 217
            self.train_dataset,
            batch_size=64,
            shuffle=False,
            num_replicas=num_replicas,
            rank=rank)
218
        val_sampler = DistributedBatchSampler(
219 220 221 222 223
            self.val_dataset,
            batch_size=64,
            shuffle=False,
            num_replicas=num_replicas,
            rank=rank)
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241

        train_loader = fluid.io.DataLoader(
            self.train_dataset,
            batch_sampler=train_sampler,
            places=self.device,
            return_list=True)

        val_loader = fluid.io.DataLoader(
            self.val_dataset,
            batch_sampler=val_sampler,
            places=self.device,
            return_list=True)

        model.fit(train_loader, val_loader)
        fluid.disable_dygraph() if dynamic else None

    def evaluate(self, dynamic):
        fluid.enable_dygraph(self.device) if dynamic else None
242 243
        model = Model(LeNet(), self.inputs, self.labels)
        model.prepare(metrics=Accuracy())
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
        model.load(self.weight_path)
        result = model.evaluate(self.val_dataset, batch_size=64)
        np.testing.assert_allclose(result['acc'], self.acc1)

        sampler = DistributedBatchSampler(
            self.val_dataset, batch_size=64, shuffle=False)

        val_loader = fluid.io.DataLoader(
            self.val_dataset,
            batch_sampler=sampler,
            places=self.device,
            return_list=True)

        model.evaluate(val_loader)

        fluid.disable_dygraph() if dynamic else None

    def predict(self, dynamic):
        fluid.enable_dygraph(self.device) if dynamic else None
263 264
        model = Model(LeNet(), self.inputs)
        model.prepare()
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
        model.load(self.weight_path)
        output = model.predict(
            self.test_dataset, batch_size=64, stack_outputs=True)
        np.testing.assert_equal(output[0].shape[0], len(self.test_dataset))

        acc = compute_acc(output[0], self.val_dataset.labels)
        np.testing.assert_allclose(acc, self.acc1)

        sampler = DistributedBatchSampler(
            self.test_dataset, batch_size=64, shuffle=False)

        test_loader = fluid.io.DataLoader(
            self.test_dataset,
            batch_sampler=sampler,
            places=self.device,
            return_list=True)

        model.evaluate(test_loader)

        fluid.disable_dygraph() if dynamic else None


287
class MyModel(fluid.dygraph.Layer):
288
    def __init__(self, classifier_activation='softmax'):
289
        super(MyModel, self).__init__()
290
        self._fc = Linear(20, 10, act=classifier_activation)
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309

    def forward(self, x):
        y = self._fc(x)
        return y


class TestModelFunction(unittest.TestCase):
    def set_seed(self, seed=1024):
        fluid.default_startup_program().random_seed = seed
        fluid.default_main_program().random_seed = seed

    def test_train_batch(self, dynamic=True):
        dim = 20
        data = np.random.random(size=(4, dim)).astype(np.float32)
        label = np.random.randint(0, 10, size=(4, 1)).astype(np.int64)

        def get_expect():
            fluid.enable_dygraph(fluid.CPUPlace())
            self.set_seed()
310
            m = MyModel(classifier_activation=None)
311 312 313 314
            optim = fluid.optimizer.SGD(learning_rate=0.001,
                                        parameter_list=m.parameters())
            m.train()
            output = m(to_variable(data))
315
            loss = CrossEntropyLoss(reduction='sum')(output, to_variable(label))
316 317 318 319 320 321 322 323 324
            avg_loss = fluid.layers.reduce_sum(loss)
            avg_loss.backward()
            optim.minimize(avg_loss)
            m.clear_gradients()
            fluid.disable_dygraph()
            return avg_loss.numpy()

        ref = get_expect()
        for dynamic in [True, False]:
325
            device = hapi.set_device('cpu')
326 327 328
            fluid.enable_dygraph(device) if dynamic else None
            self.set_seed()

329
            net = MyModel(classifier_activation=None)
330
            optim2 = fluid.optimizer.SGD(learning_rate=0.001,
331
                                         parameter_list=net.parameters())
332

333 334
            inputs = [Input([None, dim], 'float32', 'x')]
            labels = [Input([None, 1], 'int64', 'label')]
335
            model = Model(net, inputs, labels)
336 337
            model.prepare(
                optim2, loss_function=CrossEntropyLoss(reduction="sum"))
338 339 340 341 342
            loss, = model.train_batch([data], [label])

            np.testing.assert_allclose(loss.flatten(), ref.flatten())
            fluid.disable_dygraph() if dynamic else None

343
    def test_test_batch(self):
344 345 346 347 348 349 350 351 352 353 354 355 356 357
        dim = 20
        data = np.random.random(size=(4, dim)).astype(np.float32)

        def get_expect():
            fluid.enable_dygraph(fluid.CPUPlace())
            self.set_seed()
            m = MyModel()
            m.eval()
            output = m(to_variable(data))
            fluid.disable_dygraph()
            return output.numpy()

        ref = get_expect()
        for dynamic in [True, False]:
358
            device = hapi.set_device('cpu')
359 360
            fluid.enable_dygraph(device) if dynamic else None
            self.set_seed()
361
            net = MyModel()
362
            inputs = [Input([None, dim], 'float32', 'x')]
363 364
            model = Model(net, inputs)
            model.prepare()
365 366
            out, = model.test_batch([data])

367
            np.testing.assert_allclose(out, ref, rtol=1e-6)
368 369 370 371 372
            fluid.disable_dygraph() if dynamic else None

    def test_save_load(self):
        path = tempfile.mkdtemp()
        for dynamic in [True, False]:
373
            device = hapi.set_device('cpu')
374
            fluid.enable_dygraph(device) if dynamic else None
375
            net = MyModel(classifier_activation=None)
376 377
            inputs = [Input([None, 20], 'float32', 'x')]
            labels = [Input([None, 1], 'int64', 'label')]
378
            optim = fluid.optimizer.SGD(learning_rate=0.001,
379 380
                                        parameter_list=net.parameters())
            model = Model(net, inputs, labels)
381
            model.prepare(
382 383
                optimizer=optim,
                loss_function=CrossEntropyLoss(reduction="sum"))
384 385 386 387 388 389 390
            model.save(path + '/test')
            model.load(path + '/test')
            shutil.rmtree(path)
            fluid.disable_dygraph() if dynamic else None

    def test_dynamic_save_static_load(self):
        path = tempfile.mkdtemp()
391 392 393
        # dynamic saving
        device = hapi.set_device('cpu')
        fluid.enable_dygraph(device)
394
        model = Model(MyModel(classifier_activation=None))
395 396 397
        optim = fluid.optimizer.SGD(learning_rate=0.001,
                                    parameter_list=model.parameters())
        model.prepare(
398
            optimizer=optim, loss_function=CrossEntropyLoss(reduction="sum"))
399 400
        model.save(path + '/test')
        fluid.disable_dygraph()
401

402 403
        inputs = [Input([None, 20], 'float32', 'x')]
        labels = [Input([None, 1], 'int64', 'label')]
404
        model = Model(MyModel(classifier_activation=None), inputs, labels)
405 406 407
        optim = fluid.optimizer.SGD(learning_rate=0.001,
                                    parameter_list=model.parameters())
        model.prepare(
408
            optimizer=optim, loss_function=CrossEntropyLoss(reduction="sum"))
409 410 411 412 413 414
        model.load(path + '/test')
        shutil.rmtree(path)

    def test_static_save_dynamic_load(self):
        path = tempfile.mkdtemp()

415
        net = MyModel(classifier_activation=None)
416 417
        inputs = [Input([None, 20], 'float32', 'x')]
        labels = [Input([None, 1], 'int64', 'label')]
418
        optim = fluid.optimizer.SGD(learning_rate=0.001,
419 420
                                    parameter_list=net.parameters())
        model = Model(net, inputs, labels)
421
        model.prepare(
422
            optimizer=optim, loss_function=CrossEntropyLoss(reduction="sum"))
423 424
        model.save(path + '/test')

425
        device = hapi.set_device('cpu')
426 427
        fluid.enable_dygraph(device)  #if dynamic else None

428
        net = MyModel(classifier_activation=None)
429 430
        inputs = [Input([None, 20], 'float32', 'x')]
        labels = [Input([None, 1], 'int64', 'label')]
431
        optim = fluid.optimizer.SGD(learning_rate=0.001,
432 433
                                    parameter_list=net.parameters())
        model = Model(net, inputs, labels)
434
        model.prepare(
435
            optimizer=optim, loss_function=CrossEntropyLoss(reduction="sum"))
436 437 438 439 440 441
        model.load(path + '/test')
        shutil.rmtree(path)
        fluid.disable_dygraph()

    def test_parameters(self):
        for dynamic in [True, False]:
442
            device = hapi.set_device('cpu')
443
            fluid.enable_dygraph(device) if dynamic else None
444
            net = MyModel()
445
            inputs = [Input([None, 20], 'float32', 'x')]
446 447
            model = Model(net, inputs)
            model.prepare()
448 449 450 451 452 453
            params = model.parameters()
            self.assertTrue(params[0].shape[0] == 20)
            self.assertTrue(params[0].shape[1] == 10)
            fluid.disable_dygraph() if dynamic else None

    def test_export_deploy_model(self):
454
        net = LeNet()
455
        inputs = [Input([-1, 1, 28, 28], 'float32', 'image')]
456 457
        model = Model(net, inputs)
        model.prepare()
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
        save_dir = tempfile.mkdtemp()
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)

        tensor_img = np.array(
            np.random.random((1, 1, 28, 28)), dtype=np.float32)
        ori_results = model.test_batch(tensor_img)

        model.save_inference_model(save_dir)

        place = fluid.CPUPlace() if not fluid.is_compiled_with_cuda(
        ) else fluid.CUDAPlace(0)
        exe = fluid.Executor(place)
        [inference_program, feed_target_names, fetch_targets] = (
            fluid.io.load_inference_model(
                dirname=save_dir, executor=exe))

        results = exe.run(inference_program,
                          feed={feed_target_names[0]: tensor_img},
                          fetch_list=fetch_targets)

479
        np.testing.assert_allclose(results, ori_results, rtol=1e-6)
480 481 482
        shutil.rmtree(save_dir)


483 484 485 486 487 488 489 490 491 492
class TestRaiseError(unittest.TestCase):
    def test_input_without_name(self):
        net = MyModel(classifier_activation=None)

        inputs = [Input([None, 10], 'float32')]
        labels = [Input([None, 1], 'int64', 'label')]
        with self.assertRaises(ValueError):
            model = Model(net, inputs, labels)


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