export_model.py 2.9 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
W
weishengyu 已提交
27
from ppcls.arch import build_model, RecModel
28
from ppcls.utils.save_load import load_dygraph_pretrain
W
weishengyu 已提交
29
from ppcls.arch.gears.identity_head import IdentityHead
W
WuHaobo 已提交
30 31


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

37 38 39
    def __init__(self, config):
        super().__init__()
        self.base_model = build_model(config)
W
weishengyu 已提交
40
        self.infer_output_key = config.get("infer_output_key")
W
weishengyu 已提交
41 42
        if self.infer_output_key == "features" and isinstance(self.base_model,
                                                              RecModel):
W
dbg  
weishengyu 已提交
43
            self.base_model.head = IdentityHead()
W
weishengyu 已提交
44
        if config.get("infer_add_softmax", True):
W
weishengyu 已提交
45 46 47
            self.softmax = nn.Softmax(axis=-1)
        else:
            self.softmax = None
W
WuHaobo 已提交
48

49 50 51 52 53 54
    def eval(self):
        self.training = False
        for layer in self.sublayers():
            layer.training = False
            layer.eval()

55 56
    def forward(self, x):
        x = self.base_model(x)
W
weishengyu 已提交
57 58 59 60
        if self.infer_output_key is not None:
            x = x[self.infer_output_key]
        if self.softmax is not None:
            x = self.softmax(x)
61
        return x
W
WuHaobo 已提交
62 63


64 65 66 67 68 69
if __name__ == "__main__":
    args = config.parse_args()
    config = config.get_config(args.config, overrides=args.override, show=True)
    # set device
    assert config["Global"]["device"] in ["cpu", "gpu", "xpu"]
    device = paddle.set_device(config["Global"]["device"])
W
weishengyu 已提交
70
    model = ExportModel(config["Arch"])
71 72 73 74

    if config["Global"]["pretrained_model"] is not None:
        load_dygraph_pretrain(model.base_model,
                              config["Global"]["pretrained_model"])
W
WuHaobo 已提交
75

L
littletomatodonkey 已提交
76
    model.eval()
77

78
    model = paddle.jit.to_static(
79 80 81
        model,
        input_spec=[
            paddle.static.InputSpec(
82 83
                shape=[None] + config["Global"]["image_shape"],
                dtype='float32')
84
        ])
85 86 87
    paddle.jit.save(model,
                    os.path.join(config["Global"]["save_inference_dir"],
                                 "inference"))