checkpoint.py 10.6 KB
Newer Older
Q
qingqing01 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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.

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

import errno
import os
import time
import numpy as np
import paddle
W
wangxinxin08 已提交
25
import paddle.nn as nn
Q
qingqing01 已提交
26 27 28 29 30 31 32 33 34 35 36 37
from .download import get_weights_path

from .logger import setup_logger
logger = setup_logger(__name__)


def is_url(path):
    """
    Whether path is URL.
    Args:
        path (string): URL string or not.
    """
K
Kaipeng Deng 已提交
38 39 40
    return path.startswith('http://') \
            or path.startswith('https://') \
            or path.startswith('ppdet://')
Q
qingqing01 已提交
41 42


43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
def _get_unique_endpoints(trainer_endpoints):
    # Sorting is to avoid different environmental variables for each card
    trainer_endpoints.sort()
    ips = set()
    unique_endpoints = set()
    for endpoint in trainer_endpoints:
        ip = endpoint.split(":")[0]
        if ip in ips:
            continue
        ips.add(ip)
        unique_endpoints.add(endpoint)
    logger.info("unique_endpoints {}".format(unique_endpoints))
    return unique_endpoints


Q
qingqing01 已提交
58 59 60 61 62 63 64
def _strip_postfix(path):
    path, ext = os.path.splitext(path)
    assert ext in ['', '.pdparams', '.pdopt', '.pdmodel'], \
            "Unknown postfix {} from weights".format(ext)
    return path


65
def load_weight(model, weight, optimizer=None, ema=None, exchange=True):
Q
qingqing01 已提交
66
    if is_url(weight):
K
Kaipeng Deng 已提交
67
        weight = get_weights_path(weight)
Q
qingqing01 已提交
68 69 70 71 72 73 74

    path = _strip_postfix(weight)
    pdparam_path = path + '.pdparams'
    if not os.path.exists(pdparam_path):
        raise ValueError("Model pretrain path {} does not "
                         "exists.".format(pdparam_path))

S
shangliang Xu 已提交
75
    if ema is not None and os.path.exists(path + '.pdema'):
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
        if exchange:
            # Exchange model and ema_model to load
            logger.info('Exchange model and ema_model to load:')
            ema_state_dict = paddle.load(pdparam_path)
            logger.info('Loading ema_model weights from {}'.format(path +
                                                                   '.pdparams'))
            param_state_dict = paddle.load(path + '.pdema')
            logger.info('Loading model weights from {}'.format(path + '.pdema'))
        else:
            ema_state_dict = paddle.load(path + '.pdema')
            logger.info('Loading ema_model weights from {}'.format(path +
                                                                   '.pdema'))
            param_state_dict = paddle.load(pdparam_path)
            logger.info('Loading model weights from {}'.format(path +
                                                               '.pdparams'))
S
shangliang Xu 已提交
91 92 93 94
    else:
        ema_state_dict = None
        param_state_dict = paddle.load(pdparam_path)

95 96 97 98
    model_dict = model.state_dict()
    model_weight = {}
    incorrect_keys = 0

99
    for key, value in model_dict.items():
100
        if key in param_state_dict.keys():
101 102 103 104 105 106
            if isinstance(param_state_dict[key], np.ndarray):
                param_state_dict[key] = paddle.to_tensor(param_state_dict[key])
            if value.dtype == param_state_dict[key].dtype:
                model_weight[key] = param_state_dict[key]
            else:
                model_weight[key] = param_state_dict[key].astype(value.dtype)
107 108 109 110 111 112 113
        else:
            logger.info('Unmatched key: {}'.format(key))
            incorrect_keys += 1

    assert incorrect_keys == 0, "Load weight {} incorrectly, \
            {} keys unmatched, please check again.".format(weight,
                                                           incorrect_keys)
K
Kaipeng Deng 已提交
114
    logger.info('Finish resuming model weights: {}'.format(pdparam_path))
115 116

    model.set_dict(model_weight)
Q
qingqing01 已提交
117

G
Guanghua Yu 已提交
118
    last_epoch = 0
Q
qingqing01 已提交
119 120
    if optimizer is not None and os.path.exists(path + '.pdopt'):
        optim_state_dict = paddle.load(path + '.pdopt')
121
        # to solve resume bug, will it be fixed in paddle 2.0
Q
qingqing01 已提交
122 123 124 125 126 127
        for key in optimizer.state_dict().keys():
            if not key in optim_state_dict.keys():
                optim_state_dict[key] = optimizer.state_dict()[key]
        if 'last_epoch' in optim_state_dict:
            last_epoch = optim_state_dict.pop('last_epoch')
        optimizer.set_state_dict(optim_state_dict)
G
Guanghua Yu 已提交
128

S
shangliang Xu 已提交
129
        if ema_state_dict is not None:
S
shangliang Xu 已提交
130 131
            ema.resume(ema_state_dict,
                       optim_state_dict['LR_Scheduler']['last_epoch'])
S
shangliang Xu 已提交
132 133
    elif ema_state_dict is not None:
        ema.resume(ema_state_dict)
G
Guanghua Yu 已提交
134
    return last_epoch
Q
qingqing01 已提交
135 136


W
wangguanzhong 已提交
137 138 139 140 141 142 143
def match_state_dict(model_state_dict, weight_state_dict):
    """
    Match between the model state dict and pretrained weight state dict.
    Return the matched state dict.

    The method supposes that all the names in pretrained weight state dict are
    subclass of the names in models`, if the prefix 'backbone.' in pretrained weight
S
shangliang Xu 已提交
144
    keys is stripped. And we could get the candidates for each model key. Then we
W
wangguanzhong 已提交
145
    select the name with the longest matched size as the final match result. For
S
shangliang Xu 已提交
146
    example, the model state dict has the name of
W
wangguanzhong 已提交
147 148 149 150 151 152 153 154 155
    'backbone.res2.res2a.branch2a.conv.weight' and the pretrained weight as
    name of 'res2.res2a.branch2a.conv.weight' and 'branch2a.conv.weight'. We
    match the 'res2.res2a.branch2a.conv.weight' to the model key.
    """

    model_keys = sorted(model_state_dict.keys())
    weight_keys = sorted(weight_state_dict.keys())

    def match(a, b):
156
        if b.startswith('backbone.res5'):
S
shangliang Xu 已提交
157
            # In Faster RCNN, res5 pretrained weights have prefix of backbone,
W
wangguanzhong 已提交
158 159
            # however, the corresponding model weights have difficult prefix,
            # bbox_head.
W
wangguanzhong 已提交
160
            b = b[9:]
W
wangguanzhong 已提交
161 162 163 164 165 166 167 168 169 170
        return a == b or a.endswith("." + b)

    match_matrix = np.zeros([len(model_keys), len(weight_keys)])
    for i, m_k in enumerate(model_keys):
        for j, w_k in enumerate(weight_keys):
            if match(m_k, w_k):
                match_matrix[i, j] = len(w_k)
    max_id = match_matrix.argmax(1)
    max_len = match_matrix.max(1)
    max_id[max_len == 0] = -1
171 172 173

    load_id = set(max_id)
    load_id.discard(-1)
G
Guanghua Yu 已提交
174
    not_load_weight_name = []
175 176 177 178
    for idx in range(len(weight_keys)):
        if idx not in load_id:
            not_load_weight_name.append(weight_keys[idx])

G
Guanghua Yu 已提交
179 180 181
    if len(not_load_weight_name) > 0:
        logger.info('{} in pretrained weight is not used in the model, '
                    'and its will not be loaded'.format(not_load_weight_name))
W
wangguanzhong 已提交
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
    matched_keys = {}
    result_state_dict = {}
    for model_id, weight_id in enumerate(max_id):
        if weight_id == -1:
            continue
        model_key = model_keys[model_id]
        weight_key = weight_keys[weight_id]
        weight_value = weight_state_dict[weight_key]
        model_value_shape = list(model_state_dict[model_key].shape)

        if list(weight_value.shape) != model_value_shape:
            logger.info(
                'The shape {} in pretrained weight {} is unmatched with '
                'the shape {} in model {}. And the weight {} will not be '
                'loaded'.format(weight_value.shape, weight_key,
                                model_value_shape, model_key, weight_key))
            continue

        assert model_key not in result_state_dict
        result_state_dict[model_key] = weight_value
        if weight_key in matched_keys:
            raise ValueError('Ambiguity weight {} loaded, it matches at least '
                             '{} and {} in the model'.format(
                                 weight_key, model_key, matched_keys[
                                     weight_key]))
        matched_keys[weight_key] = model_key
    return result_state_dict


K
Kaipeng Deng 已提交
211
def load_pretrain_weight(model, pretrain_weight):
Q
qingqing01 已提交
212
    if is_url(pretrain_weight):
K
Kaipeng Deng 已提交
213
        pretrain_weight = get_weights_path(pretrain_weight)
Q
qingqing01 已提交
214 215 216 217

    path = _strip_postfix(pretrain_weight)
    if not (os.path.isdir(path) or os.path.isfile(path) or
            os.path.exists(path + '.pdparams')):
218 219 220 221
        raise ValueError("Model pretrain path `{}` does not exists. "
                         "If you don't want to load pretrain model, "
                         "please delete `pretrain_weights` field in "
                         "config file.".format(path))
Q
qingqing01 已提交
222 223 224

    model_dict = model.state_dict()

K
Kaipeng Deng 已提交
225 226
    weights_path = path + '.pdparams'
    param_state_dict = paddle.load(weights_path)
W
wangguanzhong 已提交
227
    param_state_dict = match_state_dict(model_dict, param_state_dict)
K
Kaipeng Deng 已提交
228

229 230 231 232 233 234
    for k, v in param_state_dict.items():
        if isinstance(v, np.ndarray):
            v = paddle.to_tensor(v)
        if model_dict[k].dtype != v.dtype:
            param_state_dict[k] = v.astype(model_dict[k].dtype)

K
Kaipeng Deng 已提交
235 236
    model.set_dict(param_state_dict)
    logger.info('Finish loading model weights: {}'.format(weights_path))
Q
qingqing01 已提交
237 238


S
shangliang Xu 已提交
239 240 241 242 243 244
def save_model(model,
               optimizer,
               save_dir,
               save_name,
               last_epoch,
               ema_model=None):
Q
qingqing01 已提交
245 246
    """
    save model into disk.
247

Q
qingqing01 已提交
248
    Args:
S
shangliang Xu 已提交
249
        model (dict): the model state_dict to save parameters.
Q
qingqing01 已提交
250 251 252 253 254
        optimizer (paddle.optimizer.Optimizer): the Optimizer instance to
            save optimizer states.
        save_dir (str): the directory to be saved.
        save_name (str): the path to be saved.
        last_epoch (int): the epoch index.
S
shangliang Xu 已提交
255
        ema_model (dict|None): the ema_model state_dict to save parameters.
Q
qingqing01 已提交
256
    """
257 258
    if paddle.distributed.get_rank() != 0:
        return
S
shangliang Xu 已提交
259 260
    assert isinstance(model, dict), ("model is not a instance of dict, "
                                     "please call model.state_dict() to get.")
Q
qingqing01 已提交
261 262 263
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
    save_path = os.path.join(save_dir, save_name)
S
shangliang Xu 已提交
264 265
    # save model
    if ema_model is None:
W
wangxinxin08 已提交
266
        paddle.save(model, save_path + ".pdparams")
S
shangliang Xu 已提交
267 268 269 270 271 272 273 274 275 276 277 278
    else:
        assert isinstance(ema_model,
                          dict), ("ema_model is not a instance of dict, "
                                  "please call model.state_dict() to get.")
        # Exchange model and ema_model to save
        paddle.save(ema_model, save_path + ".pdparams")
        paddle.save(model, save_path + ".pdema")
    # save optimizer
    state_dict = optimizer.state_dict()
    state_dict['last_epoch'] = last_epoch
    paddle.save(state_dict, save_path + ".pdopt")
    logger.info("Save checkpoint: {}".format(save_dir))