def train_pixelcnn_prior(params, checkpoint_dir, recover=True, force=False): if force and os.path.exists(checkpoint_dir): shutil.rmtree(checkpoint_dir) logger.set_logger_dir(checkpoint_dir) dataset_params = params['dataset'] model_params = params['model'] trainer_params = params['trainer'] train_ds, val_ds, sample_train, sample_val, sample_train_label, \ sample_val_label = get_dataflow( dataset_params['path'], False, dataset_params['train_val_split'], trainer_params['batch_size'], trainer_params['num_parallel']) vqvae_checkpoint_path = trainer_params['vqvae_checkpoint_path'] vqvae_config_path = os.path.join(os.path.split(vqvae_checkpoint_path)[0], 'config.json') model_params['vqvae_model_params'] = vqvae_config_path latent_shape = model_params['latent_shape'] num_labels = model_params['num_labels'] params.to_file(os.path.join(logger.get_logger_dir(), 'config.json')) model = BasePixelCNNPrior.from_params(model_params) trainer = SyncMultiGPUTrainerParameterServer( gpus=trainer_params['num_gpus'], ps_device=None) trainer_config = AutoResumeTrainConfig( always_resume=recover, model=model, dataflow=train_ds, callbacks=[ SequentialSampling(trainer_params['num_examples_to_generate'], latent_shape, num_labels, model, os.path.join(checkpoint_dir, 'images')), Reconstruct(model, sample_train, sample_val, os.path.join(checkpoint_dir, 'images'), sample_train_label, sample_val_label), ModelSaver(max_to_keep=5, checkpoint_dir=checkpoint_dir), InferenceRunner(input=val_ds, infs=ScalarStats(['loss'])), MinSaver(monitor_stat='validation_loss'), CompressResource(os.path.join(checkpoint_dir, 'images'), os.path.join(checkpoint_dir, 'images.zip')), RestoreWeights(vqvae_checkpoint_path), Notification('Training status', 'Complete') ], steps_per_epoch=trainer_params['steps_per_epoch'], max_epoch=trainer_params['max_epochs'] ) launch_train_with_config(trainer_config, trainer)
def run_once(self, opt, sess_init=None, save_dir=None): #### train_datagen = self.get_datagen(opt['train_batch_size'], mode='train') valid_datagen = self.get_datagen(opt['infer_batch_size'], mode='valid') ###### must be called before ModelSaver if save_dir is None: logger.set_logger_dir(self.save_dir) else: logger.set_logger_dir(save_dir) ###### model_flags = opt['model_flags'] model = self.get_model()(**model_flags) ###### callbacks = [ ModelSaver(max_to_keep=1, keep_checkpoint_every_n_hours=None), ] for param_name, param_info in opt['manual_parameters'].items(): model.add_manual_variable(param_name, param_info[0]) callbacks.append( ScheduledHyperParamSetter(param_name, param_info[1])) # multi-GPU inference (with mandatory queue prefetch) infs = [StatCollector()] callbacks.append( DataParallelInferenceRunner(valid_datagen, infs, list(range(nr_gpus)))) if self.model_mode == 'seg_gland': callbacks.append(MaxSaver('valid_dice_obj')) elif self.model_mode == 'seg_nuc': callbacks.append(MaxSaver('valid_dice_np')) else: callbacks.append(MaxSaver('valid_auc')) ###### steps_per_epoch = train_datagen.size() // nr_gpus config = TrainConfig( model=model, callbacks=callbacks, dataflow=train_datagen, steps_per_epoch=steps_per_epoch, max_epoch=opt['nr_epochs'], ) config.session_init = sess_init launch_train_with_config(config, SyncMultiGPUTrainerParameterServer(nr_gpus)) tf.reset_default_graph( ) # remove the entire graph in case of multiple runs return
def train_image_embedding_softmax(params, checkpoint_dir, recover=True, force=False): if force and os.path.exists(checkpoint_dir): shutil.rmtree(checkpoint_dir) logger.set_logger_dir(checkpoint_dir) dataset_params = params['dataset'] model_params = params['model'] trainer_params = params['trainer'] train_ds, val_ds, _, _, _, _ = get_dataflow( dataset_params['path'], False, dataset_params['train_val_split'], trainer_params['batch_size'], trainer_params['num_parallel']) vqvae_checkpoint_path = trainer_params['vqvae_checkpoint_path'] vqvae_config_path = os.path.join(os.path.split(vqvae_checkpoint_path)[0], 'config.json') model_params['vqvae_model_params'] = vqvae_config_path params.to_file(os.path.join(logger.get_logger_dir(), 'config.json')) model = BaseImageEmbedding.from_params(model_params) trainer = SyncMultiGPUTrainerParameterServer( gpus=trainer_params['num_gpus'], ps_device=None) trainer_config = AutoResumeTrainConfig( always_resume=recover, model=model, dataflow=train_ds, callbacks=[ InferenceRunner(input=val_ds, infs=[ ScalarStats('loss'), ClassificationError('correct_prediction', 'val-correct_prediction')]), ModelSaver(max_to_keep=5, checkpoint_dir=checkpoint_dir), MinSaver(monitor_stat='val-correct_prediction'), RestoreWeights(vqvae_checkpoint_path), SendStat('Training status', [ 'loss', 'accuracy', 'validation_loss', 'val-correct_prediction'], after_every=2), Notification('Training status', 'Complete') ], steps_per_epoch=trainer_params['steps_per_epoch'], max_epoch=trainer_params['max_epochs'] ) launch_train_with_config(trainer_config, trainer)
def run_once(self, opt, sess_init=None, save_dir=None): #### train_datagen = self.get_datagen(opt["train_batch_size"], mode="train") valid_datagen = self.get_datagen(opt["infer_batch_size"], mode="valid") ###### must be called before ModelSaver if save_dir is None: logger.set_logger_dir(self.save_dir) else: logger.set_logger_dir(save_dir) ###### model_flags = opt["model_flags"] model = self.get_model()(**model_flags) ###### callbacks = [ # ModelSaver(max_to_keep=20), # TODO dynamic this ModelSaver(max_to_keep=opt["nr_epochs"]), # InjectShell(file='/tools/hover_net/src/config.yml', shell='ipython'), ] for param_name, param_info in opt["manual_parameters"].items(): model.add_manual_variable(param_name, param_info[0]) callbacks.append(ScheduledHyperParamSetter(param_name, param_info[1])) # multi-GPU inference (with mandatory queue prefetch) infs = [StatCollector()] callbacks.append( DataParallelInferenceRunner(valid_datagen, infs, list(range(nr_gpus))) ) callbacks.append(MaxSaver("valid_dice")) ###### steps_per_epoch = train_datagen.size() // nr_gpus config = TrainConfig( model=model, callbacks=callbacks, dataflow=train_datagen, steps_per_epoch=steps_per_epoch, max_epoch=opt["nr_epochs"], ) config.session_init = sess_init launch_train_with_config(config, SyncMultiGPUTrainerParameterServer(nr_gpus)) tf.reset_default_graph() # remove the entire graph in case of multiple runs # TODO: save return
def run(model): instance = Model(model, model.conf.data_format) if not model.conf.is_train: batch = 64 dataset = get_data(model.conf.data_dir, 'val', batch) eval_on_ILSVRC12( instance, get_model_loader(model.conf.logdir + '/' + model.conf.test_step), dataset) else: logger.set_logger_dir(os.path.join(model.conf.logdir)) config = get_config(instance, model.conf) if model.conf.reload_step: config.session_init = get_model_loader(model.conf.logdir + '/' + model.conf.reload_step) trainer = SyncMultiGPUTrainerParameterServer(max(get_nr_gpu(), 1)) launch_train_with_config(config, trainer)
def train_vae(params, checkpoint_dir, recover=True, force=False): if force and os.path.exists(checkpoint_dir): shutil.rmtree(checkpoint_dir) logger.set_logger_dir(checkpoint_dir) dataset_params = params['dataset'] model_params = params['model'] trainer_params = params['trainer'] train_ds, val_ds, sample_train, sample_val, _, _ = \ get_dataflow(dataset_params['path'], dataset_params['binarizer'], dataset_params['train_val_split'], trainer_params['batch_size'], trainer_params['num_parallel']) params.to_file(os.path.join(logger.get_logger_dir(), 'config.json')) latent_dim = model_params['latent_dim'] model = BaseVAE.from_params(model_params) trainer = SyncMultiGPUTrainerParameterServer( gpus=trainer_params['num_gpus'], ps_device=None) trainer_config = AutoResumeTrainConfig( always_resume=recover, model=model, dataflow=train_ds, callbacks=[ Sampling(model, trainer_params['num_examples_to_generate'], latent_dim, os.path.join(checkpoint_dir, 'images')), Reconstruct(model, sample_train, sample_val, os.path.join(checkpoint_dir, 'images')), ModelSaver(max_to_keep=5, checkpoint_dir=checkpoint_dir), InferenceRunner(input=val_ds, infs=ScalarStats(['avg_logpx_z', 'neg_elbo'])), MinSaver(monitor_stat='validation_neg_elbo'), CompressResource(os.path.join(checkpoint_dir, 'images'), os.path.join(checkpoint_dir, 'images.zip')), Notification('Training status', 'Complete') ], steps_per_epoch=trainer_params['steps_per_epoch'], max_epoch=trainer_params['max_epochs'] ) launch_train_with_config(trainer_config, trainer)
def run_once(self, nr_gpus, freeze, sess_init=None, save_dir=None): #### train_datagen = self.get_datagen(mode='train') valid_datagen = self.get_datagen(mode='valid') ###### must be called before ModelSaver if save_dir is None: logger.set_logger_dir(self.save_dir) else: logger.set_logger_dir(save_dir) callbacks = [ ModelSaver(max_to_keep=200), ScheduledHyperParamSetter('learning_rate', self.lr_sched), ] ###### # multi-GPU inference (with mandatory queue prefetch) infs = [StatCollector()] callbacks.append( DataParallelInferenceRunner(valid_datagen, infs, list(range(nr_gpus)))) ###### steps_per_epoch = train_datagen.size() // nr_gpus MODEL_MAKER = Model_NP_XY if self.model_mode == 'np+xy' else Model_NP_DIST config = TrainConfig( model=MODEL_MAKER(freeze), callbacks=callbacks, dataflow=train_datagen, steps_per_epoch=steps_per_epoch, max_epoch=self.nr_epochs, ) config.session_init = sess_init launch_train_with_config(config, SyncMultiGPUTrainerParameterServer(nr_gpus)) tf.reset_default_graph( ) # remove the entire graph in case of multiple runs return
def train_image_embedding_triplet(params, checkpoint_dir, recover=True, force=False): if force and os.path.exists(checkpoint_dir): shutil.rmtree(checkpoint_dir) logger.set_logger_dir(checkpoint_dir) dataset_params = params['dataset'] model_params = params['model'] trainer_params = params['trainer'] train_ds = get_triplet_dataflow( dataset_params['path'], trainer_params['items_per_batch'], trainer_params['images_per_item'], trainer_params['num_parallel']) vqvae_checkpoint_path = trainer_params['vqvae_checkpoint_path'] vqvae_config_path = os.path.join(os.path.split(vqvae_checkpoint_path)[0], 'config.json') model_params['vqvae_model_params'] = vqvae_config_path params.to_file(os.path.join(logger.get_logger_dir(), 'config.json')) model = BaseImageEmbedding.from_params(model_params) trainer = SyncMultiGPUTrainerParameterServer( gpus=trainer_params['num_gpus'], ps_device=None) trainer_config = AutoResumeTrainConfig( always_resume=recover, model=model, dataflow=train_ds, callbacks=[ ModelSaver(max_to_keep=5, checkpoint_dir=checkpoint_dir), MinSaver(monitor_stat='loss'), RestoreWeights(vqvae_checkpoint_path), SendStat('Training status', ['loss', 'pos_triplet_frac'], after_every=2), Notification('Training status', 'Complete') ], steps_per_epoch=trainer_params['steps_per_epoch'], max_epoch=trainer_params['max_epochs'] ) launch_train_with_config(trainer_config, trainer)
help='variants of resnet to use', default='resnet') parser.add_argument('--lp', choices=['2', 'inf']) args = parser.parse_args() if args.gpu: os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu if args.mode == 'se': assert args.depth >= 50 nr_tower = max(get_nr_gpu(), 1) batch_size = TOTAL_BATCH_SIZE // nr_tower model = Model(args.image_size, args.depth, args.data_format, args.mode) if args.eval: batch = 128 # something that can run on one gpu ds = get_data('val', batch, args.image_size) eval_on_ILSVRC12(model, get_model_loader(args.load), ds) else: logger.set_logger_dir(args.checkpoint_dir) config = get_config(model, args.checkpoint_dir, args.image_size, fake=args.fake) if args.load: config.session_init = get_model_loader(args.load) trainer = SyncMultiGPUTrainerParameterServer(max(get_nr_gpu(), 1)) launch_train_with_config(config, trainer)
action='store_true') parser.add_argument('--data_format', help='specify NCHW or NHWC', type=str, default='NCHW') parser.add_argument('-d', '--depth', help='resnet depth', type=int, default=18, choices=[18, 34, 50, 101]) parser.add_argument('--eval', action='store_true') args = parser.parse_args() DEPTH = args.depth if args.gpu: os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu if args.eval: BATCH_SIZE = 128 # something that can run on one gpu ds = get_data('val') eval_on_ILSVRC12(Model(), args.load, ds) sys.exit() logger.set_logger_dir( os.path.join('train_log', 'imagenet-resnet-d' + str(DEPTH))) config = get_config(fake=args.fake, data_format=args.data_format) if args.load: config.session_init = SaverRestore(args.load) SyncMultiGPUTrainerParameterServer(config).train()
def train_child(model_cls, args, log_dir, child_dir, prev_dir): """ """ if not os.path.exists(child_dir): os.mkdir(child_dir) if os.path.basename(child_dir) == "0" and args.use_init_model: init_model_dir = os.path.join(args.data_dir, 'init_model', args.ds_name) if os.path.exists(init_model_dir): # This implies that there exists init_model_dir, and we are in first model # so we do not need to train. Copy the model and mark finished logger.info("Skip first model as this model is fully trained.") cmd = "mkdir -p {cdir} ; cp {pdir}/* {cdir}/ ".format(\ cdir=child_dir, pdir=args.init_model_dir) _ = subprocess.check_output(cmd, shell=True) return # get training params for train-config (model, args, starting_epoch, lr_schedule, ds_train, insrc_train, train_cbs) = get_training_params(model_cls, args) ## Model callbacks # loss weight update ls_cbs_func = getattr(model, 'compute_loss_select_callbacks', None) if callable(ls_cbs_func): train_cbs.extend(ls_cbs_func()) # extra callback for general logging/ update. extra_callbacks = DEFAULT_CALLBACKS() if not args.do_remote_child_inf_runner: extra_callbacks = \ [ecb for ecb in extra_callbacks if not isinstance(ecb, ProgressBar)] logger.info("Extra callbacks are {}".format( [ecb.__class__ for ecb in extra_callbacks])) # Logging for analysis model_str = model.net_info.to_str() logger.info('LayerInfoListString is :\n {}'.format(model_str)) train_callbacks = [ ModelSaver(checkpoint_dir=child_dir, max_to_keep=1, keep_checkpoint_every_n_hours=100), ] + train_cbs if lr_schedule: train_callbacks.append( ScheduledHyperParamSetter('learning_rate', lr_schedule)) logger.info('The updated params for training is \n{}'.format(args)) config = TrainConfig( data=insrc_train, dataflow=ds_train, callbacks=train_callbacks, extra_callbacks=extra_callbacks, model=model, monitors=[JSONWriter(), ScalarPrinter()], #, TFEventWriter()], steps_per_epoch=args.steps_per_epoch, max_epoch=args.max_epoch, starting_epoch=starting_epoch) for dn in [child_dir, prev_dir]: if dn is None: continue ckpt = tf.train.latest_checkpoint(dn) if ckpt: if args.search_cat_based: restore_cls = SaverRestoreSizeRelaxed else: restore_cls = SaverRestore _ignore = [DYNAMIC_WEIGHTS_NAME] _sess_init_load = restore_cls(ckpt, ignore=_ignore) if dn == child_dir: # loading from self keep global step config.session_init = _sess_init_load else: # loading from others. Set global_step to 0 config.session_init = ChainInit([ _sess_init_load, AssignGlobalStep(0), ]) break launch_train_with_config(config, SyncMultiGPUTrainerParameterServer(args.nr_gpu)) return model