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 ...
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 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)...
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_chai...
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 i...
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 rang...
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...
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) ...
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))...
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: ...
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...
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)] ...
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: ...
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(...
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] ...
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...
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)) ...
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...
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 ...
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 obj...
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 ...
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 o...
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 '...
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: a...
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 respo...
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:...
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 perfor...
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.Goo...
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 ---------- p...
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 ...
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 =...
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 architec...
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...
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 ...
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"] ret...
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 ...
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 : ...
Pack the output Parameters ---------- init_parameter : dict Returns ------- output : dict def _pack_output(self, init_parameter): """Pack the output Parameters ---------- init_parameter : dict Returns ------- ou...
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 ---------- ...
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...
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: ...
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, 1...
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(...
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], p...
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...
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 pa...
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: ...
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(s...
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.readli...
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 fr...
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.it...
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_p...
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...
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 confi...
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: d...
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 ...
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_...
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 ...
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:...
Return positinal embedding. def positional_encoding(inputs, num_units=None, zero_pad=True, scale=True, scope="positional_encoding", reuse=None): ''' Return positinal embedding. ''' Sh...
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 ...
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) ...
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 exce...
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 ...
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: ret...
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 Retur...
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 ...
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:...
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 ------- ...
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 ...
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...
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 R...
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,...
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...
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') pa...
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_ful...
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_com...
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 differen...
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!\...
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_re...
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_...
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 ...
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'] } respo...
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 = ...
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_d...
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('tune...
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('Pl...
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_erro...