__init__.py 8.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
#   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.
B
barrierye 已提交
14
# pylint: disable=doc-string-missing
15 16 17

from paddle.fluid import Executor
from paddle.fluid.compiler import CompiledProgram
18
from paddle.fluid.framework import core
G
guru4elephant 已提交
19
from paddle.fluid.framework import default_main_program
20
from paddle.fluid.framework import Program
G
guru4elephant 已提交
21
from paddle.fluid import CPUPlace
22
from paddle.fluid.io import save_inference_model
23
import paddle.fluid as fluid
24
from ..proto import general_model_config_pb2 as model_conf
G
guru4elephant 已提交
25
import os
W
wangjiawei04 已提交
26 27 28
import paddle
import paddle.nn.functional as F
from paddle.jit import to_static
29

W
wangjiawei04 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
def save_dygraph_model(serving_model_folder, client_config_folder, model):
    paddle.jit.save(model, "serving_tmp")
    loaded_layer = paddle.jit.load(path=".", model_filename="serving_tmp.pdmodel", params_filename="serving_tmp.pdiparams")
    feed_target_names = [x.name for x in loaded_layer._input_spec()]
    fetch_target_names = [x.name for x in loaded_layer._output_spec()]

    inference_program = loaded_layer.program()
    feed_var_dict = {
           x: inference_program.global_block().var(x)
           for x in feed_target_names
    }
    fetch_var_dict = {
           x: inference_program.global_block().var(x)
           for x in fetch_target_names
    }
    config = model_conf.GeneralModelConfig()

    #int64 = 0; float32 = 1; int32 = 2;
    for key in feed_var_dict:
        feed_var = model_conf.FeedVar()
        feed_var.alias_name = key
        feed_var.name = feed_var_dict[key].name
        feed_var.is_lod_tensor = feed_var_dict[key].lod_level >= 1
        if feed_var_dict[key].dtype == core.VarDesc.VarType.INT64:
            feed_var.feed_type = 0
        if feed_var_dict[key].dtype == core.VarDesc.VarType.FP32:
            feed_var.feed_type = 1
        if feed_var_dict[key].dtype == core.VarDesc.VarType.INT32:
            feed_var.feed_type = 2
        if feed_var.is_lod_tensor:
            feed_var.shape.extend([-1])
        else:
            tmp_shape = []
            for v in feed_var_dict[key].shape:
                if v >= 0:
                    tmp_shape.append(v)
            feed_var.shape.extend(tmp_shape)
        config.feed_var.extend([feed_var])
    for key in fetch_var_dict:
        fetch_var = model_conf.FetchVar()
        fetch_var.alias_name = key
        fetch_var.name = fetch_var_dict[key].name
        fetch_var.is_lod_tensor = 1
        if fetch_var_dict[key].dtype == core.VarDesc.VarType.INT64:
            fetch_var.fetch_type = 0
        if fetch_var_dict[key].dtype == core.VarDesc.VarType.FP32:
            fetch_var.fetch_type = 1
        if fetch_var_dict[key].dtype == core.VarDesc.VarType.INT32:
            fetch_var.fetch_type = 2
        if fetch_var.is_lod_tensor:
            fetch_var.shape.extend([-1])
        else:
            tmp_shape = []
            for v in fetch_var_dict[key].shape:
                if v >= 0:
                    tmp_shape.append(v)
            fetch_var.shape.extend(tmp_shape)
        config.fetch_var.extend([fetch_var])
    cmd = "mkdir -p {}".format(client_config_folder)
    os.system(cmd)
    cmd = "mkdir -p {}".format(serving_model_folder)
    os.system(cmd)
    cmd = "mv {} {}/__model__".format("serving_tmp.pdmodel", serving_model_folder)
    os.system(cmd)
    cmd = "mv {} {}/__params__".format("serving_tmp.pdiparams", serving_model_folder)
    os.system(cmd)
    cmd = "rm -rf serving_tmp.pd*"
    os.system(cmd)
    with open("{}/serving_client_conf.prototxt".format(client_config_folder),
              "w") as fout:
        fout.write(str(config))
    with open("{}/serving_server_conf.prototxt".format(serving_model_folder),
              "w") as fout:
        fout.write(str(config))
    with open("{}/serving_client_conf.stream.prototxt".format(
            client_config_folder), "wb") as fout:
        fout.write(config.SerializeToString())
    with open("{}/serving_server_conf.stream.prototxt".format(
            serving_model_folder), "wb") as fout:
        fout.write(config.SerializeToString())
B
barrierye 已提交
110

111 112 113 114
def save_model(server_model_folder,
               client_config_folder,
               feed_var_dict,
               fetch_var_dict,
115
               main_program=None):
G
guru4elephant 已提交
116 117
    executor = Executor(place=CPUPlace())

118
    feed_var_names = [feed_var_dict[x].name for x in feed_var_dict]
M
MRXLT 已提交
119 120 121 122 123
    target_vars = []
    target_var_names = []
    for key in sorted(fetch_var_dict.keys()):
        target_vars.append(fetch_var_dict[key])
        target_var_names.append(key)
124 125 126 127 128 129

    save_inference_model(
        server_model_folder,
        feed_var_names,
        target_vars,
        executor,
W
wangjiawei04 已提交
130 131
        model_filename="__model__",
        params_filename="__params__",
132 133
        main_program=main_program)

134 135
    config = model_conf.GeneralModelConfig()

M
MRXLT 已提交
136
    #int64 = 0; float32 = 1; int32 = 2;
137 138 139 140
    for key in feed_var_dict:
        feed_var = model_conf.FeedVar()
        feed_var.alias_name = key
        feed_var.name = feed_var_dict[key].name
141
        feed_var.is_lod_tensor = feed_var_dict[key].lod_level >= 1
M
MRXLT 已提交
142
        if feed_var_dict[key].dtype == core.VarDesc.VarType.INT64:
143 144 145
            feed_var.feed_type = 0
        if feed_var_dict[key].dtype == core.VarDesc.VarType.FP32:
            feed_var.feed_type = 1
M
MRXLT 已提交
146 147
        if feed_var_dict[key].dtype == core.VarDesc.VarType.INT32:
            feed_var.feed_type = 2
148 149 150 151 152 153 154 155 156 157
        if feed_var.is_lod_tensor:
            feed_var.shape.extend([-1])
        else:
            tmp_shape = []
            for v in feed_var_dict[key].shape:
                if v >= 0:
                    tmp_shape.append(v)
            feed_var.shape.extend(tmp_shape)
        config.feed_var.extend([feed_var])

M
MRXLT 已提交
158
    for key in target_var_names:
159 160 161
        fetch_var = model_conf.FetchVar()
        fetch_var.alias_name = key
        fetch_var.name = fetch_var_dict[key].name
W
wangjiawei04 已提交
162 163
        #fetch_var.is_lod_tensor = fetch_var_dict[key].lod_level >= 1
        fetch_var.is_lod_tensor = 1
M
MRXLT 已提交
164
        if fetch_var_dict[key].dtype == core.VarDesc.VarType.INT64:
165 166
            fetch_var.fetch_type = 0
        if fetch_var_dict[key].dtype == core.VarDesc.VarType.FP32:
B
barrierye 已提交
167
            fetch_var.fetch_type = 1
M
MRXLT 已提交
168 169
        if fetch_var_dict[key].dtype == core.VarDesc.VarType.INT32:
            fetch_var.fetch_type = 2
G
guru4elephant 已提交
170
        if fetch_var.is_lod_tensor:
171 172 173 174 175 176 177
            fetch_var.shape.extend([-1])
        else:
            tmp_shape = []
            for v in fetch_var_dict[key].shape:
                if v >= 0:
                    tmp_shape.append(v)
            fetch_var.shape.extend(tmp_shape)
178 179
        config.fetch_var.extend([fetch_var])

S
shaohua.zhang 已提交
180 181 182 183 184 185
    try:
        save_dirname = os.path.normpath(client_config_folder)
        os.makedirs(save_dirname)
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise
B
barrierye 已提交
186 187
    with open("{}/serving_client_conf.prototxt".format(client_config_folder),
              "w") as fout:
188
        fout.write(str(config))
B
barrierye 已提交
189 190
    with open("{}/serving_server_conf.prototxt".format(server_model_folder),
              "w") as fout:
191
        fout.write(str(config))
B
barrierye 已提交
192 193
    with open("{}/serving_client_conf.stream.prototxt".format(
            client_config_folder), "wb") as fout:
G
guru4elephant 已提交
194
        fout.write(config.SerializeToString())
B
barrierye 已提交
195 196
    with open("{}/serving_server_conf.stream.prototxt".format(
            server_model_folder), "wb") as fout:
G
guru4elephant 已提交
197
        fout.write(config.SerializeToString())
198 199


M
MRXLT 已提交
200 201
def inference_model_to_serving(dirname,
                               serving_server="serving_server",
M
MRXLT 已提交
202 203
                               serving_client="serving_client",
                               model_filename=None,
204
                               params_filename=None):
205 206 207
    place = fluid.CPUPlace()
    exe = fluid.Executor(place)
    inference_program, feed_target_names, fetch_targets = \
M
MRXLT 已提交
208
            fluid.io.load_inference_model(dirname=dirname, executor=exe, model_filename=model_filename, params_filename=params_filename)
209 210 211 212 213
    feed_dict = {
        x: inference_program.global_block().var(x)
        for x in feed_target_names
    }
    fetch_dict = {x.name: x for x in fetch_targets}
M
MRXLT 已提交
214
    save_model(serving_server, serving_client, feed_dict, fetch_dict,
215
               inference_program)
216 217 218
    feed_names = feed_dict.keys()
    fetch_names = fetch_dict.keys()
    return feed_names, fetch_names