checkpoint.py 9.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# Copyright (c) 2019 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

20
import errno
21 22
import os
import shutil
23
import tempfile
24
import time
25
import numpy as np
26
import re
27 28 29 30 31 32 33
import paddle.fluid as fluid

from .download import get_weights_path

import logging
logger = logging.getLogger(__name__)

W
wangguanzhong 已提交
34 35 36
__all__ = [
    'load_checkpoint',
    'load_and_fusebn',
37
    'load_params',
W
wangguanzhong 已提交
38 39
    'save',
]
40 41 42 43 44 45 46 47 48 49 50


def is_url(path):
    """
    Whether path is URL.
    Args:
        path (string): URL string or not.
    """
    return path.startswith('http://') or path.startswith('https://')


51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
def _get_weight_path(path):
    env = os.environ
    if 'PADDLE_TRAINERS_NUM' in env and 'PADDLE_TRAINER_ID' in env:
        trainer_id = int(env['PADDLE_TRAINER_ID'])
        num_trainers = int(env['PADDLE_TRAINERS_NUM'])
        if num_trainers <= 1:
            path = get_weights_path(path)
        else:
            from ppdet.utils.download import map_path, WEIGHTS_HOME
            weight_path = map_path(path, WEIGHTS_HOME)
            lock_path = weight_path + '.lock'
            if not os.path.exists(weight_path):
                try:
                    os.makedirs(os.path.dirname(weight_path))
                except OSError as e:
                    if e.errno != errno.EEXIST:
                        raise
                with open(lock_path, 'w'):  # touch    
                    os.utime(lock_path, None)
                if trainer_id == 0:
                    get_weights_path(path)
                    os.remove(lock_path)
                else:
                    while os.path.exists(lock_path):
                        time.sleep(1)
            path = weight_path
    else:
        path = get_weights_path(path)
    return path


82 83 84 85 86 87 88 89 90 91 92 93 94
def _load_state(path):
    if os.path.exists(path + '.pdopt'):
        # XXX another hack to ignore the optimizer state
        tmp = tempfile.mkdtemp()
        dst = os.path.join(tmp, os.path.basename(os.path.normpath(path)))
        shutil.copy(path + '.pdparams', dst + '.pdparams')
        state = fluid.io.load_program_state(dst)
        shutil.rmtree(tmp)
    else:
        state = fluid.io.load_program_state(path)
    return state


K
Kaipeng Deng 已提交
95 96 97 98 99 100 101
def _strip_postfix(path):
    path, ext = os.path.splitext(path)
    assert ext in ['', '.pdparams', '.pdopt', '.pdmodel'], \
            "Unknown postfix {} from weights".format(ext)
    return path


102
def load_params(exe, prog, path, ignore_params=[]):
103 104 105 106 107 108
    """
    Load model from the given path.
    Args:
        exe (fluid.Executor): The fluid.Executor object.
        prog (fluid.Program): load weight to which Program object.
        path (string): URL string or loca model path.
109
        ignore_params (list): ignore variable to load when finetuning.
110
            It can be specified by finetune_exclude_pretrained_params 
111
            and the usage can refer to docs/advanced_tutorials/TRANSFER_LEARNING.md
112
    """
113

114
    if is_url(path):
115
        path = _get_weight_path(path)
K
Kaipeng Deng 已提交
116 117

    path = _strip_postfix(path)
118 119
    if not (os.path.isdir(path) or os.path.isfile(path) or
            os.path.exists(path + '.pdparams')):
120 121
        raise ValueError("Model pretrain path {} does not "
                         "exists.".format(path))
122

Y
Yang Zhang 已提交
123
    logger.debug('Loading parameters from {}...'.format(path))
124

125 126 127 128 129 130 131 132 133 134 135 136 137 138
    ignore_set = set()
    state = _load_state(path)

    # ignore the parameter which mismatch the shape 
    # between the model and pretrain weight.
    all_var_shape = {}
    for block in prog.blocks:
        for param in block.all_parameters():
            all_var_shape[param.name] = param.shape
    ignore_set.update([
        name for name, shape in all_var_shape.items()
        if name in state and shape != state[name].shape
    ])

139 140 141 142 143
    if ignore_params:
        all_var_names = [var.name for var in prog.list_vars()]
        ignore_list = filter(
            lambda var: any([re.match(name, var) for name in ignore_params]),
            all_var_names)
144
        ignore_set.update(list(ignore_list))
145

146 147
    if len(ignore_set) > 0:
        for k in ignore_set:
148
            if k in state:
149 150
                logger.warning('variable {}: state shape {}, param shape {}'.format(k, state[k].shape, all_var_shape[k]))
                # logger.warning('variable {} not used'.format(k))
151 152
                del state[k]
    fluid.io.set_program_state(prog, state)
153 154 155 156 157 158 159 160 161 162 163


def load_checkpoint(exe, prog, path):
    """
    Load model from the given path.
    Args:
        exe (fluid.Executor): The fluid.Executor object.
        prog (fluid.Program): load weight to which Program object.
        path (string): URL string or loca model path.
    """
    if is_url(path):
164
        path = _get_weight_path(path)
K
Kaipeng Deng 已提交
165 166

    path = _strip_postfix(path)
167 168
    if not (os.path.isdir(path) or os.path.exists(path + '.pdparams')):
        raise ValueError("Model pretrain path {} does not "
169
                         "exists.".format(path))
170
    fluid.load(prog, path, executor=exe)
171 172


Q
qingqing01 已提交
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
def global_step(scope=None):
    """
    Load global step in scope.
    Args:
        scope (fluid.Scope): load global step from which scope. If None,
            from default global_scope().

    Returns:
        global step: int.
    """
    if scope is None:
        scope = fluid.global_scope()
    v = scope.find_var('@LR_DECAY_COUNTER@')
    step = np.array(v.get_tensor())[0] if v else 0
    return step


190 191 192 193 194 195 196 197 198 199 200
def save(exe, prog, path):
    """
    Load model from the given path.
    Args:
        exe (fluid.Executor): The fluid.Executor object.
        prog (fluid.Program): save weight from which Program object.
        path (string): the path to save model.
    """
    if os.path.isdir(path):
        shutil.rmtree(path)
    logger.info('Save model to {}.'.format(path))
201
    fluid.save(prog, path)
202 203 204 205 206 207 208 209 210 211 212


def load_and_fusebn(exe, prog, path):
    """
    Fuse params of batch norm to scale and bias.

    Args:
        exe (fluid.Executor): The fluid.Executor object.
        prog (fluid.Program): save weight from which Program object.
        path (string): the path to save model.
    """
Y
Yang Zhang 已提交
213
    logger.debug('Load model and fuse batch norm if have from {}...'.format(
Q
qingqing01 已提交
214
        path))
215

216
    if is_url(path):
217
        path = _get_weight_path(path)
218

219 220 221
    if not os.path.exists(path):
        raise ValueError("Model path {} does not exists.".format(path))

222 223 224 225 226 227 228 229 230 231
    # Since the program uses affine-channel, there is no running mean and var
    # in the program, here append running mean and var.
    # NOTE, the params of batch norm should be like:
    #  x_scale
    #  x_offset
    #  x_mean
    #  x_variance
    #  x is any prefix
    mean_variances = set()
    bn_vars = []
232
    state = _load_state(path)
233 234 235 236

    def check_mean_and_bias(prefix):
        m = prefix + 'mean'
        v = prefix + 'variance'
237
        return v in state and m in state
238 239

    has_mean_bias = True
240

241
    with fluid.program_guard(prog, fluid.Program()):
242 243
        for block in prog.blocks:
            ops = list(block.ops)
244
            if not has_mean_bias:
245 246 247 248 249 250 251 252 253
                break
            for op in ops:
                if op.type == 'affine_channel':
                    # remove 'scale' as prefix
                    scale_name = op.input('Scale')[0]  # _scale
                    bias_name = op.input('Bias')[0]  # _offset
                    prefix = scale_name[:-5]
                    mean_name = prefix + 'mean'
                    variance_name = prefix + 'variance'
254 255
                    if not check_mean_and_bias(prefix):
                        has_mean_bias = False
256 257 258
                        break

                    bias = block.var(bias_name)
259

260
                    mean_vb = block.create_var(
261 262 263
                        name=mean_name,
                        type=bias.type,
                        shape=bias.shape,
264 265
                        dtype=bias.dtype)
                    variance_vb = block.create_var(
266 267 268
                        name=variance_name,
                        type=bias.type,
                        shape=bias.shape,
269
                        dtype=bias.dtype)
270

271 272 273 274 275 276
                    mean_variances.add(mean_vb)
                    mean_variances.add(variance_vb)

                    bn_vars.append(
                        [scale_name, bias_name, mean_name, variance_name])

277
    if not has_mean_bias:
278
        fluid.io.set_program_state(prog, state)
Q
qingqing01 已提交
279 280 281 282
        logger.warning(
            "There is no paramters of batch norm in model {}. "
            "Skip to fuse batch norm. And load paramters done.".format(path))
        return
283

284
    fluid.load(prog, path, exe)
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
    eps = 1e-5
    for names in bn_vars:
        scale_name, bias_name, mean_name, var_name = names

        scale = fluid.global_scope().find_var(scale_name).get_tensor()
        bias = fluid.global_scope().find_var(bias_name).get_tensor()
        mean = fluid.global_scope().find_var(mean_name).get_tensor()
        var = fluid.global_scope().find_var(var_name).get_tensor()

        scale_arr = np.array(scale)
        bias_arr = np.array(bias)
        mean_arr = np.array(mean)
        var_arr = np.array(var)

        bn_std = np.sqrt(np.add(var_arr, eps))
        new_scale = np.float32(np.divide(scale_arr, bn_std))
        new_bias = bias_arr - mean_arr * new_scale

        # fuse to scale and bias in affine_channel
        scale.set(new_scale, exe.place)
        bias.set(new_bias, exe.place)