trainer.py 3.5 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

X
xiexionghang 已提交
27
class Trainer(object):
X
xiexionghang 已提交
28
    """R
T
tangwei 已提交
29
    """
X
xiexionghang 已提交
30
    __metaclass__ = abc.ABCMeta
T
tangwei 已提交
31

T
tangwei 已提交
32
    def __init__(self, config=None):
X
xiexionghang 已提交
33
        self._status_processor = {}
T
tangwei 已提交
34 35 36
        self._place = fluid.CPUPlace()
        self._exe = fluid.Executor(self._place)
        self._exector_context = {}
X
xiexionghang 已提交
37
        self._context = {'status': 'uninit', 'is_exit': False}
T
tangwei 已提交
38
        self._config_yaml = config
X
test  
xjqbest 已提交
39
        self._config = envs.load_yaml(config)
T
tangwei 已提交
40

X
xiexionghang 已提交
41
    def regist_context_processor(self, status_name, processor):
X
xiexionghang 已提交
42 43 44
        """
        regist a processor for specify status
        """
X
xiexionghang 已提交
45 46 47
        self._status_processor[status_name] = processor

    def context_process(self, context):
X
xiexionghang 已提交
48 49 50 51 52 53 54
        """
        select a processor to deal specify context
        Args:
            context : context with status
        Return:
            None : run a processor for this status
        """
X
xionghang 已提交
55 56 57 58 59 60 61 62 63 64 65 66
        status = context['status']
        try:
            if status in self._status_processor:
                self._status_processor[context['status']](context)
            else:
                self.other_status_processor(context)
        except Exception, err:
            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 已提交
67

X
xiexionghang 已提交
68
    def other_status_processor(self, context):
X
xiexionghang 已提交
69 70 71 72 73
        """
        if no processor match context.status, use defalut processor
        Return:
            None, just sleep in base
        """
X
xiexionghang 已提交
74
        print('unknow context_status:%s, do nothing' % context['status'])
75
        time.sleep(60)
X
xiexionghang 已提交
76

X
xionghang 已提交
77 78 79 80 81 82 83 84 85 86
    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
        """
        print('Exit app. catch exception in precoss status:%s, except:%s' \
                % (context['status'], str(exception)))
        return True

X
xiexionghang 已提交
87
    def reload_train_context(self):
X
xiexionghang 已提交
88 89 90
        """
        context maybe update timely, reload for update
        """
X
xiexionghang 已提交
91 92 93
        pass

    def run(self):
X
xiexionghang 已提交
94 95 96
        """
        keep running by statu context.
        """
X
xiexionghang 已提交
97 98 99 100 101
        while True:
            self.reload_train_context()
            self.context_process(self._context)
            if self._context['is_exit']:
                break
T
tangwei 已提交
102 103 104


def user_define_engine(engine_yaml):
X
test  
xjqbest 已提交
105
    _config = envs.load_yaml(engine_yaml)
T
tangwei 已提交
106
    envs.set_runtime_environs(_config)
T
tangwei 已提交
107 108 109 110
    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 已提交
111 112
    trainer_class = envs.lazy_instance_by_fliename(base_name,
                                                   "UserDefineTraining")
T
tangwei 已提交
113
    return trainer_class