main.py 5.4 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

25 26
from hapi.model import Model, CrossEntropy, Input, set_device
from hapi.metrics import Accuracy
D
dengkaipeng 已提交
27

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


D
dengkaipeng 已提交
35 36
def make_optimizer(step_per_epoch, parameter_list=None):
    boundaries = [e * step_per_epoch for e in [40, 60]]
D
dengkaipeng 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
    values = [FLAGS.lr * (0.1 ** i) for i in range(len(boundaries) + 1)]

    learning_rate = fluid.layers.piecewise_decay(
        boundaries=boundaries,
        values=values)
    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

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

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

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

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

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

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

        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 已提交
107 108
    model.fit(train_data=train_dataset,
              eval_data=val_dataset,
D
dengkaipeng 已提交
109 110
              epochs=FLAGS.epoch,
              batch_size=FLAGS.batch_size,
D
dengkaipeng 已提交
111
              save_dir=FLAGS.save_dir or 'tsm_checkpoint',
D
dengkaipeng 已提交
112
              num_workers=FLAGS.num_workers,
D
dengkaipeng 已提交
113 114 115 116 117 118
              drop_last=True,
              shuffle=True)


if __name__ == '__main__':
    parser = argparse.ArgumentParser("CNN training on TSM")
D
dengkaipeng 已提交
119 120 121
    parser.add_argument(
        "--data", type=str, default='dataset/kinetics',
        help="path to dataset root directory")
D
dengkaipeng 已提交
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
    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 已提交
153 154 155 156 157 158
    parser.add_argument(
        "-s",
        "--save_dir",
        default=None,
        type=str,
        help="directory path for checkpoint saving, default ./yolo_checkpoint")
D
dengkaipeng 已提交
159
    FLAGS = parser.parse_args()
D
dengkaipeng 已提交
160
    print_arguments(FLAGS)
D
dengkaipeng 已提交
161 162 163

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