train.py 5.9 KB
Newer Older
L
linqingke 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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
#
# less 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.
# ============================================================================

"""train FasterRcnn and get checkpoint files."""

import os
19
import time
L
linqingke 已提交
20
import argparse
21
import ast
L
linqingke 已提交
22 23 24 25 26 27 28
import random
import numpy as np

import mindspore.common.dtype as mstype
from mindspore import context, Tensor
from mindspore.communication.management import init
from mindspore.train.callback import CheckpointConfig, ModelCheckpoint, TimeMonitor
Y
yao_yf 已提交
29 30
from mindspore.train import Model
from mindspore.context import ParallelMode
L
linqingke 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
from mindspore.train.serialization import load_checkpoint, load_param_into_net
from mindspore.nn import SGD
import mindspore.dataset.engine as de

from src.FasterRcnn.faster_rcnn_r50 import Faster_Rcnn_Resnet50
from src.network_define import LossCallBack, WithLossCell, TrainOneStepCell, LossNet
from src.config import config
from src.dataset import data_to_mindrecord_byte_image, create_fasterrcnn_dataset
from src.lr_schedule import dynamic_lr

random.seed(1)
np.random.seed(1)
de.config.set_seed(1)

parser = argparse.ArgumentParser(description="FasterRcnn training")
46
parser.add_argument("--run_distribute", type=ast.literal_eval, default=False, help="Run distribute, default: false.")
Z
zhouyuanshen 已提交
47 48 49 50 51
parser.add_argument("--dataset", type=str, default="coco", help="Dataset name, default: coco.")
parser.add_argument("--pre_trained", type=str, default="", help="Pretrained file path.")
parser.add_argument("--device_id", type=int, default=0, help="Device id, default: 0.")
parser.add_argument("--device_num", type=int, default=1, help="Use device nums, default: 1.")
parser.add_argument("--rank_id", type=int, default=0, help="Rank id, default: 0.")
L
linqingke 已提交
52 53
args_opt = parser.parse_args()

L
linqingke 已提交
54
context.set_context(mode=context.GRAPH_MODE, device_target="Ascend", device_id=args_opt.device_id)
L
linqingke 已提交
55 56

if __name__ == '__main__':
Z
zhouyuanshen 已提交
57
    if args_opt.run_distribute:
L
linqingke 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
        rank = args_opt.rank_id
        device_num = args_opt.device_num
        context.set_auto_parallel_context(device_num=device_num, parallel_mode=ParallelMode.DATA_PARALLEL,
                                          mirror_mean=True, parameter_broadcast=True)
        init()
    else:
        rank = 0
        device_num = 1

    print("Start create dataset!")

    # It will generate mindrecord file in args_opt.mindrecord_dir,
    # and the file name is FasterRcnn.mindrecord0, 1, ... file_num.
    prefix = "FasterRcnn.mindrecord"
    mindrecord_dir = config.mindrecord_dir
    mindrecord_file = os.path.join(mindrecord_dir, prefix + "0")
Z
zhouyuanshen 已提交
74 75
    print("CHECKING MINDRECORD FILES ...")

76
    if rank == 0 and not os.path.exists(mindrecord_file):
L
linqingke 已提交
77 78 79 80
        if not os.path.isdir(mindrecord_dir):
            os.makedirs(mindrecord_dir)
        if args_opt.dataset == "coco":
            if os.path.isdir(config.coco_root):
Z
zhouyuanshen 已提交
81
                print("Create Mindrecord. It may take some time.")
L
linqingke 已提交
82 83 84 85 86 87
                data_to_mindrecord_byte_image("coco", True, prefix)
                print("Create Mindrecord Done, at {}".format(mindrecord_dir))
            else:
                print("coco_root not exits.")
        else:
            if os.path.isdir(config.IMAGE_DIR) and os.path.exists(config.ANNO_PATH):
Z
zhouyuanshen 已提交
88
                print("Create Mindrecord. It may take some time.")
L
linqingke 已提交
89 90 91 92 93
                data_to_mindrecord_byte_image("other", True, prefix)
                print("Create Mindrecord Done, at {}".format(mindrecord_dir))
            else:
                print("IMAGE_DIR or ANNO_PATH not exits.")

94 95 96
    while not os.path.exists(mindrecord_file + ".db"):
        time.sleep(5)

Z
zhouyuanshen 已提交
97
    print("CHECKING MINDRECORD FILES DONE!")
L
linqingke 已提交
98

Z
zhouyuanshen 已提交
99
    loss_scale = float(config.loss_scale)
L
linqingke 已提交
100

Z
zhouyuanshen 已提交
101 102 103
    # When create MindDataset, using the fitst mindrecord file, such as FasterRcnn.mindrecord0.
    dataset = create_fasterrcnn_dataset(mindrecord_file, repeat_num=1,
                                        batch_size=config.batch_size, device_num=device_num, rank_id=rank)
L
linqingke 已提交
104

Z
zhouyuanshen 已提交
105 106
    dataset_size = dataset.get_dataset_size()
    print("Create dataset done!")
L
linqingke 已提交
107

Z
zhouyuanshen 已提交
108 109
    net = Faster_Rcnn_Resnet50(config=config)
    net = net.set_train()
L
linqingke 已提交
110

Z
zhouyuanshen 已提交
111 112 113 114 115 116 117
    load_path = args_opt.pre_trained
    if load_path != "":
        param_dict = load_checkpoint(load_path)
        for item in list(param_dict.keys()):
            if not item.startswith('backbone'):
                param_dict.pop(item)
        load_param_into_net(net, param_dict)
L
linqingke 已提交
118

Z
zhouyuanshen 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
    loss = LossNet()
    lr = Tensor(dynamic_lr(config, rank_size=device_num), mstype.float32)

    opt = SGD(params=net.trainable_params(), learning_rate=lr, momentum=config.momentum,
              weight_decay=config.weight_decay, loss_scale=config.loss_scale)
    net_with_loss = WithLossCell(net, loss)
    if args_opt.run_distribute:
        net = TrainOneStepCell(net_with_loss, net, opt, sens=config.loss_scale, reduce_flag=True,
                               mean=True, degree=device_num)
    else:
        net = TrainOneStepCell(net_with_loss, net, opt, sens=config.loss_scale)

    time_cb = TimeMonitor(data_size=dataset_size)
    loss_cb = LossCallBack()
    cb = [time_cb, loss_cb]
    if config.save_checkpoint:
        ckptconfig = CheckpointConfig(save_checkpoint_steps=config.save_checkpoint_epochs * dataset_size,
                                      keep_checkpoint_max=config.keep_checkpoint_max)
        ckpoint_cb = ModelCheckpoint(prefix='faster_rcnn', directory=config.save_checkpoint_path, config=ckptconfig)
        cb += [ckpoint_cb]

    model = Model(net)
    model.train(config.epoch_size, dataset, callbacks=cb)