trainer.py 6.8 KB
Newer Older
H
Helin Wang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2018 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.

Y
Yu Yang 已提交
15 16 17 18 19 20 21 22 23
import core
import framework
import executor
import data_feeder
import contextlib

# optimizer is same as the parameter of Trainer.__init__. Rename it to opt_module
import optimizer as opt_module

H
Helin Wang 已提交
24 25
__all__ = [
    'Trainer',
Y
Yu Yang 已提交
26 27 28 29
    'BeginEpochEvent',
    'EndEpochEvent',
    'BeginStepEvent',
    'EndStepEvent',
H
Helin Wang 已提交
30 31 32
]


Y
Yu Yang 已提交
33 34 35 36 37 38 39 40
class BeginEpochEvent(object):
    def __init__(self, epoch_id):
        self.epoch = epoch_id


class EndEpochEvent(object):
    def __init__(self, epoch_id):
        self.epoch = epoch_id
H
Helin Wang 已提交
41

Y
Yu Yang 已提交
42 43 44 45 46 47 48 49 50 51 52

class BeginStepEvent(object):
    def __init__(self, epoch_id, step_id):
        self.epoch = epoch_id
        self.step = step_id


class EndStepEvent(object):
    def __init__(self, epoch_id, step_id):
        self.epoch = epoch_id
        self.step = step_id
H
Helin Wang 已提交
53 54 55


class Trainer(object):
Y
Yu Yang 已提交
56 57 58 59 60 61 62 63 64
    """

    Args:
        network_func(callable): A function which will return loss. The loss must be a scaler.
        optimizer(optimizer.Optimizer): The optimizer should be an instance of Optimizer
        params:
        place: The device place of this trainer.
    """

H
Helin Wang 已提交
65
    def __init__(self, network_func, optimizer, params=None, place=None):
H
Helin Wang 已提交
66 67 68
        # 1. we need to generate a framework.Program by calling
        # network_func. Reference: fluid.program_guard in
        # test_word2vec.py
Y
Yu Yang 已提交
69 70 71 72 73 74 75 76 77 78 79 80 81 82
        self.scope = self._get_scope_from_params(params)

        self.startup_program = framework.Program()
        self.train_program = framework.Program()

        with framework.program_guard(self.train_program, self.startup_program):
            loss = network_func()
            if not isinstance(optimizer, opt_module.Optimizer):
                raise TypeError(
                    "The optimizer should be an instance of Optimizer")

            optimizer.minimize(loss)

        self.place = Trainer._check_and_get_place(place)
H
Helin Wang 已提交
83 84 85

        # 2. move the default_main_program to self.program and run the
        # default_startup program on an empty core.Scope()
Y
Yu Yang 已提交
86 87 88 89
        # Run startup program
        if params is None:
            exe = executor.Executor(place)
            exe.run(self.startup_program, scope=self.scope)
H
Helin Wang 已提交
90 91 92 93

        # 3. call self.params.add_vars with the initialized scope, it
        # will add the new vars of the initialized scope into
        # self.params.
Y
Yu Yang 已提交
94 95
        # TODO(yuyang): This depends on parameters implementation.

H
Helin Wang 已提交
96
        # TODO(helin): support distributed training
H
Helin Wang 已提交
97

Y
Yu Yang 已提交
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
    def train(self,
              num_epochs,
              event_handler,
              reader=None,
              parallel=False,
              feed_order=None):
        """
        Train the model.

        Args:
            num_epochs: The number of epoch. An epoch will process all data in reader
            event_handler: The event handler. A function with type (ev:Event)->void
            reader:
            parallel: True if use multi-CPUs or multi-GPUs
            feed_order: Feeding order of reader. None will following the defining
                order in program

        Returns:

        """
        if parallel:
            raise NotImplementedError(
                "Parallel Executor version of trainer is not implemented")

        self._train_by_executor(num_epochs, event_handler, reader, feed_order)
H
Helin Wang 已提交
123 124 125

    def test(self, reader):
        pass
Y
Yu Yang 已提交
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 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211

    def _get_scope_from_params(self, params):
        """
        Get Scope from parameter object.
        Args:
            params(Parameter|None): The parameter object instance. Could be None.

        Returns: New scope if params is None. Or params.scope()
        NOTE: This method is WIP. Not fully implemented.
        """
        if params is None:
            return core.Scope()  # new scope when params is None
        else:
            raise NotImplementedError("Not implemented right now.")

    @staticmethod
    def _check_and_get_place(place):
        """
        Check the type of place or get the default place
        Args:
            place(None|core.CUDAPlace|core.CPUPlace): the place that trainer will be executed on.

        Raises:
            TypeError if the type mismatched.

        Returns:
            the original place if it is not None.
            if fluid is compiled with CUDA, returns CUDAPlace(0) by default.
            Otherwise returns CPUPlace by default.
        """
        if place is None:
            if core.is_compiled_with_cuda():
                return core.CUDAPlace(0)
            else:
                return core.CPUPlace()
        else:
            if not isinstance(place, core.CUDAPlace) and not isinstance(
                    place, core.CPUPlace):
                raise TypeError("Place should be either CUDAPlace or CPUPlace")
            return place

    @contextlib.contextmanager
    def _prog_and_scope_guard(self):
        with framework.program_guard(
                main_program=self.train_program,
                startup_program=self.startup_program):
            with executor.scope_guard(self.scope):
                yield

    def _train_by_executor(self, num_epochs, event_handler, reader, feed_order):
        """
        Train by Executor and single device.

        Args:
            num_epochs:
            event_handler:
            reader:
            feed_order:

        Returns:

        """
        with self._prog_and_scope_guard():
            exe = executor.Executor(self.place)
            if feed_order is None:
                feed_var_list = [
                    var
                    for var in self.train_program.global_block(
                    ).vars.itervalues()
                    if hasattr(var, 'is_data') and var.is_data
                ]
            else:
                feed_var_list = [
                    self.train_program.global_block().var(var_name)
                    for var_name in feed_order
                ]

            feeder = data_feeder.DataFeeder(
                feed_list=feed_var_list, place=self.place)
            for epoch_id in range(num_epochs):
                event_handler(BeginEpochEvent(epoch_id))
                for step_id, data in enumerate(reader()):
                    event_handler(BeginStepEvent(epoch_id, step_id))
                    exe.run(feed=feeder.feed(data), fetch_list=[])
                    event_handler(EndStepEvent(epoch_id, step_id))
                event_handler(EndEpochEvent(epoch_id))