save_load.py 7.1 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 21
import os

22
import paddle
R
root 已提交
23
from . import logger
24
from .download import get_weights_path_from_url
W
WuHaobo 已提交
25

26
__all__ = ['init_model', 'save_model', 'load_dygraph_pretrain']
W
WuHaobo 已提交
27 28 29 30


def _mkdir_if_not_exist(path):
    """
W
WuHaobo 已提交
31
    mkdir if not exists, ignore the exception when multiprocess mkdir together
W
WuHaobo 已提交
32
    """
W
WuHaobo 已提交
33 34 35 36 37 38 39 40 41
    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 已提交
42
                raise OSError('Failed to mkdir {}'.format(path))
W
WuHaobo 已提交
43 44


littletomatodonkey's avatar
littletomatodonkey 已提交
45 46 47 48 49 50 51 52
def _extract_student_weights(all_params, student_prefix="Student."):
    s_params = {
        key[len(student_prefix):]: all_params[key]
        for key in all_params if student_prefix in key
    }
    return s_params


53
def load_dygraph_pretrain(model, path=None):
W
WuHaobo 已提交
54
    if not (os.path.isdir(path) or os.path.exists(path + '.pdparams')):
55
        raise ValueError("Model pretrain path {}.pdparams does not "
W
WuHaobo 已提交
56
                         "exists.".format(path))
57
    param_state_dict = paddle.load(path + ".pdparams")
58 59
    if isinstance(model, list):
        for m in model:
60 61
            if hasattr(m, 'set_dict'):
                m.set_dict(param_state_dict)
62 63
    else:
        model.set_dict(param_state_dict)
64
    return
W
WuHaobo 已提交
65 66


weixin_46524038's avatar
weixin_46524038 已提交
67 68 69 70 71
def load_dygraph_pretrain_from_url(model,
                                   pretrained_url,
                                   use_ssld=False,
                                   use_imagenet22k_pretrained=False,
                                   use_imagenet22kto1k_pretrained=False):
72
    if use_ssld:
73 74
        pretrained_url = pretrained_url.replace("_pretrained",
                                                "_ssld_pretrained")
weixin_46524038's avatar
weixin_46524038 已提交
75 76 77 78 79 80
    if use_imagenet22k_pretrained:
        pretrained_url = pretrained_url.replace("_pretrained",
                                                "_22k_pretrained")
    if use_imagenet22kto1k_pretrained:
        pretrained_url = pretrained_url.replace("_pretrained",
                                                "_22kto1k_pretrained")
81 82
    local_weight_path = get_weights_path_from_url(pretrained_url).replace(
        ".pdparams", "")
83
    load_dygraph_pretrain(model, path=local_weight_path)
84 85 86
    return


87
def load_distillation_model(model, pretrained_model):
littletomatodonkey's avatar
littletomatodonkey 已提交
88
    logger.info("In distillation mode, teacher model will be "
littletomatodonkey's avatar
littletomatodonkey 已提交
89
                "loaded firstly before student model.")
90 91 92 93

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

94 95 96 97
    teacher = model.teacher if hasattr(model,
                                       "teacher") else model._layers.teacher
    student = model.student if hasattr(model,
                                       "student") else model._layers.student
98
    load_dygraph_pretrain(teacher, path=pretrained_model[0])
99 100 101 102
    logger.info("Finish initing teacher model from {}".format(
        pretrained_model))
    # load student model
    if len(pretrained_model) >= 2:
103
        load_dygraph_pretrain(student, path=pretrained_model[1])
104 105
        logger.info("Finish initing student model from {}".format(
            pretrained_model))
littletomatodonkey's avatar
littletomatodonkey 已提交
106

littletomatodonkey's avatar
littletomatodonkey 已提交
107

F
flytocc 已提交
108 109 110 111 112
def init_model(config,
               net,
               optimizer=None,
               loss: paddle.nn.Layer=None,
               ema=None):
W
WuHaobo 已提交
113
    """
W
WuHaobo 已提交
114
    load model from checkpoint or pretrained_model
W
WuHaobo 已提交
115 116
    """
    checkpoints = config.get('checkpoints')
L
littletomatodonkey 已提交
117
    if checkpoints and optimizer is not None:
W
WuHaobo 已提交
118 119 120 121
        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)
122
        # load state dict
123
        opti_dict = paddle.load(checkpoints + ".pdopt")
124
        para_dict = paddle.load(checkpoints + ".pdparams")
125
        metric_dict = paddle.load(checkpoints + ".pdstates")
126 127
        # set state dict
        net.set_state_dict(para_dict)
H
HydrogenSulfate 已提交
128
        loss.set_state_dict(para_dict)
129
        for i in range(len(optimizer)):
130 131
            optimizer[i].set_state_dict(opti_dict[i] if isinstance(
                opti_dict, list) else opti_dict)
F
flytocc 已提交
132 133 134 135 136
        if ema is not None:
            assert os.path.exists(checkpoints + ".ema.pdparams"), \
                "Given dir {}.ema.pdparams not exist.".format(checkpoints)
            para_ema_dict = paddle.load(checkpoints + ".ema.pdparams")
            ema.set_state_dict(para_ema_dict)
L
littletomatodonkey 已提交
137
        logger.info("Finish load checkpoints from {}".format(checkpoints))
138
        return metric_dict
W
WuHaobo 已提交
139 140

    pretrained_model = config.get('pretrained_model')
141
    use_distillation = config.get('use_distillation', False)
W
WuHaobo 已提交
142
    if pretrained_model:
143
        if use_distillation:
144
            load_distillation_model(net, pretrained_model)
littletomatodonkey's avatar
littletomatodonkey 已提交
145
        else:  # common load
146
            load_dygraph_pretrain(net, path=pretrained_model)
W
weishengyu 已提交
147
            logger.info("Finish load pretrained model from {}".format(
148
                pretrained_model))
W
WuHaobo 已提交
149 150


151 152 153 154
def save_model(net,
               optimizer,
               metric_info,
               model_path,
F
flytocc 已提交
155
               ema=None,
156
               model_name="",
157
               prefix='ppcls',
littletomatodonkey's avatar
littletomatodonkey 已提交
158 159
               loss: paddle.nn.Layer=None,
               save_student_model=False):
W
WuHaobo 已提交
160
    """
W
WuHaobo 已提交
161
    save model to the target path
W
WuHaobo 已提交
162
    """
163 164
    if paddle.distributed.get_rank() != 0:
        return
L
littletomatodonkey 已提交
165
    model_path = os.path.join(model_path, model_name)
W
WuHaobo 已提交
166
    _mkdir_if_not_exist(model_path)
L
littletomatodonkey 已提交
167
    model_path = os.path.join(model_path, prefix)
168

169
    params_state_dict = net.state_dict()
littletomatodonkey's avatar
littletomatodonkey 已提交
170 171 172 173 174 175 176 177 178 179 180 181
    if loss is not None:
        loss_state_dict = loss.state_dict()
        keys_inter = set(params_state_dict.keys()) & set(loss_state_dict.keys(
        ))
        assert len(keys_inter) == 0, \
            f"keys in model and loss state_dict must be unique, but got intersection {keys_inter}"
        params_state_dict.update(loss_state_dict)

    if save_student_model:
        s_params = _extract_student_weights(params_state_dict)
        if len(s_params) > 0:
            paddle.save(s_params, model_path + "_student.pdparams")
182 183

    paddle.save(params_state_dict, model_path + ".pdparams")
F
flytocc 已提交
184 185
    if ema is not None:
        paddle.save(ema.state_dict(), model_path + ".ema.pdparams")
186
    paddle.save([opt.state_dict() for opt in optimizer], model_path + ".pdopt")
L
littletomatodonkey 已提交
187
    paddle.save(metric_info, model_path + ".pdstates")
188
    logger.info("Already save model in {}".format(model_path))