export_model.py 3.6 KB
Newer Older
1
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
W
WuHaobo 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14
#
# 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.

15 16 17
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
littletomatodonkey's avatar
littletomatodonkey 已提交
18 19 20
import os
import sys
__dir__ = os.path.dirname(os.path.abspath(__file__))
21
sys.path.append(os.path.abspath(os.path.join(__dir__, '../')))
W
WuHaobo 已提交
22

23
import paddle
24
import paddle.nn as nn
25

26
from ppcls.utils import config
littletomatodonkey's avatar
littletomatodonkey 已提交
27 28
from ppcls.utils.logger import init_logger
from ppcls.utils.config import print_config
29
from ppcls.arch import build_model, RecModel, DistillationModel
30
from ppcls.utils.save_load import load_dygraph_pretrain
W
weishengyu 已提交
31
from ppcls.arch.gears.identity_head import IdentityHead
W
WuHaobo 已提交
32 33


W
weishengyu 已提交
34
class ExportModel(nn.Layer):
35
    """
36
    ExportModel: add softmax onto the model
37
    """
W
WuHaobo 已提交
38

39 40
    def __init__(self, config):
        super().__init__()
C
cuicheng01 已提交
41
        print (config)
42
        self.base_model = build_model(config)
43 44 45 46 47 48 49 50

        # we should choose a final model to export
        if isinstance(self.base_model, DistillationModel):
            self.infer_model_name = config["infer_model_name"]
        else:
            self.infer_model_name = None

        self.infer_output_key = config.get("infer_output_key", None)
W
weishengyu 已提交
51 52
        if self.infer_output_key == "features" and isinstance(self.base_model,
                                                              RecModel):
W
dbg  
weishengyu 已提交
53
            self.base_model.head = IdentityHead()
W
weishengyu 已提交
54
        if config.get("infer_add_softmax", True):
W
weishengyu 已提交
55 56 57
            self.softmax = nn.Softmax(axis=-1)
        else:
            self.softmax = None
W
WuHaobo 已提交
58

59 60 61 62 63 64
    def eval(self):
        self.training = False
        for layer in self.sublayers():
            layer.training = False
            layer.eval()

65 66
    def forward(self, x):
        x = self.base_model(x)
C
cuicheng01 已提交
67 68
        if isinstance(x, list):
            x = x[0]
69 70
        if self.infer_model_name is not None:
            x = x[self.infer_model_name]
W
weishengyu 已提交
71 72 73 74
        if self.infer_output_key is not None:
            x = x[self.infer_output_key]
        if self.softmax is not None:
            x = self.softmax(x)
75
        return x
W
WuHaobo 已提交
76 77


78 79
if __name__ == "__main__":
    args = config.parse_args()
littletomatodonkey's avatar
littletomatodonkey 已提交
80 81 82 83 84 85 86
    config = config.get_config(
        args.config, overrides=args.override, show=False)
    log_file = os.path.join(config['Global']['output_dir'],
                            config["Arch"]["name"], "export.log")
    init_logger(name='root', log_file=log_file)
    print_config(config)

87 88 89
    # set device
    assert config["Global"]["device"] in ["cpu", "gpu", "xpu"]
    device = paddle.set_device(config["Global"]["device"])
W
weishengyu 已提交
90
    model = ExportModel(config["Arch"])
91 92 93
    if config["Global"]["pretrained_model"] is not None:
        load_dygraph_pretrain(model.base_model,
                              config["Global"]["pretrained_model"])
W
WuHaobo 已提交
94

L
littletomatodonkey 已提交
95
    model.eval()
96

97
    model = paddle.jit.to_static(
98 99 100
        model,
        input_spec=[
            paddle.static.InputSpec(
101 102
                shape=[None] + config["Global"]["image_shape"],
                dtype='float32')
103
        ])
104 105 106
    paddle.jit.save(model,
                    os.path.join(config["Global"]["save_inference_dir"],
                                 "inference"))