trainer.py 8.1 KB
Newer Older
T
tangwei 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# 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.

X
xiexionghang 已提交
15
import abc
T
tangwei 已提交
16
import os
X
xiexionghang 已提交
17
import time
T
tangwei 已提交
18
import sys
T
tangwei 已提交
19
import yaml
X
xionghang 已提交
20
import traceback
T
tangwei 已提交
21

T
tangwei 已提交
22
from paddle import fluid
T
tangwei 已提交
23

24
from paddlerec.core.utils import envs
T
tangwei 已提交
25

T
tangwei 已提交
26

C
Chengmo 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
class EngineMode:
    """
    There are various engine designed for different runing environment.
    """
    SINGLE = 1
    CLUSTER = 2
    LOCAL_CLUSTER = 3


class FleetMode:
    """
    Paddle Distributed train support: ParameterServer/Collective/PSlib
    """
    PS = 1
    COLLECTIVE = 2
    PSLIB = 3


class Device:
    """
    PaddleRec Support CPU/GPU, XPU will comming soon
    """
    CPU = 1
    GPU = 2
    # XPU =3


X
xiexionghang 已提交
54
class Trainer(object):
C
Chengmo 已提交
55 56
    """
    Trainer Base
T
tangwei 已提交
57
    """
X
xiexionghang 已提交
58
    __metaclass__ = abc.ABCMeta
T
tangwei 已提交
59

T
tangwei 已提交
60
    def __init__(self, config=None):
X
xiexionghang 已提交
61
        self._status_processor = {}
C
Chengmo 已提交
62 63 64
        self.model = None
        self.inference_models = []
        self.increment_models = []
T
tangwei 已提交
65
        self._exector_context = {}
X
xiexionghang 已提交
66
        self._context = {'status': 'uninit', 'is_exit': False}
T
tangwei 已提交
67
        self._context["config_yaml"] = config
C
Chengmo 已提交
68 69 70

        self._model = {}
        self._dataset = {}
T
tangwei 已提交
71

T
tangwei 已提交
72
        self._runner_name = envs.get_runtime_environ("mode")
C
Chengmo 已提交
73 74
        self._context["runner_name"] = self._runner_name

T
tangwei 已提交
75
        phase_names = envs.get_global_env(
T
tangwei 已提交
76 77 78
            "runner." + self._runner_name + ".phases", None)
        phases = []
        if phase_names is None:
T
tangwei 已提交
79
            phases = envs.get_global_env("phase")
T
tangwei 已提交
80
        else:
T
tangwei 已提交
81
            for phase in envs.get_global_env("phase"):
T
tangwei 已提交
82 83 84 85
                if phase["name"] in phase_names:
                    phases.append(phase)

        self._context["phases"] = phases
C
Chengmo 已提交
86 87 88 89 90 91 92 93 94 95 96 97
        print("PaddleRec: Runner {} Begin".format(self._runner_name))
        self.which_engine()
        self.which_device()
        self.which_fleet_mode()
        self.which_executor_mode()
        self.legality_check()

    def which_device(self):
        """R
        """
        device = envs.get_global_env(
            "runner." + self._runner_name + ".device", default_value="CPU")
T
tangwei 已提交
98 99 100
        device = device.upper()

        if device == 'GPU':
C
Chengmo 已提交
101 102 103 104 105
            self.check_gpu()
            self.device = Device.GPU
            gpu_id = int(os.environ.get('FLAGS_selected_gpus', 0))
            self._place = fluid.CUDAPlace(gpu_id)
            self._exe = fluid.Executor(self._place)
T
tangwei 已提交
106
        elif device == "CPU":
C
Chengmo 已提交
107 108 109 110 111
            self.device = Device.CPU
            self._place = fluid.CPUPlace()
            self._exe = fluid.Executor(self._place)
        else:
            raise ValueError("Not Support device {}".format(device))
T
tangwei 已提交
112
        self._context["device"] = device
C
Chengmo 已提交
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 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
        self._context["exe"] = self._exe
        self._context["place"] = self._place

    def check_gpu(self):
        """
        Log error and exit when set use_gpu=true in paddlepaddle
        cpu version.
        """
        err = "GPU cannot be set as true while you are " \
            "using paddlepaddle cpu version ! \nPlease try: \n" \
            "\t1. Install paddlepaddle-gpu to run model on GPU \n" \
            "\t2. Set device as cpu in config file to run " \
            "model on CPU"

        try:
            if not fluid.is_compiled_with_cuda():
                raise RuntimeError(err)
        except Exception as e:
            pass

    def which_engine(self):
        engine = envs.get_runtime_environ("train.trainer.engine")
        if engine.upper() == "SINGLE":
            self.engine = EngineMode.SINGLE
            self.is_fleet = False
        elif engine.upper() == "LOCAL_CLUSTER":
            self.engine = EngineMode.LOCAL_CLUSTER
            self.is_fleet = True
        elif engine.upper() == "CLUSTER":
            self.engine = EngineMode.CLUSTER
            self.is_fleet = True
        else:
            raise ValueError("Not Support Engine {}".format(engine))
        self._context["is_fleet"] = self.is_fleet
        self._context["engine"] = self.engine

    def which_fleet_mode(self):
        fleet_mode = envs.get_runtime_environ("fleet_mode")
        if fleet_mode.upper() == "PS":
            self.fleet_mode = FleetMode.PS
        elif fleet_mode.upper() == "COLLECTIVE":
            self.fleet_mode = FleetMode.COLLECTIVE
        elif fleet_mode.upper() == "PSLIB":
            self.fleet_mode = FleetMode.PSLIB
        else:
            raise ValueError("Not Support Fleet Mode {}".format(fleet_mode))

        self._context["is_pslib"] = (fleet_mode.upper() == "PSLIB")
        self._context["fleet_mode"] = fleet_mode

    def which_executor_mode(self):
        executor_mode = envs.get_runtime_environ("train.trainer.executor_mode")
        if executor_mode.upper() not in ["TRAIN", "INFER"]:
            raise ValueError("Not Support Executor Mode {}".format(
                executor_mode))
        if executor_mode.upper() == "TRAIN":
            self.is_infer = False
        else:
            self.is_infer = True
        print("Executor Mode: {}".format(executor_mode))
        self._context["is_infer"] = self.is_infer

    def legality_check(self):
        if self.device == Device.CPU:
            assert self.fleet_mode != FleetMode.COLLECTIVE, "Not Support CPU with Collective Mode"

        if self.is_infer:
            assert self.engine == EngineMode.SINGLE, "Not Support Distributed Infer "

    @abc.abstractmethod
    def processor_register(self):
        pass

X
xiexionghang 已提交
186
    def regist_context_processor(self, status_name, processor):
X
xiexionghang 已提交
187 188 189
        """
        regist a processor for specify status
        """
X
xiexionghang 已提交
190 191 192
        self._status_processor[status_name] = processor

    def context_process(self, context):
X
xiexionghang 已提交
193 194 195 196 197 198 199
        """
        select a processor to deal specify context
        Args:
            context : context with status
        Return:
            None : run a processor for this status
        """
X
xionghang 已提交
200 201 202 203 204 205
        status = context['status']
        try:
            if status in self._status_processor:
                self._status_processor[context['status']](context)
            else:
                self.other_status_processor(context)
X
xujiaqi01 已提交
206
        except Exception as err:
X
xionghang 已提交
207 208 209 210 211
            traceback.print_exc()
            print('Catch Exception:%s' % str(err))
            sys.stdout.flush()
            self._context['is_exit'] = self.handle_processor_exception(
                status, context, err)
T
tangwei 已提交
212

X
xiexionghang 已提交
213
    def other_status_processor(self, context):
X
xiexionghang 已提交
214 215 216 217 218
        """
        if no processor match context.status, use defalut processor
        Return:
            None, just sleep in base
        """
X
xiexionghang 已提交
219
        print('unknow context_status:%s, do nothing' % context['status'])
220
        time.sleep(60)
X
xiexionghang 已提交
221

X
xionghang 已提交
222 223 224 225 226 227
    def handle_processor_exception(self, status, context, exception):
        """
        when exception throwed from processor, will call this func to handle it 
        Return:
            bool exit_app or not
        """
C
Chengmo 已提交
228 229
        print('Exit app. catch exception in precoss status:%s, except:%s' %
              (context['status'], str(exception)))
X
xionghang 已提交
230 231
        return True

X
xiexionghang 已提交
232
    def reload_train_context(self):
X
xiexionghang 已提交
233 234 235
        """
        context maybe update timely, reload for update
        """
X
xiexionghang 已提交
236 237 238
        pass

    def run(self):
X
xiexionghang 已提交
239 240 241
        """
        keep running by statu context.
        """
X
xiexionghang 已提交
242 243 244 245 246
        while True:
            self.reload_train_context()
            self.context_process(self._context)
            if self._context['is_exit']:
                break
T
tangwei 已提交
247 248 249


def user_define_engine(engine_yaml):
X
test  
xjqbest 已提交
250
    _config = envs.load_yaml(engine_yaml)
T
tangwei 已提交
251
    envs.set_runtime_environs(_config)
T
tangwei 已提交
252 253 254 255
    train_location = envs.get_global_env("engine.file")
    train_dirname = os.path.dirname(train_location)
    base_name = os.path.splitext(os.path.basename(train_location))[0]
    sys.path.append(train_dirname)
T
tangwei 已提交
256 257
    trainer_class = envs.lazy_instance_by_fliename(base_name,
                                                   "UserDefineTraining")
T
tangwei 已提交
258
    return trainer_class