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

import os
import collections
H
hong 已提交
19
from ..framework import Variable, default_main_program, in_dygraph_mode, dygraph_only, Parameter
20 21 22
import pickle
from . import learning_rate_scheduler
import warnings
H
hong 已提交
23
from .. import core
24

H
hong 已提交
25 26 27 28
__all__ = [
    'save_dygraph',
    'load_dygraph',
]
29 30


H
hong 已提交
31 32 33 34 35 36 37
@dygraph_only
def save_dygraph(state_dict, model_path):
    '''
    Save Layer's state_dict to disk. This will generate a file with suffix ".pdparams"
    
    The state_dict is get from Layers.state_dict function
    
38
    Args:
H
hong 已提交
39 40
        state_dict(dict) : The state dict to be saved.
        model_path(str) : the file prefix to save the state_dict. The format is "dirname/file_prefix". If file_prefix is empty str. A exception will be raised
41 42

    Returns:
L
lujun 已提交
43
        None
44 45

    Examples:
H
hong 已提交
46 47 48 49 50 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 82 83 84 85 86
        .. code-block:: python

            import paddle.fluid as fluid

            with fluid.dygraph.guard():
                emb = fluid.dygraph.Embedding( "emb", [10, 10])

                state_dict = emb.state_dict()
                fluid.save_dygraph( state_dict, "paddle_dy")

                adam = fluid.optimizer.Adam( learning_rate = fluid.layers.noam_decay( 100, 10000) )

                state_dict = adam.state_dict()
                fluid.save_dygraph( state_dict, "paddle_dy")

    '''

    base_name = os.path.basename(model_path)
    assert base_name != "", "model_path MUST be format of dirname/filename [dirname\\filename in Window], Now filename is empty str"

    suffix = ".pdparams"
    assert len(state_dict) > 0, "state_dict is empty, no need to save"

    for k, v in state_dict.items():
        if not isinstance(v, Parameter):
            suffix = ".pdopt"
        break

    core._save_dygraph_dict(model_path + suffix, state_dict)


@dygraph_only
def load_dygraph(model_path):
    '''
    Load parameter state_dict from disk.

    Args:
        model_path(str) : The file prefix store the state_dict. (The path should Not contain suffix '.pdparams') 

    Returns:
        state_dict(dict) : the dict store the state_dict
L
lujun 已提交
87

H
hong 已提交
88
    Examples:
89
        .. code-block:: python
L
lujun 已提交
90

H
hong 已提交
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
            import paddle.fluid as fluid
            
            with fluid.dygraph.guard():
                emb = fluid.dygraph.Embedding( "emb", [10, 10])

                state_dict = emb.state_dict()
                fluid.save_dygraph( state_dict, "paddle_dy")

                adam = fluid.optimizer.Adam( learning_rate = fluid.layers.noam_decay( 100, 10000) )
                state_dict = adam.state_dict()
                fluid.save_dygraph( state_dict, "padle_dy")

                para_state_dict, opti_state_dict = fluid.load_dygraph( "paddle_dy")

    '''

    params_file_path = model_path + ".pdparams"
    if not os.path.exists(params_file_path):
        raise RuntimeError("Parameter file [ {} ] not exists".format(
            params_file_path))

    para_dict = core._load_dygraph_dict(params_file_path)

    opti_dict = None
    opti_file_path = model_path + ".pdopt"
    if os.path.exists(opti_file_path):
        opti_dict = core._load_dygraph_dict(opti_file_path)

    return para_dict, opti_dict


@dygraph_only
def load_optimizer(model_path):
    '''
    Load optimizer state_dict from disk.
126 127

    Args:
H
hong 已提交
128
        model_path(str) : The file prefix store the state_dict. (The path should Not contain shuffix '.pdparams')
129 130

    Returns:
H
hong 已提交
131
        state_dict(dict) : the dict store the state_dict
132 133

    Examples:
H
hong 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146
        .. code-block:: python

            import paddle.fluid as fluid

            with fluid.dygraph.guard():
                adam = fluid.optimizer.Adam(0.001)

                state_dict = adam.state_dict()
                fluid.save_optimizer( state_dict, "opt_adam")

                fluid.load_optimizer( "opt_adam")

    '''
L
lujun 已提交
147

H
hong 已提交
148 149 150 151 152 153
    assert in_dygraph_mode(), "save_optimizer only work in dygraph mode"
    opt_file_path = model_path + ".pdopt"
    if not os.path.exists(opt_file_path):
        raise RuntimeError("Optimizer file [ {} ] not exists".format(
            opt_file_path))
    return core._load_dygraph_dict(opt_file_path)