test_jit_save_load.py 53.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# 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 print_function

17
import os
18
import pickle
19
import shutil
20
import unittest
Y
YuanRisheng 已提交
21
import tempfile
22
import numpy as np
L
Leo Chen 已提交
23
import paddle
24
from paddle.static import InputSpec
25
import paddle.fluid as fluid
26
from paddle.fluid.layers.utils import flatten
27
from paddle.fluid.dygraph import Linear
28
from paddle.fluid.dygraph import declarative, ProgramTranslator
29
from paddle.fluid.dygraph.io import INFER_MODEL_SUFFIX, INFER_PARAMS_SUFFIX, INFER_PARAMS_INFO_SUFFIX
W
WeiXin 已提交
30
from paddle.fluid import unique_name
31 32

BATCH_SIZE = 32
33
BATCH_NUM = 10
34 35 36
SEED = 10


37 38
def random_batch_reader(input_size, label_size):
    def _get_random_inputs_and_labels(input_size, label_size):
39
        np.random.seed(SEED)
40 41 42
        input = np.random.random(size=input_size).astype('float32')
        label = np.random.random(size=label_size).astype('int64')
        return input, label
43 44 45

    def __reader__():
        for _ in range(BATCH_NUM):
46 47 48
            batch_input, batch_label = _get_random_inputs_and_labels(
                [BATCH_SIZE, input_size], [BATCH_SIZE, label_size])
            yield batch_input, batch_label
49 50 51 52 53 54 55 56 57 58 59 60 61 62

    return __reader__


class LinearNet(fluid.dygraph.Layer):
    def __init__(self, in_size, out_size):
        super(LinearNet, self).__init__()
        self._linear = Linear(in_size, out_size)

    @declarative
    def forward(self, x):
        return self._linear(x)


63 64 65 66 67 68 69 70 71 72
class LinearNetWithInputSpec(fluid.dygraph.Layer):
    def __init__(self, in_size, out_size):
        super(LinearNetWithInputSpec, self).__init__()
        self._linear = Linear(in_size, out_size)

    @declarative(input_spec=[InputSpec(shape=[None, 784], dtype='float32')])
    def forward(self, x):
        return self._linear(x)


73 74 75 76 77 78 79 80 81
class LinearNetNotDeclarative(fluid.dygraph.Layer):
    def __init__(self, in_size, out_size):
        super(LinearNetNotDeclarative, self).__init__()
        self._linear = Linear(in_size, out_size)

    def forward(self, x):
        return self._linear(x)


82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
class LinerNetWithLabel(paddle.nn.Layer):
    def __init__(self, in_size, out_size):
        super(LinerNetWithLabel, self).__init__()
        self._linear = Linear(in_size, out_size)

    @declarative(input_spec=[
        InputSpec(
            shape=[None, 784], dtype='float32', name="image"), InputSpec(
                shape=[None, 1], dtype='int64', name="label")
    ])
    def forward(self, x, label):
        out = self._linear(x)
        loss = fluid.layers.cross_entropy(out, label)
        avg_loss = fluid.layers.mean(loss)
        return out, avg_loss


C
Chen Weihang 已提交
99 100 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 127 128 129 130
class LinerNetWithPruneInput(paddle.nn.Layer):
    def __init__(self, in_size, out_size):
        super(LinerNetWithPruneInput, self).__init__()
        self._linear = Linear(in_size, out_size)

    @declarative(input_spec=[
        InputSpec(
            shape=[None, 784], dtype='float32', name="image"), InputSpec(
                shape=[None, 1], dtype='int64', name="label")
    ])
    def forward(self, x, label):
        out = self._linear(x)
        loss = fluid.layers.cross_entropy(out, label)
        avg_loss = fluid.layers.mean(loss)
        return out


class LinerNetWithUselessInput(paddle.nn.Layer):
    def __init__(self, in_size, out_size):
        super(LinerNetWithUselessInput, self).__init__()
        self._linear = Linear(in_size, out_size)

    @declarative(input_spec=[
        InputSpec(
            shape=[None, 784], dtype='float32', name="image"), InputSpec(
                shape=[None, 1], dtype='int64', name="label")
    ])
    def forward(self, x, label):
        out = self._linear(x)
        return out


131 132 133 134 135 136 137 138 139 140 141 142 143
class LinearNetReturnLoss(fluid.dygraph.Layer):
    def __init__(self, in_size, out_size):
        super(LinearNetReturnLoss, self).__init__()
        self._linear = Linear(in_size, out_size)

    @declarative
    def forward(self, x):
        y = self._linear(x)
        z = self._linear(y)
        loss = fluid.layers.mean(z)
        return z, loss


144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
class LinearNetMultiInput(fluid.dygraph.Layer):
    def __init__(self, in_size, out_size):
        super(LinearNetMultiInput, self).__init__()
        self._linear1 = Linear(in_size, out_size)
        self._linear2 = Linear(in_size, out_size)

    @declarative(input_spec=[
        InputSpec(
            [None, 8], dtype='float32'), InputSpec(
                [None, 8], dtype='float32')
    ])
    def forward(self, x, y):
        x_out = self._linear1(x)
        y_out = self._linear2(y)
        loss = fluid.layers.mean(x_out + y_out)
        return x_out, y_out, loss


162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
class LinearNetMultiInput1(fluid.dygraph.Layer):
    def __init__(self, in_size, out_size):
        super(LinearNetMultiInput1, self).__init__()
        self._linear1 = Linear(in_size, out_size)
        self._linear2 = Linear(in_size, out_size)

    @declarative(input_spec=(InputSpec(
        [None, 8], dtype='float32'), InputSpec(
            [None, 8], dtype='float32')))
    def forward(self, x, y):
        x_out = self._linear1(x)
        y_out = self._linear2(y)
        loss = fluid.layers.mean(x_out + y_out)
        return x_out, y_out, loss


178 179 180 181
class MultiLoadingLinearNet(fluid.dygraph.Layer):
    def __init__(self, size, model_path):
        super(MultiLoadingLinearNet, self).__init__()
        self._linear = Linear(size, size)
182 183
        self._load_linear1 = paddle.jit.load(model_path)
        self._load_linear2 = paddle.jit.load(model_path)
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207

    @declarative
    def forward(self, x):
        tmp1 = self._linear(x)
        tmp2 = self._load_linear1(tmp1)
        tmp3 = self._load_linear2(tmp2)
        y = self._linear(tmp3)
        return y


class LinearNetReturnHidden(fluid.dygraph.Layer):
    def __init__(self, in_size, out_size):
        super(LinearNetReturnHidden, self).__init__()
        self._linear_1 = Linear(in_size, out_size)
        self._linear_2 = Linear(in_size, out_size)

    @declarative
    def forward(self, x):
        y = self._linear_1(x)
        z = self._linear_2(y)
        loss = fluid.layers.mean(z)
        return y, loss


208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
class LinearNetWithNestOut(fluid.dygraph.Layer):
    def __init__(self, in_size, out_size):
        super(LinearNetWithNestOut, self).__init__()
        self._linear_1 = Linear(in_size, out_size)
        self._linear_2 = Linear(in_size, out_size)

    @declarative
    def forward(self, x):
        y = self._linear_1(x)
        z = self._linear_2(y)
        out = y + z
        loss = fluid.layers.mean(out)
        return y, [(z, loss), out]


223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
class LinearNetWithDictInput(paddle.nn.Layer):
    def __init__(self, in_size, out_size):
        super(LinearNetWithDictInput, self).__init__()
        self._linear = Linear(in_size, out_size)

    @paddle.jit.to_static(input_spec=[{
        'img': InputSpec(
            shape=[None, 8], dtype='float32', name='img')
    }, {
        'label': InputSpec(
            shape=[None, 1], dtype='int64', name='label')
    }])
    def forward(self, img, label):
        out = self._linear(img['img'])
        # not return loss to avoid prune output
        loss = paddle.nn.functional.cross_entropy(out, label['label'])
        return out


242 243 244 245 246 247 248 249 250 251
class LinearNetWithDictInputNoPrune(paddle.nn.Layer):
    def __init__(self, in_size, out_size):
        super(LinearNetWithDictInputNoPrune, self).__init__()
        self._linear = Linear(in_size, out_size)

    def forward(self, img):
        out = self._linear(img['img'] + img['img2'])
        return out


252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
class EmptyLayer(paddle.nn.Layer):
    def __init__(self):
        super(EmptyLayer, self).__init__()

    @paddle.jit.to_static
    def forward(self, x):
        return x


class NoParamLayer(paddle.nn.Layer):
    def __init__(self):
        super(NoParamLayer, self).__init__()

    @paddle.jit.to_static
    def forward(self, x, y):
        return x + y


270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
class LinearNetWithMultiStaticFunc(fluid.dygraph.Layer):
    def __init__(self, in_size, out_size):
        super(LinearNetWithMultiStaticFunc, self).__init__()
        self._linear_0 = Linear(in_size, out_size)
        self._linear_1 = Linear(in_size, out_size)
        self._scale = paddle.to_tensor(9.9)

    @paddle.jit.to_static
    def forward(self, x):
        return self._linear_0(x)

    @paddle.jit.to_static
    def forward_no_param(self, x):
        return x

    @paddle.jit.to_static
    def forward_general(self, x):
        return self._linear_0(x) + self._linear_1(x) * self._scale


290
def train(layer, input_size=784, label_size=1):
291
    # create optimizer
L
Leo Chen 已提交
292
    sgd = fluid.optimizer.SGDOptimizer(
293
        learning_rate=0.01, parameter_list=layer.parameters())
294 295
    # create data loader
    train_loader = fluid.io.DataLoader.from_generator(capacity=5)
296 297
    train_loader.set_batch_generator(
        random_batch_reader(input_size, label_size))
298 299 300 301 302 303 304 305 306 307 308
    # train
    for data in train_loader():
        img, label = data
        label.stop_gradient = True

        cost = layer(img)

        loss = fluid.layers.cross_entropy(cost, label)
        avg_loss = fluid.layers.mean(loss)

        avg_loss.backward()
L
Leo Chen 已提交
309
        sgd.minimize(avg_loss)
310 311 312 313
        layer.clear_gradients()
    return [img], layer, avg_loss


314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
def train_with_label(layer, input_size=784, label_size=1):
    # create optimizer
    sgd = fluid.optimizer.SGDOptimizer(
        learning_rate=0.01, parameter_list=layer.parameters())
    # create data loader
    train_loader = fluid.io.DataLoader.from_generator(capacity=5)
    train_loader.set_batch_generator(
        random_batch_reader(input_size, label_size))
    # train
    for data in train_loader():
        img, label = data
        label.stop_gradient = True

        out, avg_loss = layer(img, label)

        avg_loss.backward()
        sgd.minimize(avg_loss)
        layer.clear_gradients()
    return out


335 336
class TestJitSaveLoad(unittest.TestCase):
    def setUp(self):
Y
YuanRisheng 已提交
337 338 339
        self.temp_dir = tempfile.TemporaryDirectory()
        self.model_path = os.path.join(self.temp_dir.name,
                                       "test_jit_save_load/model")
340 341 342
        # enable dygraph mode
        fluid.enable_dygraph()
        # config seed
C
cnn 已提交
343
        paddle.seed(SEED)
L
Leo Chen 已提交
344
        paddle.framework.random._manual_program_seed(SEED)
345

Y
YuanRisheng 已提交
346 347 348
    def tearDown(self):
        self.temp_dir.cleanup()

349
    def train_and_save_model(self, model_path=None):
350 351
        layer = LinearNet(784, 1)
        example_inputs, layer, _ = train(layer)
352
        final_model_path = model_path if model_path else self.model_path
353
        orig_input_types = [type(x) for x in example_inputs]
354 355
        paddle.jit.save(
            layer=layer, path=final_model_path, input_spec=example_inputs)
356 357
        new_input_types = [type(x) for x in example_inputs]
        self.assertEqual(orig_input_types, new_input_types)
358 359
        return layer

360
    def test_save_load(self):
361 362 363
        # train and save model
        train_layer = self.train_and_save_model()
        # load model
364
        loaded_layer = paddle.jit.load(self.model_path)
365 366 367 368 369
        self.load_and_inference(train_layer, loaded_layer)
        self.load_dygraph_state_dict(train_layer)
        self.load_and_finetune(train_layer, loaded_layer)

    def load_and_inference(self, train_layer, infer_layer):
370
        train_layer.eval()
371
        infer_layer.eval()
372 373 374 375 376 377
        # inference & compare
        x = fluid.dygraph.to_variable(
            np.random.random((1, 784)).astype('float32'))
        self.assertTrue(
            np.array_equal(train_layer(x).numpy(), infer_layer(x).numpy()))

378 379
    def load_and_finetune(self, train_layer, load_train_layer):
        train_layer.train()
380 381
        load_train_layer.train()
        # train & compare
L
Leo Chen 已提交
382 383
        img0, _, train_loss = train(train_layer)
        img1, _, load_train_loss = train(load_train_layer)
384 385 386
        self.assertTrue(
            np.array_equal(train_loss.numpy(), load_train_loss.numpy()))

387 388
    def load_dygraph_state_dict(self, train_layer):
        train_layer.eval()
389
        # construct new model
390
        new_layer = LinearNet(784, 1)
391
        orig_state_dict = new_layer.state_dict()
392
        load_state_dict = paddle.load(self.model_path)
393 394 395
        for structured_name in orig_state_dict:
            self.assertTrue(structured_name in load_state_dict)
        new_layer.set_state_dict(load_state_dict)
396 397 398 399 400 401 402
        new_layer.eval()
        # inference & compare
        x = fluid.dygraph.to_variable(
            np.random.random((1, 784)).astype('float32'))
        self.assertTrue(
            np.array_equal(train_layer(x).numpy(), new_layer(x).numpy()))

403
    def test_load_dygraph_no_path(self):
Y
YuanRisheng 已提交
404 405
        model_path = os.path.join(self.temp_dir.name,
                                  "test_jit_save_load.no_path/model_path")
406 407 408
        with self.assertRaises(ValueError):
            model_dict, _ = fluid.dygraph.load_dygraph(model_path)

409
    def test_jit_load_no_path(self):
Y
YuanRisheng 已提交
410 411
        path = os.path.join(self.temp_dir.name,
                            "test_jit_save_load.no_path/model_path")
412 413 414
        with self.assertRaises(ValueError):
            loaded_layer = paddle.jit.load(path)

415

416 417 418 419
class TestSaveLoadWithNestOut(unittest.TestCase):
    def setUp(self):
        # enable dygraph mode
        fluid.enable_dygraph()
Y
YuanRisheng 已提交
420 421 422 423
        self.temp_dir = tempfile.TemporaryDirectory()

    def tearDown(self):
        self.temp_dir.cleanup()
424 425 426 427 428 429 430 431 432

    def test_nest_output(self):
        x = fluid.dygraph.to_variable(
            np.random.random((4, 8)).astype('float32'))

        net = LinearNetWithNestOut(8, 8)
        dy_outs = flatten(net(x))
        net = declarative(net, input_spec=[InputSpec([None, 8], name='x')])

Y
YuanRisheng 已提交
433
        model_path = os.path.join(self.temp_dir.name, "net_with_nest_out/model")
434 435 436 437 438 439 440 441 442 443
        paddle.jit.save(net, model_path)

        load_net = paddle.jit.load(model_path)
        load_outs = flatten(load_net(x))

        self.assertTrue(len(dy_outs) == 4)
        for dy_out, load_out in zip(dy_outs, load_outs):
            self.assertTrue(np.allclose(dy_out.numpy(), load_out.numpy()))


444 445 446 447 448 449 450 451 452 453 454
class TestSaveLoadWithDictInput(unittest.TestCase):
    def test_dict_input(self):
        # NOTE: This net cannot be executed, it is just 
        # a special case for exporting models in model validation
        # We DO NOT recommend this writing way of Layer
        net = LinearNetWithDictInput(8, 8)
        # net.forward.concrete_program.inputs: 
        # (<__main__.LinearNetWithDictInput object at 0x7f2655298a98>, 
        #  {'img': var img : fluid.VarType.LOD_TENSOR.shape(-1, 8).astype(VarType.FP32)}, 
        #  {'label': var label : fluid.VarType.LOD_TENSOR.shape(-1, 1).astype(VarType.INT64)})
        self.assertEqual(len(net.forward.concrete_program.inputs), 3)
Y
YuanRisheng 已提交
455 456 457
        temp_dir = tempfile.TemporaryDirectory()
        path = os.path.join(temp_dir.name,
                            "test_jit_save_load_with_dict_input/model")
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
        # prune inputs
        paddle.jit.save(
            layer=net,
            path=path,
            input_spec=[{
                'img': InputSpec(
                    shape=[None, 8], dtype='float32', name='img')
            }])

        img = paddle.randn(shape=[4, 8], dtype='float32')
        loaded_net = paddle.jit.load(path)
        loaded_out = loaded_net(img)

        # loaded_net._input_spec():
        # [InputSpec(shape=(-1, 8), dtype=VarType.FP32, name=img)]
        self.assertEqual(len(loaded_net._input_spec()), 1)
Y
YuanRisheng 已提交
474
        temp_dir.cleanup()
475 476


477 478 479
class TestSaveLoadWithDictInputNoPrune(unittest.TestCase):
    def test_dict_input(self):
        net = LinearNetWithDictInputNoPrune(8, 8)
Y
YuanRisheng 已提交
480 481 482
        temp_dir = tempfile.TemporaryDirectory()
        path = os.path.join(temp_dir.name,
                            "test_jit_save_load_with_dict_input_no_prune/model")
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
        # prune inputs
        paddle.jit.save(
            layer=net,
            path=path,
            input_spec=[{
                'img': InputSpec(
                    shape=[None, 8], dtype='float32', name='img'),
                'img2': InputSpec(
                    shape=[None, 8], dtype='float32', name='img2')
            }])

        img = paddle.randn(shape=[4, 8], dtype='float32')
        img2 = paddle.randn(shape=[4, 8], dtype='float32')
        loaded_net = paddle.jit.load(path)
        loaded_out = loaded_net(img, img2)

        self.assertEqual(len(loaded_net._input_spec()), 2)
Y
YuanRisheng 已提交
500
        temp_dir.cleanup()
501 502


503 504 505 506
class TestSaveLoadWithInputSpec(unittest.TestCase):
    def setUp(self):
        # enable dygraph mode
        fluid.enable_dygraph()
Y
YuanRisheng 已提交
507 508 509 510
        self.temp_dir = tempfile.TemporaryDirectory()

    def tearDown(self):
        self.temp_dir.cleanup()
511 512 513 514 515 516 517 518

    def test_with_input_spec(self):
        net = LinearNetReturnLoss(8, 8)
        # set x.shape = [None, 8]
        net.forward = declarative(
            net.forward, input_spec=[InputSpec(
                [None, 8], name='x')])

Y
YuanRisheng 已提交
519 520
        model_path = os.path.join(self.temp_dir.name,
                                  "input_spec.output_spec/model")
521 522 523 524 525 526 527
        # check inputs and outputs
        self.assertTrue(len(net.forward.inputs) == 1)
        input_x = net.forward.inputs[0]
        self.assertTrue(input_x.shape == (-1, 8))
        self.assertTrue(input_x.name == 'x')

        # 1. prune loss
528 529
        output_spec = net.forward.outputs[:1]
        paddle.jit.save(net, model_path, output_spec=output_spec)
530 531

        # 2. load to infer
532
        infer_layer = paddle.jit.load(model_path)
533 534 535 536 537 538 539
        x = fluid.dygraph.to_variable(
            np.random.random((4, 8)).astype('float32'))
        pred = infer_layer(x)

    def test_multi_in_out(self):
        net = LinearNetMultiInput(8, 8)

Y
YuanRisheng 已提交
540 541
        model_path = os.path.join(self.temp_dir.name,
                                  "multi_inout.output_spec1/model")
542 543 544 545 546 547 548 549
        # 1. check inputs and outputs
        self.assertTrue(len(net.forward.inputs) == 2)
        input_x = net.forward.inputs[0]
        input_y = net.forward.inputs[1]
        self.assertTrue(input_x.shape == (-1, 8))
        self.assertTrue(input_y.shape == (-1, 8))

        # 2. prune loss
550 551
        output_spec = net.forward.outputs[:2]
        paddle.jit.save(net, model_path, output_spec=output_spec)
552 553

        # 3. load to infer
554
        infer_layer = paddle.jit.load(model_path)
555 556 557 558 559 560 561 562
        x = fluid.dygraph.to_variable(
            np.random.random((4, 8)).astype('float32'))
        y = fluid.dygraph.to_variable(
            np.random.random((4, 8)).astype('float32'))
        # 4. predict
        pred_x, pred_y = infer_layer(x, y)

        # 1. prune y and loss
Y
YuanRisheng 已提交
563 564
        model_path = os.path.join(self.temp_dir.name,
                                  "multi_inout.output_spec2/model")
565 566
        output_spec = net.forward.outputs[:1]
        paddle.jit.save(net, model_path, [input_x], output_spec=output_spec)
567
        # 2. load again
568
        infer_layer2 = paddle.jit.load(model_path)
569 570 571 572 573
        # 3. predict
        pred_xx = infer_layer2(x)

        # 4. assert pred_x == pred_xx
        self.assertTrue(np.allclose(pred_x.numpy(), pred_xx.numpy()))
574 575 576 577

    def test_multi_in_out1(self):
        net = LinearNetMultiInput1(8, 8)

Y
YuanRisheng 已提交
578 579
        model_path = os.path.join(self.temp_dir.name,
                                  "multi_inout1.output_spec1/model")
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
        # 1. check inputs and outputs
        self.assertTrue(len(net.forward.inputs) == 2)
        input_x = net.forward.inputs[0]
        input_y = net.forward.inputs[1]
        self.assertTrue(input_x.shape == (-1, 8))
        self.assertTrue(input_y.shape == (-1, 8))

        # 2. prune loss
        output_spec = net.forward.outputs[:2]
        paddle.jit.save(net, model_path, output_spec=output_spec)

        # 3. load to infer
        infer_layer = paddle.jit.load(model_path)
        x = fluid.dygraph.to_variable(
            np.random.random((4, 8)).astype('float32'))
        y = fluid.dygraph.to_variable(
            np.random.random((4, 8)).astype('float32'))
        # 4. predict
        pred_x, pred_y = infer_layer(x, y)

        # 1. prune y and loss
Y
YuanRisheng 已提交
601 602
        model_path = os.path.join(self.temp_dir.name,
                                  "multi_inout1.output_spec2/model")
603 604 605 606 607 608 609 610 611
        output_spec = net.forward.outputs[:1]
        paddle.jit.save(net, model_path, (input_x, ), output_spec=output_spec)
        # 2. load again
        infer_layer2 = paddle.jit.load(model_path)
        # 3. predict
        pred_xx = infer_layer2(x)

        # 4. assert pred_x == pred_xx
        self.assertTrue(np.allclose(pred_x.numpy(), pred_xx.numpy()))
612 613


614 615 616 617 618
class TestJitSaveLoadConfig(unittest.TestCase):
    def setUp(self):
        # enable dygraph mode
        fluid.enable_dygraph()
        # config seed
C
cnn 已提交
619
        paddle.seed(SEED)
L
Leo Chen 已提交
620
        paddle.framework.random._manual_program_seed(SEED)
Y
YuanRisheng 已提交
621 622 623 624
        self.temp_dir = tempfile.TemporaryDirectory()

    def tearDown(self):
        self.temp_dir.cleanup()
625 626 627 628 629 630 631 632 633 634 635 636 637

    def test_output_spec(self):
        train_layer = LinearNetReturnLoss(8, 8)
        adam = fluid.optimizer.AdamOptimizer(
            learning_rate=0.1, parameter_list=train_layer.parameters())
        x = fluid.dygraph.to_variable(
            np.random.random((4, 8)).astype('float32'))
        for i in range(10):
            out, loss = train_layer(x)
            loss.backward()
            adam.minimize(loss)
            train_layer.clear_gradients()

Y
YuanRisheng 已提交
638 639
        model_path = os.path.join(self.temp_dir.name,
                                  "save_load_config.output_spec")
640 641
        output_spec = [out]
        paddle.jit.save(
642
            layer=train_layer,
643
            path=model_path,
644
            input_spec=[x],
645
            output_spec=output_spec)
646 647

        train_layer.eval()
648
        infer_layer = paddle.jit.load(model_path)
649 650 651 652 653
        x = fluid.dygraph.to_variable(
            np.random.random((4, 8)).astype('float32'))
        self.assertTrue(
            np.array_equal(train_layer(x)[0].numpy(), infer_layer(x).numpy()))

654 655
    def test_save_no_support_config_error(self):
        layer = LinearNet(784, 1)
Y
YuanRisheng 已提交
656
        path = os.path.join(self.temp_dir.name, "no_support_config_test")
657 658 659 660
        with self.assertRaises(ValueError):
            paddle.jit.save(layer=layer, path=path, model_filename="")

    def test_load_empty_model_filename_error(self):
Y
YuanRisheng 已提交
661
        path = os.path.join(self.temp_dir.name, "error_model_filename_test")
662 663 664 665
        with self.assertRaises(ValueError):
            paddle.jit.load(path, model_filename="")

    def test_load_empty_params_filename_error(self):
Y
YuanRisheng 已提交
666
        path = os.path.join(self.temp_dir.name, "error_params_filename_test")
667 668 669 670
        with self.assertRaises(ValueError):
            paddle.jit.load(path, params_filename="")

    def test_load_with_no_support_config(self):
Y
YuanRisheng 已提交
671
        path = os.path.join(self.temp_dir.name, "no_support_config_test")
672 673 674
        with self.assertRaises(ValueError):
            paddle.jit.load(path, separate_params=True)

675

676 677 678
class TestJitMultipleLoading(unittest.TestCase):
    def setUp(self):
        self.linear_size = 4
Y
YuanRisheng 已提交
679 680 681
        self.temp_dir = tempfile.TemporaryDirectory()
        self.model_path = os.path.join(self.temp_dir.name,
                                       "jit_multi_load/model")
682 683 684
        # enable dygraph mode
        fluid.enable_dygraph()
        # config seed
C
cnn 已提交
685
        paddle.seed(SEED)
L
Leo Chen 已提交
686
        paddle.framework.random._manual_program_seed(SEED)
687 688 689
        # train and save base model
        self.train_and_save_orig_model()

Y
YuanRisheng 已提交
690 691 692
    def tearDown(self):
        self.temp_dir.cleanup()

693 694 695
    def train_and_save_orig_model(self):
        layer = LinearNet(self.linear_size, self.linear_size)
        example_inputs, layer, _ = train(layer, self.linear_size, 1)
696 697
        paddle.jit.save(
            layer=layer, path=self.model_path, input_spec=example_inputs)
698 699 700 701 702 703 704 705 706 707 708

    def test_load_model_retransform_inference(self):
        multi_loaded_layer = MultiLoadingLinearNet(self.linear_size,
                                                   self.model_path)
        state_dict = multi_loaded_layer.state_dict()
        name_set = set()
        for _, var in state_dict.items():
            self.assertTrue(var.name not in name_set)
            name_set.add(var.name)


709 710 711
class TestJitPruneModelAndLoad(unittest.TestCase):
    def setUp(self):
        self.linear_size = 4
Y
YuanRisheng 已提交
712 713 714
        self.temp_dir = tempfile.TemporaryDirectory()
        self.model_path = os.path.join(self.temp_dir.name,
                                       "jit_prune_model_and_load/model")
715 716 717
        # enable dygraph mode
        fluid.enable_dygraph()
        # config seed
C
cnn 已提交
718
        paddle.seed(SEED)
L
Leo Chen 已提交
719
        paddle.framework.random._manual_program_seed(SEED)
720

Y
YuanRisheng 已提交
721 722 723
    def tearDown(self):
        self.temp_dir.cleanup()

724 725 726 727 728 729 730 731 732 733 734 735
    def train_and_save(self):
        train_layer = LinearNetReturnHidden(8, 8)
        adam = fluid.optimizer.AdamOptimizer(
            learning_rate=0.1, parameter_list=train_layer.parameters())
        x = fluid.dygraph.to_variable(
            np.random.random((4, 8)).astype('float32'))
        for i in range(10):
            hidden, loss = train_layer(x)
            loss.backward()
            adam.minimize(loss)
            train_layer.clear_gradients()

736 737
        output_spec = [hidden]
        paddle.jit.save(
738
            layer=train_layer,
739
            path=self.model_path,
740
            input_spec=[x],
741
            output_spec=output_spec)
742 743 744 745 746 747 748

        return train_layer

    def test_load_pruned_model(self):
        train_layer = self.train_and_save()
        train_layer.eval()

749
        infer_layer = paddle.jit.load(self.model_path)
750 751 752 753 754 755 756 757 758 759

        x = fluid.dygraph.to_variable(
            np.random.random((4, 8)).astype('float32'))
        self.assertTrue(
            np.array_equal(train_layer(x)[0].numpy(), infer_layer(x).numpy()))

    def test_load_var_not_in_extra_var_info(self):
        self.train_and_save()

        # chage extra var info
760
        var_info_path = self.model_path + INFER_PARAMS_INFO_SUFFIX
761 762 763 764 765 766 767
        with open(var_info_path, 'rb') as f:
            extra_var_info = pickle.load(f)
            extra_var_info.clear()
        with open(var_info_path, 'wb') as f:
            pickle.dump(extra_var_info, f, protocol=2)

        with self.assertRaises(RuntimeError):
768
            paddle.jit.load(self.model_path)
769 770


771 772 773 774 775
class TestJitSaveMultiCases(unittest.TestCase):
    def setUp(self):
        # enable dygraph mode
        fluid.enable_dygraph()
        # config seed
C
cnn 已提交
776
        paddle.seed(SEED)
777
        paddle.framework.random._manual_program_seed(SEED)
Y
YuanRisheng 已提交
778 779 780 781
        self.temp_dir = tempfile.TemporaryDirectory()

    def tearDown(self):
        self.temp_dir.cleanup()
782

C
Chen Weihang 已提交
783 784 785 786 787
    def verify_inference_correctness(self,
                                     layer,
                                     model_path,
                                     with_label_and_loss=False,
                                     with_label=False):
788 789 790 791
        layer.eval()
        loaded_layer = paddle.jit.load(model_path)
        loaded_layer.eval()
        # inference & compare
Z
Zhou Wei 已提交
792
        x = paddle.to_tensor(np.random.random((1, 784)).astype('float32'))
C
Chen Weihang 已提交
793
        if with_label_and_loss:
Z
Zhou Wei 已提交
794
            y = paddle.to_tensor(np.random.random((1, 1)).astype('int64'))
795 796
            pred, _ = layer(x, y)
            pred = pred.numpy()
C
Chen Weihang 已提交
797 798 799 800
        elif with_label:
            y = paddle.to_tensor(np.random.random((1, 1)).astype('int64'))
            pred = layer(x, y)
            pred = pred.numpy()
801 802 803 804 805 806 807 808 809 810 811 812 813
        else:
            pred = layer(x).numpy()
        loaded_pred = loaded_layer(x).numpy()
        self.assertTrue(
            np.array_equal(pred, loaded_pred),
            msg="Result diff when load and inference:\nlayer result:\n{}\n" \
                "loaded layer result:\n{}".format(pred, loaded_pred))

    def test_no_prune_to_static_after_train(self):
        layer = LinearNet(784, 1)

        train(layer)

Y
YuanRisheng 已提交
814 815
        model_path = os.path.join(self.temp_dir.name,
                                  "test_no_prune_to_static_after_train/model")
816 817 818 819 820 821 822
        paddle.jit.save(layer, model_path)

        self.verify_inference_correctness(layer, model_path)

    def test_no_prune_to_static_no_train(self):
        layer = LinearNetWithInputSpec(784, 1)

Y
YuanRisheng 已提交
823 824
        model_path = os.path.join(self.temp_dir.name,
                                  "test_no_prune_to_static_no_train/model")
825 826 827 828 829 830 831 832 833
        paddle.jit.save(layer, model_path)

        self.verify_inference_correctness(layer, model_path)

    def test_no_prune_no_to_static_after_train(self):
        layer = LinearNetNotDeclarative(784, 1)

        train(layer)

Y
YuanRisheng 已提交
834 835
        model_path = os.path.join(
            self.temp_dir.name, "test_no_prune_no_to_static_after_train/model")
836 837 838 839 840 841 842 843 844 845 846 847 848
        paddle.jit.save(
            layer,
            model_path,
            input_spec=[InputSpec(
                shape=[None, 784], dtype='float32')])

        self.verify_inference_correctness(layer, model_path)

    def test_no_prune_no_to_static_after_train_with_examples(self):
        layer = LinearNetNotDeclarative(784, 1)

        example_inputs, _, _ = train(layer)

Y
YuanRisheng 已提交
849 850 851
        model_path = os.path.join(
            self.temp_dir.name,
            "test_no_prune_no_to_static_after_train_with_examples/model")
852
        paddle.jit.save(layer=layer, path=model_path, input_spec=example_inputs)
853 854 855 856 857 858

        self.verify_inference_correctness(layer, model_path)

    def test_no_prune_no_to_static_no_train(self):
        layer = LinearNetNotDeclarative(784, 1)

Y
YuanRisheng 已提交
859 860
        model_path = os.path.join(self.temp_dir.name,
                                  "test_no_prune_no_to_static_no_train/model")
861 862 863 864 865 866 867 868 869 870 871 872 873
        paddle.jit.save(
            layer,
            model_path,
            input_spec=[InputSpec(
                shape=[None, 784], dtype='float32')])

        self.verify_inference_correctness(layer, model_path)

    def test_prune_to_static_after_train(self):
        layer = LinerNetWithLabel(784, 1)

        out = train_with_label(layer)

Y
YuanRisheng 已提交
874 875
        model_path = os.path.join(self.temp_dir.name,
                                  "test_prune_to_static_after_train/model")
876 877 878 879 880 881 882
        paddle.jit.save(
            layer,
            model_path,
            input_spec=[
                InputSpec(
                    shape=[None, 784], dtype='float32', name="image")
            ],
883
            output_spec=[out])
884

C
Chen Weihang 已提交
885 886
        self.verify_inference_correctness(
            layer, model_path, with_label_and_loss=True)
887 888 889 890

    def test_prune_to_static_no_train(self):
        layer = LinerNetWithLabel(784, 1)

Y
YuanRisheng 已提交
891 892
        model_path = os.path.join(self.temp_dir.name,
                                  "test_prune_to_static_no_train/model")
893 894
        # TODO: no train, cannot get output_spec var here
        # now only can use index
895
        output_spec = layer.forward.outputs[:1]
896 897 898 899 900 901 902
        paddle.jit.save(
            layer,
            model_path,
            input_spec=[
                InputSpec(
                    shape=[None, 784], dtype='float32', name="image")
            ],
903
            output_spec=output_spec)
904

C
Chen Weihang 已提交
905 906 907 908 909 910
        self.verify_inference_correctness(
            layer, model_path, with_label_and_loss=True)

    def test_prune_input_to_static_no_train(self):
        layer = LinerNetWithPruneInput(784, 1)

Y
YuanRisheng 已提交
911 912
        model_path = os.path.join(self.temp_dir.name,
                                  "test_prune_input_to_static_no_train/model")
C
Chen Weihang 已提交
913 914 915 916 917 918 919 920 921 922 923 924 925
        paddle.jit.save(
            layer,
            model_path,
            input_spec=[
                InputSpec(
                    shape=[None, 784], dtype='float32', name="image")
            ])

        self.verify_inference_correctness(layer, model_path, with_label=True)

    def test_prune_useless_input_to_static_no_train(self):
        layer = LinerNetWithUselessInput(784, 1)

Y
YuanRisheng 已提交
926 927 928
        model_path = os.path.join(
            self.temp_dir.name,
            "test_prune_useless_input_to_static_no_train/model")
C
Chen Weihang 已提交
929 930 931 932 933 934 935 936 937
        paddle.jit.save(
            layer,
            model_path,
            input_spec=[
                InputSpec(
                    shape=[None, 784], dtype='float32', name="image")
            ])

        self.verify_inference_correctness(layer, model_path, with_label=True)
938 939 940 941 942 943

    def test_no_prune_input_spec_name_warning(self):
        layer = LinearNetWithInputSpec(784, 1)

        train(layer)

Y
YuanRisheng 已提交
944 945
        model_path = os.path.join(self.temp_dir.name,
                                  "test_no_prune_input_spec_name_warning/model")
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
        paddle.jit.save(
            layer,
            model_path,
            input_spec=[InputSpec(
                shape=[None, 784], dtype='float32')])
        paddle.jit.save(
            layer,
            model_path,
            input_spec=[
                InputSpec(
                    shape=[None, 784], dtype='float32', name='feed_input')
            ])

        self.verify_inference_correctness(layer, model_path)

    def test_not_prune_output_spec_name_warning(self):
        layer = LinearNet(784, 1)

        train(layer)

Y
YuanRisheng 已提交
966 967
        model_path = os.path.join(
            self.temp_dir.name, "test_not_prune_output_spec_name_warning/model")
Z
Zhou Wei 已提交
968
        out = paddle.to_tensor(np.random.random((1, 1)).astype('float'))
969
        paddle.jit.save(layer, model_path, output_spec=[out])
970 971 972 973 974 975

        self.verify_inference_correctness(layer, model_path)

    def test_prune_input_spec_name_error(self):
        layer = LinerNetWithLabel(784, 1)

Y
YuanRisheng 已提交
976 977
        model_path = os.path.join(self.temp_dir.name,
                                  "test_prune_input_spec_name_error/model")
978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997
        with self.assertRaises(ValueError):
            paddle.jit.save(
                layer,
                model_path,
                input_spec=[InputSpec(
                    shape=[None, 784], dtype='float32')])
        with self.assertRaises(ValueError):
            paddle.jit.save(
                layer,
                model_path,
                input_spec=[
                    InputSpec(
                        shape=[None, 784], dtype='float32', name='feed_input')
                ])

    def test_prune_output_spec_name_error(self):
        layer = LinerNetWithLabel(784, 1)

        train_with_label(layer)

Y
YuanRisheng 已提交
998 999
        model_path = os.path.join(self.temp_dir.name,
                                  "test_prune_to_static_after_train/model")
Z
Zhou Wei 已提交
1000
        out = paddle.to_tensor(np.random.random((1, 1)).astype('float'))
1001 1002 1003 1004 1005 1006 1007 1008
        with self.assertRaises(ValueError):
            paddle.jit.save(
                layer,
                model_path,
                input_spec=[
                    InputSpec(
                        shape=[None, 784], dtype='float32', name="image")
                ],
1009
                output_spec=[out])
1010 1011


1012 1013
class TestJitSaveLoadEmptyLayer(unittest.TestCase):
    def setUp(self):
Y
YuanRisheng 已提交
1014 1015 1016
        self.temp_dir = tempfile.TemporaryDirectory()
        self.model_path = os.path.join(self.temp_dir.name,
                                       "jit_save_load_empty_layer/model")
1017 1018 1019
        # enable dygraph mode
        paddle.disable_static()

Y
YuanRisheng 已提交
1020 1021 1022
    def tearDown(self):
        self.temp_dir.cleanup()

1023 1024
    def test_save_load_empty_layer(self):
        layer = EmptyLayer()
Z
Zhou Wei 已提交
1025
        x = paddle.to_tensor(np.random.random((10)).astype('float32'))
1026 1027 1028 1029 1030 1031 1032 1033 1034
        out = layer(x)
        paddle.jit.save(layer, self.model_path)
        load_layer = paddle.jit.load(self.model_path)
        load_out = load_layer(x)
        self.assertTrue(np.array_equal(out, load_out))


class TestJitSaveLoadNoParamLayer(unittest.TestCase):
    def setUp(self):
Y
YuanRisheng 已提交
1035 1036 1037
        self.temp_dir = tempfile.TemporaryDirectory()
        self.model_path = os.path.join(self.temp_dir.name,
                                       "jit_save_load_no_param_layer/model")
1038 1039 1040
        # enable dygraph mode
        paddle.disable_static()

Y
YuanRisheng 已提交
1041 1042 1043
    def tearDown(self):
        self.temp_dir.cleanup()

1044 1045
    def test_save_load_no_param_layer(self):
        layer = NoParamLayer()
Z
Zhou Wei 已提交
1046 1047
        x = paddle.to_tensor(np.random.random((5)).astype('float32'))
        y = paddle.to_tensor(np.random.random((5)).astype('float32'))
1048 1049 1050 1051 1052 1053 1054
        out = layer(x, y)
        paddle.jit.save(layer, self.model_path)
        load_layer = paddle.jit.load(self.model_path)
        load_out = load_layer(x, y)
        self.assertTrue(np.array_equal(out, load_out))


1055 1056 1057 1058
class TestJitSaveLoadMultiMethods(unittest.TestCase):
    def setUp(self):
        # enable dygraph mode
        paddle.disable_static()
Y
YuanRisheng 已提交
1059 1060 1061 1062
        self.temp_dir = tempfile.TemporaryDirectory()

    def tearDown(self):
        self.temp_dir.cleanup()
1063 1064

    def test_jit_save_load_inference(self):
Y
YuanRisheng 已提交
1065 1066
        model_path_inference = os.path.join(self.temp_dir.name,
                                            "jit_save_load_multi_methods/model")
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
        IMAGE_SIZE = 224
        layer = LinearNetWithMultiStaticFunc(IMAGE_SIZE, 10)
        inps = paddle.randn([1, IMAGE_SIZE])
        result_origin = {}
        for func in dir(layer):
            if func.startswith('forward'):
                result_origin[func] = getattr(layer, func, None)(inps)
        paddle.jit.save(layer, model_path_inference)
        load_net = paddle.jit.load(model_path_inference)
        for func, result in result_origin.items():
            self.assertTrue(
                float((result - getattr(load_net, func, None)(inps)).abs().max(
                )) < 1e-5)

    def test_jit_save_load_multi_methods_inputspec(self):
Y
YuanRisheng 已提交
1082 1083
        model_path = os.path.join(self.temp_dir.name,
                                  'jit_save_load_multi_methods/model')
1084 1085 1086 1087 1088
        layer = LinearNetWithMultiStaticFunc(784, 1)
        with self.assertRaises(ValueError):
            paddle.jit.save(
                layer, model_path, input_spec=[InputSpec(shape=[None, 784])])

1089
    def test_parse_name(self):
Y
YuanRisheng 已提交
1090 1091
        model_path_inference = os.path.join(self.temp_dir.name,
                                            "jit_save_load_parse_name/model")
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
        IMAGE_SIZE = 224
        layer = LinearNet(IMAGE_SIZE, 1)
        inps = paddle.randn([1, IMAGE_SIZE])
        layer(inps)
        paddle.jit.save(layer, model_path_inference)
        paddle.jit.save(layer, model_path_inference + '_v2')
        load_net = paddle.jit.load(model_path_inference)

        self.assertFalse(hasattr(load_net, 'v2'))

1102

W
WeiXin 已提交
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
class LayerSaved(paddle.nn.Layer):
    def __init__(self, in_size, out_size):
        super(LayerSaved, self).__init__()
        self.hidden = 100
        self._linear_0 = Linear(in_size, self.hidden)
        self._linear_1_0 = Linear(self.hidden, self.hidden)
        self._linear_1_1 = Linear(self.hidden, self.hidden)
        self._linear_2 = Linear(self.hidden, out_size)
        self._scale = paddle.to_tensor(9.9)

    @paddle.jit.to_static
    def forward(self, x):
        y = self._linear_0(x)
        # Multiple blocks
        if x.shape[0] == 1:
            y = self._linear_1_0(y)
        else:
            y += self._linear_1_1(y + self._scale)
        return self._linear_2(y)


class LayerLoadFinetune(paddle.nn.Layer):
    def __init__(self, in_size, out_size, load_path):
        super(LayerLoadFinetune, self).__init__()
        # Test duplicate name
        self._linear_0 = Linear(in_size, in_size)
        self._linear_1_0 = Linear(out_size, in_size)
        self._linear_1_1 = Linear(out_size, in_size)
        self._linear_2 = Linear(out_size, out_size)
        self._scale = paddle.to_tensor(9.9)

        # Load multiple times
        self._load_l1 = paddle.jit.load(load_path)
        self._load_l2 = paddle.jit.load(load_path)

    @paddle.jit.to_static
    def forward(self, x):
        y = self._linear_0(x)
        y = self._load_l1(y)
        # Multiple blocks
        if x.shape[0] == 1:
            y = self._linear_1_0(y)
            y = self._load_l1(y)
        else:
            y += self._linear_1_1(x + self._scale)
            y = self._load_l2(y)
        y = self._linear_1_0(y)
        y = self._load_l1(y)
        y = self._linear_1_0(y)
        # Use the same layer multiple times.
        y = self._load_l1(y)
        return y


1157 1158 1159 1160
class TestJitSaveLoadSaveWithoutRunning(unittest.TestCase):
    def setUp(self):
        # enable dygraph mode
        paddle.disable_static()
Y
YuanRisheng 已提交
1161 1162 1163 1164
        self.temp_dir = tempfile.TemporaryDirectory()

    def tearDown(self):
        self.temp_dir.cleanup()
1165 1166

    def test_save_load_finetune_load(self):
Y
YuanRisheng 已提交
1167 1168
        model_path = os.path.join(
            self.temp_dir.name, "test_jit_save_load_save_without_running/model")
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
        IMAGE_SIZE = 224
        inps0 = paddle.randn([1, IMAGE_SIZE])
        inps1 = paddle.randn([2, IMAGE_SIZE])
        # Use new namespace
        with unique_name.guard():
            layer_save = LayerSaved(IMAGE_SIZE, IMAGE_SIZE)
        #save
        paddle.jit.save(
            layer_save,
            model_path,
            input_spec=[
                paddle.static.InputSpec(
                    shape=[None, IMAGE_SIZE], dtype='float32')
            ])
        result_00 = layer_save(inps0)
        result_01 = layer_save(inps1)
        #load and save without running
        with unique_name.guard():
            layer_load = paddle.jit.load(model_path)
            paddle.jit.save(
                layer_load,
                model_path,
                input_spec=[
                    paddle.static.InputSpec(
                        shape=[None, IMAGE_SIZE], dtype='float32')
                ])
        #reload
        layer_reload = paddle.jit.load(model_path)
        result_10 = layer_reload(inps0)
        result_11 = layer_reload(inps1)

        self.assertTrue(float((result_00 - result_10).abs().max()) < 1e-5)
        self.assertTrue(float((result_01 - result_11).abs().max()) < 1e-5)


W
WeiXin 已提交
1204 1205 1206 1207
class TestJitSaveLoadFinetuneLoad(unittest.TestCase):
    def setUp(self):
        # enable dygraph mode
        paddle.disable_static()
Y
YuanRisheng 已提交
1208 1209 1210 1211
        self.temp_dir = tempfile.TemporaryDirectory()

    def tearDown(self):
        self.temp_dir.cleanup()
W
WeiXin 已提交
1212 1213

    def test_save_load_finetune_load(self):
Y
YuanRisheng 已提交
1214 1215
        model_path = os.path.join(self.temp_dir.name,
                                  "test_jit_save_load_finetune_load/model")
W
WeiXin 已提交
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
        IMAGE_SIZE = 224
        inps0 = paddle.randn([1, IMAGE_SIZE])
        inps1 = paddle.randn([2, IMAGE_SIZE])
        # Use new namespace
        with unique_name.guard():
            layer_save = LayerSaved(IMAGE_SIZE, IMAGE_SIZE)
        layer_save(inps0)
        #save
        paddle.jit.save(layer_save, model_path)
        #load
        with unique_name.guard():
            layer_load = LayerLoadFinetune(IMAGE_SIZE, IMAGE_SIZE, model_path)
        #train
        train(layer_load, input_size=IMAGE_SIZE)
        result_00 = layer_load(inps0)
        result_01 = layer_load(inps1)
        #save
        paddle.jit.save(layer_load, model_path)
        #load
        layer_finetune = paddle.jit.load(model_path)
        result_10 = layer_finetune(inps0)
        result_11 = layer_finetune(inps1)

        self.assertTrue(float((result_00 - result_10).abs().max()) < 1e-5)
        self.assertTrue(float(((result_01 - result_11)).abs().max()) < 1e-5)


1243 1244 1245 1246 1247 1248
# NOTE(weixin): When there are multiple test functions in an 
# `unittest.TestCase`, functions will affect each other, 
# and there is a risk of random failure. 
# So divided into three TestCase: TestJitSaveLoadFunctionCase1, 
# TestJitSaveLoadFunctionCase2, TestJitSaveLoadFunctionCase3.
class TestJitSaveLoadFunctionCase1(unittest.TestCase):
1249 1250
    def setUp(self):
        paddle.disable_static()
Y
YuanRisheng 已提交
1251 1252 1253 1254
        self.temp_dir = tempfile.TemporaryDirectory()

    def tearDown(self):
        self.temp_dir.cleanup()
1255 1256 1257 1258 1259 1260

    def test_jit_save_load_static_function(self):
        @paddle.jit.to_static
        def fun(inputs):
            return paddle.tanh(inputs)

Y
YuanRisheng 已提交
1261 1262
        path = os.path.join(self.temp_dir.name,
                            'test_jit_save_load_function_1/func')
1263 1264 1265 1266 1267 1268 1269 1270 1271
        inps = paddle.rand([3, 6])
        origin = fun(inps)

        paddle.jit.save(fun, path)
        load_func = paddle.jit.load(path)

        load_result = load_func(inps)
        self.assertTrue((load_result - origin).abs().max() < 1e-10)

1272 1273 1274 1275

class TestJitSaveLoadFunctionCase2(unittest.TestCase):
    def setUp(self):
        paddle.disable_static()
Y
YuanRisheng 已提交
1276 1277 1278 1279
        self.temp_dir = tempfile.TemporaryDirectory()

    def tearDown(self):
        self.temp_dir.cleanup()
1280

1281 1282 1283 1284 1285 1286 1287 1288
    def test_jit_save_load_function_input_spec(self):
        @paddle.jit.to_static(input_spec=[
            InputSpec(
                shape=[None, 6], dtype='float32', name='x'),
        ])
        def fun(inputs):
            return paddle.nn.functional.relu(inputs)

Y
YuanRisheng 已提交
1289 1290
        path = os.path.join(self.temp_dir.name,
                            'test_jit_save_load_function_2/func')
1291 1292 1293 1294 1295 1296 1297 1298
        inps = paddle.rand([3, 6])
        origin = fun(inps)

        paddle.jit.save(fun, path)
        load_func = paddle.jit.load(path)
        load_result = load_func(inps)
        self.assertTrue((load_result - origin).abs().max() < 1e-10)

1299 1300 1301 1302

class TestJitSaveLoadFunctionCase3(unittest.TestCase):
    def setUp(self):
        paddle.disable_static()
Y
YuanRisheng 已提交
1303 1304 1305 1306
        self.temp_dir = tempfile.TemporaryDirectory()

    def tearDown(self):
        self.temp_dir.cleanup()
1307

1308 1309 1310 1311
    def test_jit_save_load_function_function(self):
        def fun(inputs):
            return paddle.tanh(inputs)

Y
YuanRisheng 已提交
1312 1313
        path = os.path.join(self.temp_dir.name,
                            'test_jit_save_load_function_3/func')
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
        inps = paddle.rand([3, 6])
        origin = fun(inps)

        paddle.jit.save(
            fun,
            path,
            input_spec=[
                InputSpec(
                    shape=[None, 6], dtype='float32', name='x'),
            ])
        load_func = paddle.jit.load(path)

        load_result = load_func(inps)
        self.assertTrue((load_result - origin).abs().max() < 1e-10)


1330 1331 1332
class TestJitSaveLoadFunctionWithParamCase1(unittest.TestCase):
    def setUp(self):
        paddle.disable_static()
Y
YuanRisheng 已提交
1333 1334 1335 1336
        self.temp_dir = tempfile.TemporaryDirectory()

    def tearDown(self):
        self.temp_dir.cleanup()
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356

    def test_jit_save_load_function(self):
        class LinearNet(paddle.nn.Layer):
            def __init__(self):
                super(LinearNet, self).__init__()
                self._linear = paddle.nn.Linear(5, 6)

            def forward(self, x):
                return paddle.tanh(x)

            def anothor_forward(self, x):
                return self._linear(x)

        layer = LinearNet()

        inps = paddle.rand([3, 5])
        origin = layer.anothor_forward(inps)

        func = paddle.jit.to_static(
            layer.anothor_forward, [paddle.static.InputSpec(shape=[-1, 5])])
Y
YuanRisheng 已提交
1357 1358 1359
        path = os.path.join(
            self.temp_dir.name,
            'test_jit_save_load_function_with_params_case1/func')
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
        paddle.jit.save(func, path)
        load_func = paddle.jit.load(path)

        load_result = load_func(inps)
        self.assertTrue(np.array_equal(load_result.numpy(), origin.numpy()))


class TestJitSaveLoadFunctionWithParamCase2(unittest.TestCase):
    def setUp(self):
        paddle.disable_static()
Y
YuanRisheng 已提交
1370 1371 1372 1373
        self.temp_dir = tempfile.TemporaryDirectory()

    def tearDown(self):
        self.temp_dir.cleanup()
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391

    def test_jit_save_load_function(self):
        class LinearNet(paddle.nn.Layer):
            def __init__(self):
                super(LinearNet, self).__init__()
                self._linear = paddle.nn.Linear(5, 6)

            def forward(self, x):
                return paddle.tanh(x)

            @paddle.jit.to_static(input_spec=[InputSpec(shape=[-1, 5])])
            def anothor_forward(self, x):
                return self._linear(x)

        layer = LinearNet()

        inps = paddle.rand([3, 5])

Y
YuanRisheng 已提交
1392 1393 1394
        path = os.path.join(
            self.temp_dir.name,
            'test_jit_save_load_function_with_params_case2/func')
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
        paddle.jit.save(layer.anothor_forward, path)
        origin_result = layer.anothor_forward(inps)
        load_func = paddle.jit.load(path)

        load_result = load_func(inps)

        self.assertTrue(
            np.array_equal(origin_result.numpy(), load_result.numpy()))


class TestJitSaveLoadFunctionWithParamCase3(unittest.TestCase):
    def setUp(self):
        paddle.disable_static()
Y
YuanRisheng 已提交
1408 1409 1410 1411
        self.temp_dir = tempfile.TemporaryDirectory()

    def tearDown(self):
        self.temp_dir.cleanup()
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430

    def test_jit_save_load_function(self):
        class LinearNet(paddle.nn.Layer):
            def __init__(self):
                super(LinearNet, self).__init__()
                self._linear = paddle.nn.Linear(5, 6)

            def forward(self, x):
                return paddle.tanh(x)

            @paddle.jit.to_static
            def anothor_forward(self, x):
                return self._linear(x)

        layer = LinearNet()

        inps = paddle.rand([3, 5])
        origin = layer.anothor_forward(inps)

Y
YuanRisheng 已提交
1431 1432 1433
        path = os.path.join(
            self.temp_dir.name,
            'test_jit_save_load_function_with_params_case3/func')
1434 1435 1436 1437 1438 1439 1440
        paddle.jit.save(layer.anothor_forward, path)
        load_func = paddle.jit.load(path)

        load_result = load_func(inps)
        self.assertTrue(np.array_equal(load_result.numpy(), origin.numpy()))


1441
class TestJitSaveLoadDataParallel(unittest.TestCase):
Y
YuanRisheng 已提交
1442 1443 1444 1445 1446 1447
    def setUp(self):
        self.temp_dir = tempfile.TemporaryDirectory()

    def tearDown(self):
        self.temp_dir.cleanup()

1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
    def verify_inference_correctness(self, layer, path):
        layer.eval()
        loaded_layer = paddle.jit.load(path)
        loaded_layer.eval()
        # inference & compare
        x = paddle.to_tensor(np.random.random((1, 784)).astype('float32'))
        pred = layer(x).numpy()
        loaded_pred = loaded_layer(x).numpy()
        self.assertTrue(
            np.array_equal(pred, loaded_pred),
            msg="Result diff when load and inference:\nlayer result:\n{}\n" \
                "loaded layer result:\n{}".format(pred, loaded_pred))

    def test_jit_save_data_parallel_with_inputspec(self):
        layer = LinearNetNotDeclarative(784, 1)
        layer = paddle.DataParallel(layer)
Y
YuanRisheng 已提交
1464 1465
        path = os.path.join(self.temp_dir.name,
                            "jit_save_data_parallel_with_inputspec/model")
1466 1467 1468 1469 1470 1471 1472 1473 1474
        paddle.jit.save(
            layer=layer, path=path, input_spec=[InputSpec(shape=[None, 784])])

        self.verify_inference_correctness(layer, path)

    def test_jit_save_data_parallel_with_to_static(self):
        layer = LinearNetWithInputSpec(784, 1)
        layer = paddle.DataParallel(layer)

Y
YuanRisheng 已提交
1475 1476
        path = os.path.join(self.temp_dir.name,
                            "jit_save_data_parallel_with_to_static/model")
1477 1478 1479 1480 1481
        paddle.jit.save(layer, path)

        self.verify_inference_correctness(layer, path)


1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
class InputSepcLayer(paddle.nn.Layer):
    '''
    A layer with InputSpec to test InputSpec compatibility
    '''

    @paddle.jit.to_static(input_spec=[
        InputSpec(
            shape=[None, 8], dtype='float32', name='x'), InputSpec(
                shape=[None, 1], dtype='float64', name='y')
    ])
    def forward(self, x, y):
        return x, y


class TestInputSpecCompatibility(unittest.TestCase):
Y
YuanRisheng 已提交
1497 1498 1499 1500 1501 1502
    def setUp(self):
        self.temp_dir = tempfile.TemporaryDirectory()

    def tearDown(self):
        self.temp_dir.cleanup()

1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
    def _assert_input_spec_layer_return(self, expect_layer, test_layer):
        input_x = paddle.uniform([8, 8], dtype='float32')
        input_y = paddle.uniform([8, 1], dtype='float64')
        expected_result = expect_layer(input_x, input_y)
        test_result = test_layer(input_x, input_y)
        np.testing.assert_allclose(expected_result[0].numpy(),
                                   test_result[0].numpy())
        np.testing.assert_allclose(expected_result[1].numpy(),
                                   test_result[1].numpy())

    def test_jit_save_compatible_input_sepc(self):
        layer = InputSepcLayer()
Y
YuanRisheng 已提交
1515 1516
        save_dir = os.path.join(self.temp_dir.name,
                                "jit_save_compatible_input_spec")
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
        path = save_dir + "/model"

        paddle.jit.save(layer=layer, path=path)
        no_input_spec_layer = paddle.jit.load(path)
        self._assert_input_spec_layer_return(layer, no_input_spec_layer)
        shutil.rmtree(save_dir)

        paddle.jit.save(
            layer=layer,
            path=path,
            input_spec=[
                InputSpec(
                    shape=[None, 8], dtype='float32', name='x'), InputSpec(
                        shape=[None, 1], dtype='float64', name='y')
            ])
        same_input_spec_layer = paddle.jit.load(path)
        self._assert_input_spec_layer_return(layer, same_input_spec_layer)
        shutil.rmtree(save_dir)

        paddle.jit.save(
            layer=layer,
            path=path,
            input_spec=[
                InputSpec(
                    shape=[8, 8], dtype='float32'), InputSpec(
                        shape=[8, -1], dtype='float64')
            ])
        compatible_input_spec_layer = paddle.jit.load(path)
        self._assert_input_spec_layer_return(layer, compatible_input_spec_layer)
        shutil.rmtree(save_dir)

    def test_jit_save_incompatible_input_sepc(self):
        layer = InputSepcLayer()
Y
YuanRisheng 已提交
1550 1551
        save_dir = os.path.join(self.temp_dir.name,
                                "jit_save_compatible_input_spec")
1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589
        path = save_dir + "/model"

        with self.assertRaises(ValueError):
            # type mismatch
            paddle.jit.save(
                layer=layer,
                path=path,
                input_spec=[
                    InputSpec(
                        shape=[None, 8], dtype='float64'), InputSpec(
                            shape=[None, 1], dtype='float64')
                ])

        with self.assertRaises(ValueError):
            # shape len mismatch
            paddle.jit.save(
                layer=layer,
                path=path,
                input_spec=[
                    InputSpec(
                        shape=[None, 8, 1], dtype='float32'), InputSpec(
                            shape=[None, 1], dtype='float64')
                ])

        with self.assertRaises(ValueError):
            # shape mismatch
            paddle.jit.save(
                layer=layer,
                path=path,
                input_spec=[
                    InputSpec(
                        shape=[None, 8], dtype='float32'), InputSpec(
                            shape=[None, 2], dtype='float64')
                ])
        if os.path.exists(save_dir):
            shutil.rmtree(save_dir)


1590
if __name__ == '__main__':
1591 1592
    with fluid.framework._test_eager_guard():
        unittest.main()