startup.py 8.7 KB
Newer Older
C
Chengmo 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# 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 print_function

import warnings
18
import logging
C
Chengmo 已提交
19 20

import paddle.fluid as fluid
C
Chengmo 已提交
21
import paddle.fluid.core as core
C
Chengmo 已提交
22 23
from paddlerec.core.utils import envs

C
Chengmo 已提交
24 25 26 27
__all__ = [
    "StartupBase", "SingleStartup", "PSStartup", "CollectiveStartup",
    "FineTuningStartup"
]
C
Chengmo 已提交
28

29 30 31 32
logging.basicConfig(format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger("fluid")
logger.setLevel(logging.INFO)

C
Chengmo 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48

class StartupBase(object):
    """R
    """

    def __init__(self, context):
        pass

    def startup(self, context):
        pass

    def load(self, context, is_fleet=False, main_program=None):
        dirname = envs.get_global_env(
            "runner." + context["runner_name"] + ".init_model_path", None)
        if dirname is None or dirname == "":
            return
49
        logger.info("going to load ", dirname)
C
chengmo 已提交
50 51
        fluid.io.load_persistables(
            context["exe"], dirname, main_program=main_program)
52
        logger.info("load from {} success".format(dirname))
C
Chengmo 已提交
53 54 55 56 57 58 59


class SingleStartup(StartupBase):
    """R
    """

    def __init__(self, context):
60
        logger.info("Running SingleStartup.")
C
Chengmo 已提交
61 62 63
        pass

    def startup(self, context):
T
tangwei 已提交
64
        for model_dict in context["phases"]:
C
Chengmo 已提交
65 66 67 68 69 70 71 72 73
            with fluid.scope_guard(context["model"][model_dict["name"]][
                    "scope"]):
                train_prog = context["model"][model_dict["name"]][
                    "main_program"]
                startup_prog = context["model"][model_dict["name"]][
                    "startup_program"]
                with fluid.program_guard(train_prog, startup_prog):
                    context["exe"].run(startup_prog)
                    self.load(context, main_program=train_prog)
C
Chengmo 已提交
74 75 76 77 78 79 80 81 82 83 84 85 86
        context["status"] = "train_pass"


class FineTuningStartup(StartupBase):
    """R
    """

    def __init__(self, context):
        self.op_name_scope = "op_namescope"
        self.clip_op_name_scope = "@CLIP"
        self.self.op_role_var_attr_name = core.op_proto_and_checker_maker.kOpRoleVarAttrName(
        )

87
        logger.info("Running SingleStartup.")
C
Chengmo 已提交
88 89 90 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 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162

    def _is_opt_role_op(self, op):
        # NOTE: depend on oprole to find out whether this op is for
        # optimize
        op_maker = core.op_proto_and_checker_maker
        optimize_role = core.op_proto_and_checker_maker.OpRole.Optimize
        if op_maker.kOpRoleAttrName() in op.attr_names and \
                int(op.all_attrs()[op_maker.kOpRoleAttrName()]) == int(optimize_role):
            return True
        return False

    def _get_params_grads(self, program):
        """
        Get optimizer operators, parameters and gradients from origin_program
        Returns:
            opt_ops (list): optimize operators.
            params_grads (dict): parameter->gradient.
        """
        block = program.global_block()
        params_grads = []
        # tmp set to dedup
        optimize_params = set()
        origin_var_dict = program.global_block().vars
        for op in block.ops:
            if self._is_opt_role_op(op):
                # Todo(chengmo): Whether clip related op belongs to Optimize guard should be discussed
                # delete clip op from opt_ops when run in Parameter Server mode
                if self.op_name_scope in op.all_attrs(
                ) and self.clip_op_name_scope in op.attr(self.op_name_scope):
                    op._set_attr(
                        "op_role",
                        int(core.op_proto_and_checker_maker.OpRole.Backward))
                    continue

                if op.attr(self.op_role_var_attr_name):
                    param_name = op.attr(self.op_role_var_attr_name)[0]
                    grad_name = op.attr(self.op_role_var_attr_name)[1]
                    if not param_name in optimize_params:
                        optimize_params.add(param_name)
                        params_grads.append([
                            origin_var_dict[param_name],
                            origin_var_dict[grad_name]
                        ])
        return params_grads

    @staticmethod
    def is_persistable(var):
        """
        Check whether the given variable is persistable.

        Args:
            var(Variable): The variable to be checked.

        Returns:
            bool: True if the given `var` is persistable
            False if not.

        Examples:
            .. code-block:: python

                import paddle.fluid as fluid
                param = fluid.default_main_program().global_block().var('fc.b')
                res = fluid.io.is_persistable(param)
        """
        if var.desc.type() == core.VarDesc.VarType.FEED_MINIBATCH or \
                var.desc.type() == core.VarDesc.VarType.FETCH_LIST or \
                var.desc.type() == core.VarDesc.VarType.READER:
            return False
        return var.persistable

    def load(self, context, is_fleet=False, main_program=None):
        dirname = envs.get_global_env(
            "runner." + context["runner_name"] + ".init_model_path", None)
        if dirname is None or dirname == "":
            return
163
        logger.info("going to load ", dirname)
C
Chengmo 已提交
164 165 166 167 168 169 170 171 172 173 174 175 176

        params_grads = self._get_params_grads(main_program)
        update_params = [p for p, _ in params_grads]
        need_load_vars = []
        parameters = list(
            filter(FineTuningStartup.is_persistable, main_program.list_vars()))

        for param in parameters:
            if param not in update_params:
                need_load_vars.append(param)

        fluid.io.load_vars(context["exe"], dirname, main_program,
                           need_load_vars)
177
        logger.info("load from {} success".format(dirname))
C
Chengmo 已提交
178 179 180 181 182 183 184 185 186 187 188 189

    def startup(self, context):
        for model_dict in context["phases"]:
            with fluid.scope_guard(context["model"][model_dict["name"]][
                    "scope"]):
                train_prog = context["model"][model_dict["name"]][
                    "main_program"]
                startup_prog = context["model"][model_dict["name"]][
                    "startup_program"]
                with fluid.program_guard(train_prog, startup_prog):
                    context["exe"].run(startup_prog)
                    self.load(context, main_program=train_prog)
C
Chengmo 已提交
190 191 192 193 194
        context["status"] = "train_pass"


class PSStartup(StartupBase):
    def __init__(self, context):
195
        logger.info("Running PSStartup.")
C
Chengmo 已提交
196 197 198
        pass

    def startup(self, context):
T
tangwei 已提交
199
        model_dict = context["env"]["phase"][0]
C
Chengmo 已提交
200 201 202 203 204 205 206 207 208 209 210 211
        with fluid.scope_guard(context["model"][model_dict["name"]]["scope"]):

            train_prog = context["model"][model_dict["name"]]["main_program"]
            startup_prog = context["model"][model_dict["name"]][
                "startup_program"]
            with fluid.program_guard(train_prog, startup_prog):
                context["exe"].run(startup_prog)
        context["status"] = "train_pass"


class CollectiveStartup(StartupBase):
    def __init__(self, context):
212
        logger.info("Running CollectiveStartup.")
C
Chengmo 已提交
213 214 215
        pass

    def startup(self, context):
T
tangwei 已提交
216
        model_dict = context["env"]["phase"][0]
C
Chengmo 已提交
217 218 219 220 221 222 223
        with fluid.scope_guard(context["model"][model_dict["name"]]["scope"]):
            train_prog = context["model"][model_dict["name"]][
                "default_main_program"]
            startup_prog = context["model"][model_dict["name"]][
                "startup_program"]
            with fluid.program_guard(train_prog, startup_prog):
                context["exe"].run(startup_prog)
C
chengmo 已提交
224
                self.load(context, main_program=train_prog)
C
Chengmo 已提交
225
        context["status"] = "train_pass"
226 227 228 229


class SingleInferStartup(StartupBase):
    def __init__(self, context):
230
        logger.info("Running SingleInferStartup.")
231 232 233 234 235 236 237 238 239 240 241 242 243
        pass

    def startup(self, context):
        for model_dict in context["phases"]:
            with fluid.scope_guard(context["model"][model_dict["name"]][
                    "scope"]):
                train_prog = context["model"][model_dict["name"]][
                    "main_program"]
                startup_prog = context["model"][model_dict["name"]][
                    "startup_program"]
                with fluid.program_guard(train_prog, startup_prog):
                    context["exe"].run(startup_prog)
        context["status"] = "train_pass"