test_jit_save_load.py 56.6 KB
Newer Older
1
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
2
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
3 4 5 6 7 8 9 10 11 12 13 14 15
#
# 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.

16
import os
17
import pickle
18
import shutil
19
import tempfile
20 21
import unittest

22
import numpy as np
23

L
Leo Chen 已提交
24
import paddle
25
import paddle.fluid as fluid
26
from paddle.fluid import unique_name
27
from paddle.fluid.dygraph.io import INFER_PARAMS_INFO_SUFFIX
28 29
from paddle.fluid.layers.utils import flatten
from paddle.jit.api import declarative
30
from paddle.nn import Linear
31
from paddle.static import InputSpec
32 33

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


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

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

    return __reader__


class LinearNet(fluid.dygraph.Layer):
    def __init__(self, in_size, out_size):
57
        super().__init__()
58 59 60 61 62 63 64
        self._linear = Linear(in_size, out_size)

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


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

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


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

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


84 85
class LinerNetWithLabel(paddle.nn.Layer):
    def __init__(self, in_size, out_size):
86
        super().__init__()
87 88
        self._linear = Linear(in_size, out_size)

89 90 91 92 93 94
    @declarative(
        input_spec=[
            InputSpec(shape=[None, 784], dtype='float32', name="image"),
            InputSpec(shape=[None, 1], dtype='int64', name="label"),
        ]
    )
95 96
    def forward(self, x, label):
        out = self._linear(x)
97 98 99
        loss = paddle.nn.functional.cross_entropy(
            out, label, reduction='none', use_softmax=False
        )
100
        avg_loss = paddle.mean(loss)
101 102 103
        return out, avg_loss


C
Chen Weihang 已提交
104 105
class LinerNetWithPruneInput(paddle.nn.Layer):
    def __init__(self, in_size, out_size):
106
        super().__init__()
C
Chen Weihang 已提交
107 108
        self._linear = Linear(in_size, out_size)

109 110 111 112 113 114
    @declarative(
        input_spec=[
            InputSpec(shape=[None, 784], dtype='float32', name="image"),
            InputSpec(shape=[None, 1], dtype='int64', name="label"),
        ]
    )
C
Chen Weihang 已提交
115 116
    def forward(self, x, label):
        out = self._linear(x)
117 118 119
        loss = paddle.nn.functional.cross_entropy(
            out, label, reduction='none', use_softmax=False
        )
120
        avg_loss = paddle.mean(loss)
C
Chen Weihang 已提交
121 122 123 124 125
        return out


class LinerNetWithUselessInput(paddle.nn.Layer):
    def __init__(self, in_size, out_size):
126
        super().__init__()
C
Chen Weihang 已提交
127 128
        self._linear = Linear(in_size, out_size)

129 130 131 132 133 134
    @declarative(
        input_spec=[
            InputSpec(shape=[None, 784], dtype='float32', name="image"),
            InputSpec(shape=[None, 1], dtype='int64', name="label"),
        ]
    )
C
Chen Weihang 已提交
135 136 137 138 139
    def forward(self, x, label):
        out = self._linear(x)
        return out


140 141
class LinearNetReturnLoss(fluid.dygraph.Layer):
    def __init__(self, in_size, out_size):
142
        super().__init__()
143 144 145 146 147 148
        self._linear = Linear(in_size, out_size)

    @declarative
    def forward(self, x):
        y = self._linear(x)
        z = self._linear(y)
149
        loss = paddle.mean(z)
150 151 152
        return z, loss


153 154
class LinearNetMultiInput(fluid.dygraph.Layer):
    def __init__(self, in_size, out_size):
155
        super().__init__()
156 157 158
        self._linear1 = Linear(in_size, out_size)
        self._linear2 = Linear(in_size, out_size)

159 160 161 162 163 164
    @declarative(
        input_spec=[
            InputSpec([None, 8], dtype='float32'),
            InputSpec([None, 8], dtype='float32'),
        ]
    )
165 166 167
    def forward(self, x, y):
        x_out = self._linear1(x)
        y_out = self._linear2(y)
168
        loss = paddle.mean(x_out + y_out)
169 170 171
        return x_out, y_out, loss


172 173
class LinearNetMultiInput1(fluid.dygraph.Layer):
    def __init__(self, in_size, out_size):
174
        super().__init__()
175 176 177
        self._linear1 = Linear(in_size, out_size)
        self._linear2 = Linear(in_size, out_size)

178 179 180 181 182 183
    @declarative(
        input_spec=(
            InputSpec([None, 8], dtype='float32'),
            InputSpec([None, 8], dtype='float32'),
        )
    )
184 185 186
    def forward(self, x, y):
        x_out = self._linear1(x)
        y_out = self._linear2(y)
187
        loss = paddle.mean(x_out + y_out)
188 189 190
        return x_out, y_out, loss


191 192
class MultiLoadingLinearNet(fluid.dygraph.Layer):
    def __init__(self, size, model_path):
193
        super().__init__()
194
        self._linear = Linear(size, size)
195 196
        self._load_linear1 = paddle.jit.load(model_path)
        self._load_linear2 = paddle.jit.load(model_path)
197 198 199 200 201 202 203 204 205 206 207 208

    @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):
209
        super().__init__()
210 211 212 213 214 215 216
        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)
217
        loss = paddle.mean(z)
218 219 220
        return y, loss


221 222
class LinearNetWithNestOut(fluid.dygraph.Layer):
    def __init__(self, in_size, out_size):
223
        super().__init__()
224 225 226 227 228 229 230 231
        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
232
        loss = paddle.mean(out)
233 234 235
        return y, [(z, loss), out]


236 237
class LinearNetWithDictInput(paddle.nn.Layer):
    def __init__(self, in_size, out_size):
238
        super().__init__()
239 240
        self._linear = Linear(in_size, out_size)

241 242 243 244 245 246
    @paddle.jit.to_static(
        input_spec=[
            {'img': InputSpec(shape=[None, 8], dtype='float32', name='img')},
            {'label': InputSpec(shape=[None, 1], dtype='int64', name='label')},
        ]
    )
247 248 249 250 251 252 253
    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


254 255
class LinearNetWithDictInputNoPrune(paddle.nn.Layer):
    def __init__(self, in_size, out_size):
256
        super().__init__()
257 258 259 260 261 262 263
        self._linear = Linear(in_size, out_size)

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


264 265
class EmptyLayer(paddle.nn.Layer):
    def __init__(self):
266
        super().__init__()
267 268 269 270 271 272 273 274

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


class NoParamLayer(paddle.nn.Layer):
    def __init__(self):
275
        super().__init__()
276 277 278 279 280 281

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


282 283
class LinearNetWithMultiStaticFunc(fluid.dygraph.Layer):
    def __init__(self, in_size, out_size):
284
        super().__init__()
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
        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


302
def train(layer, input_size=784, label_size=1):
303
    # create optimizer
304 305 306
    sgd = fluid.optimizer.SGDOptimizer(
        learning_rate=0.01, parameter_list=layer.parameters()
    )
307 308
    # create data loader
    train_loader = fluid.io.DataLoader.from_generator(capacity=5)
309 310 311
    train_loader.set_batch_generator(
        random_batch_reader(input_size, label_size)
    )
312 313 314 315 316 317 318
    # train
    for data in train_loader():
        img, label = data
        label.stop_gradient = True

        cost = layer(img)

319 320 321
        loss = paddle.nn.functional.cross_entropy(
            cost, label, reduction='none', use_softmax=False
        )
322
        avg_loss = paddle.mean(loss)
323 324

        avg_loss.backward()
L
Leo Chen 已提交
325
        sgd.minimize(avg_loss)
326 327 328 329
        layer.clear_gradients()
    return [img], layer, avg_loss


330 331
def train_with_label(layer, input_size=784, label_size=1):
    # create optimizer
332 333 334
    sgd = fluid.optimizer.SGDOptimizer(
        learning_rate=0.01, parameter_list=layer.parameters()
    )
335 336
    # create data loader
    train_loader = fluid.io.DataLoader.from_generator(capacity=5)
337 338 339
    train_loader.set_batch_generator(
        random_batch_reader(input_size, label_size)
    )
340 341 342 343 344 345 346 347 348 349 350 351 352
    # 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


353 354
class TestJitSaveLoad(unittest.TestCase):
    def setUp(self):
355
        self.temp_dir = tempfile.TemporaryDirectory()
356 357 358
        self.model_path = os.path.join(
            self.temp_dir.name, "test_jit_save_load/model"
        )
359 360 361
        # enable dygraph mode
        fluid.enable_dygraph()
        # config seed
C
cnn 已提交
362
        paddle.seed(SEED)
L
Leo Chen 已提交
363
        paddle.framework.random._manual_program_seed(SEED)
364

365 366 367
    def tearDown(self):
        self.temp_dir.cleanup()

368
    def train_and_save_model(self, model_path=None):
369 370
        layer = LinearNet(784, 1)
        example_inputs, layer, _ = train(layer)
371
        final_model_path = model_path if model_path else self.model_path
372
        orig_input_types = [type(x) for x in example_inputs]
373 374 375
        paddle.jit.save(
            layer=layer, path=final_model_path, input_spec=example_inputs
        )
376 377
        new_input_types = [type(x) for x in example_inputs]
        self.assertEqual(orig_input_types, new_input_types)
378 379
        return layer

380
    def test_save_load(self):
381 382 383
        # train and save model
        train_layer = self.train_and_save_model()
        # load model
384
        loaded_layer = paddle.jit.load(self.model_path)
385 386 387 388 389
        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):
390
        train_layer.eval()
391
        infer_layer.eval()
392 393
        # inference & compare
        x = fluid.dygraph.to_variable(
394 395
            np.random.random((1, 784)).astype('float32')
        )
396
        np.testing.assert_array_equal(
397 398
            train_layer(x).numpy(), infer_layer(x).numpy()
        )
399

400 401
    def load_and_finetune(self, train_layer, load_train_layer):
        train_layer.train()
402 403
        load_train_layer.train()
        # train & compare
L
Leo Chen 已提交
404 405
        img0, _, train_loss = train(train_layer)
        img1, _, load_train_loss = train(load_train_layer)
406 407 408
        np.testing.assert_array_equal(
            train_loss.numpy(), load_train_loss.numpy()
        )
409

410 411
    def load_dygraph_state_dict(self, train_layer):
        train_layer.eval()
412
        # construct new model
413
        new_layer = LinearNet(784, 1)
414
        orig_state_dict = new_layer.state_dict()
415
        load_state_dict = paddle.load(self.model_path)
416 417 418
        for structured_name in orig_state_dict:
            self.assertTrue(structured_name in load_state_dict)
        new_layer.set_state_dict(load_state_dict)
419 420 421
        new_layer.eval()
        # inference & compare
        x = fluid.dygraph.to_variable(
422 423
            np.random.random((1, 784)).astype('float32')
        )
424
        np.testing.assert_array_equal(
425 426
            train_layer(x).numpy(), new_layer(x).numpy()
        )
427

428
    def test_load_dygraph_no_path(self):
429 430 431
        model_path = os.path.join(
            self.temp_dir.name, "test_jit_save_load.no_path/model_path"
        )
432 433 434
        with self.assertRaises(ValueError):
            model_dict, _ = fluid.dygraph.load_dygraph(model_path)

435
    def test_jit_load_no_path(self):
436 437 438
        path = os.path.join(
            self.temp_dir.name, "test_jit_save_load.no_path/model_path"
        )
439 440 441
        with self.assertRaises(ValueError):
            loaded_layer = paddle.jit.load(path)

442

443 444 445 446
class TestSaveLoadWithNestOut(unittest.TestCase):
    def setUp(self):
        # enable dygraph mode
        fluid.enable_dygraph()
447 448 449 450
        self.temp_dir = tempfile.TemporaryDirectory()

    def tearDown(self):
        self.temp_dir.cleanup()
451 452 453

    def test_nest_output(self):
        x = fluid.dygraph.to_variable(
454 455
            np.random.random((4, 8)).astype('float32')
        )
456 457 458 459 460

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

461
        model_path = os.path.join(self.temp_dir.name, "net_with_nest_out/model")
462 463 464 465 466 467 468
        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):
469 470 471
            np.testing.assert_allclose(
                dy_out.numpy(), load_out.numpy(), rtol=1e-05
            )
472 473


474 475
class TestSaveLoadWithDictInput(unittest.TestCase):
    def test_dict_input(self):
476
        # NOTE: This net cannot be executed, it is just
477 478 479
        # a special case for exporting models in model validation
        # We DO NOT recommend this writing way of Layer
        net = LinearNetWithDictInput(8, 8)
480 481 482
        # net.forward.concrete_program.inputs:
        # (<__main__.LinearNetWithDictInput object at 0x7f2655298a98>,
        #  {'img': var img : fluid.VarType.LOD_TENSOR.shape(-1, 8).astype(VarType.FP32)},
483 484
        #  {'label': var label : fluid.VarType.LOD_TENSOR.shape(-1, 1).astype(VarType.INT64)})
        self.assertEqual(len(net.forward.concrete_program.inputs), 3)
485
        temp_dir = tempfile.TemporaryDirectory()
486 487 488
        path = os.path.join(
            temp_dir.name, "test_jit_save_load_with_dict_input/model"
        )
489
        # prune inputs
490 491 492 493 494 495 496
        paddle.jit.save(
            layer=net,
            path=path,
            input_spec=[
                {'img': InputSpec(shape=[None, 8], dtype='float32', name='img')}
            ],
        )
497 498 499 500 501 502 503 504

        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)
505
        temp_dir.cleanup()
506 507


508 509 510
class TestSaveLoadWithDictInputNoPrune(unittest.TestCase):
    def test_dict_input(self):
        net = LinearNetWithDictInputNoPrune(8, 8)
511 512
        temp_dir = tempfile.TemporaryDirectory()
        path = os.path.join(
513 514
            temp_dir.name, "test_jit_save_load_with_dict_input_no_prune/model"
        )
515
        # prune inputs
516 517 518 519 520 521 522 523 524 525 526 527 528 529
        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'
                    ),
                }
            ],
        )
530 531 532 533 534 535 536

        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)
537
        temp_dir.cleanup()
538 539


540 541 542 543
class TestSaveLoadWithInputSpec(unittest.TestCase):
    def setUp(self):
        # enable dygraph mode
        fluid.enable_dygraph()
544 545 546 547
        self.temp_dir = tempfile.TemporaryDirectory()

    def tearDown(self):
        self.temp_dir.cleanup()
548 549 550 551

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

556 557 558
        model_path = os.path.join(
            self.temp_dir.name, "input_spec.output_spec/model"
        )
559 560 561 562 563 564 565
        # 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
566 567
        output_spec = net.forward.outputs[:1]
        paddle.jit.save(net, model_path, output_spec=output_spec)
568 569

        # 2. load to infer
570
        infer_layer = paddle.jit.load(model_path)
571
        x = fluid.dygraph.to_variable(
572 573
            np.random.random((4, 8)).astype('float32')
        )
574 575 576 577 578
        pred = infer_layer(x)

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

579 580 581
        model_path = os.path.join(
            self.temp_dir.name, "multi_inout.output_spec1/model"
        )
582 583 584 585 586 587 588 589
        # 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
590 591
        output_spec = net.forward.outputs[:2]
        paddle.jit.save(net, model_path, output_spec=output_spec)
592 593

        # 3. load to infer
594
        infer_layer = paddle.jit.load(model_path)
595
        x = fluid.dygraph.to_variable(
596 597
            np.random.random((4, 8)).astype('float32')
        )
598
        y = fluid.dygraph.to_variable(
599 600
            np.random.random((4, 8)).astype('float32')
        )
601 602 603 604
        # 4. predict
        pred_x, pred_y = infer_layer(x, y)

        # 1. prune y and loss
605 606 607
        model_path = os.path.join(
            self.temp_dir.name, "multi_inout.output_spec2/model"
        )
608 609
        output_spec = net.forward.outputs[:1]
        paddle.jit.save(net, model_path, [input_x], output_spec=output_spec)
610
        # 2. load again
611
        infer_layer2 = paddle.jit.load(model_path)
612 613 614 615
        # 3. predict
        pred_xx = infer_layer2(x)

        # 4. assert pred_x == pred_xx
616
        np.testing.assert_allclose(pred_x.numpy(), pred_xx.numpy(), rtol=1e-05)
617 618 619 620

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

621 622 623
        model_path = os.path.join(
            self.temp_dir.name, "multi_inout1.output_spec1/model"
        )
624 625 626 627 628 629 630 631 632 633 634 635 636 637
        # 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(
638 639
            np.random.random((4, 8)).astype('float32')
        )
640
        y = fluid.dygraph.to_variable(
641 642
            np.random.random((4, 8)).astype('float32')
        )
643 644 645 646
        # 4. predict
        pred_x, pred_y = infer_layer(x, y)

        # 1. prune y and loss
647 648 649
        model_path = os.path.join(
            self.temp_dir.name, "multi_inout1.output_spec2/model"
        )
650
        output_spec = net.forward.outputs[:1]
651
        paddle.jit.save(net, model_path, (input_x,), output_spec=output_spec)
652 653 654 655 656 657
        # 2. load again
        infer_layer2 = paddle.jit.load(model_path)
        # 3. predict
        pred_xx = infer_layer2(x)

        # 4. assert pred_x == pred_xx
658
        np.testing.assert_allclose(pred_x.numpy(), pred_xx.numpy(), rtol=1e-05)
659 660


661 662 663 664 665
class TestJitSaveLoadConfig(unittest.TestCase):
    def setUp(self):
        # enable dygraph mode
        fluid.enable_dygraph()
        # config seed
C
cnn 已提交
666
        paddle.seed(SEED)
L
Leo Chen 已提交
667
        paddle.framework.random._manual_program_seed(SEED)
668 669 670 671
        self.temp_dir = tempfile.TemporaryDirectory()

    def tearDown(self):
        self.temp_dir.cleanup()
672 673 674 675

    def test_output_spec(self):
        train_layer = LinearNetReturnLoss(8, 8)
        adam = fluid.optimizer.AdamOptimizer(
676 677
            learning_rate=0.1, parameter_list=train_layer.parameters()
        )
678
        x = fluid.dygraph.to_variable(
679 680
            np.random.random((4, 8)).astype('float32')
        )
681 682 683 684 685 686
        for i in range(10):
            out, loss = train_layer(x)
            loss.backward()
            adam.minimize(loss)
            train_layer.clear_gradients()

687 688 689
        model_path = os.path.join(
            self.temp_dir.name, "save_load_config.output_spec"
        )
690
        output_spec = [out]
691 692 693 694 695 696
        paddle.jit.save(
            layer=train_layer,
            path=model_path,
            input_spec=[x],
            output_spec=output_spec,
        )
697 698

        train_layer.eval()
699
        infer_layer = paddle.jit.load(model_path)
700
        x = fluid.dygraph.to_variable(
701 702
            np.random.random((4, 8)).astype('float32')
        )
703
        np.testing.assert_array_equal(
704 705
            train_layer(x)[0].numpy(), infer_layer(x).numpy()
        )
706

707 708
    def test_save_no_support_config_error(self):
        layer = LinearNet(784, 1)
709
        path = os.path.join(self.temp_dir.name, "no_support_config_test")
710 711 712 713
        with self.assertRaises(ValueError):
            paddle.jit.save(layer=layer, path=path, model_filename="")

    def test_load_empty_model_filename_error(self):
714
        path = os.path.join(self.temp_dir.name, "error_model_filename_test")
715 716 717 718
        with self.assertRaises(ValueError):
            paddle.jit.load(path, model_filename="")

    def test_load_empty_params_filename_error(self):
719
        path = os.path.join(self.temp_dir.name, "error_params_filename_test")
720 721 722 723
        with self.assertRaises(ValueError):
            paddle.jit.load(path, params_filename="")

    def test_load_with_no_support_config(self):
724
        path = os.path.join(self.temp_dir.name, "no_support_config_test")
725 726 727
        with self.assertRaises(ValueError):
            paddle.jit.load(path, separate_params=True)

728

729 730 731
class TestJitMultipleLoading(unittest.TestCase):
    def setUp(self):
        self.linear_size = 4
732
        self.temp_dir = tempfile.TemporaryDirectory()
733 734 735
        self.model_path = os.path.join(
            self.temp_dir.name, "jit_multi_load/model"
        )
736 737 738
        # enable dygraph mode
        fluid.enable_dygraph()
        # config seed
C
cnn 已提交
739
        paddle.seed(SEED)
L
Leo Chen 已提交
740
        paddle.framework.random._manual_program_seed(SEED)
741 742 743
        # train and save base model
        self.train_and_save_orig_model()

744 745 746
    def tearDown(self):
        self.temp_dir.cleanup()

747 748 749
    def train_and_save_orig_model(self):
        layer = LinearNet(self.linear_size, self.linear_size)
        example_inputs, layer, _ = train(layer, self.linear_size, 1)
750 751 752
        paddle.jit.save(
            layer=layer, path=self.model_path, input_spec=example_inputs
        )
753 754

    def test_load_model_retransform_inference(self):
755 756 757
        multi_loaded_layer = MultiLoadingLinearNet(
            self.linear_size, self.model_path
        )
758 759 760 761 762 763 764
        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)


765 766 767
class TestJitPruneModelAndLoad(unittest.TestCase):
    def setUp(self):
        self.linear_size = 4
768
        self.temp_dir = tempfile.TemporaryDirectory()
769 770 771
        self.model_path = os.path.join(
            self.temp_dir.name, "jit_prune_model_and_load/model"
        )
772 773 774
        # enable dygraph mode
        fluid.enable_dygraph()
        # config seed
C
cnn 已提交
775
        paddle.seed(SEED)
L
Leo Chen 已提交
776
        paddle.framework.random._manual_program_seed(SEED)
777

778 779 780
    def tearDown(self):
        self.temp_dir.cleanup()

781 782 783
    def train_and_save(self):
        train_layer = LinearNetReturnHidden(8, 8)
        adam = fluid.optimizer.AdamOptimizer(
784 785
            learning_rate=0.1, parameter_list=train_layer.parameters()
        )
786
        x = fluid.dygraph.to_variable(
787 788
            np.random.random((4, 8)).astype('float32')
        )
789 790 791 792 793 794
        for i in range(10):
            hidden, loss = train_layer(x)
            loss.backward()
            adam.minimize(loss)
            train_layer.clear_gradients()

795
        output_spec = [hidden]
796 797 798 799 800 801
        paddle.jit.save(
            layer=train_layer,
            path=self.model_path,
            input_spec=[x],
            output_spec=output_spec,
        )
802 803 804 805 806 807 808

        return train_layer

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

809
        infer_layer = paddle.jit.load(self.model_path)
810 811

        x = fluid.dygraph.to_variable(
812 813
            np.random.random((4, 8)).astype('float32')
        )
814
        np.testing.assert_array_equal(
815 816
            train_layer(x)[0].numpy(), infer_layer(x).numpy()
        )
817 818 819 820 821

    def test_load_var_not_in_extra_var_info(self):
        self.train_and_save()

        # chage extra var info
822
        var_info_path = self.model_path + INFER_PARAMS_INFO_SUFFIX
823 824 825 826 827 828 829
        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):
830
            paddle.jit.load(self.model_path)
831 832


833 834 835 836 837
class TestJitSaveMultiCases(unittest.TestCase):
    def setUp(self):
        # enable dygraph mode
        fluid.enable_dygraph()
        # config seed
C
cnn 已提交
838
        paddle.seed(SEED)
839
        paddle.framework.random._manual_program_seed(SEED)
840 841 842 843
        self.temp_dir = tempfile.TemporaryDirectory()

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

845 846 847
    def verify_inference_correctness(
        self, layer, model_path, with_label_and_loss=False, with_label=False
    ):
848 849 850 851
        layer.eval()
        loaded_layer = paddle.jit.load(model_path)
        loaded_layer.eval()
        # inference & compare
Z
Zhou Wei 已提交
852
        x = paddle.to_tensor(np.random.random((1, 784)).astype('float32'))
C
Chen Weihang 已提交
853
        if with_label_and_loss:
Z
Zhou Wei 已提交
854
            y = paddle.to_tensor(np.random.random((1, 1)).astype('int64'))
855 856
            pred, _ = layer(x, y)
            pred = pred.numpy()
C
Chen Weihang 已提交
857 858 859 860
        elif with_label:
            y = paddle.to_tensor(np.random.random((1, 1)).astype('int64'))
            pred = layer(x, y)
            pred = pred.numpy()
861 862 863
        else:
            pred = layer(x).numpy()
        loaded_pred = loaded_layer(x).numpy()
864 865 866
        np.testing.assert_array_equal(
            pred,
            loaded_pred,
867 868 869 870
            err_msg='Result diff when load and inference:\nlayer result:\n{}\nloaded layer result:\n{}'.format(
                pred, loaded_pred
            ),
        )
871 872 873 874 875 876

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

        train(layer)

877 878 879
        model_path = os.path.join(
            self.temp_dir.name, "test_no_prune_to_static_after_train/model"
        )
880 881 882 883 884 885 886
        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)

887 888 889
        model_path = os.path.join(
            self.temp_dir.name, "test_no_prune_to_static_no_train/model"
        )
890 891 892 893 894 895 896 897 898
        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)

899
        model_path = os.path.join(
900 901
            self.temp_dir.name, "test_no_prune_no_to_static_after_train/model"
        )
902 903 904
        paddle.jit.save(
            layer,
            model_path,
905 906
            input_spec=[InputSpec(shape=[None, 784], dtype='float32')],
        )
907 908 909 910 911 912 913 914

        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)

915 916
        model_path = os.path.join(
            self.temp_dir.name,
917 918
            "test_no_prune_no_to_static_after_train_with_examples/model",
        )
919
        paddle.jit.save(layer=layer, path=model_path, input_spec=example_inputs)
920 921 922 923 924 925

        self.verify_inference_correctness(layer, model_path)

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

926 927 928
        model_path = os.path.join(
            self.temp_dir.name, "test_no_prune_no_to_static_no_train/model"
        )
929 930 931
        paddle.jit.save(
            layer,
            model_path,
932 933
            input_spec=[InputSpec(shape=[None, 784], dtype='float32')],
        )
934 935 936 937 938 939 940 941

        self.verify_inference_correctness(layer, model_path)

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

        out = train_with_label(layer)

942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
        model_path = os.path.join(
            self.temp_dir.name, "test_prune_to_static_after_train/model"
        )
        paddle.jit.save(
            layer,
            model_path,
            input_spec=[
                InputSpec(shape=[None, 784], dtype='float32', name="image")
            ],
            output_spec=[out],
        )

        self.verify_inference_correctness(
            layer, model_path, with_label_and_loss=True
        )
957 958 959 960

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

961 962 963
        model_path = os.path.join(
            self.temp_dir.name, "test_prune_to_static_no_train/model"
        )
964 965
        # TODO: no train, cannot get output_spec var here
        # now only can use index
966
        output_spec = layer.forward.outputs[:1]
967 968 969 970 971 972 973 974 975 976 977 978
        paddle.jit.save(
            layer,
            model_path,
            input_spec=[
                InputSpec(shape=[None, 784], dtype='float32', name="image")
            ],
            output_spec=output_spec,
        )

        self.verify_inference_correctness(
            layer, model_path, with_label_and_loss=True
        )
C
Chen Weihang 已提交
979 980 981 982

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

983 984 985 986 987 988 989 990 991 992
        model_path = os.path.join(
            self.temp_dir.name, "test_prune_input_to_static_no_train/model"
        )
        paddle.jit.save(
            layer,
            model_path,
            input_spec=[
                InputSpec(shape=[None, 784], dtype='float32', name="image")
            ],
        )
C
Chen Weihang 已提交
993 994 995 996 997 998

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

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

999 1000
        model_path = os.path.join(
            self.temp_dir.name,
1001 1002 1003 1004 1005 1006 1007 1008 1009
            "test_prune_useless_input_to_static_no_train/model",
        )
        paddle.jit.save(
            layer,
            model_path,
            input_spec=[
                InputSpec(shape=[None, 784], dtype='float32', name="image")
            ],
        )
C
Chen Weihang 已提交
1010 1011

        self.verify_inference_correctness(layer, model_path, with_label=True)
1012 1013 1014 1015 1016 1017

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

        train(layer)

1018
        model_path = os.path.join(
1019 1020
            self.temp_dir.name, "test_no_prune_input_spec_name_warning/model"
        )
1021 1022 1023
        paddle.jit.save(
            layer,
            model_path,
1024 1025 1026 1027 1028 1029 1030 1031 1032
            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')
            ],
        )
1033 1034 1035 1036 1037 1038 1039 1040

        self.verify_inference_correctness(layer, model_path)

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

        train(layer)

1041
        model_path = os.path.join(
1042 1043
            self.temp_dir.name, "test_not_prune_output_spec_name_warning/model"
        )
Z
Zhou Wei 已提交
1044
        out = paddle.to_tensor(np.random.random((1, 1)).astype('float'))
1045
        paddle.jit.save(layer, model_path, output_spec=[out])
1046 1047 1048 1049 1050 1051

        self.verify_inference_correctness(layer, model_path)

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

1052 1053 1054
        model_path = os.path.join(
            self.temp_dir.name, "test_prune_input_spec_name_error/model"
        )
1055 1056 1057 1058
        with self.assertRaises(ValueError):
            paddle.jit.save(
                layer,
                model_path,
1059 1060
                input_spec=[InputSpec(shape=[None, 784], dtype='float32')],
            )
1061
        with self.assertRaises(ValueError):
1062 1063 1064 1065 1066 1067 1068 1069 1070
            paddle.jit.save(
                layer,
                model_path,
                input_spec=[
                    InputSpec(
                        shape=[None, 784], dtype='float32', name='feed_input'
                    )
                ],
            )
1071 1072 1073 1074 1075 1076

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

        train_with_label(layer)

1077 1078 1079
        model_path = os.path.join(
            self.temp_dir.name, "test_prune_to_static_after_train/model"
        )
Z
Zhou Wei 已提交
1080
        out = paddle.to_tensor(np.random.random((1, 1)).astype('float'))
1081
        with self.assertRaises(ValueError):
1082 1083 1084 1085 1086 1087 1088 1089
            paddle.jit.save(
                layer,
                model_path,
                input_spec=[
                    InputSpec(shape=[None, 784], dtype='float32', name="image")
                ],
                output_spec=[out],
            )
1090 1091


1092 1093
class TestJitSaveLoadEmptyLayer(unittest.TestCase):
    def setUp(self):
1094
        self.temp_dir = tempfile.TemporaryDirectory()
1095 1096 1097
        self.model_path = os.path.join(
            self.temp_dir.name, "jit_save_load_empty_layer/model"
        )
1098 1099 1100
        # enable dygraph mode
        paddle.disable_static()

1101 1102 1103
    def tearDown(self):
        self.temp_dir.cleanup()

1104 1105
    def test_save_load_empty_layer(self):
        layer = EmptyLayer()
Z
Zhou Wei 已提交
1106
        x = paddle.to_tensor(np.random.random((10)).astype('float32'))
1107 1108 1109 1110
        out = layer(x)
        paddle.jit.save(layer, self.model_path)
        load_layer = paddle.jit.load(self.model_path)
        load_out = load_layer(x)
1111
        np.testing.assert_array_equal(out, load_out)
1112 1113 1114 1115


class TestJitSaveLoadNoParamLayer(unittest.TestCase):
    def setUp(self):
1116
        self.temp_dir = tempfile.TemporaryDirectory()
1117 1118 1119
        self.model_path = os.path.join(
            self.temp_dir.name, "jit_save_load_no_param_layer/model"
        )
1120 1121 1122
        # enable dygraph mode
        paddle.disable_static()

1123 1124 1125
    def tearDown(self):
        self.temp_dir.cleanup()

1126 1127
    def test_save_load_no_param_layer(self):
        layer = NoParamLayer()
Z
Zhou Wei 已提交
1128 1129
        x = paddle.to_tensor(np.random.random((5)).astype('float32'))
        y = paddle.to_tensor(np.random.random((5)).astype('float32'))
1130 1131 1132 1133
        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)
1134
        np.testing.assert_array_equal(out, load_out)
1135 1136


1137 1138 1139 1140
class TestJitSaveLoadMultiMethods(unittest.TestCase):
    def setUp(self):
        # enable dygraph mode
        paddle.disable_static()
1141 1142 1143 1144
        self.temp_dir = tempfile.TemporaryDirectory()

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

    def test_jit_save_load_inference(self):
1147
        model_path_inference = os.path.join(
1148 1149
            self.temp_dir.name, "jit_save_load_multi_methods/model"
        )
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
        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(
1161 1162 1163 1164 1165
                float(
                    (result - getattr(load_net, func, None)(inps)).abs().max()
                )
                < 1e-5
            )
1166 1167

    def test_jit_save_load_multi_methods_inputspec(self):
1168 1169 1170
        model_path = os.path.join(
            self.temp_dir.name, 'jit_save_load_multi_methods/model'
        )
1171 1172
        layer = LinearNetWithMultiStaticFunc(784, 1)
        with self.assertRaises(ValueError):
1173 1174 1175
            paddle.jit.save(
                layer, model_path, input_spec=[InputSpec(shape=[None, 784])]
            )
1176

1177
    def test_parse_name(self):
1178 1179 1180
        model_path_inference = os.path.join(
            self.temp_dir.name, "jit_save_load_parse_name/model"
        )
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
        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'))

1191

W
WeiXin 已提交
1192 1193
class LayerSaved(paddle.nn.Layer):
    def __init__(self, in_size, out_size):
1194
        super().__init__()
W
WeiXin 已提交
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
        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
1206
        if paddle.shape(x)[0] == 1:
W
WeiXin 已提交
1207 1208 1209 1210 1211 1212
            y = self._linear_1_0(y)
        else:
            y += self._linear_1_1(y + self._scale)
        return self._linear_2(y)


1213 1214
class Net(paddle.nn.Layer):
    def __init__(self):
1215
        super().__init__()
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 1243
        self.fc1 = paddle.nn.Linear(4, 4)
        self.fc2 = paddle.nn.Linear(4, 4)
        self.bias = 0.4
        self.flag = paddle.ones([2], dtype="int32")

    @paddle.jit.to_static(input_spec=[InputSpec([None, 4], dtype='float32')])
    def log_softmax(self, input):
        return paddle.nn.functional.log_softmax(input, axis=-1)

    @paddle.jit.to_static(input_spec=[InputSpec([None, 4], dtype='float32')])
    def forward(self, x):
        out = self.fc1(x)
        out = paddle.nn.functional.relu(out)
        out = paddle.mean(out)
        return out

    @paddle.jit.to_static(input_spec=[InputSpec([None, 4], dtype='float32')])
    def infer(self, input):
        out = self.fc2(input)
        out = out + self.bias
        out = paddle.mean(out)
        return out

    # For extra Python float
    @paddle.jit.to_static(property=True)
    def fbias(self):
        return self.bias + 1

1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
    @paddle.jit.to_static(property=True)
    def down_sampling(self):
        return 4

    @paddle.jit.to_static(property=True)
    def fstr(self):
        return "save str property"

    @paddle.jit.to_static(property=True)
    def ints(self):
        return [10, 20]

    @paddle.jit.to_static(property=True)
    def floats(self):
        return [1.1, 2.2]

    @paddle.jit.to_static(property=True)
    def strs(self):
        return ["hello", "world"]


class NetTensor(paddle.nn.Layer):
    def __init__(self):
        super().__init__()
        self.fc1 = paddle.nn.Linear(4, 4)
        self.fc2 = paddle.nn.Linear(4, 4)
        self.bias = 0.4
        self.flag = paddle.ones([2], dtype="int32")

    @paddle.jit.to_static(input_spec=[InputSpec([None, 4], dtype='float32')])
    def forward(self, x):
        out = self.fc1(x)
        out = paddle.nn.functional.relu(out)
        out = paddle.mean(out)
        return out

1280 1281
    @paddle.jit.to_static(property=True)
    def fflag(self):
1282
        return True
1283 1284


1285
class TestJitSaveCombineProperty(unittest.TestCase):
1286 1287 1288 1289 1290 1291 1292 1293
    def setUp(self):
        # enable dygraph mode
        paddle.disable_static()
        self.temp_dir = tempfile.TemporaryDirectory()

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

1294
    def test_jit_save_combine_property(self):
1295 1296 1297
        model_path = os.path.join(
            self.temp_dir.name, "test_jit_save_combine/model"
        )
1298 1299 1300
        # Use new namespace
        with unique_name.guard():
            net = Net()
1301
        # save
1302
        paddle.jit.save(net, model_path, combine_params=True)
1303

1304
    def test_jit_save_tensor_property(self):
1305 1306 1307
        model_path = os.path.join(
            self.temp_dir.name, "test_jit_save_combine/model"
        )
1308 1309 1310 1311 1312 1313
        # Use new namespace
        with unique_name.guard():
            net = NetTensor()

        paddle.jit.save(net, model_path, combine_params=True)

1314

W
WeiXin 已提交
1315 1316
class LayerLoadFinetune(paddle.nn.Layer):
    def __init__(self, in_size, out_size, load_path):
1317
        super().__init__()
W
WeiXin 已提交
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
        # 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
1334
        if paddle.shape(x)[0] == 1:
W
WeiXin 已提交
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
            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


1348 1349 1350 1351
class TestJitSaveLoadSaveWithoutRunning(unittest.TestCase):
    def setUp(self):
        # enable dygraph mode
        paddle.disable_static()
1352 1353 1354 1355
        self.temp_dir = tempfile.TemporaryDirectory()

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

    def test_save_load_finetune_load(self):
1358
        model_path = os.path.join(
1359 1360
            self.temp_dir.name, "test_jit_save_load_save_without_running/model"
        )
1361 1362 1363 1364 1365 1366
        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)
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
        # save
        paddle.jit.save(
            layer_save,
            model_path,
            input_spec=[
                paddle.static.InputSpec(
                    shape=[None, IMAGE_SIZE], dtype='float32'
                )
            ],
        )
1377 1378
        result_00 = layer_save(inps0)
        result_01 = layer_save(inps1)
1379
        # load and save without running
1380 1381
        with unique_name.guard():
            layer_load = paddle.jit.load(model_path)
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
            paddle.jit.save(
                layer_load,
                model_path,
                input_spec=[
                    paddle.static.InputSpec(
                        shape=[None, IMAGE_SIZE], dtype='float32'
                    )
                ],
            )
        # reload
1392 1393 1394 1395 1396 1397 1398 1399
        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 已提交
1400 1401 1402 1403
class TestJitSaveLoadFinetuneLoad(unittest.TestCase):
    def setUp(self):
        # enable dygraph mode
        paddle.disable_static()
1404 1405 1406 1407
        self.temp_dir = tempfile.TemporaryDirectory()

    def tearDown(self):
        self.temp_dir.cleanup()
W
WeiXin 已提交
1408 1409

    def test_save_load_finetune_load(self):
1410 1411 1412
        model_path = os.path.join(
            self.temp_dir.name, "test_jit_save_load_finetune_load/model"
        )
W
WeiXin 已提交
1413 1414 1415 1416 1417 1418 1419
        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)
1420
        # save
W
WeiXin 已提交
1421
        paddle.jit.save(layer_save, model_path)
1422
        # load
W
WeiXin 已提交
1423 1424
        with unique_name.guard():
            layer_load = LayerLoadFinetune(IMAGE_SIZE, IMAGE_SIZE, model_path)
1425
        # train
W
WeiXin 已提交
1426 1427 1428
        train(layer_load, input_size=IMAGE_SIZE)
        result_00 = layer_load(inps0)
        result_01 = layer_load(inps1)
1429
        # save
W
WeiXin 已提交
1430
        paddle.jit.save(layer_load, model_path)
1431
        # load
W
WeiXin 已提交
1432 1433 1434 1435 1436 1437 1438 1439
        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)


1440 1441 1442 1443
# 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,
1444 1445
# TestJitSaveLoadFunctionCase2, TestJitSaveLoadFunctionCase3.
class TestJitSaveLoadFunctionCase1(unittest.TestCase):
1446 1447
    def setUp(self):
        paddle.disable_static()
1448 1449 1450 1451
        self.temp_dir = tempfile.TemporaryDirectory()

    def tearDown(self):
        self.temp_dir.cleanup()
1452 1453 1454 1455 1456 1457

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

1458 1459 1460
        path = os.path.join(
            self.temp_dir.name, 'test_jit_save_load_function_1/func'
        )
1461 1462 1463 1464 1465 1466 1467 1468 1469
        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)

1470 1471 1472 1473

class TestJitSaveLoadFunctionCase2(unittest.TestCase):
    def setUp(self):
        paddle.disable_static()
1474 1475 1476 1477
        self.temp_dir = tempfile.TemporaryDirectory()

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

1479
    def test_jit_save_load_function_input_spec(self):
1480 1481 1482 1483 1484
        @paddle.jit.to_static(
            input_spec=[
                InputSpec(shape=[None, 6], dtype='float32', name='x'),
            ]
        )
1485 1486 1487
        def fun(inputs):
            return paddle.nn.functional.relu(inputs)

1488 1489 1490
        path = os.path.join(
            self.temp_dir.name, 'test_jit_save_load_function_2/func'
        )
1491 1492 1493 1494 1495 1496 1497 1498
        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)

1499 1500 1501 1502

class TestJitSaveLoadFunctionCase3(unittest.TestCase):
    def setUp(self):
        paddle.disable_static()
1503 1504 1505 1506
        self.temp_dir = tempfile.TemporaryDirectory()

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

1508 1509 1510 1511
    def test_jit_save_load_function_function(self):
        def fun(inputs):
            return paddle.tanh(inputs)

1512 1513 1514
        path = os.path.join(
            self.temp_dir.name, 'test_jit_save_load_function_3/func'
        )
1515 1516 1517
        inps = paddle.rand([3, 6])
        origin = fun(inps)

1518 1519 1520 1521 1522 1523 1524
        paddle.jit.save(
            fun,
            path,
            input_spec=[
                InputSpec(shape=[None, 6], dtype='float32', name='x'),
            ],
        )
1525 1526 1527 1528 1529 1530
        load_func = paddle.jit.load(path)

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


1531 1532 1533
class TestJitSaveLoadFunctionWithParamCase1(unittest.TestCase):
    def setUp(self):
        paddle.disable_static()
1534 1535 1536 1537
        self.temp_dir = tempfile.TemporaryDirectory()

    def tearDown(self):
        self.temp_dir.cleanup()
1538 1539 1540 1541

    def test_jit_save_load_function(self):
        class LinearNet(paddle.nn.Layer):
            def __init__(self):
1542
                super().__init__()
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
                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)

1556 1557 1558
        func = paddle.jit.to_static(
            layer.anothor_forward, [paddle.static.InputSpec(shape=[-1, 5])]
        )
1559 1560
        path = os.path.join(
            self.temp_dir.name,
1561 1562
            'test_jit_save_load_function_with_params_case1/func',
        )
1563 1564 1565 1566
        paddle.jit.save(func, path)
        load_func = paddle.jit.load(path)

        load_result = load_func(inps)
1567
        np.testing.assert_array_equal(load_result.numpy(), origin.numpy())
1568 1569 1570 1571 1572


class TestJitSaveLoadFunctionWithParamCase2(unittest.TestCase):
    def setUp(self):
        paddle.disable_static()
1573 1574 1575 1576
        self.temp_dir = tempfile.TemporaryDirectory()

    def tearDown(self):
        self.temp_dir.cleanup()
1577 1578 1579 1580

    def test_jit_save_load_function(self):
        class LinearNet(paddle.nn.Layer):
            def __init__(self):
1581
                super().__init__()
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594
                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])

1595 1596
        path = os.path.join(
            self.temp_dir.name,
1597 1598
            'test_jit_save_load_function_with_params_case2/func',
        )
1599 1600 1601 1602 1603 1604
        paddle.jit.save(layer.anothor_forward, path)
        origin_result = layer.anothor_forward(inps)
        load_func = paddle.jit.load(path)

        load_result = load_func(inps)

1605 1606 1607
        np.testing.assert_array_equal(
            origin_result.numpy(), load_result.numpy()
        )
1608 1609 1610 1611 1612


class TestJitSaveLoadFunctionWithParamCase3(unittest.TestCase):
    def setUp(self):
        paddle.disable_static()
1613 1614 1615 1616
        self.temp_dir = tempfile.TemporaryDirectory()

    def tearDown(self):
        self.temp_dir.cleanup()
1617 1618 1619 1620

    def test_jit_save_load_function(self):
        class LinearNet(paddle.nn.Layer):
            def __init__(self):
1621
                super().__init__()
1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
                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)

1636 1637
        path = os.path.join(
            self.temp_dir.name,
1638 1639
            'test_jit_save_load_function_with_params_case3/func',
        )
1640 1641 1642 1643
        paddle.jit.save(layer.anothor_forward, path)
        load_func = paddle.jit.load(path)

        load_result = load_func(inps)
1644
        np.testing.assert_array_equal(load_result.numpy(), origin.numpy())
1645 1646


1647
class TestJitSaveLoadDataParallel(unittest.TestCase):
1648 1649 1650 1651 1652 1653
    def setUp(self):
        self.temp_dir = tempfile.TemporaryDirectory()

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

1654 1655 1656 1657 1658 1659 1660 1661
    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()
1662 1663 1664
        np.testing.assert_array_equal(
            pred,
            loaded_pred,
1665 1666 1667 1668
            err_msg='Result diff when load and inference:\nlayer result:\n{}\nloaded layer result:\n{}'.format(
                pred, loaded_pred
            ),
        )
1669 1670 1671 1672

    def test_jit_save_data_parallel_with_inputspec(self):
        layer = LinearNetNotDeclarative(784, 1)
        layer = paddle.DataParallel(layer)
1673 1674 1675 1676 1677 1678
        path = os.path.join(
            self.temp_dir.name, "jit_save_data_parallel_with_inputspec/model"
        )
        paddle.jit.save(
            layer=layer, path=path, input_spec=[InputSpec(shape=[None, 784])]
        )
1679 1680 1681 1682 1683 1684 1685

        self.verify_inference_correctness(layer, path)

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

1686 1687 1688
        path = os.path.join(
            self.temp_dir.name, "jit_save_data_parallel_with_to_static/model"
        )
1689 1690 1691 1692 1693
        paddle.jit.save(layer, path)

        self.verify_inference_correctness(layer, path)


1694 1695 1696 1697 1698
class InputSepcLayer(paddle.nn.Layer):
    '''
    A layer with InputSpec to test InputSpec compatibility
    '''

1699 1700 1701 1702 1703 1704
    @paddle.jit.to_static(
        input_spec=[
            InputSpec(shape=[None, 8], dtype='float32', name='x'),
            InputSpec(shape=[None, 1], dtype='float64', name='y'),
        ]
    )
1705 1706 1707 1708 1709
    def forward(self, x, y):
        return x, y


class TestInputSpecCompatibility(unittest.TestCase):
1710 1711 1712 1713 1714 1715
    def setUp(self):
        self.temp_dir = tempfile.TemporaryDirectory()

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

1716 1717 1718 1719 1720
    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)
1721 1722 1723 1724 1725 1726
        np.testing.assert_allclose(
            expected_result[0].numpy(), test_result[0].numpy()
        )
        np.testing.assert_allclose(
            expected_result[1].numpy(), test_result[1].numpy()
        )
1727 1728 1729

    def test_jit_save_compatible_input_sepc(self):
        layer = InputSepcLayer()
1730 1731 1732
        save_dir = os.path.join(
            self.temp_dir.name, "jit_save_compatible_input_spec"
        )
1733 1734 1735 1736 1737 1738 1739
        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)

1740 1741 1742 1743 1744 1745 1746 1747
        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'),
            ],
        )
1748 1749 1750 1751
        same_input_spec_layer = paddle.jit.load(path)
        self._assert_input_spec_layer_return(layer, same_input_spec_layer)
        shutil.rmtree(save_dir)

1752 1753 1754 1755 1756 1757 1758 1759
        paddle.jit.save(
            layer=layer,
            path=path,
            input_spec=[
                InputSpec(shape=[8, 8], dtype='float32'),
                InputSpec(shape=[8, -1], dtype='float64'),
            ],
        )
1760 1761 1762 1763 1764 1765
        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()
1766 1767 1768
        save_dir = os.path.join(
            self.temp_dir.name, "jit_save_compatible_input_spec"
        )
1769 1770 1771 1772
        path = save_dir + "/model"

        with self.assertRaises(ValueError):
            # type mismatch
1773 1774 1775 1776 1777 1778 1779 1780
            paddle.jit.save(
                layer=layer,
                path=path,
                input_spec=[
                    InputSpec(shape=[None, 8], dtype='float64'),
                    InputSpec(shape=[None, 1], dtype='float64'),
                ],
            )
1781 1782 1783

        with self.assertRaises(ValueError):
            # shape len mismatch
1784 1785 1786 1787 1788 1789 1790 1791
            paddle.jit.save(
                layer=layer,
                path=path,
                input_spec=[
                    InputSpec(shape=[None, 8, 1], dtype='float32'),
                    InputSpec(shape=[None, 1], dtype='float64'),
                ],
            )
1792 1793 1794

        with self.assertRaises(ValueError):
            # shape mismatch
1795 1796 1797 1798 1799 1800 1801 1802
            paddle.jit.save(
                layer=layer,
                path=path,
                input_spec=[
                    InputSpec(shape=[None, 8], dtype='float32'),
                    InputSpec(shape=[None, 2], dtype='float64'),
                ],
            )
1803 1804 1805 1806
        if os.path.exists(save_dir):
            shutil.rmtree(save_dir)


H
Hui Zhang 已提交
1807 1808
class NotJitForward(paddle.nn.Layer):
    def __init__(self):
1809
        super().__init__()
H
Hui Zhang 已提交
1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838

    def forward(self, x, y):
        return x + y


class TestNotJitForward(unittest.TestCase):
    def setUp(self):
        self.temp_dir = tempfile.TemporaryDirectory()

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

    def test_jit_not_save_forward(self):
        layer = NotJitForward()

        save_dir = os.path.join(self.temp_dir.name, "jit_not_save_forward")
        path = save_dir + "/model"

        paddle.jit.save(layer=layer, path=path, skip_forward=True)

        self.assertTrue(not os.path.exists(path + ".pdmodel"))
        self.assertTrue(not os.path.exists(path + ".pdparam"))

        with self.assertRaises(ValueError):
            paddle.jit.load(path=path)

        shutil.rmtree(save_dir)


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