main.py 6.4 KB
Newer Older
L
LielinJiang 已提交
1
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
L
LielinJiang 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#
# 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 division
from __future__ import print_function

import argparse
import contextlib
import os

import time
import math
import numpy as np

26
import paddle.fluid as fluid
L
LielinJiang 已提交
27
from paddle.fluid.dygraph.parallel import ParallelEnv
D
dengkaipeng 已提交
28
from paddle.io import BatchSampler, DataLoader
L
LielinJiang 已提交
29

L
LielinJiang 已提交
30 31
from hapi.model import Input, set_device
from hapi.loss import CrossEntropy
32 33 34 35 36 37
from hapi.distributed import DistributedBatchSampler
from hapi.metrics import Accuracy
import hapi.vision.models as models

from imagenet_dataset import ImageNetDataset

L
LielinJiang 已提交
38 39 40

def make_optimizer(step_per_epoch, parameter_list=None):
    base_lr = FLAGS.lr
41 42 43 44 45
    lr_scheduler = FLAGS.lr_scheduler
    momentum = FLAGS.momentum
    weight_decay = FLAGS.weight_decay

    if lr_scheduler == 'piecewise':
L
LielinJiang 已提交
46 47
        milestones = FLAGS.milestones
        boundaries = [step_per_epoch * e for e in milestones]
48 49 50 51 52 53 54 55 56 57
        values = [base_lr * (0.1**i) for i in range(len(boundaries) + 1)]
        learning_rate = fluid.layers.piecewise_decay(
            boundaries=boundaries, values=values)
    elif lr_scheduler == 'cosine':
        learning_rate = fluid.layers.cosine_decay(base_lr, step_per_epoch,
                                                  FLAGS.epoch)
    else:
        raise ValueError(
            "Expected lr_scheduler in ['piecewise', 'cosine'], but got {}".
            format(lr_scheduler))
L
LielinJiang 已提交
58 59 60 61 62 63

    learning_rate = fluid.layers.linear_lr_warmup(
        learning_rate=learning_rate,
        warmup_steps=5 * step_per_epoch,
        start_lr=0.,
        end_lr=base_lr)
64

L
LielinJiang 已提交
65 66 67 68 69
    optimizer = fluid.optimizer.Momentum(
        learning_rate=learning_rate,
        momentum=momentum,
        regularization=fluid.regularizer.L2Decay(weight_decay),
        parameter_list=parameter_list)
70

L
LielinJiang 已提交
71 72 73 74 75 76 77
    return optimizer


def main():
    device = set_device(FLAGS.device)
    fluid.enable_dygraph(device) if FLAGS.dynamic else None

78 79 80
    model_list = [x for x in models.__dict__["__all__"]]
    assert FLAGS.arch in model_list, "Expected FLAGS.arch in {}, but received {}".format(
        model_list, FLAGS.arch)
L
LielinJiang 已提交
81 82
    model = models.__dict__[FLAGS.arch](pretrained=FLAGS.eval_only and
                                        not FLAGS.resume)
L
LielinJiang 已提交
83 84 85 86 87 88 89 90

    if FLAGS.resume is not None:
        model.load(FLAGS.resume)

    inputs = [Input([None, 3, 224, 224], 'float32', name='image')]
    labels = [Input([None, 1], 'int64', name='label')]

    train_dataset = ImageNetDataset(
L
LielinJiang 已提交
91 92 93 94 95 96 97 98 99 100
        os.path.join(FLAGS.data, 'train'),
        mode='train',
        image_size=FLAGS.image_size,
        resize_short_size=FLAGS.resize_short_size)

    val_dataset = ImageNetDataset(
        os.path.join(FLAGS.data, 'val'),
        mode='val',
        image_size=FLAGS.image_size,
        resize_short_size=FLAGS.resize_short_size)
L
LielinJiang 已提交
101 102 103 104 105 106

    optim = make_optimizer(
        np.ceil(
            len(train_dataset) * 1. / FLAGS.batch_size / ParallelEnv().nranks),
        parameter_list=model.parameters())

107 108 109 110 111 112 113
    model.prepare(
        optim,
        CrossEntropy(),
        Accuracy(topk=(1, 5)),
        inputs,
        labels,
        FLAGS.device)
L
LielinJiang 已提交
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

    if FLAGS.eval_only:
        model.evaluate(
            val_dataset,
            batch_size=FLAGS.batch_size,
            num_workers=FLAGS.num_workers)
        return

    output_dir = os.path.join(FLAGS.output_dir, FLAGS.arch,
                              time.strftime('%Y-%m-%d-%H-%M',
                                            time.localtime()))
    if ParallelEnv().local_rank == 0 and not os.path.exists(output_dir):
        os.makedirs(output_dir)

    model.fit(train_dataset,
              val_dataset,
              batch_size=FLAGS.batch_size,
              epochs=FLAGS.epoch,
              save_dir=output_dir,
              num_workers=FLAGS.num_workers)


if __name__ == '__main__':
    parser = argparse.ArgumentParser("Resnet Training on ImageNet")
    parser.add_argument(
        'data',
        metavar='DIR',
        help='path to dataset '
        '(should have subdirectories named "train" and "val"')
    parser.add_argument(
        "--arch", type=str, default='resnet50', help="model name")
    parser.add_argument(
        "--device", type=str, default='gpu', help="device to run, cpu or gpu")
    parser.add_argument(
        "-d", "--dynamic", action='store_true', help="enable dygraph mode")
    parser.add_argument(
L
LielinJiang 已提交
150
        "-e", "--epoch", default=90, type=int, help="number of epoch")
L
LielinJiang 已提交
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
    parser.add_argument(
        '--lr',
        '--learning-rate',
        default=0.1,
        type=float,
        metavar='LR',
        help='initial learning rate')
    parser.add_argument(
        "-b", "--batch-size", default=64, type=int, help="batch size")
    parser.add_argument(
        "-n", "--num-workers", default=4, type=int, help="dataloader workers")
    parser.add_argument(
        "--output-dir", type=str, default='output', help="save dir")
    parser.add_argument(
        "-r",
        "--resume",
        default=None,
        type=str,
        help="checkpoint path to resume")
    parser.add_argument(
171
        "--eval-only", action='store_true', help="only evaluate the model")
172 173 174 175 176
    parser.add_argument(
        "--lr-scheduler",
        default='piecewise',
        type=str,
        help="learning rate scheduler")
L
LielinJiang 已提交
177 178 179 180 181 182
    parser.add_argument(
        "--milestones",
        nargs='+',
        type=int,
        default=[30, 60, 80],
        help="piecewise decay milestones")
183 184 185
    parser.add_argument(
        "--weight-decay", default=1e-4, type=float, help="weight decay")
    parser.add_argument("--momentum", default=0.9, type=float, help="momentum")
L
LielinJiang 已提交
186 187 188 189 190
    parser.add_argument(
        "--image-size", default=224, type=int, help="intput image size")
    parser.add_argument(
        "--resize-short-size",
        default=256,
L
LielinJiang 已提交
191
        type=int,
L
LielinJiang 已提交
192
        help="short size of keeping ratio resize")
L
LielinJiang 已提交
193 194 195
    FLAGS = parser.parse_args()
    assert FLAGS.data, "error: must provide data path"
    main()