required=True, help="Checkpoint file path.") parser.add_argument("--run_platform", type=str, default="Ascend", choices=("Ascend", "GPU", "CPU"), help="run platform, support Ascend ,GPU and CPU.") return parser.parse_args() if __name__ == '__main__': args_opt = get_eval_args() if args_opt.dataset == "coco": json_path = os.path.join( config.coco_root, config.instances_set.format(config.val_data_type)) elif args_opt.dataset == "voc": json_path = os.path.join(config.voc_root, config.voc_json) else: raise ValueError('SSD eval only support dataset mode is coco and voc!') context.set_context(mode=context.GRAPH_MODE, device_target=args_opt.run_platform, device_id=args_opt.device_id) mindrecord_file = create_mindrecord(args_opt.dataset, "ssd_eval.mindrecord", False) print("Start Eval!") ssd_eval(mindrecord_file, args_opt.checkpoint_path, json_path)
def main(): args_opt = get_args() rank = 0 device_num = 1 if args_opt.run_platform == "CPU": context.set_context(mode=context.GRAPH_MODE, device_target="CPU") else: context.set_context(mode=context.GRAPH_MODE, device_target=args_opt.run_platform, device_id=args_opt.device_id) if args_opt.distribute: device_num = args_opt.device_num context.reset_auto_parallel_context() context.set_auto_parallel_context( parallel_mode=ParallelMode.DATA_PARALLEL, gradients_mean=True, device_num=device_num) init() context.set_auto_parallel_context( all_reduce_fusion_config=[29, 58, 89]) rank = get_rank() mindrecord_file = create_mindrecord(args_opt.dataset, "ssd.mindrecord", True) if args_opt.only_create_dataset: return loss_scale = float(args_opt.loss_scale) if args_opt.run_platform == "CPU": loss_scale = 1.0 # When create MindDataset, using the fitst mindrecord file, such as ssd.mindrecord0. use_multiprocessing = (args_opt.run_platform != "CPU") dataset = create_ssd_dataset(mindrecord_file, repeat_num=1, batch_size=args_opt.batch_size, device_num=device_num, rank=rank, use_multiprocessing=use_multiprocessing) dataset_size = dataset.get_dataset_size() print("Create dataset done!") backbone = ssd_mobilenet_v2() if config.model == "ssd300": ssd = SSD300(backbone=backbone, config=config) elif config.model == "ssd_mobilenet_v1_fpn": ssd = ssd_mobilenet_v1_fpn(config=config) else: raise ValueError(f'config.model: {config.model} is not supported') if args_opt.run_platform == "GPU": ssd.to_float(dtype.float16) net = SSDWithLossCell(ssd, config) init_net_param(net) if config.feature_extractor_base_param != "": param_dict = load_checkpoint(config.feature_extractor_base_param) for x in list(param_dict.keys()): param_dict["network.feature_extractor.mobilenet_v1." + x] = param_dict[x] del param_dict[x] load_param_into_net(ssd.feature_extractor.mobilenet_v1.network, param_dict) # checkpoint ckpt_config = CheckpointConfig(save_checkpoint_steps=dataset_size * args_opt.save_checkpoint_epochs) save_ckpt_path = './ckpt_' + str(rank) + '/' ckpoint_cb = ModelCheckpoint(prefix="ssd", directory=save_ckpt_path, config=ckpt_config) if args_opt.pre_trained: param_dict = load_checkpoint(args_opt.pre_trained) if args_opt.filter_weight: filter_checkpoint_parameter(param_dict) load_param_into_net(net, param_dict) if args_opt.freeze_layer == "backbone": for param in backbone.feature_1.trainable_params(): param.requires_grad = False lr = Tensor( get_lr(global_step=args_opt.pre_trained_epoch_size * dataset_size, lr_init=config.lr_init, lr_end=config.lr_end_rate * args_opt.lr, lr_max=args_opt.lr, warmup_epochs=config.warmup_epochs, total_epochs=args_opt.epoch_size, steps_per_epoch=dataset_size)) if "use_global_norm" in config and config.use_global_norm: opt = nn.Momentum( filter(lambda x: x.requires_grad, net.get_parameters()), lr, config.momentum, config.weight_decay, 1.0) net = TrainingWrapper(net, opt, loss_scale, True) else: opt = nn.Momentum( filter(lambda x: x.requires_grad, net.get_parameters()), lr, config.momentum, config.weight_decay, loss_scale) net = TrainingWrapper(net, opt, loss_scale) callback = [TimeMonitor(data_size=dataset_size), LossMonitor(), ckpoint_cb] model = Model(net) dataset_sink_mode = False if args_opt.mode == "sink" and args_opt.run_platform != "CPU": print("In sink mode, one epoch return a loss.") dataset_sink_mode = True print( "Start train SSD, the first epoch will be slower because of the graph compilation." ) model.train(args_opt.epoch_size, dataset, callbacks=callback, dataset_sink_mode=dataset_sink_mode)
def main(): parser = argparse.ArgumentParser(description="retinanet training") parser.add_argument("--only_create_dataset", type=ast.literal_eval, default=False, help="If set it true, only create Mindrecord, default is False.") parser.add_argument("--distribute", type=ast.literal_eval, default=False, help="Run distribute, default is False.") parser.add_argument("--device_id", type=int, default=0, help="Device id, default is 0.") parser.add_argument("--device_num", type=int, default=1, help="Use device nums, default is 1.") parser.add_argument("--lr", type=float, default=0.1, help="Learning rate, default is 0.1.") parser.add_argument("--mode", type=str, default="sink", help="Run sink mode or not, default is sink.") parser.add_argument("--dataset", type=str, default="coco", help="Dataset, default is coco.") parser.add_argument("--epoch_size", type=int, default=500, help="Epoch size, default is 500.") parser.add_argument("--batch_size", type=int, default=32, help="Batch size, default is 32.") parser.add_argument("--pre_trained", type=str, default=None, help="Pretrained Checkpoint file path.") parser.add_argument("--pre_trained_epoch_size", type=int, default=0, help="Pretrained epoch size.") parser.add_argument("--save_checkpoint_epochs", type=int, default=1, help="Save checkpoint epochs, default is 1.") parser.add_argument("--loss_scale", type=int, default=1024, help="Loss scale, default is 1024.") parser.add_argument("--filter_weight", type=ast.literal_eval, default=False, help="Filter weight parameters, default is False.") parser.add_argument("--run_platform", type=str, default="Ascend", choices=("Ascend"), help="run platform, only support Ascend.") args_opt = parser.parse_args() if args_opt.run_platform == "Ascend": context.set_context(mode=context.GRAPH_MODE, device_target="Ascend") if args_opt.distribute: if os.getenv("DEVICE_ID", "not_set").isdigit(): context.set_context(device_id=int(os.getenv("DEVICE_ID"))) init() device_num = args_opt.device_num rank = get_rank() context.set_auto_parallel_context(parallel_mode=ParallelMode.DATA_PARALLEL, gradients_mean=True, device_num=device_num) else: rank = 0 device_num = 1 context.set_context(device_id=args_opt.device_id) else: raise ValueError("Unsupported platform.") mindrecord_file = create_mindrecord(args_opt.dataset, "retinanet.mindrecord", True) if not args_opt.only_create_dataset: loss_scale = float(args_opt.loss_scale) # When create MindDataset, using the fitst mindrecord file, such as retinanet.mindrecord0. dataset = create_retinanet_dataset(mindrecord_file, repeat_num=1, batch_size=args_opt.batch_size, device_num=device_num, rank=rank) dataset_size = dataset.get_dataset_size() print("Create dataset done!") backbone = resnet50(config.num_classes) retinanet = retinanet50(backbone, config) net = retinanetWithLossCell(retinanet, config) net.to_float(mindspore.float16) init_net_param(net) if args_opt.pre_trained: if args_opt.pre_trained_epoch_size <= 0: raise KeyError("pre_trained_epoch_size must be greater than 0.") param_dict = load_checkpoint(args_opt.pre_trained) if args_opt.filter_weight: filter_checkpoint_parameter(param_dict) load_param_into_net(net, param_dict) lr = Tensor(get_lr(global_step=config.global_step, lr_init=config.lr_init, lr_end=config.lr_end_rate * args_opt.lr, lr_max=args_opt.lr, warmup_epochs1=config.warmup_epochs1, warmup_epochs2=config.warmup_epochs2, warmup_epochs3=config.warmup_epochs3, warmup_epochs4=config.warmup_epochs4, warmup_epochs5=config.warmup_epochs5, total_epochs=args_opt.epoch_size, steps_per_epoch=dataset_size)) opt = nn.Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), lr, config.momentum, config.weight_decay, loss_scale) net = TrainingWrapper(net, opt, loss_scale) model = Model(net) print("Start train retinanet, the first epoch will be slower because of the graph compilation.") cb = [TimeMonitor(), LossMonitor()] cb += [Monitor(lr_init=lr.asnumpy())] config_ck = CheckpointConfig(save_checkpoint_steps=dataset_size * args_opt.save_checkpoint_epochs, keep_checkpoint_max=config.keep_checkpoint_max) ckpt_cb = ModelCheckpoint(prefix="retinanet", directory=config.save_checkpoint_path, config=config_ck) if args_opt.distribute: if rank == 0: cb += [ckpt_cb] model.train(args_opt.epoch_size, dataset, callbacks=cb, dataset_sink_mode=True) else: cb += [ckpt_cb] model.train(args_opt.epoch_size, dataset, callbacks=cb, dataset_sink_mode=True)
def main(): args_opt = get_args() rank = 0 device_num = 1 if args_opt.run_platform == "CPU": context.set_context(mode=context.GRAPH_MODE, device_target="CPU") else: context.set_context(mode=context.GRAPH_MODE, device_target=args_opt.run_platform, device_id=args_opt.device_id) if args_opt.distribute: device_num = args_opt.device_num context.reset_auto_parallel_context() context.set_auto_parallel_context( parallel_mode=ParallelMode.DATA_PARALLEL, gradients_mean=True, device_num=device_num) init() if config.model == "ssd_resnet50_fpn": context.set_auto_parallel_context( all_reduce_fusion_config=[90, 183, 279]) if config.model == "ssd_vgg16": context.set_auto_parallel_context( all_reduce_fusion_config=[20, 41, 62]) else: context.set_auto_parallel_context( all_reduce_fusion_config=[29, 58, 89]) rank = get_rank() mindrecord_file = create_mindrecord(args_opt.dataset, "ssd.mindrecord", True) if args_opt.only_create_dataset: return loss_scale = float(args_opt.loss_scale) if args_opt.run_platform == "CPU": loss_scale = 1.0 # When create MindDataset, using the fitst mindrecord file, such as ssd.mindrecord0. use_multiprocessing = (args_opt.run_platform != "CPU") dataset = create_ssd_dataset(mindrecord_file, repeat_num=1, batch_size=args_opt.batch_size, device_num=device_num, rank=rank, use_multiprocessing=use_multiprocessing) dataset_size = dataset.get_dataset_size() print(f"Create dataset done! dataset size is {dataset_size}") ssd = ssd_model_build(args_opt) if ("use_float16" in config and config.use_float16) or args_opt.run_platform == "GPU": ssd.to_float(dtype.float16) net = SSDWithLossCell(ssd, config) # checkpoint ckpt_config = CheckpointConfig(save_checkpoint_steps=dataset_size * args_opt.save_checkpoint_epochs) save_ckpt_path = './ckpt_' + str(rank) + '/' ckpoint_cb = ModelCheckpoint(prefix="ssd", directory=save_ckpt_path, config=ckpt_config) if args_opt.pre_trained: param_dict = load_checkpoint(args_opt.pre_trained) if args_opt.filter_weight: filter_checkpoint_parameter_by_list(param_dict, config.checkpoint_filter_list) load_param_into_net(net, param_dict, True) lr = Tensor( get_lr(global_step=args_opt.pre_trained_epoch_size * dataset_size, lr_init=config.lr_init, lr_end=config.lr_end_rate * args_opt.lr, lr_max=args_opt.lr, warmup_epochs=config.warmup_epochs, total_epochs=args_opt.epoch_size, steps_per_epoch=dataset_size)) if "use_global_norm" in config and config.use_global_norm: opt = nn.Momentum( filter(lambda x: x.requires_grad, net.get_parameters()), lr, config.momentum, config.weight_decay, 1.0) net = TrainingWrapper(net, opt, loss_scale, True) else: opt = nn.Momentum( filter(lambda x: x.requires_grad, net.get_parameters()), lr, config.momentum, config.weight_decay, loss_scale) net = TrainingWrapper(net, opt, loss_scale) callback = [TimeMonitor(data_size=dataset_size), LossMonitor(), ckpoint_cb] model = Model(net) dataset_sink_mode = False if args_opt.mode == "sink" and args_opt.run_platform != "CPU": print("In sink mode, one epoch return a loss.") dataset_sink_mode = True print( "Start train SSD, the first epoch will be slower because of the graph compilation." ) model.train(args_opt.epoch_size, dataset, callbacks=callback, dataset_sink_mode=dataset_sink_mode)
# Copyright 2021 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 # # 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. # ============================================================================ """create mindrecord for training retinanet.""" import argparse from src.dataset import create_mindrecord if __name__ == "__main__": parser = argparse.ArgumentParser(description="retinanet dataset create") parser.add_argument("--dataset", type=str, default="coco", help="Dataset, default is coco.") args_opt = parser.parse_args() mindrecord_file = create_mindrecord(args_opt.dataset, "retinanet.mindrecord", True)