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

15
import contextlib
16
import os
17

Y
Yu Yang 已提交
18
import core
19

Y
Yu Yang 已提交
20
import data_feeder
21 22
import executor
import framework
J
Jeff Wang 已提交
23
import io
Y
Yu Yang 已提交
24 25
# optimizer is same as the parameter of Trainer.__init__. Rename it to opt_module
import optimizer as opt_module
26
import parallel_executor
Y
Yancey 已提交
27
from transpiler import distribute_transpiler
Y
Yu Yang 已提交
28

H
Helin Wang 已提交
29
__all__ = [
30 31
    'Trainer', 'BeginEpochEvent', 'EndEpochEvent', 'BeginStepEvent',
    'EndStepEvent', 'CheckpointConfig'
H
Helin Wang 已提交
32 33 34
]


Y
Yu Yang 已提交
35
class BeginEpochEvent(object):
Y
yuyang18 已提交
36 37 38 39 40 41 42
    """
    The begin of a training epoch.

    Args:
        epoch_id(int): The current epoch ID.
    """

Y
Yu Yang 已提交
43 44 45 46 47
    def __init__(self, epoch_id):
        self.epoch = epoch_id


class EndEpochEvent(object):
Y
yuyang18 已提交
48 49 50 51 52 53 54
    """
    The end of a training epoch.

    Args:
        epoch_id(int): The current epoch ID.
    """

Y
Yu Yang 已提交
55 56
    def __init__(self, epoch_id):
        self.epoch = epoch_id
H
Helin Wang 已提交
57

Y
Yu Yang 已提交
58 59

class BeginStepEvent(object):
Y
yuyang18 已提交
60 61 62 63 64 65 66 67
    """
    The begin of a training epoch.

    Args:
        epoch_id(int): The current epoch ID.
        step_id(int): The current step ID.
    """

Y
Yu Yang 已提交
68 69 70
    def __init__(self, epoch_id, step_id):
        self.epoch = epoch_id
        self.step = step_id
Y
yuyang18 已提交
71
        self.fetch_metrics = True
Y
yuyang18 已提交
72 73 74 75
        """
        If fetch_metrics is true, the metrics will be fetched at the 
        EndStepEvent. Default is True.
        """
Y
Yu Yang 已提交
76 77 78


class EndStepEvent(object):
Y
yuyang18 已提交
79 80 81 82 83 84 85
    """
    The end of a training step.

    Args:
        epoch_id(int): The current epoch ID.
        step_id(int): The current step ID.
        metrics(list): A list of fetched tensor. The order of this list is same
Y
yuyang18 已提交
86
            as the :code:`train_func` returns.
Y
yuyang18 已提交
87 88
    """

Y
yuyang18 已提交
89
    def __init__(self, epoch_id, step_id, metrics):
Y
Yu Yang 已提交
90 91
        self.epoch = epoch_id
        self.step = step_id
Y
yuyang18 已提交
92
        self.metrics = metrics
H
Helin Wang 已提交
93 94


95
class CheckpointConfig(object):
Y
yuyang18 已提交
96 97 98 99 100 101
    """
    Parameter object for :code:`fluid.io.save_checkpoint` and
    :code:`fluid.Trainer`. Used to configuration how to save checkpoint.

    Args:
        checkpoint_dir(str): Directory path to save check point. Default is the
Y
yuyang18 已提交
102
            current directory.
Y
yuyang18 已提交
103 104 105 106 107 108 109 110 111 112 113 114 115 116

        max_num_checkpoints(int): The max number of local check points.
        epoch_interval(int): Every number of epoch to save check point.
        step_interval(int): Every number of step to save check point.

    Examples:
        >>> config = fluid.CheckpointConfig("./checkpoints")
        >>> trainer = fluid.Trainer(train_func=train_program,
        >>>                         place=place,
        >>>                         optimizer_func=optimizer_func,
        >>>                         checkpoint_config=config)
        >>> trainer.train(...)
    """

117 118 119
    def __init__(self,
                 checkpoint_dir=None,
                 max_num_checkpoints=3,
T
tangwei12 已提交
120 121 122
                 epoch_interval=1,
                 step_interval=10):

123 124
        assert epoch_interval >= 1
        assert step_interval >= 1
125

T
tangwei12 已提交
126 127
        self.checkpoint_dir = checkpoint_dir \
            if checkpoint_dir is not None else os.getcwd()
128 129 130
        self.max_num_checkpoints = max_num_checkpoints
        self.epoch_interval = epoch_interval
        self.step_interval = step_interval
131 132
        self.epoch_id = 0
        self.step_id = 0
T
tangwei12 已提交
133
        self.load_serial = None
T
tangwei12 已提交
134
        self.pserver_id = None
T
tangwei12 已提交
135
        self.lookup_table_name = None
T
tangwei12 已提交
136

137

Q
Qiao Longfei 已提交
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
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


H
Helin Wang 已提交
164
class Trainer(object):
Y
Yu Yang 已提交
165
    """
Y
yuyang18 已提交
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
    A trainer wraps MultiGPU/MultiNode training loops and can be used to train a
    simple neural network easily.

    This API takes a :code:`train_func`. A :code:`train_func` is a function that
    return loss as it first return value. The reset value can be fetched by
    EndStepEvent.metrics

    This API also takes a :code:`optimizer_func` that will return an optimizer
    instance.

    For example, to train a MLP for MNIST dataset, the sample program is

    >>> import paddle.fluid as fluid
    >>>
    >>> def mlp(image, layer_sizes=[200, 100], activation="relu", num_classes=10):
    >>>     hidden = image
    >>>     for layer_size in layer_sizes:
    >>>         hidden = fluid.layers.fc(input=hidden, size=layer_size, act=activation)
    >>>     return fluid.layers.fc(input=hidden, size=num_classes, act="softmax")
    >>>
    >>> def train_mnist_mlp():
    >>>     img = fluid.layers.data(name='image', shape=[784])
    >>>     label = fluid.layers.data(name='label', shape=[1], dtype='int64')
    >>>     prediction = mlp(img)
    >>>     return fluid.layers.mean(fluid.layers.cross_entropy(prediction, label))
    >>>
    >>> def optimizer():
    >>>     return fluid.optimizer.Adam()
    >>>
    >>> trainer = Trainer(train_func=train_mnist_mlp,
    >>>                   optimizer_func=optimizer,
    >>>                   place=fluid.CUDAPlace(0),
    >>>                   parallel=True)
    >>>
    >>> def train_callback(event):
    >>>     if isinstance(event, fluid.EndStepEvent):
    >>>         print "Epoch ID", event.epoch, "Step ID",\
    >>>             event.step, "AvgLoss", event.metrics[0]
    >>>     elif isinstance(event, fluid.EndEpochEvent):
    >>>         trainer.save_params("./model_{0}".format(event.epoch))
    >>>
    >>> trainer.train(num_epochs=100, event_handler=train_callback)

    For more example, please see :ref:`api_guide_high_level_api`.

Y
Yu Yang 已提交
211 212

    Args:
Y
yuyang18 已提交
213 214
        train_func(callable): A function which will return loss. The loss must be
            a scalar tensor.
215
        optimizer_func(callable): A function that returns an Optimizer object.
Y
yuyang18 已提交
216 217 218 219 220 221
        place(CUDAPlace|CPUPlace): The device place of this trainer. If
            :code:`parallel=True,` all CUDA Places will be used if :code:`place`
            is a :code:`CUDAPlace`.
        parallel(bool): True if use multiple devices.
        checkpoint_config(CheckpointConfig): Configuration about how to save
            checkpoints.
Y
Yu Yang 已提交
222 223
    """

Q
Qiao Longfei 已提交
224 225
    def __init__(self,
                 train_func,
226
                 optimizer_func,
T
tangwei12 已提交
227
                 param_path=None,
Y
yuyang18 已提交
228
                 place=None,
229 230
                 parallel=False,
                 checkpoint_config=None):
231
        self.__stop = False
Y
yuyang18 已提交
232
        self.parallel = parallel
Q
Qiao Longfei 已提交
233

234 235
        # config for checkpoint
        # only chief worker will save variables
T
tangwei12 已提交
236
        self.trainer_id = 0
T
tangwei12 已提交
237 238 239
        self.checkpoint_cfg = checkpoint_config
        if self.checkpoint_cfg:
            assert isinstance(self.checkpoint_cfg, CheckpointConfig)
T
tangwei12 已提交
240
            serial = io.get_latest_checkpoint_serial(
T
tangwei12 已提交
241 242
                self.checkpoint_cfg.checkpoint_dir)
            self.checkpoint_cfg.load_serial = serial if serial >= 0 else None
243

H
Helin Wang 已提交
244
        self.scope = core.Scope()
Y
Yu Yang 已提交
245

Y
yuyang18 已提交
246 247 248 249
        # 1. we need to generate a framework.Program by calling
        # program_func. Reference: fluid.program_guard in
        # test_word2vec.py

Y
Yu Yang 已提交
250 251 252 253
        self.startup_program = framework.Program()
        self.train_program = framework.Program()

        with framework.program_guard(self.train_program, self.startup_program):
Q
Qiao Longfei 已提交
254
            program_func_outs = train_func()
Y
yuyang18 已提交
255
            self.train_func_outputs = program_func_outs if isinstance(
F
fengjiayi 已提交
256
                program_func_outs, list) else [program_func_outs]
257
            self.test_program = self.train_program.clone(for_test=True)
258

259
            # The first element of program_func_outs is loss.
260 261 262
            loss = self.train_func_outputs[0]

            optimizer = optimizer_func()
Y
Yu Yang 已提交
263 264 265
            if not isinstance(optimizer, opt_module.Optimizer):
                raise TypeError(
                    "The optimizer should be an instance of Optimizer")
266
            optimize_ops, params_grads = optimizer.minimize(loss)
Y
Yu Yang 已提交
267

Q
Qiao Longfei 已提交
268
        self.place = check_and_get_place(place)
H
Helin Wang 已提交
269

Q
Qiao Longfei 已提交
270
        self._dist_transpile_if_necessary(optimize_ops, params_grads)
271

H
Helin Wang 已提交
272 273
        # 2. move the default_main_program to self.program and run the
        # default_startup program on an empty core.Scope()
Y
Yu Yang 已提交
274
        # Run startup program
275 276 277
        with self._prog_and_scope_guard():
            exe = executor.Executor(place)
            exe.run(self.startup_program)
H
Helin Wang 已提交
278

T
tangwei12 已提交
279
        if self.checkpoint_cfg and self.checkpoint_cfg.load_serial:
T
tangwei12 已提交
280
            self._load_checkpoint()
T
tangwei12 已提交
281 282

        if param_path and os.path.isdir(param_path):
T
tangwei12 已提交
283
            # load params from param_path into scope
T
tangwei12 已提交
284 285 286 287
            io.load_persistables(
                executor=exe,
                dirname=param_path,
                main_program=self.startup_program)
T
tangwei12 已提交
288

289 290 291 292 293 294 295 296 297 298 299 300
    def _transpile_nccl2_dist(self):
        # PADDLE_TRAINER_IPS
        if "PADDLE_TRAINER_IPS" not in os.environ:
            self.nccl_id_var = None
        else:
            self.trainer_id = int(os.getenv("PADDLE_TRAINER_ID"))
            port = os.getenv("PADDLE_PSERVER_PORT")
            worker_ips = os.getenv("PADDLE_TRAINER_IPS")
            worker_endpoints = []
            for ip in worker_ips.split(","):
                worker_endpoints.append(':'.join([ip, port]))
            self.num_trainers = len(worker_endpoints)
Y
yi.wu 已提交
301
            current_endpoint = os.getenv("PADDLE_CURRENT_IP") + ":" + port
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
            worker_endpoints.remove(current_endpoint)
            # TODO(wuyi): use self.nccl_id_var, self.num_trainers and self.trainer_id
            # in ParallelExecutor to start
            # distributed training using NCCL2
            self.nccl_id_var = self.startup_program.global_block().create_var(
                name="NCCLID", persistable=True, type=core.VarDesc.VarType.RAW)
            self.startup_program.global_block().append_op(
                type="gen_nccl_id",
                inputs={},
                outputs={"NCCLID": self.nccl_id_var},
                attrs={
                    "endpoint": current_endpoint,
                    "endpoint_list": worker_endpoints,
                    "trainer_id": self.trainer_id
                })

Q
Qiao Longfei 已提交
318
    def _dist_transpile_if_necessary(self, optimize_ops, params_grads):
319 320 321 322
        self._transpile_nccl2_dist()
        if self.nccl_id_var != None:
            return

323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
        if "PADDLE_TRAINING_ROLE" not in os.environ:
            return

        # the port of all pservers, needed by both trainer and pserver
        port = os.getenv("PADDLE_PSERVER_PORT", "6174")
        # comma separated ips of all pservers, needed by trainer and
        # pserver
        pserver_ips = os.getenv("PADDLE_PSERVER_IPS", "")
        eplist = []
        for ip in pserver_ips.split(","):
            eplist.append(':'.join([ip, port]))
        pserver_endpoints = ",".join(eplist)
        # total number of workers/trainers in the job, needed by
        # trainer and pserver
        trainers = int(os.getenv("PADDLE_TRAINERS"))
        # the IP of the local machine, needed by pserver only
        current_endpoint = os.getenv("PADDLE_CURRENT_IP", "") + ":" + port
        # the unique trainer id, starting from 0, needed by trainer
        # only
T
bug fix  
tangwei12 已提交
342
        self.trainer_id = int(os.getenv("PADDLE_TRAINER_ID", "0"))
T
tangwei12 已提交
343

344 345 346 347 348
        # the role, should be either PSERVER or TRAINER
        training_role = os.getenv("PADDLE_TRAINING_ROLE")
        with self._prog_and_scope_guard():
            t = distribute_transpiler.DistributeTranspiler()
            t.transpile(
T
bug fix  
tangwei12 已提交
349
                self.trainer_id, pservers=pserver_endpoints, trainers=trainers)
350
            if training_role == "PSERVER":
T
tangwei12 已提交
351
                if self.checkpoint_cfg:
T
tangwei12 已提交
352 353 354 355
                    pserver_id = eplist.index(current_endpoint)
                    self.checkpoint_cfg.pserver_id = pserver_id
                    if t.has_distributed_lookup_table:
                        self.checkpoint_cfg.lookup_table_name = t.table_name
T
tangwei12 已提交
356

357 358 359 360 361 362 363 364 365
                self.train_program = t.get_pserver_program(current_endpoint)
                self.startup_program = t.get_startup_program(current_endpoint,
                                                             self.train_program)
            elif training_role == "TRAINER":
                self.train_program = t.get_trainer_program()
            else:
                raise ValueError(
                    'TRAINING_ROLE environment variable must be either TRAINER or PSERVER'
                )
H
Helin Wang 已提交
366

367 368 369 370 371 372
    def stop(self):
        """
        stop training
        """
        self.__stop = True

Y
yuyang18 已提交
373
    def train(self, num_epochs, event_handler, reader=None, feed_order=None):
Y
Yu Yang 已提交
374
        """
Y
yuyang18 已提交
375
        Start the train loop to train the model.
Y
Yu Yang 已提交
376 377

        Args:
Y
yuyang18 已提交
378 379 380
            num_epochs(int): The number of epoch. An epoch will process all data in reader
            event_handler(callable): The event handler. A function with type (ev:Event)->void
            reader(callable): A reader creator object. See also
Y
yuyang18 已提交
381
                :ref:`api_guide_python_reader` .
Y
yuyang18 已提交
382
            feed_order(list): Feeding order of reader. None will following the defining
Y
Yu Yang 已提交
383 384 385
                order in program

        Returns:
Y
yuyang18 已提交
386
            None
Y
Yu Yang 已提交
387
        """
388 389 390 391 392 393
        training_role = os.getenv("PADDLE_TRAINING_ROLE", "")
        if training_role == "PSERVER":
            with self._prog_and_scope_guard():
                exe = executor.Executor(self.place)
                exe.run()
                return
Y
yuyang18 已提交
394 395 396 397 398 399
        if self.parallel:
            self._train_by_parallel_executor(num_epochs, event_handler, reader,
                                             feed_order)
        else:
            self._train_by_executor(num_epochs, event_handler, reader,
                                    feed_order)
H
Helin Wang 已提交
400

401
    def test(self, reader, feed_order):
F
fengjiayi 已提交
402 403 404 405
        """
        Test the model on given test data

        Args:
Y
yuyang18 已提交
406 407 408
            reader(callable): The reader that yields test data.
            feed_order(list): Feeding order of reader. None will following the
                defining order in program
F
fengjiayi 已提交
409 410
        """

Y
yuyang18 已提交
411 412
        return self._test_by_executor(reader, feed_order,
                                      self.train_func_outputs)
Y
Yu Yang 已提交
413

H
Helin Wang 已提交
414
    def save_params(self, param_path):
Y
yuyang18 已提交
415
        """
Y
yuyang18 已提交
416 417
        Save all parameters into :code:`param_path`.

Y
yuyang18 已提交
418
        Args:
Y
yuyang18 已提交
419
            param_path(str): The path to save parameters.
Y
yuyang18 已提交
420 421 422 423

        Returns:
            None
        """
424 425 426
        with self._prog_and_scope_guard():
            exe = executor.Executor(self.place)
            io.save_persistables(exe, dirname=param_path)
Y
Yu Yang 已提交
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449

    @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():
F
fengjiayi 已提交
450
            feed_var_list = build_feed_var_list(self.train_program, feed_order)
Y
Yu Yang 已提交
451 452
            feeder = data_feeder.DataFeeder(
                feed_list=feed_var_list, place=self.place)
F
fengjiayi 已提交
453
            exe = executor.Executor(self.place)
Y
yuyang18 已提交
454 455 456 457
            reader = feeder.decorate_reader(reader, multi_devices=False)
            self._train_by_any_executor(event_handler, exe, num_epochs, reader)

    def _train_by_any_executor(self, event_handler, exe, num_epochs, reader):
T
tangwei12 已提交
458
        if self.checkpoint_cfg:
T
bug fix  
tangwei12 已提交
459 460
            epochs = [
                epoch_id for epoch_id in range(num_epochs)
T
tangwei12 已提交
461
                if epoch_id >= self.checkpoint_cfg.epoch_id
T
bug fix  
tangwei12 已提交
462 463 464 465
            ]
        else:
            epochs = [epoch_id for epoch_id in range(num_epochs)]

T
tangwei12 已提交
466
        for epoch_id in epochs:
Y
yuyang18 已提交
467 468
            event_handler(BeginEpochEvent(epoch_id))
            for step_id, data in enumerate(reader()):
469
                if self.__stop:
T
bug fix  
tangwei12 已提交
470 471
                    if self.checkpoint_cfg:
                        self._clean_checkpoint()
472
                    return
T
tangwei12 已提交
473

T
tangwei12 已提交
474 475
                if self.checkpoint_cfg and self.checkpoint_cfg.load_serial \
                    and self.checkpoint_cfg.step_id >= step_id and self.checkpoint_cfg.epoch_id == epoch_id:
T
tangwei12 已提交
476 477
                    continue

Y
yuyang18 已提交
478 479 480 481 482 483 484 485 486 487
                begin_event = BeginStepEvent(epoch_id, step_id)
                event_handler(begin_event)
                if begin_event.fetch_metrics:
                    metrics = exe.run(feed=data,
                                      fetch_list=[
                                          var.name
                                          for var in self.train_func_outputs
                                      ])
                else:
                    metrics = exe.run(feed=data, fetch_list=[])
T
tangwei12 已提交
488

T
tangwei12 已提交
489 490
                if self.checkpoint_cfg:
                    self._save_checkpoint(epoch_id, step_id)
T
tangwei12 已提交
491
                event_handler(EndStepEvent(epoch_id, step_id, metrics))
Y
yuyang18 已提交
492
            event_handler(EndEpochEvent(epoch_id))
T
tangwei12 已提交
493 494
        if self.checkpoint_cfg:
            self._clean_checkpoint()
F
fengjiayi 已提交
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512

    def _test_by_executor(self, reader, feed_order, fetch_list):
        with executor.scope_guard(self.scope):
            feed_var_list = build_feed_var_list(self.test_program, feed_order)
            feeder = data_feeder.DataFeeder(
                feed_list=feed_var_list, place=self.place)
            exe = executor.Executor(self.place)
            accumulated = len(fetch_list) * [0]
            count = 0
            for data in reader():
                outs = exe.run(program=self.test_program,
                               feed=feeder.feed(data),
                               fetch_list=fetch_list)
                accumulated = [x[0] + x[1][0] for x in zip(accumulated, outs)]
                count += 1

            return [x / count for x in accumulated]

Y
yuyang18 已提交
513 514 515 516 517 518 519 520
    def _train_by_parallel_executor(self, num_epochs, event_handler, reader,
                                    feed_order):
        with self._prog_and_scope_guard():
            pe = self._get_or_create_parallel_executor()
            feed_var_list = build_feed_var_list(self.train_program, feed_order)
            feeder = data_feeder.DataFeeder(
                feed_list=feed_var_list, place=self.place)
            reader = feeder.decorate_reader(reader, multi_devices=True)
521
            self._train_by_any_executor(event_handler, pe, num_epochs, reader)
Y
yuyang18 已提交
522 523 524 525 526 527 528 529 530 531 532

    def _get_parallel_executor(self):
        return getattr(self, 'parallel_executor', None)

    def _get_or_create_parallel_executor(self):
        if self._get_parallel_executor() is None:
            self.parallel_executor = parallel_executor.ParallelExecutor(
                use_cuda=isinstance(self.place, core.CUDAPlace),
                loss_name=self.train_func_outputs[0].name)
        return self._get_parallel_executor()

T
tangwei12 已提交
533
    def _clean_checkpoint(self):
T
tangwei12 已提交
534 535
        assert self.checkpoint_cfg
        io.clean_checkpoint(checkpoint_dir=self.checkpoint_cfg.checkpoint_dir)
T
tangwei12 已提交
536

537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
    def _get_checkpoint_load_args(self):
        """
        epoch_id and step_id are runtime arguments, they are not variables, will load them independently.
        """
        return ["epoch_id", "step_id"]

    def _get_checkpoint_save_args(self, epoch_id, step_id):
        """
        epoch_id and step_id are runtime arguments, they are not variables, will save them independently.
        """
        trainer_args = {}
        trainer_args["epoch_id"] = epoch_id
        trainer_args["step_id"] = step_id
        return trainer_args

T
tangwei12 已提交
552
    def _save_checkpoint(self, epoch_id, step_id):
T
tangwei12 已提交
553
        assert self.checkpoint_cfg
T
tangwei12 已提交
554

T
tangwei12 已提交
555 556
        if epoch_id % self.checkpoint_cfg.epoch_interval == 0 \
            and step_id % self.checkpoint_cfg.step_interval == 0:
T
tangwei12 已提交
557 558 559
            exe = executor.Executor(self.place)
            io.save_checkpoint(
                executor=exe,
T
tangwei12 已提交
560
                checkpoint_dir=self.checkpoint_cfg.checkpoint_dir,
T
tangwei12 已提交
561
                trainer_id=self.trainer_id,
562
                trainer_args=self._get_checkpoint_save_args(epoch_id, step_id),
T
tangwei12 已提交
563
                main_program=self.train_program,
T
tangwei12 已提交
564
                max_num_checkpoints=self.checkpoint_cfg.max_num_checkpoints)
T
tangwei12 已提交
565

T
tangwei12 已提交
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
    def _load_checkpoint(self):
        with self._prog_and_scope_guard():
            exe = executor.Executor(self.place)
            io.load_checkpoint(
                executor=exe,
                checkpoint_dir=self.checkpoint_cfg.checkpoint_dir,
                main_program=self.startup_program)

            if not self.checkpoint_cfg.pserver_id:
                load_trainer_args = self._get_checkpoint_load_args()
                trainer_args = io.load_checkpoint(
                    executor=exe,
                    checkpoint_dir=self.checkpoint_cfg.checkpoint_dir,
                    main_program=self.startup_program,
                    role_id=self.trainer_id,
                    is_trainer=True,
                    load_trainer_args=load_trainer_args)

                if len(trainer_args) != 2:
                    raise ValueError(
                        "the return trainer_args length do not equal _get_checkpoint_load_args"
                    )

                self.checkpoint_cfg.epoch_id = int(trainer_args[0])
                self.checkpoint_cfg.step_id = int(trainer_args[1])
            else:
                if self.checkpoint_cfg.lookup_table_name:
                    io.load_checkpoint(
                        executor=exe,
                        checkpoint_dir=self.checkpoint_cfg.checkpoint_dir,
                        main_program=self.startup_program,
                        role_id=self.checkpoint_cfg.pserver_id,
                        is_trainer=False,
                        load_trainer_args=None,
                        load_lookup_table=self.checkpoint_cfg.lookup_table_name)

F
fengjiayi 已提交
602 603 604 605 606

def build_feed_var_list(program, feed_order):
    if not isinstance(program, framework.Program):
        raise TypeError("The 'program' should be an object of Program")

607
    if isinstance(feed_order, list):
F
fengjiayi 已提交
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
        feed_var_list = [
            program.global_block().var(var_name) for var_name in feed_order
        ]
    else:
        if not isinstance(feed_order, dict):
            raise TypeError(
                "The 'feed_order' should be either None, list or dict.")
        if not sorted(feed_order.values()) == range(len(feed_order)):
            raise ValueError(
                "The values of 'feed_order' should be a permutation of [0, len(feed_order))"
            )
        sorted_pair_list = sorted(feed_order.items(), key=lambda item: item[1])
        feed_var_list = [
            program.global_block().var(pair[0]) for pair in sorted_pair_list
        ]
    return feed_var_list