def _get_model_desc(self): model_desc = self.trainer.model_desc if not model_desc or 'modules' not in model_desc: if ModelConfig.model_desc_file is not None: desc_file = ModelConfig.model_desc_file desc_file = desc_file.replace("{local_base_path}", self.trainer.local_base_path) if ":" not in desc_file: desc_file = os.path.abspath(desc_file) if ":" in desc_file: local_desc_file = FileOps.join_path( self.trainer.local_output_path, os.path.basename(desc_file)) FileOps.copy_file(desc_file, local_desc_file) desc_file = local_desc_file model_desc = Config(desc_file) logger.info("net_desc:{}".format(model_desc)) elif ModelConfig.model_desc is not None: model_desc = ModelConfig.model_desc elif ModelConfig.models_folder is not None: folder = ModelConfig.models_folder.replace( "{local_base_path}", self.trainer.local_base_path) pattern = FileOps.join_path(folder, "desc_*.json") desc_file = glob.glob(pattern)[0] model_desc = Config(desc_file) else: return None return model_desc
def save_results(self): """Save the results of evolution contains the information of pupulation and elitism.""" _path = FileOps.join_path(self.local_output_path, General.step_name) FileOps.make_dir(_path) arch_file = FileOps.join_path(_path, 'arch.txt') arch_child = FileOps.join_path(_path, 'arch_child.txt') sel_arch_file = FileOps.join_path(_path, 'selected_arch.npy') sel_arch = [] with open(arch_file, 'a') as fw_a, open(arch_child, 'a') as fw_ac: writer_a = csv.writer(fw_a, lineterminator='\n') writer_ac = csv.writer(fw_ac, lineterminator='\n') writer_ac.writerow( ['Population Iteration: ' + str(self.evolution_count + 1)]) for c in range(self.individual_num): writer_ac.writerow( self._log_data(net_info_type='active_only', pop=self.pop[c], value=self.pop[c].fitness)) writer_a.writerow( ['Population Iteration: ' + str(self.evolution_count + 1)]) for c in range(self.elitism_num): writer_a.writerow( self._log_data(net_info_type='active_only', pop=self.elitism[c], value=self.elit_fitness[c])) sel_arch.append(self.elitism[c].gene) sel_arch = np.stack(sel_arch) np.save(sel_arch_file, sel_arch) if self.backup_base_path is not None: FileOps.copy_folder(self.local_output_path, self.backup_base_path)
def _save_best_model(self): """Save best model.""" if zeus.is_torch_backend(): torch.save(self.trainer.model.state_dict(), self.trainer.weights_file) elif zeus.is_tf_backend(): worker_path = self.trainer.get_local_worker_path() model_id = "model_{}".format(self.trainer.worker_id) weights_folder = FileOps.join_path(worker_path, model_id) FileOps.make_dir(weights_folder) checkpoint_file = tf.train.latest_checkpoint(worker_path) ckpt_globs = glob.glob("{}.*".format(checkpoint_file)) for _file in ckpt_globs: dst_file = model_id + os.path.splitext(_file)[-1] FileOps.copy_file(_file, FileOps.join_path(weights_folder, dst_file)) FileOps.copy_file(FileOps.join_path(worker_path, 'checkpoint'), weights_folder) elif zeus.is_ms_backend(): worker_path = self.trainer.get_local_worker_path() save_path = os.path.join( worker_path, "model_{}.ckpt".format(self.trainer.worker_id)) for file in os.listdir(worker_path): if file.startswith("CKP") and file.endswith(".ckpt"): self.weights_file = FileOps.join_path(worker_path, file) os.rename(self.weights_file, save_path)
def _save_checkpoint(self, epoch, best=False): """Save model weights. :param epoch: current epoch :type epoch: int """ save_dir = os.path.join(self.worker_path, str(epoch)) FileOps.make_dir(save_dir) for name in self.model.model_names: if isinstance(name, str): save_filename = '%s_net_%s.pth' % (epoch, name) save_path = FileOps.join_path(save_dir, save_filename) net = getattr(self.model, 'net' + name) best_file = FileOps.join_path(self.worker_path, "model_{}.pth".format(name)) if self.cfg.cuda and torch.cuda.is_available(): # torch.save(net.module.cpu().state_dict(), save_path) torch.save(net.module.state_dict(), save_path) # net.cuda() if best: torch.save(net.module.state_dict(), best_file) else: torch.save(net.cpu().state_dict(), save_path) if best: torch.save(net.cpu().state_dict(), best_file)
def _init_next_rung(self): """Init next rung to search.""" next_rung_id = self.rung_id + 1 if next_rung_id >= self.total_rungs: self.rung_id = self.rung_id + 1 return for i in range(self.config_count): self.all_config_dict[i][next_rung_id] = self.all_config_dict[i][self.rung_id] current_score = [] for i in range(self.config_count): current_score.append((i, self.best_score_dict[self.rung_id][i])) current_score.sort(key=lambda current_score: current_score[1]) for i in range(4): better_id = current_score[self.config_count - 1 - i][0] worse_id = current_score[i][0] better_worker_result_path = FileOps.join_path(self.local_base_path, 'cache', 'pba', str(better_id), 'checkpoint') FileOps.make_dir(better_worker_result_path) worse_worker_result_path = FileOps.join_path(self.local_base_path, 'cache', 'pba', str(worse_id), 'checkpoint') FileOps.make_dir(worse_worker_result_path) shutil.rmtree(worse_worker_result_path) shutil.copytree(better_worker_result_path, worse_worker_result_path) self.all_config_dict[worse_id] = self.all_config_dict[better_id] policy_unchange = self.all_config_dict[worse_id][next_rung_id] policy_changed = self.explore(policy_unchange) self.all_config_dict[worse_id][next_rung_id] = policy_changed for id in range(self.config_count): self.best_score_dict[next_rung_id][id] = -1 * float('inf') tmp_row_data = {'config_id': id, 'rung_id': next_rung_id, 'status': StatusType.WAITTING} self._add_to_board(tmp_row_data) self.rung_id = self.rung_id + 1
def _save_worker_record(cls, record): step_name = record.get('step_name') worker_id = record.get('worker_id') _path = TaskOps().get_local_worker_path(step_name, worker_id) for record_name in ["desc", "performance"]: _file_name = None _file = None record_value = record.get(record_name) if not record_value: continue _file = None try: # for cars/darts save multi-desc if isinstance(record_value, list) and record_name == "desc": for idx, value in enumerate(record_value): _file_name = "desc_{}.json".format(idx) _file = FileOps.join_path(_path, _file_name) with open(_file, "w") as f: json.dump(value, f) else: _file_name = None if record_name == "desc": _file_name = "desc_{}.json".format(worker_id) if record_name == "performance": _file_name = "performance_{}.json".format(worker_id) _file = FileOps.join_path(_path, _file_name) with open(_file, "w") as f: json.dump(record_value, f) except Exception as ex: logging.error( "Failed to save {}, file={}, desc={}, msg={}".format( record_name, _file, record_value, str(ex)))
def load_model(self): """Load model.""" if not self.model_desc and not self.weights_file: saved_folder = self.get_local_worker_path(self.step_name, self.worker_id) self.weights_file = FileOps.join_path( saved_folder, 'model_{}.pth'.format(self.worker_id)) self.model_desc = FileOps.join_path( saved_folder, 'desc_{}.json'.format(self.worker_id)) if 'modules' not in self.model_desc: self.model_desc = ModelConfig.model_desc self.model = ModelZoo.get_model(self.model_desc, self.weights_file)
def dump_model_visual_info(trainer, epoch, model, inputs): """Dump model to tensorboard event files. :param trainer: trainer. :type worker: object that the class was inherited from DistributedWorker. :param model: model. :type model: model. :param inputs: input data. :type inputs: data. """ (_, visual, interval, title, worker_id, output_path) = _get_trainer_info(trainer) if visual is not True: return if epoch % interval != 0: return title = str(worker_id) _path = FileOps.join_path(output_path, title) FileOps.make_dir(_path) try: with SummaryWriter(_path) as writer: writer.add_graph(model, (inputs,)) except Exception as e: logging.error("Failed to dump model visual info, worker id: {}, epoch: {}, error: {}".format( worker_id, epoch, str(e) ))
def load_model(self): """Load model.""" self.saved_folder = self.get_local_worker_path(self.step_name, self.worker_id) if not self.model_desc: self.model_desc = FileOps.join_path(self.saved_folder, 'desc_{}.json'.format(self.worker_id)) if not self.weights_file: if zeus.is_torch_backend(): self.weights_file = FileOps.join_path(self.saved_folder, 'model_{}.pth'.format(self.worker_id)) elif zeus.is_ms_backend(): for file in os.listdir(self.saved_folder): if file.startswith("CKP") and file.endswith(".ckpt"): self.weights_file = FileOps.join_path(self.saved_folder, file) if 'modules' not in self.model_desc: self.model_desc = ModelConfig.model_desc self.model = ModelZoo.get_model(self.model_desc, self.weights_file)
def search(self): """Search an id and hps from hpo.""" sample = self.hpo.propose() if sample is None: return None re_hps = {} sample = copy.deepcopy(sample) sample_id = sample.get('config_id') trans_para = sample.get('configs') rung_id = sample.get('rung_id') all_para = sample.get('all_configs') re_hps['dataset.transforms'] = [{ 'type': 'PBATransformer', 'para_array': trans_para, 'all_para': all_para, 'operation_names': self.operation_names }] checkpoint_path = FileOps.join_path(self.local_base_path, 'worker', 'cache', str(sample_id), 'checkpoint') FileOps.make_dir(checkpoint_path) if os.path.exists(checkpoint_path): re_hps['trainer.checkpoint_path'] = checkpoint_path if 'epoch' in sample: re_hps['trainer.epochs'] = sample.get('epoch') return dict(worker_id=sample_id, encoded_desc=re_hps, rung_id=rung_id)
def before_train(self, logs=None): """Call before_train of the managed callbacks.""" super().before_train(logs) """Be called before the training process.""" hpo_result = FileOps.load_pickle( FileOps.join_path(self.trainer.local_output_path, 'best_config.pickle')) logging.info("loading stage1_hpo_result \n{}".format(hpo_result)) feature_interaction_score = hpo_result['feature_interaction_score'] print('feature_interaction_score:', feature_interaction_score) sorted_pairs = sorted(feature_interaction_score.items(), key=lambda x: abs(x[1]), reverse=True) if ModelConfig.model_desc: fis_ratio = ModelConfig.model_desc["custom"]["fis_ratio"] else: fis_ratio = 1.0 top_k = int(len(feature_interaction_score) * min(1.0, fis_ratio)) self.selected_pairs = list(map(lambda x: x[0], sorted_pairs[:top_k])) # add selected_pairs setattr(ModelConfig.model_desc['custom'], 'selected_pairs', self.selected_pairs)
def _generate_init_model(self): """Generate init model by loading pretrained model. :return: initial model after loading pretrained model :rtype: torch.nn.Module """ model_init = self._new_model_init() chn_mask = self._init_chn_node_mask() if vega.is_torch_backend(): checkpoint = torch.load(self.config.init_model_file + '.pth') model_init.load_state_dict(checkpoint) model = PruneMobileNet(model_init).apply(chn_mask) model.to(self.device) elif vega.is_tf_backend(): model = model_init with tf.compat.v1.Session( config=self.trainer._init_session_config()) as sess: saver = tf.compat.v1.train.import_meta_graph("{}.meta".format( self.config.init_model_file)) saver.restore(sess, self.config.init_model_file) all_weight = tf.compat.v1.get_collection( tf.compat.v1.GraphKeys.VARIABLES) all_weight = [ t for t in all_weight if not t.name.endswith('Momentum:0') ] PruneMobileNet(all_weight).apply(chn_mask) save_file = FileOps.join_path( self.trainer.get_local_worker_path(), 'prune_model') saver.save(sess, save_file) elif vega.is_ms_backend(): parameter_dict = load_checkpoint(self.config.init_model_file) load_param_into_net(model_init, parameter_dict) model = PruneMobileNet(model_init).apply(chn_mask) return model
def after_valid(self, logs=None): """Call after_valid of the managed callbacks.""" self.model = self.trainer.model feature_interaction_score = self.model.get_feature_interaction_score() print('get feature_interaction_score', feature_interaction_score) feature_interaction = [] for feature in feature_interaction_score: if abs(feature_interaction_score[feature]) > 0: feature_interaction.append(feature) print('get feature_interaction', feature_interaction) curr_auc = float(self.trainer.valid_metrics.results['auc']) if curr_auc > self.best_score: best_config = { 'score': curr_auc, 'feature_interaction': feature_interaction } logging.info("BEST CONFIG IS\n{}".format(best_config)) pickle_result_file = FileOps.join_path( self.trainer.local_output_path, 'best_config.pickle') logging.info("Saved to {}".format(pickle_result_file)) FileOps.dump_pickle(best_config, pickle_result_file) self.best_score = curr_auc
def _load_checkpoint(self): """Load checkpoint.""" if zeus.is_torch_backend(): checkpoint_file = FileOps.join_path( self.trainer.get_local_worker_path(), self.trainer.checkpoint_file_name) if os.path.exists(checkpoint_file): try: logging.info("Load checkpoint file, file={}".format( checkpoint_file)) checkpoint = torch.load(checkpoint_file) self.trainer.model.load_state_dict(checkpoint["weight"]) self.trainer.optimizer.load_state_dict( checkpoint["optimizer"]) self.trainer.lr_scheduler.load_state_dict( checkpoint["lr_scheduler"]) if self.trainer._resume_training: epoch = checkpoint["epoch"] self.trainer._start_epoch = checkpoint["epoch"] logging.info( "Resume fully train, change start epoch to {}". format(self.trainer._start_epoch)) except Exception as e: logging.info("Load checkpoint failed {}".format(e)) else: logging.info('Use default model')
def load_records_from_model_folder(cls, model_folder): """Transfer json_file to records.""" if not model_folder or not os.path.exists(model_folder): logging.error( "Failed to load records from model folder, folder={}".format( model_folder)) return [] records = [] pattern = FileOps.join_path(model_folder, "desc_*.json") files = glob.glob(pattern) for _file in files: try: with open(_file) as f: worker_id = _file.split(".")[-2].split("_")[-1] weights_file = os.path.join( os.path.dirname(_file), "model_{}.pth".format(worker_id)) if os.path.exists(weights_file): sample = dict(worker_id=worker_id, desc=json.load(f), weights_file=weights_file) else: sample = dict(worker_id=worker_id, desc=json.load(f)) record = ReportRecord().load_dict(sample) records.append(record) except Exception as ex: logging.info( 'Can not read records from json because {}'.format(ex)) return records
def _backup(self): """Backup result worker folder.""" if self.need_backup is True and self.backup_base_path is not None: backup_worker_path = FileOps.join_path( self.backup_base_path, self.get_worker_subpath()) FileOps.copy_folder( self.get_local_worker_path(self.step_name, self.worker_id), backup_worker_path)
def dump(self): """Dump report to file.""" try: _file = FileOps.join_path(TaskOps().step_path, "reports.csv") FileOps.make_base_dir(_file) data = self.all_records data_dict = {} for step in data: step_data = step.serialize().items() for k, v in step_data: if k in data_dict: data_dict[k].append(v) else: data_dict[k] = [v] data = pd.DataFrame(data_dict) data.to_csv(_file, index=False) _file = os.path.join(TaskOps().step_path, ".reports") _dump_data = [ ReportServer._hist_records, ReportServer.__instances__ ] with open(_file, "wb") as f: pickle.dump(_dump_data, f, protocol=pickle.HIGHEST_PROTOCOL) self.backup_output_path() except Exception: logging.warning(traceback.format_exc())
def _get_current_step_records(self): step_name = General.step_name models_folder = PipeStepConfig.pipe_step.get("models_folder") cur_index = PipelineConfig.steps.index(step_name) if cur_index >= 1 or models_folder: # records = Report().get_step_records(PipelineConfig.steps[cur_index - 1]) if not models_folder: models_folder = FileOps.join_path( TaskOps().local_output_path, PipelineConfig.steps[cur_index - 1]) models_folder = models_folder.replace("{local_base_path}", TaskOps().local_base_path) records = Report().load_records_from_model_folder(models_folder) else: records = self._load_single_model_records() final_records = [] for record in records: if not record.weights_file: logger.error("Model file is not existed, id={}".format( record.worker_id)) else: record.step_name = General.step_name final_records.append(record) logging.debug("Records: {}".format(final_records)) return final_records
def _copy_needed_file(self): if self.config.pareto_front_file is None: raise FileNotFoundError( "Config item paretor_front_file not found in config file.") init_pareto_front_file = self.config.pareto_front_file.replace( "{local_base_path}", self.local_base_path) self.pareto_front_file = FileOps.join_path( self.local_output_path, self.step_name, "pareto_front.csv") FileOps.make_base_dir(self.pareto_front_file) FileOps.copy_file(init_pareto_front_file, self.pareto_front_file) if self.config.random_file is None: raise FileNotFoundError( "Config item random_file not found in config file.") init_random_file = self.config.random_file.replace( "{local_base_path}", self.local_base_path) self.random_file = FileOps.join_path( self.local_output_path, self.step_name, "random.csv") FileOps.copy_file(init_random_file, self.random_file)
def _save_best_model(self): """Save best model.""" if zeus.is_torch_backend(): torch.save(self.trainer.model.state_dict(), self.trainer.weights_file) elif zeus.is_tf_backend(): worker_path = self.trainer.get_local_worker_path() model_id = "model_{}".format(self.trainer.worker_id) weights_folder = FileOps.join_path(worker_path, model_id) FileOps.make_dir(weights_folder) checkpoint_file = tf.train.latest_checkpoint(worker_path) ckpt_globs = glob.glob("{}.*".format(checkpoint_file)) for _file in ckpt_globs: dst_file = model_id + os.path.splitext(_file)[-1] FileOps.copy_file(_file, FileOps.join_path(weights_folder, dst_file)) FileOps.copy_file(FileOps.join_path(worker_path, 'checkpoint'), weights_folder)
def get_pareto_list_size(self): """Get the number of pareto list.""" pareto_list_size = 0 pareto_file_locate = FileOps.join_path(self.local_base_path, "result", "pareto_front.csv") if os.path.exists(pareto_file_locate): pareto_front_df = pd.read_csv(pareto_file_locate) pareto_list_size = pareto_front_df.size return pareto_list_size
def __init__(self, **kwargs): """Construct the Imagenet class.""" Dataset.__init__(self, **kwargs) self.args.data_path = FileOps.download_dataset(self.args.data_path) split = 'train' if self.mode == 'train' else 'val' local_data_path = FileOps.join_path(self.args.data_path, split) ImageFolder.__init__(self, root=local_data_path, transform=Compose(self.transforms.__transform__))
def before_train(self, logs=None): """Be called before the whole train process.""" self.trainer.config.call_metrics_on_train = False self.cfg = self.trainer.config self.worker_id = self.trainer.worker_id self.local_base_path = self.trainer.local_base_path self.local_output_path = self.trainer.local_output_path self.result_path = FileOps.join_path(self.trainer.local_base_path, "result") FileOps.make_dir(self.result_path) self.logger_patch()
def set_trainer(self, trainer): """Set trainer object for current callback.""" self.trainer = trainer self.trainer._train_loop = self.train_process self.cfg = self.trainer.config self._worker_id = self.trainer._worker_id self.worker_path = self.trainer.get_local_worker_path() self.output_path = self.trainer.local_output_path self.best_model_name = "model_best" self.best_model_file = FileOps.join_path( self.worker_path, "model_{}.pth".format(self.trainer.worker_id))
def from_json(cls, data, skip_check=True): """Restore config from a dictionary or a file.""" t_cls = super(ModelConfig, cls).from_json(data, skip_check) if data.get("models_folder") and not data.get('model_desc'): folder = data.models_folder.replace( "{local_base_path}", os.path.join(TaskConfig.local_base_path, TaskConfig.task_id)) pattern = FileOps.join_path(folder, "desc_*.json") desc_file = glob.glob(pattern)[0] t_cls.model_desc = Config(desc_file) return t_cls
def logger_patch(self): """Patch the default logger.""" worker_path = self.trainer.get_local_worker_path() worker_spec_log_file = FileOps.join_path(worker_path, 'current_worker.log') logger = logging.getLogger(__name__) for hdlr in logger.handlers: logger.removeHandler(hdlr) for hdlr in logging.root.handlers: logging.root.removeHandler(hdlr) logger.addHandler(logging.FileHandler(worker_spec_log_file)) logger.addHandler(logging.StreamHandler()) logger.setLevel(logging.INFO) logging.root = logger
def after_train(self, logs=None): """Call after_train of the managed callbacks.""" curr_auc = float(self.trainer.valid_metrics.results['auc']) self.sieve_board = self.sieve_board.append( { 'selected_feature_pairs': self.selected_pairs, 'score': curr_auc }, ignore_index=True) result_file = FileOps.join_path( self.trainer.local_output_path, '{}_result.csv'.format(self.trainer.__worker_id__)) self.sieve_board.to_csv(result_file, sep='\t')
def _get_search_space_list(self): """Get search space list from models folder.""" models_folder = PipeStepConfig.pipe_step.get("models_folder") if not models_folder: self.search_space_list = None return self.search_space_list = [] models_folder = models_folder.replace("{local_base_path}", TaskOps().local_base_path) pattern = FileOps.join_path(models_folder, "*.json") files = glob.glob(pattern) for file in files: with open(file) as f: self.search_space_list.append(json.load(f))
def _output_records(self, step_name, records, desc=True, weights_file=False, performance=False): """Dump records.""" columns = ["worker_id", "performance", "desc"] outputs = [] for record in records: record = record.serialize() _record = {} for key in columns: _record[key] = record[key] outputs.append(deepcopy(_record)) data = pd.DataFrame(outputs) step_path = FileOps.join_path(TaskOps().local_output_path, step_name) FileOps.make_dir(step_path) _file = FileOps.join_path(step_path, "output.csv") try: data.to_csv(_file, index=False) except Exception: logging.error("Failed to save output file, file={}".format(_file)) for record in outputs: worker_id = record["worker_id"] worker_path = TaskOps().get_local_worker_path(step_name, worker_id) outputs_globs = [] if desc: outputs_globs += glob.glob( FileOps.join_path(worker_path, "desc_*.json")) if weights_file: outputs_globs += glob.glob( FileOps.join_path(worker_path, "model_*.pth")) if performance: outputs_globs += glob.glob( FileOps.join_path(worker_path, "performance_*.json")) for _file in outputs_globs: FileOps.copy_file(_file, step_path)
def before_train(self, logs=None): """Call before_train of the managed callbacks.""" super().before_train(logs) """Be called before the training process.""" hpo_result = FileOps.load_pickle(FileOps.join_path( self.trainer.local_output_path, 'best_config.pickle')) logging.info("loading stage1_hpo_result \n{}".format(hpo_result)) self.selected_pairs = hpo_result['feature_interaction'] logging.info('feature_interaction:', self.selected_pairs) # add selected_pairs setattr(ModelConfig.model_desc['custom'], 'selected_pairs', self.selected_pairs)