model.py 93.5 KB
Newer Older
1
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14
#
# 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 17 18
import inspect
import os
import pickle
19
import socket
20 21 22 23
import time
import warnings

import numpy as np
24

25
import paddle
26 27
import paddle.distributed as dist
import paddle.distributed.fleet as fleet
28
from paddle import fluid
29 30
from paddle.autograd import no_grad
from paddle.distributed.fleet.base import role_maker
31
from paddle.fluid import core
32 33
from paddle.fluid.dygraph.base import to_variable
from paddle.fluid.executor import global_scope
34
from paddle.fluid.framework import Variable
35
from paddle.fluid.framework import _current_expected_place as _get_device
36
from paddle.fluid.framework import _get_paddle_place, _non_static_mode
37
from paddle.framework.io_utils import is_belong_to_optimizer
38
from paddle.io import DataLoader, Dataset, DistributedBatchSampler
39
from paddle.jit.translated_layer import INFER_MODEL_SUFFIX, INFER_PARAMS_SUFFIX
40
from paddle.metric import Metric
41 42
from paddle.static import InputSpec as Input

43
from .callbacks import EarlyStopping, config_callbacks
L
LielinJiang 已提交
44
from .model_summary import summary
45

46
__all__ = []
47 48 49 50 51 52 53 54 55 56 57 58 59

_parallel_context_initialized = False


def to_list(value):
    if value is None:
        return value
    if isinstance(value, (list, tuple)):
        return list(value)
    return [value]


def to_numpy(var):
60 61 62
    assert isinstance(
        var, (Variable, fluid.core.VarBase, fluid.core.eager.Tensor)
    ), "not a variable"
H
hong 已提交
63
    if isinstance(var, (fluid.core.VarBase, fluid.core.eager.Tensor)):
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
        return var.numpy()
    t = global_scope().find_var(var.name).get_tensor()
    return np.array(t)


def flatten_list(l):
    assert isinstance(l, list), "not a list"
    outl = []
    splits = []
    for sl in l:
        assert isinstance(sl, list), "sub content not a list"
        splits.append(len(sl))
        outl += sl
    return outl, splits


def restore_flatten_list(l, splits):
    outl = []
    for split in splits:
        assert len(l) >= split, "list length invalid"
        sl, l = l[:split], l[split:]
        outl.append(sl)
    return outl


def extract_args(func):
90
    return inspect.getfullargspec(func).args
91 92


93 94 95 96 97
def _all_gather(x):
    output = []
    dist.all_gather(output, x)
    output = paddle.concat(output, axis=0)
    return output
98 99 100


def wait_server_ready(endpoints):
101
    assert not isinstance(endpoints, str)
102 103 104 105 106 107
    while True:
        all_ok = True
        not_ready_endpoints = []
        for ep in endpoints:
            ip_port = ep.split(":")
            with contextlib.closing(
108 109
                socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            ) as sock:
110 111 112 113 114 115 116 117 118 119 120
                sock.settimeout(2)
                result = sock.connect_ex((ip_port[0], int(ip_port[1])))
                if result != 0:
                    all_ok = False
                    not_ready_endpoints.append(ep)
        if not all_ok:
            time.sleep(3)
        else:
            break


121 122 123
def init_communicator(
    program, rank, nranks, wait_port, current_endpoint, endpoints
):
124 125 126 127
    if nranks < 2:
        return
    other_endpoints = endpoints[:]
    other_endpoints.remove(current_endpoint)
128
    block = program.global_block()
129 130
    if rank == 0 and wait_port:
        wait_server_ready(other_endpoints)
131 132 133 134
    if core.is_compiled_with_cuda():
        nccl_id_var = block.create_var(
            name=fluid.unique_name.generate('nccl_id'),
            persistable=True,
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
            type=fluid.core.VarDesc.VarType.RAW,
        )

        block.append_op(
            type='c_gen_nccl_id',
            inputs={},
            outputs={'Out': nccl_id_var},
            attrs={
                'rank': rank,
                'endpoint': current_endpoint,
                'other_endpoints': other_endpoints,
            },
        )

        block.append_op(
            type='c_comm_init',
            inputs={'X': nccl_id_var},
            outputs={},
            attrs={
                'nranks': nranks,
                'rank': rank,
                'ring_id': 0,
            },
        )
159 160
    elif core.is_compiled_with_npu():
        hccl_id_var = block.create_var(
Z
zhangchunle 已提交
161
            name=fluid.unique_name.generate('hccl_id'),
162
            persistable=True,
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
            type=core.VarDesc.VarType.RAW,
        )
        block.append_op(
            type='c_gen_hccl_id',
            inputs={},
            outputs={'Out': hccl_id_var},
            attrs={
                'rank': rank,
                'endpoint': current_endpoint,
                'other_endpoints': other_endpoints,
            },
        )
        block.append_op(
            type='c_comm_init_hccl',
            inputs={'X': hccl_id_var},
            outputs={},
            attrs={
                'rank': rank,
                'ring_id': 0,
                'device_id': int(os.getenv("FLAGS_selected_npus")),
                'rank_ids': nranks,
            },
        )
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 212 213
    elif core.is_compiled_with_xpu():
        bkcl_id_var = block.create_var(
            name=fluid.unique_name.generate('bkcl_id'),
            persistable=True,
            type=fluid.core.VarDesc.VarType.RAW,
        )

        block.append_op(
            type='c_gen_bkcl_id',
            inputs={},
            outputs={'Out': bkcl_id_var},
            attrs={
                'rank': rank,
                'endpoint': current_endpoint,
                'other_endpoints': other_endpoints,
            },
        )

        block.append_op(
            type='c_comm_init',
            inputs={'X': bkcl_id_var},
            outputs={},
            attrs={
                'nranks': nranks,
                'rank': rank,
                'ring_id': 0,
            },
        )
214 215 216 217


def prepare_distributed_context(place=None):
    if place is None:
218
        place = (
219 220
            fluid.CUDAPlace(paddle.distributed.ParallelEnv().dev_id)
            if paddle.distributed.ParallelEnv().nranks > 1
221
            else fluid.CUDAPlace(0)
222
        )
223

224
    place = _get_paddle_place(place)
Q
qizhaoaoe 已提交
225
    strategy = paddle.distributed.parallel.ParallelStrategy()
226 227 228 229 230 231 232 233
    strategy.nranks = paddle.distributed.ParallelEnv().nranks
    strategy.local_rank = paddle.distributed.ParallelEnv().local_rank
    strategy.trainer_endpoints = (
        paddle.distributed.ParallelEnv().trainer_endpoints
    )
    strategy.current_endpoint = (
        paddle.distributed.ParallelEnv().current_endpoint
    )
234 235 236 237 238 239 240 241 242 243

    if strategy.nranks < 2:
        return

    global _parallel_context_initialized

    if not _parallel_context_initialized and isinstance(place, fluid.CUDAPlace):

        def _init_context():
            communicator_prog = fluid.Program()
244 245 246 247 248 249 250 251
            init_communicator(
                communicator_prog,
                strategy.local_rank,
                strategy.nranks,
                True,
                strategy.current_endpoint,
                strategy.trainer_endpoints,
            )
252 253 254
            exe = fluid.Executor(place)
            exe.run(communicator_prog)

J
Jiabin Yang 已提交
255
        if fluid._non_static_mode():
256 257 258 259 260
            fluid.disable_dygraph()
            _init_context()
            fluid.enable_dygraph(place)

    else:
261
        assert "Only support CUDAPlace for now."
262 263 264

    _parallel_context_initialized = True
    return strategy
265 266


L
LiuChiachi 已提交
267
def _update_input_info(inputs):
L
LiuChiachi 已提交
268
    "Get input shape list by given inputs in Model initialization."
269
    shapes = None
L
LiuChiachi 已提交
270
    dtypes = None
L
LiuChiachi 已提交
271 272
    if isinstance(inputs, Input):
        shapes = [list(inputs.shape)]
L
LiuChiachi 已提交
273
        dtypes = [inputs.dtype]
274
    elif isinstance(inputs, (list, tuple)):
275
        shapes = [list(input.shape) for input in inputs]
L
LiuChiachi 已提交
276
        dtypes = [input.dtype for input in inputs]
277 278
    elif isinstance(inputs, dict):
        shapes = [list(inputs[name].shape) for name in inputs]
L
LiuChiachi 已提交
279 280 281 282
        dtypes = [inputs[name].dtype for name in inputs]
    else:
        return None
    return shapes, dtypes
283 284


285
class StaticGraphAdapter:
286
    """
287

288
    Model traning/inference with a static graph.
289

290 291 292
    """

    def __init__(self, model):
293
        super().__init__()
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
        self.model = model
        # with `_build_once` gone, parameters are now created in `__init__`
        # so we need to keep track of the parameters already created
        self._startup_prog = fluid.default_startup_program()
        self._orig_prog = fluid.default_main_program()

        self._label_vars = {}  # label variables
        self._input_vars = {}  # label variables
        self._endpoints = {}
        self._loss_endpoint = None
        self._executor = None
        self._progs = {}
        self._compiled_progs = {}

        self._merge_count = {
            'eval_total': 0,
            'test_total': 0,
            'eval_batch': 0,
312
            'test_batch': 0,
313 314
        }

315 316
        self._nranks = paddle.distributed.ParallelEnv().nranks
        self._local_rank = paddle.distributed.ParallelEnv().local_rank
317

J
Jiaqi Liu 已提交
318 319 320
        self._amp_level = "O0"
        self._amp_configs = {}
        self._amp_custom_lists = {}
L
Leo Chen 已提交
321
        self._use_fp16_guard = None
J
Jiaqi Liu 已提交
322

323 324 325 326 327 328 329 330
    @property
    def mode(self):
        return self.model.mode

    @mode.setter
    def mode(self, value):
        self.model.mode = value

L
lyuwenyu 已提交
331
    def train_batch(self, inputs, labels=None, update=True):
332 333 334
        assert (
            self.model._optimizer
        ), "model not ready, please call `model.prepare()` first"
335
        self.mode = 'train'
336 337
        assert (
            update is True
338
        ), "Does not support `update == False` in static graph mode by now."
339 340 341 342 343 344
        return self._run(inputs, labels)

    def eval_batch(self, inputs, labels=None):
        self.mode = 'eval'
        return self._run(inputs, labels)

345
    def predict_batch(self, inputs):
346 347 348 349
        self.mode = 'test'
        return self._run(inputs, None)

    def parameters(self, *args, **kwargs):
350
        return self.model.network.parameters(*args, **kwargs)
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368

    def save(self, path):
        def _save(state, path):
            if not state:
                return
            state = {
                k: to_numpy(v) if isinstance(v, Variable) else v
                for k, v in state.items()
            }
            with open(path, 'wb') as f:
                pickle.dump(state, f)

        base = os.path.basename(path)
        assert base != "", "path should be of 'dirname/filename' format"
        dir_name = os.path.dirname(path)
        if dir_name and not os.path.exists(dir_name):
            os.makedirs(dir_name)
        param_path = path + ".pdparams"
369
        _save(self.model.network.state_dict(), param_path)
370 371 372 373 374 375
        prog = self._progs.get('train', None)
        if prog is None or self.model._optimizer is None:
            return
        # XXX `optimizer.state_dict()` only work in dygraph mode
        optim_path = path + ".pdopt"
        optim = {
376
            p.name: p for p in filter(is_belong_to_optimizer, prog.list_vars())
377 378 379 380 381 382
        }
        if not optim:
            return

        _save(optim, optim_path)

L
Leo Chen 已提交
383
    # TODO: support save/load scaler state in static graph
384 385 386 387 388 389 390 391
    def load(self, param_state_pairs, optim_state):
        if self._executor is None:
            executor = fluid.Executor(fluid.CPUPlace())._default_executor
        else:
            executor = self._executor._default_executor

        # restore parameter states
        fluid.core._create_loaded_parameter(
392 393 394 395
            [param for param, state in param_state_pairs],
            global_scope(),
            executor,
        )
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
        for param, state in param_state_pairs:
            self._set_var(param, state)

        # restore optimizer states
        # FIXME what if a different optimizer is used?
        if not self.model._optimizer or not optim_state:
            return
        self._load_optimizer(optim_state, executor)

    def _load_optimizer(self, state, executor):
        prog = self._progs.get('train', None)
        optim = list(filter(is_belong_to_optimizer, prog.list_vars()))
        if not optim:
            return

        fluid.core._create_loaded_parameter(optim, global_scope(), executor)

        converted_state = dict(state)
        for var in optim:
            if var.name in ["@LR_DECAY_COUNTER@", "global_step"]:
                # When using learning rate scheduler, dygraph would name the
                # global step var as "global_step" to save, while static-graph
                # would has a state var named as "@LR_DECAY_COUNTER@".
                # NOTE: dygraph saved global_step is 1 larger than that in
                # static-graph, since the time of global_step to increase is
                # different.
                state_val = (
423 424 425 426
                    (np.array(converted_state.pop("global_step")) - 1)
                    if "global_step" in converted_state
                    else converted_state.pop("@LR_DECAY_COUNTER@", None)
                )
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
                if state_val is not None:
                    converted_state[var.name] = state_val
            elif var.name.startswith("learning_rate_"):
                # When using static learning rate, static-graph would make it
                # a persistable var named 'unique_name.generate("learning_rate")',
                # However, dygraph wouldn't save it.
                if var.name not in state:
                    continue
            else:
                # moment and other accumulators
                if var.name not in converted_state:
                    # try to convert from dygraph name
                    opt_name = self.model._optimizer._name
                    opt_cls_name = self.model._optimizer.__class__.__name__
                    opt_unq_name = None
                    for name in self.model._optimizer._accumulators.keys():
443 444 445 446 447 448 449 450 451
                        accum_name = (
                            name
                            if opt_name is None
                            else name[len(opt_name) + 1 :]
                        )
                        for (
                            param_name,
                            state_var,
                        ) in self.model._optimizer._accumulators[name].items():
452 453 454
                            if opt_unq_name is None:
                                # can not infer out the exact unique(opt_name),
                                # thus try to extract rather than generate
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
                                for state_key in sorted(
                                    state.keys(),
                                    key=lambda x: len(x),
                                    reverse=True,
                                ):
                                    prefix = (
                                        param_name
                                        + "_"
                                        + (
                                            opt_cls_name
                                            if opt_name is None
                                            else opt_name
                                        )
                                        + "_"
                                    )
470
                                    if state_key.startswith(prefix):
471 472 473
                                        prefix_offset = state_key[
                                            len(prefix) :
                                        ].find("_") + len(prefix)
474
                                        opt_unq_name = state_key[
475 476 477 478
                                            len(
                                                param_name + "_"
                                            ) : prefix_offset
                                        ]
479 480 481 482
                                        # TODO: assert
                                        # assert opt_unq_name is None
                                    # gen(param.name + "_" + gen(opt_name) + "_" + accum_name)
                                    # always end with "_0" since the unique optimizer._name
483 484 485 486 487 488 489 490
                            dy_state_name = (
                                param_name
                                + "_"
                                + opt_unq_name
                                + "_"
                                + accum_name
                                + "_0"
                            )
491
                            converted_state[
492 493
                                state_var.name
                            ] = converted_state.pop(dy_state_name)
494

495 496 497
            assert (
                var.name in converted_state
            ), "variable [{}] is not in optimizer state file".format(var.name)
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
            self._set_var(var, converted_state[var.name])

    def _set_var(self, var, ndarray):
        t = global_scope().find_var(var.name).get_tensor()
        p = t._place()
        if p.is_cpu_place():
            place = fluid.CPUPlace()
        elif p.is_cuda_pinned_place():
            place = fluid.CUDAPinnedPlace()
        else:
            p = fluid.core.Place()
            p.set_place(t._place())
            place = fluid.CUDAPlace(p.gpu_device_id())

        t.set(ndarray, place)

    def _run(self, inputs, labels=None):
        compiled_prog = self._compiled_progs.get(self.mode, None)
516 517 518
        assert (
            compiled_prog
        ), "Model is not ready, please call `model.prepare()` first"
519 520 521 522

        inputs = to_list(inputs)
        if labels is not None:
            labels = to_list(labels)
523 524
        assert len(inputs) == len(self._input_vars[self.mode]), (
            "number of inputs"
525
            + " does not match number of arguments of `forward` method"
526
        )
527 528 529

        feed = {}
        input_names = [v.name for v in self._input_vars[self.mode]]
L
Leo Chen 已提交
530 531
        input_dtypes = [v.dtype for v in self._input_vars[self.mode]]

532 533 534 535
        for idx, n in enumerate(input_names):
            # train and test may take different arguments
            if inputs[idx] is not None:
                feed[n] = inputs[idx]
536 537 538 539
            if (
                self._amp_level == 'O2'
                and input_dtypes[idx] == core.VarDesc.VarType.FP16
            ):
L
Leo Chen 已提交
540 541
                if isinstance(feed[n], core.LoDTensor):
                    feed[n] = feed[n]._as_type(core.VarDesc.VarType.FP16)
L
Leo Chen 已提交
542
                elif isinstance(feed[n], np.array):
L
Leo Chen 已提交
543 544
                    feed[n] = feed[n].astype('float16')

545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
        if labels is not None:
            for idx, v in enumerate(self._label_vars[self.mode]):
                feed[v.name] = labels[idx]

        endpoints = self._endpoints[self.mode]
        if self.mode == 'test':
            fetch_list = endpoints['output']
        else:
            metric_list, metric_splits = flatten_list(endpoints['metric'])
            fetch_list = endpoints['loss'] + metric_list
            num_loss = len(endpoints['loss'])

        # if fetch Variable is same as input Variable, do not fetch
        # from program, get it from input directly
        pruned_fetch_list = []
        pruned_fetch_idx_name_map = [""] * len(fetch_list)
        for i, fetch_var in enumerate(fetch_list):
            if fetch_var.name in feed.keys():
                pruned_fetch_idx_name_map[i] = fetch_var.name
            else:
                pruned_fetch_list.append(fetch_var)

567 568 569 570 571 572
        rets = self._executor.run(
            compiled_prog,
            feed=feed,
            fetch_list=pruned_fetch_list,
            return_numpy=False,
        )
573 574 575 576 577 578 579 580 581 582

        # restore pruned fetch_list Variable from feeds
        for i, name in enumerate(pruned_fetch_idx_name_map):
            if len(name) > 0:
                rets.insert(i, feed[name])

        # LoDTensor cannot be fetch as numpy directly
        rets = [np.array(v) for v in rets]
        if self.mode == 'test':
            return rets[:]
583

584 585 586 587
        metric_states = restore_flatten_list(rets[num_loss:], metric_splits)
        metrics = []
        for metric, state in zip(self.model._metrics, metric_states):
            # cut off padding size
588 589 590 591 592 593
            if (
                self.mode != 'train'
                and self.model._test_dataloader is not None
                and isinstance(self.model._test_dataloader, DataLoader)
                and self._nranks > 1
            ):
594 595 596 597 598 599
                total_size = len(self.model._test_dataloader.dataset)
                # TODO: fixme if have better way to get batch size
                samples = state[0].shape[0]
                current_count = self._merge_count.get(self.mode + '_total', 0)
                if current_count + samples >= total_size:
                    state = [
600
                        s[: int(total_size - current_count), ...] for s in state
601 602
                    ]
                    self._merge_count[self.mode + '_total'] = 0
603 604 605
                    self._merge_count[self.mode + '_batch'] = int(
                        total_size - current_count
                    )
606 607 608 609 610
                else:
                    self._merge_count[self.mode + '_total'] += samples
                    self._merge_count[self.mode + '_batch'] = samples

            metrics.append(metric.update(*state))
611 612 613 614 615

        if num_loss and len(metrics):
            return rets[:num_loss], metrics
        else:
            return rets[:num_loss] if num_loss else metrics
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636

    def prepare(self):
        modes = ['train', 'eval', 'test']
        for mode in modes:
            self._make_program(mode)
            self._compile_and_initialize(self._progs[mode], mode)

    def _make_program(self, mode):
        prog = self._progs.get(mode, None)
        if prog is not None:
            return

        prog = self._orig_prog.clone()
        # NOTE: When defining learning rate scheduling in static-graph, ops to
        # increase the global step var and calculate learning rate would be
        # prepended into _orig_prog. test program maked by `_orig_prog.clone`
        # also would include these ops. Thus must prune these ops in test
        # program, otherwise the global step would be changed in test.
        if mode != 'train':
            for op in list(prog.global_block().ops):
                prog.global_block()._remove_op(0)
637 638 639 640 641
        if (
            mode == 'train'
            and self.model._optimizer
            and self.model._optimizer._learning_rate_map
        ):
642 643 644 645 646 647 648 649
            # HACK workaround learning rate map issue
            lr_var = self.model._optimizer._learning_rate_map[self._orig_prog]
            new_lr_var = prog.global_block().vars[lr_var.name]
            self.model._optimizer._learning_rate_map[prog] = new_lr_var

        losses = []
        metrics = []
        with fluid.program_guard(prog, self._startup_prog):
650 651
            inputs = self.model._inputs
            labels = self.model._labels if self.model._labels else []
652 653
            inputs = [k._create_feed_layer() for k in to_list(inputs)]
            labels = [k._create_feed_layer() for k in to_list(labels)]
654
            self._label_vars[mode] = labels
655
            outputs = to_list(self.model.network.forward(*inputs))
656

657 658
            if mode != 'test' and self.model._loss:
                losses = self.model._loss(*(outputs + labels))
659 660

            if self._nranks > 1 and mode != 'train':
661
                outputs = [_all_gather(o) for o in outputs]
662
                if mode != 'test':
663
                    labels = [_all_gather(l) for l in labels]
664 665 666

            if mode != 'test':
                for metric in self.model._metrics:
667
                    metrics.append(to_list(metric.compute(*(outputs + labels))))
668 669

            if mode == 'train' and self.model._optimizer:
670
                self._loss_endpoint = paddle.add_n(losses)
671 672 673
                if self._nranks > 1:
                    role = role_maker.PaddleCloudRoleMaker(is_collective=True)
                    fleet.init(role)
J
Jiaqi Liu 已提交
674 675 676 677 678
                    dist_strategy = fleet.DistributedStrategy()
                    if self._amp_level != 'O0':
                        dist_strategy.amp = True
                        dist_strategy.amp_configs = self._amp_configs.copy()
                        dist_strategy.amp_configs.update(self._amp_custom_lists)
679 680 681
                        dist_strategy.amp_configs['use_pure_fp16'] = (
                            self._amp_level == 'O2'
                        )
682
                    self.model._optimizer = fleet.distributed_optimizer(
683 684
                        self.model._optimizer, strategy=dist_strategy
                    )
J
Jiaqi Liu 已提交
685
                elif self._amp_level != "O0" and core.is_compiled_with_cuda:
686 687 688 689 690 691 692
                    amp_lists = (
                        paddle.static.amp.AutoMixedPrecisionLists(
                            **self._amp_custom_lists
                        )
                        if self._amp_custom_lists
                        else None
                    )
J
Jiaqi Liu 已提交
693 694 695 696 697
                    self.model._optimizer = paddle.static.amp.decorate(
                        self.model._optimizer,
                        amp_lists=amp_lists,
                        use_pure_fp16=self._amp_level == "O2",
                        use_fp16_guard=self._use_fp16_guard,
698 699
                        **self._amp_configs
                    )
700 701 702 703 704 705 706 707 708 709 710

                self.model._optimizer.minimize(self._loss_endpoint)

        if mode != 'train':  # clone again to put it in test mode
            prog = prog.clone(for_test=True)

        self._input_vars[mode] = inputs

        self._progs[mode] = prog
        self._endpoints[mode] = {
            "output": outputs,
711
            "loss": to_list(losses),
712
            "metric": metrics,
713 714 715 716 717 718 719
        }

    def _compile_and_initialize(self, prog, mode):
        compiled_prog = self._compiled_progs.get(mode, None)
        if compiled_prog is not None:
            return compiled_prog

720 721 722
        assert (
            self.model._place is not None
        ), "device is not set, please call `model.prepare()` first"
723 724 725 726 727 728 729 730 731 732 733 734

        place = self.model._place

        # XXX *ALL WEIGHTS* should be initialized upon model construction
        # even if `forward()` may run different code path for different mode
        # therefore startup program only needs to run once
        if self._executor is None:
            self._executor = fluid.Executor(place)
            # XXX incremental initialization
            uninitialized = []
            for var_py in self._startup_prog.list_vars():
                var = fluid.global_scope().find_var(var_py.name)
735 736 737 738 739
                if (
                    not var_py.name.startswith('nccl_id')
                    and var
                    and var.get_tensor()._is_initialized()
                ):
740 741 742
                    continue

                uninitialized.append(var_py)
743 744 745 746 747 748 749 750 751

            # for RawProgramOptimizer, it will insert OP with no outputs like:
            #       c_comm_init(inputs={X=['comm_id_0']}
            # but we cannot prune this op.
            block = self._startup_prog.global_block()
            for op in block.ops:
                if op.type == "c_comm_init":
                    uninitialized.append(op)

752 753 754 755
            if uninitialized:
                startup_prog = self._startup_prog._prune(uninitialized)
                self._executor.run(startup_prog)

756 757 758 759
        if (
            self._amp_level == "O2"
            and mode == 'train'
            and core.is_compiled_with_cuda()
J
Jiaqi Liu 已提交
760 761 762
        ):
            self.model._optimizer.amp_init(place)

763 764 765 766 767 768 769 770
        if self._nranks < 2:
            compiled_prog = fluid.CompiledProgram(prog)
        else:
            compiled_prog = prog

        self._compiled_progs[mode] = compiled_prog


771
class DynamicGraphAdapter:
772
    def __init__(self, model):
773
        super().__init__()
774
        self.model = model
775 776
        self._nranks = paddle.distributed.ParallelEnv().nranks
        self._local_rank = paddle.distributed.ParallelEnv().local_rank
777 778 779 780
        self._merge_count = {
            'eval_total': 0,
            'test_total': 0,
            'eval_batch': 0,
781
            'test_batch': 0,
782 783
        }

L
LiuChiachi 已提交
784
        self._input_info = None
J
Jiaqi Liu 已提交
785 786 787 788 789
        self._amp_level = "O0"
        self._amp_configs = {}
        self._amp_custom_lists = {}
        self._use_fp16_guard = True

790
        if self._nranks > 1:
791
            dist.init_parallel_env()
Q
qizhaoaoe 已提交
792
            stradegy = paddle.distributed.parallel.ParallelStrategy()
793 794 795 796 797 798 799 800
            stradegy.nranks = paddle.distributed.ParallelEnv().nranks
            stradegy.local_rank = paddle.distributed.ParallelEnv().local_rank
            stradegy.trainer_endpoints = (
                paddle.distributed.ParallelEnv().trainer_endpoints
            )
            stradegy.current_endpoint = (
                paddle.distributed.ParallelEnv().current_endpoint
            )
Q
qizhaoaoe 已提交
801
            self.ddp_model = paddle.DataParallel(self.model.network, stradegy)
802 803 804 805 806 807 808 809 810 811

    @property
    def mode(self):
        return self.model.mode

    @mode.setter
    def mode(self, value):
        self.model.mode = value

    # TODO multi device in dygraph mode not implemented at present time
L
lyuwenyu 已提交
812
    def train_batch(self, inputs, labels=None, update=True):
813 814 815
        assert (
            self.model._optimizer
        ), "model not ready, please call `model.prepare()` first"
816
        self.model.network.train()
817 818
        self.mode = 'train'
        inputs = to_list(inputs)
L
LiuChiachi 已提交
819
        self._input_info = _update_input_info(inputs)
820 821 822
        labels = labels or []
        labels = [to_variable(l) for l in to_list(labels)]

L
Leo Chen 已提交
823 824 825 826
        # scaler should be initialized only once
        if self._amp_level != "O0" and self.model._scaler is None:
            self.model._scaler = paddle.amp.GradScaler(**self._amp_configs)

827 828 829 830 831
        with paddle.amp.auto_cast(
            enable=self._amp_level != 'O0',
            **self._amp_custom_lists,
            level=self._amp_level
        ):
J
Jiaqi Liu 已提交
832
            if self._nranks > 1:
833
                outputs = self.ddp_model(*[to_variable(x) for x in inputs])
J
Jiaqi Liu 已提交
834
            else:
835
                outputs = self.model.network(*[to_variable(x) for x in inputs])
836

L
Leo Chen 已提交
837 838
        losses = self.model._loss(*(to_list(outputs) + labels))
        losses = to_list(losses)
839
        final_loss = paddle.add_n(losses)
840

J
Jiaqi Liu 已提交
841
        if self._amp_level != "O0":
L
Leo Chen 已提交
842
            scaled = self.model._scaler.scale(final_loss)
J
Jiaqi Liu 已提交
843
            scaled.backward()
L
lyuwenyu 已提交
844
            if update:
L
Leo Chen 已提交
845
                self.model._scaler.minimize(self.model._optimizer, scaled)
L
lyuwenyu 已提交
846
                self.model.network.clear_gradients()
J
Jiaqi Liu 已提交
847 848
        else:
            final_loss.backward()
L
lyuwenyu 已提交
849 850 851
            if update:
                self.model._optimizer.minimize(final_loss)
                self.model.network.clear_gradients()
L
update  
lyuwenyu 已提交
852

853 854
        metrics = []
        for metric in self.model._metrics:
855
            metric_outs = metric.compute(*(to_list(outputs) + labels))
Z
zhangchunle 已提交
856
            m = metric.update(*[to_numpy(m) for m in to_list(metric_outs)])
857 858
            metrics.append(m)

859 860 861 862 863
        return (
            ([to_numpy(l) for l in losses], metrics)
            if len(metrics) > 0
            else [to_numpy(l) for l in losses]
        )
864 865

    def eval_batch(self, inputs, labels=None):
866
        self.model.network.eval()
867 868
        self.mode = 'eval'
        inputs = to_list(inputs)
L
LiuChiachi 已提交
869
        self._input_info = _update_input_info(inputs)
870 871 872
        labels = labels or []
        labels = [to_variable(l) for l in to_list(labels)]

873
        outputs = self.model.network(*[to_variable(x) for x in inputs])
874 875 876 877 878 879 880 881 882

        # Transfrom data to expected device
        expected_device = paddle.device.get_device()
        for o in to_list(outputs):
            o._to(device=expected_device)

        for l in labels:
            l._to(device=expected_device)

883 884
        if self.model._loss:
            losses = self.model._loss(*(to_list(outputs) + labels))
885 886
            losses = to_list(losses)

887
        if self._nranks > 1:
888 889
            outputs = [_all_gather(o) for o in to_list(outputs)]
            labels = [_all_gather(l) for l in labels]
890 891 892
        metrics = []
        for metric in self.model._metrics:
            # cut off padding value.
893 894 895 896 897
            if (
                self.model._test_dataloader is not None
                and self._nranks > 1
                and isinstance(self.model._test_dataloader, DataLoader)
            ):
898 899 900 901 902
                total_size = len(self.model._test_dataloader.dataset)
                samples = outputs[0].shape[0]
                current_count = self._merge_count.get(self.mode + '_total', 0)
                if current_count + samples >= total_size:
                    outputs = [
903
                        o[: int(total_size - current_count)] for o in outputs
904 905
                    ]
                    labels = [
906
                        l[: int(total_size - current_count)] for l in labels
907 908
                    ]
                    self._merge_count[self.mode + '_total'] = 0
909 910 911
                    self._merge_count[self.mode + '_batch'] = int(
                        total_size - current_count
                    )
912 913 914 915
                else:
                    self._merge_count[self.mode + '_total'] += samples
                    self._merge_count[self.mode + '_batch'] = samples

916
            metric_outs = metric.compute(*(to_list(outputs) + labels))
Z
zhangchunle 已提交
917
            m = metric.update(*[to_numpy(m) for m in to_list(metric_outs)])
918 919
            metrics.append(m)

920
        if self.model._loss and len(metrics):
921
            return [to_numpy(l) for l in losses], metrics
922
        elif self.model._loss:
923 924 925
            return [to_numpy(l) for l in losses]
        else:
            return metrics
926

927
    def predict_batch(self, inputs):
928
        self.model.network.eval()
929 930
        self.mode = 'test'
        inputs = [to_variable(x) for x in to_list(inputs)]
L
LiuChiachi 已提交
931
        self._input_info = _update_input_info(inputs)
932
        outputs = self.model.network(*inputs)
933
        if self._nranks > 1 and isinstance(self.model._place, fluid.CUDAPlace):
934
            outputs = [_all_gather(o) for o in to_list(outputs)]
935 936 937 938

        return [to_numpy(o) for o in to_list(outputs)]

    def parameters(self, *args, **kwargs):
939
        return self.model.network.parameters(*args, **kwargs)
940 941

    def save(self, path):
942
        params = self.model.network.state_dict()
943
        paddle.save(params, path + '.pdparams')
L
Leo Chen 已提交
944 945 946
        if self.model._optimizer is not None:
            if self.model._optimizer.state_dict():
                optim = self.model._optimizer.state_dict()
947
                paddle.save(optim, path + '.pdopt')
L
Leo Chen 已提交
948 949 950 951 952 953
        if hasattr(self.model, '_scaler') and self.model._scaler is not None:
            if self.model._scaler.state_dict():
                scaler = self.model._scaler.state_dict()
                paddle.save(scaler, path + '.pdscaler')

    def load(self, param_state_pairs, optim_state, scaler_state=None):
954 955 956 957
        # restore parameter states
        for param, state in param_state_pairs:
            param.set_value(state)

L
Leo Chen 已提交
958 959 960 961
        if hasattr(self.model, '_scaler') and self.model._scaler is not None:
            if scaler_state:
                self.model._scaler.load_state_dict(scaler_state)

962 963 964 965
        # resotre optimizer states
        if not self.model._optimizer or not optim_state:
            return

966 967
        # If optimizer performs set_state_dict when state vars haven't been created,
        # which would happen when set_state_dict before minimize, the state would be
968 969 970 971 972 973 974 975 976 977
        # stored in optimizer._accumulators_holder and loaded lazily.
        # To contrive this when loading from static-graph saved states, extend
        # state dict to include keys named accoring to dygraph naming rules.
        # TODO: if len(self.model._optimizer._accumulators) > 0
        converted_state = dict(optim_state)
        opt_unq_name = self.model._optimizer._name
        if opt_unq_name is None:
            opt_unq_name = ''

        opt_cls_name = self.model._optimizer.__class__.__name__
978
        opt_name = opt_unq_name[: opt_unq_name.rfind("_")]  # remove suffix idx
979
        param_names = [param.name for param in self.model.network.parameters()]
980 981 982
        for var_name, state_var in sorted(
            optim_state.items(), key=lambda x: len(x[0]), reverse=True
        ):
983 984 985 986 987
            if var_name in ["@LR_DECAY_COUNTER@", "global_step"]:
                # NOTE: dygraph saved global_step is 1 larger than that in
                # static-graph, since the time of global_step to increase is
                # different.
                if var_name == "@LR_DECAY_COUNTER@":
988 989 990
                    converted_state["global_step"] = (
                        np.array(converted_state.pop("@LR_DECAY_COUNTER@")) + 1
                    )
991 992 993 994 995 996
            else:
                # moment and other accumulators
                # extend state dict to include promising dygraph names
                for param_name in param_names:
                    if var_name.startswith(param_name + "_" + opt_name):
                        # when init optimizer with name
997 998 999 1000 1001 1002 1003
                        accum_name = var_name[
                            len(param_name + "_" + opt_name + "_") :
                        ]
                    elif (
                        var_name.startswith(param_name + "_")
                        and opt_name == opt_cls_name
                    ):
1004
                        # when init optimizer without name
1005
                        accum_name = var_name[len(param_name + "_") :]
1006 1007 1008
                    else:
                        continue
                    # remove suffix idx
1009
                    accum_name = accum_name[: accum_name.rfind("_")]
1010 1011
                    # state names always end with "_0" in dygraph because of the
                    # unique optimizer._name
1012 1013 1014 1015 1016 1017 1018 1019
                    dy_state_name = (
                        param_name
                        + "_"
                        + opt_unq_name
                        + "_"
                        + accum_name
                        + "_0"
                    )
1020 1021
                    converted_state[dy_state_name] = state_var

1022 1023
        if not hasattr(self.model._optimizer, 'set_state_dict'):
            warnings.warn(
1024
                "paddle.fluid.optimizer is deprecated in API 2.0, please use paddle.optimizer instead."
1025 1026 1027 1028
            )
            self.model._optimizer.set_dict(converted_state)
        else:
            self.model._optimizer.set_state_dict(converted_state)
1029

L
Leo Chen 已提交
1030
    def prepare(self):
1031 1032 1033 1034
        if (
            self._amp_level == "O2"
            and self.model.mode == 'train'
            and core.is_compiled_with_cuda()
L
Leo Chen 已提交
1035 1036 1037 1038
        ):
            self.model.network, self.model._optimizer = paddle.amp.decorate(
                models=self.model.network,
                optimizers=self.model._optimizer,
1039 1040
                level='O2',
            )
L
Leo Chen 已提交
1041 1042 1043
        if self._amp_level != "O0":
            self.model._scaler = None

1044

1045
class Model:
1046
    """
1047

1048 1049
    An Model object is network with training and inference features.
    Dynamic graph and static graph are supported at the same time,
1050
    switched by `paddle.enable_static()`. The usage is as follows.
1051
    But note, the switching between dynamic and static should be before
1052
    instantiating a Model. The input description, i.e, paddle.static.InputSpec,
1053
    must be required for static graph.
1054

1055
    When training on GPU, auto mixed precision (AMP O1) and pure float16
1056
    (AMP O2) training are both supported in static graph mode and dynamic mode.
1057
    In static graph mode, before training with pure float16 (AMP O2),
J
Jiaqi Liu 已提交
1058 1059
    `multi_precision` could be set to True when creating optimizer, which can
    avoid poor accuracy or slow convergence in a way, and inputs of dtype float
1060 1061 1062 1063
    should be cast to float16 by users. `paddle.static.amp.fp16_guard` API
    should be also used to limit the range of pure float16 training, otherwise,
    'use_fp16_guard' should be set to False by users. However, limiting the
    range of is not supported during training using AMP.
J
Jiaqi Liu 已提交
1064

1065
    Args:
1066 1067
        network (paddle.nn.Layer): The network is an instance of
            paddle.nn.Layer.
1068
        inputs (InputSpec|list|tuple|dict|None, optional): `inputs`, entry points of network,
1069
            could be a InputSpec instance, or list/tuple of InputSpec instances,
1070
            or dict ({name: InputSpec}), and it couldn't be None in static
1071 1072
            graph. Default: None.
        labels (InputSpec|list|tuple|None, optional): `labels`, entry points of network,
1073
            could be a InputSpec instnace or list/tuple of InputSpec instances,
1074
            or None. For static graph, if labels is required in loss,
1075
            labels must be set. Otherwise, it could be None. Default: None.
1076 1077


1078
    Examples:
J
Jiaqi Liu 已提交
1079 1080
        1. A common example

1081
        .. code-block:: python
1082
          :name: code-example1
1083

1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
            import paddle
            import paddle.nn as nn
            import paddle.vision.transforms as T
            from paddle.static import InputSpec

            device = paddle.set_device('cpu') # or 'gpu'

            net = nn.Sequential(
                nn.Flatten(1),
                nn.Linear(784, 200),
                nn.Tanh(),
                nn.Linear(200, 10))

            # inputs and labels are not required for dynamic graph.
            input = InputSpec([None, 784], 'float32', 'x')
            label = InputSpec([None, 1], 'int64', 'label')
1100

1101 1102 1103 1104 1105
            model = paddle.Model(net, input, label)
            optim = paddle.optimizer.SGD(learning_rate=1e-3,
                parameters=model.parameters())

            model.prepare(optim,
1106 1107
                        paddle.nn.CrossEntropyLoss(),
                        paddle.metric.Accuracy())
1108 1109 1110 1111 1112 1113 1114

            transform = T.Compose([
                T.Transpose(),
                T.Normalize([127.5], [127.5])
            ])
            data = paddle.vision.datasets.MNIST(mode='train', transform=transform)
            model.fit(data, epochs=2, batch_size=32, verbose=1)
J
Jiaqi Liu 已提交
1115 1116 1117 1118 1119


        2. An example using mixed precision training.

        .. code-block:: python
1120
          :name: code-example2
J
Jiaqi Liu 已提交
1121

1122 1123 1124 1125
            # required: gpu
            import paddle
            import paddle.nn as nn
            import paddle.vision.transforms as T
J
Jiaqi Liu 已提交
1126

1127 1128
            def run_example_code():
                device = paddle.set_device('gpu')
J
Jiaqi Liu 已提交
1129

1130 1131
                net = nn.Sequential(nn.Flatten(1), nn.Linear(784, 200), nn.Tanh(),
                                    nn.Linear(200, 10))
J
Jiaqi Liu 已提交
1132

1133 1134
                model = paddle.Model(net)
                optim = paddle.optimizer.SGD(learning_rate=1e-3, parameters=model.parameters())
J
Jiaqi Liu 已提交
1135

1136 1137 1138 1139 1140 1141 1142 1143 1144
                amp_configs = {
                    "level": "O1",
                    "custom_white_list": {'conv2d'},
                    "use_dynamic_loss_scaling": True
                }
                model.prepare(optim,
                    paddle.nn.CrossEntropyLoss(),
                    paddle.metric.Accuracy(),
                    amp_configs=amp_configs)
J
Jiaqi Liu 已提交
1145

1146 1147 1148 1149 1150 1151 1152
                transform = T.Compose([T.Transpose(), T.Normalize([127.5], [127.5])])
                data = paddle.vision.datasets.MNIST(mode='train', transform=transform)
                model.fit(data, epochs=2, batch_size=32, verbose=1)

            # mixed precision training is only supported on GPU now.
            if paddle.is_compiled_with_cuda():
                run_example_code()
J
Jiaqi Liu 已提交
1153

1154 1155
    """

1156
    def __init__(self, network, inputs=None, labels=None):
1157
        self.mode = 'train'
1158
        self.network = network
1159 1160
        self._inputs = None
        self._labels = None
1161
        self._loss = None
1162 1163
        self._loss_weights = None
        self._optimizer = None
L
LiuChiachi 已提交
1164
        self._input_info = None
1165
        self._is_shape_inferred = False
1166
        self._test_dataloader = None
L
LiuChiachi 已提交
1167
        self.stop_training = False
1168

J
Jiabin Yang 已提交
1169
        if not _non_static_mode():
1170
            if not isinstance(inputs, (list, tuple, dict, Input)):
1171
                raise TypeError(
1172 1173
                    "'inputs' must be list or tuple or dict, and couldn't be None."
                )
1174
        elif inputs:
L
LiuChiachi 已提交
1175
            self._input_info = _update_input_info(inputs)
L
LielinJiang 已提交
1176

1177
        self._inputs = self._verify_spec(inputs, is_input=True)
1178
        self._labels = self._verify_spec(labels)
1179

1180
        # init backend
J
Jiabin Yang 已提交
1181
        if fluid._non_static_mode():
1182 1183 1184 1185
            self._adapter = DynamicGraphAdapter(self)
        else:
            self._adapter = StaticGraphAdapter(self)

L
lyuwenyu 已提交
1186
    def train_batch(self, inputs, labels=None, update=True):
1187
        """
1188

L
lyuwenyu 已提交
1189 1190
        Run one training step on one batch of data. And using `update` indicates
        whether optimizer update gradients computing by this batch.
1191 1192

        Args:
1193 1194
            inputs (numpy.ndarray|Tensor|list): Batch of input data. It could
                be a numpy array or paddle.Tensor, or a list of arrays or
1195
                tensors (in case the model has multiple inputs).
1196 1197 1198
            labels (numpy.ndarray|Tensor|list, optional): Batch of labels. It could be
                a numpy array or paddle.Tensor, or a list of arrays or tensors
                (in case the model has multiple labels). If has no labels,
1199 1200 1201
                set None. Default: None.
            update (bool, optional): Whether update parameters after loss.backward() computing.
                Set it to False to accumulate gradients. Default: True.
1202 1203 1204 1205 1206 1207 1208 1209 1210

        Returns:
            A list of scalar training loss if the model has no metrics,
            or a tuple (list of scalar loss, list of metrics) if the model
            set metrics.

        Examples:

            .. code-block:: python
1211

1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
                import paddle
                import paddle.nn as nn
                from paddle.static import InputSpec

                device = paddle.set_device('cpu') # or 'gpu'

                net = nn.Sequential(
                    nn.Linear(784, 200),
                    nn.Tanh(),
                    nn.Linear(200, 10))

                input = InputSpec([None, 784], 'float32', 'x')
                label = InputSpec([None, 1], 'int64', 'label')
                model = paddle.Model(net, input, label)
                optim = paddle.optimizer.SGD(learning_rate=1e-3,
                    parameters=model.parameters())
                model.prepare(optim, paddle.nn.CrossEntropyLoss())
                data = paddle.rand((4, 784), dtype="float32")
                label = paddle.randint(0, 10, (4, 1), dtype="int64")
                loss = model.train_batch([data], [label])
                print(loss)
                # [array([2.192784], dtype=float32)]
1234

1235
        """
L
lyuwenyu 已提交
1236
        loss = self._adapter.train_batch(inputs, labels, update)
J
Jiabin Yang 已提交
1237
        if fluid._non_static_mode() and self._input_info is None:
L
LiuChiachi 已提交
1238
            self._update_inputs()
1239
        return loss
1240

Z
zhaoyingli 已提交
1241
    @no_grad()
1242 1243
    def eval_batch(self, inputs, labels=None):
        """
1244

1245 1246 1247
        Run one evaluating step on a batch of data.

        Args:
1248 1249
            inputs (numpy.ndarray|Tensor|list): Batch of input data. It could
                be a numpy array or paddle.Tensor, or a list of arrays or
1250
                tensors (in case the model has multiple inputs).
1251 1252 1253
            labels (numpy.ndarray|Tensor|list, optional): Batch of labels. It could be
                a numpy array or paddle.Tensor, or a list of arrays or tensors
                (in case the model has multiple labels). If has no labels,
1254
                set None. Default: None.
1255 1256 1257 1258 1259 1260 1261 1262 1263

        Returns:
            A list of scalar testing loss if the model has no metrics,
            or a tuple (list of scalar loss, list of metrics) if the model
            set metrics.

        Examples:

            .. code-block:: python
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287

                import paddle
                import paddle.nn as nn
                from paddle.static import InputSpec

                device = paddle.set_device('cpu') # or 'gpu'

                net = nn.Sequential(
                    nn.Linear(784, 200),
                    nn.Tanh(),
                    nn.Linear(200, 10))

                input = InputSpec([None, 784], 'float32', 'x')
                label = InputSpec([None, 1], 'int64', 'label')
                model = paddle.Model(net, input, label)
                optim = paddle.optimizer.SGD(learning_rate=1e-3,
                    parameters=model.parameters())
                model.prepare(optim,
                            paddle.nn.CrossEntropyLoss(), metrics=paddle.metric.Accuracy())
                data = paddle.rand((4, 784), dtype="float32")
                label = paddle.randint(0, 10, (4, 1), dtype="int64")
                loss, acc = model.eval_batch([data], [label])
                print(loss, acc)
                # [array([2.8825705], dtype=float32)] [0.0]
1288

1289
        """
1290
        loss = self._adapter.eval_batch(inputs, labels)
J
Jiabin Yang 已提交
1291
        if fluid._non_static_mode() and self._input_info is None:
L
LiuChiachi 已提交
1292
            self._update_inputs()
1293
        return loss
1294

Z
zhaoyingli 已提交
1295
    @no_grad()
1296
    def predict_batch(self, inputs):
1297
        """
1298

1299
        Run one predicting step on a batch of data.
1300 1301

        Args:
1302 1303
            inputs (numpy.ndarray|Tensor|list): Batch of input data. It could
                be a numpy array or paddle.Tensor, or a list of arrays or
1304
                tensors (in case the model has multiple inputs).
1305 1306 1307 1308 1309 1310 1311 1312

        Returns:
            A list of numpy.ndarray of predictions, that is the outputs
            of Model forward.

        Examples:

            .. code-block:: python
1313 1314 1315 1316 1317 1318

                import paddle
                import paddle.nn as nn
                from paddle.static import InputSpec

                device = paddle.set_device('cpu') # or 'gpu'
1319

1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
                input = InputSpec([None, 784], 'float32', 'x')
                label = InputSpec([None, 1], 'int64', 'label')

                net = nn.Sequential(
                    nn.Linear(784, 200),
                    nn.Tanh(),
                    nn.Linear(200, 10),
                    nn.Softmax())

                model = paddle.Model(net, input, label)
                model.prepare()
                data = paddle.rand((1, 784), dtype="float32")
                out = model.predict_batch([data])
                print(out)
                # [array([[0.08189095, 0.16740078, 0.06889386, 0.05085445, 0.10729759,
                #          0.02217775, 0.14518553, 0.1591538 , 0.01808308, 0.17906217]],
                #          dtype=float32)]
1337

1338
        """
1339
        loss = self._adapter.predict_batch(inputs)
J
Jiabin Yang 已提交
1340
        if fluid._non_static_mode() and self._input_info is None:
L
LiuChiachi 已提交
1341
            self._update_inputs()
1342
        return loss
1343

1344
    def save(self, path, training=True):
1345
        """
1346

1347
        This function saves parameters, optimizer information or model and
1348 1349
        paramters only for inference to path. It depends on the parameter
        `training`.
1350

1351
        If `training` is set to True, the parameters saved contain all
1352
        the trainable Variable, will save to a file with suffix ".pdparams".
1353 1354 1355 1356
        The optimizer information contains all the variable used by optimizer.
        For Adam optimizer, contains beta1, beta2, momentum etc. All the
        information will save to a file with suffix ".pdopt". (If the optimizer
        have no variable need to save (like SGD), the fill will not generated).
1357
        This function will silently overwrite existing file at the target location.
1358

1359
        If `training` is set to False, only inference model will be saved.
1360 1361

        Args:
1362 1363 1364
            path (str): The file prefix to save model. The format
                is 'dirname/file_prefix' or 'file_prefix'. if empty str.
                A exception will be raised.
1365 1366
            training (bool, optional): Whether to save for training. If not, save
                for inference only. Default: True.
1367 1368 1369 1370 1371 1372 1373

        Returns:
            None

        Examples:

            .. code-block:: python
1374

1375
                import paddle
1376
                import paddle.nn as nn
1377
                import paddle.vision.transforms as T
1378
                from paddle.static import InputSpec
1379

1380
                class Mnist(nn.Layer):
1381
                    def __init__(self):
1382
                        super().__init__()
1383
                        self.net = nn.Sequential(
L
LielinJiang 已提交
1384
                            nn.Flatten(1),
1385 1386 1387 1388
                            nn.Linear(784, 200),
                            nn.Tanh(),
                            nn.Linear(200, 10),
                            nn.Softmax())
1389

1390
                    def forward(self, x):
1391
                        return self.net(x)
1392

1393
                dynamic = True  # False
1394
                # if use static graph, do not set
1395 1396
                if not dynamic:
                    paddle.enable_static()
1397

1398 1399 1400
                input = InputSpec([None, 784], 'float32', 'x')
                label = InputSpec([None, 1], 'int64', 'label')
                model = paddle.Model(Mnist(), input, label)
1401
                optim = paddle.optimizer.SGD(learning_rate=1e-3,
1402
                    parameters=model.parameters())
1403
                model.prepare(optim, paddle.nn.CrossEntropyLoss())
1404

1405 1406 1407 1408 1409
                transform = T.Compose([
                    T.Transpose(),
                    T.Normalize([127.5], [127.5])
                ])
                data = paddle.vision.datasets.MNIST(mode='train', transform=transform)
1410

1411
                model.fit(data, epochs=1, batch_size=32, verbose=0)
1412 1413
                model.save('checkpoint/test')  # save for training
                model.save('inference_model', False)  # save for inference
1414

1415
        """
1416

1417
        if paddle.distributed.ParallelEnv().local_rank == 0:
1418 1419 1420 1421
            if not training:
                self._save_inference_model(path)
            else:
                self._adapter.save(path)
1422 1423 1424

    def load(self, path, skip_mismatch=False, reset_optimizer=False):
        """
1425

1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
        Load from files storing the model states and optimizer states. The file
        for optimizer states is not necessary if no need to restore the optimizer.

        NOTE: parameters are retrieved out from the file storing model states
        accoring to their structured names.

        For fine-tuning or transfer-learning models where some of the layers have
        changed, keep parameters needed to restore have same structured names in
        the pre-trained model and fine-tuning model.

        Args:
            path (str): The prefix of files storing the model states and
                optimizer states. The files would be `path.pdparams` and
                `path.pdopt` separately, and the latter is not necessary
                when no need to restore.
1441
            skip_mismatch (bool, optional): Whether to skip the loading of mismatch
1442 1443
                parameter or raise an error when mismatch happens (not found
                the parameter in file storing model states of or receives a
1444 1445
                mismatch shape). Default: False.
            reset_optimizer (bool, optional): If True, ignore the providing file storing
1446 1447
                optimizer states and initialize optimizer states from scratch.
                Otherwise, restore optimizer states from `path.pdopt` if
1448
                a optimizer has been set to the model. Default: False.
1449 1450 1451 1452 1453 1454 1455

        Returns:
            None

        Examples:

            .. code-block:: python
1456 1457 1458 1459

                import paddle
                import paddle.nn as nn
                from paddle.static import InputSpec
L
LielinJiang 已提交
1460

1461
                device = paddle.set_device('cpu')
L
LielinJiang 已提交
1462

1463
                input = InputSpec([None, 784], 'float32', 'x')
1464

1465 1466 1467 1468 1469
                model = paddle.Model(nn.Sequential(
                    nn.Linear(784, 200),
                    nn.Tanh(),
                    nn.Linear(200, 10),
                    nn.Softmax()), input)
L
LielinJiang 已提交
1470

1471 1472
                model.save('checkpoint/test')
                model.load('checkpoint/test')
1473

1474 1475 1476 1477 1478 1479
        """

        def _load_state_from_path(path):
            if not os.path.exists(path):
                return
            with open(path, 'rb') as f:
T
tianshuo78520a 已提交
1480
                return pickle.load(f, encoding='latin1')
1481 1482 1483 1484 1485

        def _check_match(key, param):
            state = param_state.get(key, None)
            if state is None:
                raise ValueError(
1486 1487
                    "{} is not found in the providing file.".format(key)
                )
1488 1489
            if list(state.shape) != list(param.shape):
                raise ValueError(
1490 1491 1492 1493
                    "{} receives a shape {}, but the expected shape is {}.".format(
                        key, list(state.shape), list(param.shape)
                    )
                )
1494 1495 1496 1497
            return param, state

        def _strip_postfix(path):
            path, ext = os.path.splitext(path)
1498 1499 1500 1501 1502 1503
            assert ext in [
                '',
                '.pdparams',
                '.pdopt',
                '.pdmodel',
            ], "Unknown postfix {} from weights".format(ext)
1504 1505 1506 1507 1508 1509 1510
            return path

        path = _strip_postfix(path)
        param_state = _load_state_from_path(path + ".pdparams")
        assert param_state, "Failed to load parameters, please check path."

        matched_param_state = []
1511
        for key, param in self.network.state_dict().items():
1512 1513 1514 1515 1516
            try:
                match_res = _check_match(key, param)
            except ValueError as err:
                if skip_mismatch:
                    warnings.warn(
1517 1518
                        ("Skip loading for {}. ".format(key) + str(err))
                    )
1519 1520 1521 1522 1523 1524
                    # reset optimizer when mismatch happens
                    reset_optimizer = True
                else:
                    raise err
            matched_param_state.append(match_res)

1525 1526 1527
        optim_state = (
            None if reset_optimizer else _load_state_from_path(path + ".pdopt")
        )
L
Leo Chen 已提交
1528 1529

        # TODO: support save/load scaler state in static graph
J
Jiabin Yang 已提交
1530
        if _non_static_mode():
L
Leo Chen 已提交
1531 1532 1533 1534 1535
            scaler_state = None
            if hasattr(self, '_scaler') and self._scaler is not None:
                if os.path.exists(path + '.pdscaler'):
                    scaler_state = paddle.load(path + '.pdscaler')

1536 1537 1538
            return self._adapter.load(
                matched_param_state, optim_state, scaler_state
            )
L
Leo Chen 已提交
1539 1540
        else:
            return self._adapter.load(matched_param_state, optim_state)
1541 1542 1543

    def parameters(self, *args, **kwargs):
        """
1544

1545 1546 1547 1548 1549 1550 1551 1552 1553
        Returns a list of parameters of the model.

        Returns:
            A list of Parameter in static graph.
            A list of ParamBase in dynamic graph.

        Examples:

            .. code-block:: python
1554

1555 1556 1557
                import paddle
                import paddle.nn as nn
                from paddle.static import InputSpec
1558

1559
                input = InputSpec([None, 784], 'float32', 'x')
1560

1561 1562 1563 1564
                model = paddle.Model(nn.Sequential(
                    nn.Linear(784, 200),
                    nn.Tanh(),
                    nn.Linear(200, 10)), input)
L
LielinJiang 已提交
1565

1566
                params = model.parameters()
1567

1568 1569 1570
        """
        return self._adapter.parameters()

J
Jiaqi Liu 已提交
1571 1572 1573
    def _prepare_amp(self, amp_configs):
        def _check_pure_fp16_configs():
            # pure float16 training has some restricts now
L
Leo Chen 已提交
1574 1575
            if self._adapter._amp_level == "O2" and self._optimizer._grad_clip:
                # clip by value is not supported
1576 1577 1578
                assert isinstance(
                    self._optimizer._grad_clip,
                    (paddle.nn.ClipGradByGlobalNorm, paddle.nn.ClipGradByNorm),
1579
                ), "Only ClipGradByNorm and ClipGradByGlobalNorm are supported in amp training with level=O2 currently."
J
Jiaqi Liu 已提交
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590

        self._adapter._amp_custom_lists = {}
        self._adapter._amp_configs = {}

        # check and get level of mixed precision training
        if not amp_configs:
            self._adapter._amp_level = 'O0'
            return
        elif isinstance(amp_configs, str):
            if amp_configs not in ('O0', 'O1', 'O2'):
                raise ValueError(
1591 1592
                    "The level of amp_configs should be 'O0', 'O1' or 'O2'."
                )
J
Jiaqi Liu 已提交
1593 1594 1595 1596 1597 1598 1599 1600
            self._adapter._amp_level = amp_configs
            _check_pure_fp16_configs()
            return
        else:
            if 'level' not in amp_configs:
                self._adapter._amp_level = 'O1'
            elif amp_configs['level'] not in ('O0', 'O1', 'O2'):
                raise ValueError(
1601 1602
                    "amp_configs['level'] should be 'O0', 'O1' or 'O2'."
                )
J
Jiaqi Liu 已提交
1603 1604 1605 1606 1607 1608 1609 1610
            else:
                self._adapter._amp_level = amp_configs['level']
        amp_config_key_set = set(amp_configs.keys()) - {'level'}
        if not amp_config_key_set or self._adapter._amp_level == 'O0':
            return

        if 'use_pure_fp16' in amp_configs:
            raise ValueError(
1611
                "'use_pure_fp16' is an invalid parameter, the level of mixed precision training only depends on 'O1' or 'O2'."
J
Jiaqi Liu 已提交
1612 1613 1614 1615 1616 1617 1618
            )

        _check_pure_fp16_configs()

        # construct amp_custom_lists
        if self._adapter._amp_level != 'O0' and amp_config_key_set:
            for param_name in [
1619 1620 1621
                'custom_white_list',
                'custom_black_list',
                'custom_black_varnames',
J
Jiaqi Liu 已提交
1622 1623 1624
            ]:
                if param_name in amp_config_key_set:
                    self._adapter._amp_custom_lists[param_name] = amp_configs[
1625 1626
                        param_name
                    ]
J
Jiaqi Liu 已提交
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
                    amp_config_key_set -= {param_name}

        def _check_amp_configs(amp_config_key_set):
            accepted_param_set = {
                'init_loss_scaling',
                'incr_ratio',
                'decr_ratio',
                'incr_every_n_steps',
                'decr_every_n_nan_or_inf',
                'use_dynamic_loss_scaling',
                'use_fp16_guard',
            }
            if amp_config_key_set - accepted_param_set:
                raise ValueError(
1641 1642 1643 1644
                    "Except for 'level', the keys of 'amp_configs' must be accepted by mixed precision APIs, but {} could not be recognized.".format(
                        tuple(amp_config_key_set - accepted_param_set)
                    )
                )
J
Jiaqi Liu 已提交
1645 1646

            if 'use_fp16_guard' in amp_config_key_set:
J
Jiabin Yang 已提交
1647
                if _non_static_mode():
J
Jiaqi Liu 已提交
1648
                    raise ValueError(
1649
                        "'use_fp16_guard' is supported in static graph mode only."
1650
                    )
J
Jiaqi Liu 已提交
1651 1652 1653 1654 1655 1656 1657 1658 1659
                self._adapter._use_fp16_guard = amp_configs['use_fp16_guard']
                amp_config_key_set.remove('use_fp16_guard')

            return amp_config_key_set

        amp_configs_set = _check_amp_configs(amp_config_key_set)
        for key in amp_configs_set:
            self._adapter._amp_configs[key] = amp_configs[key]

1660 1661 1662
    def prepare(
        self, optimizer=None, loss=None, metrics=None, amp_configs=None
    ):
1663
        """
1664

1665 1666 1667
        Configures the model before runing.

        Args:
1668
            optimizer (Optimizer|None, optional): Optimizer must be set in training
1669
                and should be a Optimizer instance. It can be None in eval
1670 1671
                and test mode. Default: None.
            loss (Loss|Callable|None, optional): Loss function can
1672
                be a `paddle.nn.Layer` instance or any callable function
1673
                taken the predicted values and ground truth values as input.
1674 1675 1676 1677
                It can be None when there is no loss. Default: None.
            metrics (Metric|list[Metric]|None, optional): If metrics is set, all
                metrics will be calculated and output in train/eval mode. Default: None.
            amp_configs (str|dict|None, optional): AMP configurations. If AMP or pure
J
Jiaqi Liu 已提交
1678 1679 1680
                float16 training is used, the key 'level' of 'amp_configs'
                should be set to 'O1' or 'O2' respectively. Otherwise, the
                value of 'level' defaults to 'O0', which means float32
1681 1682
                training. In addition to 'level', parameters consistent with
                mixed precision API could also be passed in. The supported
J
Jiaqi Liu 已提交
1683 1684 1685 1686
                keys are: 'init_loss_scaling', 'incr_ratio', 'decr_ratio',
                'incr_every_n_steps', 'decr_every_n_nan_or_inf',
                'use_dynamic_loss_scaling', 'custom_white_list',
                'custom_black_list', and 'custom_black_varnames'or
1687
                'use_fp16_guard' is only supported in static graph mode. Mixed
1688 1689 1690 1691 1692
                precision API documentations  :ref:`api_paddle_amp_auto_cast`
                and  :ref:`api_paddle_amp_GradScaler` could be referenced
                for details. For convenience, 'amp_configs' could be set to
                'O1' or 'O2' if no more parameters are needed. 'amp_configs'
                could be None in float32 training. Default: None.
1693

1694 1695
        Returns:
            None
1696

1697
        """
1698 1699
        self._place = _get_device()
        if isinstance(self._place, fluid.CUDAPlace):
1700
            global _parallel_context_initialized
1701 1702 1703 1704
            if (
                paddle.distributed.ParallelEnv().nranks > 1
                and not _parallel_context_initialized
            ):
J
Jiabin Yang 已提交
1705
                if fluid._non_static_mode():
1706
                    main_prog_seed = fluid.default_main_program().random_seed
1707 1708 1709
                    startup_prog_seed = (
                        fluid.default_startup_program().random_seed
                    )
1710
                    fluid.disable_dygraph()
1711
                    paddle.disable_static(self._place)
1712 1713 1714
                    # enable_dygraph would create and switch to a new program,
                    # thus also copy seed to the new program
                    fluid.default_main_program().random_seed = main_prog_seed
1715 1716 1717
                    fluid.default_startup_program().random_seed = (
                        startup_prog_seed
                    )
1718 1719 1720 1721 1722
                else:
                    prepare_distributed_context(self._place)
                _parallel_context_initialized = True

        self._optimizer = optimizer
1723 1724
        if loss is not None:
            if not isinstance(loss, paddle.nn.Layer) and not callable(loss):
1725 1726 1727
                raise TypeError(
                    "'loss' must be sub classes of `paddle.nn.Layer` or any callable function."
                )
1728
        self._loss = loss
1729 1730 1731

        metrics = metrics or []
        for metric in to_list(metrics):
1732 1733 1734
            assert isinstance(
                metric, Metric
            ), "{} is not sub class of Metric".format(metric.__class__.__name__)
1735
        self._metrics = to_list(metrics)
J
Jiaqi Liu 已提交
1736
        self._prepare_amp(amp_configs)
1737

L
Leo Chen 已提交
1738
        self._adapter.prepare()
1739

1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757
    def fit(
        self,
        train_data=None,
        eval_data=None,
        batch_size=1,
        epochs=1,
        eval_freq=1,
        log_freq=10,
        save_dir=None,
        save_freq=1,
        verbose=2,
        drop_last=False,
        shuffle=True,
        num_workers=0,
        callbacks=None,
        accumulate_grad_batches=1,
        num_iters=None,
    ):
1758
        """
1759

1760 1761 1762 1763
        Trains the model for a fixed number of epochs. If `eval_data` is set,
        evaluation will be done at the end of each epoch.

        Args:
1764 1765
            train_data (Dataset|DataLoader, optional): An iterable data loader is used for
                train. An instance of paddle paddle.io.Dataset or
1766
                paddle.io.Dataloader is recomended. Default: None.
1767
            eval_data (Dataset|DataLoader, optional): An iterable data loader is used for
1768 1769
                evaluation at the end of epoch. If None, will not do evaluation.
                An instance of paddle.io.Dataset or paddle.io.Dataloader
1770
                is recomended. Default: None.
1771
            batch_size (int|list, optional): The batch size of train_data and eval_data. When
1772 1773 1774 1775
                train_data and eval_data are both the instance of Dataloader, this
                parameter will be ignored. Default: 1.
            epochs (int, optional): The number of epochs to train the model. Default: 1.
            eval_freq (int, optional): The frequency, in number of epochs, an evalutation
1776
                is performed. Default: 1.
1777
            log_freq (int, optional): The frequency, in number of steps, the training logs
1778
                are printed. Default: 10.
1779
            save_dir(str|None, optional): The directory to save checkpoint during training.
1780
                If None, will not save checkpoint. Default: None.
1781
            save_freq (int, optional): The frequency, in number of epochs, to save
1782
                checkpoint. Default: 1.
1783
            verbose (int, optional): The verbosity mode, should be 0, 1, or 2. 0 = silent,
1784
                1 = progress bar, 2 = one line per epoch. Default: 2.
1785
            drop_last (bool, optional): Whether drop the last incomplete batch of
1786 1787 1788
                train_data when dataset size is not divisible by the batch size.
                When train_data is an instance of Dataloader, this parameter
                will be ignored. Default: False.
1789
            shuffle (bool, optional): Whther to shuffle train_data. When train_data is
1790 1791
                an instance of Dataloader, this parameter will be ignored.
                Default: True.
1792
            num_workers (int, optional): The number of subprocess to load data, 0 for no
1793 1794 1795
                subprocess used and loading data in main process.
                When train_data and eval_data are both the instance of
                Dataloader, this parameter will be ignored. Default: 0.
1796 1797 1798
            callbacks (Callback|None, optional): A list of `Callback` instances to apply
                during training. If None, :ref:`api_paddle_callbacks_ProgBarLogger` and
                :ref:`api_paddle_callbacks_ModelCheckpoint` are automatically inserted. Default: None.
1799
            accumulate_grad_batches (int, optional): The number of batches to accumulate gradident
L
lyuwenyu 已提交
1800
                during training process before optimizer updates. It can mimic large batch
L
lyuwenyu 已提交
1801
                size. Default: 1.
1802 1803 1804 1805
            num_iters (int|None, optional): The number of iterations to evaluate the model.
                If None, evaluate on whole input dataset, otherwise, evaluate `num_iters` times.
                Default: None.

1806 1807 1808 1809
        Returns:
            None

        Examples:
1810
            1. An example use Dataset and set batch size, shuffle in fit.
1811 1812 1813
               How to make a batch is done internally.

            .. code-block:: python
1814
              :name: code-example3
1815

1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848
                import paddle
                import paddle.vision.transforms as T
                from paddle.vision.datasets import MNIST
                from paddle.static import InputSpec

                dynamic = True
                if not dynamic:
                    paddle.enable_static()

                transform = T.Compose([
                    T.Transpose(),
                    T.Normalize([127.5], [127.5])
                ])
                train_dataset = MNIST(mode='train', transform=transform)
                val_dataset = MNIST(mode='test', transform=transform)

                input = InputSpec([None, 1, 28, 28], 'float32', 'image')
                label = InputSpec([None, 1], 'int64', 'label')

                model = paddle.Model(
                    paddle.vision.models.LeNet(),
                    input, label)
                optim = paddle.optimizer.Adam(
                    learning_rate=0.001, parameters=model.parameters())
                model.prepare(
                    optim,
                    paddle.nn.CrossEntropyLoss(),
                    paddle.metric.Accuracy(topk=(1, 2)))
                model.fit(train_dataset,
                            val_dataset,
                            epochs=2,
                            batch_size=64,
                            save_dir='mnist_checkpoint')
1849 1850 1851 1852 1853

            2. An example use DataLoader, batch size and shuffle is set in
               DataLoader.

            .. code-block:: python
1854
              :name: code-example4
1855 1856 1857 1858 1859

                import paddle
                import paddle.vision.transforms as T
                from paddle.vision.datasets import MNIST
                from paddle.static import InputSpec
1860

1861 1862 1863
                dynamic = True
                if not dynamic:
                    paddle.enable_static()
1864

1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877
                transform = T.Compose([
                        T.Transpose(),
                        T.Normalize([127.5], [127.5])
                    ])
                train_dataset = MNIST(mode='train', transform=transform)
                train_loader = paddle.io.DataLoader(train_dataset,
                    batch_size=64)
                val_dataset = MNIST(mode='test', transform=transform)
                val_loader = paddle.io.DataLoader(val_dataset,
                    batch_size=64)

                input = InputSpec([None, 1, 28, 28], 'float32', 'image')
                label = InputSpec([None, 1], 'int64', 'label')
1878

1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890
                model = paddle.Model(
                    paddle.vision.models.LeNet(), input, label)
                optim = paddle.optimizer.Adam(
                    learning_rate=0.001, parameters=model.parameters())
                model.prepare(
                    optim,
                    paddle.nn.CrossEntropyLoss(),
                    paddle.metric.Accuracy(topk=(1, 2)))
                model.fit(train_loader,
                            val_loader,
                            epochs=2,
                            save_dir='mnist_checkpoint')
1891

1892
        """
1893
        assert train_data is not None, "train_data must be given!"
1894

1895 1896 1897 1898 1899 1900 1901 1902 1903 1904
        if isinstance(batch_size, (tuple, list)) and all(
            [isinstance(x, int) for x in batch_size]
        ):
            assert (
                len(batch_size) == 2
            ), "batch_size length error, expected train_batch_size and eval_batch_size."
            train_batch_size, eval_batch_size = batch_size
        elif isinstance(batch_size, int):
            train_batch_size, eval_batch_size = batch_size, batch_size

1905
        if isinstance(train_data, Dataset):
1906 1907
            train_sampler = DistributedBatchSampler(
                train_data,
1908
                batch_size=train_batch_size,
1909 1910 1911 1912 1913 1914 1915 1916 1917 1918
                shuffle=shuffle,
                drop_last=drop_last,
            )
            train_loader = DataLoader(
                train_data,
                batch_sampler=train_sampler,
                places=self._place,
                num_workers=num_workers,
                return_list=True,
            )
1919 1920 1921 1922
        else:
            train_loader = train_data

        if eval_data is not None and isinstance(eval_data, Dataset):
1923
            eval_sampler = DistributedBatchSampler(
1924
                eval_data, batch_size=eval_batch_size
1925 1926 1927 1928 1929 1930 1931 1932
            )
            eval_loader = DataLoader(
                eval_data,
                batch_sampler=eval_sampler,
                places=self._place,
                num_workers=num_workers,
                return_list=True,
            )
1933 1934 1935 1936 1937 1938 1939
        elif eval_data is not None:
            eval_loader = eval_data
        else:
            eval_loader = None

        do_eval = eval_loader is not None
        self._test_dataloader = eval_loader
L
update  
lyuwenyu 已提交
1940

L
lyuwenyu 已提交
1941
        self._accumulate = accumulate_grad_batches
L
update  
lyuwenyu 已提交
1942

1943
        steps = self._len_data_loader(train_loader)
1944
        self.num_iters = num_iters
1945 1946 1947 1948 1949
        if (
            num_iters is not None
            and isinstance(num_iters, int)
            and isinstance(steps, int)
        ):
1950 1951 1952
            assert num_iters > 0, "num_iters must be greater than 0!"
            epochs = (num_iters // steps) + 1
            steps = min(num_iters, steps)
1953 1954 1955 1956 1957 1958 1959 1960 1961
        cbks = config_callbacks(
            callbacks,
            model=self,
            epochs=epochs,
            steps=steps,
            log_freq=log_freq,
            save_freq=save_freq,
            save_dir=save_dir,
            verbose=verbose,
1962 1963
            metrics=self._metrics_name(),
        )
1964

L
LiuChiachi 已提交
1965 1966 1967
        if any(isinstance(k, EarlyStopping) for k in cbks) and not do_eval:
            warnings.warn("EarlyStopping needs validation data.")

1968 1969 1970 1971 1972 1973 1974 1975 1976
        cbks.on_begin('train')
        for epoch in range(epochs):
            cbks.on_epoch_begin(epoch)
            logs = self._run_one_epoch(train_loader, cbks, 'train')
            cbks.on_epoch_end(epoch, logs)

            if do_eval and epoch % eval_freq == 0:

                eval_steps = self._len_data_loader(eval_loader)
1977 1978 1979 1980
                cbks.on_begin(
                    'eval',
                    {'steps': eval_steps, 'metrics': self._metrics_name()},
                )
1981 1982 1983 1984

                eval_logs = self._run_one_epoch(eval_loader, cbks, 'eval')

                cbks.on_end('eval', eval_logs)
1985 1986
            if self.stop_training:
                break
1987 1988 1989

        cbks.on_end('train', logs)
        self._test_dataloader = None
L
update  
lyuwenyu 已提交
1990

1991 1992 1993 1994 1995 1996 1997 1998 1999 2000
    def evaluate(
        self,
        eval_data,
        batch_size=1,
        log_freq=10,
        verbose=2,
        num_workers=0,
        callbacks=None,
        num_iters=None,
    ):
2001 2002 2003 2004 2005
        """
        Evaluate the loss and metrics of the model on input dataset.

        Args:
            eval_data (Dataset|DataLoader): An iterable data loader is used for
2006
                evaluation. An instance of paddle.io.Dataset or
2007
                paddle.io.Dataloader is recomended.
2008 2009 2010 2011
            batch_size (int, optional): The batch size of train_data and eval_data.
                When eval_data is the instance of Dataloader, this argument will be
                ignored. Default: 1.
            log_freq (int, optional): The frequency, in number of steps, the eval logs
2012
                are printed. Default: 10.
2013
            verbose (int, optional): The verbosity mode, should be 0, 1, or 2. 0 = silent,
2014
                1 = progress bar, 2 = one line per epoch. Default: 2.
2015
            num_workers (int, optional): The number of subprocess to load data,
2016 2017 2018
                0 for no subprocess used and loading data in main process. When
                train_data and eval_data are both the instance of Dataloader,
                this parameter will be ignored. Default: 0.
2019
            callbacks (Callback|None, optional): A list of `Callback` instances to apply
2020 2021
                during training. If None, `ProgBarLogger` and `ModelCheckpoint`
                are automatically inserted. Default: None.
2022 2023 2024
            num_iters (int|None, optional): The number of iterations to evaluate the model.
                If None, evaluate on whole input dataset, otherwise, evaluate `num_iters` times.
                Default: None.
2025 2026 2027 2028 2029
        Returns:
            dict: Result of metric. The key is the names of Metric,
                value is a scalar or numpy.array.

        Examples:
2030 2031

          .. code-block:: python
2032

2033 2034 2035
                import paddle
                import paddle.vision.transforms as T
                from paddle.static import InputSpec
2036

2037 2038 2039 2040 2041 2042
                # declarative mode
                transform = T.Compose([
                        T.Transpose(),
                        T.Normalize([127.5], [127.5])
                    ])
                val_dataset = paddle.vision.datasets.MNIST(mode='test', transform=transform)
2043

2044 2045 2046 2047 2048 2049 2050
                input = InputSpec([-1, 1, 28, 28], 'float32', 'image')
                label = InputSpec([None, 1], 'int64', 'label')
                model = paddle.Model(paddle.vision.models.LeNet(), input, label)
                model.prepare(metrics=paddle.metric.Accuracy())
                result = model.evaluate(val_dataset, batch_size=64)
                print(result)
                # {'acc': 0.0699}
2051 2052 2053
        """

        if eval_data is not None and isinstance(eval_data, Dataset):
2054 2055 2056 2057 2058 2059 2060 2061 2062 2063
            eval_sampler = DistributedBatchSampler(
                eval_data, batch_size=batch_size
            )
            eval_loader = DataLoader(
                eval_data,
                batch_sampler=eval_sampler,
                places=self._place,
                num_workers=num_workers,
                return_list=True,
            )
2064 2065 2066 2067 2068 2069 2070 2071 2072 2073
        else:
            eval_loader = eval_data

        self._test_dataloader = eval_loader

        cbks = config_callbacks(
            callbacks,
            model=self,
            log_freq=log_freq,
            verbose=verbose,
2074 2075
            metrics=self._metrics_name(),
        )
2076 2077

        eval_steps = self._len_data_loader(eval_loader)
2078
        self.num_iters = num_iters
2079 2080 2081 2082 2083
        if (
            num_iters is not None
            and isinstance(num_iters, int)
            and isinstance(eval_steps, int)
        ):
2084 2085 2086
            assert num_iters > 0, "num_iters must be greater than 0!"
            eval_steps = min(num_iters, eval_steps)
            self.num_iters = eval_steps
2087 2088 2089
        cbks.on_begin(
            'eval', {'steps': eval_steps, 'metrics': self._metrics_name()}
        )
2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102

        logs = self._run_one_epoch(eval_loader, cbks, 'eval')

        cbks.on_end('eval', logs)

        self._test_dataloader = None

        eval_result = {}
        for k in self._metrics_name():
            eval_result[k] = logs[k]

        return eval_result

2103 2104 2105 2106 2107 2108 2109 2110 2111
    def predict(
        self,
        test_data,
        batch_size=1,
        num_workers=0,
        stack_outputs=False,
        verbose=1,
        callbacks=None,
    ):
2112 2113 2114 2115 2116 2117 2118
        """
        Compute the output predictions on testing data.

        Args:
            test_data (Dataset|DataLoader): An iterable data loader is used for
                predict. An instance of paddle.io.Dataset or paddle.io.Dataloader
                is recomended.
2119 2120
            batch_size (int, optional): The batch size of test_data. When test_data is the
                instance of Dataloader, this argument will be ignored. Default: 1.
2121
            num_workers (int, optional): The number of subprocess to load data, 0 for no subprocess
2122 2123 2124 2125
                used and loading data in main process. When test_data is the instance of Dataloader,
                this argument will be ignored. Default: 0.
            stack_outputs (bool, optional): Whether stack output field like a batch, as for an output
                field of a sample is in shape [X, Y], test_data contains N samples, predict
2126
                output field will be in shape [N, X, Y] if stack_output is True, and will
2127
                be a length N list in shape [[X, Y], [X, Y], ..., [X, Y]] if stack_outputs
2128 2129
                is False. stack_outputs as False is used for LoDTensor output situation,
                it is recommended set as True if outputs contains no LoDTensor. Default: False.
2130
            verbose (int, optional): The verbosity mode, should be 0, 1, or 2. 0 = silent,
2131
                1 = progress bar, 2 = one line per batch. Default: 1.
2132
            callbacks(Callback, optional): A Callback instance, Default: None.
2133

2134 2135 2136 2137
        Returns:
            list: output of models.

        Examples:
2138 2139

          .. code-block:: python
2140

2141 2142 2143
                import numpy as np
                import paddle
                from paddle.static import InputSpec
2144

2145 2146
                class MnistDataset(paddle.vision.datasets.MNIST):
                    def __init__(self, mode, return_label=True):
2147
                        super().__init__(mode=mode)
2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178
                        self.return_label = return_label

                    def __getitem__(self, idx):
                        img = np.reshape(self.images[idx], [1, 28, 28])
                        if self.return_label:
                            return img, np.array(self.labels[idx]).astype('int64')
                        return img,

                    def __len__(self):
                        return len(self.images)

                test_dataset = MnistDataset(mode='test', return_label=False)

                # imperative mode
                input = InputSpec([-1, 1, 28, 28], 'float32', 'image')
                model = paddle.Model(paddle.vision.models.LeNet(), input)
                model.prepare()
                result = model.predict(test_dataset, batch_size=64)
                print(len(result[0]), result[0][0].shape)
                # 157 (64, 10)

                # declarative mode
                device = paddle.set_device('cpu')
                paddle.enable_static()
                input = InputSpec([-1, 1, 28, 28], 'float32', 'image')
                model = paddle.Model(paddle.vision.models.LeNet(), input)
                model.prepare()

                result = model.predict(test_dataset, batch_size=64)
                print(len(result[0]), result[0][0].shape)
                # 157 (64, 10)
2179 2180 2181
        """

        if test_data is not None and isinstance(test_data, Dataset):
2182 2183 2184 2185 2186 2187 2188 2189 2190 2191
            test_sampler = DistributedBatchSampler(
                test_data, batch_size=batch_size
            )
            test_loader = DataLoader(
                test_data,
                batch_sampler=test_sampler,
                places=self._place,
                num_workers=num_workers,
                return_list=True,
            )
2192 2193 2194 2195 2196
        else:
            test_loader = test_data

        self._test_dataloader = test_loader

2197
        cbks = config_callbacks(callbacks, model=self, verbose=verbose)
2198 2199 2200 2201

        test_steps = self._len_data_loader(test_loader)
        logs = {'steps': test_steps}

2202
        cbks.on_begin('predict', logs)
2203 2204 2205

        outputs = []

2206
        logs, outputs = self._run_one_epoch(test_loader, cbks, 'predict')
2207 2208 2209 2210 2211 2212 2213 2214 2215 2216

        outputs = list(zip(*outputs))

        # NOTE: for lod tensor output, we should not stack outputs
        # for stacking may lose its detail info
        if stack_outputs:
            outputs = [np.vstack(outs) for outs in outputs]

        self._test_dataloader = None

2217
        cbks.on_end('predict', logs)
2218 2219
        return outputs

2220
    def _save_inference_model(self, path):
2221
        """
2222
        Save inference model can be used in static or dynamic mode.
2223 2224

        Args:
2225 2226
            path (str): The path prefix to save model. The format is
                ``dirname/file_prefix`` or ``file_prefix``.
2227
        Returns:
2228
            None
2229 2230
        """

J
Jiabin Yang 已提交
2231
        if fluid._non_static_mode():
2232 2233
            with fluid.framework._dygraph_guard(None):
                layer = self.network
L
LiuChiachi 已提交
2234
                if self._input_info is None:  # No provided or inferred
2235
                    raise RuntimeError(
L
LiuChiachi 已提交
2236
                        "Saving inference model needs 'inputs' or running before saving. Please specify 'inputs' in Model initialization or input training data and perform a training for shape derivation."
2237 2238 2239 2240
                    )
                if self._is_shape_inferred:
                    warnings.warn(
                        "'inputs' was not specified when Model initialization, so the input shape to be saved will be the shape derived from the user's actual inputs. The input shape to be saved is %s. For saving correct input shapes, please provide 'inputs' for Model initialization."
2241 2242
                        % self._input_info[0]
                    )
L
LiuChiachi 已提交
2243

2244
                paddle.jit.save(layer, path, input_spec=self._inputs)
2245

2246
        else:
2247 2248 2249 2250 2251 2252
            # path check
            file_prefix = os.path.basename(path)
            if file_prefix == "":
                raise ValueError(
                    "The input path MUST be format of dirname/file_prefix "
                    "[dirname\\file_prefix in Windows system], but received "
2253 2254
                    "file_prefix is empty string."
                )
2255 2256 2257 2258 2259 2260 2261 2262 2263

            dirname = os.path.dirname(path)
            if dirname and not os.path.exists(dirname):
                os.makedirs(dirname)

            model_path = dirname
            model_filename = file_prefix + INFER_MODEL_SUFFIX
            params_filename = file_prefix + INFER_PARAMS_SUFFIX

2264
            prog = self._adapter._progs.get('test', None)
2265 2266 2267
            assert (
                prog
            ), "Model is not ready, please call `model.prepare()` first"
2268 2269 2270 2271 2272 2273

            infer_prog = prog.clone(for_test=True)

            input_names = [v.name for v in self._adapter._input_vars['test']]
            endpoints = self._adapter._endpoints['test']['output']

2274 2275 2276 2277 2278 2279 2280 2281 2282
            fluid.io.save_inference_model(
                model_path,
                input_names,
                endpoints,
                self._adapter._executor,
                main_program=infer_prog,
                model_filename=model_filename,
                params_filename=params_filename,
            )
2283

L
update  
lyuwenyu 已提交
2284
    def _run_one_epoch(
2285 2286 2287 2288 2289 2290
        self,
        data_loader,
        callbacks,
        mode,
        logs={},
    ):
2291 2292 2293 2294 2295 2296 2297 2298 2299 2300
        outputs = []
        for step, data in enumerate(data_loader):
            # data might come from different types of data_loader and have
            # different format, as following:
            # 1. DataLoader in static graph:
            #    [[input1, input2, ..., label1, lable2, ...]]
            # 2. DataLoader in dygraph
            #    [input1, input2, ..., label1, lable2, ...]
            # 3. custumed iterator yield concated inputs and labels:
            #   [input1, input2, ..., label1, lable2, ...]
2301
            # 4. custumed iterator yield separated inputs and labels:
2302 2303
            #   ([input1, input2, ...], [label1, lable2, ...])
            # To handle all of these, flatten (nested) list to list.
2304
            data = paddle.utils.flatten(data)
2305 2306
            # LoDTensor.shape is callable, where LoDTensor comes from
            # DataLoader in static graph
2307

2308 2309 2310 2311 2312
            batch_size = (
                data[0].shape()[0]
                if callable(data[0].shape)
                else data[0].shape[0]
            )
2313 2314 2315

            callbacks.on_batch_begin(mode, step, logs)

2316
            if mode != 'predict':
2317
                _inputs = [data[: len(self._inputs)], data[len(self._inputs) :]]
L
lyuwenyu 已提交
2318
                if mode == 'train':
2319 2320 2321 2322
                    _inputs.append(
                        (step + 1) % self._accumulate == 0
                        or step + 1 == len(data_loader)
                    )
L
update  
lyuwenyu 已提交
2323

L
lyuwenyu 已提交
2324
                outs = getattr(self, mode + '_batch')(*_inputs)
L
update  
lyuwenyu 已提交
2325

2326
                if self._metrics and self._loss:
2327
                    metrics = [[float(l) for l in outs[0]]]
2328
                elif self._loss:
2329
                    metrics = [[float(l) for l in outs]]
2330 2331
                else:
                    metrics = []
2332 2333 2334 2335 2336 2337 2338 2339 2340 2341

                # metrics
                for metric in self._metrics:
                    res = metric.accumulate()
                    metrics.extend(to_list(res))

                assert len(self._metrics_name()) == len(metrics)
                for k, v in zip(self._metrics_name(), metrics):
                    logs[k] = v
            else:
L
LielinJiang 已提交
2342
                if self._inputs is not None:
2343
                    outs = self.predict_batch(data[: len(self._inputs)])
L
LielinJiang 已提交
2344
                else:
2345
                    outs = self.predict_batch(data)
L
LielinJiang 已提交
2346

2347 2348 2349
                outputs.append(outs)

            logs['step'] = step
2350 2351 2352 2353
            if (
                mode == 'train'
                or self._adapter._merge_count.get(mode + '_batch', 0) <= 0
            ):
2354 2355 2356
                logs['batch_size'] = (
                    batch_size * paddle.distributed.ParallelEnv().nranks
                )
2357 2358 2359 2360
            else:
                logs['batch_size'] = self._adapter._merge_count[mode + '_batch']

            callbacks.on_batch_end(mode, step, logs)
2361 2362
            if hasattr(self, 'num_iters') and self.num_iters is not None:
                self.num_iters -= 1
2363 2364 2365
                if self.num_iters <= 0:
                    self.stop_training = True
                    del self.num_iters
2366
                    break
2367 2368
        self._reset_metrics()

2369
        if mode == 'predict':
2370 2371 2372
            return logs, outputs
        return logs

L
LielinJiang 已提交
2373
    def summary(self, input_size=None, dtype=None):
L
LielinJiang 已提交
2374 2375 2376
        """Prints a string summary of the network.

        Args:
2377 2378 2379 2380
            input_size (tuple|InputSpec|list[tuple|InputSpec], optional): size of input tensor.
                    if not set, input_size will get from ``self._inputs`` if network only have
                    one input, input_size can be tuple or InputSpec. if model have multiple
                    input, input_size must be a list which contain every input's shape.
L
LielinJiang 已提交
2381
                    Default: None.
2382
            dtype (str, optional): if dtype is None, 'float32' will be used, Default: None.
L
LielinJiang 已提交
2383 2384 2385 2386 2387 2388

        Returns:
            Dict: a summary of the network including total params and total trainable params.

        Examples:
            .. code-block:: python
2389 2390 2391 2392 2393 2394

                import paddle
                from paddle.static import InputSpec

                input = InputSpec([None, 1, 28, 28], 'float32', 'image')
                label = InputSpec([None, 1], 'int64', 'label')
L
LielinJiang 已提交
2395

2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406
                model = paddle.Model(paddle.vision.models.LeNet(),
                    input, label)
                optim = paddle.optimizer.Adam(
                    learning_rate=0.001, parameters=model.parameters())
                model.prepare(
                    optim,
                    paddle.nn.CrossEntropyLoss())

                params_info = model.summary()
                print(params_info)
                # {'total_params': 61610, 'trainable_params': 61610}
L
LielinJiang 已提交
2407 2408

        """
2409 2410 2411
        assert (
            input_size is not None or self._inputs is not None
        ), "'input_size' or 'self._input' must be set"
2412 2413 2414 2415
        if input_size is not None:
            _input_size = input_size
        else:
            _input_size = self._inputs
2416
        return summary(self.network, _input_size, dtypes=dtype)
L
LielinJiang 已提交
2417

L
LiuChiachi 已提交
2418
    def _verify_spec(self, specs, shapes=None, dtypes=None, is_input=False):
2419 2420
        out_specs = []

2421 2422 2423 2424 2425 2426
        if specs is None:
            # Note(Aurelius84): If not specific specs of `Input`, using argument names of `forward` function
            # to generate `Input`. But how can we know the actual shape of each input tensor?

            if is_input:
                arg_names = extract_args(self.network.forward)[1:]
L
LiuChiachi 已提交
2427
                # While Saving inference model in dygraph, and providing inputs only in running.
2428 2429 2430 2431
                if (
                    shapes is not None
                    and dtypes is not None
                    and fluid._non_static_mode()
L
LiuChiachi 已提交
2432
                ):
2433
                    out_specs = [
2434
                        Input(name=n, dtype=dtypes[i], shape=shapes[i])
2435 2436 2437 2438 2439 2440 2441
                        for i, n in enumerate(arg_names)
                    ]
                else:
                    out_specs = [Input(name=n, shape=[None]) for n in arg_names]
            else:
                out_specs = to_list(specs)
        elif isinstance(specs, dict):
2442 2443
            assert is_input is False
            out_specs = [
2444 2445
                specs[n]
                for n in extract_args(self.network.forward)
2446 2447
                if n != 'self'
            ]
2448 2449 2450 2451 2452 2453 2454 2455
        else:
            out_specs = to_list(specs)
        # Note: checks each element has specificed `name`.
        if out_specs is not None:
            for i, spec in enumerate(out_specs):
                assert isinstance(spec, Input)
                if spec.name is None:
                    raise ValueError(
2456 2457 2458 2459
                        "Requires Input[{}].name != None, but receive `None` with {}.".format(
                            i, spec
                        )
                    )
2460 2461 2462

        return out_specs

2463 2464 2465 2466 2467
    def _reset_metrics(self):
        for metric in self._metrics:
            metric.reset()

    def _metrics_name(self):
2468
        metrics_name = ['loss'] if self._loss else []
2469 2470 2471 2472 2473 2474 2475 2476 2477 2478
        for m in self._metrics:
            metrics_name.extend(to_list(m.name()))
        return metrics_name

    def _len_data_loader(self, data_loader):
        try:
            steps = len(data_loader)
        except Exception:
            steps = None
        return steps
L
LiuChiachi 已提交
2479 2480 2481

    def _update_inputs(self):
        "Update self._inputs according to given inputs."
L
LiuChiachi 已提交
2482 2483
        self._input_info = self._adapter._input_info
        if self._input_info is not None and len(self._input_info) == 2:
2484 2485 2486
            self._inputs = self._verify_spec(
                None, self._input_info[0], self._input_info[1], True
            )
L
LiuChiachi 已提交
2487
            self._is_shape_inferred = True