text
stringlengths
81
112k
Insert the new_layers after the node with start_node_id. def _insert_new_layers(self, new_layers, start_node_id, end_node_id): """Insert the new_layers after the node with start_node_id.""" new_node_id = self._add_node(deepcopy(self.node_list[end_node_id])) temp_output_id = new_node_id for layer in new_layers[:-1]: temp_output_id = self.add_layer(layer, temp_output_id) self._add_edge(new_layers[-1], temp_output_id, end_node_id) new_layers[-1].input = self.node_list[temp_output_id] new_layers[-1].output = self.node_list[end_node_id] self._redirect_edge(start_node_id, end_node_id, new_node_id)
Add a weighted add skip-connection from after start node to end node. Args: start_id: The convolutional layer ID, after which to start the skip-connection. end_id: The convolutional layer ID, after which to end the skip-connection. def to_add_skip_model(self, start_id, end_id): """Add a weighted add skip-connection from after start node to end node. Args: start_id: The convolutional layer ID, after which to start the skip-connection. end_id: The convolutional layer ID, after which to end the skip-connection. """ self.operation_history.append(("to_add_skip_model", start_id, end_id)) filters_end = self.layer_list[end_id].output.shape[-1] filters_start = self.layer_list[start_id].output.shape[-1] start_node_id = self.layer_id_to_output_node_ids[start_id][0] pre_end_node_id = self.layer_id_to_input_node_ids[end_id][0] end_node_id = self.layer_id_to_output_node_ids[end_id][0] skip_output_id = self._insert_pooling_layer_chain(start_node_id, end_node_id) # Add the conv layer new_conv_layer = get_conv_class(self.n_dim)(filters_start, filters_end, 1) skip_output_id = self.add_layer(new_conv_layer, skip_output_id) # Add the add layer. add_input_node_id = self._add_node(deepcopy(self.node_list[end_node_id])) add_layer = StubAdd() self._redirect_edge(pre_end_node_id, end_node_id, add_input_node_id) self._add_edge(add_layer, add_input_node_id, end_node_id) self._add_edge(add_layer, skip_output_id, end_node_id) add_layer.input = [ self.node_list[add_input_node_id], self.node_list[skip_output_id], ] add_layer.output = self.node_list[end_node_id] self.node_list[end_node_id].shape = add_layer.output_shape # Set weights to the additional conv layer. if self.weighted: filter_shape = (1,) * self.n_dim weights = np.zeros((filters_end, filters_start) + filter_shape) bias = np.zeros(filters_end) new_conv_layer.set_weights( (add_noise(weights, np.array([0, 1])), add_noise(bias, np.array([0, 1]))) )
Add a weighted add concatenate connection from after start node to end node. Args: start_id: The convolutional layer ID, after which to start the skip-connection. end_id: The convolutional layer ID, after which to end the skip-connection. def to_concat_skip_model(self, start_id, end_id): """Add a weighted add concatenate connection from after start node to end node. Args: start_id: The convolutional layer ID, after which to start the skip-connection. end_id: The convolutional layer ID, after which to end the skip-connection. """ self.operation_history.append(("to_concat_skip_model", start_id, end_id)) filters_end = self.layer_list[end_id].output.shape[-1] filters_start = self.layer_list[start_id].output.shape[-1] start_node_id = self.layer_id_to_output_node_ids[start_id][0] pre_end_node_id = self.layer_id_to_input_node_ids[end_id][0] end_node_id = self.layer_id_to_output_node_ids[end_id][0] skip_output_id = self._insert_pooling_layer_chain(start_node_id, end_node_id) concat_input_node_id = self._add_node(deepcopy(self.node_list[end_node_id])) self._redirect_edge(pre_end_node_id, end_node_id, concat_input_node_id) concat_layer = StubConcatenate() concat_layer.input = [ self.node_list[concat_input_node_id], self.node_list[skip_output_id], ] concat_output_node_id = self._add_node(Node(concat_layer.output_shape)) self._add_edge(concat_layer, concat_input_node_id, concat_output_node_id) self._add_edge(concat_layer, skip_output_id, concat_output_node_id) concat_layer.output = self.node_list[concat_output_node_id] self.node_list[concat_output_node_id].shape = concat_layer.output_shape # Add the concatenate layer. new_conv_layer = get_conv_class(self.n_dim)( filters_start + filters_end, filters_end, 1 ) self._add_edge(new_conv_layer, concat_output_node_id, end_node_id) new_conv_layer.input = self.node_list[concat_output_node_id] new_conv_layer.output = self.node_list[end_node_id] self.node_list[end_node_id].shape = new_conv_layer.output_shape if self.weighted: filter_shape = (1,) * self.n_dim weights = np.zeros((filters_end, filters_end) + filter_shape) for i in range(filters_end): filter_weight = np.zeros((filters_end,) + filter_shape) center_index = (i,) + (0,) * self.n_dim filter_weight[center_index] = 1 weights[i, ...] = filter_weight weights = np.concatenate( (weights, np.zeros((filters_end, filters_start) + filter_shape)), axis=1 ) bias = np.zeros(filters_end) new_conv_layer.set_weights( (add_noise(weights, np.array([0, 1])), add_noise(bias, np.array([0, 1]))) )
Extract the the description of the Graph as an instance of NetworkDescriptor. def extract_descriptor(self): """Extract the the description of the Graph as an instance of NetworkDescriptor.""" main_chain = self.get_main_chain() index_in_main_chain = {} for index, u in enumerate(main_chain): index_in_main_chain[u] = index ret = NetworkDescriptor() for u in main_chain: for v, layer_id in self.adj_list[u]: if v not in index_in_main_chain: continue layer = self.layer_list[layer_id] copied_layer = copy(layer) copied_layer.weights = None ret.add_layer(deepcopy(copied_layer)) for u in index_in_main_chain: for v, layer_id in self.adj_list[u]: if v not in index_in_main_chain: temp_u = u temp_v = v temp_layer_id = layer_id skip_type = None while not (temp_v in index_in_main_chain and temp_u in index_in_main_chain): if is_layer(self.layer_list[temp_layer_id], "Concatenate"): skip_type = NetworkDescriptor.CONCAT_CONNECT if is_layer(self.layer_list[temp_layer_id], "Add"): skip_type = NetworkDescriptor.ADD_CONNECT temp_u = temp_v temp_v, temp_layer_id = self.adj_list[temp_v][0] ret.add_skip_connection( index_in_main_chain[u], index_in_main_chain[temp_u], skip_type ) elif index_in_main_chain[v] - index_in_main_chain[u] != 1: skip_type = None if is_layer(self.layer_list[layer_id], "Concatenate"): skip_type = NetworkDescriptor.CONCAT_CONNECT if is_layer(self.layer_list[layer_id], "Add"): skip_type = NetworkDescriptor.ADD_CONNECT ret.add_skip_connection( index_in_main_chain[u], index_in_main_chain[v], skip_type ) return ret
clear weights of the graph def clear_weights(self): ''' clear weights of the graph ''' self.weighted = False for layer in self.layer_list: layer.weights = None
Return a list of layer IDs in the main chain. def get_main_chain_layers(self): """Return a list of layer IDs in the main chain.""" main_chain = self.get_main_chain() ret = [] for u in main_chain: for v, layer_id in self.adj_list[u]: if v in main_chain and u in main_chain: ret.append(layer_id) return ret
Returns the main chain node ID list. def get_main_chain(self): """Returns the main chain node ID list.""" pre_node = {} distance = {} for i in range(self.n_nodes): distance[i] = 0 pre_node[i] = i for i in range(self.n_nodes - 1): for u in range(self.n_nodes): for v, _ in self.adj_list[u]: if distance[u] + 1 > distance[v]: distance[v] = distance[u] + 1 pre_node[v] = u temp_id = 0 for i in range(self.n_nodes): if distance[i] > distance[temp_id]: temp_id = i ret = [] for i in range(self.n_nodes + 5): ret.append(temp_id) if pre_node[temp_id] == temp_id: break temp_id = pre_node[temp_id] assert temp_id == pre_node[temp_id] ret.reverse() return ret
Run the tuner. This function will never return unless raise. def run(self): """Run the tuner. This function will never return unless raise. """ _logger.info('Start dispatcher') if dispatcher_env_vars.NNI_MODE == 'resume': self.load_checkpoint() while True: command, data = receive() if data: data = json_tricks.loads(data) if command is None or command is CommandType.Terminate: break if multi_thread_enabled(): result = self.pool.map_async(self.process_command_thread, [(command, data)]) self.thread_results.append(result) if any([thread_result.ready() and not thread_result.successful() for thread_result in self.thread_results]): _logger.debug('Caught thread exception') break else: self.enqueue_command(command, data) if self.worker_exceptions: break _logger.info('Dispatcher exiting...') self.stopping = True if multi_thread_enabled(): self.pool.close() self.pool.join() else: self.default_worker.join() self.assessor_worker.join() _logger.info('Terminated by NNI manager')
Process commands in command queues. def command_queue_worker(self, command_queue): """Process commands in command queues. """ while True: try: # set timeout to ensure self.stopping is checked periodically command, data = command_queue.get(timeout=3) try: self.process_command(command, data) except Exception as e: _logger.exception(e) self.worker_exceptions.append(e) break except Empty: pass if self.stopping and (_worker_fast_exit_on_terminate or command_queue.empty()): break
Enqueue command into command queues def enqueue_command(self, command, data): """Enqueue command into command queues """ if command == CommandType.TrialEnd or (command == CommandType.ReportMetricData and data['type'] == 'PERIODICAL'): self.assessor_command_queue.put((command, data)) else: self.default_command_queue.put((command, data)) qsize = self.default_command_queue.qsize() if qsize >= QUEUE_LEN_WARNING_MARK: _logger.warning('default queue length: %d', qsize) qsize = self.assessor_command_queue.qsize() if qsize >= QUEUE_LEN_WARNING_MARK: _logger.warning('assessor queue length: %d', qsize)
Worker thread to process a command. def process_command_thread(self, request): """Worker thread to process a command. """ command, data = request if multi_thread_enabled(): try: self.process_command(command, data) except Exception as e: _logger.exception(str(e)) raise else: pass
Update values in the array, to match their corresponding type def match_val_type(vals, vals_bounds, vals_types): ''' Update values in the array, to match their corresponding type ''' vals_new = [] for i, _ in enumerate(vals_types): if vals_types[i] == "discrete_int": # Find the closest integer in the array, vals_bounds vals_new.append(min(vals_bounds[i], key=lambda x: abs(x - vals[i]))) elif vals_types[i] == "range_int": # Round down to the nearest integer vals_new.append(math.floor(vals[i])) elif vals_types[i] == "range_continuous": # Don't do any processing for continous numbers vals_new.append(vals[i]) else: return None return vals_new
Random generate variable value within their bounds def rand(x_bounds, x_types): ''' Random generate variable value within their bounds ''' outputs = [] for i, _ in enumerate(x_bounds): if x_types[i] == "discrete_int": temp = x_bounds[i][random.randint(0, len(x_bounds[i]) - 1)] outputs.append(temp) elif x_types[i] == "range_int": temp = random.randint(x_bounds[i][0], x_bounds[i][1]) outputs.append(temp) elif x_types[i] == "range_continuous": temp = random.uniform(x_bounds[i][0], x_bounds[i][1]) outputs.append(temp) else: return None return outputs
wider graph def to_wider_graph(graph): ''' wider graph ''' weighted_layer_ids = graph.wide_layer_ids() weighted_layer_ids = list( filter(lambda x: graph.layer_list[x].output.shape[-1], weighted_layer_ids) ) wider_layers = sample(weighted_layer_ids, 1) for layer_id in wider_layers: layer = graph.layer_list[layer_id] if is_layer(layer, "Conv"): n_add = layer.filters else: n_add = layer.units graph.to_wider_model(layer_id, n_add) return graph
skip connection graph def to_skip_connection_graph(graph): ''' skip connection graph ''' # The last conv layer cannot be widen since wider operator cannot be done over the two sides of flatten. weighted_layer_ids = graph.skip_connection_layer_ids() valid_connection = [] for skip_type in sorted([NetworkDescriptor.ADD_CONNECT, NetworkDescriptor.CONCAT_CONNECT]): for index_a in range(len(weighted_layer_ids)): for index_b in range(len(weighted_layer_ids))[index_a + 1 :]: valid_connection.append((index_a, index_b, skip_type)) if not valid_connection: return graph for index_a, index_b, skip_type in sample(valid_connection, 1): a_id = weighted_layer_ids[index_a] b_id = weighted_layer_ids[index_b] if skip_type == NetworkDescriptor.ADD_CONNECT: graph.to_add_skip_model(a_id, b_id) else: graph.to_concat_skip_model(a_id, b_id) return graph
create new layer for the graph def create_new_layer(layer, n_dim): ''' create new layer for the graph ''' input_shape = layer.output.shape dense_deeper_classes = [StubDense, get_dropout_class(n_dim), StubReLU] conv_deeper_classes = [get_conv_class(n_dim), get_batch_norm_class(n_dim), StubReLU] if is_layer(layer, "ReLU"): conv_deeper_classes = [get_conv_class(n_dim), get_batch_norm_class(n_dim)] dense_deeper_classes = [StubDense, get_dropout_class(n_dim)] elif is_layer(layer, "Dropout"): dense_deeper_classes = [StubDense, StubReLU] elif is_layer(layer, "BatchNormalization"): conv_deeper_classes = [get_conv_class(n_dim), StubReLU] layer_class = None if len(input_shape) == 1: # It is in the dense layer part. layer_class = sample(dense_deeper_classes, 1)[0] else: # It is in the conv layer part. layer_class = sample(conv_deeper_classes, 1)[0] if layer_class == StubDense: new_layer = StubDense(input_shape[0], input_shape[0]) elif layer_class == get_dropout_class(n_dim): new_layer = layer_class(Constant.DENSE_DROPOUT_RATE) elif layer_class == get_conv_class(n_dim): new_layer = layer_class( input_shape[-1], input_shape[-1], sample((1, 3, 5), 1)[0], stride=1 ) elif layer_class == get_batch_norm_class(n_dim): new_layer = layer_class(input_shape[-1]) elif layer_class == get_pooling_class(n_dim): new_layer = layer_class(sample((1, 3, 5), 1)[0]) else: new_layer = layer_class() return new_layer
deeper graph def to_deeper_graph(graph): ''' deeper graph ''' weighted_layer_ids = graph.deep_layer_ids() if len(weighted_layer_ids) >= Constant.MAX_LAYERS: return None deeper_layer_ids = sample(weighted_layer_ids, 1) for layer_id in deeper_layer_ids: layer = graph.layer_list[layer_id] new_layer = create_new_layer(layer, graph.n_dim) graph.to_deeper_model(layer_id, new_layer) return graph
judge if a graph is legal or not. def legal_graph(graph): '''judge if a graph is legal or not. ''' descriptor = graph.extract_descriptor() skips = descriptor.skip_connections if len(skips) != len(set(skips)): return False return True
core transform function for graph. def transform(graph): '''core transform function for graph. ''' graphs = [] for _ in range(Constant.N_NEIGHBOURS * 2): random_num = randrange(3) temp_graph = None if random_num == 0: temp_graph = to_deeper_graph(deepcopy(graph)) elif random_num == 1: temp_graph = to_wider_graph(deepcopy(graph)) elif random_num == 2: temp_graph = to_skip_connection_graph(deepcopy(graph)) if temp_graph is not None and temp_graph.size() <= Constant.MAX_MODEL_SIZE: graphs.append(temp_graph) if len(graphs) >= Constant.N_NEIGHBOURS: break return graphs
low: an float that represent an lower bound high: an float that represent an upper bound random_state: an object of numpy.random.RandomState def uniform(low, high, random_state): ''' low: an float that represent an lower bound high: an float that represent an upper bound random_state: an object of numpy.random.RandomState ''' assert high > low, 'Upper bound must be larger than lower bound' return random_state.uniform(low, high)
low: an float that represent an lower bound high: an float that represent an upper bound q: sample step random_state: an object of numpy.random.RandomState def quniform(low, high, q, random_state): ''' low: an float that represent an lower bound high: an float that represent an upper bound q: sample step random_state: an object of numpy.random.RandomState ''' return np.round(uniform(low, high, random_state) / q) * q
low: an float that represent an lower bound high: an float that represent an upper bound random_state: an object of numpy.random.RandomState def loguniform(low, high, random_state): ''' low: an float that represent an lower bound high: an float that represent an upper bound random_state: an object of numpy.random.RandomState ''' assert low > 0, 'Lower bound must be positive' return np.exp(uniform(np.log(low), np.log(high), random_state))
low: an float that represent an lower bound high: an float that represent an upper bound q: sample step random_state: an object of numpy.random.RandomState def qloguniform(low, high, q, random_state): ''' low: an float that represent an lower bound high: an float that represent an upper bound q: sample step random_state: an object of numpy.random.RandomState ''' return np.round(loguniform(low, high, random_state) / q) * q
mu: float or array_like of floats sigma: float or array_like of floats q: sample step random_state: an object of numpy.random.RandomState def qnormal(mu, sigma, q, random_state): ''' mu: float or array_like of floats sigma: float or array_like of floats q: sample step random_state: an object of numpy.random.RandomState ''' return np.round(normal(mu, sigma, random_state) / q) * q
mu: float or array_like of floats sigma: float or array_like of floats random_state: an object of numpy.random.RandomState def lognormal(mu, sigma, random_state): ''' mu: float or array_like of floats sigma: float or array_like of floats random_state: an object of numpy.random.RandomState ''' return np.exp(normal(mu, sigma, random_state))
mu: float or array_like of floats sigma: float or array_like of floats q: sample step random_state: an object of numpy.random.RandomState def qlognormal(mu, sigma, q, random_state): ''' mu: float or array_like of floats sigma: float or array_like of floats q: sample step random_state: an object of numpy.random.RandomState ''' return np.round(lognormal(mu, sigma, random_state) / q) * q
Predict by Gaussian Process Model def predict(parameters_value, regressor_gp): ''' Predict by Gaussian Process Model ''' parameters_value = numpy.array(parameters_value).reshape(-1, len(parameters_value)) mu, sigma = regressor_gp.predict(parameters_value, return_std=True) return mu[0], sigma[0]
Call rest get method def rest_get(url, timeout): '''Call rest get method''' try: response = requests.get(url, timeout=timeout) return response except Exception as e: print('Get exception {0} when sending http get to url {1}'.format(str(e), url)) return None
Call rest post method def rest_post(url, data, timeout, rethrow_exception=False): '''Call rest post method''' try: response = requests.post(url, headers={'Accept': 'application/json', 'Content-Type': 'application/json'},\ data=data, timeout=timeout) return response except Exception as e: if rethrow_exception is True: raise print('Get exception {0} when sending http post to url {1}'.format(str(e), url)) return None
Call rest put method def rest_put(url, data, timeout): '''Call rest put method''' try: response = requests.put(url, headers={'Accept': 'application/json', 'Content-Type': 'application/json'},\ data=data, timeout=timeout) return response except Exception as e: print('Get exception {0} when sending http put to url {1}'.format(str(e), url)) return None
Call rest delete method def rest_delete(url, timeout): '''Call rest delete method''' try: response = requests.delete(url, timeout=timeout) return response except Exception as e: print('Get exception {0} when sending http delete to url {1}'.format(str(e), url)) return None
update the best performance of completed trial job Parameters ---------- trial_job_id: int trial job id success: bool True if succssfully finish the experiment, False otherwise def trial_end(self, trial_job_id, success): """update the best performance of completed trial job Parameters ---------- trial_job_id: int trial job id success: bool True if succssfully finish the experiment, False otherwise """ if success: if self.set_best_performance: self.completed_best_performance = max(self.completed_best_performance, self.trial_history[-1]) else: self.set_best_performance = True self.completed_best_performance = self.trial_history[-1] logger.info('Updated complted best performance, trial job id:', trial_job_id) else: logger.info('No need to update, trial job id: ', trial_job_id)
assess whether a trial should be early stop by curve fitting algorithm Parameters ---------- trial_job_id: int trial job id trial_history: list The history performance matrix of each trial Returns ------- bool AssessResult.Good or AssessResult.Bad Raises ------ Exception unrecognize exception in curvefitting_assessor def assess_trial(self, trial_job_id, trial_history): """assess whether a trial should be early stop by curve fitting algorithm Parameters ---------- trial_job_id: int trial job id trial_history: list The history performance matrix of each trial Returns ------- bool AssessResult.Good or AssessResult.Bad Raises ------ Exception unrecognize exception in curvefitting_assessor """ self.trial_job_id = trial_job_id self.trial_history = trial_history if not self.set_best_performance: return AssessResult.Good curr_step = len(trial_history) if curr_step < self.start_step: return AssessResult.Good if trial_job_id in self.last_judgment_num.keys() and curr_step - self.last_judgment_num[trial_job_id] < self.gap: return AssessResult.Good self.last_judgment_num[trial_job_id] = curr_step try: start_time = datetime.datetime.now() # Predict the final result curvemodel = CurveModel(self.target_pos) predict_y = curvemodel.predict(trial_history) logger.info('Prediction done. Trial job id = ', trial_job_id, '. Predict value = ', predict_y) if predict_y is None: logger.info('wait for more information to predict precisely') return AssessResult.Good standard_performance = self.completed_best_performance * self.threshold end_time = datetime.datetime.now() if (end_time - start_time).seconds > 60: logger.warning('Curve Fitting Assessor Runtime Exceeds 60s, Trial Id = ', self.trial_job_id, 'Trial History = ', self.trial_history) if self.higher_better: if predict_y > standard_performance: return AssessResult.Good return AssessResult.Bad else: if predict_y < standard_performance: return AssessResult.Good return AssessResult.Bad except Exception as exception: logger.exception('unrecognize exception in curvefitting_assessor', exception)
data is search space def handle_initialize(self, data): ''' data is search space ''' self.tuner.update_search_space(data) send(CommandType.Initialized, '') return True
Returns a set of trial neural architecture, as a serializable object. Parameters ---------- parameter_id : int def generate_parameters(self, parameter_id): """ Returns a set of trial neural architecture, as a serializable object. Parameters ---------- parameter_id : int """ if not self.history: self.init_search() new_father_id = None generated_graph = None if not self.training_queue: new_father_id, generated_graph = self.generate() new_model_id = self.model_count self.model_count += 1 self.training_queue.append((generated_graph, new_father_id, new_model_id)) self.descriptors.append(generated_graph.extract_descriptor()) graph, father_id, model_id = self.training_queue.pop(0) # from graph to json json_model_path = os.path.join(self.path, str(model_id) + ".json") json_out = graph_to_json(graph, json_model_path) self.total_data[parameter_id] = (json_out, father_id, model_id) return json_out
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. 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. """ reward = extract_scalar_reward(value) if parameter_id not in self.total_data: raise RuntimeError("Received parameter_id not in total_data.") (_, father_id, model_id) = self.total_data[parameter_id] graph = self.bo.searcher.load_model_by_id(model_id) # to use the value and graph self.add_model(reward, model_id) self.update(father_id, graph, reward, model_id)
Call the generators to generate the initial architectures for the search. def init_search(self): """Call the generators to generate the initial architectures for the search.""" if self.verbose: logger.info("Initializing search.") for generator in self.generators: graph = generator(self.n_classes, self.input_shape).generate( self.default_model_len, self.default_model_width ) model_id = self.model_count self.model_count += 1 self.training_queue.append((graph, -1, model_id)) self.descriptors.append(graph.extract_descriptor()) if self.verbose: logger.info("Initialization finished.")
Generate the next neural architecture. Returns ------- other_info: any object Anything to be saved in the training queue together with the architecture. generated_graph: Graph An instance of Graph. def generate(self): """Generate the next neural architecture. Returns ------- other_info: any object Anything to be saved in the training queue together with the architecture. generated_graph: Graph An instance of Graph. """ generated_graph, new_father_id = self.bo.generate(self.descriptors) if new_father_id is None: new_father_id = 0 generated_graph = self.generators[0]( self.n_classes, self.input_shape ).generate(self.default_model_len, self.default_model_width) return new_father_id, generated_graph
Update the controller with evaluation result of a neural architecture. Parameters ---------- other_info: any object In our case it is the father ID in the search tree. graph: Graph An instance of Graph. The trained neural architecture. metric_value: float The final evaluated metric value. model_id: int def update(self, other_info, graph, metric_value, model_id): """ Update the controller with evaluation result of a neural architecture. Parameters ---------- other_info: any object In our case it is the father ID in the search tree. graph: Graph An instance of Graph. The trained neural architecture. metric_value: float The final evaluated metric value. model_id: int """ father_id = other_info self.bo.fit([graph.extract_descriptor()], [metric_value]) self.bo.add_child(father_id, model_id)
Add model to the history, x_queue and y_queue Parameters ---------- metric_value : float graph : dict model_id : int Returns ------- model : dict def add_model(self, metric_value, model_id): """ Add model to the history, x_queue and y_queue Parameters ---------- metric_value : float graph : dict model_id : int Returns ------- model : dict """ if self.verbose: logger.info("Saving model.") # Update best_model text file ret = {"model_id": model_id, "metric_value": metric_value} self.history.append(ret) if model_id == self.get_best_model_id(): file = open(os.path.join(self.path, "best_model.txt"), "w") file.write("best model: " + str(model_id)) file.close() return ret
Get the best model_id from history using the metric value def get_best_model_id(self): """ Get the best model_id from history using the metric value """ if self.optimize_mode is OptimizeMode.Maximize: return max(self.history, key=lambda x: x["metric_value"])["model_id"] return min(self.history, key=lambda x: x["metric_value"])["model_id"]
Get the model by model_id Parameters ---------- model_id : int model index Returns ------- load_model : Graph the model graph representation def load_model_by_id(self, model_id): """Get the model by model_id Parameters ---------- model_id : int model index Returns ------- load_model : Graph the model graph representation """ with open(os.path.join(self.path, str(model_id) + ".json")) as fin: json_str = fin.read().replace("\n", "") load_model = json_to_graph(json_str) return load_model
Random sample some init seed within bounds. def _rand_init(x_bounds, x_types, selection_num_starting_points): ''' Random sample some init seed within bounds. ''' return [lib_data.rand(x_bounds, x_types) for i \ in range(0, selection_num_starting_points)]
Return median def get_median(temp_list): """Return median """ num = len(temp_list) temp_list.sort() print(temp_list) if num % 2 == 0: median = (temp_list[int(num/2)] + temp_list[int(num/2) - 1]) / 2 else: median = temp_list[int(num/2)] return median
Update the self.x_bounds and self.x_types by the search_space.json Parameters ---------- search_space : dict def update_search_space(self, search_space): """Update the self.x_bounds and self.x_types by the search_space.json Parameters ---------- search_space : dict """ self.x_bounds = [[] for i in range(len(search_space))] self.x_types = [NONE_TYPE for i in range(len(search_space))] for key in search_space: self.key_order.append(key) key_type = {} if isinstance(search_space, dict): for key in search_space: key_type = search_space[key]['_type'] key_range = search_space[key]['_value'] idx = self.key_order.index(key) if key_type == 'quniform': if key_range[2] == 1: self.x_bounds[idx] = [key_range[0], key_range[1]] self.x_types[idx] = 'range_int' else: bounds = [] for value in np.arange(key_range[0], key_range[1], key_range[2]): bounds.append(value) self.x_bounds[idx] = bounds self.x_types[idx] = 'discrete_int' elif key_type == 'randint': self.x_bounds[idx] = [0, key_range[0]] self.x_types[idx] = 'range_int' elif key_type == 'uniform': self.x_bounds[idx] = [key_range[0], key_range[1]] self.x_types[idx] = 'range_continuous' elif key_type == 'choice': self.x_bounds[idx] = key_range for key_value in key_range: if not isinstance(key_value, (int, float)): raise RuntimeError("Metis Tuner only support numerical choice.") self.x_types[idx] = 'discrete_int' else: logger.info("Metis Tuner doesn't support this kind of variable: " + str(key_type)) raise RuntimeError("Metis Tuner doesn't support this kind of variable: " + str(key_type)) else: logger.info("The format of search space is not a dict.") raise RuntimeError("The format of search space is not a dict.") self.minimize_starting_points = _rand_init(self.x_bounds, self.x_types, \ self.selection_num_starting_points)
Pack the output Parameters ---------- init_parameter : dict Returns ------- output : dict def _pack_output(self, init_parameter): """Pack the output Parameters ---------- init_parameter : dict Returns ------- output : dict """ output = {} for i, param in enumerate(init_parameter): output[self.key_order[i]] = param return output
Generate next parameter for trial If the number of trial result is lower than cold start number, metis will first random generate some parameters. Otherwise, metis will choose the parameters by the Gussian Process Model and the Gussian Mixture Model. Parameters ---------- parameter_id : int Returns ------- result : dict def generate_parameters(self, parameter_id): """Generate next parameter for trial If the number of trial result is lower than cold start number, metis will first random generate some parameters. Otherwise, metis will choose the parameters by the Gussian Process Model and the Gussian Mixture Model. Parameters ---------- parameter_id : int Returns ------- result : dict """ if len(self.samples_x) < self.cold_start_num: init_parameter = _rand_init(self.x_bounds, self.x_types, 1)[0] results = self._pack_output(init_parameter) else: self.minimize_starting_points = _rand_init(self.x_bounds, self.x_types, \ self.selection_num_starting_points) results = self._selection(self.samples_x, self.samples_y_aggregation, self.samples_y, self.x_bounds, self.x_types, threshold_samplessize_resampling=(None if self.no_resampling is True else 50), no_candidates=self.no_candidates, minimize_starting_points=self.minimize_starting_points, minimize_constraints_fun=self.minimize_constraints_fun) logger.info("Generate paramageters:\n" + str(results)) return results
Tuner receive result from trial. Parameters ---------- parameter_id : int parameters : dict value : dict/float if value is dict, it should have "default" key. def receive_trial_result(self, parameter_id, parameters, value): """Tuner receive result from trial. Parameters ---------- parameter_id : int parameters : dict value : dict/float if value is dict, it should have "default" key. """ value = extract_scalar_reward(value) if self.optimize_mode == OptimizeMode.Maximize: value = -value logger.info("Received trial result.") logger.info("value is :" + str(value)) logger.info("parameter is : " + str(parameters)) # parse parameter to sample_x sample_x = [0 for i in range(len(self.key_order))] for key in parameters: idx = self.key_order.index(key) sample_x[idx] = parameters[key] # parse value to sample_y temp_y = [] if sample_x in self.samples_x: idx = self.samples_x.index(sample_x) temp_y = self.samples_y[idx] temp_y.append(value) self.samples_y[idx] = temp_y # calculate y aggregation median = get_median(temp_y) self.samples_y_aggregation[idx] = [median] else: self.samples_x.append(sample_x) self.samples_y.append([value]) # calculate y aggregation self.samples_y_aggregation.append([value])
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 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.append(_params) self.receive_trial_result(parameter_id=_parameter_id, parameters=_params, value=_value) logger.info("Successfully import data to metis tuner.")
Trains GP regression model def create_model(samples_x, samples_y_aggregation, n_restarts_optimizer=250, is_white_kernel=False): ''' Trains GP regression model ''' kernel = gp.kernels.ConstantKernel(constant_value=1, constant_value_bounds=(1e-12, 1e12)) * \ gp.kernels.Matern(nu=1.5) if is_white_kernel is True: kernel += gp.kernels.WhiteKernel(noise_level=1, noise_level_bounds=(1e-12, 1e12)) regressor = gp.GaussianProcessRegressor(kernel=kernel, n_restarts_optimizer=n_restarts_optimizer, normalize_y=True, alpha=1e-10) regressor.fit(numpy.array(samples_x), numpy.array(samples_y_aggregation)) model = {} model['model'] = regressor model['kernel_prior'] = str(kernel) model['kernel_posterior'] = str(regressor.kernel_) model['model_loglikelihood'] = regressor.log_marginal_likelihood(regressor.kernel_.theta) return model
generate all possible configs for hyperparameters from hyperparameter space. ss_spec: hyperparameter space def json2paramater(self, ss_spec): ''' generate all possible configs for hyperparameters from hyperparameter space. ss_spec: hyperparameter space ''' if isinstance(ss_spec, dict): if '_type' in ss_spec.keys(): _type = ss_spec['_type'] _value = ss_spec['_value'] chosen_params = list() if _type == 'choice': for value in _value: choice = self.json2paramater(value) if isinstance(choice, list): chosen_params.extend(choice) else: chosen_params.append(choice) else: chosen_params = self.parse_qtype(_type, _value) else: chosen_params = dict() for key in ss_spec.keys(): chosen_params[key] = self.json2paramater(ss_spec[key]) return self.expand_parameters(chosen_params) elif isinstance(ss_spec, list): chosen_params = list() for subspec in ss_spec[1:]: choice = self.json2paramater(subspec) if isinstance(choice, list): chosen_params.extend(choice) else: chosen_params.append(choice) chosen_params = list(map(lambda v: {ss_spec[0]: v}, chosen_params)) else: chosen_params = copy.deepcopy(ss_spec) return chosen_params
parse type of quniform parameter and return a list def _parse_quniform(self, param_value): '''parse type of quniform parameter and return a list''' if param_value[2] < 2: raise RuntimeError("The number of values sampled (q) should be at least 2") low, high, count = param_value[0], param_value[1], param_value[2] interval = (high - low) / (count - 1) return [float(low + interval * i) for i in range(count)]
parse type of quniform or qloguniform def parse_qtype(self, param_type, param_value): '''parse type of quniform or qloguniform''' if param_type == 'quniform': return self._parse_quniform(param_value) if param_type == 'qloguniform': param_value[:2] = np.log(param_value[:2]) return list(np.exp(self._parse_quniform(param_value))) raise RuntimeError("Not supported type: %s" % param_type)
Enumerate all possible combinations of all parameters para: {key1: [v11, v12, ...], key2: [v21, v22, ...], ...} return: {{key1: v11, key2: v21, ...}, {key1: v11, key2: v22, ...}, ...} def expand_parameters(self, para): ''' Enumerate all possible combinations of all parameters para: {key1: [v11, v12, ...], key2: [v21, v22, ...], ...} return: {{key1: v11, key2: v21, ...}, {key1: v11, key2: v22, ...}, ...} ''' if len(para) == 1: for key, values in para.items(): return list(map(lambda v: {key: v}, values)) key = list(para)[0] values = para.pop(key) rest_para = self.expand_parameters(para) ret_para = list() for val in values: for config in rest_para: config[key] = val ret_para.append(copy.deepcopy(config)) return ret_para
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 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 _params_tuple = convert_dict2tuple(_params) self.supplement_data[_params_tuple] = True logger.info("Successfully import data to grid search tuner.")
Log message into stdout def nni_log(log_type, log_message): '''Log message into stdout''' dt = datetime.now() print('[{0}] {1} {2}'.format(dt, log_type.value, log_message))
Write buffer data into logger/stdout def write(self, buf): ''' Write buffer data into logger/stdout ''' for line in buf.rstrip().splitlines(): self.orig_stdout.write(line.rstrip() + '\n') self.orig_stdout.flush() try: self.logger.log(self.log_level, line.rstrip()) except Exception as e: pass
Run the thread, logging everything. If the log_collection is 'none', the log content will not be enqueued def run(self): """Run the thread, logging everything. If the log_collection is 'none', the log content will not be enqueued """ for line in iter(self.pipeReader.readline, ''): self.orig_stdout.write(line.rstrip() + '\n') self.orig_stdout.flush() if self.log_collection == 'none': # If not match metrics, do not put the line into queue if not self.log_pattern.match(line): continue self.queue.put(line) self.pipeReader.close()
Extract scalar reward from trial result. Raises ------ RuntimeError Incorrect final result: the final result should be float/int, or a dict which has a key named "default" whose value is float/int. def extract_scalar_reward(value, scalar_key='default'): """ Extract scalar reward from trial result. Raises ------ RuntimeError Incorrect final result: the final result should be float/int, or a dict which has a key named "default" whose value is float/int. """ if isinstance(value, float) or isinstance(value, int): reward = value elif isinstance(value, dict) and scalar_key in value and isinstance(value[scalar_key], (float, int)): reward = value[scalar_key] else: raise RuntimeError('Incorrect final result: the final result should be float/int, or a dict which has a key named "default" whose value is float/int.') return reward
convert dict type to tuple to solve unhashable problem. def convert_dict2tuple(value): """ convert dict type to tuple to solve unhashable problem. """ if isinstance(value, dict): for _keys in value: value[_keys] = convert_dict2tuple(value[_keys]) return tuple(sorted(value.items())) else: return value
Initialize dispatcher logging configuration def init_dispatcher_logger(): """ Initialize dispatcher logging configuration""" logger_file_path = 'dispatcher.log' if dispatcher_env_vars.NNI_LOG_DIRECTORY is not None: logger_file_path = os.path.join(dispatcher_env_vars.NNI_LOG_DIRECTORY, logger_file_path) init_logger(logger_file_path, dispatcher_env_vars.NNI_LOG_LEVEL)
We opted for a single multidimensional KDE compared to the hierarchy of one-dimensional KDEs used in TPE. The dimensional is seperated by budget. This function sample a configuration from largest budget. Firstly we sample "num_samples" configurations, then prefer one with the largest l(x)/g(x). Parameters: ----------- info_dict: dict record the information of this configuration Returns ------- dict: new configuration named sample dict: info_dict, record the information of this configuration def sample_from_largest_budget(self, info_dict): """We opted for a single multidimensional KDE compared to the hierarchy of one-dimensional KDEs used in TPE. The dimensional is seperated by budget. This function sample a configuration from largest budget. Firstly we sample "num_samples" configurations, then prefer one with the largest l(x)/g(x). Parameters: ----------- info_dict: dict record the information of this configuration Returns ------- dict: new configuration named sample dict: info_dict, record the information of this configuration """ best = np.inf best_vector = None budget = max(self.kde_models.keys()) l = self.kde_models[budget]['good'].pdf g = self.kde_models[budget]['bad'].pdf minimize_me = lambda x: max(1e-32, g(x))/max(l(x), 1e-32) kde_good = self.kde_models[budget]['good'] kde_bad = self.kde_models[budget]['bad'] for i in range(self.num_samples): idx = np.random.randint(0, len(kde_good.data)) datum = kde_good.data[idx] vector = [] for m, bw, t in zip(datum, kde_good.bw, self.vartypes): bw = max(bw, self.min_bandwidth) if t == 0: bw = self.bw_factor*bw vector.append(sps.truncnorm.rvs(-m/bw, (1-m)/bw, loc=m, scale=bw)) else: if np.random.rand() < (1-bw): vector.append(int(m)) else: vector.append(np.random.randint(t)) val = minimize_me(vector) if not np.isfinite(val): logger.warning('sampled vector: %s has EI value %s'%(vector, val)) logger.warning("data in the KDEs:\n%s\n%s"%(kde_good.data, kde_bad.data)) logger.warning("bandwidth of the KDEs:\n%s\n%s"%(kde_good.bw, kde_bad.bw)) logger.warning("l(x) = %s"%(l(vector))) logger.warning("g(x) = %s"%(g(vector))) # right now, this happens because a KDE does not contain all values for a categorical parameter # this cannot be fixed with the statsmodels KDE, so for now, we are just going to evaluate this one # if the good_kde has a finite value, i.e. there is no config with that value in the bad kde, # so it shouldn't be terrible. if np.isfinite(l(vector)): best_vector = vector break if val < best: best = val best_vector = vector if best_vector is None: logger.debug("Sampling based optimization with %i samples failed -> using random configuration"%self.num_samples) sample = self.configspace.sample_configuration().get_dictionary() info_dict['model_based_pick'] = False else: logger.debug('best_vector: {}, {}, {}, {}'.format(best_vector, best, l(best_vector), g(best_vector))) for i, hp_value in enumerate(best_vector): if isinstance( self.configspace.get_hyperparameter( self.configspace.get_hyperparameter_by_idx(i) ), ConfigSpace.hyperparameters.CategoricalHyperparameter ): best_vector[i] = int(np.rint(best_vector[i])) sample = ConfigSpace.Configuration(self.configspace, vector=best_vector).get_dictionary() sample = ConfigSpace.util.deactivate_inactive_hyperparameters( configuration_space=self.configspace, configuration=sample) info_dict['model_based_pick'] = True return sample, info_dict
Function to sample a new configuration This function is called inside BOHB to query a new configuration Parameters: ----------- budget: float the budget for which this configuration is scheduled Returns ------- config return a valid configuration with parameters and budget def get_config(self, budget): """Function to sample a new configuration This function is called inside BOHB to query a new configuration Parameters: ----------- budget: float the budget for which this configuration is scheduled Returns ------- config return a valid configuration with parameters and budget """ logger.debug('start sampling a new configuration.') sample = None info_dict = {} # If no model is available, sample from prior # also mix in a fraction of random configs if len(self.kde_models.keys()) == 0 or np.random.rand() < self.random_fraction: sample = self.configspace.sample_configuration() info_dict['model_based_pick'] = False if sample is None: sample, info_dict= self.sample_from_largest_budget(info_dict) sample = ConfigSpace.util.deactivate_inactive_hyperparameters( configuration_space=self.configspace, configuration=sample.get_dictionary() ).get_dictionary() logger.debug('done sampling a new configuration.') sample['TRIAL_BUDGET'] = budget return sample
Function to register finished runs. Every time a run has finished, this function should be called to register it with the loss. Parameters: ----------- loss: float the loss of the parameters budget: float the budget of the parameters parameters: dict the parameters of this trial update_model: bool whether use this parameter to update BP model Returns ------- None def new_result(self, loss, budget, parameters, update_model=True): """ Function to register finished runs. Every time a run has finished, this function should be called to register it with the loss. Parameters: ----------- loss: float the loss of the parameters budget: float the budget of the parameters parameters: dict the parameters of this trial update_model: bool whether use this parameter to update BP model Returns ------- None """ if loss is None: # One could skip crashed results, but we decided # assign a +inf loss and count them as bad configurations loss = np.inf if budget not in self.configs.keys(): self.configs[budget] = [] self.losses[budget] = [] # skip model building if we already have a bigger model if max(list(self.kde_models.keys()) + [-np.inf]) > budget: return # We want to get a numerical representation of the configuration in the original space conf = ConfigSpace.Configuration(self.configspace, parameters) self.configs[budget].append(conf.get_array()) self.losses[budget].append(loss) # skip model building: # a) if not enough points are available if len(self.configs[budget]) <= self.min_points_in_model - 1: logger.debug("Only %i run(s) for budget %f available, need more than %s \ -> can't build model!"%(len(self.configs[budget]), budget, self.min_points_in_model+1)) return # b) during warnm starting when we feed previous results in and only update once if not update_model: return train_configs = np.array(self.configs[budget]) train_losses = np.array(self.losses[budget]) n_good = max(self.min_points_in_model, (self.top_n_percent * train_configs.shape[0])//100) n_bad = max(self.min_points_in_model, ((100-self.top_n_percent)*train_configs.shape[0])//100) # Refit KDE for the current budget idx = np.argsort(train_losses) train_data_good = self.impute_conditional_data(train_configs[idx[:n_good]]) train_data_bad = self.impute_conditional_data(train_configs[idx[n_good:n_good+n_bad]]) if train_data_good.shape[0] <= train_data_good.shape[1]: return if train_data_bad.shape[0] <= train_data_bad.shape[1]: return #more expensive crossvalidation method #bw_estimation = 'cv_ls' # quick rule of thumb bw_estimation = 'normal_reference' bad_kde = sm.nonparametric.KDEMultivariate(data=train_data_bad, var_type=self.kde_vartypes, bw=bw_estimation) good_kde = sm.nonparametric.KDEMultivariate(data=train_data_good, var_type=self.kde_vartypes, bw=bw_estimation) bad_kde.bw = np.clip(bad_kde.bw, self.min_bandwidth, None) good_kde.bw = np.clip(good_kde.bw, self.min_bandwidth, None) self.kde_models[budget] = { 'good': good_kde, 'bad' : bad_kde } # update probs for the categorical parameters for later sampling logger.debug('done building a new model for budget %f based on %i/%i split\nBest loss for this budget:%f\n' %(budget, n_good, n_bad, np.min(train_losses)))
Check the search space is valid: only contains 'choice' type Parameters ---------- search_space : dict def is_valid(self, search_space): """ Check the search space is valid: only contains 'choice' type Parameters ---------- search_space : dict """ if not len(search_space) == 1: raise RuntimeError('BatchTuner only supprt one combined-paramreters key.') for param in search_space: param_type = search_space[param][TYPE] if not param_type == CHOICE: raise RuntimeError('BatchTuner only supprt one combined-paramreters type is choice.') else: if isinstance(search_space[param][VALUE], list): return search_space[param][VALUE] raise RuntimeError('The combined-paramreters value in BatchTuner is not a list.') return None
Returns a dict of trial (hyper-)parameters, as a serializable object. Parameters ---------- parameter_id : int def generate_parameters(self, parameter_id): """Returns a dict of trial (hyper-)parameters, as a serializable object. Parameters ---------- parameter_id : int """ self.count +=1 if self.count>len(self.values)-1: raise nni.NoMoreTrialError('no more parameters now.') return self.values[self.count]
Applies layer normalization. Args: inputs: A tensor with 2 or more dimensions, where the first dimension has `batch_size`. epsilon: A floating number. A very small number for preventing ZeroDivision Error. scope: Optional scope for `variable_scope`. reuse: Boolean, whether to reuse the weights of a previous layer by the same name. Returns: A tensor with the same shape and data dtype as `inputs`. def normalize(inputs, epsilon=1e-8, scope="ln"): '''Applies layer normalization. Args: inputs: A tensor with 2 or more dimensions, where the first dimension has `batch_size`. epsilon: A floating number. A very small number for preventing ZeroDivision Error. scope: Optional scope for `variable_scope`. reuse: Boolean, whether to reuse the weights of a previous layer by the same name. Returns: A tensor with the same shape and data dtype as `inputs`. ''' with tf.variable_scope(scope): inputs_shape = inputs.get_shape() params_shape = inputs_shape[-1:] mean, variance = tf.nn.moments(inputs, [-1], keep_dims=True) beta = tf.Variable(tf.zeros(params_shape)) gamma = tf.Variable(tf.ones(params_shape)) normalized = (inputs - mean) / ((variance + epsilon) ** (.5)) outputs = gamma * normalized + beta return outputs
Applies multihead attention. Args: queries: A 3d tensor with shape of [N, T_q, C_q]. keys: A 3d tensor with shape of [N, T_k, C_k]. num_units: A cdscalar. Attention size. dropout_rate: A floating point number. is_training: Boolean. Controller of mechanism for dropout. causality: Boolean. If true, units that reference the future are masked. num_heads: An int. Number of heads. scope: Optional scope for `variable_scope`. reuse: Boolean, whether to reuse the weights of a previous layer by the same name. Returns A 3d tensor with shape of (N, T_q, C) def multihead_attention(queries, keys, scope="multihead_attention", num_units=None, num_heads=4, dropout_rate=0, is_training=True, causality=False): '''Applies multihead attention. Args: queries: A 3d tensor with shape of [N, T_q, C_q]. keys: A 3d tensor with shape of [N, T_k, C_k]. num_units: A cdscalar. Attention size. dropout_rate: A floating point number. is_training: Boolean. Controller of mechanism for dropout. causality: Boolean. If true, units that reference the future are masked. num_heads: An int. Number of heads. scope: Optional scope for `variable_scope`. reuse: Boolean, whether to reuse the weights of a previous layer by the same name. Returns A 3d tensor with shape of (N, T_q, C) ''' global look5 with tf.variable_scope(scope): # Set the fall back option for num_units if num_units is None: num_units = queries.get_shape().as_list()[-1] Q_ = [] K_ = [] V_ = [] for head_i in range(num_heads): Q = tf.layers.dense(queries, num_units / num_heads, activation=tf.nn.relu, name='Query' + str(head_i)) # (N, T_q, C) K = tf.layers.dense(keys, num_units / num_heads, activation=tf.nn.relu, name='Key' + str(head_i)) # (N, T_k, C) V = tf.layers.dense(keys, num_units / num_heads, activation=tf.nn.relu, name='Value' + str(head_i)) # (N, T_k, C) Q_.append(Q) K_.append(K) V_.append(V) # Split and concat Q_ = tf.concat(Q_, axis=0) # (h*N, T_q, C/h) K_ = tf.concat(K_, axis=0) # (h*N, T_k, C/h) V_ = tf.concat(V_, axis=0) # (h*N, T_k, C/h) # Multiplication outputs = tf.matmul(Q_, tf.transpose(K_, [0, 2, 1])) # (h*N, T_q, T_k) # Scale outputs = outputs / (K_.get_shape().as_list()[-1] ** 0.5) # Key Masking key_masks = tf.sign(tf.abs(tf.reduce_sum(keys, axis=-1))) # (N, T_k) key_masks = tf.tile(key_masks, [num_heads, 1]) # (h*N, T_k) key_masks = tf.tile(tf.expand_dims(key_masks, 1), [1, tf.shape(queries)[1], 1]) # (h*N, T_q, T_k) paddings = tf.ones_like(outputs) * (-2 ** 32 + 1) outputs = tf.where(tf.equal(key_masks, 0), paddings, outputs) # (h*N, T_q, T_k) # Causality = Future blinding if causality: diag_vals = tf.ones_like(outputs[0, :, :]) # (T_q, T_k) tril = tf.contrib.linalg.LinearOperatorTriL( diag_vals).to_dense() # (T_q, T_k) masks = tf.tile(tf.expand_dims(tril, 0), [tf.shape(outputs)[0], 1, 1]) # (h*N, T_q, T_k) paddings = tf.ones_like(masks) * (-2 ** 32 + 1) outputs = tf.where(tf.equal(masks, 0), paddings, outputs) # (h*N, T_q, T_k) # Activation look5 = outputs outputs = tf.nn.softmax(outputs) # (h*N, T_q, T_k) # Query Masking query_masks = tf.sign( tf.abs(tf.reduce_sum(queries, axis=-1))) # (N, T_q) query_masks = tf.tile(query_masks, [num_heads, 1]) # (h*N, T_q) query_masks = tf.tile(tf.expand_dims( query_masks, -1), [1, 1, tf.shape(keys)[1]]) # (h*N, T_q, T_k) outputs *= query_masks # broadcasting. (N, T_q, C) # Dropouts outputs = dropout(outputs, dropout_rate, is_training) # Weighted sum outputs = tf.matmul(outputs, V_) # ( h*N, T_q, C/h) # Restore shape outputs = tf.concat(tf.split(outputs, num_heads, axis=0), axis=2) # (N, T_q, C) # Residual connection if queries.get_shape().as_list()[-1] == num_units: outputs += queries # Normalize outputs = normalize(outputs, scope=scope) # (N, T_q, C) return outputs
Return positinal embedding. def positional_encoding(inputs, num_units=None, zero_pad=True, scale=True, scope="positional_encoding", reuse=None): ''' Return positinal embedding. ''' Shape = tf.shape(inputs) N = Shape[0] T = Shape[1] num_units = Shape[2] with tf.variable_scope(scope, reuse=reuse): position_ind = tf.tile(tf.expand_dims(tf.range(T), 0), [N, 1]) # First part of the PE function: sin and cos argument # Second part, apply the cosine to even columns and sin to odds. X = tf.expand_dims(tf.cast(tf.range(T), tf.float32), axis=1) Y = tf.expand_dims( tf.cast(10000 ** -(2 * tf.range(num_units) / num_units), tf.float32), axis=0) h1 = tf.cast((tf.range(num_units) + 1) % 2, tf.float32) h2 = tf.cast((tf.range(num_units) % 2), tf.float32) position_enc = tf.multiply(X, Y) position_enc = tf.sin(position_enc) * tf.multiply(tf.ones_like(X), h1) + \ tf.cos(position_enc) * tf.multiply(tf.ones_like(X), h2) # Convert to a tensor lookup_table = position_enc if zero_pad: lookup_table = tf.concat((tf.zeros(shape=[1, num_units]), lookup_table[1:, :]), 0) outputs = tf.nn.embedding_lookup(lookup_table, position_ind) if scale: outputs = outputs * tf.sqrt(tf.cast(num_units, tf.float32)) return outputs
Point-wise feed forward net. Args: inputs: A 3d tensor with shape of [N, T, C]. num_units: A list of two integers. scope: Optional scope for `variable_scope`. reuse: Boolean, whether to reuse the weights of a previous layer by the same name. Returns: A 3d tensor with the same shape and dtype as inputs def feedforward(inputs, num_units, scope="multihead_attention"): '''Point-wise feed forward net. Args: inputs: A 3d tensor with shape of [N, T, C]. num_units: A list of two integers. scope: Optional scope for `variable_scope`. reuse: Boolean, whether to reuse the weights of a previous layer by the same name. Returns: A 3d tensor with the same shape and dtype as inputs ''' with tf.variable_scope(scope): # Inner layer params = {"inputs": inputs, "filters": num_units[0], "kernel_size": 1, "activation": tf.nn.relu, "use_bias": True} outputs = tf.layers.conv1d(**params) # Readout layer params = {"inputs": outputs, "filters": num_units[1], "kernel_size": 1, "activation": None, "use_bias": True} outputs = tf.layers.conv1d(**params) # Residual connection outputs += inputs # Normalize outputs = normalize(outputs) return outputs
Generate search space. Return a serializable search space object. module_name: name of the module (str) code: user code (str) def generate(module_name, code): """Generate search space. Return a serializable search space object. module_name: name of the module (str) code: user code (str) """ try: ast_tree = ast.parse(code) except Exception: raise RuntimeError('Bad Python code') visitor = SearchSpaceGenerator(module_name) try: visitor.visit(ast_tree) except AssertionError as exc: raise RuntimeError('%d: %s' % (visitor.last_line, exc.args[0])) return visitor.search_space, astor.to_source(ast_tree)
Call rest put method def rest_put(url, data, timeout, show_error=False): '''Call rest put method''' try: response = requests.put(url, headers={'Accept': 'application/json', 'Content-Type': 'application/json'},\ data=data, timeout=timeout) return response except Exception as exception: if show_error: print_error(exception) return None
Call rest post method def rest_post(url, data, timeout, show_error=False): '''Call rest post method''' try: response = requests.post(url, headers={'Accept': 'application/json', 'Content-Type': 'application/json'},\ data=data, timeout=timeout) return response except Exception as exception: if show_error: print_error(exception) return None
Call rest get method def rest_get(url, timeout, show_error=False): '''Call rest get method''' try: response = requests.get(url, timeout=timeout) return response except Exception as exception: if show_error: print_error(exception) return None
Call rest delete method def rest_delete(url, timeout, show_error=False): '''Call rest delete method''' try: response = requests.delete(url, timeout=timeout) return response except Exception as exception: if show_error: print_error(exception) return None
Check if restful server is ready def check_rest_server(rest_port): '''Check if restful server is ready''' retry_count = 5 for _ in range(retry_count): response = rest_get(check_status_url(rest_port), REST_TIME_OUT) if response: if response.status_code == 200: return True, response else: return False, response else: time.sleep(3) return False, response
Check if restful server is ready, only check once def check_rest_server_quick(rest_port): '''Check if restful server is ready, only check once''' response = rest_get(check_status_url(rest_port), 5) if response and response.status_code == 200: return True, response return False, None
Vapor pressure model Parameters ---------- x: int a: float b: float c: float Returns ------- float np.exp(a+b/x+c*np.log(x)) def vap(x, a, b, c): """Vapor pressure model Parameters ---------- x: int a: float b: float c: float Returns ------- float np.exp(a+b/x+c*np.log(x)) """ return np.exp(a+b/x+c*np.log(x))
logx linear Parameters ---------- x: int a: float b: float Returns ------- float a * np.log(x) + b def logx_linear(x, a, b): """logx linear Parameters ---------- x: int a: float b: float Returns ------- float a * np.log(x) + b """ x = np.log(x) return a*x + b
dr hill zero background Parameters ---------- x: int theta: float eta: float kappa: float Returns ------- float (theta* x**eta) / (kappa**eta + x**eta) def dr_hill_zero_background(x, theta, eta, kappa): """dr hill zero background Parameters ---------- x: int theta: float eta: float kappa: float Returns ------- float (theta* x**eta) / (kappa**eta + x**eta) """ return (theta* x**eta) / (kappa**eta + x**eta)
logistic power Parameters ---------- x: int a: float b: float c: float Returns ------- float a/(1.+(x/np.exp(b))**c) def log_power(x, a, b, c): """"logistic power Parameters ---------- x: int a: float b: float c: float Returns ------- float a/(1.+(x/np.exp(b))**c) """ return a/(1.+(x/np.exp(b))**c)
pow4 Parameters ---------- x: int alpha: float a: float b: float c: float Returns ------- float c - (a*x+b)**-alpha def pow4(x, alpha, a, b, c): """pow4 Parameters ---------- x: int alpha: float a: float b: float c: float Returns ------- float c - (a*x+b)**-alpha """ return c - (a*x+b)**-alpha
Morgan-Mercer-Flodin http://www.pisces-conservation.com/growthhelp/index.html?morgan_mercer_floden.htm Parameters ---------- x: int alpha: float beta: float kappa: float delta: float Returns ------- float alpha - (alpha - beta) / (1. + (kappa * x)**delta) def mmf(x, alpha, beta, kappa, delta): """Morgan-Mercer-Flodin http://www.pisces-conservation.com/growthhelp/index.html?morgan_mercer_floden.htm Parameters ---------- x: int alpha: float beta: float kappa: float delta: float Returns ------- float alpha - (alpha - beta) / (1. + (kappa * x)**delta) """ return alpha - (alpha - beta) / (1. + (kappa * x)**delta)
exp4 Parameters ---------- x: int c: float a: float b: float alpha: float Returns ------- float c - np.exp(-a*(x**alpha)+b) def exp4(x, c, a, b, alpha): """exp4 Parameters ---------- x: int c: float a: float b: float alpha: float Returns ------- float c - np.exp(-a*(x**alpha)+b) """ return c - np.exp(-a*(x**alpha)+b)
Weibull model http://www.pisces-conservation.com/growthhelp/index.html?morgan_mercer_floden.htm Parameters ---------- x: int alpha: float beta: float kappa: float delta: float Returns ------- float alpha - (alpha - beta) * np.exp(-(kappa * x)**delta) def weibull(x, alpha, beta, kappa, delta): """Weibull model http://www.pisces-conservation.com/growthhelp/index.html?morgan_mercer_floden.htm Parameters ---------- x: int alpha: float beta: float kappa: float delta: float Returns ------- float alpha - (alpha - beta) * np.exp(-(kappa * x)**delta) """ return alpha - (alpha - beta) * np.exp(-(kappa * x)**delta)
http://www.pisces-conservation.com/growthhelp/janoschek.htm Parameters ---------- x: int a: float beta: float k: float delta: float Returns ------- float a - (a - beta) * np.exp(-k*x**delta) def janoschek(x, a, beta, k, delta): """http://www.pisces-conservation.com/growthhelp/janoschek.htm Parameters ---------- x: int a: float beta: float k: float delta: float Returns ------- float a - (a - beta) * np.exp(-k*x**delta) """ return a - (a - beta) * np.exp(-k*x**delta)
Definite the arguments users need to follow and input def parse_args(): '''Definite the arguments users need to follow and input''' parser = argparse.ArgumentParser(prog='nnictl', description='use nnictl command to control nni experiments') parser.add_argument('--version', '-v', action='store_true') parser.set_defaults(func=nni_info) # create subparsers for args with sub values subparsers = parser.add_subparsers() # parse start command parser_start = subparsers.add_parser('create', help='create a new experiment') parser_start.add_argument('--config', '-c', required=True, dest='config', help='the path of yaml config file') parser_start.add_argument('--port', '-p', default=DEFAULT_REST_PORT, dest='port', help='the port of restful server') parser_start.add_argument('--debug', '-d', action='store_true', help=' set debug mode') parser_start.set_defaults(func=create_experiment) # parse resume command parser_resume = subparsers.add_parser('resume', help='resume a new experiment') parser_resume.add_argument('id', nargs='?', help='The id of the experiment you want to resume') parser_resume.add_argument('--port', '-p', default=DEFAULT_REST_PORT, dest='port', help='the port of restful server') parser_resume.add_argument('--debug', '-d', action='store_true', help=' set debug mode') parser_resume.set_defaults(func=resume_experiment) # parse update command parser_updater = subparsers.add_parser('update', help='update the experiment') #add subparsers for parser_updater parser_updater_subparsers = parser_updater.add_subparsers() parser_updater_searchspace = parser_updater_subparsers.add_parser('searchspace', help='update searchspace') parser_updater_searchspace.add_argument('id', nargs='?', help='the id of experiment') parser_updater_searchspace.add_argument('--filename', '-f', required=True) parser_updater_searchspace.set_defaults(func=update_searchspace) parser_updater_concurrency = parser_updater_subparsers.add_parser('concurrency', help='update concurrency') parser_updater_concurrency.add_argument('id', nargs='?', help='the id of experiment') parser_updater_concurrency.add_argument('--value', '-v', required=True) parser_updater_concurrency.set_defaults(func=update_concurrency) parser_updater_duration = parser_updater_subparsers.add_parser('duration', help='update duration') parser_updater_duration.add_argument('id', nargs='?', help='the id of experiment') parser_updater_duration.add_argument('--value', '-v', required=True, help='the unit of time should in {\'s\', \'m\', \'h\', \'d\'}') parser_updater_duration.set_defaults(func=update_duration) parser_updater_trialnum = parser_updater_subparsers.add_parser('trialnum', help='update maxtrialnum') parser_updater_trialnum.add_argument('--id', '-i', dest='id', help='the id of experiment') parser_updater_trialnum.add_argument('--value', '-v', required=True) parser_updater_trialnum.set_defaults(func=update_trialnum) #parse stop command parser_stop = subparsers.add_parser('stop', help='stop the experiment') parser_stop.add_argument('id', nargs='?', help='the id of experiment, use \'all\' to stop all running experiments') parser_stop.set_defaults(func=stop_experiment) #parse trial command parser_trial = subparsers.add_parser('trial', help='get trial information') #add subparsers for parser_trial parser_trial_subparsers = parser_trial.add_subparsers() parser_trial_ls = parser_trial_subparsers.add_parser('ls', help='list trial jobs') parser_trial_ls.add_argument('id', nargs='?', help='the id of experiment') parser_trial_ls.set_defaults(func=trial_ls) parser_trial_kill = parser_trial_subparsers.add_parser('kill', help='kill trial jobs') parser_trial_kill.add_argument('id', nargs='?', help='the id of experiment') parser_trial_kill.add_argument('--trial_id', '-T', required=True, dest='trial_id', help='the id of trial to be killed') parser_trial_kill.set_defaults(func=trial_kill) #parse experiment command parser_experiment = subparsers.add_parser('experiment', help='get experiment information') #add subparsers for parser_experiment parser_experiment_subparsers = parser_experiment.add_subparsers() parser_experiment_show = parser_experiment_subparsers.add_parser('show', help='show the information of experiment') parser_experiment_show.add_argument('id', nargs='?', help='the id of experiment') parser_experiment_show.set_defaults(func=list_experiment) parser_experiment_status = parser_experiment_subparsers.add_parser('status', help='show the status of experiment') parser_experiment_status.add_argument('id', nargs='?', help='the id of experiment') parser_experiment_status.set_defaults(func=experiment_status) parser_experiment_list = parser_experiment_subparsers.add_parser('list', help='list all of running experiment ids') parser_experiment_list.add_argument('all', nargs='?', help='list all of experiments') parser_experiment_list.set_defaults(func=experiment_list) #import tuning data parser_import_data = parser_experiment_subparsers.add_parser('import', help='import additional data') parser_import_data.add_argument('id', nargs='?', help='the id of experiment') parser_import_data.add_argument('--filename', '-f', required=True) parser_import_data.set_defaults(func=import_data) #export trial data parser_trial_export = parser_experiment_subparsers.add_parser('export', help='export trial job results to csv or json') parser_trial_export.add_argument('id', nargs='?', help='the id of experiment') parser_trial_export.add_argument('--type', '-t', choices=['json', 'csv'], required=True, dest='type', help='target file type') parser_trial_export.add_argument('--filename', '-f', required=True, dest='path', help='target file path') parser_trial_export.set_defaults(func=export_trials_data) #TODO:finish webui function #parse board command parser_webui = subparsers.add_parser('webui', help='get web ui information') #add subparsers for parser_board parser_webui_subparsers = parser_webui.add_subparsers() parser_webui_url = parser_webui_subparsers.add_parser('url', help='show the url of web ui') parser_webui_url.add_argument('id', nargs='?', help='the id of experiment') parser_webui_url.set_defaults(func=webui_url) #parse config command parser_config = subparsers.add_parser('config', help='get config information') parser_config_subparsers = parser_config.add_subparsers() parser_config_show = parser_config_subparsers.add_parser('show', help='show the information of config') parser_config_show.add_argument('id', nargs='?', help='the id of experiment') parser_config_show.set_defaults(func=get_config) #parse log command parser_log = subparsers.add_parser('log', help='get log information') # add subparsers for parser_log parser_log_subparsers = parser_log.add_subparsers() parser_log_stdout = parser_log_subparsers.add_parser('stdout', help='get stdout information') parser_log_stdout.add_argument('id', nargs='?', help='the id of experiment') parser_log_stdout.add_argument('--tail', '-T', dest='tail', type=int, help='get tail -100 content of stdout') parser_log_stdout.add_argument('--head', '-H', dest='head', type=int, help='get head -100 content of stdout') parser_log_stdout.add_argument('--path', action='store_true', default=False, help='get the path of stdout file') parser_log_stdout.set_defaults(func=log_stdout) parser_log_stderr = parser_log_subparsers.add_parser('stderr', help='get stderr information') parser_log_stderr.add_argument('id', nargs='?', help='the id of experiment') parser_log_stderr.add_argument('--tail', '-T', dest='tail', type=int, help='get tail -100 content of stderr') parser_log_stderr.add_argument('--head', '-H', dest='head', type=int, help='get head -100 content of stderr') parser_log_stderr.add_argument('--path', action='store_true', default=False, help='get the path of stderr file') parser_log_stderr.set_defaults(func=log_stderr) parser_log_trial = parser_log_subparsers.add_parser('trial', help='get trial log path') parser_log_trial.add_argument('id', nargs='?', help='the id of experiment') parser_log_trial.add_argument('--trial_id', '-T', dest='trial_id', help='find trial log path by id') parser_log_trial.set_defaults(func=log_trial) #parse package command parser_package = subparsers.add_parser('package', help='control nni tuner and assessor packages') # add subparsers for parser_package parser_package_subparsers = parser_package.add_subparsers() parser_package_install = parser_package_subparsers.add_parser('install', help='install packages') parser_package_install.add_argument('--name', '-n', dest='name', help='package name to be installed') parser_package_install.set_defaults(func=package_install) parser_package_show = parser_package_subparsers.add_parser('show', help='show the information of packages') parser_package_show.set_defaults(func=package_show) #parse tensorboard command parser_tensorboard = subparsers.add_parser('tensorboard', help='manage tensorboard') parser_tensorboard_subparsers = parser_tensorboard.add_subparsers() parser_tensorboard_start = parser_tensorboard_subparsers.add_parser('start', help='start tensorboard') parser_tensorboard_start.add_argument('id', nargs='?', help='the id of experiment') parser_tensorboard_start.add_argument('--trial_id', '-T', dest='trial_id', help='the id of trial') parser_tensorboard_start.add_argument('--port', dest='port', default=6006, help='the port to start tensorboard') parser_tensorboard_start.set_defaults(func=start_tensorboard) parser_tensorboard_start = parser_tensorboard_subparsers.add_parser('stop', help='stop tensorboard') parser_tensorboard_start.add_argument('id', nargs='?', help='the id of experiment') parser_tensorboard_start.set_defaults(func=stop_tensorboard) #parse top command parser_top = subparsers.add_parser('top', help='monitor the experiment') parser_top.add_argument('--time', '-t', dest='time', type=int, default=3, help='the time interval to update the experiment status, ' \ 'the unit is second') parser_top.set_defaults(func=monitor_experiment) args = parser.parse_args() args.func(args)
generate stdout and stderr log path def get_log_path(config_file_name): '''generate stdout and stderr log path''' stdout_full_path = os.path.join(NNICTL_HOME_DIR, config_file_name, 'stdout') stderr_full_path = os.path.join(NNICTL_HOME_DIR, config_file_name, 'stderr') return stdout_full_path, stderr_full_path
print log information def print_log_content(config_file_name): '''print log information''' stdout_full_path, stderr_full_path = get_log_path(config_file_name) print_normal(' Stdout:') print(check_output_command(stdout_full_path)) print('\n\n') print_normal(' Stderr:') print(check_output_command(stderr_full_path))
Find nni lib from the following locations in order Return nni root directory if it exists def get_nni_installation_path(): ''' Find nni lib from the following locations in order Return nni root directory if it exists ''' def try_installation_path_sequentially(*sitepackages): '''Try different installation path sequentially util nni is found. Return None if nothing is found ''' def _generate_installation_path(sitepackages_path): python_dir = get_python_dir(sitepackages_path) entry_file = os.path.join(python_dir, 'nni', 'main.js') if os.path.isfile(entry_file): return python_dir return None for sitepackage in sitepackages: python_dir = _generate_installation_path(sitepackage) if python_dir: return python_dir return None if os.getenv('VIRTUAL_ENV'): # if 'virtualenv' package is used, `site` has not attr getsitepackages, so we will instead use VIRTUAL_ENV # Note that conda venv will not have VIRTUAL_ENV python_dir = os.getenv('VIRTUAL_ENV') else: python_sitepackage = site.getsitepackages()[0] # If system-wide python is used, we will give priority to using `local sitepackage`--"usersitepackages()" given that nni exists there if python_sitepackage.startswith('/usr') or python_sitepackage.startswith('/Library'): python_dir = try_installation_path_sequentially(site.getusersitepackages(), site.getsitepackages()[0]) else: python_dir = try_installation_path_sequentially(site.getsitepackages()[0], site.getusersitepackages()) if python_dir: entry_file = os.path.join(python_dir, 'nni', 'main.js') if os.path.isfile(entry_file): return os.path.join(python_dir, 'nni') print_error('Fail to find nni under python library') exit(1)
Run nni manager process def start_rest_server(port, platform, mode, config_file_name, experiment_id=None, log_dir=None, log_level=None): '''Run nni manager process''' nni_config = Config(config_file_name) if detect_port(port): print_error('Port %s is used by another process, please reset the port!\n' \ 'You could use \'nnictl create --help\' to get help information' % port) exit(1) if (platform != 'local') and detect_port(int(port) + 1): print_error('PAI mode need an additional adjacent port %d, and the port %d is used by another process!\n' \ 'You could set another port to start experiment!\n' \ 'You could use \'nnictl create --help\' to get help information' % ((int(port) + 1), (int(port) + 1))) exit(1) print_normal('Starting restful server...') entry_dir = get_nni_installation_path() entry_file = os.path.join(entry_dir, 'main.js') node_command = 'node' if sys.platform == 'win32': node_command = os.path.join(entry_dir[:-3], 'Scripts', 'node.exe') cmds = [node_command, entry_file, '--port', str(port), '--mode', platform, '--start_mode', mode] if log_dir is not None: cmds += ['--log_dir', log_dir] if log_level is not None: cmds += ['--log_level', log_level] if mode == 'resume': cmds += ['--experiment_id', experiment_id] stdout_full_path, stderr_full_path = get_log_path(config_file_name) stdout_file = open(stdout_full_path, 'a+') stderr_file = open(stderr_full_path, 'a+') time_now = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) #add time information in the header of log files log_header = LOG_HEADER % str(time_now) stdout_file.write(log_header) stderr_file.write(log_header) if sys.platform == 'win32': from subprocess import CREATE_NEW_PROCESS_GROUP process = Popen(cmds, cwd=entry_dir, stdout=stdout_file, stderr=stderr_file, creationflags=CREATE_NEW_PROCESS_GROUP) else: process = Popen(cmds, cwd=entry_dir, stdout=stdout_file, stderr=stderr_file) return process, str(time_now)
set trial configuration def set_trial_config(experiment_config, port, config_file_name): '''set trial configuration''' request_data = dict() request_data['trial_config'] = experiment_config['trial'] response = rest_put(cluster_metadata_url(port), json.dumps(request_data), REST_TIME_OUT) if check_response(response): return True else: print('Error message is {}'.format(response.text)) _, stderr_full_path = get_log_path(config_file_name) if response: with open(stderr_full_path, 'a+') as fout: fout.write(json.dumps(json.loads(response.text), indent=4, sort_keys=True, separators=(',', ':'))) return False
set local configuration def set_local_config(experiment_config, port, config_file_name): '''set local configuration''' #set machine_list request_data = dict() if experiment_config.get('localConfig'): request_data['local_config'] = experiment_config['localConfig'] if request_data['local_config'] and request_data['local_config'].get('gpuIndices') \ and isinstance(request_data['local_config'].get('gpuIndices'), int): request_data['local_config']['gpuIndices'] = str(request_data['local_config'].get('gpuIndices')) response = rest_put(cluster_metadata_url(port), json.dumps(request_data), REST_TIME_OUT) err_message = '' if not response or not check_response(response): if response is not None: err_message = response.text _, stderr_full_path = get_log_path(config_file_name) with open(stderr_full_path, 'a+') as fout: fout.write(json.dumps(json.loads(err_message), indent=4, sort_keys=True, separators=(',', ':'))) return False, err_message return set_trial_config(experiment_config, port, config_file_name)
Call setClusterMetadata to pass trial def set_remote_config(experiment_config, port, config_file_name): '''Call setClusterMetadata to pass trial''' #set machine_list request_data = dict() request_data['machine_list'] = experiment_config['machineList'] if request_data['machine_list']: for i in range(len(request_data['machine_list'])): if isinstance(request_data['machine_list'][i].get('gpuIndices'), int): request_data['machine_list'][i]['gpuIndices'] = str(request_data['machine_list'][i].get('gpuIndices')) response = rest_put(cluster_metadata_url(port), json.dumps(request_data), REST_TIME_OUT) err_message = '' if not response or not check_response(response): if response is not None: err_message = response.text _, stderr_full_path = get_log_path(config_file_name) with open(stderr_full_path, 'a+') as fout: fout.write(json.dumps(json.loads(err_message), indent=4, sort_keys=True, separators=(',', ':'))) return False, err_message result, message = setNNIManagerIp(experiment_config, port, config_file_name) if not result: return result, message #set trial_config return set_trial_config(experiment_config, port, config_file_name), err_message
set nniManagerIp def setNNIManagerIp(experiment_config, port, config_file_name): '''set nniManagerIp''' if experiment_config.get('nniManagerIp') is None: return True, None ip_config_dict = dict() ip_config_dict['nni_manager_ip'] = { 'nniManagerIp' : experiment_config['nniManagerIp'] } response = rest_put(cluster_metadata_url(port), json.dumps(ip_config_dict), REST_TIME_OUT) err_message = None if not response or not response.status_code == 200: if response is not None: err_message = response.text _, stderr_full_path = get_log_path(config_file_name) with open(stderr_full_path, 'a+') as fout: fout.write(json.dumps(json.loads(err_message), indent=4, sort_keys=True, separators=(',', ':'))) return False, err_message return True, None
set kubeflow configuration def set_frameworkcontroller_config(experiment_config, port, config_file_name): '''set kubeflow configuration''' frameworkcontroller_config_data = dict() frameworkcontroller_config_data['frameworkcontroller_config'] = experiment_config['frameworkcontrollerConfig'] response = rest_put(cluster_metadata_url(port), json.dumps(frameworkcontroller_config_data), REST_TIME_OUT) err_message = None if not response or not response.status_code == 200: if response is not None: err_message = response.text _, stderr_full_path = get_log_path(config_file_name) with open(stderr_full_path, 'a+') as fout: fout.write(json.dumps(json.loads(err_message), indent=4, sort_keys=True, separators=(',', ':'))) return False, err_message result, message = setNNIManagerIp(experiment_config, port, config_file_name) if not result: return result, message #set trial_config return set_trial_config(experiment_config, port, config_file_name), err_message
Call startExperiment (rest POST /experiment) with yaml file content def set_experiment(experiment_config, mode, port, config_file_name): '''Call startExperiment (rest POST /experiment) with yaml file content''' request_data = dict() request_data['authorName'] = experiment_config['authorName'] request_data['experimentName'] = experiment_config['experimentName'] request_data['trialConcurrency'] = experiment_config['trialConcurrency'] request_data['maxExecDuration'] = experiment_config['maxExecDuration'] request_data['maxTrialNum'] = experiment_config['maxTrialNum'] request_data['searchSpace'] = experiment_config.get('searchSpace') request_data['trainingServicePlatform'] = experiment_config.get('trainingServicePlatform') if experiment_config.get('description'): request_data['description'] = experiment_config['description'] if experiment_config.get('multiPhase'): request_data['multiPhase'] = experiment_config.get('multiPhase') if experiment_config.get('multiThread'): request_data['multiThread'] = experiment_config.get('multiThread') if experiment_config.get('advisor'): request_data['advisor'] = experiment_config['advisor'] else: request_data['tuner'] = experiment_config['tuner'] if 'assessor' in experiment_config: request_data['assessor'] = experiment_config['assessor'] #debug mode should disable version check if experiment_config.get('debug') is not None: request_data['versionCheck'] = not experiment_config.get('debug') if experiment_config.get('logCollection'): request_data['logCollection'] = experiment_config.get('logCollection') request_data['clusterMetaData'] = [] if experiment_config['trainingServicePlatform'] == 'local': request_data['clusterMetaData'].append( {'key':'codeDir', 'value':experiment_config['trial']['codeDir']}) request_data['clusterMetaData'].append( {'key': 'command', 'value': experiment_config['trial']['command']}) elif experiment_config['trainingServicePlatform'] == 'remote': request_data['clusterMetaData'].append( {'key': 'machine_list', 'value': experiment_config['machineList']}) request_data['clusterMetaData'].append( {'key': 'trial_config', 'value': experiment_config['trial']}) elif experiment_config['trainingServicePlatform'] == 'pai': request_data['clusterMetaData'].append( {'key': 'pai_config', 'value': experiment_config['paiConfig']}) request_data['clusterMetaData'].append( {'key': 'trial_config', 'value': experiment_config['trial']}) elif experiment_config['trainingServicePlatform'] == 'kubeflow': request_data['clusterMetaData'].append( {'key': 'kubeflow_config', 'value': experiment_config['kubeflowConfig']}) request_data['clusterMetaData'].append( {'key': 'trial_config', 'value': experiment_config['trial']}) elif experiment_config['trainingServicePlatform'] == 'frameworkcontroller': request_data['clusterMetaData'].append( {'key': 'frameworkcontroller_config', 'value': experiment_config['frameworkcontrollerConfig']}) request_data['clusterMetaData'].append( {'key': 'trial_config', 'value': experiment_config['trial']}) response = rest_post(experiment_url(port), json.dumps(request_data), REST_TIME_OUT, show_error=True) if check_response(response): return response else: _, stderr_full_path = get_log_path(config_file_name) if response is not None: with open(stderr_full_path, 'a+') as fout: fout.write(json.dumps(json.loads(response.text), indent=4, sort_keys=True, separators=(',', ':'))) print_error('Setting experiment error, error message is {}'.format(response.text)) return None
follow steps to start rest server and start experiment def launch_experiment(args, experiment_config, mode, config_file_name, experiment_id=None): '''follow steps to start rest server and start experiment''' nni_config = Config(config_file_name) # check packages for tuner if experiment_config.get('tuner') and experiment_config['tuner'].get('builtinTunerName'): tuner_name = experiment_config['tuner']['builtinTunerName'] module_name = ModuleName[tuner_name] try: check_call([sys.executable, '-c', 'import %s'%(module_name)]) except ModuleNotFoundError as e: print_error('The tuner %s should be installed through nnictl'%(tuner_name)) exit(1) log_dir = experiment_config['logDir'] if experiment_config.get('logDir') else None log_level = experiment_config['logLevel'] if experiment_config.get('logLevel') else None if log_level not in ['trace', 'debug'] and args.debug: log_level = 'debug' # start rest server rest_process, start_time = start_rest_server(args.port, experiment_config['trainingServicePlatform'], mode, config_file_name, experiment_id, log_dir, log_level) nni_config.set_config('restServerPid', rest_process.pid) # Deal with annotation if experiment_config.get('useAnnotation'): path = os.path.join(tempfile.gettempdir(), get_user(), 'nni', 'annotation') if not os.path.isdir(path): os.makedirs(path) path = tempfile.mkdtemp(dir=path) code_dir = expand_annotations(experiment_config['trial']['codeDir'], path) experiment_config['trial']['codeDir'] = code_dir search_space = generate_search_space(code_dir) experiment_config['searchSpace'] = json.dumps(search_space) assert search_space, ERROR_INFO % 'Generated search space is empty' elif experiment_config.get('searchSpacePath'): search_space = get_json_content(experiment_config.get('searchSpacePath')) experiment_config['searchSpace'] = json.dumps(search_space) else: experiment_config['searchSpace'] = json.dumps('') # check rest server running, _ = check_rest_server(args.port) if running: print_normal('Successfully started Restful server!') else: print_error('Restful server start failed!') print_log_content(config_file_name) try: kill_command(rest_process.pid) except Exception: raise Exception(ERROR_INFO % 'Rest server stopped!') exit(1) # set remote config if experiment_config['trainingServicePlatform'] == 'remote': print_normal('Setting remote config...') config_result, err_msg = set_remote_config(experiment_config, args.port, config_file_name) if config_result: print_normal('Successfully set remote config!') else: print_error('Failed! Error is: {}'.format(err_msg)) try: kill_command(rest_process.pid) except Exception: raise Exception(ERROR_INFO % 'Rest server stopped!') exit(1) # set local config if experiment_config['trainingServicePlatform'] == 'local': print_normal('Setting local config...') if set_local_config(experiment_config, args.port, config_file_name): print_normal('Successfully set local config!') else: print_error('Set local config failed!') try: kill_command(rest_process.pid) except Exception: raise Exception(ERROR_INFO % 'Rest server stopped!') exit(1) #set pai config if experiment_config['trainingServicePlatform'] == 'pai': print_normal('Setting pai config...') config_result, err_msg = set_pai_config(experiment_config, args.port, config_file_name) if config_result: print_normal('Successfully set pai config!') else: if err_msg: print_error('Failed! Error is: {}'.format(err_msg)) try: kill_command(rest_process.pid) except Exception: raise Exception(ERROR_INFO % 'Restful server stopped!') exit(1) #set kubeflow config if experiment_config['trainingServicePlatform'] == 'kubeflow': print_normal('Setting kubeflow config...') config_result, err_msg = set_kubeflow_config(experiment_config, args.port, config_file_name) if config_result: print_normal('Successfully set kubeflow config!') else: if err_msg: print_error('Failed! Error is: {}'.format(err_msg)) try: kill_command(rest_process.pid) except Exception: raise Exception(ERROR_INFO % 'Restful server stopped!') exit(1) #set kubeflow config if experiment_config['trainingServicePlatform'] == 'frameworkcontroller': print_normal('Setting frameworkcontroller config...') config_result, err_msg = set_frameworkcontroller_config(experiment_config, args.port, config_file_name) if config_result: print_normal('Successfully set frameworkcontroller config!') else: if err_msg: print_error('Failed! Error is: {}'.format(err_msg)) try: kill_command(rest_process.pid) except Exception: raise Exception(ERROR_INFO % 'Restful server stopped!') exit(1) # start a new experiment print_normal('Starting experiment...') # set debug configuration if experiment_config.get('debug') is None: experiment_config['debug'] = args.debug response = set_experiment(experiment_config, mode, args.port, config_file_name) if response: if experiment_id is None: experiment_id = json.loads(response.text).get('experiment_id') nni_config.set_config('experimentId', experiment_id) else: print_error('Start experiment failed!') print_log_content(config_file_name) try: kill_command(rest_process.pid) except Exception: raise Exception(ERROR_INFO % 'Restful server stopped!') exit(1) if experiment_config.get('nniManagerIp'): web_ui_url_list = ['{0}:{1}'.format(experiment_config['nniManagerIp'], str(args.port))] else: web_ui_url_list = get_local_urls(args.port) nni_config.set_config('webuiUrl', web_ui_url_list) #save experiment information nnictl_experiment_config = Experiments() nnictl_experiment_config.add_experiment(experiment_id, args.port, start_time, config_file_name, experiment_config['trainingServicePlatform']) print_normal(EXPERIMENT_SUCCESS_INFO % (experiment_id, ' '.join(web_ui_url_list)))
resume an experiment def resume_experiment(args): '''resume an experiment''' experiment_config = Experiments() experiment_dict = experiment_config.get_all_experiments() experiment_id = None experiment_endTime = None #find the latest stopped experiment if not args.id: print_error('Please set experiment id! \nYou could use \'nnictl resume {id}\' to resume a stopped experiment!\n' \ 'You could use \'nnictl experiment list all\' to show all of stopped experiments!') exit(1) else: if experiment_dict.get(args.id) is None: print_error('Id %s not exist!' % args.id) exit(1) if experiment_dict[args.id]['status'] != 'STOPPED': print_error('Experiment %s is running!' % args.id) exit(1) experiment_id = args.id print_normal('Resuming experiment %s...' % experiment_id) nni_config = Config(experiment_dict[experiment_id]['fileName']) experiment_config = nni_config.get_config('experimentConfig') experiment_id = nni_config.get_config('experimentId') new_config_file_name = ''.join(random.sample(string.ascii_letters + string.digits, 8)) new_nni_config = Config(new_config_file_name) new_nni_config.set_config('experimentConfig', experiment_config) launch_experiment(args, experiment_config, 'resume', new_config_file_name, experiment_id) new_nni_config.set_config('restServerPort', args.port)
start a new experiment def create_experiment(args): '''start a new experiment''' config_file_name = ''.join(random.sample(string.ascii_letters + string.digits, 8)) nni_config = Config(config_file_name) config_path = os.path.abspath(args.config) if not os.path.exists(config_path): print_error('Please set correct config path!') exit(1) experiment_config = get_yml_content(config_path) validate_all_content(experiment_config, config_path) nni_config.set_config('experimentConfig', experiment_config) launch_experiment(args, experiment_config, 'new', config_file_name) nni_config.set_config('restServerPort', args.port)