text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_buckets(min_length, max_length, bucket_count): ''' Get bucket by length. ''' if bucket_count <= 0: return [max_length] unit_length = int((max_length - min_length) // (bucket_count)) buckets = [min_length + unit_length * (i + 1) for i in range(0, bucket_count)] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def tokenize(self, text): ''' tokenize function in Tokenizer. ''' start = -1 tokens = [] for i, character in enumerate(text): if character == ' ' or character == '\t': if start >= 0: word = text[start:i] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_new_id(self): """ generate new id and event hook for new Individual """
self.events.append(Event()) indiv_id = self.indiv_counter self.indiv_counter += 1 return indiv_id
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_population(self, population_size, graph_max_layer, graph_min_layer): """ initialize populations for evolution tuner """
population = [] graph = Graph(max_layer_num=graph_max_layer, min_layer_num=graph_min_layer, inputs=[Layer(LayerType.input.value, output=[4, 5], size='x'), Layer(LayerType.input.value, output=[4, 5], size='y')], output=[Layer(LayerType.output.value, inputs=[4]...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def copyHdfsDirectoryToLocal(hdfsDirectory, localDirectory, hdfsClient): '''Copy directory from HDFS to local''' if not os.path.exists(localDirectory): os.makedirs(localDirectory) try: listing = hdfsClient.list_status(hdfsDirectory) except Exception as exception: nni_log(LogType....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def copyHdfsFileToLocal(hdfsFilePath, localFilePath, hdfsClient, override=True): '''Copy file from HDFS to local''' if not hdfsClient.exists(hdfsFilePath): raise Exception('HDFS file {} does not exist!'.format(hdfsFilePath)) try: file_status = hdfsClient.get_file_status(hdfsFilePath) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def copyDirectoryToHdfs(localDirectory, hdfsDirectory, hdfsClient): '''Copy directory from local to HDFS''' if not os.path.exists(localDirectory): raise Exception('Local Directory does not exist!') hdfsClient.mkdirs(hdfsDirectory) result = True for file in os.listdir(localDirectory): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def copyFileToHdfs(localFilePath, hdfsFilePath, hdfsClient, override=True): '''Copy a local file to HDFS directory''' if not os.path.exists(localFilePath): raise Exception('Local file Path does not exist!') if os.path.isdir(localFilePath): raise Exception('localFile should not a directory!')...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def load_data(): '''Load dataset, use boston dataset''' boston = load_boston() X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=99, test_size=0.25) #normalize data ss_X = StandardScaler() ss_y = StandardScaler() X_train = ss_X.fit_transform(X_trai...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def run(X_train, X_test, y_train, y_test, PARAMS): '''Train model and predict result''' model.fit(X_train, y_train) predict_y = model.predict(X_test) score = r2_score(y_test, predict_y) LOG.debug('r2 score: %s' % score) nni.report_final_result(score)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def to_json(self): ''' NetworkDescriptor to json representation ''' skip_list = [] for u, v, connection_type in self.skip_connections: skip_list.append({"from": u, "to": v, "type": connection_type}) return {"node_list": self.layers, "skip_list": skip_list}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_edge(self, layer, input_id, output_id): """Add a new layer to the graph. The nodes should be created in advance."""
if layer in self.layer_to_id: layer_id = self.layer_to_id[layer] if input_id not in self.layer_id_to_input_node_ids[layer_id]: self.layer_id_to_input_node_ids[layer_id].append(input_id) if output_id not in self.layer_id_to_output_node_ids[layer_id]: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _redirect_edge(self, u_id, v_id, new_v_id): """Redirect the layer to a new node. Change the edge originally from `u_id` to `v_id` into an edge from `u_id` to...
layer_id = None for index, edge_tuple in enumerate(self.adj_list[u_id]): if edge_tuple[0] == v_id: layer_id = edge_tuple[1] self.adj_list[u_id][index] = (new_v_id, layer_id) self.layer_list[layer_id].output = self.node_list[new_v_id] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _replace_layer(self, layer_id, new_layer): """Replace the layer with a new layer."""
old_layer = self.layer_list[layer_id] new_layer.input = old_layer.input new_layer.output = old_layer.output new_layer.output.shape = new_layer.output_shape self.layer_list[layer_id] = new_layer self.layer_to_id[new_layer] = layer_id self.layer_to_id.pop(old_layer...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def topological_order(self): """Return the topological order of the node IDs from the input node to the output node."""
q = Queue() in_degree = {} for i in range(self.n_nodes): in_degree[i] = 0 for u in range(self.n_nodes): for v, _ in self.adj_list[u]: in_degree[v] += 1 for i in range(self.n_nodes): if in_degree[i] == 0: q.put(i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_pooling_layers(self, start_node_id, end_node_id): """Given two node IDs, return all the pooling layers between them."""
layer_list = [] node_list = [start_node_id] assert self._depth_first_search(end_node_id, layer_list, node_list) ret = [] for layer_id in layer_list: layer = self.layer_list[layer_id] if is_layer(layer, "Pooling"): ret.append(layer) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _depth_first_search(self, target_id, layer_id_list, node_list): """Search for all the layers and nodes down the path. A recursive function to search all the ...
assert len(node_list) <= self.n_nodes u = node_list[-1] if u == target_id: return True for v, layer_id in self.adj_list[u]: layer_id_list.append(layer_id) node_list.append(v) if self._depth_first_search(target_id, layer_id_list, node_list...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 = s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_mai...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def clear_weights(self): ''' clear weights of the graph ''' self.weighted = False for layer in self.layer_list: layer.weights = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.Termi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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_type...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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"): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def handle_initialize(self, data): ''' data is search space ''' self.tuner.update_search_space(data) send(CommandType.Initialized, '') return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.traini...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate(self): """Generate the next neural architecture. Returns ------- other_info: any object Anything to be saved in the training queue together with the...
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) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, other_info, graph, metric_value, model_id): """ Update the controller with evaluation result of a neural architecture. Parameters other_info: an...
father_id = other_info self.bo.fit([graph.extract_descriptor()], [metric_value]) self.bo.add_child(father_id, model_id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 Return...
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")...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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"]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 repre...
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
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, \ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receive_trial_result(self, parameter_id, parameters, value): """Tuner receive result from trial. Parameters parameter_id : int parameters : dict value : dict...
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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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)) * \ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 = (hi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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):...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_scalar_reward(value, scalar_key='default'): """ Extract scalar reward from trial result. Raises ------ RuntimeError Incorrect final result: the final...
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/i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_config(self, budget): """Function to sample a new configuration This function is called inside BOHB to query a new configuration Parameters: budget: floa...
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 =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 els...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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_ur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def f_comb(self, pos, sample): """return the value of the f_comb when epoch = pos Parameters pos: int the epoch number of the position you want to predict sample...
ret = 0 for i in range(self.effective_model_num): model = self.effective_model[i] y = self.predict_y(model, pos) ret += sample[i] * y return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _outlierDetection_threaded(inputs): ''' Detect the outlier ''' [samples_idx, samples_x, samples_y_aggregation] = inputs sys.stderr.write("[%s] DEBUG: Evaluating %dth of %d samples\n"\ % (os.path.basename(__file__), samples_idx + 1, len(samples_x))) outlier = None ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def outlierDetection_threaded(samples_x, samples_y_aggregation): ''' Use Multi-thread to detect the outlier ''' outliers = [] threads_inputs = [[samples_idx, samples_x, samples_y_aggregation]\ for samples_idx in range(0, len(samples_x))] threads_pool = ThreadPool(min...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def deeper_conv_block(conv_layer, kernel_size, weighted=True): '''deeper conv layer. ''' n_dim = get_n_dim(conv_layer) filter_shape = (kernel_size,) * 2 n_filters = conv_layer.filters weight = np.zeros((n_filters, n_filters) + filter_shape) center = tuple(map(lambda x: int((x - 1) / 2), filt...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dense_to_deeper_block(dense_layer, weighted=True): '''deeper dense layer. ''' units = dense_layer.units weight = np.eye(units) bias = np.zeros(units) new_dense_layer = StubDense(units, units) if weighted: new_dense_layer.set_weights( (add_noise(weight, np.array([0, 1]...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def wider_pre_dense(layer, n_add, weighted=True): '''wider previous dense layer. ''' if not weighted: return StubDense(layer.input_units, layer.units + n_add) n_units2 = layer.units teacher_w, teacher_b = layer.get_weights() rand = np.random.randint(n_units2, size=n_add) student_w ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def wider_pre_conv(layer, n_add_filters, weighted=True): '''wider previous conv layer. ''' n_dim = get_n_dim(layer) if not weighted: return get_conv_class(n_dim)( layer.input_channel, layer.filters + n_add_filters, kernel_size=layer.kernel_size, ) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def wider_next_conv(layer, start_dim, total_dim, n_add, weighted=True): '''wider next conv layer. ''' n_dim = get_n_dim(layer) if not weighted: return get_conv_class(n_dim)(layer.input_channel + n_add, layer.filters, kerne...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def wider_bn(layer, start_dim, total_dim, n_add, weighted=True): '''wider batch norm layer. ''' n_dim = get_n_dim(layer) if not weighted: return get_batch_norm_class(n_dim)(layer.num_features + n_add) weights = layer.get_weights() new_weights = [ add_noise(np.ones(n_add, dtype=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def wider_next_dense(layer, start_dim, total_dim, n_add, weighted=True): '''wider next dense layer. ''' if not weighted: return StubDense(layer.input_units + n_add, layer.units) teacher_w, teacher_b = layer.get_weights() student_w = teacher_w.copy() n_units_each_channel = int(teacher_w.s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def add_noise(weights, other_weights): '''add noise to the layer. ''' w_range = np.ptp(other_weights.flatten()) noise_range = NOISE_RATIO * w_range noise = np.random.uniform(-noise_range / 2.0, noise_range / 2.0, weights.shape) return np.add(noise, weights)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def init_dense_weight(layer): '''initilize dense layer weight. ''' units = layer.units weight = np.eye(units) bias = np.zeros(units) layer.set_weights( (add_noise(weight, np.array([0, 1])), add_noise(bias, np.array([0, 1]))) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def init_conv_weight(layer): '''initilize conv layer weight. ''' n_filters = layer.filters filter_shape = (layer.kernel_size,) * get_n_dim(layer) weight = np.zeros((n_filters, n_filters) + filter_shape) center = tuple(map(lambda x: int((x - 1) / 2), filter_shape)) for i in range(n_filters):...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def init_bn_weight(layer): '''initilize batch norm layer weight. ''' n_filters = layer.num_features new_weights = [ add_noise(np.ones(n_filters, dtype=np.float32), np.array([0, 1])), add_noise(np.zeros(n_filters, dtype=np.float32), np.array([0, 1])), add_noise(np.zeros(n_filters,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def parse_log_path(args, trial_content): '''parse log path''' path_list = [] host_list = [] for trial in trial_content: if args.trial_id and args.trial_id != 'all' and trial.get('id') != args.trial_id: continue pattern = r'(?P<head>.+)://(?P<host>.+):(?P<path>.*)' mat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def copy_data_from_remote(args, nni_config, trial_content, path_list, host_list, temp_nni_path): '''use ssh client to copy data from remote machine to local machien''' machine_list = nni_config.get_config('experimentConfig').get('machineList') machine_dict = {} local_path_list = [] for machine in ma...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_path_list(args, nni_config, trial_content, temp_nni_path): '''get path list according to different platform''' path_list, host_list = parse_log_path(args, trial_content) platform = nni_config.get_config('experimentConfig').get('trainingServicePlatform') if platform == 'local': print_norm...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def start_tensorboard_process(args, nni_config, path_list, temp_nni_path): '''call cmds to start tensorboard process in local machine''' if detect_port(args.port): print_error('Port %s is used by another process, please reset port!' % str(args.port)) exit(1) stdout_file = open(os.path.j...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _ratio_scores(parameters_value, clusteringmodel_gmm_good, clusteringmodel_gmm_bad): ''' The ratio is smaller the better ''' ratio = clusteringmodel_gmm_good.score([parameters_value]) / clusteringmodel_gmm_bad.score([parameters_value]) sigma = 0 return ratio, sigma
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def selection(x_bounds, x_types, clusteringmodel_gmm_good, clusteringmodel_gmm_bad, minimize_starting_points, minimize_constraints_fun=None): ''' Select the lowest mu value ''' results = lib_acquisition_function.next_hyperparameter_lo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _minimize_constraints_fun_summation(x): ''' Minimize constraints fun summation ''' summation = sum([x[i] for i in CONSTRAINT_PARAMS_IDX]) return CONSTRAINT_UPPERBOUND >= summation >= CONSTRAINT_LOWERBOUND
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def load_data(): '''Load dataset, use 20newsgroups dataset''' digits = load_digits() X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, random_state=99, test_size=0.25) ss = StandardScaler() X_train = ss.fit_transform(X_train) X_test = ss.transform(X_test) retu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_hyperparameter_configurations(self, num, r, config_generator): """generate num hyperparameter configurations from search space using Bayesian optimizatio...
global _KEY assert self.i == 0 hyperparameter_configs = dict() for _ in range(num): params_id = create_bracket_parameter_id(self.s, self.i) params = config_generator.get_config(r) params[_KEY] = r hyperparameter_configs[params_id] = params...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_initialize(self, data): """Initialize Tuner, including creating Bayesian optimization-based parametric models and search space formations Parameters d...
logger.info('start to handle_initialize') # convert search space jason to ConfigSpace self.handle_update_search_space(data) # generate BOHB config_generator using Bayesian optimization if self.search_space: self.cg = CG_BOHB(configspace=self.search_space, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_new_bracket(self): """generate a new bracket"""
logger.debug( 'start to create a new SuccessiveHalving iteration, self.curr_s=%d', self.curr_s) if self.curr_s < 0: logger.info("s < 0, Finish this round of Hyperband in BOHB. Generate new round") self.curr_s = self.s_max self.brackets[self.curr_s] = Bracket(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_request_trial_jobs(self, data): """recerive the number of request and generate trials Parameters data: int number of trial jobs that nni manager ask t...
# Receive new request self.credit += data for _ in range(self.credit): self._request_one_trial_job()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_trial_end(self, data): """receive the information of trial end and generate next configuaration. Parameters data: dict() it has three keys: trial_job_...
logger.debug('Tuner handle trial end, result is %s', data) hyper_params = json_tricks.loads(data['hyper_params']) s, i, _ = hyper_params['parameter_id'].split('_') hyper_configs = self.brackets[int(s)].inform_trial_end(int(i)) if hyper_configs is not None: logger.d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_report_metric_data(self, data): """reveice the metric data and update Bayesian optimization with final result Parameters data: it is an object which h...
logger.debug('handle report metric data = %s', data) assert 'value' in data value = extract_scalar_reward(data['value']) if self.optimize_mode is OptimizeMode.Maximize: reward = -value else: reward = value assert 'parameter_id' in data s,...