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

"""
T
tangwei 已提交
16
Training use fluid with DistributeTranspiler
T
tangwei 已提交
17 18
"""
import os
T
tangwei 已提交
19

T
tangwei 已提交
20
import paddle.fluid as fluid
T
tangwei 已提交
21 22
from paddle.fluid.incubate.fleet.parameter_server.distribute_transpiler import fleet

T
tangwei 已提交
23 24
from fleetrec.core.trainer import Trainer
from fleetrec.core.utils import envs
T
tangwei 已提交
25
from fleetrec.core.utils import dataloader_instance
T
tangwei 已提交
26 27


T
tangwei 已提交
28
class TranspileTrainer(Trainer):
T
tangwei 已提交
29 30
    def __init__(self, config=None):
        Trainer.__init__(self, config)
T
tangwei 已提交
31
        self.processor_register()
T
tangwei 已提交
32
        self.model = None
T
tangwei12 已提交
33 34 35
        self.inference_models = []
        self.increment_models = []

T
tangwei 已提交
36 37
    def processor_register(self):
        print("Need implement by trainer, `self.regist_context_processor('uninit', self.instance)` must be the first")
T
tangwei 已提交
38

T
tangwei 已提交
39 40 41 42 43 44 45 46 47 48
    def _get_dataloader(self):
        namespace = "train.reader"
        dataloader = self.model._data_loader
        batch_size = envs.get_global_env("batch_size", None, namespace)
        reader_class = envs.get_global_env("class", None, namespace)

        reader = dataloader_instance.dataloader(reader_class, "TRAIN", self._config_yaml)
        dataloader.set_sample_generator(reader, batch_size)
        return dataloader

T
tangwei12 已提交
49 50 51
    def _get_dataset(self):
        namespace = "train.reader"

T
bug fix  
tangwei 已提交
52
        inputs = self.model.get_inputs()
T
tangwei 已提交
53
        threads = int(envs.get_runtime_environ("train.trainer.threads"))
T
tangwei12 已提交
54
        batch_size = envs.get_global_env("batch_size", None, namespace)
T
tangwei 已提交
55 56
        reader_class = envs.get_global_env("class", None, namespace)
        abs_dir = os.path.dirname(os.path.abspath(__file__))
T
tangwei 已提交
57
        reader = os.path.join(abs_dir, '../utils', 'dataset_instance.py')
T
tangwei 已提交
58
        pipe_cmd = "python {} {} {} {}".format(reader, reader_class, "TRAIN", self._config_yaml)
T
tangwei12 已提交
59 60
        train_data_path = envs.get_global_env("train_data_path", None, namespace)

T
tangwei 已提交
61 62
        dataset = fluid.DatasetFactory().create_dataset()
        dataset.set_use_var(inputs)
T
tangwei 已提交
63
        dataset.set_pipe_command(pipe_cmd)
T
tangwei 已提交
64 65 66
        dataset.set_batch_size(batch_size)
        dataset.set_thread(threads)
        file_list = [
T
tangwei12 已提交
67 68
            os.path.join(train_data_path, x)
            for x in os.listdir(train_data_path)
T
tangwei 已提交
69 70 71 72 73
        ]

        dataset.set_filelist(file_list)
        return dataset

T
tangwei 已提交
74
    def save(self, epoch_id, namespace, is_fleet=False):
T
tangwei12 已提交
75 76 77
        def need_save(epoch_id, epoch_interval, is_last=False):
            if is_last:
                return True
T
tangwei 已提交
78

T
tangwei12 已提交
79 80
            if epoch_id == -1:
                return False
T
tangwei 已提交
81

T
tangwei12 已提交
82 83
            return epoch_id % epoch_interval == 0

T
tangwei 已提交
84
        def save_inference_model():
T
tangwei12 已提交
85
            save_interval = envs.get_global_env("save.inference.epoch_interval", -1, namespace)
T
tangwei 已提交
86 87 88 89

            if not need_save(epoch_id, save_interval, False):
                return

T
tangwei12 已提交
90 91 92 93 94
            print("save inference model is not supported now.")
            return

            feed_varnames = envs.get_global_env("save.inference.feed_varnames", None, namespace)
            fetch_varnames = envs.get_global_env("save.inference.fetch_varnames", None, namespace)
T
tangwei 已提交
95
            fetch_vars = [fluid.global_scope().vars[varname] for varname in fetch_varnames]
T
tangwei12 已提交
96
            dirname = envs.get_global_env("save.inference.dirname", None, namespace)
T
tangwei 已提交
97 98 99

            assert dirname is not None
            dirname = os.path.join(dirname, str(epoch_id))
T
tangwei 已提交
100 101

            if is_fleet:
T
tangwei 已提交
102
                fleet.save_inference_model(dirname, feed_varnames, fetch_vars)
T
tangwei 已提交
103
            else:
T
tangwei 已提交
104
                fluid.io.save_inference_model(dirname, feed_varnames, fetch_vars, self._exe)
T
tangwei12 已提交
105
            self.inference_models.append((epoch_id, dirname))
T
tangwei 已提交
106 107

        def save_persistables():
T
tangwei12 已提交
108
            save_interval = envs.get_global_env("save.increment.epoch_interval", -1, namespace)
T
tangwei 已提交
109 110 111 112

            if not need_save(epoch_id, save_interval, False):
                return

T
tangwei12 已提交
113
            dirname = envs.get_global_env("save.increment.dirname", None, namespace)
T
tangwei 已提交
114 115 116

            assert dirname is not None
            dirname = os.path.join(dirname, str(epoch_id))
T
tangwei 已提交
117 118

            if is_fleet:
T
tangwei 已提交
119
                fleet.save_persistables(self._exe, dirname)
T
tangwei 已提交
120
            else:
T
tangwei 已提交
121
                fluid.io.save_persistables(self._exe, dirname)
T
tangwei12 已提交
122
            self.increment_models.append((epoch_id, dirname))
T
tangwei 已提交
123 124 125 126

        save_persistables()
        save_inference_model()

T
tangwei 已提交
127 128
    def instance(self, context):
        models = envs.get_global_env("train.model.models")
T
bug fix  
tangwei 已提交
129
        model_class = envs.lazy_instance(models, "Model")
T
tangwei 已提交
130
        self.model = model_class(None)
T
tangwei 已提交
131
        context['status'] = 'init_pass'
T
tangwei 已提交
132

T
tangwei 已提交
133 134 135
    def init(self, context):
        print("Need to be implement")
        context['is_exit'] = True
T
tangwei 已提交
136

T
tangwei 已提交
137 138 139 140 141
    def dataloader_train(self, context):
        print("Need to be implement")
        context['is_exit'] = True

    def dataset_train(self, context):
T
tangwei 已提交
142 143
        print("Need to be implement")
        context['is_exit'] = True
T
tangwei 已提交
144

T
tangwei12 已提交
145
    def infer(self, context):
T
tangwei 已提交
146
        context['is_exit'] = True
T
tangwei12 已提交
147 148

    def terminal(self, context):
T
tangwei 已提交
149
        print("clean up and exit")
T
tangwei12 已提交
150
        context['is_exit'] = True