save_load.py 5.4 KB
Newer Older
W
WuHaobo 已提交
1 2
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
W
WuHaobo 已提交
3 4 5
# 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
W
WuHaobo 已提交
6 7 8
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
W
WuHaobo 已提交
9 10 11 12 13
# 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.
W
WuHaobo 已提交
14 15 16 17 18

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

W
WuHaobo 已提交
19
import errno
W
WuHaobo 已提交
20
import os
W
WuHaobo 已提交
21
import re
W
WuHaobo 已提交
22
import shutil
W
WuHaobo 已提交
23
import tempfile
W
WuHaobo 已提交
24

25
import paddle
W
WuHaobo 已提交
26
from ppcls.utils import logger
27
from .download import get_weights_path_from_url
W
WuHaobo 已提交
28

29
__all__ = ['init_model', 'save_model', 'load_dygraph_pretrain']
W
WuHaobo 已提交
30 31 32 33


def _mkdir_if_not_exist(path):
    """
W
WuHaobo 已提交
34
    mkdir if not exists, ignore the exception when multiprocess mkdir together
W
WuHaobo 已提交
35
    """
W
WuHaobo 已提交
36 37 38 39 40 41 42 43 44
    if not os.path.exists(path):
        try:
            os.makedirs(path)
        except OSError as e:
            if e.errno == errno.EEXIST and os.path.isdir(path):
                logger.warning(
                    'be happy if some process has already created {}'.format(
                        path))
            else:
W
WuHaobo 已提交
45
                raise OSError('Failed to mkdir {}'.format(path))
W
WuHaobo 已提交
46 47


48
def load_dygraph_pretrain(model, path=None):
W
WuHaobo 已提交
49 50 51
    if not (os.path.isdir(path) or os.path.exists(path + '.pdparams')):
        raise ValueError("Model pretrain path {} does not "
                         "exists.".format(path))
52
    param_state_dict = paddle.load(path + ".pdparams")
53 54
    model.set_dict(param_state_dict)
    return
W
WuHaobo 已提交
55 56


57
def load_dygraph_pretrain_from_url(model, pretrained_url, use_ssld):
58
    if use_ssld:
59 60 61 62
        pretrained_url = pretrained_url.replace("_pretrained",
                                                "_ssld_pretrained")
    local_weight_path = get_weights_path_from_url(pretrained_url).replace(
        ".pdparams", "")
63
    load_dygraph_pretrain(model, path=local_weight_path)
64 65 66
    return


67
def load_distillation_model(model, pretrained_model):
littletomatodonkey's avatar
littletomatodonkey 已提交
68
    logger.info("In distillation mode, teacher model will be "
littletomatodonkey's avatar
littletomatodonkey 已提交
69
                "loaded firstly before student model.")
70 71 72 73

    if not isinstance(pretrained_model, list):
        pretrained_model = [pretrained_model]

74 75 76 77
    teacher = model.teacher if hasattr(model,
                                       "teacher") else model._layers.teacher
    student = model.student if hasattr(model,
                                       "student") else model._layers.student
78
    load_dygraph_pretrain(teacher, path=pretrained_model[0])
79 80 81 82
    logger.info("Finish initing teacher model from {}".format(
        pretrained_model))
    # load student model
    if len(pretrained_model) >= 2:
83
        load_dygraph_pretrain(student, path=pretrained_model[1])
84 85
        logger.info("Finish initing student model from {}".format(
            pretrained_model))
littletomatodonkey's avatar
littletomatodonkey 已提交
86

littletomatodonkey's avatar
littletomatodonkey 已提交
87

88
def init_model(config, net, optimizer=None):
W
WuHaobo 已提交
89
    """
W
WuHaobo 已提交
90
    load model from checkpoint or pretrained_model
W
WuHaobo 已提交
91 92
    """
    checkpoints = config.get('checkpoints')
L
littletomatodonkey 已提交
93
    if checkpoints and optimizer is not None:
W
WuHaobo 已提交
94 95 96 97
        assert os.path.exists(checkpoints + ".pdparams"), \
            "Given dir {}.pdparams not exist.".format(checkpoints)
        assert os.path.exists(checkpoints + ".pdopt"), \
            "Given dir {}.pdopt not exist.".format(checkpoints)
98 99
        para_dict = paddle.load(checkpoints + ".pdparams")
        opti_dict = paddle.load(checkpoints + ".pdopt")
100
        metric_dict = paddle.load(checkpoints + ".pdstates")
W
WuHaobo 已提交
101
        net.set_dict(para_dict)
littletomatodonkey's avatar
littletomatodonkey 已提交
102
        optimizer.set_state_dict(opti_dict)
L
littletomatodonkey 已提交
103
        logger.info("Finish load checkpoints from {}".format(checkpoints))
104
        return metric_dict
W
WuHaobo 已提交
105 106

    pretrained_model = config.get('pretrained_model')
107
    use_distillation = config.get('use_distillation', False)
W
WuHaobo 已提交
108
    if pretrained_model:
109
        if use_distillation:
110
            load_distillation_model(net, pretrained_model)
littletomatodonkey's avatar
littletomatodonkey 已提交
111
        else:  # common load
112
            load_dygraph_pretrain(net, path=pretrained_model)
113
            logger.info(
L
littletomatodonkey 已提交
114
                logger.coloring("Finish load pretrained model from {}".format(
115
                    pretrained_model), "HEADER"))
W
WuHaobo 已提交
116 117


118 119 120 121 122 123 124 125 126 127 128 129 130
def _save_student_model(net, model_prefix):
    """
    save student model if the net is the network contains student
    """
    student_model_prefix = model_prefix + "_student.pdparams"
    if hasattr(net, "_layers"):
        net = net._layers
    if hasattr(net, "student"):
        paddle.save(net.student.state_dict(), student_model_prefix)
        logger.info("Already save student model in {}".format(
            student_model_prefix))


131 132 133 134 135 136
def save_model(net,
               optimizer,
               metric_info,
               model_path,
               model_name="",
               prefix='ppcls'):
W
WuHaobo 已提交
137
    """
W
WuHaobo 已提交
138
    save model to the target path
W
WuHaobo 已提交
139
    """
140 141
    if paddle.distributed.get_rank() != 0:
        return
L
littletomatodonkey 已提交
142
    model_path = os.path.join(model_path, model_name)
W
WuHaobo 已提交
143 144
    _mkdir_if_not_exist(model_path)
    model_prefix = os.path.join(model_path, prefix)
W
WuHaobo 已提交
145

146 147
    _save_student_model(net, model_prefix)

148 149
    paddle.save(net.state_dict(), model_prefix + ".pdparams")
    paddle.save(optimizer.state_dict(), model_prefix + ".pdopt")
150
    paddle.save(metric_info, model_prefix + ".pdstates")
151
    logger.info("Already save model in {}".format(model_path))