utility.py 29.9 KB
Newer Older
R
ruri 已提交
1
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#
#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
R
ruri 已提交
18

R
root 已提交
19
import six
R
ruri 已提交
20 21 22 23
import argparse
import functools
import sys
import os
24
import logging
R
ruri 已提交
25 26
import warnings
import signal
27
import json
R
ruri 已提交
28

29
import numpy as np
R
ruri 已提交
30 31
import paddle
import paddle.fluid as fluid
32 33 34
from paddle.fluid.wrapped_decorator import signature_safe_contextmanager
from paddle.fluid.framework import Program, program_guard, name_scope, default_main_program
from paddle.fluid import unique_name, layers
35 36

import distutils.util
37
from utils import dist_utils
38

39 40 41 42 43
from utils.optimizer import Optimizer

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

44

45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
def print_arguments(args):
    """Print argparse's arguments.

    Usage:

    .. code-block:: python

        parser = argparse.ArgumentParser()
        parser.add_argument("name", default="Jonh", type=str, help="User name.")
        args = parser.parse_args()
        print_arguments(args)

    :param args: Input argparse.Namespace for printing.
    :type args: argparse.Namespace
    """
60 61

    logger.info("-------------  Configuration Arguments -------------")
R
root 已提交
62
    for arg, value in sorted(six.iteritems(vars(args))):
63 64
        logger.info("%25s : %s" % (arg, value))
    logger.info("----------------------------------------------------")
65 66 67


def add_arguments(argname, type, default, help, argparser, **kwargs):
68
    """Add argparse's argument.
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84

    Usage:

    .. code-block:: python

        parser = argparse.ArgumentParser()
        add_argument("name", str, "Jonh", "User name.", parser)
        args = parser.parse_args()
    """
    type = distutils.util.strtobool if type == bool else type
    argparser.add_argument(
        "--" + argname,
        default=default,
        type=type,
        help=help + ' Default: %(default)s.',
        **kwargs)
R
ruri 已提交
85

R
ruri 已提交
86 87 88 89

def parse_args():
    """Add arguments

90
    Returns:
R
ruri 已提交
91
        all training args
R
ruri 已提交
92
    """
R
ruri 已提交
93 94 95 96 97 98 99 100 101
    parser = argparse.ArgumentParser(description=__doc__)
    add_arg = functools.partial(add_arguments, argparser=parser)
    # yapf: disable

    # ENV
    add_arg('use_gpu',                  bool,   True,                   "Whether to use GPU.")
    add_arg('model_save_dir',           str,    "./output",        "The directory path to save model.")
    add_arg('data_dir',                 str,    "./data/ILSVRC2012/",   "The ImageNet dataset root directory.")
    add_arg('pretrained_model',         str,    None,                   "Whether to load pretrained model.")
102
    add_arg('finetune_exclude_pretrained_params', str, None,            "Ignore params when doing finetune")
R
ruri 已提交
103 104
    add_arg('checkpoint',               str,    None,                   "Whether to resume checkpoint.")
    add_arg('print_step',               int,    10,                     "The steps interval to print logs")
105
    add_arg('save_step',                int,    1,                      "The steps interval to save checkpoints")
R
ruri 已提交
106 107 108 109

    # SOLVER AND HYPERPARAMETERS
    add_arg('model',                    str,    "ResNet50",   "The name of network.")
    add_arg('total_images',             int,    1281167,                "The number of total training images.")
R
ruri 已提交
110
    parser.add_argument('--image_shape', nargs='+', type=int, default=[3, 224, 224], help="The shape of image")
R
ruri 已提交
111 112
    add_arg('num_epochs',               int,    120,                    "The number of total epochs.")
    add_arg('class_dim',                int,    1000,                   "The number of total classes.")
113
    add_arg('batch_size',               int,    8,                      "Minibatch size on all the devices.")
114
    add_arg('test_batch_size',          int,    8,                   "Test batch size on all the devices.")
R
ruri 已提交
115 116 117 118
    add_arg('lr',                       float,  0.1,                    "The learning rate.")
    add_arg('lr_strategy',              str,    "piecewise_decay",      "The learning rate decay strategy.")
    add_arg('l2_decay',                 float,  1e-4,                   "The l2_decay parameter.")
    add_arg('momentum_rate',            float,  0.9,                    "The value of momentum_rate.")
119 120 121 122
    add_arg('warm_up_epochs',           float,  5.0,                    "The value of warm up epochs")
    add_arg('decay_epochs',             float,  2.4,                    "Decay epochs of exponential decay learning rate scheduler")
    add_arg('decay_rate',               float,  0.97,                   "Decay rate of exponential decay learning rate scheduler")
    add_arg('drop_connect_rate',        float,  0.2,                    "The value of drop connect rate")
R
ruri 已提交
123
    parser.add_argument('--step_epochs', nargs='+', type=int, default=[30, 60, 90], help="piecewise decay step")
124

R
ruri 已提交
125
    # READER AND PREPROCESS
126
    add_arg('use_dali',                 bool,   False,                  "Whether to use nvidia DALI for preprocessing")
R
ruri 已提交
127 128 129 130 131 132 133
    add_arg('lower_scale',              float,  0.08,                   "The value of lower_scale in ramdom_crop")
    add_arg('lower_ratio',              float,  3./4.,                  "The value of lower_ratio in ramdom_crop")
    add_arg('upper_ratio',              float,  4./3.,                  "The value of upper_ratio in ramdom_crop")
    add_arg('resize_short_size',        int,    256,                    "The value of resize_short_size")
    add_arg('use_mixup',                bool,   False,                  "Whether to use mixup")
    add_arg('mixup_alpha',              float,  0.2,                    "The value of mixup_alpha")
    add_arg('reader_thread',            int,    8,                      "The number of multi thread reader")
134
    add_arg('reader_buf_size',          int,    8,                      "The buf size of multi thread reader")
R
ruri 已提交
135
    add_arg('interpolation',            int,    None,                   "The interpolation mode")
136
    add_arg('use_aa',                   bool,   False,                  "Whether to use auto augment")
R
ruri 已提交
137 138 139 140
    parser.add_argument('--image_mean', nargs='+', type=float, default=[0.485, 0.456, 0.406], help="The mean of input image data")
    parser.add_argument('--image_std', nargs='+', type=float, default=[0.229, 0.224, 0.225], help="The std of input image data")

    # SWITCH
141
    add_arg('validate',                 bool,   True,                   "whether to validate when training.")
R
ruri 已提交
142 143 144
    add_arg('use_fp16',                 bool,   False,                  "Whether to enable half precision training with fp16." )
    add_arg('scale_loss',               float,  1.0,                    "The value of scale_loss for fp16." )
    add_arg('use_dynamic_loss_scaling', bool,   True,                   "Whether to use dynamic loss scaling.")
145 146 147
    add_arg('data_format',              str,    "NCHW",                 "Tensor data format when training.")
    add_arg('fuse_elewise_add_act_ops', bool,   False,                  "Whether to use elementwise_act fusion.")
    add_arg('fuse_bn_act_ops',          bool,   False,                  "Whether to use batch_norm and act fusion.")
Z
Zhang Ting 已提交
148
    add_arg('fuse_bn_add_act_ops',      bool,   False,                  "Whether to use batch_norm, elementwise_add and act fusion. This is only used for AMP training.")
L
Leo Chen 已提交
149
    add_arg('enable_addto',             bool,   False,                  "Whether to enable the addto strategy for gradient accumulation or not. This is only used for AMP training.")
R
ruri 已提交
150

R
ruri 已提交
151
    add_arg('use_label_smoothing',      bool,   False,                  "Whether to use label_smoothing")
152
    add_arg('label_smoothing_epsilon',  float,  0.1,                    "The value of label_smoothing_epsilon parameter")
R
ruri 已提交
153 154
    #NOTE: (2019/08/08) temporary disable use_distill
    #add_arg('use_distill',              bool,   False,                  "Whether to use distill")
155 156 157
    add_arg('use_ema',                  bool,   False,                  "Whether to use ExponentialMovingAverage.")
    add_arg('ema_decay',                float,  0.9999,                 "The value of ema decay rate")
    add_arg('padding_type',             str,    "SAME",                 "Padding type of convolution")
158
    add_arg('use_se',                   bool,   True,                   "Whether to use Squeeze-and-Excitation module for EfficientNet.")
159

160
    #NOTE: args for profiler
161 162 163 164 165
    add_arg("enable_ce",                bool,   False,                  "Whether to enable ce")
    add_arg('random_seed',              int,    None,                   "random seed")
    add_arg('is_profiler',              bool,   False,                  "Whether to start the profiler")
    add_arg('profiler_path',            str,    './profilier_files',                   "the profiler output file path")
    add_arg('max_iter',                 int,    0,                      "the max train batch num")
R
ruri 已提交
166
    add_arg('same_feed',                int,    0,                      "whether to feed same images")
R
ruri 已提交
167 168 169


    # yapf: enable
R
ruri 已提交
170 171 172 173 174 175
    args = parser.parse_args()

    return args


def check_gpu():
176
    """
R
ruri 已提交
177
    Log error and exit when set use_gpu=true in paddlepaddle
R
ruri 已提交
178
    cpu ver sion.
R
ruri 已提交
179 180
    """
    err = "Config use_gpu cannot be set as true while you are " \
R
ruri 已提交
181 182 183 184
                "using paddlepaddle cpu version ! \nPlease try: \n" \
                "\t1. Install paddlepaddle-gpu to run model on GPU \n" \
                "\t2. Set use_gpu as false in config file to run " \
                "model on CPU"
185
    try:
R
ruri 已提交
186
        if args.use_gpu and not fluid.is_compiled_with_cuda():
187
            logger.error(err)
R
ruri 已提交
188 189 190
            sys.exit(1)
    except Exception as e:
        pass
R
ruri 已提交
191 192


193 194 195 196 197 198 199 200 201 202 203 204
def check_version():
    """
    Log error and exit when the installed version of paddlepaddle is
    not satisfied.
    """
    err = "PaddlePaddle version 1.6 or higher is required, " \
          "or a suitable develop version is satisfied as well. \n" \
          "Please make sure the version is good with your code." \

    try:
        fluid.require_version('1.6.0')
    except Exception as e:
205
        logger.error(err)
206 207 208
        sys.exit(1)


R
ruri 已提交
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
def check_args(args):
    """check arguments before running

    Args:
        all arguments
    """

    # check models name
    sys.path.append("..")
    import models
    model_list = [m for m in dir(models) if "__" not in m]
    assert args.model in model_list, "{} is not in lists: {}, please check the model name".format(
        args.model, model_list)

    # check learning rate strategy
224
    lr_strategy_list = [l for l in dir(Optimizer) if not l.startswith('__')]
R
ruri 已提交
225
    if args.lr_strategy not in lr_strategy_list:
226 227
        logger.warning(
            "\n{} is not in lists: {}, \nUse default learning strategy now!".
R
ruri 已提交
228 229
            format(args.lr_strategy, lr_strategy_list))
        args.lr_strategy = "default_decay"
230

R
ruri 已提交
231 232 233 234
    # check confict of GoogLeNet and mixup
    if args.model == "GoogLeNet":
        assert args.use_mixup == False, "Cannot use mixup processing in GoogLeNet, please set use_mixup = False."

235
    # check interpolation of reader settings
R
ruri 已提交
236 237 238 239 240
    if args.interpolation:
        assert args.interpolation in [
            0, 1, 2, 3, 4
        ], "Wrong interpolation, please set:\n0: cv2.INTER_NEAREST\n1: cv2.INTER_LINEAR\n2: cv2.INTER_CUBIC\n3: cv2.INTER_AREA\n4: cv2.INTER_LANCZOS4"

241
    # check padding type
242 243 244 245 246
    if args.padding_type:
        assert args.padding_type in [
            "SAME", "VALID", "DYNAMIC"
        ], "Wrong padding_type, please set:\nSAME\nVALID\nDYNAMIC"

247
    # check checkpint and pretrained_model
R
ruri 已提交
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
    assert args.checkpoint is None or args.pretrained_model is None, "Do not init model by checkpoint and pretrained_model both."

    # check pretrained_model path for loading
    if args.pretrained_model is not None:
        assert isinstance(args.pretrained_model, str)
        assert os.path.isdir(
            args.
            pretrained_model), "please support available pretrained_model path."

    #FIXME: check checkpoint path for saving
    if args.checkpoint is not None:
        assert isinstance(args.checkpoint, str)
        assert os.path.isdir(
            args.checkpoint
        ), "please support available checkpoint path for initing model."

    # check gpu: when using gpu, the number of visible cards should divide batch size
    if args.use_gpu:
        assert args.batch_size % fluid.core.get_cuda_device_count(
        ) == 0, "please support correct batch_size({}), which can be divided by available cards({}), you can change the number of cards by indicating: export CUDA_VISIBLE_DEVICES= ".format(
            args.batch_size, fluid.core.get_cuda_device_count())

    # check data directory
    assert os.path.isdir(
        args.data_dir
    ), "Data doesn't exist in {}, please load right path".format(args.data_dir)

275
    # check CE
R
ruri 已提交
276 277
    if args.enable_ce:
        args.random_seed = 0
278
        logger.warning("CE is running now! already set random seed to 0")
R
ruri 已提交
279

280
    # check class_dim
281
    assert args.class_dim > 1, "class_dim must greater than 1"
R
ruri 已提交
282

283
    # check dali preprocess
R
ruri 已提交
284
    if args.use_dali:
285
        logger.warning(
R
ruri 已提交
286 287 288
            "DALI preprocessing is activated!!!\nWarning: 1. Please make sure paddlepaddle is compiled by GCC5.4 or later version!\n\t 2. Please make sure nightly builds DALI is installed correctly.\n----------------------------------------------------"
        )

289
    #check gpu
R
ruri 已提交
290
    check_gpu()
291
    check_version()
R
ruri 已提交
292 293 294


def init_model(exe, args, program):
295 296 297
    """load model from checkpoint or pretrained model
    """

R
ruri 已提交
298 299
    if args.checkpoint:
        fluid.io.load_persistables(exe, args.checkpoint, main_program=program)
300
        logger.info("Finish initing model from %s" % (args.checkpoint))
R
ruri 已提交
301 302

    if args.pretrained_model:
303
        """
304
        # yapf: disable
305
        # This is a dict of fc layers in all the classification models.
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
        final_fc_name = [
                         "fc8_weights","fc8_offset", #alexnet
                         "fc_weights","fc_offset", #darknet, densenet, dpn, hrnet, mobilenet_v3, res2net, res2net_vd, resnext, resnext_vd, xception
                         #efficient
                         "out","out_offset", "out1","out1_offset", "out2","out2_offset", #googlenet
                         "final_fc_weights", "final_fc_offset", #inception_v4
                         "fc7_weights", "fc7_offset", #mobilenetv1
                         "fc10_weights", "fc10_offset", #mobilenetv2
                         "fc_0", #resnet, resnet_vc, resnet_vd
                         "fc.weight", "fc.bias", #resnext101_wsl
                         "fc6_weights", "fc6_offset", #se_resnet_vd, se_resnext, se_resnext_vd, shufflenet_v2, shufflenet_v2_swish,
                         #squeezenet
                         "fc8_weights", "fc8_offset", #vgg
                         "fc_bias" #"fc_weights", xception_deeplab
                         ]
        # yapf: enable
322 323 324 325 326 327 328
        """
        final_fc_name = []
        if args.finetune_exclude_pretrained_params:
            final_fc_name = [
                str(s)
                for s in args.finetune_exclude_pretrained_params.split(",")
            ]
R
ruri 已提交
329

330
        def is_parameter(var):
331 332 333 334 335 336 337 338
            fc_exclude_flag = False
            for item in final_fc_name:
                if item in var.name:
                    fc_exclude_flag = True

            return isinstance(
                var, fluid.framework.
                Parameter) and not fc_exclude_flag and os.path.exists(
339
                    os.path.join(args.pretrained_model, var.name))
R
ruri 已提交
340

341
        logger.info("Load pretrain weights from {}, exclude params {}.".format(
342
            args.pretrained_model, final_fc_name))
343
        vars = filter(is_parameter, program.list_vars())
R
ruri 已提交
344
        fluid.io.load_vars(
345
            exe, args.pretrained_model, vars=vars, main_program=program)
R
ruri 已提交
346 347 348


def save_model(args, exe, train_prog, info):
349 350 351
    """save model in model_path
    """

R
ruri 已提交
352 353 354 355
    model_path = os.path.join(args.model_save_dir, args.model, str(info))
    if not os.path.isdir(model_path):
        os.makedirs(model_path)
    fluid.io.save_persistables(exe, model_path, main_program=train_prog)
356
    logger.info("Already save model in %s" % (model_path))
R
ruri 已提交
357 358


359 360 361
def save_json(info, path):
    """ save eval result or infer result to file as json format.
    """
362
    with open(path, 'w') as f:
363 364 365
        json.dump(info, f)


366 367
def create_data_loader(is_train, args):
    """create data_loader
R
ruri 已提交
368 369

    Usage:
370
        Using mixup process in training, it will return 5 results, include data_loader, image, y_a(label), y_b(label) and lamda, or it will return 3 results, include data_loader, image, and label.
R
ruri 已提交
371

372
    Args:
R
ruri 已提交
373 374 375 376
        is_train: mode
        args: arguments

    Returns:
377
        data_loader and the input data of net,
R
ruri 已提交
378
    """
R
ruri 已提交
379
    image_shape = args.image_shape
380 381 382 383 384
    feed_image = fluid.data(
        name="feed_image",
        shape=[None] + image_shape,
        dtype="float32",
        lod_level=0)
R
ruri 已提交
385

386 387 388 389
    feed_label = fluid.data(
        name="feed_label", shape=[None, 1], dtype="int64", lod_level=0)
    feed_y_a = fluid.data(
        name="feed_y_a", shape=[None, 1], dtype="int64", lod_level=0)
R
ruri 已提交
390

391 392
    capacity = 64 if int(os.environ.get('PADDLE_TRAINERS_NUM', 1)) <= 1 else 8

R
ruri 已提交
393
    if is_train and args.use_mixup:
394 395 396 397
        feed_y_b = fluid.data(
            name="feed_y_b", shape=[None, 1], dtype="int64", lod_level=0)
        feed_lam = fluid.data(
            name="feed_lam", shape=[None, 1], dtype="float32", lod_level=0)
R
ruri 已提交
398

399
        data_loader = fluid.io.DataLoader.from_generator(
R
ruri 已提交
400
            feed_list=[feed_image, feed_y_a, feed_y_b, feed_lam],
401
            capacity=capacity,
R
ruri 已提交
402
            use_double_buffer=True,
403
            iterable=True)
404
        return data_loader, [feed_image, feed_y_a, feed_y_b, feed_lam]
R
ruri 已提交
405
    else:
406 407 408
        if args.use_dali:
            return None, [feed_image, feed_label]

409
        data_loader = fluid.io.DataLoader.from_generator(
R
ruri 已提交
410
            feed_list=[feed_image, feed_label],
411
            capacity=capacity,
R
ruri 已提交
412
            use_double_buffer=True,
413
            iterable=True)
R
ruri 已提交
414

415
        return data_loader, [feed_image, feed_label]
R
ruri 已提交
416 417


R
ruri 已提交
418 419 420 421 422 423
def print_info(info_mode,
               metrics,
               time_info,
               pass_id=0,
               batch_id=0,
               print_step=1,
424
               device_num=1,
425
               class_dim=5,
426 427
               reader_cost=None,
               ips=None):
R
ruri 已提交
428 429 430 431 432 433 434 435 436 437
    """print function

    Args:
        pass_id: epoch index
        batch_id: batch index
        print_step: the print_step arguments
        metrics: message to print
        time_info: time infomation
        info_mode: mode
    """
438
    #XXX: Use specific name to choose pattern, not the length of metrics.
R
ruri 已提交
439
    if info_mode == "batch":
440 441 442 443 444
        time_info_str = "batch_cost %.5f sec" % time_info
        if reader_cost:
            time_info_str += ", reader_cost %.5f sec" % reader_cost
        if ips:
            time_info_str += ", ips %.5f images/sec" % ips
R
ruri 已提交
445 446 447 448 449
        if batch_id % print_step == 0:
            #if isinstance(metrics,np.ndarray):
            # train and mixup output
            if len(metrics) == 2:
                loss, lr = metrics
450
                logger.info(
451
                    "[Pass {0}, train batch {1}] \tloss {2}, lr {3}, {4}".
R
ruri 已提交
452
                    format(pass_id, batch_id, "%.5f" % loss, "%.5f" % lr,
453
                           time_info_str))
R
ruri 已提交
454 455 456
            # train and no mixup output
            elif len(metrics) == 4:
                loss, acc1, acc5, lr = metrics
457
                logger.info(
458
                    "[Pass {0}, train batch {1}] \tloss {2}, acc1 {3}, acc{7} {4}, lr {5}, {6}".
R
ruri 已提交
459
                    format(pass_id, batch_id, "%.5f" % loss, "%.5f" % acc1,
460 461
                           "%.5f" % acc5, "%.5f" % lr, time_info_str,
                           min(class_dim, 5)))
R
ruri 已提交
462 463 464
            # test output
            elif len(metrics) == 3:
                loss, acc1, acc5 = metrics
465
                logger.info(
466
                    "[Pass {0}, test  batch {1}] \tloss {2}, acc1 {3}, acc{6} {4}, {5}".
R
ruri 已提交
467
                    format(pass_id, batch_id, "%.5f" % loss, "%.5f" % acc1,
468
                           "%.5f" % acc5, time_info_str, min(class_dim, 5)))
R
ruri 已提交
469 470 471 472 473 474 475 476 477 478
            else:
                raise Exception(
                    "length of metrics {} is not implemented, It maybe caused by wrong format of build_program_output".
                    format(len(metrics)))
            sys.stdout.flush()

    elif info_mode == "epoch":
        ## TODO add time elapse
        if len(metrics) == 5:
            train_loss, _, test_loss, test_acc1, test_acc5 = metrics
479
            logger.info(
480
                "[End pass {0}]\ttrain_loss {1}, test_loss {2}, test_acc1 {3}, test_acc{5} {4}".
R
ruri 已提交
481
                format(pass_id, "%.5f" % train_loss, "%.5f" % test_loss, "%.5f"
482
                       % test_acc1, "%.5f" % test_acc5, min(class_dim, 5)))
R
ruri 已提交
483 484
        elif len(metrics) == 7:
            train_loss, train_acc1, train_acc5, _, test_loss, test_acc1, test_acc5 = metrics
485
            logger.info(
486
                "[End pass {0}]\ttrain_loss {1}, train_acc1 {2}, train_acc{7} {3},test_loss {4}, test_acc1 {5}, test_acc{7} {6}".
R
ruri 已提交
487 488
                format(pass_id, "%.5f" % train_loss, "%.5f" % train_acc1, "%.5f"
                       % train_acc5, "%.5f" % test_loss, "%.5f" % test_acc1,
489
                       "%.5f" % test_acc5, min(class_dim, 5)))
R
ruri 已提交
490 491
        sys.stdout.flush()
    elif info_mode == "ce":
R
ruri 已提交
492 493 494 495 496 497 498
        assert len(
            metrics
        ) == 7, "Enable CE: The Metrics should contain train_loss, train_acc1, train_acc5, test_loss, test_acc1, test_acc5, and train_speed"
        assert len(
            time_info
        ) > 10, "0~9th batch statistics will drop when doing benchmark or ce, because it might be mixed with startup time, so please make sure training at least 10 batches."
        print_ce(device_num, metrics, time_info)
R
ruri 已提交
499 500 501 502
    else:
        raise Exception("Illegal info_mode")


R
ruri 已提交
503 504 505 506 507 508 509
def print_ce(device_num, metrics, time_info):
    """ Print log for CE(for internal test).
    """
    train_loss, train_acc1, train_acc5, _, test_loss, test_acc1, test_acc5 = metrics

    train_speed = np.mean(np.array(time_info[10:]))

510 511 512 513 514 515 516
    logger.info("kpis\ttrain_cost_card{}\t{}".format(device_num, train_loss))
    logger.info("kpis\ttrain_acc1_card{}\t{}".format(device_num, train_acc1))
    logger.info("kpis\ttrain_acc5_card{}\t{}".format(device_num, train_acc5))
    logger.info("kpis\ttest_cost_card{}\t{}".format(device_num, test_loss))
    logger.info("kpis\ttest_acc1_card{}\t{}".format(device_num, test_acc1))
    logger.info("kpis\ttest_acc5_card{}\t{}".format(device_num, test_acc5))
    logger.info("kpis\ttrain_speed_card{}\t{}".format(device_num, train_speed))
R
ruri 已提交
517 518


519 520 521 522 523 524
def best_strategy_compiled(args,
                           program,
                           loss,
                           exe,
                           mode="train",
                           share_prog=None):
R
ruri 已提交
525 526 527 528 529 530 531
    """make a program which wrapped by a compiled program
    """

    if os.getenv('FLAGS_use_ngraph'):
        return program
    else:
        build_strategy = fluid.compiler.BuildStrategy()
Z
Zhen Wang 已提交
532 533 534 535
        try:
            fluid.require_version(min_version='1.7.0')
            build_strategy.fuse_bn_act_ops = args.fuse_bn_act_ops
        except Exception as e:
536 537 538
            logger.info(
                "PaddlePaddle version 1.7.0 or higher is "
                "required when you want to fuse batch_norm and activation_op.")
539
        build_strategy.fuse_elewise_add_act_ops = args.fuse_elewise_add_act_ops
R
ruri 已提交
540

L
Leo Chen 已提交
541 542 543 544 545 546 547 548 549
        try:
            build_strategy.enable_addto = args.enable_addto
        except Exception as e:
            logger.info(
                "PaddlePaddle 2.0-rc or higher is "
                "required when you want to enable addto strategy.")
        build_strategy.enable_addto = args.enable_addto


R
ruri 已提交
550
        exec_strategy = fluid.ExecutionStrategy()
R
ruri 已提交
551 552 553 554

        if args.use_gpu:
            exec_strategy.num_threads = fluid.core.get_cuda_device_count()

R
ruri 已提交
555 556
        exec_strategy.num_iteration_per_drop_scope = 10

557 558 559 560 561 562 563
        num_trainers = int(os.environ.get('PADDLE_TRAINERS_NUM', 1))
        if num_trainers > 1 and args.use_gpu:
            dist_utils.prepare_for_multi_process(exe, build_strategy, program)
            # NOTE: the process is fast when num_threads is 1
            # for multi-process training.
            exec_strategy.num_threads = 1

R
ruri 已提交
564
        compiled_program = fluid.CompiledProgram(program).with_data_parallel(
565
            loss_name=loss.name if mode == "train" else None,
566
            share_vars_from=share_prog if mode == "val" else None,
R
ruri 已提交
567 568 569 570
            build_strategy=build_strategy,
            exec_strategy=exec_strategy)

        return compiled_program
571 572 573


class ExponentialMovingAverage(object):
574 575 576 577 578
    def __init__(self,
                 decay=0.999,
                 thres_steps=None,
                 zero_debias=False,
                 name=None):
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
        self._decay = decay
        self._thres_steps = thres_steps
        self._name = name if name is not None else ''
        self._decay_var = self._get_ema_decay()

        self._params_tmps = []
        for param in default_main_program().global_block().all_parameters():
            if param.do_model_average != False:
                tmp = param.block.create_var(
                    name=unique_name.generate(".".join(
                        [self._name + param.name, 'ema_tmp'])),
                    dtype=param.dtype,
                    persistable=False,
                    stop_gradient=True)
                self._params_tmps.append((param, tmp))

        self._ema_vars = {}
        for param, tmp in self._params_tmps:
            with param.block.program._optimized_guard(
598
                [param, tmp]), name_scope('moving_average'):
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
                self._ema_vars[param.name] = self._create_ema_vars(param)

        self.apply_program = Program()
        block = self.apply_program.global_block()
        with program_guard(main_program=self.apply_program):
            decay_pow = self._get_decay_pow(block)
            for param, tmp in self._params_tmps:
                param = block._clone_variable(param)
                tmp = block._clone_variable(tmp)
                ema = block._clone_variable(self._ema_vars[param.name])
                layers.assign(input=param, output=tmp)
                # bias correction
                if zero_debias:
                    ema = ema / (1.0 - decay_pow)
                layers.assign(input=ema, output=param)

        self.restore_program = Program()
        block = self.restore_program.global_block()
        with program_guard(main_program=self.restore_program):
            for param, tmp in self._params_tmps:
                tmp = block._clone_variable(tmp)
                param = block._clone_variable(param)
                layers.assign(input=tmp, output=param)

    def _get_ema_decay(self):
        with default_main_program()._lr_schedule_guard():
            decay_var = layers.tensor.create_global_var(
                shape=[1],
                value=self._decay,
                dtype='float32',
                persistable=True,
                name="scheduled_ema_decay_rate")

            if self._thres_steps is not None:
                decay_t = (self._thres_steps + 1.0) / (self._thres_steps + 10.0)
                with layers.control_flow.Switch() as switch:
                    with switch.case(decay_t < self._decay):
                        layers.tensor.assign(decay_t, decay_var)
                    with switch.default():
                        layers.tensor.assign(
                            np.array(
                                [self._decay], dtype=np.float32),
                            decay_var)
        return decay_var

    def _get_decay_pow(self, block):
        global_steps = layers.learning_rate_scheduler._decay_step_counter()
        decay_var = block._clone_variable(self._decay_var)
        decay_pow_acc = layers.elementwise_pow(decay_var, global_steps + 1)
        return decay_pow_acc

    def _create_ema_vars(self, param):
        param_ema = layers.create_global_var(
            name=unique_name.generate(self._name + param.name + '_ema'),
            shape=param.shape,
            value=0.0,
            dtype=param.dtype,
            persistable=True)

        return param_ema

    def update(self):
        """
        Update Exponential Moving Average. Should only call this method in
        train program.
        """
        param_master_emas = []
        for param, tmp in self._params_tmps:
            with param.block.program._optimized_guard(
668
                [param, tmp]), name_scope('moving_average'):
669 670 671 672 673 674
                param_ema = self._ema_vars[param.name]
                if param.name + '.master' in self._ema_vars:
                    master_ema = self._ema_vars[param.name + '.master']
                    param_master_emas.append([param_ema, master_ema])
                else:
                    ema_t = param_ema * self._decay_var + param * (
675
                        1 - self._decay_var)
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
                    layers.assign(input=ema_t, output=param_ema)

        # for fp16 params
        for param_ema, master_ema in param_master_emas:
            default_main_program().global_block().append_op(
                type="cast",
                inputs={"X": master_ema},
                outputs={"Out": param_ema},
                attrs={
                    "in_dtype": master_ema.dtype,
                    "out_dtype": param_ema.dtype
                })

    @signature_safe_contextmanager
    def apply(self, executor, need_restore=True):
        """
        Apply moving average to parameters for evaluation.

        Args:
            executor (Executor): The Executor to execute applying.
            need_restore (bool): Whether to restore parameters after applying.
        """
        executor.run(self.apply_program)
        try:
            yield
        finally:
            if need_restore:
                self.restore(executor)

    def restore(self, executor):
        """Restore parameters.

        Args:
            executor (Executor): The Executor to execute restoring.
        """
        executor.run(self.restore_program)