test_inference_model_io.py 5.0 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2
#
D
dzhwinter 已提交
3 4 5
# 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
D
dzhwinter 已提交
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8
#
D
dzhwinter 已提交
9 10 11 12 13 14
# 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.

15 16
from __future__ import print_function

D
dzhwinter 已提交
17 18
import unittest

M
minqiyang 已提交
19
import six
D
dzhwinter 已提交
20
import numpy as np
21
import paddle.fluid.core as core
22

23 24 25
import paddle.fluid.executor as executor
import paddle.fluid.layers as layers
import paddle.fluid.optimizer as optimizer
T
tangwei12 已提交
26
from paddle.fluid.compiler import CompiledProgram
27 28
from paddle.fluid.framework import Program, program_guard
from paddle.fluid.io import save_inference_model, load_inference_model
D
dzhwinter 已提交
29
from paddle.fluid.transpiler import memory_optimize
30 31 32 33 34 35 36 37


class TestBook(unittest.TestCase):
    def test_fit_line_inference_model(self):
        MODEL_DIR = "./tmp/inference_model"

        init_program = Program()
        program = Program()
38 39 40 41 42 43 44 45

        with program_guard(program, init_program):
            x = layers.data(name='x', shape=[2], dtype='float32')
            y = layers.data(name='y', shape=[1], dtype='float32')

            y_predict = layers.fc(input=x, size=1, act=None)

            cost = layers.square_error_cost(input=y_predict, label=y)
Y
Yu Yang 已提交
46
            avg_cost = layers.mean(cost)
47 48 49

            sgd_optimizer = optimizer.SGDOptimizer(learning_rate=0.001)
            sgd_optimizer.minimize(avg_cost, init_program)
50 51 52 53 54 55

        place = core.CPUPlace()
        exe = executor.Executor(place)

        exe.run(init_program, feed={}, fetch_list=[])

M
minqiyang 已提交
56
        for i in six.moves.xrange(100):
D
dzhwinter 已提交
57
            tensor_x = np.array(
58
                [[1, 1], [1, 2], [3, 4], [5, 2]]).astype("float32")
D
dzhwinter 已提交
59
            tensor_y = np.array([[-2], [-3], [-7], [-7]]).astype("float32")
60 61 62 63 64 65 66

            exe.run(program,
                    feed={'x': tensor_x,
                          'y': tensor_y},
                    fetch_list=[avg_cost])

        save_inference_model(MODEL_DIR, ["x", "y"], [avg_cost], exe, program)
D
dzhwinter 已提交
67 68 69 70
        expected = exe.run(program,
                           feed={'x': tensor_x,
                                 'y': tensor_y},
                           fetch_list=[avg_cost])[0]
71

M
minqiyang 已提交
72
        six.moves.reload_module(executor)  # reload to build a new scope
73 74 75 76 77 78 79 80 81 82
        exe = executor.Executor(place)

        [infer_prog, feed_var_names, fetch_vars] = load_inference_model(
            MODEL_DIR, exe)

        outs = exe.run(
            infer_prog,
            feed={feed_var_names[0]: tensor_x,
                  feed_var_names[1]: tensor_y},
            fetch_list=fetch_vars)
D
dzhwinter 已提交
83
        actual = outs[0]
84 85 86

        self.assertEqual(feed_var_names, ["x", "y"])
        self.assertEqual(len(fetch_vars), 1)
87 88
        print("fetch %s" % str(fetch_vars[0]))
        self.assertTrue("scale" in str(fetch_vars[0]))
89 90 91
        self.assertEqual(expected, actual)


D
dzhwinter 已提交
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
class TestSaveInferenceModel(unittest.TestCase):
    def test_save_inference_model(self):
        MODEL_DIR = "./tmp/inference_model2"
        init_program = Program()
        program = Program()

        # fake program without feed/fetch
        with program_guard(program, init_program):
            x = layers.data(name='x', shape=[2], dtype='float32')
            y = layers.data(name='y', shape=[1], dtype='float32')

            y_predict = layers.fc(input=x, size=1, act=None)

            cost = layers.square_error_cost(input=y_predict, label=y)
            avg_cost = layers.mean(cost)

        place = core.CPUPlace()
        exe = executor.Executor(place)
        exe.run(init_program, feed={}, fetch_list=[])

D
dzhwinter 已提交
112
        save_inference_model(MODEL_DIR, ["x", "y"], [avg_cost], exe, program)
D
dzhwinter 已提交
113 114


T
tangwei12 已提交
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
class TestInstance(unittest.TestCase):
    def test_save_inference_model(self):
        MODEL_DIR = "./tmp/inference_model3"
        init_program = Program()
        program = Program()

        # fake program without feed/fetch
        with program_guard(program, init_program):
            x = layers.data(name='x', shape=[2], dtype='float32')
            y = layers.data(name='y', shape=[1], dtype='float32')

            y_predict = layers.fc(input=x, size=1, act=None)

            cost = layers.square_error_cost(input=y_predict, label=y)
            avg_cost = layers.mean(cost)

        place = core.CPUPlace()
        exe = executor.Executor(place)
        exe.run(init_program, feed={}, fetch_list=[])

        # will print warning message

        cp_prog = CompiledProgram(program).with_data_parallel(
            loss_name=avg_cost.name)

C
chengduo 已提交
140
        save_inference_model(MODEL_DIR, ["x", "y"], [avg_cost], exe, cp_prog)
T
tangwei12 已提交
141 142 143 144
        self.assertRaises(TypeError, save_inference_model,
                          [MODEL_DIR, ["x", "y"], [avg_cost], [], cp_prog])


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