export_model.py 2.4 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 28 29
from ppcls.utils import config
from ppcls.engine.trainer import Trainer
from ppcls.arch import build_model
from ppcls.utils.save_load import load_dygraph_pretrain
W
WuHaobo 已提交
30 31


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

37 38 39 40
    def __init__(self, config):
        super().__init__()
        self.base_model = build_model(config)
        self.softmax = nn.Softmax(axis=-1)
W
WuHaobo 已提交
41

42 43 44 45 46 47
    def eval(self):
        self.training = False
        for layer in self.sublayers():
            layer.training = False
            layer.eval()

48 49 50
    def forward(self, x):
        x = self.base_model(x)
        x = self.softmax(x)
51
        return x
W
WuHaobo 已提交
52 53


54 55 56 57 58 59 60 61 62 63 64 65
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"])

    model = ClasModel(config["Arch"])

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

L
littletomatodonkey 已提交
67
    model.eval()
68

69
    model = paddle.jit.to_static(
70 71 72
        model,
        input_spec=[
            paddle.static.InputSpec(
73 74
                shape=[None] + config["Global"]["image_shape"],
                dtype='float32')
75
        ])
76 77 78
    paddle.jit.save(model,
                    os.path.join(config["Global"]["save_inference_dir"],
                                 "inference"))