model.py 77.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 15 16 17 18 19 20 21 22 23 24
#
# 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.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import inspect
import os
import pickle
import numpy as np
import six
import warnings
25 26 27
import time
import socket
import contextlib
28 29
from collections import Iterable

30
import paddle
31
from paddle import fluid
32 33
from paddle.fluid import core
from paddle.fluid.framework import in_dygraph_mode, Variable, ParamBase, _current_expected_place
34 35
from paddle.fluid.framework import in_dygraph_mode, Variable
from paddle.fluid.framework import _current_expected_place as _get_device
36 37 38 39
from paddle.fluid.executor import global_scope
from paddle.fluid.io import is_belong_to_optimizer
from paddle.fluid.dygraph.base import to_variable
from paddle.fluid.dygraph.parallel import ParallelEnv
40
from paddle.fluid.dygraph.dygraph_to_static.program_translator import ProgramTranslator, FunctionSpec
41
from paddle.fluid.layers.utils import flatten
42
from paddle.fluid.layers import collective
43 44
from paddle.fluid.incubate.fleet.collective import fleet, DistributedStrategy
from paddle.fluid.incubate.fleet.base import role_maker
45

46 47
from paddle.io import DataLoader, Dataset, DistributedBatchSampler
from paddle.fluid.executor import scope_guard, Executor
48
from paddle.fluid.dygraph.layers import Layer
49
from paddle.metric import Metric
50 51
from paddle.static import InputSpec as Input

52
from .callbacks import config_callbacks
L
LielinJiang 已提交
53
from .model_summary import summary
54

55 56 57 58 59 60 61 62 63 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 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
__all__ = ['Model', ]

_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):
    assert isinstance(var, (Variable, fluid.core.VarBase)), "not a variable"
    if isinstance(var, fluid.core.VarBase):
        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):
    if hasattr(inspect, 'getfullargspec'):
        return inspect.getfullargspec(func)[0]
    else:
        return inspect.getargspec(func)[0]


def _all_gather(x, nranks, ring_id=0, use_calc_stream=True):
    return collective._c_allgather(
        x, nranks, ring_id=ring_id, use_calc_stream=use_calc_stream)


def wait_server_ready(endpoints):
    assert not isinstance(endpoints, six.string_types)
    while True:
        all_ok = True
        not_ready_endpoints = []
        for ep in endpoints:
            ip_port = ep.split(":")
            with contextlib.closing(
                    socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
                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


def init_communicator(program, rank, nranks, wait_port, current_endpoint,
                      endpoints):
    if nranks < 2:
        return
    other_endpoints = endpoints[:]
    other_endpoints.remove(current_endpoint)
    if rank == 0 and wait_port:
        wait_server_ready(other_endpoints)
    block = program.global_block()
    nccl_id_var = block.create_var(
        name=fluid.unique_name.generate('nccl_id'),
        persistable=True,
        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,
        })


def prepare_distributed_context(place=None):
    if place is None:
        place = fluid.CUDAPlace(ParallelEnv().dev_id) if ParallelEnv().nranks > 1 \
            else fluid.CUDAPlace(0)

    strategy = fluid.dygraph.parallel.ParallelStrategy()
    strategy.nranks = ParallelEnv().nranks
    strategy.local_rank = ParallelEnv().local_rank
    strategy.trainer_endpoints = ParallelEnv().trainer_endpoints
    strategy.current_endpoint = ParallelEnv().current_endpoint

    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()
            init_communicator(communicator_prog, strategy.local_rank,
                              strategy.nranks, True, strategy.current_endpoint,
                              strategy.trainer_endpoints)
            exe = fluid.Executor(place)
            exe.run(communicator_prog)

        if fluid.in_dygraph_mode():
            fluid.disable_dygraph()
            _init_context()
            fluid.enable_dygraph(place)
        else:
            _init_context()

    else:
        assert ("Only support CUDAPlace for now.")

    _parallel_context_initialized = True
    return strategy
201 202


203
def _update_input_shapes(inputs):
L
LiuChiachi 已提交
204
    "Get input shape list by given inputs in Model initialization."
205
    shapes = None
L
LiuChiachi 已提交
206 207 208
    if isinstance(inputs, Input):
        shapes = [list(inputs.shape)]
    elif isinstance(inputs, list):
209 210 211 212 213 214
        shapes = [list(input.shape) for input in inputs]
    elif isinstance(inputs, dict):
        shapes = [list(inputs[name].shape) for name in inputs]
    return shapes


215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
class StaticGraphAdapter(object):
    """
    Model traning/inference with a static graph.
    """

    def __init__(self, model):
        super(StaticGraphAdapter, self).__init__()
        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,
            'test_batch': 0
        }

        self._nranks = ParallelEnv().nranks
        self._local_rank = ParallelEnv().local_rank

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

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

    def train_batch(self, inputs, labels=None):
        assert self.model._optimizer, \
            "model not ready, please call `model.prepare()` first"
        self.mode = 'train'
        return self._run(inputs, labels)

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

264
    def predict_batch(self, inputs):
265 266 267 268
        self.mode = 'test'
        return self._run(inputs, None)

    def parameters(self, *args, **kwargs):
269
        return self.model.network.parameters(*args, **kwargs)
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287

    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"
288
        _save(self.model.network.state_dict(), param_path)
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 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 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
        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 = {
            p.name: p
            for p in filter(is_belong_to_optimizer, prog.list_vars())
        }
        if not optim:
            return

        _save(optim, optim_path)

    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(
            [param for param, state in param_state_pairs],
            global_scope(), executor)
        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 = (
                    np.array(converted_state.pop("global_step")) - 1
                ) if "global_step" in converted_state else converted_state.pop(
                    "@LR_DECAY_COUNTER@", None)
                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():
                        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():
                            if opt_unq_name is None:
                                # can not infer out the exact unique(opt_name),
                                # thus try to extract rather than generate
                                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) + "_"
                                    if state_key.startswith(prefix):
                                        prefix_offset = state_key[len(
                                            prefix):].find("_") + len(prefix)
                                        opt_unq_name = state_key[len(
                                            param_name + "_"):prefix_offset]
                                        # 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
                            dy_state_name = (param_name + "_" + opt_unq_name +
                                             "_" + accum_name + "_0")
                            converted_state[
                                state_var.name] = converted_state.pop(
                                    dy_state_name)

            assert var.name in converted_state, \
                "variable [{}] is not in optimizer state file".format(var.name)
            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)
        assert compiled_prog, \
            "Model is not ready, please call `model.prepare()` first"

        inputs = to_list(inputs)
        if labels is not None:
            labels = to_list(labels)
        assert len(inputs) == len(self._input_vars[self.mode]), \
            "number of inputs" \
            + " does not match number of arguments of `forward` method"

        feed = {}
        input_names = [v.name for v in self._input_vars[self.mode]]
        for idx, n in enumerate(input_names):
            # train and test may take different arguments
            if inputs[idx] is not None:
                feed[n] = inputs[idx]
        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)

        rets = self._executor.run(compiled_prog,
                                  feed=feed,
                                  fetch_list=pruned_fetch_list,
                                  return_numpy=False)

        # 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])

456
        # step learning rate scheduler on each batch end
457 458
        if self.model._optimizer and self.mode == 'train' and \
                hasattr(self.model._optimizer, '_learning_rate') and \
459 460 461 462
                isinstance(self.model._optimizer._learning_rate,
                           paddle.optimizer.lr.LRScheduler):
            self.model._optimizer._learning_rate.step()

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

468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
        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
            if self.mode != 'train' and self.model._test_dataloader is not None \
                    and isinstance(self.model._test_dataloader, DataLoader) \
                    and self._nranks > 1:
                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 = [
                        s[:int(total_size - current_count), ...] for s in state
                    ]
                    self._merge_count[self.mode + '_total'] = 0
                    self._merge_count[self.mode + '_batch'] = int(total_size -
                                                                  current_count)
                else:
                    self._merge_count[self.mode + '_total'] += samples
                    self._merge_count[self.mode + '_batch'] = samples

            metrics.append(metric.update(*state))
491 492 493 494 495

        if num_loss and len(metrics):
            return rets[:num_loss], metrics
        else:
            return rets[:num_loss] if num_loss else metrics
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526

    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)
        if mode == 'train' and self.model._optimizer \
                and self.model._optimizer._learning_rate_map:
            # 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):
527 528
            inputs = self.model._inputs
            labels = self.model._labels if self.model._labels else []
529 530
            inputs = [k._create_feed_layer() for k in to_list(inputs)]
            labels = [k._create_feed_layer() for k in to_list(labels)]
531
            self._label_vars[mode] = labels
532
            outputs = to_list(self.model.network.forward(*inputs))
533

534 535
            if mode != 'test' and self.model._loss:
                losses = self.model._loss(*(outputs + labels))
536 537 538 539 540 541 542 543

            if self._nranks > 1 and mode != 'train':
                outputs = [_all_gather(o, self._nranks) for o in outputs]
                if mode != 'test':
                    labels = [_all_gather(l, self._nranks) for l in labels]

            if mode != 'test':
                for metric in self.model._metrics:
544
                    metrics.append(to_list(metric.compute(*(outputs + labels))))
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566

            if mode == 'train' and self.model._optimizer:
                self._loss_endpoint = fluid.layers.sum(losses)
                if self._nranks > 1:
                    role = role_maker.PaddleCloudRoleMaker(is_collective=True)
                    fleet.init(role)
                    dist_strategy = DistributedStrategy()
                    dist_strategy.mode = "collective"
                    dist_strategy.collective_mode = "grad_allreduce"
                    self.model._optimizer = fleet.distributed_optimizer(
                        self.model._optimizer, strategy=dist_strategy)

                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,
567
            "loss": to_list(losses),
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
            "metric": metrics
        }

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

        assert self.model._place is not None, \
            "device is not set, please call `model.prepare()` first"

        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)
                if not var_py.name.startswith('nccl_id') and var and \
                        var.get_tensor()._is_initialized():
                    continue

                uninitialized.append(var_py)
            if uninitialized:
                startup_prog = self._startup_prog._prune(uninitialized)
                self._executor.run(startup_prog)

        if self._nranks < 2:
            compiled_prog = fluid.CompiledProgram(prog)
        else:
            compiled_prog = prog

        self._compiled_progs[mode] = compiled_prog


class DynamicGraphAdapter(object):
    def __init__(self, model):
        super(DynamicGraphAdapter, self).__init__()
        self.model = model
        self._nranks = ParallelEnv().nranks
        self._local_rank = ParallelEnv().local_rank
        self._merge_count = {
            'eval_total': 0,
            'test_total': 0,
            'eval_batch': 0,
            'test_batch': 0
        }

620
        self._input_shapes = None
621 622 623 624 625 626
        if self._nranks > 1:
            stradegy = fluid.dygraph.parallel.ParallelStrategy()
            stradegy.nranks = ParallelEnv().nranks
            stradegy.local_rank = ParallelEnv().local_rank
            stradegy.trainer_endpoints = ParallelEnv().trainer_endpoints
            stradegy.current_endpoint = ParallelEnv().current_endpoint
627 628
            self.ddp_model = fluid.dygraph.parallel.DataParallel(
                self.model.network, stradegy)
629 630 631 632 633 634 635 636 637 638 639 640 641

    @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
    def train_batch(self, inputs, labels=None):
        assert self.model._optimizer, \
            "model not ready, please call `model.prepare()` first"
642
        self.model.network.train()
643 644
        self.mode = 'train'
        inputs = to_list(inputs)
645
        self._input_shapes = _update_input_shapes(inputs)
646 647 648
        labels = labels or []
        labels = [to_variable(l) for l in to_list(labels)]

649 650 651
        if self._nranks > 1:
            outputs = self.ddp_model.forward(* [to_variable(x) for x in inputs])
        else:
652 653
            outputs = self.model.network.forward(
                * [to_variable(x) for x in inputs])
654 655 656 657 658

        losses = self.model._loss(*(to_list(outputs) + labels))
        losses = to_list(losses)
        final_loss = fluid.layers.sum(losses)
        final_loss.backward()
659 660

        self.model._optimizer.minimize(final_loss)
661
        self.model.network.clear_gradients()
662 663 664 665 666 667 668

        # step learning rate scheduler on each batch end
        if self.model._optimizer and \
                isinstance(self.model._optimizer._learning_rate,
                           paddle.optimizer.lr.LRScheduler):
            self.model._optimizer._learning_rate.step()

669 670
        metrics = []
        for metric in self.model._metrics:
671
            metric_outs = metric.compute(*(to_list(outputs) + labels))
672 673 674 675 676 677 678
            m = metric.update(* [to_numpy(m) for m in to_list(metric_outs)])
            metrics.append(m)

        return ([to_numpy(l) for l in losses], metrics) \
            if len(metrics) > 0 else [to_numpy(l) for l in losses]

    def eval_batch(self, inputs, labels=None):
679
        self.model.network.eval()
680 681
        self.mode = 'eval'
        inputs = to_list(inputs)
682
        self._input_shapes = _update_input_shapes(inputs)
683 684 685
        labels = labels or []
        labels = [to_variable(l) for l in to_list(labels)]

686
        outputs = self.model.network.forward(* [to_variable(x) for x in inputs])
687 688
        if self.model._loss:
            losses = self.model._loss(*(to_list(outputs) + labels))
689 690
            losses = to_list(losses)

691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
        if self._nranks > 1:
            outputs = [_all_gather(o, self._nranks) for o in to_list(outputs)]
            labels = [_all_gather(l, self._nranks) for l in labels]
        metrics = []
        for metric in self.model._metrics:
            # cut off padding value.
            if self.model._test_dataloader is not None and self._nranks > 1 \
                    and isinstance(self.model._test_dataloader, DataLoader):
                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 = [
                        o[:int(total_size - current_count)] for o in outputs
                    ]
                    labels = [
                        l[:int(total_size - current_count)] for l in labels
                    ]
                    self._merge_count[self.mode + '_total'] = 0
                    self._merge_count[self.mode + '_batch'] = int(total_size -
                                                                  current_count)
                else:
                    self._merge_count[self.mode + '_total'] += samples
                    self._merge_count[self.mode + '_batch'] = samples

716
            metric_outs = metric.compute(*(to_list(outputs) + labels))
717 718 719
            m = metric.update(* [to_numpy(m) for m in to_list(metric_outs)])
            metrics.append(m)

720
        if self.model._loss and len(metrics):
721
            return [to_numpy(l) for l in losses], metrics
722
        elif self.model._loss:
723 724 725
            return [to_numpy(l) for l in losses]
        else:
            return metrics
726

727
    def predict_batch(self, inputs):
728
        self.model.network.eval()
729 730
        self.mode = 'test'
        inputs = [to_variable(x) for x in to_list(inputs)]
731
        self._input_shapes = _update_input_shapes(inputs)
732
        outputs = self.model.network.forward(*inputs)
733 734 735 736 737 738
        if self._nranks > 1 and isinstance(self.model._place, fluid.CUDAPlace):
            outputs = [_all_gather(o, self._nranks) for o in to_list(outputs)]

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

    def parameters(self, *args, **kwargs):
739
        return self.model.network.parameters(*args, **kwargs)
740 741

    def save(self, path):
742
        params = self.model.network.state_dict()
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
        fluid.save_dygraph(params, path)
        if self.model._optimizer is None:
            return
        if self.model._optimizer.state_dict():
            optim = self.model._optimizer.state_dict()
            fluid.save_dygraph(optim, path)

    def load(self, param_state_pairs, optim_state):
        # restore parameter states
        for param, state in param_state_pairs:
            param.set_value(state)

        # resotre optimizer states
        if not self.model._optimizer or not optim_state:
            return

759 760
        # 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
761 762 763 764 765 766 767 768 769 770 771
        # 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__
        opt_name = opt_unq_name[:opt_unq_name.rfind("_")]  # remove suffix idx
772
        param_names = [param.name for param in self.model.network.parameters()]
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
        for var_name, state_var in sorted(
                optim_state.items(), key=lambda x: len(x[0]), reverse=True):
            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@":
                    converted_state["global_step"] = np.array(
                        converted_state.pop("@LR_DECAY_COUNTER@")) + 1
            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
                        accum_name = var_name[len(param_name + "_" + opt_name +
                                                  "_"):]
                    elif var_name.startswith(param_name +
                                             "_") and opt_name == opt_cls_name:
                        # when init optimizer without name
                        accum_name = var_name[len(param_name + "_"):]
                    else:
                        continue
                    # remove suffix idx
                    accum_name = accum_name[:accum_name.rfind("_")]
                    # state names always end with "_0" in dygraph because of the
                    # unique optimizer._name
                    dy_state_name = (param_name + "_" + opt_unq_name + "_" +
                                     accum_name + "_0")
                    converted_state[dy_state_name] = state_var

804 805
        if not hasattr(self.model._optimizer, 'set_state_dict'):
            warnings.warn(
806
                "paddle.fluid.optimizer is deprecated in API 2.0, please use paddle.optimizer instead."
807 808 809 810
            )
            self.model._optimizer.set_dict(converted_state)
        else:
            self.model._optimizer.set_state_dict(converted_state)
811 812


813
class Model(object):
814 815 816
    """
    An Model object is network with training and inference features.
    Dynamic graph and static graph are supported at the same time,
817
    switched by `paddle.disable_static()`. The usage is as follows.
818
    But note, the switching between dynamic and static should be before
819
    instantiating a Model. The input description, i.e, paddle.static.InputSpec,
820
    must be required for static graph.
821

822
    Args:
823 824
        network (paddle.nn.Layer): The network is an instance of
            paddle.nn.Layer.
825 826
        inputs (InputSpec|list|dict|None): `inputs`, entry points of network,
            could be a InputSpec instance, or lits of InputSpec instances,
827 828
            or dict ({name: InputSpec}), and it couldn't be None in static
            graph.
829 830 831
        labels (InputSpec|list|None): `labels`, entry points of network,
            could be a InputSpec instnace or lits of InputSpec instances,
            or None. For static graph, if labels is required in loss,
832 833 834
            labels must be set. Otherwise, it could be None.


835
    Examples:
836 837
        .. code-block:: python

838
        import paddle
839 840 841 842 843 844
        import paddle.nn as nn
        from paddle.static import InputSpec

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

        net = nn.Sequential(
L
LielinJiang 已提交
845
            nn.Flatten(1),
846 847 848 849
            nn.Linear(784, 200),
            nn.Tanh(),
            nn.Linear(200, 10))

850
        # inputs and labels are not required for dynamic graph.
851 852
        input = InputSpec([None, 784], 'float32', 'x')
        label = InputSpec([None, 1], 'int64', 'label')
853
        
854
        model = paddle.Model(net, input, label)
855
        optim = paddle.optimizer.SGD(learning_rate=1e-3,
856
            parameters=model.parameters())
857
        model.prepare(optim,
858
                      paddle.nn.CrossEntropyLoss(),
859
                      paddle.metric.Accuracy())
860
        
L
LielinJiang 已提交
861
        data = paddle.vision.datasets.MNIST(mode='train')
862
        model.fit(data, epochs=2, batch_size=32, verbose=1)
863 864
    """

865
    def __init__(self, network, inputs=None, labels=None):
866
        self.mode = 'train'
867
        self.network = network
868 869
        self._inputs = None
        self._labels = None
870
        self._loss = None
871 872
        self._loss_weights = None
        self._optimizer = None
873 874
        self._input_shapes = None
        self._is_shape_inferred = False
875 876
        self._test_dataloader = None

877 878 879 880 881 882
        if not in_dygraph_mode():
            if not isinstance(inputs, (list, dict, Input)):
                raise TypeError(
                    "'inputs' must be list or dict, and couldn't be None.")
        elif inputs:
            self._input_shapes = _update_input_shapes(inputs)
L
LielinJiang 已提交
883

884
        self._inputs = self._verify_spec(inputs, is_input=True)
885
        self._labels = self._verify_spec(labels)
886

887 888 889 890 891 892 893 894 895 896 897
        # init backend
        if fluid.in_dygraph_mode():
            self._adapter = DynamicGraphAdapter(self)
        else:
            self._adapter = StaticGraphAdapter(self)

    def train_batch(self, inputs, labels=None):
        """
        Run one training step on a batch of data.

        Args:
898 899 900 901 902 903 904
            inputs (numpy.ndarray|Tensor|list): Batch of input data. It could 
                be a numpy array or paddle.Tensor, or a list of arrays or 
                tensors (in case the model has multiple inputs).
            labels (numpy.ndarray|Tensor|list): 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, 
                set None. Default is None.
905 906 907 908 909 910 911 912 913 914 915

        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
            
              import numpy as np
916
              import paddle
917 918
              import paddle.nn as nn
              from paddle.static import InputSpec
919

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

922 923 924 925 926 927 928 929
              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)
930
              optim = paddle.optimizer.SGD(learning_rate=1e-3,
931
                  parameters=model.parameters())
932
              model.prepare(optim, paddle.nn.CrossEntropyLoss())
933 934 935 936 937
              data = np.random.random(size=(4,784)).astype(np.float32)
              label = np.random.randint(0, 10, size=(4, 1)).astype(np.int64)
              loss = model.train_batch([data], [label])
              print(loss)
        """
938 939
        loss = self._adapter.train_batch(inputs, labels)
        if fluid.in_dygraph_mode() and self._input_shapes is None:
L
LiuChiachi 已提交
940
            self._update_inputs()
941
        return loss
942 943 944 945 946 947

    def eval_batch(self, inputs, labels=None):
        """
        Run one evaluating step on a batch of data.

        Args:
948 949 950 951 952 953 954
            inputs (numpy.ndarray|Tensor|list): Batch of input data. It could 
                be a numpy array or paddle.Tensor, or a list of arrays or 
                tensors (in case the model has multiple inputs).
            labels (numpy.ndarray|Tensor|list): 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, 
                set None. Default is None.
955 956 957 958 959 960 961 962 963 964 965

        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
            
              import numpy as np
966
              import paddle
967 968
              import paddle.nn as nn
              from paddle.static import InputSpec
969

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

972 973 974 975 976 977 978 979
              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)
980
              optim = paddle.optimizer.SGD(learning_rate=1e-3,
981
                  parameters=model.parameters())
982
              model.prepare(optim,
983
                            paddle.nn.CrossEntropyLoss())
984 985 986 987 988
              data = np.random.random(size=(4,784)).astype(np.float32)
              label = np.random.randint(0, 10, size=(4, 1)).astype(np.int64)
              loss = model.eval_batch([data], [label])
              print(loss)
        """
989 990
        loss = self._adapter.eval_batch(inputs, labels)
        if fluid.in_dygraph_mode() and self._input_shapes is None:
L
LiuChiachi 已提交
991
            self._update_inputs()
992
        return loss
993

994
    def predict_batch(self, inputs):
995
        """
996
        Run one predicting step on a batch of data.
997 998

        Args:
999 1000 1001
            inputs (numpy.ndarray|Tensor|list): Batch of input data. It could 
                be a numpy array or paddle.Tensor, or a list of arrays or 
                tensors (in case the model has multiple inputs).
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011

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

        Examples:

            .. code-block:: python
            
              import numpy as np
1012
              import paddle
1013
              import paddle.nn as nn
L
LielinJiang 已提交
1014
              from paddle.static import InputSpec
1015

1016
              device = paddle.set_device('cpu') # or 'gpu'
L
LielinJiang 已提交
1017 1018 1019
              
              input = InputSpec([None, 784], 'float32', 'x')
              label = InputSpec([None, 1], 'int64', 'label')
1020

1021 1022 1023 1024 1025 1026
              net = nn.Sequential(
                  nn.Linear(784, 200),
                  nn.Tanh(),
                  nn.Linear(200, 10),
                  nn.Softmax())

L
LielinJiang 已提交
1027
              model = paddle.Model(net, input, label)
1028
              model.prepare()
1029
              data = np.random.random(size=(4,784)).astype(np.float32)
1030
              out = model.predict_batch([data])
1031 1032
              print(out)
        """
1033
        loss = self._adapter.predict_batch(inputs)
1034
        if fluid.in_dygraph_mode() and self._input_shapes is None:
L
LiuChiachi 已提交
1035
            self._update_inputs()
1036
        return loss
1037

1038 1039 1040 1041 1042
    def save(self, path, training=True):
        """  
        This function saves parameters, optimizer information or model and 
        paramters only for inference to path. It depends on the parameter
        `training`.
1043

1044 1045
        If `training` is set to True, the parameters saved contain all 
        the trainable Variable, will save to a file with suffix ".pdparams".
1046 1047 1048 1049
        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).
1050
        This function will silently overwrite existing file at the target location.
1051

1052
        If `training` is set to False, only inference model will be saved.
1053 1054 1055 1056 1057

        Args:
            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.
1058 1059
            training (bool, optional): Whether to save for training. If not, save
                for inference only. Default: True.
1060 1061 1062 1063 1064 1065 1066

        Returns:
            None

        Examples:

            .. code-block:: python
1067

1068
                import paddle
1069 1070
                import paddle.nn as nn
                from paddle.static import InputSpec
1071

1072
                class Mnist(nn.Layer):
1073
                    def __init__(self):
1074
                        super(Mnist, self).__init__()
1075
                        self.net = nn.Sequential(
L
LielinJiang 已提交
1076
                            nn.Flatten(1),
1077 1078 1079 1080
                            nn.Linear(784, 200),
                            nn.Tanh(),
                            nn.Linear(200, 10),
                            nn.Softmax())
1081

1082
                    def forward(self, x):
1083
                        return self.net(x)
1084

1085
                dynamic = True  # False
1086
                device = paddle.set_device('cpu')
1087 1088
                # if use static graph, do not set
                paddle.disable_static(device) if dynamic else None
1089

1090 1091 1092
                input = InputSpec([None, 784], 'float32', 'x')
                label = InputSpec([None, 1], 'int64', 'label')
                model = paddle.Model(Mnist(), input, label)
1093
                optim = paddle.optimizer.SGD(learning_rate=1e-3,
1094
                    parameters=model.parameters())
1095
                model.prepare(optim, paddle.nn.CrossEntropyLoss())
L
LielinJiang 已提交
1096
                data = paddle.vision.datasets.MNIST(mode='train')
1097
                model.fit(data, epochs=1, batch_size=32, verbose=0)
1098 1099
                model.save('checkpoint/test')  # save for training
                model.save('inference_model', False)  # save for inference
1100
        """
1101

1102
        if ParallelEnv().local_rank == 0:
1103 1104 1105 1106
            if not training:
                self._save_inference_model(path)
            else:
                self._adapter.save(path)
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140

    def load(self, path, skip_mismatch=False, reset_optimizer=False):
        """
        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.
            skip_mismatch (bool): Whether to skip the loading of mismatch
                parameter or raise an error when mismatch happens (not found
                the parameter in file storing model states of or receives a
                mismatch shape).
            reset_optimizer (bool): If True, ignore the providing file storing
                optimizer states and initialize optimizer states from scratch.
                Otherwise, restore optimizer states from `path.pdopt` if
                a optimizer has been set to the model. Default False.

        Returns:
            None

        Examples:

            .. code-block:: python
            
1141
              import paddle
1142
              import paddle.nn as nn
L
LielinJiang 已提交
1143 1144
              from paddle.static import InputSpec

1145
              device = paddle.set_device('cpu')
L
LielinJiang 已提交
1146 1147

              input = InputSpec([None, 784], 'float32', 'x')
1148 1149 1150 1151 1152

              model = paddle.Model(nn.Sequential(
                  nn.Linear(784, 200),
                  nn.Tanh(),
                  nn.Linear(200, 10),
L
LielinJiang 已提交
1153 1154
                  nn.Softmax()), input)

1155
              model.save('checkpoint/test')
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
              model.load('checkpoint/test')
        """

        def _load_state_from_path(path):
            if not os.path.exists(path):
                return
            with open(path, 'rb') as f:
                return pickle.load(f) if six.PY2 else pickle.load(
                    f, encoding='latin1')

        def _check_match(key, param):
            state = param_state.get(key, None)
            if state is None:
                raise ValueError(
                    "{} is not found in the providing file.".format(key))
            if list(state.shape) != list(param.shape):
                raise ValueError(
                    "{} receives a shape {}, but the expected shape is {}.".
                    format(key, list(state.shape), list(param.shape)))
            return param, state

        def _strip_postfix(path):
            path, ext = os.path.splitext(path)
            assert ext in ['', '.pdparams', '.pdopt', '.pdmodel'], \
                    "Unknown postfix {} from weights".format(ext)
            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 = []
1188
        for key, param in self.network.state_dict().items():
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
            try:
                match_res = _check_match(key, param)
            except ValueError as err:
                if skip_mismatch:
                    warnings.warn(
                        ("Skip loading for {}. ".format(key) + str(err)))
                    # reset optimizer when mismatch happens
                    reset_optimizer = True
                else:
                    raise err
            matched_param_state.append(match_res)

        optim_state = None if reset_optimizer else _load_state_from_path(
            path + ".pdopt")
        return self._adapter.load(matched_param_state, optim_state)

    def parameters(self, *args, **kwargs):
        """
        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

1217
              import paddle
1218
              import paddle.nn as nn
L
LielinJiang 已提交
1219
              from paddle.static import InputSpec
1220

L
LielinJiang 已提交
1221 1222
              input = InputSpec([None, 784], 'float32', 'x')
              
1223 1224 1225
              model = paddle.Model(nn.Sequential(
                  nn.Linear(784, 200),
                  nn.Tanh(),
L
LielinJiang 已提交
1226 1227
                  nn.Linear(200, 10)), input)

1228 1229 1230 1231
              params = model.parameters()
        """
        return self._adapter.parameters()

1232
    def prepare(self, optimizer=None, loss=None, metrics=None):
1233 1234 1235 1236 1237 1238 1239
        """
        Configures the model before runing.

        Args:
            optimizer (Optimizer|None): Optimizer must be set in training
                and should be a Optimizer instance. It can be None in eval
                and test mode.
1240 1241
            loss (Loss|callable function|None): Loss function can
                be a `paddle.nn.Layer` instance or any callable function
1242 1243
                taken the predicted values and ground truth values as input.
                It can be None when there is no loss.
1244 1245 1246 1247 1248 1249 1250
            metrics (Metric|list of Metric|None): If metrics is set, all
                metrics will be calculated and output in train/eval mode.

        Returns:
            None
        """

1251 1252
        self._place = _get_device()
        if isinstance(self._place, fluid.CUDAPlace):
1253 1254 1255 1256 1257 1258 1259
            global _parallel_context_initialized
            if ParallelEnv().nranks > 1 and not _parallel_context_initialized:
                if fluid.in_dygraph_mode():
                    main_prog_seed = fluid.default_main_program().random_seed
                    startup_prog_seed = fluid.default_startup_program(
                    ).random_seed
                    fluid.disable_dygraph()
1260
                    paddle.disable_static(self._place)
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
                    # 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
                    fluid.default_startup_program(
                    ).random_seed = startup_prog_seed
                    fluid.dygraph.parallel.prepare_context()
                else:
                    prepare_distributed_context(self._place)
                _parallel_context_initialized = True

        self._optimizer = optimizer
1272 1273 1274 1275 1276
        if loss is not None:
            if not isinstance(loss, paddle.nn.Layer) and not callable(loss):
                raise TypeError("'loss' must be sub classes of " \
                    "`paddle.nn.Layer` or any callable function.")
        self._loss = loss
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354

        metrics = metrics or []
        for metric in to_list(metrics):
            assert isinstance(metric, Metric), \
                "{} is not sub class of Metric".format(
                    metric.__class__.__name__)
        self._metrics = to_list(metrics)

        if not in_dygraph_mode():
            self._adapter.prepare()

    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, ):
        """
        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:
            train_data (Dataset|DataLoader): An iterable data loader is used for 
                train. An instance of paddle paddle.io.Dataset or 
                paddle.io.Dataloader is recomended. Default: None.
            eval_data (Dataset|DataLoader): An iterable data loader is used for
                evaluation at the end of epoch. If None, will not do evaluation. 
                An instance of paddle.io.Dataset or paddle.io.Dataloader 
                is recomended. Default: None.
            batch_size (int): Integer number. The batch size of train_data
                and eval_data. When train_data and eval_data are both the
                instance of Dataloader, this parameter will be ignored.
                Default: 1.
            epochs (int): Integer number. The number of epochs to train
                the model. Default: 1.
            eval_freq (int): The frequency, in number of epochs, an evalutation
                is performed. Default: 1.
            log_freq (int): The frequency, in number of steps, the training logs
                are printed. Default: 10.
            save_dir(str|None): The directory to save checkpoint during training.
                If None, will not save checkpoint. Default: None.
            save_freq (int): The frequency, in number of epochs, to save
                checkpoint. Default: 1.
            verbose (int): The verbosity mode, should be 0, 1, or 2. 0 = silent,
                1 = progress bar, 2 = one line per epoch. Default: 2.
            drop_last (bool): Whether drop the last incomplete batch of
                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.
            shuffle (bool): Whther to shuffle train_data. When train_data is
                an instance of Dataloader, this parameter will be ignored.
                Default: True.
            num_workers (int): The number of subprocess to load data, 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.
            callbacks (Callback|None): A list of `Callback` instances to apply
                during training. If None, `ProgBarLogger` and `ModelCheckpoint`
                are automatically inserted. Default: None.

        Returns:
            None

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

            .. code-block:: python

1355
              import paddle
1356
              from paddle.static import InputSpec
1357 1358

              dynamic = True
1359
              device = paddle.set_device('cpu') # or 'gpu'
1360
              paddle.disable_static(device) if dynamic else None
1361
           
1362 1363
              train_dataset = paddle.vision.datasets.MNIST(mode='train')
              val_dataset = paddle.vision.datasets.MNIST(mode='test')
1364
           
1365 1366
              input = InputSpec([None, 1, 28, 28], 'float32', 'image')
              label = InputSpec([None, 1], 'int64', 'label')
1367
           
1368
              model = paddle.Model(
L
LielinJiang 已提交
1369
                  paddle.vision.models.LeNet(),
1370
                  input, label)
1371 1372
              optim = paddle.optimizer.Adam(
                  learning_rate=0.001, parameters=model.parameters())
1373 1374
              model.prepare(
                  optim,
1375
                  paddle.nn.CrossEntropyLoss(),
1376
                  paddle.metric.Accuracy(topk=(1, 2)))
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
              model.fit(train_dataset,
                        val_dataset,
                        epochs=2,
                        batch_size=64,
                        save_dir='mnist_checkpoint')

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

            .. code-block:: python

1388
              import paddle
1389
              from paddle.static import InputSpec
1390 1391

              dynamic = True
1392
              device = paddle.set_device('cpu') # or 'gpu'
1393
              paddle.disable_static(device) if dynamic else None
1394
           
1395
              train_dataset = paddle.vision.datasets.MNIST(mode='train')
1396
              train_loader = paddle.io.DataLoader(train_dataset,
1397
                  places=device, batch_size=64)
1398
              val_dataset = paddle.vision.datasets.MNIST(mode='test')
1399
              val_loader = paddle.io.DataLoader(val_dataset,
1400 1401
                  places=device, batch_size=64)
           
1402 1403
              input = InputSpec([None, 1, 28, 28], 'float32', 'image')
              label = InputSpec([None, 1], 'int64', 'label')
1404
           
1405
              model = paddle.Model(
L
LielinJiang 已提交
1406
                  paddle.vision.models.LeNet(), input, label)
1407 1408
              optim = paddle.optimizer.Adam(
                  learning_rate=0.001, parameters=model.parameters())
1409 1410
              model.prepare(
                  optim,
1411
                  paddle.nn.CrossEntropyLoss(),
1412
                  paddle.metric.Accuracy(topk=(1, 2)))
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
              model.fit(train_loader,
                        val_loader,
                        epochs=2,
                        save_dir='mnist_checkpoint')
        """

        assert train_data is not None, \
                "train_data must be given!"

        if isinstance(train_data, Dataset):
            train_sampler = DistributedBatchSampler(
                train_data,
                batch_size=batch_size,
                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)
        else:
            train_loader = train_data

        if eval_data is not None and isinstance(eval_data, Dataset):
            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)
        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

        steps = self._len_data_loader(train_loader)
        cbks = config_callbacks(
            callbacks,
            model=self,
            epochs=epochs,
            steps=steps,
            log_freq=log_freq,
            save_freq=save_freq,
            save_dir=save_dir,
            verbose=verbose,
            metrics=self._metrics_name(), )

        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)
                cbks.on_begin('eval', {
                    'steps': eval_steps,
                    'metrics': self._metrics_name()
                })

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

                cbks.on_end('eval', eval_logs)

        cbks.on_end('train', logs)
        self._test_dataloader = None

    def evaluate(
            self,
            eval_data,
            batch_size=1,
            log_freq=10,
            verbose=2,
            num_workers=0,
            callbacks=None, ):
        """
        Evaluate the loss and metrics of the model on input dataset.

        Args:
            eval_data (Dataset|DataLoader): An iterable data loader is used for
                evaluation. An instance of paddle.io.Dataset or 
                paddle.io.Dataloader is recomended.
            batch_size (int): Integer number. 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): The frequency, in number of steps, the eval logs
                are printed. Default: 10.
            verbose (int): The verbosity mode, should be 0, 1, or 2. 0 = silent,
                1 = progress bar, 2 = one line per epoch. Default: 2.
            num_workers (int): The number of subprocess to load data,
                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.
            callbacks (Callback|None): A list of `Callback` instances to apply
                during training. If None, `ProgBarLogger` and `ModelCheckpoint`
                are automatically inserted. Default: None.
        Returns:
            dict: Result of metric. The key is the names of Metric,
                value is a scalar or numpy.array.

        Examples:
        .. code-block:: python

1524
            import paddle
1525
            from paddle.static import InputSpec
1526

1527
            # declarative mode
1528
            val_dataset = paddle.vision.datasets.MNIST(mode='test')
1529

1530 1531 1532
            input = InputSpec([-1, 1, 28, 28], 'float32', 'image')
            label = InputSpec([None, 1], 'int64', 'label')
            model = paddle.Model(paddle.vision.models.LeNet(), input, label)
1533
            model.prepare(metrics=paddle.metric.Accuracy())
1534 1535 1536 1537
            result = model.evaluate(val_dataset, batch_size=64)
            print(result)

            # imperative mode
1538
            paddle.disable_static()
L
LielinJiang 已提交
1539
            model = paddle.Model(paddle.vision.models.LeNet(), input, label)
1540
            model.prepare(metrics=paddle.metric.Accuracy())
1541 1542
            result = model.evaluate(val_dataset, batch_size=64)
            print(result)
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
                
        """

        if eval_data is not None and isinstance(eval_data, Dataset):
            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)
        else:
            eval_loader = eval_data

        self._test_dataloader = eval_loader

        cbks = config_callbacks(
            callbacks,
            model=self,
            log_freq=log_freq,
            verbose=verbose,
            metrics=self._metrics_name(), )

        eval_steps = self._len_data_loader(eval_loader)
        cbks.on_begin('eval',
                      {'steps': eval_steps,
                       'metrics': self._metrics_name()})

        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

    def predict(self,
                test_data,
                batch_size=1,
                num_workers=0,
                stack_outputs=False,
                callbacks=None):
        """
        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.
            batch_size (int): Integer number. The batch size of train_data and eval_data.
                When train_data and eval_data are both the instance of Dataloader, this
                argument will be ignored. Default: 1.
            num_workers (int): The number of subprocess to load data, 0 for no subprocess 
                used and loading data in main process. When train_data and eval_data are
                both the instance of Dataloader, this argument will be ignored. Default: 0.
1603
            stack_outputs (bool): Whether stack output field like a batch, as for an output
1604 1605 1606 1607 1608
                filed of a sample is in shape [X, Y], test_data contains N samples, predict
                output field will be in shape [N, X, Y] if stack_output is True, and will
                be a length N list in shape [[X, Y], [X, Y], ....[X, Y]] if stack_outputs
                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.
1609
            callbacks(Callback): A Callback instance, default None.
1610 1611 1612 1613 1614 1615 1616
        Returns:
            list: output of models.

        Examples:
        .. code-block:: python

            import numpy as np
1617
            import paddle
1618
            from paddle.static import InputSpec
1619

1620
            class MnistDataset(paddle.vision.datasets.MNIST):
1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
                def __init__(self, mode, return_label=True):
                    super(MnistDataset, self).__init__(mode=mode)
                    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)

L
LielinJiang 已提交
1636
            # imperative mode
1637 1638
            input = InputSpec([-1, 1, 28, 28], 'float32', 'image')
            model = paddle.Model(paddle.vision.models.LeNet(), input)
1639
            model.prepare()
1640
            result = model.predict(test_dataset, batch_size=64)
1641
            print(len(result[0]), result[0][0].shape)
1642

L
LielinJiang 已提交
1643
            # declarative mode
1644
            device = paddle.set_device('cpu')
L
LielinJiang 已提交
1645 1646 1647
            paddle.enable_static()
            input = InputSpec([-1, 1, 28, 28], 'float32', 'image')
            model = paddle.Model(paddle.vision.models.LeNet(), input)
1648
            model.prepare()
L
LielinJiang 已提交
1649

1650 1651
            result = model.predict(test_dataset, batch_size=64)
            print(len(result[0]), result[0][0].shape)
1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
        """

        if test_data is not None and isinstance(test_data, Dataset):
            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)
        else:
            test_loader = test_data

        self._test_dataloader = test_loader

        cbks = config_callbacks(callbacks, model=self, verbose=1)

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

        cbks.on_begin('test', logs)

        outputs = []

        logs, outputs = self._run_one_epoch(test_loader, cbks, 'test')

        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

        cbks.on_end('test', logs)
        return outputs

1691 1692 1693 1694 1695
    def _save_inference_model(self,
                              save_dir,
                              model_filename=None,
                              params_filename=None,
                              model_only=False):
1696
        """
1697
        Save inference model can be in static or dynamic mode.
1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713

        Args:
            save_dir (str): The directory path to save the inference model.
            model_filename (str|None): The name of file to save the inference
                model itself. If is set None, a default filename
                :code:`__model__` will be used.
            params_filename (str|None): The name of file to save all related
                parameters. If it is set None, parameters will be saved
                in separate files .
            model_only (bool): If True, It will save inference model only,
                and do not save parameters. Default: False.

        Returns:
            list: The fetch variables' name list
        """

1714 1715 1716 1717 1718 1719
        def get_inout_spec(all_vars, return_name=False):
            result_list = []
            valid_vars = [var for var in all_vars if isinstance(var, Variable)]
            result_list = valid_vars
            if return_name:
                result_list = [var.name for var in result_list]
1720

1721
            return result_list
1722

1723
        if fluid.in_dygraph_mode():
1724 1725
            with fluid.framework._dygraph_guard(None):
                layer = self.network
1726 1727
                if self._input_shapes is None:  # No provided or inferred
                    raise RuntimeError(
L
LiuChiachi 已提交
1728
                        "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."
1729 1730 1731 1732 1733
                    )
                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."
                        % self._input_shapes)
1734 1735
                layer.forward = paddle.jit.to_static(
                    layer.forward, input_spec=self._inputs)
1736 1737 1738

                # 1. input check
                prog_translator = ProgramTranslator()
1739
                if not prog_translator.enable_to_static:
1740
                    raise RuntimeError(
1741
                        "save_inference_model doesn't work when setting ProgramTranslator.enable to False."
1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793
                    )
                if not isinstance(layer, Layer):
                    raise TypeError(
                        "The input layer should be 'Layer', but received layer type is %s."
                        % type(layer))

                # 2. get program of declarative Layer.forward
                concrete_program = layer.forward.concrete_program

                # NOTE: we maintain the mapping of variable name to
                # structured name, the buffer variable (non-persistable)
                # saved to inference program may not need by dygraph Layer,
                # we only record the state_dict variable's structured name
                state_names_dict = dict()
                for structured_name, var in layer.state_dict().items():
                    state_names_dict[var.name] = structured_name

                # 3. share parameters from Layer to scope & record var info
                scope = core.Scope()
                extra_var_info = dict()
                for param_or_buffer in concrete_program.parameters:
                    # share to scope
                    param_or_buffer_tensor = scope.var(
                        param_or_buffer.name).get_tensor()
                    src_tensor = param_or_buffer.value().get_tensor()
                    param_or_buffer_tensor._share_data_with(src_tensor)
                    # record var info
                    extra_info_dict = dict()
                    if param_or_buffer.name in state_names_dict:
                        extra_info_dict['structured_name'] = state_names_dict[
                            param_or_buffer.name]
                    extra_info_dict[
                        'stop_gradient'] = param_or_buffer.stop_gradient
                    if isinstance(param_or_buffer, ParamBase):
                        extra_info_dict['trainable'] = param_or_buffer.trainable
                    extra_var_info[param_or_buffer.name] = extra_info_dict

                # 4. build input & output spec
                input_var_names = get_inout_spec(concrete_program.inputs, True)
                output_vars = get_inout_spec(concrete_program.outputs)

                # 5. save inference model
                with scope_guard(scope):
                    return fluid.io.save_inference_model(
                        dirname=save_dir,
                        feeded_var_names=input_var_names,
                        target_vars=output_vars,
                        executor=Executor(_current_expected_place()),
                        main_program=concrete_program.main_program.clone(),
                        model_filename=model_filename,
                        params_filename=params_filename,
                        program_only=model_only)
1794

1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813
        else:
            prog = self._adapter._progs.get('test', None)
            assert prog, \
                "Model is not ready, please call `model.prepare()` first"

            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']

            return fluid.io.save_inference_model(
                save_dir,
                input_names,
                endpoints,
                self._adapter._executor,
                main_program=infer_prog,
                model_filename=model_filename,
                params_filename=params_filename,
                program_only=model_only)
1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831

    def _run_one_epoch(self, data_loader, callbacks, mode, logs={}):
        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, ...]
            # 4. custumed iterator yield seperated inputs and labels:
            #   ([input1, input2, ...], [label1, lable2, ...])
            # To handle all of these, flatten (nested) list to list.
            data = flatten(data)
            # LoDTensor.shape is callable, where LoDTensor comes from
            # DataLoader in static graph
1832

1833 1834 1835 1836 1837 1838 1839 1840
            batch_size = data[0].shape()[0] if callable(data[
                0].shape) else data[0].shape[0]

            callbacks.on_batch_begin(mode, step, logs)

            if mode != 'test':
                outs = getattr(self, mode + '_batch')(data[:len(self._inputs)],
                                                      data[len(self._inputs):])
1841
                if self._metrics and self._loss:
1842
                    metrics = [[l[0] for l in outs[0]]]
1843
                elif self._loss:
1844 1845 1846
                    metrics = [[l[0] for l in outs]]
                else:
                    metrics = []
1847 1848 1849 1850 1851 1852 1853 1854 1855 1856

                # 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 已提交
1857
                if self._inputs is not None:
1858
                    outs = self.predict_batch(data[:len(self._inputs)])
L
LielinJiang 已提交
1859
                else:
1860
                    outs = self.predict_batch(data)
L
LielinJiang 已提交
1861

1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877
                outputs.append(outs)

            logs['step'] = step
            if mode == 'train' or self._adapter._merge_count.get(
                    mode + '_batch', 0) <= 0:
                logs['batch_size'] = batch_size * ParallelEnv().nranks
            else:
                logs['batch_size'] = self._adapter._merge_count[mode + '_batch']

            callbacks.on_batch_end(mode, step, logs)
        self._reset_metrics()

        if mode == 'test':
            return logs, outputs
        return logs

L
LielinJiang 已提交
1878
    def summary(self, input_size=None, dtype=None):
L
LielinJiang 已提交
1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900
        """Prints a string summary of the network.

        Args:
            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. 
                    Default: None.
            dtypes (str, optional): if dtypes is None, 'float32' will be used, Default: None.

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

        Examples:
            .. code-block:: python

              import paddle
              from paddle.static import InputSpec
           
              input = InputSpec([None, 1, 28, 28], 'float32', 'image')
              label = InputSpec([None, 1], 'int64', 'label')
           
L
LielinJiang 已提交
1901
              model = paddle.Model(paddle.vision.LeNet(),
L
LielinJiang 已提交
1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912
                  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)

        """
1913 1914 1915 1916 1917 1918
        assert (input_size is not None or self._inputs is not None
                ), "'input_size' or 'self._input' must be set"
        if input_size is not None:
            _input_size = input_size
        else:
            _input_size = self._inputs
L
LielinJiang 已提交
1919
        return summary(self.network, _input_size, dtype)
L
LielinJiang 已提交
1920

1921
    def _verify_spec(self, specs, shapes=None, is_input=False):
1922 1923
        out_specs = []

1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940
        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:]
                if shapes is not None and fluid.in_dygraph_mode():
                    out_specs = [
                        Input(
                            name=n, shape=shapes[i])
                        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):
1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951
            assert is_input == False
            out_specs = [specs[n] \
                for n in extract_args(self.network.forward) if n != 'self']
        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(
1952 1953
                        "Requires Input[{}].name != None, but receive `None` with {}."
                        .format(i, spec))
1954 1955 1956

        return out_specs

1957 1958 1959 1960 1961
    def _reset_metrics(self):
        for metric in self._metrics:
            metric.reset()

    def _metrics_name(self):
1962
        metrics_name = ['loss'] if self._loss else []
1963 1964 1965 1966 1967 1968 1969 1970 1971 1972
        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 已提交
1973 1974 1975 1976 1977 1978

    def _update_inputs(self):
        "Update self._inputs according to given inputs."
        self._input_shapes = self._adapter._input_shapes
        self._is_shape_inferred = True
        self._inputs = self._verify_spec(None, self._input_shapes, True)