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 27
from ppcls.utils import config
from ppcls.engine.trainer import Trainer
W
weishengyu 已提交
28 29
from ppcls.arch import build_model, RecModel
from ppcls.arch.backbone.base.theseus_layer import Identity
30
from ppcls.utils.save_load import load_dygraph_pretrain
W
WuHaobo 已提交
31 32


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

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

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

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


65 66 67 68 69 70
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 已提交
71
    model = ExportModel(config["Arch"])
72 73 74 75

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

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

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