trainer.py 8.5 KB
Newer Older
Q
qijun 已提交
1
"""
Q
qijun 已提交
2
Module Trainer
Q
qijun 已提交
3
"""
Y
Yu Yang 已提交
4
import collections
Q
qiaolongfei 已提交
5 6
import gzip
import os
Y
Yu Yang 已提交
7

Y
Yu Yang 已提交
8 9
import py_paddle.swig_paddle as api

10
from data_feeder import DataFeeder
Q
qiaolongfei 已提交
11
from topology import Topology
Q
qiaolongfei 已提交
12
from . import event as v2_event
Y
Yu Yang 已提交
13 14 15
from . import optimizer as v2_optimizer
from . import parameters as v2_parameters

16
__all__ = ['SGD']
Q
qijun 已提交
17

Y
Yu Yang 已提交
18 19

def default_event_handler(event):
Y
Yu Yang 已提交
20 21 22 23 24 25 26
    """
    Default event handler. It will print some log and save mode.

    TODO(yuyang18): Complete it!
    :param event:
    :return:
    """
Y
Yu Yang 已提交
27 28 29
    pass


Y
Yu Yang 已提交
30 31 32
class SGD(object):
    """
    Simple SGD Trainer.
Q
qijun 已提交
33 34
    SGD Trainer combines data reader, network topolopy and update_equation together
    to train/test a neural network.
Y
Yu Yang 已提交
35 36 37 38 39 40 41

    :param update_equation: The optimizer object.
    :type update_equation: paddle.v2.optimizer.Optimizer
    :param cost: Target cost that neural network should be optimized.
    :type cost: paddle.v2.config_base.Layer
    :param parameters: The parameters dictionary.
    :type parameters: paddle.v2.parameters.Parameters
D
dangqingqing 已提交
42 43
    :param extra_layers: Some layers in the neural network graph are not
                         in the path of cost layer.
W
wuyi05 已提交
44
    :param pserver_spec: pserver location, eg: localhost:3000
D
dangqingqing 已提交
45
    :type extra_layers: paddle.v2.config_base.Layer
Y
Yu Yang 已提交
46
    """
Y
Yu Yang 已提交
47

Q
qiaolongfei 已提交
48 49 50 51 52
    def __init__(self,
                 cost,
                 parameters,
                 update_equation,
                 extra_layers=None,
53 54
                 is_local=True,
                 pserver_spec=None):
55

Y
Yu Yang 已提交
56 57 58
        if not isinstance(parameters, v2_parameters.Parameters):
            raise TypeError('parameters should be parameters')

Y
Yu Yang 已提交
59
        if not isinstance(update_equation, v2_optimizer.Optimizer):
Y
Yu Yang 已提交
60 61
            raise TypeError("update equation parameter must be "
                            "paddle.v2.optimizer.Optimizer")
62
        topology = Topology(cost, extra_layers=extra_layers)
Y
Yu Yang 已提交
63
        self.__optimizer__ = update_equation
Y
Yu Yang 已提交
64 65
        self.__topology__ = topology
        self.__parameters__ = parameters
66
        self.__topology_in_proto__ = topology.proto()
Q
qiaolongfei 已提交
67
        self.__is_local__ = is_local
68
        self.__pserver_spec__ = pserver_spec
69

Q
qiaolongfei 已提交
70 71 72 73 74 75
        self.__use_sparse_updater__ = self.__topology__.use_sparse_updater()
        # # In local mode, disable sparse_remote_update.
        if is_local:
            for param in self.__topology_in_proto__.parameters:
                if param.sparse_remote_update:
                    param.sparse_remote_update = False
76

Q
qiaolongfei 已提交
77 78
        self.__gm_create_mode__ = api.CREATE_MODE_NORMAL if not \
            self.__use_sparse_updater__ else api.CREATE_MODE_SGD_SPARSE_CPU_TRAINING
Y
Yu Yang 已提交
79
        self.__data_types__ = topology.data_type()
Y
Yu Yang 已提交
80
        gm = api.GradientMachine.createFromConfigProto(
Q
qiaolongfei 已提交
81
            self.__topology_in_proto__, self.__gm_create_mode__,
Y
Yu Yang 已提交
82 83 84 85
            self.__optimizer__.enable_types())
        assert isinstance(gm, api.GradientMachine)
        self.__gradient_machine__ = gm
        self.__gradient_machine__.randParameters()
Q
qiaolongfei 已提交
86
        self.__parameters__.append_gradient_machine(gm)
Q
qiaolongfei 已提交
87 88
        self.__parameter_updater__ = None

Q
qiaolongfei 已提交
89
    def __use_remote_sparse_updater__(self):
Q
qiaolongfei 已提交
90
        return self.__use_sparse_updater__ and not self.__is_local__
Y
Yu Yang 已提交
91

Q
qiaolongfei 已提交
92 93 94 95 96 97 98 99 100 101 102 103
    def __prepare_parameter__(self, in_args):
        """
        prepare parameter before forward backward.
        1. When use remote sparse updater, parameters should be got
        from ps according to input arguments.
        :param in_args: input arguments of this batch.
        :return:
        """
        if self.__use_remote_sparse_updater__():
            self.__gradient_machine__.prefetch(in_args)
            self.__parameter_updater__.getParametersRemote()

Q
qiaolongfei 已提交
104
    def save_parameter_to_tar(self, f):
Q
qiaolongfei 已提交
105 106 107
        self.__parameter_updater__.catchUpWith()
        self.__parameter_updater__.apply()
        self.__parameter_updater__.getParametersRemote(True, True)
Q
qiaolongfei 已提交
108
        self.__parameters__.to_tar(f)
Q
qiaolongfei 已提交
109
        self.__parameter_updater__.restore()
Y
Yu Yang 已提交
110

Y
Yu Yang 已提交
111
    def train(self, reader, num_passes=1, event_handler=None, feeding=None):
Y
Yu Yang 已提交
112 113 114
        """
        Training method. Will train num_passes of input data.

Q
qijun 已提交
115 116 117
        :param reader: A reader that reads and yeilds data items. Usually we use a
                       batched reader to do mini-batch training.
        :type reader: collections.Iterable
Y
Yu Yang 已提交
118 119 120 121
        :param num_passes: The total train passes.
        :param event_handler: Event handler. A method will be invoked when event
                              occurred.
        :type event_handler: (BaseEvent) => None
Y
Yu Yang 已提交
122 123
        :param feeding: Feeding is a map of neural network input name and array
                        index that reader returns.
Y
Yu Yang 已提交
124
        :type feeding: dict|list
Y
Yu Yang 已提交
125 126
        :return:
        """
Y
Yu Yang 已提交
127 128 129 130
        if event_handler is None:
            event_handler = default_event_handler
        __check_train_args__(**locals())

Q
qiaolongfei 已提交
131
        self.__parameter_updater__ = self.__optimizer__.create_updater(
132 133
            self.__is_local__, num_passes, self.__use_sparse_updater__,
            self.__pserver_spec__)
Q
qiaolongfei 已提交
134
        self.__parameter_updater__.init(self.__gradient_machine__)
Y
Yu Yang 已提交
135

Y
Yu Yang 已提交
136 137
        self.__gradient_machine__.start()
        batch_evaluator = self.__gradient_machine__.makeEvaluator()
Y
Yu Yang 已提交
138
        assert isinstance(batch_evaluator, api.Evaluator)
Y
Yu Yang 已提交
139
        pass_evaluator = self.__gradient_machine__.makeEvaluator()
Y
Yu Yang 已提交
140
        assert isinstance(pass_evaluator, api.Evaluator)
Y
Yu Yang 已提交
141
        out_args = api.Arguments.createArguments(0)
Y
Yu Yang 已提交
142
        feeder = DataFeeder(self.__data_types__, feeding)
Y
Yu Yang 已提交
143
        for pass_id in xrange(num_passes):
Y
Yu Yang 已提交
144 145
            event_handler(v2_event.BeginPass(pass_id))
            pass_evaluator.start()
Q
qiaolongfei 已提交
146
            self.__parameter_updater__.startPass()
Y
Yu Yang 已提交
147
            for batch_id, data_batch in enumerate(reader()):
Y
Yu Yang 已提交
148 149 150 151
                batch_evaluator.start()
                event_handler(
                    v2_event.BeginIteration(
                        pass_id=pass_id, batch_id=batch_id))
Q
qiaolongfei 已提交
152 153
                pass_type = self.__parameter_updater__.startBatch(
                    len(data_batch))
Q
qiaolongfei 已提交
154
                in_args = feeder(data_batch)
Q
qiaolongfei 已提交
155
                self.__prepare_parameter__(in_args)
Q
qiaolongfei 已提交
156 157
                self.__gradient_machine__.forwardBackward(in_args, out_args,
                                                          pass_type)
Y
Yu Yang 已提交
158 159
                self.__gradient_machine__.eval(pass_evaluator)
                self.__gradient_machine__.eval(batch_evaluator)
L
liaogang 已提交
160 161
                for each_param in self.__gradient_machine__.getNonStaticParameters(
                ):
Q
qiaolongfei 已提交
162
                    self.__parameter_updater__.update(each_param)
Y
Yu Yang 已提交
163
                cost_sum = out_args.sum()
Y
Yu Yang 已提交
164
                cost = cost_sum / len(data_batch)
Q
qiaolongfei 已提交
165
                self.__parameter_updater__.finishBatch(cost)
Y
Yu Yang 已提交
166
                batch_evaluator.finish()
Y
Yu Yang 已提交
167
                event_handler(
Y
Yu Yang 已提交
168
                    v2_event.EndIteration(
Y
Yu Yang 已提交
169 170 171 172
                        pass_id=pass_id,
                        batch_id=batch_id,
                        cost=cost,
                        evaluator=batch_evaluator))
Y
Yu Yang 已提交
173

Q
qiaolongfei 已提交
174
            self.__parameter_updater__.finishPass()
Y
Yu Yang 已提交
175 176
            pass_evaluator.finish()
            event_handler(v2_event.EndPass(pass_id, evaluator=pass_evaluator))
Y
Yu Yang 已提交
177 178
        self.__gradient_machine__.finish()

Y
Yu Yang 已提交
179
    def test(self, reader, feeding=None):
Q
qijun 已提交
180 181 182 183
        """
        Testing method. Will test input data.

        :param reader: A reader that reads and yeilds data items.
X
xuwei06 已提交
184
        :type reader: collections.Iterable
Q
qijun 已提交
185 186 187 188 189
        :param feeding: Feeding is a map of neural network input name and array
                        index that reader returns.
        :type feeding: dict
        :return:
        """
Y
Yu Yang 已提交
190
        feeder = DataFeeder(self.__data_types__, feeding)
Y
Yu Yang 已提交
191 192 193
        evaluator = self.__gradient_machine__.makeEvaluator()
        out_args = api.Arguments.createArguments(0)
        evaluator.start()
Y
Yu Yang 已提交
194 195
        total_cost = 0
        num_samples = 0.0
Y
Yu Yang 已提交
196
        for data_batch in reader():
Y
Yu Yang 已提交
197
            num_samples += len(data_batch)
Q
qiaolongfei 已提交
198
            in_args = feeder(data_batch)
Q
qiaolongfei 已提交
199
            self.__prepare_parameter__(in_args)
Q
qiaolongfei 已提交
200
            self.__gradient_machine__.forward(in_args, out_args, api.PASS_TEST)
Y
Yu Yang 已提交
201
            total_cost += out_args.sum()
Y
Yu Yang 已提交
202
            self.__gradient_machine__.eval(evaluator)
Y
Yu Yang 已提交
203

Y
Yu Yang 已提交
204
        evaluator.finish()
Y
Yu Yang 已提交
205 206
        return v2_event.TestResult(
            evaluator=evaluator, cost=total_cost / num_samples)
Y
Yu Yang 已提交
207 208 209


def __check_train_args__(reader, event_handler, **kwargs):
Y
Yu Yang 已提交
210 211 212
    """
    Check train function's argument types
    """
Y
Yu Yang 已提交
213
    if not callable(reader) or not isinstance(reader(), collections.Iterator):
Y
Yu Yang 已提交
214 215
        raise TypeError('train_data_reader should be a function, '
                        'which can return a iterator')
Y
Yu Yang 已提交
216
    if not callable(event_handler):
Y
Yu Yang 已提交
217
        raise TypeError('event handler should be a function')