test_inference_model_io.py 14.4 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

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

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


37 38 39 40 41 42
class InferModel(object):
    def __init__(self, list):
        self.program = list[0]
        self.feed_var_names = list[1]
        self.fetch_vars = list[2]

43

44
class TestBook(unittest.TestCase):
45 46
    def test_fit_line_inference_model(self):
        MODEL_DIR = "./tmp/inference_model"
47
        UNI_MODEL_DIR = "./tmp/inference_model1"
48 49 50

        init_program = Program()
        program = Program()
51 52 53 54 55 56 57 58

        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 已提交
59
            avg_cost = layers.mean(cost)
60 61 62

            sgd_optimizer = optimizer.SGDOptimizer(learning_rate=0.001)
            sgd_optimizer.minimize(avg_cost, init_program)
63 64 65 66 67 68

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

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

M
minqiyang 已提交
69
        for i in six.moves.xrange(100):
D
dzhwinter 已提交
70
            tensor_x = np.array(
71
                [[1, 1], [1, 2], [3, 4], [5, 2]]).astype("float32")
D
dzhwinter 已提交
72
            tensor_y = np.array([[-2], [-3], [-7], [-7]]).astype("float32")
73 74 75 76 77 78

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

79
        # Separated model and unified model
80
        save_inference_model(MODEL_DIR, ["x", "y"], [avg_cost], exe, program)
81 82 83 84 85 86
        save_inference_model(UNI_MODEL_DIR, ["x", "y"], [avg_cost], exe,
                             program, 'model', 'params')
        main_program = program.clone()._prune_with_input(
            feeded_var_names=["x", "y"], targets=[avg_cost])
        params_str = save_persistables(exe, None, main_program, None)

D
dzhwinter 已提交
87 88 89 90
        expected = exe.run(program,
                           feed={'x': tensor_x,
                                 'y': tensor_y},
                           fetch_list=[avg_cost])[0]
91

M
minqiyang 已提交
92
        six.moves.reload_module(executor)  # reload to build a new scope
93

94
        model_0 = InferModel(load_inference_model(MODEL_DIR, exe))
95 96
        with open(os.path.join(UNI_MODEL_DIR, 'model'), "rb") as f:
            model_str = f.read()
97
        model_1 = InferModel(
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
            load_inference_model(None, exe, model_str, params_str))

        for model in [model_0, model_1]:
            outs = exe.run(model.program,
                           feed={
                               model.feed_var_names[0]: tensor_x,
                               model.feed_var_names[1]: tensor_y
                           },
                           fetch_list=model.fetch_vars)
            actual = outs[0]

            self.assertEqual(model.feed_var_names, ["x", "y"])
            self.assertEqual(len(model.fetch_vars), 1)
            print("fetch %s" % str(model.fetch_vars[0]))
            self.assertEqual(expected, actual)

        self.assertRaises(ValueError, fluid.io.load_inference_model, None, exe,
                          model_str, None)
116 117


D
dzhwinter 已提交
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
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 已提交
138
        save_inference_model(MODEL_DIR, ["x", "y"], [avg_cost], exe, program)
D
dzhwinter 已提交
139

140 141 142 143 144 145 146 147
    def test_save_inference_model_with_auc(self):
        MODEL_DIR = "./tmp/inference_model4"
        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')
148
            y = layers.data(name='y', shape=[1], dtype='int32')
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
            predict = fluid.layers.fc(input=x, size=2, act='softmax')
            acc = fluid.layers.accuracy(input=predict, label=y)
            auc_var, batch_auc_var, auc_states = fluid.layers.auc(input=predict,
                                                                  label=y)
            cost = fluid.layers.cross_entropy(input=predict, label=y)
            avg_cost = fluid.layers.mean(x=cost)

        place = core.CPUPlace()
        exe = executor.Executor(place)
        exe.run(init_program, feed={}, fetch_list=[])
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            save_inference_model(MODEL_DIR, ["x", "y"], [avg_cost], exe,
                                 program)
            expected_warn = "please ensure that you have set the auc states to zeros before saving inference model"
            self.assertTrue(len(w) > 0)
            self.assertTrue(expected_warn == str(w[0].message))

D
dzhwinter 已提交
167

T
tangwei12 已提交
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
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 已提交
193
        save_inference_model(MODEL_DIR, ["x", "y"], [avg_cost], exe, cp_prog)
T
tangwei12 已提交
194 195 196 197
        self.assertRaises(TypeError, save_inference_model,
                          [MODEL_DIR, ["x", "y"], [avg_cost], [], cp_prog])


198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
class TestSaveInferenceModelNew(unittest.TestCase):
    def test_save_and_load_inference_model(self):
        MODEL_DIR = "./tmp/inference_model5"
        init_program = fluid.default_startup_program()
        program = fluid.default_main_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)

            sgd_optimizer = optimizer.SGDOptimizer(learning_rate=0.001)
            sgd_optimizer.minimize(avg_cost, init_program)

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

        tensor_x = np.array([[1, 1], [1, 2], [5, 2]]).astype("float32")
        tensor_y = np.array([[-2], [-3], [-7]]).astype("float32")
        for i in six.moves.xrange(3):
            exe.run(program,
                    feed={'x': tensor_x,
                          'y': tensor_y},
                    fetch_list=[avg_cost])

229 230
        self.assertRaises(ValueError, paddle.static.save_inference_model, None,
                          ['x', 'y'], [avg_cost], exe)
231
        self.assertRaises(ValueError, paddle.static.save_inference_model,
232
                          MODEL_DIR + "/", [x, y], [avg_cost], exe)
233
        self.assertRaises(ValueError, paddle.static.save_inference_model,
234
                          MODEL_DIR, ['x', 'y'], [avg_cost], exe)
235
        self.assertRaises(ValueError, paddle.static.save_inference_model,
236
                          MODEL_DIR, 'x', [avg_cost], exe)
237
        self.assertRaises(ValueError, paddle.static.save_inference_model,
238
                          MODEL_DIR, [x, y], ['avg_cost'], exe)
239
        self.assertRaises(ValueError, paddle.static.save_inference_model,
240
                          MODEL_DIR, [x, y], 'avg_cost', exe)
241 242 243 244

        model_path = MODEL_DIR + "_isdir.pdmodel"
        os.makedirs(model_path)
        self.assertRaises(ValueError, paddle.static.save_inference_model,
245
                          MODEL_DIR + "_isdir", [x, y], [avg_cost], exe)
246 247 248 249 250
        os.rmdir(model_path)

        params_path = MODEL_DIR + "_isdir.pdmodel"
        os.makedirs(params_path)
        self.assertRaises(ValueError, paddle.static.save_inference_model,
251
                          MODEL_DIR + "_isdir", [x, y], [avg_cost], exe)
252 253
        os.rmdir(params_path)

254 255
        paddle.static.io.save_inference_model(MODEL_DIR, [x, y], [avg_cost],
                                              exe)
256 257 258 259 260 261 262 263 264 265 266

        self.assertTrue(os.path.exists(MODEL_DIR + ".pdmodel"))
        self.assertTrue(os.path.exists(MODEL_DIR + ".pdiparams"))

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

        six.moves.reload_module(executor)  # reload to build a new scope

267 268
        self.assertRaises(ValueError, paddle.static.load_inference_model, None,
                          exe)
269
        self.assertRaises(ValueError, paddle.static.load_inference_model,
270
                          MODEL_DIR + "/", exe)
271
        self.assertRaises(ValueError, paddle.static.load_inference_model,
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
                          [MODEL_DIR], exe)
        self.assertRaises(
            ValueError,
            paddle.static.load_inference_model,
            MODEL_DIR,
            exe,
            pserver_endpoints=None)
        self.assertRaises(
            ValueError,
            paddle.static.load_inference_model,
            MODEL_DIR,
            exe,
            unsupported_param=None)
        self.assertRaises(
            (TypeError, ValueError),
            paddle.static.load_inference_model,
            None,
            exe,
            model_filename="illegal",
            params_filename="illegal")

        model = InferModel(
            paddle.static.io.load_inference_model(MODEL_DIR, exe))
295 296 297 298 299 300 301 302 303 304 305 306

        outs = exe.run(model.program,
                       feed={
                           model.feed_var_names[0]: tensor_x,
                           model.feed_var_names[1]: tensor_y
                       },
                       fetch_list=model.fetch_vars)
        actual = outs[0]

        self.assertEqual(model.feed_var_names, ["x", "y"])
        self.assertEqual(len(model.fetch_vars), 1)
        self.assertEqual(expected, actual)
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
        # test save_to_file content type should be bytes
        self.assertRaises(ValueError, paddle.static.io.save_to_file, '', 123)
        # test _get_valid_program
        self.assertRaises(TypeError, paddle.static.io._get_valid_program, 0)
        p = Program()
        cp = CompiledProgram(p)
        paddle.static.io._get_valid_program(cp)
        self.assertTrue(paddle.static.io._get_valid_program(cp) is p)
        cp._program = None
        self.assertRaises(TypeError, paddle.static.io._get_valid_program, cp)

    def test_serialize_program_and_persistables(self):
        init_program = fluid.default_startup_program()
        program = fluid.default_main_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)

            sgd_optimizer = optimizer.SGDOptimizer(learning_rate=0.001)
            sgd_optimizer.minimize(avg_cost, init_program)

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

        tensor_x = np.array([[1, 1], [1, 2], [5, 2]]).astype("float32")
        tensor_y = np.array([[-2], [-3], [-7]]).astype("float32")
        for i in six.moves.xrange(3):
            exe.run(program,
                    feed={'x': tensor_x,
                          'y': tensor_y},
                    fetch_list=[avg_cost])
346

347 348 349 350 351 352 353 354 355 356 357
        # test if return type of serialize_program is bytes
        res1 = paddle.static.io.serialize_program([x, y], [avg_cost])
        self.assertTrue(isinstance(res1, bytes))
        # test if return type of serialize_persistables is bytes
        res2 = paddle.static.io.serialize_persistables([x, y], [avg_cost], exe)
        self.assertTrue(isinstance(res2, bytes))
        # test if variables in program is empty
        res = paddle.static.io._serialize_persistables(Program(), None)
        self.assertEqual(res, None)
        self.assertRaises(TypeError, paddle.static.io.deserialize_persistables,
                          None, None, None)
358 359


360 361 362 363 364 365 366 367
class TestLoadInferenceModelError(unittest.TestCase):
    def test_load_model_not_exist(self):
        place = core.CPUPlace()
        exe = executor.Executor(place)
        self.assertRaises(ValueError, load_inference_model,
                          './test_not_exist_dir', exe)


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