text
stringlengths
81
112k
Array of IoU for each (non ignored) class def iou(preds, labels, C, EMPTY=1., ignore=None, per_image=False): """ Array of IoU for each (non ignored) class """ if not per_image: preds, labels = (preds,), (labels,) ious = [] for pred, label in zip(preds, labels): iou = [] for i in range(C): if i != ignore: # The ignored label is sometimes among predicted classes (ENet - CityScapes) intersection = ((label == i) & (pred == i)).sum() union = ((label == i) | ((pred == i) & (label != ignore))).sum() if not union: iou.append(EMPTY) else: iou.append(float(intersection) / union) ious.append(iou) ious = map(mean, zip(*ious)) # mean accross images if per_image return 100 * np.array(ious)
Binary Lovasz hinge loss logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty) labels: [B, H, W] Tensor, binary ground truth masks (0 or 1) per_image: compute the loss per image instead of per batch ignore: void class id def lovasz_hinge(logits, labels, per_image=True, ignore=None): """ Binary Lovasz hinge loss logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty) labels: [B, H, W] Tensor, binary ground truth masks (0 or 1) per_image: compute the loss per image instead of per batch ignore: void class id """ if per_image: loss = mean(lovasz_hinge_flat(*flatten_binary_scores(log.unsqueeze(0), lab.unsqueeze(0), ignore)) for log, lab in zip(logits, labels)) else: loss = lovasz_hinge_flat(*flatten_binary_scores(logits, labels, ignore)) return loss
Binary Lovasz hinge loss logits: [P] Variable, logits at each prediction (between -\infty and +\infty) labels: [P] Tensor, binary ground truth labels (0 or 1) ignore: label to ignore def lovasz_hinge_flat(logits, labels): """ Binary Lovasz hinge loss logits: [P] Variable, logits at each prediction (between -\infty and +\infty) labels: [P] Tensor, binary ground truth labels (0 or 1) ignore: label to ignore """ if len(labels) == 0: # only void pixels, the gradients should be 0 return logits.sum() * 0. signs = 2. * labels.float() - 1. errors = (1. - logits * Variable(signs)) errors_sorted, perm = torch.sort(errors, dim=0, descending=True) perm = perm.data gt_sorted = labels[perm] grad = lovasz_grad(gt_sorted) loss = torch.dot(F.elu(errors_sorted)+1, Variable(grad)) #loss = torch.dot(F.relu(errors_sorted), Variable(grad)) return loss
Flattens predictions in the batch (binary case) Remove labels equal to 'ignore' def flatten_binary_scores(scores, labels, ignore=None): """ Flattens predictions in the batch (binary case) Remove labels equal to 'ignore' """ scores = scores.view(-1) labels = labels.view(-1) if ignore is None: return scores, labels valid = (labels != ignore) vscores = scores[valid] vlabels = labels[valid] return vscores, vlabels
Binary Cross entropy loss logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty) labels: [B, H, W] Tensor, binary ground truth masks (0 or 1) ignore: void class id def binary_xloss(logits, labels, ignore=None): """ Binary Cross entropy loss logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty) labels: [B, H, W] Tensor, binary ground truth masks (0 or 1) ignore: void class id """ logits, labels = flatten_binary_scores(logits, labels, ignore) loss = StableBCELoss()(logits, Variable(labels.float())) return loss
Multi-class Lovasz-Softmax loss probas: [B, C, H, W] Variable, class probabilities at each prediction (between 0 and 1) labels: [B, H, W] Tensor, ground truth labels (between 0 and C - 1) only_present: average only on classes present in ground truth per_image: compute the loss per image instead of per batch ignore: void class labels def lovasz_softmax(probas, labels, only_present=False, per_image=False, ignore=None): """ Multi-class Lovasz-Softmax loss probas: [B, C, H, W] Variable, class probabilities at each prediction (between 0 and 1) labels: [B, H, W] Tensor, ground truth labels (between 0 and C - 1) only_present: average only on classes present in ground truth per_image: compute the loss per image instead of per batch ignore: void class labels """ if per_image: loss = mean(lovasz_softmax_flat(*flatten_probas(prob.unsqueeze(0), lab.unsqueeze(0), ignore), only_present=only_present) for prob, lab in zip(probas, labels)) else: loss = lovasz_softmax_flat(*flatten_probas(probas, labels, ignore), only_present=only_present) return loss
Multi-class Lovasz-Softmax loss probas: [P, C] Variable, class probabilities at each prediction (between 0 and 1) labels: [P] Tensor, ground truth labels (between 0 and C - 1) only_present: average only on classes present in ground truth def lovasz_softmax_flat(probas, labels, only_present=False): """ Multi-class Lovasz-Softmax loss probas: [P, C] Variable, class probabilities at each prediction (between 0 and 1) labels: [P] Tensor, ground truth labels (between 0 and C - 1) only_present: average only on classes present in ground truth """ C = probas.size(1) losses = [] for c in range(C): fg = (labels == c).float() # foreground for class c if only_present and fg.sum() == 0: continue errors = (Variable(fg) - probas[:, c]).abs() errors_sorted, perm = torch.sort(errors, 0, descending=True) perm = perm.data fg_sorted = fg[perm] losses.append(torch.dot(errors_sorted, Variable(lovasz_grad(fg_sorted)))) return mean(losses)
Flattens predictions in the batch def flatten_probas(probas, labels, ignore=None): """ Flattens predictions in the batch """ B, C, H, W = probas.size() probas = probas.permute(0, 2, 3, 1).contiguous().view(-1, C) # B * H * W, C = P, C labels = labels.view(-1) if ignore is None: return probas, labels valid = (labels != ignore) vprobas = probas[valid.nonzero().squeeze()] vlabels = labels[valid] return vprobas, vlabels
Cross entropy loss def xloss(logits, labels, ignore=None): """ Cross entropy loss """ return F.cross_entropy(logits, Variable(labels), ignore_index=255)
nanmean compatible with generators. def mean(l, ignore_nan=False, empty=0): """ nanmean compatible with generators. """ l = iter(l) if ignore_nan: l = ifilterfalse(np.isnan, l) try: n = 1 acc = next(l) except StopIteration: if empty == 'raise': raise ValueError('Empty mean') return empty for n, v in enumerate(l, 2): acc += v if n == 1: return acc return acc / n
main loop logic for trial keeper def main_loop(args): '''main loop logic for trial keeper''' if not os.path.exists(LOG_DIR): os.makedirs(LOG_DIR) stdout_file = open(STDOUT_FULL_PATH, 'a+') stderr_file = open(STDERR_FULL_PATH, 'a+') trial_keeper_syslogger = RemoteLogger(args.nnimanager_ip, args.nnimanager_port, 'trial_keeper', StdOutputType.Stdout, args.log_collection) # redirect trial keeper's stdout and stderr to syslog trial_syslogger_stdout = RemoteLogger(args.nnimanager_ip, args.nnimanager_port, 'trial', StdOutputType.Stdout, args.log_collection) sys.stdout = sys.stderr = trial_keeper_syslogger # backward compatibility hdfs_host = None hdfs_output_dir = None if args.hdfs_host: hdfs_host = args.hdfs_host elif args.pai_hdfs_host: hdfs_host = args.pai_hdfs_host if args.hdfs_output_dir: hdfs_output_dir = args.hdfs_output_dir elif args.pai_hdfs_output_dir: hdfs_output_dir = args.pai_hdfs_output_dir if hdfs_host is not None and args.nni_hdfs_exp_dir is not None: try: if args.webhdfs_path: hdfs_client = HdfsClient(hosts='{0}:80'.format(hdfs_host), user_name=args.pai_user_name, webhdfs_path=args.webhdfs_path, timeout=5) else: # backward compatibility hdfs_client = HdfsClient(hosts='{0}:{1}'.format(hdfs_host, '50070'), user_name=args.pai_user_name, timeout=5) except Exception as e: nni_log(LogType.Error, 'Create HDFS client error: ' + str(e)) raise e copyHdfsDirectoryToLocal(args.nni_hdfs_exp_dir, os.getcwd(), hdfs_client) # Notice: We don't appoint env, which means subprocess wil inherit current environment and that is expected behavior log_pipe_stdout = trial_syslogger_stdout.get_pipelog_reader() process = Popen(args.trial_command, shell = True, stdout = log_pipe_stdout, stderr = log_pipe_stdout) nni_log(LogType.Info, 'Trial keeper spawns a subprocess (pid {0}) to run command: {1}'.format(process.pid, shlex.split(args.trial_command))) while True: retCode = process.poll() # child worker process exits and all stdout data is read if retCode is not None and log_pipe_stdout.set_process_exit() and log_pipe_stdout.is_read_completed == True: nni_log(LogType.Info, 'subprocess terminated. Exit code is {}. Quit'.format(retCode)) if hdfs_output_dir is not None: # Copy local directory to hdfs for OpenPAI nni_local_output_dir = os.environ['NNI_OUTPUT_DIR'] try: if copyDirectoryToHdfs(nni_local_output_dir, hdfs_output_dir, hdfs_client): nni_log(LogType.Info, 'copy directory from {0} to {1} success!'.format(nni_local_output_dir, hdfs_output_dir)) else: nni_log(LogType.Info, 'copy directory from {0} to {1} failed!'.format(nni_local_output_dir, hdfs_output_dir)) except Exception as e: nni_log(LogType.Error, 'HDFS copy directory got exception: ' + str(e)) raise e ## Exit as the retCode of subprocess(trial) exit(retCode) break time.sleep(2)
Channel shuffle: [N,C,H,W] -> [N,g,C/g,H,W] -> [N,C/g,g,H,w] -> [N,C,H,W] def forward(self, x): '''Channel shuffle: [N,C,H,W] -> [N,g,C/g,H,W] -> [N,C/g,g,H,w] -> [N,C,H,W]''' N,C,H,W = x.size() g = self.groups return x.view(N,g,C/g,H,W).permute(0,2,1,3,4).contiguous().view(N,C,H,W)
return embedding for a specific file by given file path. def load_embedding(path): ''' return embedding for a specific file by given file path. ''' EMBEDDING_DIM = 300 embedding_dict = {} with open(path, 'r', encoding='utf-8') as file: pairs = [line.strip('\r\n').split() for line in file.readlines()] for pair in pairs: if len(pair) == EMBEDDING_DIM + 1: embedding_dict[pair[0]] = [float(x) for x in pair[1:]] logger.debug('embedding_dict size: %d', len(embedding_dict)) return embedding_dict
Generate json by prediction. def generate_predict_json(position1_result, position2_result, ids, passage_tokens): ''' Generate json by prediction. ''' predict_len = len(position1_result) logger.debug('total prediction num is %s', str(predict_len)) answers = {} for i in range(predict_len): sample_id = ids[i] passage, tokens = passage_tokens[i] kbest = find_best_answer_span( position1_result[i], position2_result[i], len(tokens), 23) _, start, end = kbest[0] answer = passage[tokens[start]['char_begin']:tokens[end]['char_end']] answers[sample_id] = answer logger.debug('generate predict done.') return answers
Generate data def generate_data(path, tokenizer, char_vcb, word_vcb, is_training=False): ''' Generate data ''' global root_path qp_pairs = data.load_from_file(path=path, is_training=is_training) tokenized_sent = 0 # qp_pairs = qp_pairs[:1000]1 for qp_pair in qp_pairs: tokenized_sent += 1 data.tokenize(qp_pair, tokenizer, is_training) for word in qp_pair['question_tokens']: word_vcb.add(word['word']) for char in word['word']: char_vcb.add(char) for word in qp_pair['passage_tokens']: word_vcb.add(word['word']) for char in word['word']: char_vcb.add(char) max_query_length = max(len(x['question_tokens']) for x in qp_pairs) max_passage_length = max(len(x['passage_tokens']) for x in qp_pairs) #min_passage_length = min(len(x['passage_tokens']) for x in qp_pairs) cfg.max_query_length = max_query_length cfg.max_passage_length = max_passage_length return qp_pairs
Calculate the f1 score. def f1_score(prediction, ground_truth): ''' Calculate the f1 score. ''' prediction_tokens = normalize_answer(prediction).split() ground_truth_tokens = normalize_answer(ground_truth).split() common = Counter(prediction_tokens) & Counter(ground_truth_tokens) num_same = sum(common.values()) if num_same == 0: return 0 precision = 1.0 * num_same / len(prediction_tokens) recall = 1.0 * num_same / len(ground_truth_tokens) f1_result = (2 * precision * recall) / (precision + recall) return f1_result
Evaluate function. def _evaluate(dataset, predictions): ''' Evaluate function. ''' f1_result = exact_match = total = 0 count = 0 for article in dataset: for paragraph in article['paragraphs']: for qa_pair in paragraph['qas']: total += 1 if qa_pair['id'] not in predictions: count += 1 continue ground_truths = list(map(lambda x: x['text'], qa_pair['answers'])) prediction = predictions[qa_pair['id']] exact_match += metric_max_over_ground_truths( exact_match_score, prediction, ground_truths) f1_result += metric_max_over_ground_truths( f1_score, prediction, ground_truths) print('total', total, 'exact_match', exact_match, 'unanswer_question ', count) exact_match = 100.0 * exact_match / total f1_result = 100.0 * f1_result / total return {'exact_match': exact_match, 'f1': f1_result}
Evaluate. def evaluate(data_file, pred_file): ''' Evaluate. ''' expected_version = '1.1' with open(data_file) as dataset_file: dataset_json = json.load(dataset_file) if dataset_json['version'] != expected_version: print('Evaluation expects v-' + expected_version + ', but got dataset with v-' + dataset_json['version'], file=sys.stderr) dataset = dataset_json['data'] with open(pred_file) as prediction_file: predictions = json.load(prediction_file) # print(json.dumps(evaluate(dataset, predictions))) result = _evaluate(dataset, predictions) # print('em:', result['exact_match'], 'f1:', result['f1']) return result['exact_match']
Evalutate with predictions/ def evaluate_with_predictions(data_file, predictions): ''' Evalutate with predictions/ ''' expected_version = '1.1' with open(data_file) as dataset_file: dataset_json = json.load(dataset_file) if dataset_json['version'] != expected_version: print('Evaluation expects v-' + expected_version + ', but got dataset with v-' + dataset_json['version'], file=sys.stderr) dataset = dataset_json['data'] result = _evaluate(dataset, predictions) return result['exact_match']
Send command to Training Service. command: CommandType object. data: string payload. def send(command, data): """Send command to Training Service. command: CommandType object. data: string payload. """ global _lock try: _lock.acquire() data = data.encode('utf8') assert len(data) < 1000000, 'Command too long' msg = b'%b%06d%b' % (command.value, len(data), data) logging.getLogger(__name__).debug('Sending command, data: [%s]' % msg) _out_file.write(msg) _out_file.flush() finally: _lock.release()
Receive a command from Training Service. Returns a tuple of command (CommandType) and payload (str) def receive(): """Receive a command from Training Service. Returns a tuple of command (CommandType) and payload (str) """ header = _in_file.read(8) logging.getLogger(__name__).debug('Received command, header: [%s]' % header) if header is None or len(header) < 8: # Pipe EOF encountered logging.getLogger(__name__).debug('Pipe EOF encountered') return None, None length = int(header[2:]) data = _in_file.read(length) command = CommandType(header[:2]) data = data.decode('utf8') logging.getLogger(__name__).debug('Received command, data: [%s]' % data) return command, data
Change json to search space in hyperopt. Parameters ---------- in_x : dict/list/str/int/float The part of json. name : str name could be ROOT, TYPE, VALUE or INDEX. def json2space(in_x, name=ROOT): """ Change json to search space in hyperopt. Parameters ---------- in_x : dict/list/str/int/float The part of json. name : str name could be ROOT, TYPE, VALUE or INDEX. """ out_y = copy.deepcopy(in_x) if isinstance(in_x, dict): if TYPE in in_x.keys(): _type = in_x[TYPE] name = name + '-' + _type _value = json2space(in_x[VALUE], name=name) if _type == 'choice': out_y = eval('hp.hp.'+_type)(name, _value) else: if _type in ['loguniform', 'qloguniform']: _value[:2] = np.log(_value[:2]) out_y = eval('hp.hp.' + _type)(name, *_value) else: out_y = dict() for key in in_x.keys(): out_y[key] = json2space(in_x[key], name+'[%s]' % str(key)) elif isinstance(in_x, list): out_y = list() for i, x_i in enumerate(in_x): out_y.append(json2space(x_i, name+'[%d]' % i)) else: logger.info('in_x is not a dict or a list in json2space fuinction %s', str(in_x)) return out_y
Change json to parameters. def json2parameter(in_x, parameter, name=ROOT): """ Change json to parameters. """ out_y = copy.deepcopy(in_x) if isinstance(in_x, dict): if TYPE in in_x.keys(): _type = in_x[TYPE] name = name + '-' + _type if _type == 'choice': _index = parameter[name] out_y = { INDEX: _index, VALUE: json2parameter(in_x[VALUE][_index], parameter, name=name+'[%d]' % _index) } else: out_y = parameter[name] else: out_y = dict() for key in in_x.keys(): out_y[key] = json2parameter( in_x[key], parameter, name + '[%s]' % str(key)) elif isinstance(in_x, list): out_y = list() for i, x_i in enumerate(in_x): out_y.append(json2parameter(x_i, parameter, name + '[%d]' % i)) else: logger.info('in_x is not a dict or a list in json2space fuinction %s', str(in_x)) return out_y
change parameters in NNI format to parameters in hyperopt format(This function also support nested dict.). For example, receive parameters like: {'dropout_rate': 0.8, 'conv_size': 3, 'hidden_size': 512} Will change to format in hyperopt, like: {'dropout_rate': 0.8, 'conv_size': {'_index': 1, '_value': 3}, 'hidden_size': {'_index': 1, '_value': 512}} def _add_index(in_x, parameter): """ change parameters in NNI format to parameters in hyperopt format(This function also support nested dict.). For example, receive parameters like: {'dropout_rate': 0.8, 'conv_size': 3, 'hidden_size': 512} Will change to format in hyperopt, like: {'dropout_rate': 0.8, 'conv_size': {'_index': 1, '_value': 3}, 'hidden_size': {'_index': 1, '_value': 512}} """ if TYPE not in in_x: # if at the top level out_y = dict() for key, value in parameter.items(): out_y[key] = _add_index(in_x[key], value) return out_y elif isinstance(in_x, dict): value_type = in_x[TYPE] value_format = in_x[VALUE] if value_type == "choice": choice_name = parameter[0] if isinstance(parameter, list) else parameter for pos, item in enumerate(value_format): # here value_format is a list if isinstance(item, list): # this format is ["choice_key", format_dict] choice_key = item[0] choice_value_format = item[1] if choice_key == choice_name: return {INDEX: pos, VALUE: [choice_name, _add_index(choice_value_format, parameter[1])]} elif choice_name == item: return {INDEX: pos, VALUE: item} else: return parameter
Delete index infromation from params def _split_index(params): """ Delete index infromation from params """ if isinstance(params, list): return [params[0], _split_index(params[1])] elif isinstance(params, dict): if INDEX in params.keys(): return _split_index(params[VALUE]) result = dict() for key in params: result[key] = _split_index(params[key]) return result else: return params
Parameters ---------- algorithm_name : str algorithm_name includes "tpe", "random_search" and anneal" def _choose_tuner(self, algorithm_name): """ Parameters ---------- algorithm_name : str algorithm_name includes "tpe", "random_search" and anneal" """ if algorithm_name == 'tpe': return hp.tpe.suggest if algorithm_name == 'random_search': return hp.rand.suggest if algorithm_name == 'anneal': return hp.anneal.suggest raise RuntimeError('Not support tuner algorithm in hyperopt.')
Update search space definition in tuner by search_space in parameters. Will called when first setup experiemnt or update search space in WebUI. Parameters ---------- search_space : dict def update_search_space(self, search_space): """ Update search space definition in tuner by search_space in parameters. Will called when first setup experiemnt or update search space in WebUI. Parameters ---------- search_space : dict """ self.json = search_space search_space_instance = json2space(self.json) rstate = np.random.RandomState() trials = hp.Trials() domain = hp.Domain(None, search_space_instance, pass_expr_memo_ctrl=None) algorithm = self._choose_tuner(self.algorithm_name) self.rval = hp.FMinIter(algorithm, domain, trials, max_evals=-1, rstate=rstate, verbose=0) self.rval.catch_eval_exceptions = False
Returns a set of trial (hyper-)parameters, as a serializable object. Parameters ---------- parameter_id : int Returns ------- params : dict def generate_parameters(self, parameter_id): """ Returns a set of trial (hyper-)parameters, as a serializable object. Parameters ---------- parameter_id : int Returns ------- params : dict """ total_params = self.get_suggestion(random_search=False) # avoid generating same parameter with concurrent trials because hyperopt doesn't support parallel mode if total_params in self.total_data.values(): # but it can cause deplicate parameter rarely total_params = self.get_suggestion(random_search=True) self.total_data[parameter_id] = total_params params = _split_index(total_params) return params
Record an observation of the objective function Parameters ---------- parameter_id : int parameters : dict value : dict/float if value is dict, it should have "default" key. value is final metrics of the trial. def receive_trial_result(self, parameter_id, parameters, value): """ Record an observation of the objective function Parameters ---------- parameter_id : int parameters : dict value : dict/float if value is dict, it should have "default" key. value is final metrics of the trial. """ reward = extract_scalar_reward(value) # restore the paramsters contains '_index' if parameter_id not in self.total_data: raise RuntimeError('Received parameter_id not in total_data.') params = self.total_data[parameter_id] if self.optimize_mode is OptimizeMode.Maximize: reward = -reward rval = self.rval domain = rval.domain trials = rval.trials new_id = len(trials) rval_specs = [None] rval_results = [domain.new_result()] rval_miscs = [dict(tid=new_id, cmd=domain.cmd, workdir=domain.workdir)] vals = params idxs = dict() out_y = dict() json2vals(self.json, vals, out_y) vals = out_y for key in domain.params: if key in [VALUE, INDEX]: continue if key not in vals or vals[key] is None or vals[key] == []: idxs[key] = vals[key] = [] else: idxs[key] = [new_id] vals[key] = [vals[key]] self.miscs_update_idxs_vals(rval_miscs, idxs, vals, idxs_map={new_id: new_id}, assert_all_vals_used=False) trial = trials.new_trial_docs([new_id], rval_specs, rval_results, rval_miscs)[0] trial['result'] = {'loss': reward, 'status': 'ok'} trial['state'] = hp.JOB_STATE_DONE trials.insert_trial_docs([trial]) trials.refresh()
Unpack the idxs-vals format into the list of dictionaries that is `misc`. Parameters ---------- idxs_map : dict idxs_map is a dictionary of id->id mappings so that the misc['idxs'] can contain different numbers than the idxs argument. def miscs_update_idxs_vals(self, miscs, idxs, vals, assert_all_vals_used=True, idxs_map=None): """ Unpack the idxs-vals format into the list of dictionaries that is `misc`. Parameters ---------- idxs_map : dict idxs_map is a dictionary of id->id mappings so that the misc['idxs'] can contain different numbers than the idxs argument. """ if idxs_map is None: idxs_map = {} assert set(idxs.keys()) == set(vals.keys()) misc_by_id = {m['tid']: m for m in miscs} for m in miscs: m['idxs'] = dict([(key, []) for key in idxs]) m['vals'] = dict([(key, []) for key in idxs]) for key in idxs: assert len(idxs[key]) == len(vals[key]) for tid, val in zip(idxs[key], vals[key]): tid = idxs_map.get(tid, tid) if assert_all_vals_used or tid in misc_by_id: misc_by_id[tid]['idxs'][key] = [tid] misc_by_id[tid]['vals'][key] = [val]
get suggestion from hyperopt Parameters ---------- random_search : bool flag to indicate random search or not (default: {False}) Returns ---------- total_params : dict parameter suggestion def get_suggestion(self, random_search=False): """get suggestion from hyperopt Parameters ---------- random_search : bool flag to indicate random search or not (default: {False}) Returns ---------- total_params : dict parameter suggestion """ rval = self.rval trials = rval.trials algorithm = rval.algo new_ids = rval.trials.new_trial_ids(1) rval.trials.refresh() random_state = rval.rstate.randint(2**31-1) if random_search: new_trials = hp.rand.suggest(new_ids, rval.domain, trials, random_state) else: new_trials = algorithm(new_ids, rval.domain, trials, random_state) rval.trials.refresh() vals = new_trials[0]['misc']['vals'] parameter = dict() for key in vals: try: parameter[key] = vals[key][0].item() except (KeyError, IndexError): parameter[key] = None # remove '_index' from json2parameter and save params-id total_params = json2parameter(self.json, parameter) return total_params
Import additional data for tuning Parameters ---------- data: a list of dictionarys, each of which has at least two keys, 'parameter' and 'value' def import_data(self, data): """Import additional data for tuning Parameters ---------- data: a list of dictionarys, each of which has at least two keys, 'parameter' and 'value' """ _completed_num = 0 for trial_info in data: logger.info("Importing data, current processing progress %s / %s" %(_completed_num, len(data))) _completed_num += 1 if self.algorithm_name == 'random_search': return assert "parameter" in trial_info _params = trial_info["parameter"] assert "value" in trial_info _value = trial_info['value'] if not _value: logger.info("Useless trial data, value is %s, skip this trial data." %_value) continue self.supplement_data_num += 1 _parameter_id = '_'.join(["ImportData", str(self.supplement_data_num)]) self.total_data[_parameter_id] = _add_index(in_x=self.json, parameter=_params) self.receive_trial_result(parameter_id=_parameter_id, parameters=_params, value=_value) logger.info("Successfully import data to TPE/Anneal tuner.")
"Lowest Mu" acquisition function def next_hyperparameter_lowest_mu(fun_prediction, fun_prediction_args, x_bounds, x_types, minimize_starting_points, minimize_constraints_fun=None): ''' "Lowest Mu" acquisition function ''' best_x = None best_acquisition_value = None x_bounds_minmax = [[i[0], i[-1]] for i in x_bounds] x_bounds_minmax = numpy.array(x_bounds_minmax) for starting_point in numpy.array(minimize_starting_points): res = minimize(fun=_lowest_mu, x0=starting_point.reshape(1, -1), bounds=x_bounds_minmax, method="L-BFGS-B", args=(fun_prediction, fun_prediction_args, \ x_bounds, x_types, minimize_constraints_fun)) if (best_acquisition_value is None) or (res.fun < best_acquisition_value): res.x = numpy.ndarray.tolist(res.x) res.x = lib_data.match_val_type(res.x, x_bounds, x_types) if (minimize_constraints_fun is None) or (minimize_constraints_fun(res.x) is True): best_acquisition_value = res.fun best_x = res.x outputs = None if best_x is not None: mu, sigma = fun_prediction(best_x, *fun_prediction_args) outputs = {'hyperparameter': best_x, 'expected_mu': mu, 'expected_sigma': sigma, 'acquisition_func': "lm"} return outputs
Calculate the lowest mu def _lowest_mu(x, fun_prediction, fun_prediction_args, x_bounds, x_types, minimize_constraints_fun): ''' Calculate the lowest mu ''' # This is only for step-wise optimization x = lib_data.match_val_type(x, x_bounds, x_types) mu = sys.maxsize if (minimize_constraints_fun is None) or (minimize_constraints_fun(x) is True): mu, _ = fun_prediction(x, *fun_prediction_args) return mu
Build char embedding network for the QA model. def build_char_states(self, char_embed, is_training, reuse, char_ids, char_lengths): """Build char embedding network for the QA model.""" max_char_length = self.cfg.max_char_length inputs = dropout(tf.nn.embedding_lookup(char_embed, char_ids), self.cfg.dropout, is_training) inputs = tf.reshape( inputs, shape=[max_char_length, -1, self.cfg.char_embed_dim]) char_lengths = tf.reshape(char_lengths, shape=[-1]) with tf.variable_scope('char_encoding', reuse=reuse): cell_fw = XGRUCell(hidden_dim=self.cfg.char_embed_dim) cell_bw = XGRUCell(hidden_dim=self.cfg.char_embed_dim) _, (left_right, right_left) = tf.nn.bidirectional_dynamic_rnn( cell_fw=cell_fw, cell_bw=cell_bw, sequence_length=char_lengths, inputs=inputs, time_major=True, dtype=tf.float32 ) left_right = tf.reshape(left_right, shape=[-1, self.cfg.char_embed_dim]) right_left = tf.reshape(right_left, shape=[-1, self.cfg.char_embed_dim]) states = tf.concat([left_right, right_left], axis=1) out_shape = tf.shape(char_ids)[1:3] out_shape = tf.concat([out_shape, tf.constant( value=[self.cfg.char_embed_dim * 2], dtype=tf.int32)], axis=0) return tf.reshape(states, shape=out_shape)
data: a dict received from nni_manager, which contains: - 'parameter_id': id of the trial - 'value': metric value reported by nni.report_final_result() - 'type': report type, support {'FINAL', 'PERIODICAL'} def handle_report_metric_data(self, data): """ data: a dict received from nni_manager, which contains: - 'parameter_id': id of the trial - 'value': metric value reported by nni.report_final_result() - 'type': report type, support {'FINAL', 'PERIODICAL'} """ if data['type'] == 'FINAL': self._handle_final_metric_data(data) elif data['type'] == 'PERIODICAL': if self.assessor is not None: self._handle_intermediate_metric_data(data) else: pass else: raise ValueError('Data type not supported: {}'.format(data['type']))
data: it has three keys: trial_job_id, event, hyper_params - trial_job_id: the id generated by training service - event: the job's state - hyper_params: the hyperparameters generated and returned by tuner def handle_trial_end(self, data): """ data: it has three keys: trial_job_id, event, hyper_params - trial_job_id: the id generated by training service - event: the job's state - hyper_params: the hyperparameters generated and returned by tuner """ trial_job_id = data['trial_job_id'] _ended_trials.add(trial_job_id) if trial_job_id in _trial_history: _trial_history.pop(trial_job_id) if self.assessor is not None: self.assessor.trial_end(trial_job_id, data['event'] == 'SUCCEEDED') if self.tuner is not None: self.tuner.trial_end(json_tricks.loads(data['hyper_params'])['parameter_id'], data['event'] == 'SUCCEEDED')
Call tuner to process final results def _handle_final_metric_data(self, data): """Call tuner to process final results """ id_ = data['parameter_id'] value = data['value'] if id_ in _customized_parameter_ids: self.tuner.receive_customized_trial_result(id_, _trial_params[id_], value) else: self.tuner.receive_trial_result(id_, _trial_params[id_], value)
Call assessor to process intermediate results def _handle_intermediate_metric_data(self, data): """Call assessor to process intermediate results """ if data['type'] != 'PERIODICAL': return if self.assessor is None: return trial_job_id = data['trial_job_id'] if trial_job_id in _ended_trials: return history = _trial_history[trial_job_id] history[data['sequence']] = data['value'] ordered_history = _sort_history(history) if len(ordered_history) < data['sequence']: # no user-visible update since last time return try: result = self.assessor.assess_trial(trial_job_id, ordered_history) except Exception as e: _logger.exception('Assessor error') if isinstance(result, bool): result = AssessResult.Good if result else AssessResult.Bad elif not isinstance(result, AssessResult): msg = 'Result of Assessor.assess_trial must be an object of AssessResult, not %s' raise RuntimeError(msg % type(result)) if result is AssessResult.Bad: _logger.debug('BAD, kill %s', trial_job_id) send(CommandType.KillTrialJob, json_tricks.dumps(trial_job_id)) # notify tuner _logger.debug('env var: NNI_INCLUDE_INTERMEDIATE_RESULTS: [%s]', dispatcher_env_vars.NNI_INCLUDE_INTERMEDIATE_RESULTS) if dispatcher_env_vars.NNI_INCLUDE_INTERMEDIATE_RESULTS == 'true': self._earlystop_notify_tuner(data) else: _logger.debug('GOOD')
Send last intermediate result as final result to tuner in case the trial is early stopped. def _earlystop_notify_tuner(self, data): """Send last intermediate result as final result to tuner in case the trial is early stopped. """ _logger.debug('Early stop notify tuner data: [%s]', data) data['type'] = 'FINAL' if multi_thread_enabled(): self._handle_final_metric_data(data) else: self.enqueue_command(CommandType.ReportMetricData, data)
parse reveive msgs to global variable def parse_rev_args(receive_msg): """ parse reveive msgs to global variable """ global trainloader global testloader global net # Loading Data logger.debug("Preparing data..") (x_train, y_train), (x_test, y_test) = fashion_mnist.load_data() y_train = to_categorical(y_train, 10) y_test = to_categorical(y_test, 10) x_train = x_train.reshape(x_train.shape+(1,)).astype("float32") x_test = x_test.reshape(x_test.shape+(1,)).astype("float32") x_train /= 255.0 x_test /= 255.0 trainloader = (x_train, y_train) testloader = (x_test, y_test) # Model logger.debug("Building model..") net = build_graph_from_json(receive_msg) # parallel model try: available_devices = os.environ["CUDA_VISIBLE_DEVICES"] gpus = len(available_devices.split(",")) if gpus > 1: net = multi_gpu_model(net, gpus) except KeyError: logger.debug("parallel model not support in this config settings") if args.optimizer == "SGD": optimizer = SGD(lr=args.learning_rate, momentum=0.9, decay=args.weight_decay) if args.optimizer == "Adadelta": optimizer = Adadelta(lr=args.learning_rate, decay=args.weight_decay) if args.optimizer == "Adagrad": optimizer = Adagrad(lr=args.learning_rate, decay=args.weight_decay) if args.optimizer == "Adam": optimizer = Adam(lr=args.learning_rate, decay=args.weight_decay) if args.optimizer == "Adamax": optimizer = Adamax(lr=args.learning_rate, decay=args.weight_decay) if args.optimizer == "RMSprop": optimizer = RMSprop(lr=args.learning_rate, decay=args.weight_decay) # Compile the model net.compile( loss="categorical_crossentropy", optimizer=optimizer, metrics=["accuracy"] ) return 0
train and eval the model def train_eval(): """ train and eval the model """ global trainloader global testloader global net (x_train, y_train) = trainloader (x_test, y_test) = testloader # train procedure net.fit( x=x_train, y=y_train, batch_size=args.batch_size, validation_data=(x_test, y_test), epochs=args.epochs, shuffle=True, callbacks=[ SendMetrics(), EarlyStopping(min_delta=0.001, patience=10), TensorBoard(log_dir=TENSORBOARD_DIR), ], ) # trial report final acc to tuner _, acc = net.evaluate(x_test, y_test) logger.debug("Final result is: %.3f", acc) nni.report_final_result(acc)
Run on end of each epoch def on_epoch_end(self, epoch, logs=None): """ Run on end of each epoch """ if logs is None: logs = dict() logger.debug(logs) nni.report_intermediate_result(logs["val_acc"])
Create a full id for a specific bracket's hyperparameter configuration Parameters ---------- brackets_id: int brackets id brackets_curr_decay: brackets curr decay increased_id: int increased id Returns ------- int params id def create_bracket_parameter_id(brackets_id, brackets_curr_decay, increased_id=-1): """Create a full id for a specific bracket's hyperparameter configuration Parameters ---------- brackets_id: int brackets id brackets_curr_decay: brackets curr decay increased_id: int increased id Returns ------- int params id """ if increased_id == -1: increased_id = str(create_parameter_id()) params_id = '_'.join([str(brackets_id), str(brackets_curr_decay), increased_id]) return params_id
Randomly generate values for hyperparameters from hyperparameter space i.e., x. Parameters ---------- ss_spec: hyperparameter space random_state: random operator to generate random values Returns ------- Parameter: Parameters in this experiment def json2paramater(ss_spec, random_state): """Randomly generate values for hyperparameters from hyperparameter space i.e., x. Parameters ---------- ss_spec: hyperparameter space random_state: random operator to generate random values Returns ------- Parameter: Parameters in this experiment """ if isinstance(ss_spec, dict): if '_type' in ss_spec.keys(): _type = ss_spec['_type'] _value = ss_spec['_value'] if _type == 'choice': _index = random_state.randint(len(_value)) chosen_params = json2paramater(ss_spec['_value'][_index], random_state) else: chosen_params = eval('parameter_expressions.' + # pylint: disable=eval-used _type)(*(_value + [random_state])) else: chosen_params = dict() for key in ss_spec.keys(): chosen_params[key] = json2paramater(ss_spec[key], random_state) elif isinstance(ss_spec, list): chosen_params = list() for _, subspec in enumerate(ss_spec): chosen_params.append(json2paramater(subspec, random_state)) else: chosen_params = copy.deepcopy(ss_spec) return chosen_params
return the values of n and r for the next round def get_n_r(self): """return the values of n and r for the next round""" return math.floor(self.n / self.eta**self.i + _epsilon), math.floor(self.r * self.eta**self.i + _epsilon)
i means the ith round. Increase i by 1 def increase_i(self): """i means the ith round. Increase i by 1""" self.i += 1 if self.i > self.bracket_id: self.no_more_trial = True
update trial's latest result with its sequence number, e.g., epoch number or batch number Parameters ---------- i: int the ith round parameter_id: int the id of the trial/parameter seq: int sequence number, e.g., epoch number or batch number value: int latest result with sequence number seq Returns ------- None def set_config_perf(self, i, parameter_id, seq, value): """update trial's latest result with its sequence number, e.g., epoch number or batch number Parameters ---------- i: int the ith round parameter_id: int the id of the trial/parameter seq: int sequence number, e.g., epoch number or batch number value: int latest result with sequence number seq Returns ------- None """ if parameter_id in self.configs_perf[i]: if self.configs_perf[i][parameter_id][0] < seq: self.configs_perf[i][parameter_id] = [seq, value] else: self.configs_perf[i][parameter_id] = [seq, value]
If the trial is finished and the corresponding round (i.e., i) has all its trials finished, it will choose the top k trials for the next round (i.e., i+1) Parameters ---------- i: int the ith round def inform_trial_end(self, i): """If the trial is finished and the corresponding round (i.e., i) has all its trials finished, it will choose the top k trials for the next round (i.e., i+1) Parameters ---------- i: int the ith round """ global _KEY # pylint: disable=global-statement self.num_finished_configs[i] += 1 _logger.debug('bracket id: %d, round: %d %d, finished: %d, all: %d', self.bracket_id, self.i, i, self.num_finished_configs[i], self.num_configs_to_run[i]) if self.num_finished_configs[i] >= self.num_configs_to_run[i] \ and self.no_more_trial is False: # choose candidate configs from finished configs to run in the next round assert self.i == i + 1 this_round_perf = self.configs_perf[i] if self.optimize_mode is OptimizeMode.Maximize: sorted_perf = sorted(this_round_perf.items(), key=lambda kv: kv[1][1], reverse=True) # reverse else: sorted_perf = sorted(this_round_perf.items(), key=lambda kv: kv[1][1]) _logger.debug('bracket %s next round %s, sorted hyper configs: %s', self.bracket_id, self.i, sorted_perf) next_n, next_r = self.get_n_r() _logger.debug('bracket %s next round %s, next_n=%d, next_r=%d', self.bracket_id, self.i, next_n, next_r) hyper_configs = dict() for k in range(next_n): params_id = sorted_perf[k][0] params = self.hyper_configs[i][params_id] params[_KEY] = next_r # modify r # generate new id increased_id = params_id.split('_')[-1] new_id = create_bracket_parameter_id(self.bracket_id, self.i, increased_id) hyper_configs[new_id] = params self._record_hyper_configs(hyper_configs) return [[key, value] for key, value in hyper_configs.items()] return None
Randomly generate num hyperparameter configurations from search space Parameters ---------- num: int the number of hyperparameter configurations Returns ------- list a list of hyperparameter configurations. Format: [[key1, value1], [key2, value2], ...] def get_hyperparameter_configurations(self, num, r, searchspace_json, random_state): # pylint: disable=invalid-name """Randomly generate num hyperparameter configurations from search space Parameters ---------- num: int the number of hyperparameter configurations Returns ------- list a list of hyperparameter configurations. Format: [[key1, value1], [key2, value2], ...] """ global _KEY # pylint: disable=global-statement assert self.i == 0 hyperparameter_configs = dict() for _ in range(num): params_id = create_bracket_parameter_id(self.bracket_id, self.i) params = json2paramater(searchspace_json, random_state) params[_KEY] = r hyperparameter_configs[params_id] = params self._record_hyper_configs(hyperparameter_configs) return [[key, value] for key, value in hyperparameter_configs.items()]
after generating one round of hyperconfigs, this function records the generated hyperconfigs, creates a dict to record the performance when those hyperconifgs are running, set the number of finished configs in this round to be 0, and increase the round number. Parameters ---------- hyper_configs: list the generated hyperconfigs def _record_hyper_configs(self, hyper_configs): """after generating one round of hyperconfigs, this function records the generated hyperconfigs, creates a dict to record the performance when those hyperconifgs are running, set the number of finished configs in this round to be 0, and increase the round number. Parameters ---------- hyper_configs: list the generated hyperconfigs """ self.hyper_configs.append(hyper_configs) self.configs_perf.append(dict()) self.num_finished_configs.append(0) self.num_configs_to_run.append(len(hyper_configs)) self.increase_i()
get one trial job, i.e., one hyperparameter configuration. def _request_one_trial_job(self): """get one trial job, i.e., one hyperparameter configuration.""" if not self.generated_hyper_configs: if self.curr_s < 0: self.curr_s = self.s_max _logger.debug('create a new bracket, self.curr_s=%d', self.curr_s) self.brackets[self.curr_s] = Bracket(self.curr_s, self.s_max, self.eta, self.R, self.optimize_mode) next_n, next_r = self.brackets[self.curr_s].get_n_r() _logger.debug('new bracket, next_n=%d, next_r=%d', next_n, next_r) assert self.searchspace_json is not None and self.random_state is not None generated_hyper_configs = self.brackets[self.curr_s].get_hyperparameter_configurations(next_n, next_r, self.searchspace_json, self.random_state) self.generated_hyper_configs = generated_hyper_configs.copy() self.curr_s -= 1 assert self.generated_hyper_configs params = self.generated_hyper_configs.pop() ret = { 'parameter_id': params[0], 'parameter_source': 'algorithm', 'parameters': params[1] } send(CommandType.NewTrialJob, json_tricks.dumps(ret))
data: JSON object, which is search space Parameters ---------- data: int number of trial jobs def handle_update_search_space(self, data): """data: JSON object, which is search space Parameters ---------- data: int number of trial jobs """ self.searchspace_json = data self.random_state = np.random.RandomState()
Parameters ---------- data: dict() it has three keys: trial_job_id, event, hyper_params trial_job_id: the id generated by training service event: the job's state hyper_params: the hyperparameters (a string) generated and returned by tuner def handle_trial_end(self, data): """ Parameters ---------- data: dict() it has three keys: trial_job_id, event, hyper_params trial_job_id: the id generated by training service event: the job's state hyper_params: the hyperparameters (a string) generated and returned by tuner """ hyper_params = json_tricks.loads(data['hyper_params']) bracket_id, i, _ = hyper_params['parameter_id'].split('_') hyper_configs = self.brackets[int(bracket_id)].inform_trial_end(int(i)) if hyper_configs is not None: _logger.debug('bracket %s next round %s, hyper_configs: %s', bracket_id, i, hyper_configs) self.generated_hyper_configs = self.generated_hyper_configs + hyper_configs for _ in range(self.credit): if not self.generated_hyper_configs: break params = self.generated_hyper_configs.pop() ret = { 'parameter_id': params[0], 'parameter_source': 'algorithm', 'parameters': params[1] } send(CommandType.NewTrialJob, json_tricks.dumps(ret)) self.credit -= 1
Parameters ---------- data: it is an object which has keys 'parameter_id', 'value', 'trial_job_id', 'type', 'sequence'. Raises ------ ValueError Data type not supported def handle_report_metric_data(self, data): """ Parameters ---------- data: it is an object which has keys 'parameter_id', 'value', 'trial_job_id', 'type', 'sequence'. Raises ------ ValueError Data type not supported """ value = extract_scalar_reward(data['value']) bracket_id, i, _ = data['parameter_id'].split('_') bracket_id = int(bracket_id) if data['type'] == 'FINAL': # sys.maxsize indicates this value is from FINAL metric data, because data['sequence'] from FINAL metric # and PERIODICAL metric are independent, thus, not comparable. self.brackets[bracket_id].set_config_perf(int(i), data['parameter_id'], sys.maxsize, value) self.completed_hyper_configs.append(data) elif data['type'] == 'PERIODICAL': self.brackets[bracket_id].set_config_perf(int(i), data['parameter_id'], data['sequence'], value) else: raise ValueError('Data type not supported: {}'.format(data['type']))
Returns a set of trial graph config, as a serializable object. parameter_id : int def generate_parameters(self, parameter_id): """Returns a set of trial graph config, as a serializable object. parameter_id : int """ if len(self.population) <= 0: logger.debug("the len of poplution lower than zero.") raise Exception('The population is empty') pos = -1 for i in range(len(self.population)): if self.population[i].result == None: pos = i break if pos != -1: indiv = copy.deepcopy(self.population[pos]) self.population.pop(pos) temp = json.loads(graph_dumps(indiv.config)) else: random.shuffle(self.population) if self.population[0].result < self.population[1].result: self.population[0] = self.population[1] indiv = copy.deepcopy(self.population[0]) self.population.pop(1) indiv.mutation() graph = indiv.config temp = json.loads(graph_dumps(graph)) logger.debug('generate_parameter return value is:') logger.debug(temp) return temp
Record an observation of the objective function parameter_id : int parameters : dict of parameters value: final metrics of the trial, including reward def receive_trial_result(self, parameter_id, parameters, value): ''' Record an observation of the objective function parameter_id : int parameters : dict of parameters value: final metrics of the trial, including reward ''' reward = extract_scalar_reward(value) if self.optimize_mode is OptimizeMode.Minimize: reward = -reward logger.debug('receive trial result is:\n') logger.debug(str(parameters)) logger.debug(str(reward)) indiv = Individual(graph_loads(parameters), result=reward) self.population.append(indiv) return
Generates a CNN. Args: model_len: An integer. Number of convolutional layers. model_width: An integer. Number of filters for the convolutional layers. Returns: An instance of the class Graph. Represents the neural architecture graph of the generated model. def generate(self, model_len=None, model_width=None): """Generates a CNN. Args: model_len: An integer. Number of convolutional layers. model_width: An integer. Number of filters for the convolutional layers. Returns: An instance of the class Graph. Represents the neural architecture graph of the generated model. """ if model_len is None: model_len = Constant.MODEL_LEN if model_width is None: model_width = Constant.MODEL_WIDTH pooling_len = int(model_len / 4) graph = Graph(self.input_shape, False) temp_input_channel = self.input_shape[-1] output_node_id = 0 stride = 1 for i in range(model_len): output_node_id = graph.add_layer(StubReLU(), output_node_id) output_node_id = graph.add_layer( self.batch_norm(graph.node_list[output_node_id].shape[-1]), output_node_id ) output_node_id = graph.add_layer( self.conv(temp_input_channel, model_width, kernel_size=3, stride=stride), output_node_id, ) temp_input_channel = model_width if pooling_len == 0 or ((i + 1) % pooling_len == 0 and i != model_len - 1): output_node_id = graph.add_layer(self.pooling(), output_node_id) output_node_id = graph.add_layer(self.global_avg_pooling(), output_node_id) output_node_id = graph.add_layer( self.dropout(Constant.CONV_DROPOUT_RATE), output_node_id ) output_node_id = graph.add_layer( StubDense(graph.node_list[output_node_id].shape[0], model_width), output_node_id, ) output_node_id = graph.add_layer(StubReLU(), output_node_id) graph.add_layer(StubDense(model_width, self.n_output_node), output_node_id) return graph
Generates a Multi-Layer Perceptron. Args: model_len: An integer. Number of hidden layers. model_width: An integer or a list of integers of length `model_len`. If it is a list, it represents the number of nodes in each hidden layer. If it is an integer, all hidden layers have nodes equal to this value. Returns: An instance of the class Graph. Represents the neural architecture graph of the generated model. def generate(self, model_len=None, model_width=None): """Generates a Multi-Layer Perceptron. Args: model_len: An integer. Number of hidden layers. model_width: An integer or a list of integers of length `model_len`. If it is a list, it represents the number of nodes in each hidden layer. If it is an integer, all hidden layers have nodes equal to this value. Returns: An instance of the class Graph. Represents the neural architecture graph of the generated model. """ if model_len is None: model_len = Constant.MODEL_LEN if model_width is None: model_width = Constant.MODEL_WIDTH if isinstance(model_width, list) and not len(model_width) == model_len: raise ValueError("The length of 'model_width' does not match 'model_len'") elif isinstance(model_width, int): model_width = [model_width] * model_len graph = Graph(self.input_shape, False) output_node_id = 0 n_nodes_prev_layer = self.input_shape[0] for width in model_width: output_node_id = graph.add_layer( StubDense(n_nodes_prev_layer, width), output_node_id ) output_node_id = graph.add_layer( StubDropout1d(Constant.MLP_DROPOUT_RATE), output_node_id ) output_node_id = graph.add_layer(StubReLU(), output_node_id) n_nodes_prev_layer = width graph.add_layer(StubDense(n_nodes_prev_layer, self.n_output_node), output_node_id) return graph
Generate search space from Python source code. Return a serializable search space object. code_dir: directory path of source files (str) def generate_search_space(code_dir): """Generate search space from Python source code. Return a serializable search space object. code_dir: directory path of source files (str) """ search_space = {} if code_dir.endswith(slash): code_dir = code_dir[:-1] for subdir, _, files in os.walk(code_dir): # generate module name from path if subdir == code_dir: package = '' else: assert subdir.startswith(code_dir + slash), subdir prefix_len = len(code_dir) + 1 package = subdir[prefix_len:].replace(slash, '.') + '.' for file_name in files: if file_name.endswith('.py'): path = os.path.join(subdir, file_name) module = package + file_name[:-3] search_space.update(_generate_file_search_space(path, module)) return search_space
Expand annotations in user code. Return dst_dir if annotation detected; return src_dir if not. src_dir: directory path of user code (str) dst_dir: directory to place generated files (str) def expand_annotations(src_dir, dst_dir): """Expand annotations in user code. Return dst_dir if annotation detected; return src_dir if not. src_dir: directory path of user code (str) dst_dir: directory to place generated files (str) """ if src_dir[-1] == slash: src_dir = src_dir[:-1] if dst_dir[-1] == slash: dst_dir = dst_dir[:-1] annotated = False for src_subdir, dirs, files in os.walk(src_dir): assert src_subdir.startswith(src_dir) dst_subdir = src_subdir.replace(src_dir, dst_dir, 1) os.makedirs(dst_subdir, exist_ok=True) for file_name in files: src_path = os.path.join(src_subdir, file_name) dst_path = os.path.join(dst_subdir, file_name) if file_name.endswith('.py'): annotated |= _expand_file_annotations(src_path, dst_path) else: shutil.copyfile(src_path, dst_path) for dir_name in dirs: os.makedirs(os.path.join(dst_subdir, dir_name), exist_ok=True) return dst_dir if annotated else src_dir
Generate send stdout url def gen_send_stdout_url(ip, port): '''Generate send stdout url''' return '{0}:{1}{2}{3}/{4}/{5}'.format(BASE_URL.format(ip), port, API_ROOT_URL, STDOUT_API, NNI_EXP_ID, NNI_TRIAL_JOB_ID)
Generate send error url def gen_send_version_url(ip, port): '''Generate send error url''' return '{0}:{1}{2}{3}/{4}/{5}'.format(BASE_URL.format(ip), port, API_ROOT_URL, VERSION_API, NNI_EXP_ID, NNI_TRIAL_JOB_ID)
validate if a digit is valid def validate_digit(value, start, end): '''validate if a digit is valid''' if not str(value).isdigit() or int(value) < start or int(value) > end: raise ValueError('%s must be a digit from %s to %s' % (value, start, end))
validate if the dispatcher of the experiment supports importing data def validate_dispatcher(args): '''validate if the dispatcher of the experiment supports importing data''' nni_config = Config(get_config_filename(args)).get_config('experimentConfig') if nni_config.get('tuner') and nni_config['tuner'].get('builtinTunerName'): dispatcher_name = nni_config['tuner']['builtinTunerName'] elif nni_config.get('advisor') and nni_config['advisor'].get('builtinAdvisorName'): dispatcher_name = nni_config['advisor']['builtinAdvisorName'] else: # otherwise it should be a customized one return if dispatcher_name not in TUNERS_SUPPORTING_IMPORT_DATA: if dispatcher_name in TUNERS_NO_NEED_TO_IMPORT_DATA: print_warning("There is no need to import data for %s" % dispatcher_name) exit(0) else: print_error("%s does not support importing addtional data" % dispatcher_name) exit(1)
load search space content def load_search_space(path): '''load search space content''' content = json.dumps(get_json_content(path)) if not content: raise ValueError('searchSpace file should not be empty') return content
call restful server to update experiment profile def update_experiment_profile(args, key, value): '''call restful server to update experiment profile''' nni_config = Config(get_config_filename(args)) rest_port = nni_config.get_config('restServerPort') running, _ = check_rest_server_quick(rest_port) if running: response = rest_get(experiment_url(rest_port), REST_TIME_OUT) if response and check_response(response): experiment_profile = json.loads(response.text) experiment_profile['params'][key] = value response = rest_put(experiment_url(rest_port)+get_query_type(key), json.dumps(experiment_profile), REST_TIME_OUT) if response and check_response(response): return response else: print_error('Restful server is not running...') return None
import additional data to the experiment def import_data(args): '''import additional data to the experiment''' validate_file(args.filename) validate_dispatcher(args) content = load_search_space(args.filename) args.port = get_experiment_port(args) if args.port is not None: if import_data_to_restful_server(args, content): pass else: print_error('Import data failed!')
call restful server to import data to the experiment def import_data_to_restful_server(args, content): '''call restful server to import data to the experiment''' nni_config = Config(get_config_filename(args)) rest_port = nni_config.get_config('restServerPort') running, _ = check_rest_server_quick(rest_port) if running: response = rest_post(import_data_url(rest_port), content, REST_TIME_OUT) if response and check_response(response): return response else: print_error('Restful server is not running...') return None
check key type def setType(key, type): '''check key type''' return And(type, error=SCHEMA_TYPE_ERROR % (key, type.__name__))
check choice def setChoice(key, *args): '''check choice''' return And(lambda n: n in args, error=SCHEMA_RANGE_ERROR % (key, str(args)))
check number range def setNumberRange(key, keyType, start, end): '''check number range''' return And( And(keyType, error=SCHEMA_TYPE_ERROR % (key, keyType.__name__)), And(lambda n: start <= n <= end, error=SCHEMA_RANGE_ERROR % (key, '(%s,%s)' % (start, end))), )
keras dropout layer. def keras_dropout(layer, rate): '''keras dropout layer. ''' from keras import layers input_dim = len(layer.input.shape) if input_dim == 2: return layers.SpatialDropout1D(rate) elif input_dim == 3: return layers.SpatialDropout2D(rate) elif input_dim == 4: return layers.SpatialDropout3D(rate) else: return layers.Dropout(rate)
real keras layer. def to_real_keras_layer(layer): ''' real keras layer. ''' from keras import layers if is_layer(layer, "Dense"): return layers.Dense(layer.units, input_shape=(layer.input_units,)) if is_layer(layer, "Conv"): return layers.Conv2D( layer.filters, layer.kernel_size, input_shape=layer.input.shape, padding="same", ) # padding if is_layer(layer, "Pooling"): return layers.MaxPool2D(2) if is_layer(layer, "BatchNormalization"): return layers.BatchNormalization(input_shape=layer.input.shape) if is_layer(layer, "Concatenate"): return layers.Concatenate() if is_layer(layer, "Add"): return layers.Add() if is_layer(layer, "Dropout"): return keras_dropout(layer, layer.rate) if is_layer(layer, "ReLU"): return layers.Activation("relu") if is_layer(layer, "Softmax"): return layers.Activation("softmax") if is_layer(layer, "Flatten"): return layers.Flatten() if is_layer(layer, "GlobalAveragePooling"): return layers.GlobalAveragePooling2D()
judge the layer type. Returns: boolean -- True or False def is_layer(layer, layer_type): '''judge the layer type. Returns: boolean -- True or False ''' if layer_type == "Input": return isinstance(layer, StubInput) elif layer_type == "Conv": return isinstance(layer, StubConv) elif layer_type == "Dense": return isinstance(layer, (StubDense,)) elif layer_type == "BatchNormalization": return isinstance(layer, (StubBatchNormalization,)) elif layer_type == "Concatenate": return isinstance(layer, (StubConcatenate,)) elif layer_type == "Add": return isinstance(layer, (StubAdd,)) elif layer_type == "Pooling": return isinstance(layer, StubPooling) elif layer_type == "Dropout": return isinstance(layer, (StubDropout,)) elif layer_type == "Softmax": return isinstance(layer, (StubSoftmax,)) elif layer_type == "ReLU": return isinstance(layer, (StubReLU,)) elif layer_type == "Flatten": return isinstance(layer, (StubFlatten,)) elif layer_type == "GlobalAveragePooling": return isinstance(layer, StubGlobalPooling)
get layer description. def layer_description_extractor(layer, node_to_id): '''get layer description. ''' layer_input = layer.input layer_output = layer.output if layer_input is not None: if isinstance(layer_input, Iterable): layer_input = list(map(lambda x: node_to_id[x], layer_input)) else: layer_input = node_to_id[layer_input] if layer_output is not None: layer_output = node_to_id[layer_output] if isinstance(layer, StubConv): return ( type(layer).__name__, layer_input, layer_output, layer.input_channel, layer.filters, layer.kernel_size, layer.stride, layer.padding, ) elif isinstance(layer, (StubDense,)): return [ type(layer).__name__, layer_input, layer_output, layer.input_units, layer.units, ] elif isinstance(layer, (StubBatchNormalization,)): return (type(layer).__name__, layer_input, layer_output, layer.num_features) elif isinstance(layer, (StubDropout,)): return (type(layer).__name__, layer_input, layer_output, layer.rate) elif isinstance(layer, StubPooling): return ( type(layer).__name__, layer_input, layer_output, layer.kernel_size, layer.stride, layer.padding, ) else: return (type(layer).__name__, layer_input, layer_output)
build layer from description. def layer_description_builder(layer_information, id_to_node): '''build layer from description. ''' # pylint: disable=W0123 layer_type = layer_information[0] layer_input_ids = layer_information[1] if isinstance(layer_input_ids, Iterable): layer_input = list(map(lambda x: id_to_node[x], layer_input_ids)) else: layer_input = id_to_node[layer_input_ids] layer_output = id_to_node[layer_information[2]] if layer_type.startswith("StubConv"): input_channel = layer_information[3] filters = layer_information[4] kernel_size = layer_information[5] stride = layer_information[6] return eval(layer_type)( input_channel, filters, kernel_size, stride, layer_input, layer_output ) elif layer_type.startswith("StubDense"): input_units = layer_information[3] units = layer_information[4] return eval(layer_type)(input_units, units, layer_input, layer_output) elif layer_type.startswith("StubBatchNormalization"): num_features = layer_information[3] return eval(layer_type)(num_features, layer_input, layer_output) elif layer_type.startswith("StubDropout"): rate = layer_information[3] return eval(layer_type)(rate, layer_input, layer_output) elif layer_type.startswith("StubPooling"): kernel_size = layer_information[3] stride = layer_information[4] padding = layer_information[5] return eval(layer_type)(kernel_size, stride, padding, layer_input, layer_output) else: return eval(layer_type)(layer_input, layer_output)
get layer width. def layer_width(layer): '''get layer width. ''' if is_layer(layer, "Dense"): return layer.units if is_layer(layer, "Conv"): return layer.filters raise TypeError("The layer should be either Dense or Conv layer.")
Define parameters. def define_params(self): ''' Define parameters. ''' input_dim = self.input_dim hidden_dim = self.hidden_dim prefix = self.name self.w_matrix = tf.Variable(tf.random_normal([input_dim, 3 * hidden_dim], stddev=0.1), name='/'.join([prefix, 'W'])) self.U = tf.Variable(tf.random_normal([hidden_dim, 3 * hidden_dim], stddev=0.1), name='/'.join([prefix, 'U'])) self.bias = tf.Variable(tf.random_normal([1, 3 * hidden_dim], stddev=0.1), name='/'.join([prefix, 'b'])) return self
Build the GRU cell. def build(self, x, h, mask=None): ''' Build the GRU cell. ''' xw = tf.split(tf.matmul(x, self.w_matrix) + self.bias, 3, 1) hu = tf.split(tf.matmul(h, self.U), 3, 1) r = tf.sigmoid(xw[0] + hu[0]) z = tf.sigmoid(xw[1] + hu[1]) h1 = tf.tanh(xw[2] + r * hu[2]) next_h = h1 * (1 - z) + h * z if mask is not None: next_h = next_h * mask + h * (1 - mask) return next_h
Build GRU sequence. def build_sequence(self, xs, masks, init, is_left_to_right): ''' Build GRU sequence. ''' states = [] last = init if is_left_to_right: for i, xs_i in enumerate(xs): h = self.build(xs_i, last, masks[i]) states.append(h) last = h else: for i in range(len(xs) - 1, -1, -1): h = self.build(xs[i], last, masks[i]) states.insert(0, h) last = h return states
conv2d returns a 2d convolution layer with full stride. def conv2d(x_input, w_matrix): """conv2d returns a 2d convolution layer with full stride.""" return tf.nn.conv2d(x_input, w_matrix, strides=[1, 1, 1, 1], padding='SAME')
max_pool downsamples a feature map by 2X. def max_pool(x_input, pool_size): """max_pool downsamples a feature map by 2X.""" return tf.nn.max_pool(x_input, ksize=[1, pool_size, pool_size, 1], strides=[1, pool_size, pool_size, 1], padding='SAME')
Main function, build mnist network, run and send result to NNI. def main(params): ''' Main function, build mnist network, run and send result to NNI. ''' # Import data mnist = download_mnist_retry(params['data_dir']) print('Mnist download data done.') logger.debug('Mnist download data done.') # Create the model # Build the graph for the deep net mnist_network = MnistNetwork(channel_1_num=params['channel_1_num'], channel_2_num=params['channel_2_num'], pool_size=params['pool_size']) mnist_network.build_network() logger.debug('Mnist build network done.') # Write log graph_location = tempfile.mkdtemp() logger.debug('Saving graph to: %s', graph_location) train_writer = tf.summary.FileWriter(graph_location) train_writer.add_graph(tf.get_default_graph()) test_acc = 0.0 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) batch_num = nni.choice(50, 250, 500, name='batch_num') for i in range(batch_num): batch = mnist.train.next_batch(batch_num) dropout_rate = nni.choice(1, 5, name='dropout_rate') mnist_network.train_step.run(feed_dict={mnist_network.images: batch[0], mnist_network.labels: batch[1], mnist_network.keep_prob: dropout_rate} ) if i % 100 == 0: test_acc = mnist_network.accuracy.eval( feed_dict={mnist_network.images: mnist.test.images, mnist_network.labels: mnist.test.labels, mnist_network.keep_prob: 1.0}) nni.report_intermediate_result(test_acc) logger.debug('test accuracy %g', test_acc) logger.debug('Pipe send intermediate result done.') test_acc = mnist_network.accuracy.eval( feed_dict={mnist_network.images: mnist.test.images, mnist_network.labels: mnist.test.labels, mnist_network.keep_prob: 1.0}) nni.report_final_result(test_acc) logger.debug('Final result is %g', test_acc) logger.debug('Send final result done.')
Build the whole neural network for the QA model. def build_net(self, is_training): """Build the whole neural network for the QA model.""" cfg = self.cfg with tf.device('/cpu:0'): word_embed = tf.get_variable( name='word_embed', initializer=self.embed, dtype=tf.float32, trainable=False) char_embed = tf.get_variable(name='char_embed', shape=[cfg.char_vcb_size, cfg.char_embed_dim], dtype=tf.float32) # [query_length, batch_size] self.query_word = tf.placeholder(dtype=tf.int32, shape=[None, None], name='query_word') self.query_mask = tf.placeholder(dtype=tf.float32, shape=[None, None], name='query_mask') # [batch_size] self.query_lengths = tf.placeholder( dtype=tf.int32, shape=[None], name='query_lengths') # [passage_length, batch_size] self.passage_word = tf.placeholder( dtype=tf.int32, shape=[None, None], name='passage_word') self.passage_mask = tf.placeholder( dtype=tf.float32, shape=[None, None], name='passage_mask') # [batch_size] self.passage_lengths = tf.placeholder( dtype=tf.int32, shape=[None], name='passage_lengths') if is_training: self.answer_begin = tf.placeholder( dtype=tf.int32, shape=[None], name='answer_begin') self.answer_end = tf.placeholder( dtype=tf.int32, shape=[None], name='answer_end') self.query_char_ids = tf.placeholder(dtype=tf.int32, shape=[ self.cfg.max_char_length, None, None], name='query_char_ids') # sequence_length, batch_size self.query_char_lengths = tf.placeholder( dtype=tf.int32, shape=[None, None], name='query_char_lengths') self.passage_char_ids = tf.placeholder(dtype=tf.int32, shape=[ self.cfg.max_char_length, None, None], name='passage_char_ids') # sequence_length, batch_size self.passage_char_lengths = tf.placeholder(dtype=tf.int32, shape=[None, None], name='passage_char_lengths') query_char_states = self.build_char_states(char_embed=char_embed, is_training=is_training, reuse=False, char_ids=self.query_char_ids, char_lengths=self.query_char_lengths) passage_char_states = self.build_char_states(char_embed=char_embed, is_training=is_training, reuse=True, char_ids=self.passage_char_ids, char_lengths=self.passage_char_lengths) with tf.variable_scope("encoding") as scope: query_states = tf.concat([tf.nn.embedding_lookup( word_embed, self.query_word), query_char_states], axis=2) scope.reuse_variables() passage_states = tf.concat([tf.nn.embedding_lookup( word_embed, self.passage_word), passage_char_states], axis=2) passage_states = tf.transpose(passage_states, perm=[1, 0, 2]) query_states = tf.transpose(query_states, perm=[1, 0, 2]) self.passage_states = passage_states self.query_states = query_states output, output2 = graph_to_network(passage_states, query_states, self.passage_lengths, self.query_lengths, self.graph, self.cfg.dropout, is_training, num_heads=cfg.num_heads, rnn_units=cfg.rnn_units) passage_att_mask = self.passage_mask batch_size_x = tf.shape(self.query_lengths) answer_h = tf.zeros( tf.concat([batch_size_x, tf.constant([cfg.ptr_dim], dtype=tf.int32)], axis=0)) answer_context = tf.reduce_mean(output2, axis=1) query_init_w = tf.get_variable( 'query_init_w', shape=[output2.get_shape().as_list()[-1], cfg.ptr_dim]) self.query_init = query_init_w answer_context = tf.matmul(answer_context, query_init_w) output = tf.transpose(output, perm=[1, 0, 2]) with tf.variable_scope('answer_ptr_layer'): ptr_att = DotAttention('ptr', hidden_dim=cfg.ptr_dim, is_vanilla=self.cfg.att_is_vanilla, is_identity_transform=self.cfg.att_is_id, need_padding=self.cfg.att_need_padding) answer_pre_compute = ptr_att.get_pre_compute(output) ptr_gru = XGRUCell(hidden_dim=cfg.ptr_dim) begin_prob, begin_logits = ptr_att.get_prob(output, answer_context, passage_att_mask, answer_pre_compute, True) att_state = ptr_att.get_att(output, begin_prob) (_, answer_h) = ptr_gru.call(inputs=att_state, state=answer_h) answer_context = answer_h end_prob, end_logits = ptr_att.get_prob(output, answer_context, passage_att_mask, answer_pre_compute, True) self.begin_prob = tf.transpose(begin_prob, perm=[1, 0]) self.end_prob = tf.transpose(end_prob, perm=[1, 0]) begin_logits = tf.transpose(begin_logits, perm=[1, 0]) end_logits = tf.transpose(end_logits, perm=[1, 0]) if is_training: def label_smoothing(inputs, masks, epsilon=0.1): """Modify target for label smoothing.""" epsilon = cfg.labelsmoothing num_of_channel = tf.shape(inputs)[-1] # number of channels inputs = tf.cast(inputs, tf.float32) return (((1 - epsilon) * inputs) + (epsilon / tf.cast(num_of_channel, tf.float32))) * masks cost1 = tf.reduce_mean( tf.losses.softmax_cross_entropy(label_smoothing( tf.one_hot(self.answer_begin, depth=tf.shape(self.passage_word)[0]), tf.transpose(self.passage_mask, perm=[1, 0])), begin_logits)) cost2 = tf.reduce_mean( tf.losses.softmax_cross_entropy( label_smoothing(tf.one_hot(self.answer_end, depth=tf.shape(self.passage_word)[0]), tf.transpose(self.passage_mask, perm=[1, 0])), end_logits)) reg_ws = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES) l2_loss = tf.reduce_sum(reg_ws) loss = cost1 + cost2 + l2_loss self.loss = loss optimizer = tf.train.AdamOptimizer(learning_rate=cfg.learning_rate) self.train_op = optimizer.minimize(self.loss) return tf.stack([self.begin_prob, self.end_prob])
call check_output command to read content from a file def check_output_command(file_path, head=None, tail=None): '''call check_output command to read content from a file''' if os.path.exists(file_path): if sys.platform == 'win32': cmds = ['powershell.exe', 'type', file_path] if head: cmds += ['|', 'select', '-first', str(head)] elif tail: cmds += ['|', 'select', '-last', str(tail)] return check_output(cmds, shell=True).decode('utf-8') else: cmds = ['cat', file_path] if head: cmds = ['head', '-' + str(head), file_path] elif tail: cmds = ['tail', '-' + str(tail), file_path] return check_output(cmds, shell=False).decode('utf-8') else: print_error('{0} does not exist!'.format(file_path)) exit(1)
kill command def kill_command(pid): '''kill command''' if sys.platform == 'win32': process = psutil.Process(pid=pid) process.send_signal(signal.CTRL_BREAK_EVENT) else: cmds = ['kill', str(pid)] call(cmds)
install python package from pip def install_package_command(package_name): '''install python package from pip''' #TODO refactor python logic if sys.platform == "win32": cmds = 'python -m pip install --user {0}'.format(package_name) else: cmds = 'python3 -m pip install --user {0}'.format(package_name) call(cmds, shell=True)
install requirements.txt def install_requirements_command(requirements_path): '''install requirements.txt''' cmds = 'cd ' + requirements_path + ' && {0} -m pip install --user -r requirements.txt' #TODO refactor python logic if sys.platform == "win32": cmds = cmds.format('python') else: cmds = cmds.format('python3') call(cmds, shell=True)
Get parameters from command line def get_params(): ''' Get parameters from command line ''' parser = argparse.ArgumentParser() parser.add_argument("--data_dir", type=str, default='/tmp/tensorflow/mnist/input_data', help="data directory") parser.add_argument("--dropout_rate", type=float, default=0.5, help="dropout rate") parser.add_argument("--channel_1_num", type=int, default=32) parser.add_argument("--channel_2_num", type=int, default=64) parser.add_argument("--conv_size", type=int, default=5) parser.add_argument("--pool_size", type=int, default=2) parser.add_argument("--hidden_size", type=int, default=1024) parser.add_argument("--learning_rate", type=float, default=1e-4) parser.add_argument("--batch_num", type=int, default=2700) parser.add_argument("--batch_size", type=int, default=32) args, _ = parser.parse_known_args() return args
Building network for mnist def build_network(self): ''' Building network for mnist ''' # Reshape to use within a convolutional neural net. # Last dimension is for "features" - there is only one here, since images are # grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc. with tf.name_scope('reshape'): try: input_dim = int(math.sqrt(self.x_dim)) except: print( 'input dim cannot be sqrt and reshape. input dim: ' + str(self.x_dim)) logger.debug( 'input dim cannot be sqrt and reshape. input dim: %s', str(self.x_dim)) raise x_image = tf.reshape(self.images, [-1, input_dim, input_dim, 1]) # First convolutional layer - maps one grayscale image to 32 feature maps. with tf.name_scope('conv1'): w_conv1 = weight_variable( [self.conv_size, self.conv_size, 1, self.channel_1_num]) b_conv1 = bias_variable([self.channel_1_num]) h_conv1 = tf.nn.relu(conv2d(x_image, w_conv1) + b_conv1) # Pooling layer - downsamples by 2X. with tf.name_scope('pool1'): h_pool1 = max_pool(h_conv1, self.pool_size) # Second convolutional layer -- maps 32 feature maps to 64. with tf.name_scope('conv2'): w_conv2 = weight_variable([self.conv_size, self.conv_size, self.channel_1_num, self.channel_2_num]) b_conv2 = bias_variable([self.channel_2_num]) h_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2) + b_conv2) # Second pooling layer. with tf.name_scope('pool2'): h_pool2 = max_pool(h_conv2, self.pool_size) # Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image # is down to 7x7x64 feature maps -- maps this to 1024 features. last_dim = int(input_dim / (self.pool_size * self.pool_size)) with tf.name_scope('fc1'): w_fc1 = weight_variable( [last_dim * last_dim * self.channel_2_num, self.hidden_size]) b_fc1 = bias_variable([self.hidden_size]) h_pool2_flat = tf.reshape( h_pool2, [-1, last_dim * last_dim * self.channel_2_num]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, w_fc1) + b_fc1) # Dropout - controls the complexity of the model, prevents co-adaptation of features. with tf.name_scope('dropout'): h_fc1_drop = tf.nn.dropout(h_fc1, self.keep_prob) # Map the 1024 features to 10 classes, one for each digit with tf.name_scope('fc2'): w_fc2 = weight_variable([self.hidden_size, self.y_dim]) b_fc2 = bias_variable([self.y_dim]) y_conv = tf.matmul(h_fc1_drop, w_fc2) + b_fc2 with tf.name_scope('loss'): cross_entropy = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=self.labels, logits=y_conv)) with tf.name_scope('adam_optimizer'): self.train_step = tf.train.AdamOptimizer( self.learning_rate).minimize(cross_entropy) with tf.name_scope('accuracy'): correct_prediction = tf.equal( tf.argmax(y_conv, 1), tf.argmax(self.labels, 1)) self.accuracy = tf.reduce_mean( tf.cast(correct_prediction, tf.float32))
get the startTime and endTime of an experiment def get_experiment_time(port): '''get the startTime and endTime of an experiment''' response = rest_get(experiment_url(port), REST_TIME_OUT) if response and check_response(response): content = convert_time_stamp_to_date(json.loads(response.text)) return content.get('startTime'), content.get('endTime') return None, None
get the status of an experiment def get_experiment_status(port): '''get the status of an experiment''' result, response = check_rest_server_quick(port) if result: return json.loads(response.text).get('status') return None
Update the experiment status in config file def update_experiment(): '''Update the experiment status in config file''' experiment_config = Experiments() experiment_dict = experiment_config.get_all_experiments() if not experiment_dict: return None for key in experiment_dict.keys(): if isinstance(experiment_dict[key], dict): if experiment_dict[key].get('status') != 'STOPPED': nni_config = Config(experiment_dict[key]['fileName']) rest_pid = nni_config.get_config('restServerPid') if not detect_process(rest_pid): experiment_config.update_experiment(key, 'status', 'STOPPED') continue rest_port = nni_config.get_config('restServerPort') startTime, endTime = get_experiment_time(rest_port) if startTime: experiment_config.update_experiment(key, 'startTime', startTime) if endTime: experiment_config.update_experiment(key, 'endTime', endTime) status = get_experiment_status(rest_port) if status: experiment_config.update_experiment(key, 'status', status)
check if the id is valid def check_experiment_id(args): '''check if the id is valid ''' update_experiment() experiment_config = Experiments() experiment_dict = experiment_config.get_all_experiments() if not experiment_dict: print_normal('There is no experiment running...') return None if not args.id: running_experiment_list = [] for key in experiment_dict.keys(): if isinstance(experiment_dict[key], dict): if experiment_dict[key].get('status') != 'STOPPED': running_experiment_list.append(key) elif isinstance(experiment_dict[key], list): # if the config file is old version, remove the configuration from file experiment_config.remove_experiment(key) if len(running_experiment_list) > 1: print_error('There are multiple experiments, please set the experiment id...') experiment_information = "" for key in running_experiment_list: experiment_information += (EXPERIMENT_DETAIL_FORMAT % (key, experiment_dict[key]['status'], \ experiment_dict[key]['port'], experiment_dict[key].get('platform'), experiment_dict[key]['startTime'], experiment_dict[key]['endTime'])) print(EXPERIMENT_INFORMATION_FORMAT % experiment_information) exit(1) elif not running_experiment_list: print_error('There is no experiment running!') return None else: return running_experiment_list[0] if experiment_dict.get(args.id): return args.id else: print_error('Id not correct!') return None
Parse the arguments for nnictl stop 1.If there is an id specified, return the corresponding id 2.If there is no id specified, and there is an experiment running, return the id, or return Error 3.If the id matches an experiment, nnictl will return the id. 4.If the id ends with *, nnictl will match all ids matchs the regular 5.If the id does not exist but match the prefix of an experiment id, nnictl will return the matched id 6.If the id does not exist but match multiple prefix of the experiment ids, nnictl will give id information def parse_ids(args): '''Parse the arguments for nnictl stop 1.If there is an id specified, return the corresponding id 2.If there is no id specified, and there is an experiment running, return the id, or return Error 3.If the id matches an experiment, nnictl will return the id. 4.If the id ends with *, nnictl will match all ids matchs the regular 5.If the id does not exist but match the prefix of an experiment id, nnictl will return the matched id 6.If the id does not exist but match multiple prefix of the experiment ids, nnictl will give id information ''' update_experiment() experiment_config = Experiments() experiment_dict = experiment_config.get_all_experiments() if not experiment_dict: print_normal('Experiment is not running...') return None result_list = [] running_experiment_list = [] for key in experiment_dict.keys(): if isinstance(experiment_dict[key], dict): if experiment_dict[key].get('status') != 'STOPPED': running_experiment_list.append(key) elif isinstance(experiment_dict[key], list): # if the config file is old version, remove the configuration from file experiment_config.remove_experiment(key) if not args.id: if len(running_experiment_list) > 1: print_error('There are multiple experiments, please set the experiment id...') experiment_information = "" for key in running_experiment_list: experiment_information += (EXPERIMENT_DETAIL_FORMAT % (key, experiment_dict[key]['status'], \ experiment_dict[key]['port'], experiment_dict[key].get('platform'), experiment_dict[key]['startTime'], experiment_dict[key]['endTime'])) print(EXPERIMENT_INFORMATION_FORMAT % experiment_information) exit(1) else: result_list = running_experiment_list elif args.id == 'all': result_list = running_experiment_list elif args.id.endswith('*'): for id in running_experiment_list: if id.startswith(args.id[:-1]): result_list.append(id) elif args.id in running_experiment_list: result_list.append(args.id) else: for id in running_experiment_list: if id.startswith(args.id): result_list.append(id) if len(result_list) > 1: print_error(args.id + ' is ambiguous, please choose ' + ' '.join(result_list) ) return None if not result_list and args.id: print_error('There are no experiments matched, please set correct experiment id...') elif not result_list: print_error('There is no experiment running...') return result_list
get the file name of config file def get_config_filename(args): '''get the file name of config file''' experiment_id = check_experiment_id(args) if experiment_id is None: print_error('Please set the experiment id!') exit(1) experiment_config = Experiments() experiment_dict = experiment_config.get_all_experiments() return experiment_dict[experiment_id]['fileName']
Convert time stamp to date time format def convert_time_stamp_to_date(content): '''Convert time stamp to date time format''' start_time_stamp = content.get('startTime') end_time_stamp = content.get('endTime') if start_time_stamp: start_time = datetime.datetime.utcfromtimestamp(start_time_stamp // 1000).strftime("%Y/%m/%d %H:%M:%S") content['startTime'] = str(start_time) if end_time_stamp: end_time = datetime.datetime.utcfromtimestamp(end_time_stamp // 1000).strftime("%Y/%m/%d %H:%M:%S") content['endTime'] = str(end_time) return content
check if restful server is running def check_rest(args): '''check if restful server is running''' nni_config = Config(get_config_filename(args)) rest_port = nni_config.get_config('restServerPort') running, _ = check_rest_server_quick(rest_port) if not running: print_normal('Restful server is running...') else: print_normal('Restful server is not running...')
Stop the experiment which is running def stop_experiment(args): '''Stop the experiment which is running''' experiment_id_list = parse_ids(args) if experiment_id_list: experiment_config = Experiments() experiment_dict = experiment_config.get_all_experiments() for experiment_id in experiment_id_list: print_normal('Stoping experiment %s' % experiment_id) nni_config = Config(experiment_dict[experiment_id]['fileName']) rest_port = nni_config.get_config('restServerPort') rest_pid = nni_config.get_config('restServerPid') if rest_pid: kill_command(rest_pid) tensorboard_pid_list = nni_config.get_config('tensorboardPidList') if tensorboard_pid_list: for tensorboard_pid in tensorboard_pid_list: try: kill_command(tensorboard_pid) except Exception as exception: print_error(exception) nni_config.set_config('tensorboardPidList', []) print_normal('Stop experiment success!') experiment_config.update_experiment(experiment_id, 'status', 'STOPPED') time_now = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) experiment_config.update_experiment(experiment_id, 'endTime', str(time_now))