trainer.py 21.8 KB
Newer Older
C
chenxuyi 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
#   Copyright (c) 2019 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.
C
chenxuyi 已提交
14
"""common ML train and eval procedure"""
C
chenxuyi 已提交
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals

import os
import itertools
import six
import inspect
from collections import namedtuple
from contextlib import contextmanager
from six.moves import zip, map
import logging
from time import time

import paddle.fluid as F
import paddle.fluid.layers as L

C
chenxuyi 已提交
32 33
from propeller.types import RunMode, StopException, SummaryRecord, StopException
from propeller.types import ModelSpec, InferenceSpec, ProgramPair, RunConfig
C
chenxuyi 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47
from propeller.paddle import summary, collection
from propeller.paddle.data.functional import Dataset
from propeller.paddle.train import distribution
from propeller.train.model import Model
from propeller.paddle.train.monitored_executor import Saver
from propeller.paddle.train import hooks, metrics

from propeller.paddle.train.monitored_executor import MonitoredExecutor

log = logging.getLogger(__name__)

__all__ = ['train_and_eval', 'Learner']


C
chenxuyi 已提交
48
def _get_summary_writer(path):
C
chenxuyi 已提交
49 50 51 52 53 54 55 56 57 58
    summary_writer = None
    try:
        from tensorboardX import SummaryWriter
        if distribution.status.is_master:
            summary_writer = SummaryWriter(os.path.join(path))
    except ImportError:
        log.warning('tensorboardX not installed, will not log to tensorboard')
    return summary_writer


C
chenxuyi 已提交
59 60 61 62 63 64
def _get_one_place():
    return F.cuda_places()[0] if F.core.is_compiled_with_cuda(
    ) else F.cpu_places()[0]


def _log_eval_result(name, eval_result, swriter, state):
C
chenxuyi 已提交
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
    log.debug(eval_result)
    printable = []
    for n, val in six.iteritems(eval_result):
        assert val.shape == (), 'metrics eval use float'
        printable.append('{}\t{}'.format(n, val))
        if swriter is not None:
            swriter.add_scalar(n, val, state.gstep)
            log.debug('write to tensorboard %s' % swriter.logdir)

    if len(printable):
        log.info('*** eval res: %10s ***' % name)
        for p in printable:
            log.info(p)
        log.info('******************************')


C
chenxuyi 已提交
81
def _build_net(model_fn, features, mode, params, run_config):
C
chenxuyi 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
    model_spec = model_fn(
        features=features, mode=mode, params=params, run_config=run_config)

    if mode == RunMode.TRAIN:
        if not isinstance(model_spec.loss, F.framework.Variable):
            raise ValueError('model_spec.metrics should be Variable, got %s' %
                             repr(model_spec.loss))
        if not (model_spec.loss.shape == () or model_spec.loss.shape == (1, )):
            raise ValueError('expect scarlar loss, got %s' %
                             repr(model_spec.loss.shape))
        model_spec.loss.persistable = True
    elif mode == RunMode.EVAL:
        if not isinstance(model_spec.metrics, dict):
            raise ValueError('model_spec.metrics should be dict, got %s' %
                             repr(model_spec.metrics))
    elif mode == RunMode.PREDICT:
        if not isinstance(model_spec.predictions, (list, tuple)):
            raise ValueError('model_spec.predictions shuold be list, got %s' %
                             repr(model_spec.predictions))
    else:
        raise ValueError('unkonw mode %s' % mode)
    return model_spec


class Learner(object):
C
chenxuyi 已提交
107 108
    """A Learner can train / eval / predict on a Dataset"""

C
chenxuyi 已提交
109 110 111 112 113
    def __init__(self,
                 model_class_or_model_fn,
                 run_config,
                 params=None,
                 warm_start_setting=None):
C
chenxuyi 已提交
114
        """
C
chenxuyi 已提交
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
        model_class_or_model_fn(callable|propeller.train.Model): `model_class_or_model_fn` be specified in 2 ways:
            1. subclass of propeller.train.Model which implements:
                1. \_\_init\_\_       (hyper_param, mode, run_config)
                2. forward            (features) => (prediction)
                3. backword           (loss) => None
                4. loss               (predictoin) => (loss)
                5. metrics (optional) (prediction) => (dict of propeller.Metrics)
                
            2. a model_fn takes following args:
                1. features
                2. param
                3. mode
                4. run_config(optional)
               and returns a `propeller.ModelSpec`

        params: any python object, will pass to your `model_fn` or `propeller.train.Model`
        run_config (propeller.RunConfig): run_config.max_steps should not be None.
        warm_start_setting (propeller.WarmStartSetting): Optional. warm start variable will overwrite model variable.
C
chenxuyi 已提交
133
        """
C
chenxuyi 已提交
134 135 136 137
        if run_config.model_dir is None:
            raise ValueError('model_dir should specified in run_config')

        if issubclass(model_class_or_model_fn, Model):
C
chenxuyi 已提交
138
            _model_fn = _build_model_fn(model_class_or_model_fn)
C
chenxuyi 已提交
139
        elif inspect.isfunction(model_class_or_model_fn):
C
chenxuyi 已提交
140
            _model_fn = model_class_or_model_fn
C
chenxuyi 已提交
141 142 143
        else:
            raise ValueError('unknown model %s' % model_class_or_model_fn)

C
chenxuyi 已提交
144
        self.model_fn = _model_fn
C
chenxuyi 已提交
145 146 147 148
        self.params = params
        self.run_config = run_config
        self.warm_start_setting = warm_start_setting

C
chenxuyi 已提交
149
    def _build_for_train(self, train_dataset):
C
chenxuyi 已提交
150 151 152 153 154 155 156 157
        train_dataset.name = 'train'
        train_program = F.Program()
        startup_prog = F.Program()
        with F.program_guard(train_program, startup_prog):
            with F.unique_name.guard():
                with collection.Collections() as collections:
                    log.info('Building Train Graph...')
                    fea = train_dataset.features()
C
chenxuyi 已提交
158 159
                    model_spec = _build_net(self.model_fn, fea, RunMode.TRAIN,
                                            self.params, self.run_config)
C
chenxuyi 已提交
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
                    log.info('Building Train Graph: Done')

                scalars = collections.get(collection.Key.SUMMARY_SCALAR)
                histograms = collections.get(collection.Key.SUMMARY_HISTOGRAM)
                skip_optimize_ops = collections.get(
                    collection.Key.SKIP_OPTIMIZE)
                skip_opt = set()
                if skip_optimize_ops is not None:
                    skip_opt |= set(skip_optimize_ops)
                if scalars is not None:
                    skip_opt |= {t for _, t in scalars}
                if histograms is not None:
                    skip_opt |= {t for _, t in histograms}
                skip_opt = list(skip_opt)
        log.info(
            'Train with: \n> Run_config: %s\n> Params: %s\n> Train_model_spec: %s\n'
            % (repr(self.run_config), repr(self.params), repr(model_spec)))

        summary_record = SummaryRecord(
            scalar=collections.get(collection.Key.SUMMARY_SCALAR),
            histogram=collections.get(collection.Key.SUMMARY_HISTOGRAM), )
        return ProgramPair(
            train_program=train_program,
            startup_program=startup_prog), model_spec, summary_record

C
chenxuyi 已提交
185
    def _build_for_eval(self, ds):
C
chenxuyi 已提交
186 187 188 189 190 191 192 193
        ds.name = 'eval'
        program = F.Program()
        startup_prog = F.Program()
        with F.program_guard(program, startup_prog):
            #share var with Train net
            with F.unique_name.guard():
                log.info('Building Eval Graph')
                fea = ds.features()
C
chenxuyi 已提交
194 195
                model_spec = _build_net(self.model_fn, fea, RunMode.EVAL,
                                        self.params, self.run_config)
C
chenxuyi 已提交
196 197 198 199 200 201 202 203
                log.info('Done')
        program = program.clone(for_test=True)
        log.info(
            'Eval with: \n> Run_config: %s\n> Params: %s\n> Train_model_spec: %s\n'
            % (repr(self.run_config), repr(self.params), repr(model_spec)))
        return ProgramPair(
            train_program=program, startup_program=startup_prog), model_spec

C
chenxuyi 已提交
204
    def _build_for_predict(self, ds):
C
chenxuyi 已提交
205 206 207 208 209 210 211 212
        ds.name = 'predict'
        program = F.Program()
        startup_prog = F.Program()
        with F.program_guard(program, startup_prog):
            #share var with Train net
            with F.unique_name.guard():
                log.info('Building Predict Graph')
                fea = ds.features()
C
chenxuyi 已提交
213 214
                model_spec = _build_net(self.model_fn, fea, RunMode.PREDICT,
                                        self.params, self.run_config)
C
chenxuyi 已提交
215 216 217 218 219 220 221 222 223 224 225
                log.info('Done')

        program = program.clone(for_test=True)

        log.info(
            'Predict with: \n> Run_config: %s\n> Params: %s\n> Train_model_spec: %s\n'
            % (repr(self.run_config), repr(self.params), repr(model_spec)))
        return ProgramPair(
            train_program=program, startup_program=startup_prog), model_spec

    def train(self, train_ds, train_hooks=[]):
C
chenxuyi 已提交
226
        """train on a `Dataset`"""
C
chenxuyi 已提交
227 228 229 230
        if not isinstance(train_ds, Dataset):
            raise ValueError('expect dataset to be instance of Dataset, got %s'
                             % repr(train_ds))

C
chenxuyi 已提交
231
        train_program, model_spec, summary_record = self._build_for_train(
C
chenxuyi 已提交
232 233 234 235 236 237 238
            train_ds)
        train_run_hooks = [
            hooks.StopAtStepHook(self.run_config.max_steps,
                                 self.run_config.run_steps),
            hooks.LoggingHook(
                model_spec.loss,
                summary_record=summary_record,
C
chenxuyi 已提交
239
                summary_writer=_get_summary_writer(
C
chenxuyi 已提交
240 241 242 243
                    os.path.join(self.run_config.model_dir, 'train_history')),
                per_step=self.run_config.log_steps,
                skip_step=self.run_config.skip_steps),
        ]
C
chenxuyi 已提交
244 245
        if model_spec.train_hooks is not None:
            train_run_hooks.extend(model_spec.train_hooks)
C
chenxuyi 已提交
246
        train_run_hooks.extend(train_hooks)
C
chenxuyi 已提交
247 248

        train_executor = F.Executor(_get_one_place())
C
chenxuyi 已提交
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277

        mon_exe = MonitoredExecutor(
            train_executor,
            train_program,
            loss=model_spec.loss,
            run_config=self.run_config,
            run_hooks=train_run_hooks,
            warm_start_setting=self.warm_start_setting)

        distribution.init_distribuition_env(
            train_program)  #only initialize distribute training with 
        mon_exe.init_or_restore_variables()
        if distribution.status.is_master:
            mon_exe._hooks.append(
                hooks.CheckpointSaverHook(
                    mon_exe._saver,
                    per_step=mon_exe._save_steps,
                    skip_step=mon_exe._skip_steps))

        try:
            with mon_exe:
                for data in train_ds.start():
                    mon_exe.run(feed=data)
        except (StopException, F.core.EOFException) as e:
            pass

        return mon_exe.result

    def evaluate(self, eval_dataset, eval_hooks=[]):
C
chenxuyi 已提交
278
        """eval on a `Dataset`"""
C
chenxuyi 已提交
279 280 281
        if not isinstance(eval_dataset, Dataset):
            raise ValueError('expect dataset to be instance of Dataset, got %s'
                             % repr(eval_dataset))
C
chenxuyi 已提交
282 283
        program, model_spec = self._build_for_eval(eval_dataset)
        single_card_place = _get_one_place()
C
chenxuyi 已提交
284 285
        eval_executor = F.Executor(single_card_place)

C
chenxuyi 已提交
286
        eval_run_hooks = [
C
chenxuyi 已提交
287 288 289 290 291
            hooks.StopAtStepHook(self.run_config.eval_max_steps,
                                 self.run_config.eval_max_steps),
            hooks.EvalHook(model_spec.metrics, )
        ]

C
chenxuyi 已提交
292 293 294 295
        if model_spec.eval_hooks is not None:
            eval_run_hooks.extend(model_spec.eval_hooks)
        eval_run_hooks.extend(eval_hooks)

C
chenxuyi 已提交
296 297 298 299
        mon_exe = MonitoredExecutor(
            eval_executor,
            program,
            run_config=self.run_config,
C
chenxuyi 已提交
300
            run_hooks=eval_run_hooks)
C
chenxuyi 已提交
301 302 303 304 305 306 307 308 309 310 311
        mon_exe.init_or_restore_variables()

        try:
            with mon_exe:
                for data in eval_dataset.start(places=[single_card_place]):
                    mon_exe.run(feed=data)
        except (StopException, F.core.EOFException) as e:
            pass

        _, eval_result = mon_exe.result

C
chenxuyi 已提交
312
        summary_writer = _get_summary_writer(
C
chenxuyi 已提交
313
            os.path.join(self.run_config.model_dir, 'eval_history'))
C
chenxuyi 已提交
314
        _log_eval_result('eval', eval_result, summary_writer, mon_exe.state)
C
chenxuyi 已提交
315 316 317

        return mon_exe.result

C
chenxuyi 已提交
318 319 320 321 322 323 324
    def predict(self,
                predict_dataset,
                ckpt=-1,
                ckpt_path=None,
                steps=-1,
                split_batch=True):
        """
C
chenxuyi 已提交
325 326 327 328 329
        Perform predictoin
        will call `model_fn` and initiate user-specifed model in `propeller.RunMode.PREDICT` mode 

        Args:
            infer_dataset (propeller.data.Dataset): should not `shuffle` or `repeat`
C
chenxuyi 已提交
330 331 332 333 334 335 336
            steps (int): steps to predict, if None is specifed, 
                will stop when `StopException` is raised in `infer_dataset`
            ckpt_path (None|str): Path of a specific checkpoint to predict. 
                If None, the latest checkpoint in model_dir is used. 
                If there are no checkpoints in model_dir, 
                prediction is run with newly initialized Variables instead of ones restored from checkpoint.
            ckpt (int): deprecated args
C
chenxuyi 已提交
337 338 339 340 341
            split_batch (bool): if True, prediction of each example in a batch is returned.

        Yields:
            Evaluated values of predictions tensors.

C
chenxuyi 已提交
342
        """
C
chenxuyi 已提交
343 344 345 346
        if not isinstance(predict_dataset, Dataset):
            raise ValueError('expect dataset to be instance of Dataset, got %s'
                             % repr(predict_dataset))

C
chenxuyi 已提交
347 348
        program, model_spec = self._build_for_predict(predict_dataset)
        single_card_place = _get_one_place()
C
chenxuyi 已提交
349 350 351 352 353 354 355 356
        executor = F.Executor(single_card_place)
        pred_run_config = RunConfig(
            run_steps=steps if steps == -1 else None,
            model_dir=self.run_config.model_dir)
        mon_exe = MonitoredExecutor(
            executor,
            program,
            run_config=pred_run_config, )
C
chenxuyi 已提交
357 358
        mon_exe.init_or_restore_variables(ckpt
                                          if ckpt_path is None else ckpt_path)
C
chenxuyi 已提交
359 360 361
        try:
            with mon_exe:
                log.info('Runining predict from dir: %s' % repr(mon_exe.state))
C
chenxuyi 已提交
362
                single_card_place = _get_one_place()
C
chenxuyi 已提交
363 364 365 366 367 368 369 370 371 372 373 374 375 376
                for data in predict_dataset.start(places=[single_card_place]):
                    res = mon_exe.run(fetch_list=model_spec.predictions,
                                      feed=data)
                    if split_batch:
                        res = map(lambda i: i.tolist(), res)
                        res = zip(*res)  # transpose
                        for r in res:
                            yield r
                    else:
                        yield list(map(lambda i: i.tolist(), res))
        except (StopException, F.core.EOFException) as e:
            pass


C
chenxuyi 已提交
377
def train_and_eval(_placeholder=None,
C
chenxuyi 已提交
378 379 380 381 382 383 384 385 386
                   model_class_or_model_fn=None,
                   params=None,
                   run_config=None,
                   train_dataset=None,
                   eval_dataset=None,
                   warm_start_setting=None,
                   train_hooks=[],
                   eval_hooks=[],
                   exporters=[]):
C
chenxuyi 已提交
387
    """
C
chenxuyi 已提交
388 389 390 391 392
    Perform train and evaluate procesure. 
    will call `model_fn` and initiate user-specifed model in `propeller.RunMode.PREDICT` mode 

    Args:
        model_class_or_model_fn(callable|propeller.train.Model): `model_class_or_model_fn` be specified in 2 ways:
C
chenxuyi 已提交
393 394
            1. subclass of propeller.train.Model
            2. a model_fn takes following args: 1. features; 2. param; 3. mode; 4. run_config(optional)
C
chenxuyi 已提交
395 396 397 398 399
               and returns a `propeller.ModelSpec`

        params: any python object, will pass to your `model_fn` or `propeller.train.Model`
        run_config (propeller.RunConfig): run_config.max_steps should not be None.
        train_dataset (propeller.paddle.data.Dataset): training will stop if global_step > run_config.max_steps.
C
chenxuyi 已提交
400 401
        eval_dataset (propeller.paddle.data.Dataset|dict): Optional, if Dict of propeller.data.Dataset were specified, 
            will perform evluatation on every evaluation sets and report results.
C
chenxuyi 已提交
402 403 404 405
        warm_start_setting (propeller.WarmStartSetting): Optional. warm start variable will overwrite model variable.
        train_hooks (list of propeller.paddle.train.RunHook): Optional.
        eval_hooks (list of propeller.paddle.train.RunHook): Optional.
        exporters (list of propeller.paddle.train.Exporter): Optional.
C
chenxuyi 已提交
406 407
    """
    if _placeholder is not None:
C
chenxuyi 已提交
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
        raise ValueError('specify keyword args to this function')
    if model_class_or_model_fn is None or params is None or run_config is None or train_dataset is None:
        raise ValueError(
            'some argument is None: model_class_or_model_fn:%s params:%s run_config:%s train_dataset:%s'
            % (model_class_or_model_fn, params, run_config, train_dataset))

    #init distribution env if envvir PROPELLER_DISCONFIG is set
    if train_dataset is None:
        raise ValueError('train dataset not specified')

    if eval_dataset is None:
        raise ValueError('eval dataset not specifed')

    if not isinstance(eval_dataset, (dict, Dataset)):
        raise ValueError(
            'Eval dataset should be propeller.Dataset of a list of that, got: %s'
            % eval_dataset)
    if isinstance(eval_dataset, Dataset):
        eval_dataset = {'eval': eval_dataset}
    ds_list = list(eval_dataset.values())
    for ds in ds_list:
        ds.name = 'eval'
    first = ds_list[0]
    for d in ds_list[1:]:
        if not first.__eq__(d):
            raise ValueError(
                'eval dataset has different output_shapes or types: %s' %
                repr(ds_list))

    est = Learner(
        model_class_or_model_fn,
        run_config,
        params,
        warm_start_setting=warm_start_setting)

C
chenxuyi 已提交
443
    class _EvalHookOnTrainLoop(hooks.RunHook):
C
chenxuyi 已提交
444
        def __init__(self):
C
chenxuyi 已提交
445
            self.program, self.model_spec = est._build_for_eval(
C
chenxuyi 已提交
446 447 448
                list(eval_dataset.values())[
                    0])  #eval_datasets must have same output shapes
            self.summary_writers = {
C
chenxuyi 已提交
449
                ds_name: _get_summary_writer(
C
chenxuyi 已提交
450 451 452 453 454 455 456
                    os.path.join(
                        os.path.join(run_config.model_dir, 'eval_history'),
                        ds_name))
                for ds_name in eval_dataset
            }

        def after_run(self, _, state):
C
chenxuyi 已提交
457
            """doc"""
C
chenxuyi 已提交
458 459 460 461 462 463 464 465 466 467
            if state.step > run_config.skip_steps and state.gstep % run_config.eval_steps == 0:
                eval_results = {}
                for name, ds in six.iteritems(eval_dataset):
                    ehooks = [
                        hooks.StopAtStepHook(est.run_config.eval_max_steps,
                                             est.run_config.eval_max_steps),
                        hooks.EvalHook(
                            self.model_spec.metrics,
                            summary_writer=self.summary_writers[name], )
                    ]
C
chenxuyi 已提交
468
                    single_card_place = _get_one_place()
C
chenxuyi 已提交
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
                    eval_executor = F.Executor(single_card_place)
                    mon_exe = MonitoredExecutor(
                        eval_executor,
                        self.program,
                        run_config=est.run_config,
                        run_hooks=ehooks + eval_hooks)
                    try:
                        with mon_exe:
                            for data in ds.start(places=[single_card_place]):
                                mon_exe.run(feed=data)
                    except (StopException, F.core.EOFException) as e:
                        pass
                    hook_results = mon_exe.result
                    eval_res = hook_results[
                        1]  # hook_results:  [StopAtStepHook, EvalHook, ...]
                    eval_results[name] = eval_res
C
chenxuyi 已提交
485 486
                    _log_eval_result(name, eval_res,
                                     self.summary_writers[name], state)
C
chenxuyi 已提交
487 488 489 490 491 492 493 494
                for exporter in exporters:
                    exporter.export(eval_executor, self.program,
                                    self.model_spec, eval_results, state)
            else:
                eval_results = {}
            return eval_results

    if distribution.status.is_master:
C
chenxuyi 已提交
495
        train_hooks.append(_EvalHookOnTrainLoop())
C
chenxuyi 已提交
496 497
    res = est.train(train_dataset, train_hooks=train_hooks)
    return res
C
chenxuyi 已提交
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537


def _build_model_fn(model_class):
    def _model_fn(features, mode, params, run_config):
        if mode != RunMode.PREDICT:
            fea, label = features[:-1], features[-1]
        else:
            fea = features

        model = model_class(params, mode, run_config=run_config)
        pred = model.forward(fea)
        if isinstance(pred, F.framework.Variable):
            prediction = [pred]
        else:
            prediction = pred
        if mode == RunMode.TRAIN:
            loss = model.loss(pred, label)
            model.backward(loss)
            return ModelSpec(loss=loss, predictions=prediction, mode=mode)
        elif mode == RunMode.EVAL:
            loss = model.loss(pred, label)
            me = model.metrics(pred, label)

            inf_spec = InferenceSpec(inputs=fea, outputs=prediction)
            if 'loss' not in me:
                me['loss'] = metrics.Mean(loss)
            return ModelSpec(
                loss=loss,
                predictions=prediction,
                metrics=me,
                mode=mode,
                inference_spec=inf_spec)
        elif mode == RunMode.PREDICT:
            inf_spec = InferenceSpec(inputs=fea, outputs=prediction)
            return ModelSpec(
                predictions=prediction, mode=mode, inference_spec=inf_spec)
        else:
            raise RuntimeError('unknown run mode %s' % mode)

    return _model_fn