main.py 5.3 KB
Newer Older
D
dengkaipeng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import division
from __future__ import print_function

import os
import argparse
import numpy as np

from paddle import fluid
D
dengkaipeng 已提交
23
from paddle.fluid.dygraph.parallel import ParallelEnv
D
dengkaipeng 已提交
24

L
LielinJiang 已提交
25 26 27 28
from paddle.incubate.hapi.model import Model, Input, set_device
from paddle.incubate.hapi.loss import CrossEntropy
from paddle.incubate.hapi.metrics import Accuracy
from paddle.incubate.hapi.vision.transforms import Compose
D
dengkaipeng 已提交
29

D
dengkaipeng 已提交
30
from modeling import tsm_resnet50
D
dengkaipeng 已提交
31 32 33
from check import check_gpu, check_version
from kinetics_dataset import KineticsDataset
from transforms import *
D
dengkaipeng 已提交
34
from utils import print_arguments
D
dengkaipeng 已提交
35 36


D
dengkaipeng 已提交
37 38
def make_optimizer(step_per_epoch, parameter_list=None):
    boundaries = [e * step_per_epoch for e in [40, 60]]
L
LielinJiang 已提交
39
    values = [FLAGS.lr * (0.1**i) for i in range(len(boundaries) + 1)]
D
dengkaipeng 已提交
40 41

    learning_rate = fluid.layers.piecewise_decay(
L
LielinJiang 已提交
42
        boundaries=boundaries, values=values)
D
dengkaipeng 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55
    optimizer = fluid.optimizer.Momentum(
        learning_rate=learning_rate,
        regularization=fluid.regularizer.L2Decay(1e-4),
        momentum=0.9,
        parameter_list=parameter_list)

    return optimizer


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

L
LielinJiang 已提交
56 57 58 59
    train_transform = Compose([
        GroupScale(), GroupMultiScaleCrop(), GroupRandomCrop(),
        GroupRandomFlip(), NormalizeImage()
    ])
D
dengkaipeng 已提交
60
    train_dataset = KineticsDataset(
L
LielinJiang 已提交
61 62 63 64 65 66
        file_list=os.path.join(FLAGS.data, 'train_10.list'),
        pickle_dir=os.path.join(FLAGS.data, 'train_10'),
        label_list=os.path.join(FLAGS.data, 'label_list'),
        transform=train_transform)
    val_transform = Compose(
        [GroupScale(), GroupCenterCrop(), NormalizeImage()])
D
dengkaipeng 已提交
67
    val_dataset = KineticsDataset(
L
LielinJiang 已提交
68 69 70 71 72
        file_list=os.path.join(FLAGS.data, 'val_10.list'),
        pickle_dir=os.path.join(FLAGS.data, 'val_10'),
        label_list=os.path.join(FLAGS.data, 'label_list'),
        mode='val',
        transform=val_transform)
D
dengkaipeng 已提交
73 74

    pretrained = FLAGS.eval_only and FLAGS.weights is None
L
LielinJiang 已提交
75 76
    model = tsm_resnet50(
        num_classes=train_dataset.num_classes, pretrained=pretrained)
D
dengkaipeng 已提交
77 78 79

    step_per_epoch = int(len(train_dataset) / FLAGS.batch_size \
                         / ParallelEnv().nranks)
D
dengkaipeng 已提交
80
    optim = make_optimizer(step_per_epoch, model.parameters())
D
dengkaipeng 已提交
81 82 83 84 85 86 87

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

    model.prepare(
        optim,
        CrossEntropy(),
D
dengkaipeng 已提交
88
        metrics=Accuracy(topk=(1, 5)),
D
dengkaipeng 已提交
89 90 91 92 93
        inputs=inputs,
        labels=labels,
        device=FLAGS.device)

    if FLAGS.eval_only:
94
        if FLAGS.weights is not None:
D
dengkaipeng 已提交
95
            model.load(FLAGS.weights, reset_optimizer=True)
D
dengkaipeng 已提交
96 97 98 99 100 101 102 103 104 105

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

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

D
dengkaipeng 已提交
106 107
    model.fit(train_data=train_dataset,
              eval_data=val_dataset,
D
dengkaipeng 已提交
108 109
              epochs=FLAGS.epoch,
              batch_size=FLAGS.batch_size,
D
dengkaipeng 已提交
110
              save_dir=FLAGS.save_dir or 'tsm_checkpoint',
D
dengkaipeng 已提交
111
              num_workers=FLAGS.num_workers,
D
dengkaipeng 已提交
112 113 114 115 116 117
              drop_last=True,
              shuffle=True)


if __name__ == '__main__':
    parser = argparse.ArgumentParser("CNN training on TSM")
D
dengkaipeng 已提交
118
    parser.add_argument(
L
LielinJiang 已提交
119 120 121
        "--data",
        type=str,
        default='dataset/kinetics',
D
dengkaipeng 已提交
122
        help="path to dataset root directory")
D
dengkaipeng 已提交
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
    parser.add_argument(
        "--device", type=str, default='gpu', help="device to use, gpu or cpu")
    parser.add_argument(
        "-d", "--dynamic", action='store_true', help="enable dygraph mode")
    parser.add_argument(
        "--eval_only", action='store_true', help="run evaluation only")
    parser.add_argument(
        "-e", "--epoch", default=70, type=int, help="number of epoch")
    parser.add_argument(
        "-j", "--num_workers", default=4, type=int, help="read worker number")
    parser.add_argument(
        '--lr',
        '--learning-rate',
        default=1e-2,
        type=float,
        metavar='LR',
        help='initial learning rate')
    parser.add_argument(
        "-b", "--batch_size", default=16, type=int, help="batch size")
    parser.add_argument(
        "-r",
        "--resume",
        default=None,
        type=str,
        help="checkpoint path to resume")
    parser.add_argument(
        "-w",
        "--weights",
        default=None,
        type=str,
        help="weights path for evaluation")
D
dengkaipeng 已提交
154 155 156 157 158 159
    parser.add_argument(
        "-s",
        "--save_dir",
        default=None,
        type=str,
        help="directory path for checkpoint saving, default ./yolo_checkpoint")
D
dengkaipeng 已提交
160
    FLAGS = parser.parse_args()
D
dengkaipeng 已提交
161
    print_arguments(FLAGS)
D
dengkaipeng 已提交
162 163 164

    check_gpu(str.lower(FLAGS.device) == 'gpu')
    check_version()
D
dengkaipeng 已提交
165
    main()