def train_net(args, ctx, pretrained, pretrained_base, pretrained_ec, epoch, prefix, begin_epoch, end_epoch, lr, lr_step): logger, final_output_path = create_logger(config.output_path, args.cfg, config.dataset.image_set) prefix = os.path.join(final_output_path, prefix) # load symbol shutil.copy2(os.path.join(curr_path, 'symbols', config.symbol + '.py'), final_output_path) sym_instance = eval(config.symbol + '.' + config.symbol)() sym = sym_instance.get_train_symbol(config) # setup multi-gpu batch_size = len(ctx) input_batch_size = config.TRAIN.BATCH_IMAGES * batch_size # print config pprint.pprint(config) logger.info('training config:{}\n'.format(pprint.pformat(config))) # load dataset and prepare imdb for training image_sets = [iset for iset in config.dataset.image_set.split('+')] segdbs = [ load_gt_segdb(config.dataset.dataset, image_set, config.dataset.root_path, config.dataset.dataset_path, result_path=final_output_path, flip=config.TRAIN.FLIP) for image_set in image_sets ] segdb = merge_segdb(segdbs) # load training data train_data = TrainDataLoader(sym, segdb, config, batch_size=input_batch_size, crop_height=config.TRAIN.CROP_HEIGHT, crop_width=config.TRAIN.CROP_WIDTH, shuffle=config.TRAIN.SHUFFLE, ctx=ctx) # infer max shape max_data_shape = [('data', (config.TRAIN.BATCH_IMAGES, 3, max([v[0] for v in config.SCALES]), max([v[1] for v in config.SCALES]))), ('data_ref', (config.TRAIN.KEY_INTERVAL - 1, 3, max([v[0] for v in config.SCALES]), max([v[1] for v in config.SCALES]))), ('eq_flag', (1, ))] max_data_shape, max_label_shape = train_data.infer_shape(max_data_shape) print 'providing maximum shape', max_data_shape, max_label_shape data_shape_dict = dict(train_data.provide_data_single + train_data.provide_label_single) pprint.pprint(data_shape_dict) sym_instance.infer_shape(data_shape_dict) # load and initialize params if config.TRAIN.RESUME: print('continue training from ', begin_epoch) arg_params, aux_params = load_param(prefix, begin_epoch, convert=True) else: print pretrained arg_params, aux_params = load_param(pretrained, epoch, convert=True) arg_params_base, aux_params_base = load_param(pretrained_base, epoch, convert=True) arg_params.update(arg_params_base) aux_params.update(aux_params_base) arg_params_ec, aux_params_ec = load_param( pretrained_ec, epoch, convert=True, argprefix=config.TRAIN.arg_prefix) arg_params.update(arg_params_ec) aux_params.update(aux_params_ec) sym_instance.init_weight(config, arg_params, aux_params) # check parameter shapes sym_instance.check_parameter_shapes(arg_params, aux_params, data_shape_dict) # create solver fixed_param_prefix = config.network.FIXED_PARAMS data_names = [k[0] for k in train_data.provide_data_single] label_names = [k[0] for k in train_data.provide_label_single] mod = MutableModule( sym, data_names=data_names, label_names=label_names, logger=logger, context=ctx, max_data_shapes=[max_data_shape for _ in range(batch_size)], max_label_shapes=[max_label_shape for _ in range(batch_size)], fixed_param_prefix=fixed_param_prefix) if config.TRAIN.RESUME: mod._preload_opt_states = '%s-%04d.states' % (prefix, begin_epoch) # decide training params # metric fcn_loss_metric = metric.FCNLogLossMetric(config.default.frequent * batch_size) eval_metrics = mx.metric.CompositeEvalMetric() for child_metric in [fcn_loss_metric]: eval_metrics.add(child_metric) # callback batch_end_callback = callback.Speedometer(train_data.batch_size, frequent=args.frequent) epoch_end_callback = mx.callback.module_checkpoint( mod, prefix, period=1, save_optimizer_states=True) # decide learning rate base_lr = lr lr_factor = 0.1 lr_epoch = [float(epoch) for epoch in lr_step.split(',')] lr_epoch_diff = [ epoch - begin_epoch for epoch in lr_epoch if epoch > begin_epoch ] lr = base_lr * (lr_factor**(len(lr_epoch) - len(lr_epoch_diff))) lr_iters = [ int(epoch * len(segdb) / batch_size) for epoch in lr_epoch_diff ] print 'lr', lr, 'lr_epoch_diff', lr_epoch_diff, 'lr_iters', lr_iters lr_scheduler = WarmupMultiFactorScheduler(lr_iters, lr_factor, config.TRAIN.warmup, config.TRAIN.warmup_lr, config.TRAIN.warmup_step) # optimizer optimizer_params = { 'momentum': config.TRAIN.momentum, 'wd': config.TRAIN.wd, 'learning_rate': lr, 'lr_scheduler': lr_scheduler, 'rescale_grad': 1.0, 'clip_gradient': None } if not isinstance(train_data, PrefetchingIter): train_data = PrefetchingIter(train_data) # train mod.fit(train_data, eval_metric=eval_metrics, epoch_end_callback=epoch_end_callback, batch_end_callback=batch_end_callback, kvstore=config.default.kvstore, optimizer='sgd', optimizer_params=optimizer_params, arg_params=arg_params, aux_params=aux_params, begin_epoch=begin_epoch, num_epoch=end_epoch)
def train_net(args, ctx, pretrained, epoch, prefix, begin_epoch, end_epoch, lr, lr_step): """Main train function for segmentation Args: args: paramenter parser ctx: GPU context pretrained: pretrained file path epoch: pretrained checkpoint epoch prefix: model save name prefix begin_epoch: which epoch start to train end_epoch: eneded epoch of training phase lr: learning rate lr_step: list of epoch number to do learning rate decay """ ########################################## # Step 1. Create logger and set up the save prefix ########################################## logger, final_output_path = create_logger(config.output_path, args.cfg, config.dataset.image_set) prefix = os.path.join(final_output_path, prefix) ########################################## # Step 2. Copy the symbols and load the symbol to build network ########################################## shutil.copy2(os.path.join(curr_path, 'symbols', config.symbol + '.py'), final_output_path) sym_instance = eval(config.symbol + '.' + config.symbol)() sym = sym_instance.get_symbol(config, is_train=True) # #sym = eval('get_' + args.network + '_train')(num_classes=config.dataset.NUM_CLASSES) ########################################## # Step 3. Setup multi-gpu and batch size ########################################## batch_size = len(ctx) input_batch_size = config.TRAIN.BATCH_IMAGES * batch_size # print config pprint.pprint(config) logger.info('training config:{}\n'.format(pprint.pformat(config))) ############################################ # Step 4. load dataset and prepare imdb for training ############################################ image_sets = [iset for iset in config.dataset.image_set.split('+')] segdbs = [ load_gt_segdb(config.dataset.dataset, image_set, config.dataset.root_path, config.dataset.dataset_path, result_path=final_output_path, flip=config.TRAIN.FLIP) for image_set in image_sets ] segdb = merge_segdb(segdbs) ############################################ # Step 5. Set dataloader and set the data shape ############################################ train_data = TrainDataLoader(sym, segdb, config, batch_size=input_batch_size, crop_height=config.TRAIN.CROP_HEIGHT, crop_width=config.TRAIN.CROP_WIDTH, shuffle=config.TRAIN.SHUFFLE, ctx=ctx) # infer max shape max_scale = [(config.TRAIN.CROP_HEIGHT, config.TRAIN.CROP_WIDTH)] max_data_shape = [('data', (config.TRAIN.BATCH_IMAGES, 3, max([v[0] for v in max_scale]), max([v[1] for v in max_scale])))] max_label_shape = [('label', (config.TRAIN.BATCH_IMAGES, 1, max([v[0] for v in max_scale]), max([v[1] for v in max_scale])))] # max_data_shape, max_label_shape = train_data.infer_shape(max_data_shape, max_label_shape) print('providing maximum shape', max_data_shape, max_label_shape) # infer shape data_shape_dict = dict(train_data.provide_data_single + train_data.provide_label_single) pprint.pprint(data_shape_dict) sym_instance.infer_shape(data_shape_dict) ############################################## # Step 6. load and initialize params ############################################## if config.TRAIN.RESUME: print('continue training from ', begin_epoch) arg_params, aux_params = load_param(prefix, begin_epoch, convert=True) else: print(pretrained) arg_params, aux_params = load_param(pretrained, epoch, convert=True) sym_instance.init_weights(config, arg_params, aux_params) # check parameter shapes sym_instance.check_parameter_shapes(arg_params, aux_params, data_shape_dict) ############################################## # Step 6 Create solver and set metrics ############################################## fixed_param_prefix = config.network.FIXED_PARAMS data_names = [k[0] for k in train_data.provide_data_single] label_names = [k[0] for k in train_data.provide_label_single] mod = MutableModule( sym, data_names=data_names, label_names=label_names, logger=logger, context=ctx, max_data_shapes=[max_data_shape for _ in xrange(batch_size)], max_label_shapes=[max_label_shape for _ in xrange(batch_size)], fixed_param_prefix=fixed_param_prefix) # decide training params # metric fcn_loss_metric = metric.FCNLogLossMetric(config.default.frequent * batch_size) eval_metrics = mx.metric.CompositeEvalMetric() # rpn_eval_metric, rpn_cls_metric, rpn_bbox_metric, eval_metric, cls_metric, bbox_metric for child_metric in [fcn_loss_metric]: eval_metrics.add(child_metric) ############################################## # Step 7. Set callback for training process ############################################## batch_end_callback = callback.Speedometer(train_data.batch_size, frequent=args.frequent) epoch_end_callback = mx.callback.module_checkpoint( mod, prefix, period=1, save_optimizer_states=True) ############################################## # Step 8. Decide learning rate and optimizers ############################################## base_lr = lr lr_factor = 0.1 lr_epoch = [float(epoch) for epoch in lr_step.split(',')] lr_epoch_diff = [ epoch - begin_epoch for epoch in lr_epoch if epoch > begin_epoch ] lr = base_lr * (lr_factor**(len(lr_epoch) - len(lr_epoch_diff))) lr_iters = [ int(epoch * len(segdb) / batch_size) for epoch in lr_epoch_diff ] print('lr', lr, 'lr_epoch_diff', lr_epoch_diff, 'lr_iters', lr_iters) lr_scheduler = WarmupMultiFactorScheduler(lr_iters, lr_factor, config.TRAIN.warmup, config.TRAIN.warmup_lr, config.TRAIN.warmup_step) # optimizer optimizer_params = { 'momentum': config.TRAIN.momentum, 'wd': config.TRAIN.wd, 'learning_rate': lr, 'lr_scheduler': lr_scheduler, 'rescale_grad': 1.0, 'clip_gradient': None } if not isinstance(train_data, PrefetchingIter): train_data = PrefetchingIter(train_data) ############################################## # Step 9 Start to train ############################################## mod.fit(train_data, eval_metric=eval_metrics, epoch_end_callback=epoch_end_callback, batch_end_callback=batch_end_callback, kvstore=config.default.kvstore, optimizer='sgd', optimizer_params=optimizer_params, arg_params=arg_params, aux_params=aux_params, begin_epoch=begin_epoch, num_epoch=end_epoch)
def train_net(args, ctx, pretrained, epoch, prefix, begin_epoch, end_epoch, lr, lr_step): new_args_name = args.cfg if args.vis: config.TRAIN.VISUALIZE = True logger, final_output_path = create_logger(config.output_path, new_args_name, config.dataset.image_set, args.temp) prefix = os.path.join(final_output_path, prefix) logger.info('called with args {}'.format(args)) print(config.train_iter.SE3_PM_LOSS) if config.train_iter.SE3_PM_LOSS: print("SE3_PM_LOSS == True") else: print("SE3_PM_LOSS == False") if not config.network.STANDARD_FLOW_REP: print_and_log("[h, w] representation for flow is dep", logger) # load dataset and prepare imdb for training image_sets = [iset for iset in config.dataset.image_set.split('+')] datasets = [dset for dset in config.dataset.dataset.split('+')] print("config.dataset.class_name: {}".format(config.dataset.class_name)) print("image_sets: {}".format(image_sets)) if datasets[0].startswith('ModelNet'): pairdbs = [ load_gt_pairdb(config, datasets[i], image_sets[i] + class_name.split('/')[-1], config.dataset.root_path, config.dataset.dataset_path, class_name=class_name, result_path=final_output_path) for class_name in config.dataset.class_name for i in range(len(image_sets)) ] else: pairdbs = [ load_gt_pairdb(config, datasets[i], image_sets[i] + class_name, config.dataset.root_path, config.dataset.dataset_path, class_name=class_name, result_path=final_output_path) for class_name in config.dataset.class_name for i in range(len(image_sets)) ] pairdb = merge_pairdb(pairdbs) if not args.temp: src_file = os.path.join(curr_path, 'symbols', config.symbol + '.py') dst_file = os.path.join( final_output_path, '{}_{}.py'.format(config.symbol, time.strftime('%Y-%m-%d-%H-%M'))) os.popen('cp {} {}'.format(src_file, dst_file)) sym_instance = eval(config.symbol + '.' + config.symbol)() sym = sym_instance.get_symbol(config, is_train=True) # setup multi-gpu batch_size = len(ctx) input_batch_size = config.TRAIN.BATCH_PAIRS * batch_size pprint.pprint(config) logger.info('training config:{}\n'.format(pprint.pformat(config))) # load training data train_data = TrainDataLoader(sym, pairdb, config, batch_size=input_batch_size, shuffle=config.TRAIN.SHUFFLE, ctx=ctx) train_data.get_batch_parallel() max_scale = [ max([v[0] for v in config.SCALES]), max(v[1] for v in config.SCALES) ] max_data_shape = [('image_observed', (config.TRAIN.BATCH_PAIRS, 3, max_scale[0], max_scale[1])), ('image_rendered', (config.TRAIN.BATCH_PAIRS, 3, max_scale[0], max_scale[1])), ('depth_gt_observed', (config.TRAIN.BATCH_PAIRS, 1, max_scale[0], max_scale[1])), ('src_pose', (config.TRAIN.BATCH_PAIRS, 3, 4)), ('tgt_pose', (config.TRAIN.BATCH_PAIRS, 3, 4))] if config.network.INPUT_DEPTH: max_data_shape.append(('depth_observed', (config.TRAIN.BATCH_PAIRS, 1, max_scale[0], max_scale[1]))) max_data_shape.append(('depth_rendered', (config.TRAIN.BATCH_PAIRS, 1, max_scale[0], max_scale[1]))) if config.network.INPUT_MASK: max_data_shape.append(('mask_observed', (config.TRAIN.BATCH_PAIRS, 1, max_scale[0], max_scale[1]))) max_data_shape.append(('mask_rendered', (config.TRAIN.BATCH_PAIRS, 1, max_scale[0], max_scale[1]))) rot_param = 3 if config.network.ROT_TYPE == "EULER" else 4 max_label_shape = [('rot', (config.TRAIN.BATCH_PAIRS, rot_param)), ('trans', (config.TRAIN.BATCH_PAIRS, 3))] if config.network.PRED_FLOW: max_label_shape.append(('flow', (config.TRAIN.BATCH_PAIRS, 2, max_scale[0], max_scale[1]))) max_label_shape.append(('flow_weights', (config.TRAIN.BATCH_PAIRS, 2, max_scale[0], max_scale[1]))) if config.train_iter.SE3_PM_LOSS: max_label_shape.append( ('point_cloud_model', (config.TRAIN.BATCH_PAIRS, 3, config.train_iter.NUM_3D_SAMPLE))) max_label_shape.append( ('point_cloud_weights', (config.TRAIN.BATCH_PAIRS, 3, config.train_iter.NUM_3D_SAMPLE))) max_label_shape.append( ('point_cloud_observed', (config.TRAIN.BATCH_PAIRS, 3, config.train_iter.NUM_3D_SAMPLE))) if config.network.PRED_MASK: max_label_shape.append( ('mask_gt_observed', (config.TRAIN.BATCH_PAIRS, 1, max_scale[0], max_scale[1]))) # max_data_shape, max_label_shape = train_data.infer_shape(max_data_shape, max_label_shape) print_and_log( 'providing maximum shape, {}, {}'.format(max_data_shape, max_label_shape), logger) # infer max shape ''' max_label_shape = [('label', (config.TRAIN.BATCH_IMAGES, 1, max([v[0] for v in max_scale]), max([v[1] for v in max_scale])))] max_data_shape, max_label_shape = train_data.infer_shape( max_data_shape, max_label_shape) print('providing maximum shape', max_data_shape, max_label_shape) ''' # infer shape data_shape_dict = dict(train_data.provide_data_single + train_data.provide_label_single) print_and_log('\ndata_shape_dict: {}\n'.format(data_shape_dict), logger) sym_instance.infer_shape(data_shape_dict) print('************(wg): infering shape **************') internals = sym.get_internals() _, out_shapes, _ = internals.infer_shape(**data_shape_dict) print(sym.list_outputs()) shape_dict = dict(zip(internals.list_outputs(), out_shapes)) pprint.pprint(shape_dict) # load and initialize params if config.TRAIN.RESUME: print('continue training from ', begin_epoch) arg_params, aux_params = load_param(prefix, begin_epoch, convert=True) elif pretrained == 'xavier': print('xavier') # arg_params = {} # aux_params = {} # sym_instance.init_weights(config, arg_params, aux_params) else: print(pretrained) arg_params, aux_params = load_param(pretrained, epoch, convert=True) print('arg_params: ', arg_params.keys()) print('aux_params: ', aux_params.keys()) if not config.network.skip_initialize: sym_instance.init_weights(config, arg_params, aux_params) # check parameter shapes if pretrained != 'xavier': sym_instance.check_parameter_shapes(arg_params, aux_params, data_shape_dict) # create solver fixed_param_prefix = config.network.FIXED_PARAMS data_names = [k[0] for k in train_data.provide_data_single] label_names = [k[0] for k in train_data.provide_label_single] mod = MutableModule( sym, data_names=data_names, label_names=label_names, logger=logger, context=ctx, max_data_shapes=[max_data_shape for _ in range(batch_size)], max_label_shapes=[max_label_shape for _ in range(batch_size)], fixed_param_prefix=fixed_param_prefix, config=config) # decide training params # metrics eval_metrics = mx.metric.CompositeEvalMetric() metric_list = [] iter_idx = 0 if config.network.PRED_FLOW: metric_list.append(metric.Flow_L2LossMetric(config, iter_idx)) metric_list.append(metric.Flow_CurLossMetric(config, iter_idx)) if config.train_iter.SE3_DIST_LOSS: metric_list.append(metric.Rot_L2LossMetric(config, iter_idx)) metric_list.append(metric.Trans_L2LossMetric(config, iter_idx)) if config.train_iter.SE3_PM_LOSS: metric_list.append(metric.PointMatchingLossMetric(config, iter_idx)) if config.network.PRED_MASK: metric_list.append(metric.MaskLossMetric(config, iter_idx)) # Visualize Training Batches if config.TRAIN.VISUALIZE: metric_list.append(metric.SimpleVisualize(config)) # metric_list.append(metric.MaskVisualize(config, save_dir = final_output_path)) metric_list.append( metric.MinibatchVisualize(config)) # flow visualization for child_metric in metric_list: eval_metrics.add(child_metric) # callback batch_end_callback = callback.Speedometer(train_data.batch_size, frequent=args.frequent) epoch_end_callback = mx.callback.module_checkpoint( mod, prefix, period=1, save_optimizer_states=True) # decide learning rate base_lr = lr lr_factor = 0.1 lr_epoch = [float(epoch) for epoch in lr_step.split(',')] lr_epoch_diff = [ epoch - begin_epoch for epoch in lr_epoch if epoch > begin_epoch ] lr = base_lr * (lr_factor**(len(lr_epoch) - len(lr_epoch_diff))) lr_iters = [ int(epoch * len(pairdb) / batch_size) for epoch in lr_epoch_diff ] print('lr', lr, 'lr_epoch_diff', lr_epoch_diff, 'lr_iters', lr_iters) lr_scheduler = WarmupMultiFactorScheduler(lr_iters, lr_factor, config.TRAIN.warmup, config.TRAIN.warmup_lr, config.TRAIN.warmup_step) if not isinstance(train_data, PrefetchingIter): train_data = PrefetchingIter(train_data) # train if config.TRAIN.optimizer == 'adam': optimizer_params = {'learning_rate': lr} if pretrained == 'xavier': init = mx.init.Mixed(['rot_weight|trans_weight', '.*'], [ mx.init.Zero(), mx.init.Xavier( rnd_type='gaussian', factor_type="in", magnitude=2) ]) mod.fit(train_data, eval_metric=eval_metrics, epoch_end_callback=epoch_end_callback, batch_end_callback=batch_end_callback, kvstore=config.default.kvstore, optimizer='adam', optimizer_params=optimizer_params, begin_epoch=begin_epoch, num_epoch=end_epoch, prefix=prefix, initializer=init, force_init=True) else: mod.fit(train_data, eval_metric=eval_metrics, epoch_end_callback=epoch_end_callback, batch_end_callback=batch_end_callback, kvstore=config.default.kvstore, optimizer='adam', arg_params=arg_params, aux_params=aux_params, begin_epoch=begin_epoch, num_epoch=end_epoch, prefix=prefix) elif config.TRAIN.optimizer == 'sgd': # optimizer optimizer_params = { 'momentum': config.TRAIN.momentum, 'wd': config.TRAIN.wd, 'learning_rate': lr, 'lr_scheduler': lr_scheduler, 'rescale_grad': 1.0, 'clip_gradient': None } if pretrained == 'xavier': init = mx.init.Mixed(['rot_weight|trans_weight', '.*'], [ mx.init.Zero(), mx.init.Xavier( rnd_type='gaussian', factor_type="in", magnitude=2) ]) mod.fit(train_data, eval_metric=eval_metrics, epoch_end_callback=epoch_end_callback, batch_end_callback=batch_end_callback, kvstore=config.default.kvstore, optimizer='sgd', optimizer_params=optimizer_params, begin_epoch=begin_epoch, num_epoch=end_epoch, prefix=prefix, initializer=init, force_init=True) else: mod.fit(train_data, eval_metric=eval_metrics, epoch_end_callback=epoch_end_callback, batch_end_callback=batch_end_callback, kvstore=config.default.kvstore, optimizer='sgd', optimizer_params=optimizer_params, arg_params=arg_params, aux_params=aux_params, begin_epoch=begin_epoch, num_epoch=end_epoch, prefix=prefix)
def train_net(args, ctx, pretrained, epoch, prefix, begin_epoch, end_epoch, lr, lr_step): logger, final_output_path, _, tensorboard_path = create_env( config.output_path, args.cfg, config.dataset.image_set) prefix = os.path.join(final_output_path, prefix) # print config pprint.pprint(config) logger.info('training config:{}\n'.format(pprint.pformat(config))) print "config.symbol", config.symbol sym_instance = eval(config.symbol + '.' + config.symbol)() sym = sym_instance.get_symbol(config, is_train=True) # setup multi-gpu input_batch_size = config.TRAIN.BATCH_IMAGES * len(ctx) NUM_GPUS = len(ctx) # load dataset and prepare imdb for training image_sets = [iset for iset in config.dataset.image_set.split('+')] segdbs = [ load_gt_segdb(config.dataset.dataset, image_set, config.dataset.root_path, config.dataset.dataset_path, result_path=final_output_path) for image_set in image_sets ] segdb = merge_segdb(segdbs) # load training data train_data = TrainDataLoader(sym, segdb, config, batch_size=input_batch_size, shuffle=config.TRAIN.SHUFFLE, ctx=ctx) # loading val data val_image_set = config.dataset.test_image_set val_root_path = config.dataset.root_path val_dataset = config.dataset.dataset val_dataset_path = config.dataset.dataset_path val_imdb = eval(val_dataset)(val_image_set, val_root_path, val_dataset_path, result_path=final_output_path) val_segdb = val_imdb.gt_segdb() val_data = TrainDataLoader(sym, val_segdb, config, batch_size=input_batch_size, shuffle=config.TRAIN.SHUFFLE, ctx=ctx) # infer max shape max_scale = [(config.TRAIN.crop_size[0], config.TRAIN.crop_size[1])] max_data_shape = [('data', (config.TRAIN.BATCH_IMAGES, 3, max([v[0] for v in max_scale]), max([v[1] for v in max_scale])))] max_label_shape = [ ('label', (config.TRAIN.BATCH_IMAGES, 1, max([v[0] for v in max_scale]) // config.network.LABEL_STRIDE, max([v[1] for v in max_scale]) // config.network.LABEL_STRIDE)) ] max_data_shape, max_label_shape = train_data.infer_shape( max_data_shape, max_label_shape) print 'providing maximum shape', max_data_shape, max_label_shape # infer shape data_shape_dict = dict(train_data.provide_data_single + train_data.provide_label_single) pprint.pprint(data_shape_dict) sym_instance.infer_shape(data_shape_dict) # load and initialize params if config.TRAIN.RESUME: print 'continue training from ', begin_epoch arg_params, aux_params = load_param(prefix, begin_epoch, convert=True) preload_opt_states = load_preload_opt_states(prefix, begin_epoch) else: print pretrained arg_params, aux_params = load_param(pretrained, epoch, convert=True) preload_opt_states = None sym_instance.init_weights(config, arg_params, aux_params) # check parameter shapes sym_instance.check_parameter_shapes(arg_params, aux_params, data_shape_dict) # create solver fixed_param_prefix = config.network.FIXED_PARAMS data_names = [k[0] for k in train_data.provide_data_single] label_names = [k[0] for k in train_data.provide_label_single] mod = MutableModule( sym, data_names=data_names, label_names=label_names, logger=logger, context=ctx, max_data_shapes=[max_data_shape for _ in xrange(NUM_GPUS)], max_label_shapes=[max_label_shape for _ in xrange(NUM_GPUS)], fixed_param_prefix=fixed_param_prefix) # metric imagecrossentropylossmetric = metric.ImageCrossEntropyLossMetric() pixcelAccMetric = metric.PixcelAccMetric() eval_metrics = mx.metric.CompositeEvalMetric() # rpn_eval_metric, rpn_cls_metric, rpn_bbox_metric, eval_metric, cls_metric, bbox_metric for child_metric in [imagecrossentropylossmetric, pixcelAccMetric]: eval_metrics.add(child_metric) # callback batch_end_callback = [ callback.Speedometer(train_data.batch_size, frequent=args.frequent), callback.TensorboardCallback(tensorboard_path, prefix="train/batch") ] epoch_end_callback = mx.callback.module_checkpoint( mod, prefix, period=1, save_optimizer_states=True) shared_tensorboard = batch_end_callback[1] epoch_end_metric_callback = callback.TensorboardCallback( tensorboard_path, shared_tensorboard=shared_tensorboard, prefix="train/epoch") eval_end_callback = callback.TensorboardCallback( tensorboard_path, shared_tensorboard=shared_tensorboard, prefix="val/epoch") lr_callback = callback.LrCallback(tensorboard_path, shared_tensorboard=shared_tensorboard, prefix='train/batch') #decide learning rate base_lr = lr lr_factor = 0.1 lr_epoch = [float(epoch) for epoch in lr_step.split(',')] lr_epoch_diff = [ epoch - begin_epoch for epoch in lr_epoch if epoch > begin_epoch ] lr = base_lr * (lr_factor**(len(lr_epoch) - len(lr_epoch_diff))) lr_iters = [ int(epoch * len(segdb) / input_batch_size) for epoch in lr_epoch_diff ] print 'lr', lr, 'lr_epoch_diff', lr_epoch_diff, 'lr_iters', lr_iters if config.TRAIN.lr_type == "MultiStage": lr_scheduler = LinearWarmupMultiStageScheduler( lr_iters, lr_factor, config.TRAIN.warmup, config.TRAIN.warmup_lr, config.TRAIN.warmup_step, args.frequent, stop_lr=lr * 0.01) elif config.TRAIN.lr_type == "MultiFactor": lr_scheduler = LinearWarmupMultiFactorScheduler( lr_iters, lr_factor, config.TRAIN.warmup, config.TRAIN.warmup_lr, config.TRAIN.warmup_step, args.frequent) optimizer_params = { 'momentum': config.TRAIN.momentum, 'wd': config.TRAIN.wd, 'learning_rate': lr, 'lr_scheduler': lr_scheduler, 'rescale_grad': 1.0, 'clip_gradient': None } optimizer = SGD(**optimizer_params) freeze_layer_pattern = config.TRAIN.FIXED_PARAMS_PATTERN if freeze_layer_pattern.strip(): args_lr_mult = {} re_prog = re.compile(freeze_layer_pattern) fixed_param_names = [ name for name in sym.list_arguments() if re_prog.match(name) ] print "fixed_params_names:" print(fixed_param_names) for name in fixed_param_names: args_lr_mult[name] = config.TRAIN.FIXED_PARAMS_PATTERN_LR_MULT else: args_lr_mult = {} optimizer.set_lr_mult(args_lr_mult) if not isinstance(train_data, PrefetchingIter): train_data = PrefetchingIter(train_data) if not isinstance(val_data, PrefetchingIter): val_data = PrefetchingIter(val_data) if Debug: monitor = mx.monitor.Monitor(1) else: monitor = None initializer = mx.initializer.Xavier(magnitude=1, rnd_type="gaussian") # train mod.fit(train_data, eval_metric=eval_metrics, epoch_end_callback=epoch_end_callback, batch_end_callback=batch_end_callback, kvstore=config.default.kvstore, eval_end_callback=eval_end_callback, epoch_end_metric_callback=epoch_end_metric_callback, optimizer=optimizer, eval_data=val_data, arg_params=arg_params, aux_params=aux_params, begin_epoch=begin_epoch, num_epoch=end_epoch, allow_missing=begin_epoch == 0, allow_extra=True, monitor=monitor, preload_opt_states=preload_opt_states, eval_data_frequency=config.TRAIN.eval_data_frequency, initializer=initializer)