id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
27,200
Microsoft/nni
tools/nni_cmd/tensorboard_utils.py
start_tensorboard_process
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.join(temp_nni_path, 'tensorboard_stdout'), 'a+') stderr_file = open(os.path.join(temp_nni_path, 'tensorboard_stderr'), 'a+') cmds = ['tensorboard', '--logdir', format_tensorboard_log_path(path_list), '--port', str(args.port)] tensorboard_process = Popen(cmds, stdout=stdout_file, stderr=stderr_file) url_list = get_local_urls(args.port) print_normal(COLOR_GREEN_FORMAT % 'Start tensorboard success!\n' + 'Tensorboard urls: ' + ' '.join(url_list)) tensorboard_process_pid_list = nni_config.get_config('tensorboardPidList') if tensorboard_process_pid_list is None: tensorboard_process_pid_list = [tensorboard_process.pid] else: tensorboard_process_pid_list.append(tensorboard_process.pid) nni_config.set_config('tensorboardPidList', tensorboard_process_pid_list)
python
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.join(temp_nni_path, 'tensorboard_stdout'), 'a+') stderr_file = open(os.path.join(temp_nni_path, 'tensorboard_stderr'), 'a+') cmds = ['tensorboard', '--logdir', format_tensorboard_log_path(path_list), '--port', str(args.port)] tensorboard_process = Popen(cmds, stdout=stdout_file, stderr=stderr_file) url_list = get_local_urls(args.port) print_normal(COLOR_GREEN_FORMAT % 'Start tensorboard success!\n' + 'Tensorboard urls: ' + ' '.join(url_list)) tensorboard_process_pid_list = nni_config.get_config('tensorboardPidList') if tensorboard_process_pid_list is None: tensorboard_process_pid_list = [tensorboard_process.pid] else: tensorboard_process_pid_list.append(tensorboard_process.pid) nni_config.set_config('tensorboardPidList', tensorboard_process_pid_list)
[ "def", "start_tensorboard_process", "(", "args", ",", "nni_config", ",", "path_list", ",", "temp_nni_path", ")", ":", "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", ".", "join", "(", "temp_nni_path", ",", "'tensorboard_stdout'", ")", ",", "'a+'", ")", "stderr_file", "=", "open", "(", "os", ".", "path", ".", "join", "(", "temp_nni_path", ",", "'tensorboard_stderr'", ")", ",", "'a+'", ")", "cmds", "=", "[", "'tensorboard'", ",", "'--logdir'", ",", "format_tensorboard_log_path", "(", "path_list", ")", ",", "'--port'", ",", "str", "(", "args", ".", "port", ")", "]", "tensorboard_process", "=", "Popen", "(", "cmds", ",", "stdout", "=", "stdout_file", ",", "stderr", "=", "stderr_file", ")", "url_list", "=", "get_local_urls", "(", "args", ".", "port", ")", "print_normal", "(", "COLOR_GREEN_FORMAT", "%", "'Start tensorboard success!\\n'", "+", "'Tensorboard urls: '", "+", "' '", ".", "join", "(", "url_list", ")", ")", "tensorboard_process_pid_list", "=", "nni_config", ".", "get_config", "(", "'tensorboardPidList'", ")", "if", "tensorboard_process_pid_list", "is", "None", ":", "tensorboard_process_pid_list", "=", "[", "tensorboard_process", ".", "pid", "]", "else", ":", "tensorboard_process_pid_list", ".", "append", "(", "tensorboard_process", ".", "pid", ")", "nni_config", ".", "set_config", "(", "'tensorboardPidList'", ",", "tensorboard_process_pid_list", ")" ]
call cmds to start tensorboard process in local machine
[ "call", "cmds", "to", "start", "tensorboard", "process", "in", "local", "machine" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/tensorboard_utils.py#L92-L109
27,201
Microsoft/nni
src/sdk/pynni/nni/metis_tuner/Regression_GMM/Selection.py
_ratio_scores
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
python
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
[ "def", "_ratio_scores", "(", "parameters_value", ",", "clusteringmodel_gmm_good", ",", "clusteringmodel_gmm_bad", ")", ":", "ratio", "=", "clusteringmodel_gmm_good", ".", "score", "(", "[", "parameters_value", "]", ")", "/", "clusteringmodel_gmm_bad", ".", "score", "(", "[", "parameters_value", "]", ")", "sigma", "=", "0", "return", "ratio", ",", "sigma" ]
The ratio is smaller the better
[ "The", "ratio", "is", "smaller", "the", "better" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/Regression_GMM/Selection.py#L37-L43
27,202
Microsoft/nni
src/sdk/pynni/nni/metis_tuner/Regression_GMM/Selection.py
selection
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_lowest_mu(\ _ratio_scores, [clusteringmodel_gmm_good, clusteringmodel_gmm_bad],\ x_bounds, x_types, minimize_starting_points, \ minimize_constraints_fun=minimize_constraints_fun) return results
python
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_lowest_mu(\ _ratio_scores, [clusteringmodel_gmm_good, clusteringmodel_gmm_bad],\ x_bounds, x_types, minimize_starting_points, \ minimize_constraints_fun=minimize_constraints_fun) return results
[ "def", "selection", "(", "x_bounds", ",", "x_types", ",", "clusteringmodel_gmm_good", ",", "clusteringmodel_gmm_bad", ",", "minimize_starting_points", ",", "minimize_constraints_fun", "=", "None", ")", ":", "results", "=", "lib_acquisition_function", ".", "next_hyperparameter_lowest_mu", "(", "_ratio_scores", ",", "[", "clusteringmodel_gmm_good", ",", "clusteringmodel_gmm_bad", "]", ",", "x_bounds", ",", "x_types", ",", "minimize_starting_points", ",", "minimize_constraints_fun", "=", "minimize_constraints_fun", ")", "return", "results" ]
Select the lowest mu value
[ "Select", "the", "lowest", "mu", "value" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/Regression_GMM/Selection.py#L63-L77
27,203
Microsoft/nni
src/sdk/pynni/nni/metis_tuner/Regression_GMM/Selection.py
_minimize_constraints_fun_summation
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
python
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
[ "def", "_minimize_constraints_fun_summation", "(", "x", ")", ":", "summation", "=", "sum", "(", "[", "x", "[", "i", "]", "for", "i", "in", "CONSTRAINT_PARAMS_IDX", "]", ")", "return", "CONSTRAINT_UPPERBOUND", ">=", "summation", ">=", "CONSTRAINT_LOWERBOUND" ]
Minimize constraints fun summation
[ "Minimize", "constraints", "fun", "summation" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/Regression_GMM/Selection.py#L99-L104
27,204
Microsoft/nni
examples/trials/sklearn/classification/main.py
load_data
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) return X_train, X_test, y_train, y_test
python
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) return X_train, X_test, y_train, y_test
[ "def", "load_data", "(", ")", ":", "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", ")", "return", "X_train", ",", "X_test", ",", "y_train", ",", "y_test" ]
Load dataset, use 20newsgroups dataset
[ "Load", "dataset", "use", "20newsgroups", "dataset" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/sklearn/classification/main.py#L29-L38
27,205
Microsoft/nni
src/sdk/pynni/nni/bohb_advisor/bohb_advisor.py
Bracket.get_hyperparameter_configurations
def get_hyperparameter_configurations(self, num, r, config_generator): """generate num hyperparameter configurations from search space using Bayesian optimization Parameters ---------- num: int the number of hyperparameter configurations Returns ------- list a list of hyperparameter configurations. Format: [[key1, value1], [key2, value2], ...] """ 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 self._record_hyper_configs(hyperparameter_configs) return [[key, value] for key, value in hyperparameter_configs.items()]
python
def get_hyperparameter_configurations(self, num, r, config_generator): """generate num hyperparameter configurations from search space using Bayesian optimization Parameters ---------- num: int the number of hyperparameter configurations Returns ------- list a list of hyperparameter configurations. Format: [[key1, value1], [key2, value2], ...] """ 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 self._record_hyper_configs(hyperparameter_configs) return [[key, value] for key, value in hyperparameter_configs.items()]
[ "def", "get_hyperparameter_configurations", "(", "self", ",", "num", ",", "r", ",", "config_generator", ")", ":", "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", "self", ".", "_record_hyper_configs", "(", "hyperparameter_configs", ")", "return", "[", "[", "key", ",", "value", "]", "for", "key", ",", "value", "in", "hyperparameter_configs", ".", "items", "(", ")", "]" ]
generate num hyperparameter configurations from search space using Bayesian optimization Parameters ---------- num: int the number of hyperparameter configurations Returns ------- list a list of hyperparameter configurations. Format: [[key1, value1], [key2, value2], ...]
[ "generate", "num", "hyperparameter", "configurations", "from", "search", "space", "using", "Bayesian", "optimization" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/bohb_advisor/bohb_advisor.py#L215-L237
27,206
Microsoft/nni
src/sdk/pynni/nni/bohb_advisor/bohb_advisor.py
BOHB.handle_initialize
def handle_initialize(self, data): """Initialize Tuner, including creating Bayesian optimization-based parametric models and search space formations Parameters ---------- data: search space search space of this experiment Raises ------ ValueError Error: Search space is None """ 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, min_points_in_model=self.min_points_in_model, top_n_percent=self.top_n_percent, num_samples=self.num_samples, random_fraction=self.random_fraction, bandwidth_factor=self.bandwidth_factor, min_bandwidth=self.min_bandwidth) else: raise ValueError('Error: Search space is None') # generate first brackets self.generate_new_bracket() send(CommandType.Initialized, '')
python
def handle_initialize(self, data): """Initialize Tuner, including creating Bayesian optimization-based parametric models and search space formations Parameters ---------- data: search space search space of this experiment Raises ------ ValueError Error: Search space is None """ 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, min_points_in_model=self.min_points_in_model, top_n_percent=self.top_n_percent, num_samples=self.num_samples, random_fraction=self.random_fraction, bandwidth_factor=self.bandwidth_factor, min_bandwidth=self.min_bandwidth) else: raise ValueError('Error: Search space is None') # generate first brackets self.generate_new_bracket() send(CommandType.Initialized, '')
[ "def", "handle_initialize", "(", "self", ",", "data", ")", ":", "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", ",", "min_points_in_model", "=", "self", ".", "min_points_in_model", ",", "top_n_percent", "=", "self", ".", "top_n_percent", ",", "num_samples", "=", "self", ".", "num_samples", ",", "random_fraction", "=", "self", ".", "random_fraction", ",", "bandwidth_factor", "=", "self", ".", "bandwidth_factor", ",", "min_bandwidth", "=", "self", ".", "min_bandwidth", ")", "else", ":", "raise", "ValueError", "(", "'Error: Search space is None'", ")", "# generate first brackets", "self", ".", "generate_new_bracket", "(", ")", "send", "(", "CommandType", ".", "Initialized", ",", "''", ")" ]
Initialize Tuner, including creating Bayesian optimization-based parametric models and search space formations Parameters ---------- data: search space search space of this experiment Raises ------ ValueError Error: Search space is None
[ "Initialize", "Tuner", "including", "creating", "Bayesian", "optimization", "-", "based", "parametric", "models", "and", "search", "space", "formations" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/bohb_advisor/bohb_advisor.py#L344-L375
27,207
Microsoft/nni
src/sdk/pynni/nni/bohb_advisor/bohb_advisor.py
BOHB.generate_new_bracket
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(s=self.curr_s, s_max=self.s_max, eta=self.eta, max_budget=self.max_budget, optimize_mode=self.optimize_mode) next_n, next_r = self.brackets[self.curr_s].get_n_r() logger.debug( 'new SuccessiveHalving iteration, next_n=%d, next_r=%d', next_n, next_r) # rewrite with TPE generated_hyper_configs = self.brackets[self.curr_s].get_hyperparameter_configurations( next_n, next_r, self.cg) self.generated_hyper_configs = generated_hyper_configs.copy()
python
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(s=self.curr_s, s_max=self.s_max, eta=self.eta, max_budget=self.max_budget, optimize_mode=self.optimize_mode) next_n, next_r = self.brackets[self.curr_s].get_n_r() logger.debug( 'new SuccessiveHalving iteration, next_n=%d, next_r=%d', next_n, next_r) # rewrite with TPE generated_hyper_configs = self.brackets[self.curr_s].get_hyperparameter_configurations( next_n, next_r, self.cg) self.generated_hyper_configs = generated_hyper_configs.copy()
[ "def", "generate_new_bracket", "(", "self", ")", ":", "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", "(", "s", "=", "self", ".", "curr_s", ",", "s_max", "=", "self", ".", "s_max", ",", "eta", "=", "self", ".", "eta", ",", "max_budget", "=", "self", ".", "max_budget", ",", "optimize_mode", "=", "self", ".", "optimize_mode", ")", "next_n", ",", "next_r", "=", "self", ".", "brackets", "[", "self", ".", "curr_s", "]", ".", "get_n_r", "(", ")", "logger", ".", "debug", "(", "'new SuccessiveHalving iteration, next_n=%d, next_r=%d'", ",", "next_n", ",", "next_r", ")", "# rewrite with TPE", "generated_hyper_configs", "=", "self", ".", "brackets", "[", "self", ".", "curr_s", "]", ".", "get_hyperparameter_configurations", "(", "next_n", ",", "next_r", ",", "self", ".", "cg", ")", "self", ".", "generated_hyper_configs", "=", "generated_hyper_configs", ".", "copy", "(", ")" ]
generate a new bracket
[ "generate", "a", "new", "bracket" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/bohb_advisor/bohb_advisor.py#L377-L392
27,208
Microsoft/nni
src/sdk/pynni/nni/bohb_advisor/bohb_advisor.py
BOHB.handle_request_trial_jobs
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 to generate """ # Receive new request self.credit += data for _ in range(self.credit): self._request_one_trial_job()
python
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 to generate """ # Receive new request self.credit += data for _ in range(self.credit): self._request_one_trial_job()
[ "def", "handle_request_trial_jobs", "(", "self", ",", "data", ")", ":", "# Receive new request", "self", ".", "credit", "+=", "data", "for", "_", "in", "range", "(", "self", ".", "credit", ")", ":", "self", ".", "_request_one_trial_job", "(", ")" ]
recerive the number of request and generate trials Parameters ---------- data: int number of trial jobs that nni manager ask to generate
[ "recerive", "the", "number", "of", "request", "and", "generate", "trials" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/bohb_advisor/bohb_advisor.py#L394-L406
27,209
Microsoft/nni
src/sdk/pynni/nni/bohb_advisor/bohb_advisor.py
BOHB.handle_trial_end
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_id, event, hyper_params trial_job_id: the id generated by training service event: the job's state hyper_params: the hyperparameters (a string) generated and returned by tuner """ 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.debug( 'bracket %s next round %s, hyper_configs: %s', s, i, hyper_configs) self.generated_hyper_configs = self.generated_hyper_configs + hyper_configs for _ in range(self.credit): self._request_one_trial_job() # Finish this bracket and generate a new bracket elif self.brackets[int(s)].no_more_trial: self.curr_s -= 1 self.generate_new_bracket() for _ in range(self.credit): self._request_one_trial_job()
python
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_id, event, hyper_params trial_job_id: the id generated by training service event: the job's state hyper_params: the hyperparameters (a string) generated and returned by tuner """ 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.debug( 'bracket %s next round %s, hyper_configs: %s', s, i, hyper_configs) self.generated_hyper_configs = self.generated_hyper_configs + hyper_configs for _ in range(self.credit): self._request_one_trial_job() # Finish this bracket and generate a new bracket elif self.brackets[int(s)].no_more_trial: self.curr_s -= 1 self.generate_new_bracket() for _ in range(self.credit): self._request_one_trial_job()
[ "def", "handle_trial_end", "(", "self", ",", "data", ")", ":", "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", ".", "debug", "(", "'bracket %s next round %s, hyper_configs: %s'", ",", "s", ",", "i", ",", "hyper_configs", ")", "self", ".", "generated_hyper_configs", "=", "self", ".", "generated_hyper_configs", "+", "hyper_configs", "for", "_", "in", "range", "(", "self", ".", "credit", ")", ":", "self", ".", "_request_one_trial_job", "(", ")", "# Finish this bracket and generate a new bracket", "elif", "self", ".", "brackets", "[", "int", "(", "s", ")", "]", ".", "no_more_trial", ":", "self", ".", "curr_s", "-=", "1", "self", ".", "generate_new_bracket", "(", ")", "for", "_", "in", "range", "(", "self", ".", "credit", ")", ":", "self", ".", "_request_one_trial_job", "(", ")" ]
receive the information of trial end and generate next configuaration. Parameters ---------- data: dict() it has three keys: trial_job_id, event, hyper_params trial_job_id: the id generated by training service event: the job's state hyper_params: the hyperparameters (a string) generated and returned by tuner
[ "receive", "the", "information", "of", "trial", "end", "and", "generate", "next", "configuaration", "." ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/bohb_advisor/bohb_advisor.py#L498-L526
27,210
Microsoft/nni
src/sdk/pynni/nni/bohb_advisor/bohb_advisor.py
BOHB.handle_report_metric_data
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 has keys 'parameter_id', 'value', 'trial_job_id', 'type', 'sequence'. Raises ------ ValueError Data type not supported """ 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, i, _ = data['parameter_id'].split('_') logger.debug('bracket id = %s, metrics value = %s, type = %s', s, value, data['type']) s = int(s) assert 'type' in data if data['type'] == 'FINAL': # and PERIODICAL metric are independent, thus, not comparable. assert 'sequence' in data self.brackets[s].set_config_perf( int(i), data['parameter_id'], sys.maxsize, value) self.completed_hyper_configs.append(data) _parameters = self.parameters[data['parameter_id']] _parameters.pop(_KEY) # update BO with loss, max_s budget, hyperparameters self.cg.new_result(loss=reward, budget=data['sequence'], parameters=_parameters, update_model=True) elif data['type'] == 'PERIODICAL': self.brackets[s].set_config_perf( int(i), data['parameter_id'], data['sequence'], value) else: raise ValueError( 'Data type not supported: {}'.format(data['type']))
python
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 has keys 'parameter_id', 'value', 'trial_job_id', 'type', 'sequence'. Raises ------ ValueError Data type not supported """ 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, i, _ = data['parameter_id'].split('_') logger.debug('bracket id = %s, metrics value = %s, type = %s', s, value, data['type']) s = int(s) assert 'type' in data if data['type'] == 'FINAL': # and PERIODICAL metric are independent, thus, not comparable. assert 'sequence' in data self.brackets[s].set_config_perf( int(i), data['parameter_id'], sys.maxsize, value) self.completed_hyper_configs.append(data) _parameters = self.parameters[data['parameter_id']] _parameters.pop(_KEY) # update BO with loss, max_s budget, hyperparameters self.cg.new_result(loss=reward, budget=data['sequence'], parameters=_parameters, update_model=True) elif data['type'] == 'PERIODICAL': self.brackets[s].set_config_perf( int(i), data['parameter_id'], data['sequence'], value) else: raise ValueError( 'Data type not supported: {}'.format(data['type']))
[ "def", "handle_report_metric_data", "(", "self", ",", "data", ")", ":", "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", ",", "i", ",", "_", "=", "data", "[", "'parameter_id'", "]", ".", "split", "(", "'_'", ")", "logger", ".", "debug", "(", "'bracket id = %s, metrics value = %s, type = %s'", ",", "s", ",", "value", ",", "data", "[", "'type'", "]", ")", "s", "=", "int", "(", "s", ")", "assert", "'type'", "in", "data", "if", "data", "[", "'type'", "]", "==", "'FINAL'", ":", "# and PERIODICAL metric are independent, thus, not comparable.", "assert", "'sequence'", "in", "data", "self", ".", "brackets", "[", "s", "]", ".", "set_config_perf", "(", "int", "(", "i", ")", ",", "data", "[", "'parameter_id'", "]", ",", "sys", ".", "maxsize", ",", "value", ")", "self", ".", "completed_hyper_configs", ".", "append", "(", "data", ")", "_parameters", "=", "self", ".", "parameters", "[", "data", "[", "'parameter_id'", "]", "]", "_parameters", ".", "pop", "(", "_KEY", ")", "# update BO with loss, max_s budget, hyperparameters", "self", ".", "cg", ".", "new_result", "(", "loss", "=", "reward", ",", "budget", "=", "data", "[", "'sequence'", "]", ",", "parameters", "=", "_parameters", ",", "update_model", "=", "True", ")", "elif", "data", "[", "'type'", "]", "==", "'PERIODICAL'", ":", "self", ".", "brackets", "[", "s", "]", ".", "set_config_perf", "(", "int", "(", "i", ")", ",", "data", "[", "'parameter_id'", "]", ",", "data", "[", "'sequence'", "]", ",", "value", ")", "else", ":", "raise", "ValueError", "(", "'Data type not supported: {}'", ".", "format", "(", "data", "[", "'type'", "]", ")", ")" ]
reveice the metric data and update Bayesian optimization with final result Parameters ---------- data: it is an object which has keys 'parameter_id', 'value', 'trial_job_id', 'type', 'sequence'. Raises ------ ValueError Data type not supported
[ "reveice", "the", "metric", "data", "and", "update", "Bayesian", "optimization", "with", "final", "result" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/bohb_advisor/bohb_advisor.py#L528-L572
27,211
Microsoft/nni
examples/trials/network_morphism/FashionMNIST/utils.py
data_transforms_cifar10
def data_transforms_cifar10(args): """ data_transforms for cifar10 dataset """ cifar_mean = [0.49139968, 0.48215827, 0.44653124] cifar_std = [0.24703233, 0.24348505, 0.26158768] train_transform = transforms.Compose( [ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(cifar_mean, cifar_std), ] ) if args.cutout: train_transform.transforms.append(Cutout(args.cutout_length)) valid_transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize(cifar_mean, cifar_std)] ) return train_transform, valid_transform
python
def data_transforms_cifar10(args): """ data_transforms for cifar10 dataset """ cifar_mean = [0.49139968, 0.48215827, 0.44653124] cifar_std = [0.24703233, 0.24348505, 0.26158768] train_transform = transforms.Compose( [ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(cifar_mean, cifar_std), ] ) if args.cutout: train_transform.transforms.append(Cutout(args.cutout_length)) valid_transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize(cifar_mean, cifar_std)] ) return train_transform, valid_transform
[ "def", "data_transforms_cifar10", "(", "args", ")", ":", "cifar_mean", "=", "[", "0.49139968", ",", "0.48215827", ",", "0.44653124", "]", "cifar_std", "=", "[", "0.24703233", ",", "0.24348505", ",", "0.26158768", "]", "train_transform", "=", "transforms", ".", "Compose", "(", "[", "transforms", ".", "RandomCrop", "(", "32", ",", "padding", "=", "4", ")", ",", "transforms", ".", "RandomHorizontalFlip", "(", ")", ",", "transforms", ".", "ToTensor", "(", ")", ",", "transforms", ".", "Normalize", "(", "cifar_mean", ",", "cifar_std", ")", ",", "]", ")", "if", "args", ".", "cutout", ":", "train_transform", ".", "transforms", ".", "append", "(", "Cutout", "(", "args", ".", "cutout_length", ")", ")", "valid_transform", "=", "transforms", ".", "Compose", "(", "[", "transforms", ".", "ToTensor", "(", ")", ",", "transforms", ".", "Normalize", "(", "cifar_mean", ",", "cifar_std", ")", "]", ")", "return", "train_transform", ",", "valid_transform" ]
data_transforms for cifar10 dataset
[ "data_transforms", "for", "cifar10", "dataset" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/network_morphism/FashionMNIST/utils.py#L116-L137
27,212
Microsoft/nni
examples/trials/network_morphism/FashionMNIST/utils.py
data_transforms_mnist
def data_transforms_mnist(args, mnist_mean=None, mnist_std=None): """ data_transforms for mnist dataset """ if mnist_mean is None: mnist_mean = [0.5] if mnist_std is None: mnist_std = [0.5] train_transform = transforms.Compose( [ transforms.RandomCrop(28, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(mnist_mean, mnist_std), ] ) if args.cutout: train_transform.transforms.append(Cutout(args.cutout_length)) valid_transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize(mnist_mean, mnist_std)] ) return train_transform, valid_transform
python
def data_transforms_mnist(args, mnist_mean=None, mnist_std=None): """ data_transforms for mnist dataset """ if mnist_mean is None: mnist_mean = [0.5] if mnist_std is None: mnist_std = [0.5] train_transform = transforms.Compose( [ transforms.RandomCrop(28, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(mnist_mean, mnist_std), ] ) if args.cutout: train_transform.transforms.append(Cutout(args.cutout_length)) valid_transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize(mnist_mean, mnist_std)] ) return train_transform, valid_transform
[ "def", "data_transforms_mnist", "(", "args", ",", "mnist_mean", "=", "None", ",", "mnist_std", "=", "None", ")", ":", "if", "mnist_mean", "is", "None", ":", "mnist_mean", "=", "[", "0.5", "]", "if", "mnist_std", "is", "None", ":", "mnist_std", "=", "[", "0.5", "]", "train_transform", "=", "transforms", ".", "Compose", "(", "[", "transforms", ".", "RandomCrop", "(", "28", ",", "padding", "=", "4", ")", ",", "transforms", ".", "RandomHorizontalFlip", "(", ")", ",", "transforms", ".", "ToTensor", "(", ")", ",", "transforms", ".", "Normalize", "(", "mnist_mean", ",", "mnist_std", ")", ",", "]", ")", "if", "args", ".", "cutout", ":", "train_transform", ".", "transforms", ".", "append", "(", "Cutout", "(", "args", ".", "cutout_length", ")", ")", "valid_transform", "=", "transforms", ".", "Compose", "(", "[", "transforms", ".", "ToTensor", "(", ")", ",", "transforms", ".", "Normalize", "(", "mnist_mean", ",", "mnist_std", ")", "]", ")", "return", "train_transform", ",", "valid_transform" ]
data_transforms for mnist dataset
[ "data_transforms", "for", "mnist", "dataset" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/network_morphism/FashionMNIST/utils.py#L140-L163
27,213
Microsoft/nni
examples/trials/network_morphism/FashionMNIST/utils.py
get_mean_and_std
def get_mean_and_std(dataset): """Compute the mean and std value of dataset.""" dataloader = torch.utils.data.DataLoader( dataset, batch_size=1, shuffle=True, num_workers=2 ) mean = torch.zeros(3) std = torch.zeros(3) print("==> Computing mean and std..") for inputs, _ in dataloader: for i in range(3): mean[i] += inputs[:, i, :, :].mean() std[i] += inputs[:, i, :, :].std() mean.div_(len(dataset)) std.div_(len(dataset)) return mean, std
python
def get_mean_and_std(dataset): """Compute the mean and std value of dataset.""" dataloader = torch.utils.data.DataLoader( dataset, batch_size=1, shuffle=True, num_workers=2 ) mean = torch.zeros(3) std = torch.zeros(3) print("==> Computing mean and std..") for inputs, _ in dataloader: for i in range(3): mean[i] += inputs[:, i, :, :].mean() std[i] += inputs[:, i, :, :].std() mean.div_(len(dataset)) std.div_(len(dataset)) return mean, std
[ "def", "get_mean_and_std", "(", "dataset", ")", ":", "dataloader", "=", "torch", ".", "utils", ".", "data", ".", "DataLoader", "(", "dataset", ",", "batch_size", "=", "1", ",", "shuffle", "=", "True", ",", "num_workers", "=", "2", ")", "mean", "=", "torch", ".", "zeros", "(", "3", ")", "std", "=", "torch", ".", "zeros", "(", "3", ")", "print", "(", "\"==> Computing mean and std..\"", ")", "for", "inputs", ",", "_", "in", "dataloader", ":", "for", "i", "in", "range", "(", "3", ")", ":", "mean", "[", "i", "]", "+=", "inputs", "[", ":", ",", "i", ",", ":", ",", ":", "]", ".", "mean", "(", ")", "std", "[", "i", "]", "+=", "inputs", "[", ":", ",", "i", ",", ":", ",", ":", "]", ".", "std", "(", ")", "mean", ".", "div_", "(", "len", "(", "dataset", ")", ")", "std", ".", "div_", "(", "len", "(", "dataset", ")", ")", "return", "mean", ",", "std" ]
Compute the mean and std value of dataset.
[ "Compute", "the", "mean", "and", "std", "value", "of", "dataset", "." ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/network_morphism/FashionMNIST/utils.py#L166-L180
27,214
Microsoft/nni
src/sdk/pynni/nni/metis_tuner/lib_constraint_summation.py
check_feasibility
def check_feasibility(x_bounds, lowerbound, upperbound): ''' This can have false positives. For examples, parameters can only be 0 or 5, and the summation constraint is between 6 and 7. ''' # x_bounds should be sorted, so even for "discrete_int" type, # the smallest and the largest number should the first and the last element x_bounds_lowerbound = sum([x_bound[0] for x_bound in x_bounds]) x_bounds_upperbound = sum([x_bound[-1] for x_bound in x_bounds]) # return ((x_bounds_lowerbound <= lowerbound) and (x_bounds_upperbound >= lowerbound)) or \ # ((x_bounds_lowerbound <= upperbound) and (x_bounds_upperbound >= upperbound)) return (x_bounds_lowerbound <= lowerbound <= x_bounds_upperbound) or \ (x_bounds_lowerbound <= upperbound <= x_bounds_upperbound)
python
def check_feasibility(x_bounds, lowerbound, upperbound): ''' This can have false positives. For examples, parameters can only be 0 or 5, and the summation constraint is between 6 and 7. ''' # x_bounds should be sorted, so even for "discrete_int" type, # the smallest and the largest number should the first and the last element x_bounds_lowerbound = sum([x_bound[0] for x_bound in x_bounds]) x_bounds_upperbound = sum([x_bound[-1] for x_bound in x_bounds]) # return ((x_bounds_lowerbound <= lowerbound) and (x_bounds_upperbound >= lowerbound)) or \ # ((x_bounds_lowerbound <= upperbound) and (x_bounds_upperbound >= upperbound)) return (x_bounds_lowerbound <= lowerbound <= x_bounds_upperbound) or \ (x_bounds_lowerbound <= upperbound <= x_bounds_upperbound)
[ "def", "check_feasibility", "(", "x_bounds", ",", "lowerbound", ",", "upperbound", ")", ":", "# x_bounds should be sorted, so even for \"discrete_int\" type,", "# the smallest and the largest number should the first and the last element", "x_bounds_lowerbound", "=", "sum", "(", "[", "x_bound", "[", "0", "]", "for", "x_bound", "in", "x_bounds", "]", ")", "x_bounds_upperbound", "=", "sum", "(", "[", "x_bound", "[", "-", "1", "]", "for", "x_bound", "in", "x_bounds", "]", ")", "# return ((x_bounds_lowerbound <= lowerbound) and (x_bounds_upperbound >= lowerbound)) or \\", "# ((x_bounds_lowerbound <= upperbound) and (x_bounds_upperbound >= upperbound))", "return", "(", "x_bounds_lowerbound", "<=", "lowerbound", "<=", "x_bounds_upperbound", ")", "or", "(", "x_bounds_lowerbound", "<=", "upperbound", "<=", "x_bounds_upperbound", ")" ]
This can have false positives. For examples, parameters can only be 0 or 5, and the summation constraint is between 6 and 7.
[ "This", "can", "have", "false", "positives", ".", "For", "examples", "parameters", "can", "only", "be", "0", "or", "5", "and", "the", "summation", "constraint", "is", "between", "6", "and", "7", "." ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/lib_constraint_summation.py#L27-L40
27,215
Microsoft/nni
src/sdk/pynni/nni/metis_tuner/lib_constraint_summation.py
rand
def rand(x_bounds, x_types, lowerbound, upperbound, max_retries=100): ''' Key idea is that we try to move towards upperbound, by randomly choose one value for each parameter. However, for the last parameter, we need to make sure that its value can help us get above lowerbound ''' outputs = None if check_feasibility(x_bounds, lowerbound, upperbound) is True: # Order parameters by their range size. We want the smallest range first, # because the corresponding parameter has less numbers to choose from x_idx_sorted = [] for i, _ in enumerate(x_bounds): if x_types[i] == "discrete_int": x_idx_sorted.append([i, len(x_bounds[i])]) elif (x_types[i] == "range_int") or (x_types[i] == "range_continuous"): x_idx_sorted.append([i, math.floor(x_bounds[i][1] - x_bounds[i][0])]) x_idx_sorted = sorted(x_idx_sorted, key=itemgetter(1)) for _ in range(max_retries): budget_allocated = 0 outputs = [None] * len(x_bounds) for i, _ in enumerate(x_idx_sorted): x_idx = x_idx_sorted[i][0] # The amount of unallocated space that we have budget_max = upperbound - budget_allocated # NOT the Last x that we need to assign a random number if i < (len(x_idx_sorted) - 1): if x_bounds[x_idx][0] <= budget_max: if x_types[x_idx] == "discrete_int": # Note the valid integer temp = [] for j in x_bounds[x_idx]: if j <= budget_max: temp.append(j) # Randomly pick a number from the integer array if temp: outputs[x_idx] = temp[random.randint(0, len(temp) - 1)] elif (x_types[x_idx] == "range_int") or \ (x_types[x_idx] == "range_continuous"): outputs[x_idx] = random.randint(x_bounds[x_idx][0], min(x_bounds[x_idx][-1], budget_max)) else: # The last x that we need to assign a random number randint_lowerbound = lowerbound - budget_allocated randint_lowerbound = 0 if randint_lowerbound < 0 else randint_lowerbound # This check: # is our smallest possible value going to overflow the available budget space, # and is our largest possible value going to underflow the lower bound if (x_bounds[x_idx][0] <= budget_max) and \ (x_bounds[x_idx][-1] >= randint_lowerbound): if x_types[x_idx] == "discrete_int": temp = [] for j in x_bounds[x_idx]: # if (j <= budget_max) and (j >= randint_lowerbound): if randint_lowerbound <= j <= budget_max: temp.append(j) if temp: outputs[x_idx] = temp[random.randint(0, len(temp) - 1)] elif (x_types[x_idx] == "range_int") or \ (x_types[x_idx] == "range_continuous"): outputs[x_idx] = random.randint(randint_lowerbound, min(x_bounds[x_idx][1], budget_max)) if outputs[x_idx] is None: break else: budget_allocated += outputs[x_idx] if None not in outputs: break return outputs
python
def rand(x_bounds, x_types, lowerbound, upperbound, max_retries=100): ''' Key idea is that we try to move towards upperbound, by randomly choose one value for each parameter. However, for the last parameter, we need to make sure that its value can help us get above lowerbound ''' outputs = None if check_feasibility(x_bounds, lowerbound, upperbound) is True: # Order parameters by their range size. We want the smallest range first, # because the corresponding parameter has less numbers to choose from x_idx_sorted = [] for i, _ in enumerate(x_bounds): if x_types[i] == "discrete_int": x_idx_sorted.append([i, len(x_bounds[i])]) elif (x_types[i] == "range_int") or (x_types[i] == "range_continuous"): x_idx_sorted.append([i, math.floor(x_bounds[i][1] - x_bounds[i][0])]) x_idx_sorted = sorted(x_idx_sorted, key=itemgetter(1)) for _ in range(max_retries): budget_allocated = 0 outputs = [None] * len(x_bounds) for i, _ in enumerate(x_idx_sorted): x_idx = x_idx_sorted[i][0] # The amount of unallocated space that we have budget_max = upperbound - budget_allocated # NOT the Last x that we need to assign a random number if i < (len(x_idx_sorted) - 1): if x_bounds[x_idx][0] <= budget_max: if x_types[x_idx] == "discrete_int": # Note the valid integer temp = [] for j in x_bounds[x_idx]: if j <= budget_max: temp.append(j) # Randomly pick a number from the integer array if temp: outputs[x_idx] = temp[random.randint(0, len(temp) - 1)] elif (x_types[x_idx] == "range_int") or \ (x_types[x_idx] == "range_continuous"): outputs[x_idx] = random.randint(x_bounds[x_idx][0], min(x_bounds[x_idx][-1], budget_max)) else: # The last x that we need to assign a random number randint_lowerbound = lowerbound - budget_allocated randint_lowerbound = 0 if randint_lowerbound < 0 else randint_lowerbound # This check: # is our smallest possible value going to overflow the available budget space, # and is our largest possible value going to underflow the lower bound if (x_bounds[x_idx][0] <= budget_max) and \ (x_bounds[x_idx][-1] >= randint_lowerbound): if x_types[x_idx] == "discrete_int": temp = [] for j in x_bounds[x_idx]: # if (j <= budget_max) and (j >= randint_lowerbound): if randint_lowerbound <= j <= budget_max: temp.append(j) if temp: outputs[x_idx] = temp[random.randint(0, len(temp) - 1)] elif (x_types[x_idx] == "range_int") or \ (x_types[x_idx] == "range_continuous"): outputs[x_idx] = random.randint(randint_lowerbound, min(x_bounds[x_idx][1], budget_max)) if outputs[x_idx] is None: break else: budget_allocated += outputs[x_idx] if None not in outputs: break return outputs
[ "def", "rand", "(", "x_bounds", ",", "x_types", ",", "lowerbound", ",", "upperbound", ",", "max_retries", "=", "100", ")", ":", "outputs", "=", "None", "if", "check_feasibility", "(", "x_bounds", ",", "lowerbound", ",", "upperbound", ")", "is", "True", ":", "# Order parameters by their range size. We want the smallest range first,", "# because the corresponding parameter has less numbers to choose from", "x_idx_sorted", "=", "[", "]", "for", "i", ",", "_", "in", "enumerate", "(", "x_bounds", ")", ":", "if", "x_types", "[", "i", "]", "==", "\"discrete_int\"", ":", "x_idx_sorted", ".", "append", "(", "[", "i", ",", "len", "(", "x_bounds", "[", "i", "]", ")", "]", ")", "elif", "(", "x_types", "[", "i", "]", "==", "\"range_int\"", ")", "or", "(", "x_types", "[", "i", "]", "==", "\"range_continuous\"", ")", ":", "x_idx_sorted", ".", "append", "(", "[", "i", ",", "math", ".", "floor", "(", "x_bounds", "[", "i", "]", "[", "1", "]", "-", "x_bounds", "[", "i", "]", "[", "0", "]", ")", "]", ")", "x_idx_sorted", "=", "sorted", "(", "x_idx_sorted", ",", "key", "=", "itemgetter", "(", "1", ")", ")", "for", "_", "in", "range", "(", "max_retries", ")", ":", "budget_allocated", "=", "0", "outputs", "=", "[", "None", "]", "*", "len", "(", "x_bounds", ")", "for", "i", ",", "_", "in", "enumerate", "(", "x_idx_sorted", ")", ":", "x_idx", "=", "x_idx_sorted", "[", "i", "]", "[", "0", "]", "# The amount of unallocated space that we have", "budget_max", "=", "upperbound", "-", "budget_allocated", "# NOT the Last x that we need to assign a random number", "if", "i", "<", "(", "len", "(", "x_idx_sorted", ")", "-", "1", ")", ":", "if", "x_bounds", "[", "x_idx", "]", "[", "0", "]", "<=", "budget_max", ":", "if", "x_types", "[", "x_idx", "]", "==", "\"discrete_int\"", ":", "# Note the valid integer", "temp", "=", "[", "]", "for", "j", "in", "x_bounds", "[", "x_idx", "]", ":", "if", "j", "<=", "budget_max", ":", "temp", ".", "append", "(", "j", ")", "# Randomly pick a number from the integer array", "if", "temp", ":", "outputs", "[", "x_idx", "]", "=", "temp", "[", "random", ".", "randint", "(", "0", ",", "len", "(", "temp", ")", "-", "1", ")", "]", "elif", "(", "x_types", "[", "x_idx", "]", "==", "\"range_int\"", ")", "or", "(", "x_types", "[", "x_idx", "]", "==", "\"range_continuous\"", ")", ":", "outputs", "[", "x_idx", "]", "=", "random", ".", "randint", "(", "x_bounds", "[", "x_idx", "]", "[", "0", "]", ",", "min", "(", "x_bounds", "[", "x_idx", "]", "[", "-", "1", "]", ",", "budget_max", ")", ")", "else", ":", "# The last x that we need to assign a random number", "randint_lowerbound", "=", "lowerbound", "-", "budget_allocated", "randint_lowerbound", "=", "0", "if", "randint_lowerbound", "<", "0", "else", "randint_lowerbound", "# This check:", "# is our smallest possible value going to overflow the available budget space,", "# and is our largest possible value going to underflow the lower bound", "if", "(", "x_bounds", "[", "x_idx", "]", "[", "0", "]", "<=", "budget_max", ")", "and", "(", "x_bounds", "[", "x_idx", "]", "[", "-", "1", "]", ">=", "randint_lowerbound", ")", ":", "if", "x_types", "[", "x_idx", "]", "==", "\"discrete_int\"", ":", "temp", "=", "[", "]", "for", "j", "in", "x_bounds", "[", "x_idx", "]", ":", "# if (j <= budget_max) and (j >= randint_lowerbound):", "if", "randint_lowerbound", "<=", "j", "<=", "budget_max", ":", "temp", ".", "append", "(", "j", ")", "if", "temp", ":", "outputs", "[", "x_idx", "]", "=", "temp", "[", "random", ".", "randint", "(", "0", ",", "len", "(", "temp", ")", "-", "1", ")", "]", "elif", "(", "x_types", "[", "x_idx", "]", "==", "\"range_int\"", ")", "or", "(", "x_types", "[", "x_idx", "]", "==", "\"range_continuous\"", ")", ":", "outputs", "[", "x_idx", "]", "=", "random", ".", "randint", "(", "randint_lowerbound", ",", "min", "(", "x_bounds", "[", "x_idx", "]", "[", "1", "]", ",", "budget_max", ")", ")", "if", "outputs", "[", "x_idx", "]", "is", "None", ":", "break", "else", ":", "budget_allocated", "+=", "outputs", "[", "x_idx", "]", "if", "None", "not", "in", "outputs", ":", "break", "return", "outputs" ]
Key idea is that we try to move towards upperbound, by randomly choose one value for each parameter. However, for the last parameter, we need to make sure that its value can help us get above lowerbound
[ "Key", "idea", "is", "that", "we", "try", "to", "move", "towards", "upperbound", "by", "randomly", "choose", "one", "value", "for", "each", "parameter", ".", "However", "for", "the", "last", "parameter", "we", "need", "to", "make", "sure", "that", "its", "value", "can", "help", "us", "get", "above", "lowerbound" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/lib_constraint_summation.py#L42-L115
27,216
Microsoft/nni
tools/nni_cmd/launcher_utils.py
expand_path
def expand_path(experiment_config, key): '''Change '~' to user home directory''' if experiment_config.get(key): experiment_config[key] = os.path.expanduser(experiment_config[key])
python
def expand_path(experiment_config, key): '''Change '~' to user home directory''' if experiment_config.get(key): experiment_config[key] = os.path.expanduser(experiment_config[key])
[ "def", "expand_path", "(", "experiment_config", ",", "key", ")", ":", "if", "experiment_config", ".", "get", "(", "key", ")", ":", "experiment_config", "[", "key", "]", "=", "os", ".", "path", ".", "expanduser", "(", "experiment_config", "[", "key", "]", ")" ]
Change '~' to user home directory
[ "Change", "~", "to", "user", "home", "directory" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher_utils.py#L29-L32
27,217
Microsoft/nni
tools/nni_cmd/launcher_utils.py
parse_relative_path
def parse_relative_path(root_path, experiment_config, key): '''Change relative path to absolute path''' if experiment_config.get(key) and not os.path.isabs(experiment_config.get(key)): absolute_path = os.path.join(root_path, experiment_config.get(key)) print_normal('expand %s: %s to %s ' % (key, experiment_config[key], absolute_path)) experiment_config[key] = absolute_path
python
def parse_relative_path(root_path, experiment_config, key): '''Change relative path to absolute path''' if experiment_config.get(key) and not os.path.isabs(experiment_config.get(key)): absolute_path = os.path.join(root_path, experiment_config.get(key)) print_normal('expand %s: %s to %s ' % (key, experiment_config[key], absolute_path)) experiment_config[key] = absolute_path
[ "def", "parse_relative_path", "(", "root_path", ",", "experiment_config", ",", "key", ")", ":", "if", "experiment_config", ".", "get", "(", "key", ")", "and", "not", "os", ".", "path", ".", "isabs", "(", "experiment_config", ".", "get", "(", "key", ")", ")", ":", "absolute_path", "=", "os", ".", "path", ".", "join", "(", "root_path", ",", "experiment_config", ".", "get", "(", "key", ")", ")", "print_normal", "(", "'expand %s: %s to %s '", "%", "(", "key", ",", "experiment_config", "[", "key", "]", ",", "absolute_path", ")", ")", "experiment_config", "[", "key", "]", "=", "absolute_path" ]
Change relative path to absolute path
[ "Change", "relative", "path", "to", "absolute", "path" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher_utils.py#L34-L39
27,218
Microsoft/nni
tools/nni_cmd/launcher_utils.py
parse_time
def parse_time(time): '''Change the time to seconds''' unit = time[-1] if unit not in ['s', 'm', 'h', 'd']: print_error('the unit of time could only from {s, m, h, d}') exit(1) time = time[:-1] if not time.isdigit(): print_error('time format error!') exit(1) parse_dict = {'s':1, 'm':60, 'h':3600, 'd':86400} return int(time) * parse_dict[unit]
python
def parse_time(time): '''Change the time to seconds''' unit = time[-1] if unit not in ['s', 'm', 'h', 'd']: print_error('the unit of time could only from {s, m, h, d}') exit(1) time = time[:-1] if not time.isdigit(): print_error('time format error!') exit(1) parse_dict = {'s':1, 'm':60, 'h':3600, 'd':86400} return int(time) * parse_dict[unit]
[ "def", "parse_time", "(", "time", ")", ":", "unit", "=", "time", "[", "-", "1", "]", "if", "unit", "not", "in", "[", "'s'", ",", "'m'", ",", "'h'", ",", "'d'", "]", ":", "print_error", "(", "'the unit of time could only from {s, m, h, d}'", ")", "exit", "(", "1", ")", "time", "=", "time", "[", ":", "-", "1", "]", "if", "not", "time", ".", "isdigit", "(", ")", ":", "print_error", "(", "'time format error!'", ")", "exit", "(", "1", ")", "parse_dict", "=", "{", "'s'", ":", "1", ",", "'m'", ":", "60", ",", "'h'", ":", "3600", ",", "'d'", ":", "86400", "}", "return", "int", "(", "time", ")", "*", "parse_dict", "[", "unit", "]" ]
Change the time to seconds
[ "Change", "the", "time", "to", "seconds" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher_utils.py#L41-L52
27,219
Microsoft/nni
tools/nni_cmd/launcher_utils.py
parse_path
def parse_path(experiment_config, config_path): '''Parse path in config file''' expand_path(experiment_config, 'searchSpacePath') if experiment_config.get('trial'): expand_path(experiment_config['trial'], 'codeDir') if experiment_config.get('tuner'): expand_path(experiment_config['tuner'], 'codeDir') if experiment_config.get('assessor'): expand_path(experiment_config['assessor'], 'codeDir') if experiment_config.get('advisor'): expand_path(experiment_config['advisor'], 'codeDir') #if users use relative path, convert it to absolute path root_path = os.path.dirname(config_path) if experiment_config.get('searchSpacePath'): parse_relative_path(root_path, experiment_config, 'searchSpacePath') if experiment_config.get('trial'): parse_relative_path(root_path, experiment_config['trial'], 'codeDir') if experiment_config.get('tuner'): parse_relative_path(root_path, experiment_config['tuner'], 'codeDir') if experiment_config.get('assessor'): parse_relative_path(root_path, experiment_config['assessor'], 'codeDir') if experiment_config.get('advisor'): parse_relative_path(root_path, experiment_config['advisor'], 'codeDir') if experiment_config.get('machineList'): for index in range(len(experiment_config['machineList'])): parse_relative_path(root_path, experiment_config['machineList'][index], 'sshKeyPath')
python
def parse_path(experiment_config, config_path): '''Parse path in config file''' expand_path(experiment_config, 'searchSpacePath') if experiment_config.get('trial'): expand_path(experiment_config['trial'], 'codeDir') if experiment_config.get('tuner'): expand_path(experiment_config['tuner'], 'codeDir') if experiment_config.get('assessor'): expand_path(experiment_config['assessor'], 'codeDir') if experiment_config.get('advisor'): expand_path(experiment_config['advisor'], 'codeDir') #if users use relative path, convert it to absolute path root_path = os.path.dirname(config_path) if experiment_config.get('searchSpacePath'): parse_relative_path(root_path, experiment_config, 'searchSpacePath') if experiment_config.get('trial'): parse_relative_path(root_path, experiment_config['trial'], 'codeDir') if experiment_config.get('tuner'): parse_relative_path(root_path, experiment_config['tuner'], 'codeDir') if experiment_config.get('assessor'): parse_relative_path(root_path, experiment_config['assessor'], 'codeDir') if experiment_config.get('advisor'): parse_relative_path(root_path, experiment_config['advisor'], 'codeDir') if experiment_config.get('machineList'): for index in range(len(experiment_config['machineList'])): parse_relative_path(root_path, experiment_config['machineList'][index], 'sshKeyPath')
[ "def", "parse_path", "(", "experiment_config", ",", "config_path", ")", ":", "expand_path", "(", "experiment_config", ",", "'searchSpacePath'", ")", "if", "experiment_config", ".", "get", "(", "'trial'", ")", ":", "expand_path", "(", "experiment_config", "[", "'trial'", "]", ",", "'codeDir'", ")", "if", "experiment_config", ".", "get", "(", "'tuner'", ")", ":", "expand_path", "(", "experiment_config", "[", "'tuner'", "]", ",", "'codeDir'", ")", "if", "experiment_config", ".", "get", "(", "'assessor'", ")", ":", "expand_path", "(", "experiment_config", "[", "'assessor'", "]", ",", "'codeDir'", ")", "if", "experiment_config", ".", "get", "(", "'advisor'", ")", ":", "expand_path", "(", "experiment_config", "[", "'advisor'", "]", ",", "'codeDir'", ")", "#if users use relative path, convert it to absolute path", "root_path", "=", "os", ".", "path", ".", "dirname", "(", "config_path", ")", "if", "experiment_config", ".", "get", "(", "'searchSpacePath'", ")", ":", "parse_relative_path", "(", "root_path", ",", "experiment_config", ",", "'searchSpacePath'", ")", "if", "experiment_config", ".", "get", "(", "'trial'", ")", ":", "parse_relative_path", "(", "root_path", ",", "experiment_config", "[", "'trial'", "]", ",", "'codeDir'", ")", "if", "experiment_config", ".", "get", "(", "'tuner'", ")", ":", "parse_relative_path", "(", "root_path", ",", "experiment_config", "[", "'tuner'", "]", ",", "'codeDir'", ")", "if", "experiment_config", ".", "get", "(", "'assessor'", ")", ":", "parse_relative_path", "(", "root_path", ",", "experiment_config", "[", "'assessor'", "]", ",", "'codeDir'", ")", "if", "experiment_config", ".", "get", "(", "'advisor'", ")", ":", "parse_relative_path", "(", "root_path", ",", "experiment_config", "[", "'advisor'", "]", ",", "'codeDir'", ")", "if", "experiment_config", ".", "get", "(", "'machineList'", ")", ":", "for", "index", "in", "range", "(", "len", "(", "experiment_config", "[", "'machineList'", "]", ")", ")", ":", "parse_relative_path", "(", "root_path", ",", "experiment_config", "[", "'machineList'", "]", "[", "index", "]", ",", "'sshKeyPath'", ")" ]
Parse path in config file
[ "Parse", "path", "in", "config", "file" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher_utils.py#L54-L80
27,220
Microsoft/nni
tools/nni_cmd/launcher_utils.py
validate_search_space_content
def validate_search_space_content(experiment_config): '''Validate searchspace content, if the searchspace file is not json format or its values does not contain _type and _value which must be specified, it will not be a valid searchspace file''' try: search_space_content = json.load(open(experiment_config.get('searchSpacePath'), 'r')) for value in search_space_content.values(): if not value.get('_type') or not value.get('_value'): print_error('please use _type and _value to specify searchspace!') exit(1) except: print_error('searchspace file is not a valid json format!') exit(1)
python
def validate_search_space_content(experiment_config): '''Validate searchspace content, if the searchspace file is not json format or its values does not contain _type and _value which must be specified, it will not be a valid searchspace file''' try: search_space_content = json.load(open(experiment_config.get('searchSpacePath'), 'r')) for value in search_space_content.values(): if not value.get('_type') or not value.get('_value'): print_error('please use _type and _value to specify searchspace!') exit(1) except: print_error('searchspace file is not a valid json format!') exit(1)
[ "def", "validate_search_space_content", "(", "experiment_config", ")", ":", "try", ":", "search_space_content", "=", "json", ".", "load", "(", "open", "(", "experiment_config", ".", "get", "(", "'searchSpacePath'", ")", ",", "'r'", ")", ")", "for", "value", "in", "search_space_content", ".", "values", "(", ")", ":", "if", "not", "value", ".", "get", "(", "'_type'", ")", "or", "not", "value", ".", "get", "(", "'_value'", ")", ":", "print_error", "(", "'please use _type and _value to specify searchspace!'", ")", "exit", "(", "1", ")", "except", ":", "print_error", "(", "'searchspace file is not a valid json format!'", ")", "exit", "(", "1", ")" ]
Validate searchspace content, if the searchspace file is not json format or its values does not contain _type and _value which must be specified, it will not be a valid searchspace file
[ "Validate", "searchspace", "content", "if", "the", "searchspace", "file", "is", "not", "json", "format", "or", "its", "values", "does", "not", "contain", "_type", "and", "_value", "which", "must", "be", "specified", "it", "will", "not", "be", "a", "valid", "searchspace", "file" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher_utils.py#L82-L94
27,221
Microsoft/nni
tools/nni_cmd/launcher_utils.py
validate_kubeflow_operators
def validate_kubeflow_operators(experiment_config): '''Validate whether the kubeflow operators are valid''' if experiment_config.get('kubeflowConfig'): if experiment_config.get('kubeflowConfig').get('operator') == 'tf-operator': if experiment_config.get('trial').get('master') is not None: print_error('kubeflow with tf-operator can not set master') exit(1) if experiment_config.get('trial').get('worker') is None: print_error('kubeflow with tf-operator must set worker') exit(1) elif experiment_config.get('kubeflowConfig').get('operator') == 'pytorch-operator': if experiment_config.get('trial').get('ps') is not None: print_error('kubeflow with pytorch-operator can not set ps') exit(1) if experiment_config.get('trial').get('master') is None: print_error('kubeflow with pytorch-operator must set master') exit(1) if experiment_config.get('kubeflowConfig').get('storage') == 'nfs': if experiment_config.get('kubeflowConfig').get('nfs') is None: print_error('please set nfs configuration!') exit(1) elif experiment_config.get('kubeflowConfig').get('storage') == 'azureStorage': if experiment_config.get('kubeflowConfig').get('azureStorage') is None: print_error('please set azureStorage configuration!') exit(1) elif experiment_config.get('kubeflowConfig').get('storage') is None: if experiment_config.get('kubeflowConfig').get('azureStorage'): print_error('please set storage type!') exit(1)
python
def validate_kubeflow_operators(experiment_config): '''Validate whether the kubeflow operators are valid''' if experiment_config.get('kubeflowConfig'): if experiment_config.get('kubeflowConfig').get('operator') == 'tf-operator': if experiment_config.get('trial').get('master') is not None: print_error('kubeflow with tf-operator can not set master') exit(1) if experiment_config.get('trial').get('worker') is None: print_error('kubeflow with tf-operator must set worker') exit(1) elif experiment_config.get('kubeflowConfig').get('operator') == 'pytorch-operator': if experiment_config.get('trial').get('ps') is not None: print_error('kubeflow with pytorch-operator can not set ps') exit(1) if experiment_config.get('trial').get('master') is None: print_error('kubeflow with pytorch-operator must set master') exit(1) if experiment_config.get('kubeflowConfig').get('storage') == 'nfs': if experiment_config.get('kubeflowConfig').get('nfs') is None: print_error('please set nfs configuration!') exit(1) elif experiment_config.get('kubeflowConfig').get('storage') == 'azureStorage': if experiment_config.get('kubeflowConfig').get('azureStorage') is None: print_error('please set azureStorage configuration!') exit(1) elif experiment_config.get('kubeflowConfig').get('storage') is None: if experiment_config.get('kubeflowConfig').get('azureStorage'): print_error('please set storage type!') exit(1)
[ "def", "validate_kubeflow_operators", "(", "experiment_config", ")", ":", "if", "experiment_config", ".", "get", "(", "'kubeflowConfig'", ")", ":", "if", "experiment_config", ".", "get", "(", "'kubeflowConfig'", ")", ".", "get", "(", "'operator'", ")", "==", "'tf-operator'", ":", "if", "experiment_config", ".", "get", "(", "'trial'", ")", ".", "get", "(", "'master'", ")", "is", "not", "None", ":", "print_error", "(", "'kubeflow with tf-operator can not set master'", ")", "exit", "(", "1", ")", "if", "experiment_config", ".", "get", "(", "'trial'", ")", ".", "get", "(", "'worker'", ")", "is", "None", ":", "print_error", "(", "'kubeflow with tf-operator must set worker'", ")", "exit", "(", "1", ")", "elif", "experiment_config", ".", "get", "(", "'kubeflowConfig'", ")", ".", "get", "(", "'operator'", ")", "==", "'pytorch-operator'", ":", "if", "experiment_config", ".", "get", "(", "'trial'", ")", ".", "get", "(", "'ps'", ")", "is", "not", "None", ":", "print_error", "(", "'kubeflow with pytorch-operator can not set ps'", ")", "exit", "(", "1", ")", "if", "experiment_config", ".", "get", "(", "'trial'", ")", ".", "get", "(", "'master'", ")", "is", "None", ":", "print_error", "(", "'kubeflow with pytorch-operator must set master'", ")", "exit", "(", "1", ")", "if", "experiment_config", ".", "get", "(", "'kubeflowConfig'", ")", ".", "get", "(", "'storage'", ")", "==", "'nfs'", ":", "if", "experiment_config", ".", "get", "(", "'kubeflowConfig'", ")", ".", "get", "(", "'nfs'", ")", "is", "None", ":", "print_error", "(", "'please set nfs configuration!'", ")", "exit", "(", "1", ")", "elif", "experiment_config", ".", "get", "(", "'kubeflowConfig'", ")", ".", "get", "(", "'storage'", ")", "==", "'azureStorage'", ":", "if", "experiment_config", ".", "get", "(", "'kubeflowConfig'", ")", ".", "get", "(", "'azureStorage'", ")", "is", "None", ":", "print_error", "(", "'please set azureStorage configuration!'", ")", "exit", "(", "1", ")", "elif", "experiment_config", ".", "get", "(", "'kubeflowConfig'", ")", ".", "get", "(", "'storage'", ")", "is", "None", ":", "if", "experiment_config", ".", "get", "(", "'kubeflowConfig'", ")", ".", "get", "(", "'azureStorage'", ")", ":", "print_error", "(", "'please set storage type!'", ")", "exit", "(", "1", ")" ]
Validate whether the kubeflow operators are valid
[ "Validate", "whether", "the", "kubeflow", "operators", "are", "valid" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher_utils.py#L96-L125
27,222
Microsoft/nni
tools/nni_cmd/launcher_utils.py
validate_common_content
def validate_common_content(experiment_config): '''Validate whether the common values in experiment_config is valid''' if not experiment_config.get('trainingServicePlatform') or \ experiment_config.get('trainingServicePlatform') not in ['local', 'remote', 'pai', 'kubeflow', 'frameworkcontroller']: print_error('Please set correct trainingServicePlatform!') exit(1) schema_dict = { 'local': LOCAL_CONFIG_SCHEMA, 'remote': REMOTE_CONFIG_SCHEMA, 'pai': PAI_CONFIG_SCHEMA, 'kubeflow': KUBEFLOW_CONFIG_SCHEMA, 'frameworkcontroller': FRAMEWORKCONTROLLER_CONFIG_SCHEMA } separate_schema_dict = { 'tuner': tuner_schema_dict, 'advisor': advisor_schema_dict, 'assessor': assessor_schema_dict } separate_builtInName_dict = { 'tuner': 'builtinTunerName', 'advisor': 'builtinAdvisorName', 'assessor': 'builtinAssessorName' } try: schema_dict.get(experiment_config['trainingServicePlatform']).validate(experiment_config) for separate_key in separate_schema_dict.keys(): if experiment_config.get(separate_key): if experiment_config[separate_key].get(separate_builtInName_dict[separate_key]): validate = False for key in separate_schema_dict[separate_key].keys(): if key.__contains__(experiment_config[separate_key][separate_builtInName_dict[separate_key]]): Schema({**separate_schema_dict[separate_key][key]}).validate(experiment_config[separate_key]) validate = True break if not validate: print_error('%s %s error!' % (separate_key, separate_builtInName_dict[separate_key])) exit(1) else: Schema({**separate_schema_dict[separate_key]['customized']}).validate(experiment_config[separate_key]) except SchemaError as error: print_error('Your config file is not correct, please check your config file content!') if error.__str__().__contains__('Wrong key'): print_error(' '.join(error.__str__().split()[:3])) else: print_error(error) exit(1) #set default value if experiment_config.get('maxExecDuration') is None: experiment_config['maxExecDuration'] = '999d' if experiment_config.get('maxTrialNum') is None: experiment_config['maxTrialNum'] = 99999 if experiment_config['trainingServicePlatform'] == 'remote': for index in range(len(experiment_config['machineList'])): if experiment_config['machineList'][index].get('port') is None: experiment_config['machineList'][index]['port'] = 22
python
def validate_common_content(experiment_config): '''Validate whether the common values in experiment_config is valid''' if not experiment_config.get('trainingServicePlatform') or \ experiment_config.get('trainingServicePlatform') not in ['local', 'remote', 'pai', 'kubeflow', 'frameworkcontroller']: print_error('Please set correct trainingServicePlatform!') exit(1) schema_dict = { 'local': LOCAL_CONFIG_SCHEMA, 'remote': REMOTE_CONFIG_SCHEMA, 'pai': PAI_CONFIG_SCHEMA, 'kubeflow': KUBEFLOW_CONFIG_SCHEMA, 'frameworkcontroller': FRAMEWORKCONTROLLER_CONFIG_SCHEMA } separate_schema_dict = { 'tuner': tuner_schema_dict, 'advisor': advisor_schema_dict, 'assessor': assessor_schema_dict } separate_builtInName_dict = { 'tuner': 'builtinTunerName', 'advisor': 'builtinAdvisorName', 'assessor': 'builtinAssessorName' } try: schema_dict.get(experiment_config['trainingServicePlatform']).validate(experiment_config) for separate_key in separate_schema_dict.keys(): if experiment_config.get(separate_key): if experiment_config[separate_key].get(separate_builtInName_dict[separate_key]): validate = False for key in separate_schema_dict[separate_key].keys(): if key.__contains__(experiment_config[separate_key][separate_builtInName_dict[separate_key]]): Schema({**separate_schema_dict[separate_key][key]}).validate(experiment_config[separate_key]) validate = True break if not validate: print_error('%s %s error!' % (separate_key, separate_builtInName_dict[separate_key])) exit(1) else: Schema({**separate_schema_dict[separate_key]['customized']}).validate(experiment_config[separate_key]) except SchemaError as error: print_error('Your config file is not correct, please check your config file content!') if error.__str__().__contains__('Wrong key'): print_error(' '.join(error.__str__().split()[:3])) else: print_error(error) exit(1) #set default value if experiment_config.get('maxExecDuration') is None: experiment_config['maxExecDuration'] = '999d' if experiment_config.get('maxTrialNum') is None: experiment_config['maxTrialNum'] = 99999 if experiment_config['trainingServicePlatform'] == 'remote': for index in range(len(experiment_config['machineList'])): if experiment_config['machineList'][index].get('port') is None: experiment_config['machineList'][index]['port'] = 22
[ "def", "validate_common_content", "(", "experiment_config", ")", ":", "if", "not", "experiment_config", ".", "get", "(", "'trainingServicePlatform'", ")", "or", "experiment_config", ".", "get", "(", "'trainingServicePlatform'", ")", "not", "in", "[", "'local'", ",", "'remote'", ",", "'pai'", ",", "'kubeflow'", ",", "'frameworkcontroller'", "]", ":", "print_error", "(", "'Please set correct trainingServicePlatform!'", ")", "exit", "(", "1", ")", "schema_dict", "=", "{", "'local'", ":", "LOCAL_CONFIG_SCHEMA", ",", "'remote'", ":", "REMOTE_CONFIG_SCHEMA", ",", "'pai'", ":", "PAI_CONFIG_SCHEMA", ",", "'kubeflow'", ":", "KUBEFLOW_CONFIG_SCHEMA", ",", "'frameworkcontroller'", ":", "FRAMEWORKCONTROLLER_CONFIG_SCHEMA", "}", "separate_schema_dict", "=", "{", "'tuner'", ":", "tuner_schema_dict", ",", "'advisor'", ":", "advisor_schema_dict", ",", "'assessor'", ":", "assessor_schema_dict", "}", "separate_builtInName_dict", "=", "{", "'tuner'", ":", "'builtinTunerName'", ",", "'advisor'", ":", "'builtinAdvisorName'", ",", "'assessor'", ":", "'builtinAssessorName'", "}", "try", ":", "schema_dict", ".", "get", "(", "experiment_config", "[", "'trainingServicePlatform'", "]", ")", ".", "validate", "(", "experiment_config", ")", "for", "separate_key", "in", "separate_schema_dict", ".", "keys", "(", ")", ":", "if", "experiment_config", ".", "get", "(", "separate_key", ")", ":", "if", "experiment_config", "[", "separate_key", "]", ".", "get", "(", "separate_builtInName_dict", "[", "separate_key", "]", ")", ":", "validate", "=", "False", "for", "key", "in", "separate_schema_dict", "[", "separate_key", "]", ".", "keys", "(", ")", ":", "if", "key", ".", "__contains__", "(", "experiment_config", "[", "separate_key", "]", "[", "separate_builtInName_dict", "[", "separate_key", "]", "]", ")", ":", "Schema", "(", "{", "*", "*", "separate_schema_dict", "[", "separate_key", "]", "[", "key", "]", "}", ")", ".", "validate", "(", "experiment_config", "[", "separate_key", "]", ")", "validate", "=", "True", "break", "if", "not", "validate", ":", "print_error", "(", "'%s %s error!'", "%", "(", "separate_key", ",", "separate_builtInName_dict", "[", "separate_key", "]", ")", ")", "exit", "(", "1", ")", "else", ":", "Schema", "(", "{", "*", "*", "separate_schema_dict", "[", "separate_key", "]", "[", "'customized'", "]", "}", ")", ".", "validate", "(", "experiment_config", "[", "separate_key", "]", ")", "except", "SchemaError", "as", "error", ":", "print_error", "(", "'Your config file is not correct, please check your config file content!'", ")", "if", "error", ".", "__str__", "(", ")", ".", "__contains__", "(", "'Wrong key'", ")", ":", "print_error", "(", "' '", ".", "join", "(", "error", ".", "__str__", "(", ")", ".", "split", "(", ")", "[", ":", "3", "]", ")", ")", "else", ":", "print_error", "(", "error", ")", "exit", "(", "1", ")", "#set default value", "if", "experiment_config", ".", "get", "(", "'maxExecDuration'", ")", "is", "None", ":", "experiment_config", "[", "'maxExecDuration'", "]", "=", "'999d'", "if", "experiment_config", ".", "get", "(", "'maxTrialNum'", ")", "is", "None", ":", "experiment_config", "[", "'maxTrialNum'", "]", "=", "99999", "if", "experiment_config", "[", "'trainingServicePlatform'", "]", "==", "'remote'", ":", "for", "index", "in", "range", "(", "len", "(", "experiment_config", "[", "'machineList'", "]", ")", ")", ":", "if", "experiment_config", "[", "'machineList'", "]", "[", "index", "]", ".", "get", "(", "'port'", ")", "is", "None", ":", "experiment_config", "[", "'machineList'", "]", "[", "index", "]", "[", "'port'", "]", "=", "22" ]
Validate whether the common values in experiment_config is valid
[ "Validate", "whether", "the", "common", "values", "in", "experiment_config", "is", "valid" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher_utils.py#L127-L182
27,223
Microsoft/nni
tools/nni_cmd/launcher_utils.py
parse_assessor_content
def parse_assessor_content(experiment_config): '''Validate whether assessor in experiment_config is valid''' if experiment_config.get('assessor'): if experiment_config['assessor'].get('builtinAssessorName'): experiment_config['assessor']['className'] = experiment_config['assessor']['builtinAssessorName'] else: validate_customized_file(experiment_config, 'assessor')
python
def parse_assessor_content(experiment_config): '''Validate whether assessor in experiment_config is valid''' if experiment_config.get('assessor'): if experiment_config['assessor'].get('builtinAssessorName'): experiment_config['assessor']['className'] = experiment_config['assessor']['builtinAssessorName'] else: validate_customized_file(experiment_config, 'assessor')
[ "def", "parse_assessor_content", "(", "experiment_config", ")", ":", "if", "experiment_config", ".", "get", "(", "'assessor'", ")", ":", "if", "experiment_config", "[", "'assessor'", "]", ".", "get", "(", "'builtinAssessorName'", ")", ":", "experiment_config", "[", "'assessor'", "]", "[", "'className'", "]", "=", "experiment_config", "[", "'assessor'", "]", "[", "'builtinAssessorName'", "]", "else", ":", "validate_customized_file", "(", "experiment_config", ",", "'assessor'", ")" ]
Validate whether assessor in experiment_config is valid
[ "Validate", "whether", "assessor", "in", "experiment_config", "is", "valid" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher_utils.py#L208-L214
27,224
Microsoft/nni
tools/nni_cmd/launcher_utils.py
validate_pai_trial_conifg
def validate_pai_trial_conifg(experiment_config): '''validate the trial config in pai platform''' if experiment_config.get('trainingServicePlatform') == 'pai': if experiment_config.get('trial').get('shmMB') and \ experiment_config['trial']['shmMB'] > experiment_config['trial']['memoryMB']: print_error('shmMB should be no more than memoryMB!') exit(1)
python
def validate_pai_trial_conifg(experiment_config): '''validate the trial config in pai platform''' if experiment_config.get('trainingServicePlatform') == 'pai': if experiment_config.get('trial').get('shmMB') and \ experiment_config['trial']['shmMB'] > experiment_config['trial']['memoryMB']: print_error('shmMB should be no more than memoryMB!') exit(1)
[ "def", "validate_pai_trial_conifg", "(", "experiment_config", ")", ":", "if", "experiment_config", ".", "get", "(", "'trainingServicePlatform'", ")", "==", "'pai'", ":", "if", "experiment_config", ".", "get", "(", "'trial'", ")", ".", "get", "(", "'shmMB'", ")", "and", "experiment_config", "[", "'trial'", "]", "[", "'shmMB'", "]", ">", "experiment_config", "[", "'trial'", "]", "[", "'memoryMB'", "]", ":", "print_error", "(", "'shmMB should be no more than memoryMB!'", ")", "exit", "(", "1", ")" ]
validate the trial config in pai platform
[ "validate", "the", "trial", "config", "in", "pai", "platform" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher_utils.py#L249-L255
27,225
Microsoft/nni
tools/nni_cmd/launcher_utils.py
validate_all_content
def validate_all_content(experiment_config, config_path): '''Validate whether experiment_config is valid''' parse_path(experiment_config, config_path) validate_common_content(experiment_config) validate_pai_trial_conifg(experiment_config) experiment_config['maxExecDuration'] = parse_time(experiment_config['maxExecDuration']) if experiment_config.get('advisor'): if experiment_config.get('assessor') or experiment_config.get('tuner'): print_error('advisor could not be set with assessor or tuner simultaneously!') exit(1) parse_advisor_content(experiment_config) validate_annotation_content(experiment_config, 'advisor', 'builtinAdvisorName') else: if not experiment_config.get('tuner'): raise Exception('Please provide tuner spec!') parse_tuner_content(experiment_config) parse_assessor_content(experiment_config) validate_annotation_content(experiment_config, 'tuner', 'builtinTunerName')
python
def validate_all_content(experiment_config, config_path): '''Validate whether experiment_config is valid''' parse_path(experiment_config, config_path) validate_common_content(experiment_config) validate_pai_trial_conifg(experiment_config) experiment_config['maxExecDuration'] = parse_time(experiment_config['maxExecDuration']) if experiment_config.get('advisor'): if experiment_config.get('assessor') or experiment_config.get('tuner'): print_error('advisor could not be set with assessor or tuner simultaneously!') exit(1) parse_advisor_content(experiment_config) validate_annotation_content(experiment_config, 'advisor', 'builtinAdvisorName') else: if not experiment_config.get('tuner'): raise Exception('Please provide tuner spec!') parse_tuner_content(experiment_config) parse_assessor_content(experiment_config) validate_annotation_content(experiment_config, 'tuner', 'builtinTunerName')
[ "def", "validate_all_content", "(", "experiment_config", ",", "config_path", ")", ":", "parse_path", "(", "experiment_config", ",", "config_path", ")", "validate_common_content", "(", "experiment_config", ")", "validate_pai_trial_conifg", "(", "experiment_config", ")", "experiment_config", "[", "'maxExecDuration'", "]", "=", "parse_time", "(", "experiment_config", "[", "'maxExecDuration'", "]", ")", "if", "experiment_config", ".", "get", "(", "'advisor'", ")", ":", "if", "experiment_config", ".", "get", "(", "'assessor'", ")", "or", "experiment_config", ".", "get", "(", "'tuner'", ")", ":", "print_error", "(", "'advisor could not be set with assessor or tuner simultaneously!'", ")", "exit", "(", "1", ")", "parse_advisor_content", "(", "experiment_config", ")", "validate_annotation_content", "(", "experiment_config", ",", "'advisor'", ",", "'builtinAdvisorName'", ")", "else", ":", "if", "not", "experiment_config", ".", "get", "(", "'tuner'", ")", ":", "raise", "Exception", "(", "'Please provide tuner spec!'", ")", "parse_tuner_content", "(", "experiment_config", ")", "parse_assessor_content", "(", "experiment_config", ")", "validate_annotation_content", "(", "experiment_config", ",", "'tuner'", ",", "'builtinTunerName'", ")" ]
Validate whether experiment_config is valid
[ "Validate", "whether", "experiment_config", "is", "valid" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher_utils.py#L257-L274
27,226
Microsoft/nni
tools/nni_cmd/url_utils.py
get_local_urls
def get_local_urls(port): '''get urls of local machine''' url_list = [] for name, info in psutil.net_if_addrs().items(): for addr in info: if AddressFamily.AF_INET == addr.family: url_list.append('http://{}:{}'.format(addr.address, port)) return url_list
python
def get_local_urls(port): '''get urls of local machine''' url_list = [] for name, info in psutil.net_if_addrs().items(): for addr in info: if AddressFamily.AF_INET == addr.family: url_list.append('http://{}:{}'.format(addr.address, port)) return url_list
[ "def", "get_local_urls", "(", "port", ")", ":", "url_list", "=", "[", "]", "for", "name", ",", "info", "in", "psutil", ".", "net_if_addrs", "(", ")", ".", "items", "(", ")", ":", "for", "addr", "in", "info", ":", "if", "AddressFamily", ".", "AF_INET", "==", "addr", ".", "family", ":", "url_list", ".", "append", "(", "'http://{}:{}'", ".", "format", "(", "addr", ".", "address", ",", "port", ")", ")", "return", "url_list" ]
get urls of local machine
[ "get", "urls", "of", "local", "machine" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/url_utils.py#L76-L83
27,227
Microsoft/nni
tools/nni_annotation/code_generator.py
convert_args_to_dict
def convert_args_to_dict(call, with_lambda=False): """Convert all args to a dict such that every key and value in the dict is the same as the value of the arg. Return the AST Call node with only one arg that is the dictionary """ keys, values = list(), list() for arg in call.args: if type(arg) in [ast.Str, ast.Num]: arg_value = arg else: # if arg is not a string or a number, we use its source code as the key arg_value = astor.to_source(arg).strip('\n"') arg_value = ast.Str(str(arg_value)) arg = make_lambda(arg) if with_lambda else arg keys.append(arg_value) values.append(arg) del call.args[:] call.args.append(ast.Dict(keys=keys, values=values)) return call
python
def convert_args_to_dict(call, with_lambda=False): """Convert all args to a dict such that every key and value in the dict is the same as the value of the arg. Return the AST Call node with only one arg that is the dictionary """ keys, values = list(), list() for arg in call.args: if type(arg) in [ast.Str, ast.Num]: arg_value = arg else: # if arg is not a string or a number, we use its source code as the key arg_value = astor.to_source(arg).strip('\n"') arg_value = ast.Str(str(arg_value)) arg = make_lambda(arg) if with_lambda else arg keys.append(arg_value) values.append(arg) del call.args[:] call.args.append(ast.Dict(keys=keys, values=values)) return call
[ "def", "convert_args_to_dict", "(", "call", ",", "with_lambda", "=", "False", ")", ":", "keys", ",", "values", "=", "list", "(", ")", ",", "list", "(", ")", "for", "arg", "in", "call", ".", "args", ":", "if", "type", "(", "arg", ")", "in", "[", "ast", ".", "Str", ",", "ast", ".", "Num", "]", ":", "arg_value", "=", "arg", "else", ":", "# if arg is not a string or a number, we use its source code as the key", "arg_value", "=", "astor", ".", "to_source", "(", "arg", ")", ".", "strip", "(", "'\\n\"'", ")", "arg_value", "=", "ast", ".", "Str", "(", "str", "(", "arg_value", ")", ")", "arg", "=", "make_lambda", "(", "arg", ")", "if", "with_lambda", "else", "arg", "keys", ".", "append", "(", "arg_value", ")", "values", ".", "append", "(", "arg", ")", "del", "call", ".", "args", "[", ":", "]", "call", ".", "args", ".", "append", "(", "ast", ".", "Dict", "(", "keys", "=", "keys", ",", "values", "=", "values", ")", ")", "return", "call" ]
Convert all args to a dict such that every key and value in the dict is the same as the value of the arg. Return the AST Call node with only one arg that is the dictionary
[ "Convert", "all", "args", "to", "a", "dict", "such", "that", "every", "key", "and", "value", "in", "the", "dict", "is", "the", "same", "as", "the", "value", "of", "the", "arg", ".", "Return", "the", "AST", "Call", "node", "with", "only", "one", "arg", "that", "is", "the", "dictionary" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_annotation/code_generator.py#L100-L118
27,228
Microsoft/nni
src/sdk/pynni/nni/__main__.py
main
def main(): ''' main function. ''' args = parse_args() if args.multi_thread: enable_multi_thread() if args.advisor_class_name: # advisor is enabled and starts to run if args.multi_phase: raise AssertionError('multi_phase has not been supported in advisor') if args.advisor_class_name in AdvisorModuleName: dispatcher = create_builtin_class_instance( args.advisor_class_name, args.advisor_args, True) else: dispatcher = create_customized_class_instance( args.advisor_directory, args.advisor_class_filename, args.advisor_class_name, args.advisor_args) if dispatcher is None: raise AssertionError('Failed to create Advisor instance') try: dispatcher.run() except Exception as exception: logger.exception(exception) raise else: # tuner (and assessor) is enabled and starts to run tuner = None assessor = None if args.tuner_class_name in ModuleName: tuner = create_builtin_class_instance( args.tuner_class_name, args.tuner_args) else: tuner = create_customized_class_instance( args.tuner_directory, args.tuner_class_filename, args.tuner_class_name, args.tuner_args) if tuner is None: raise AssertionError('Failed to create Tuner instance') if args.assessor_class_name: if args.assessor_class_name in ModuleName: assessor = create_builtin_class_instance( args.assessor_class_name, args.assessor_args) else: assessor = create_customized_class_instance( args.assessor_directory, args.assessor_class_filename, args.assessor_class_name, args.assessor_args) if assessor is None: raise AssertionError('Failed to create Assessor instance') if args.multi_phase: dispatcher = MultiPhaseMsgDispatcher(tuner, assessor) else: dispatcher = MsgDispatcher(tuner, assessor) try: dispatcher.run() tuner._on_exit() if assessor is not None: assessor._on_exit() except Exception as exception: logger.exception(exception) tuner._on_error() if assessor is not None: assessor._on_error() raise
python
def main(): ''' main function. ''' args = parse_args() if args.multi_thread: enable_multi_thread() if args.advisor_class_name: # advisor is enabled and starts to run if args.multi_phase: raise AssertionError('multi_phase has not been supported in advisor') if args.advisor_class_name in AdvisorModuleName: dispatcher = create_builtin_class_instance( args.advisor_class_name, args.advisor_args, True) else: dispatcher = create_customized_class_instance( args.advisor_directory, args.advisor_class_filename, args.advisor_class_name, args.advisor_args) if dispatcher is None: raise AssertionError('Failed to create Advisor instance') try: dispatcher.run() except Exception as exception: logger.exception(exception) raise else: # tuner (and assessor) is enabled and starts to run tuner = None assessor = None if args.tuner_class_name in ModuleName: tuner = create_builtin_class_instance( args.tuner_class_name, args.tuner_args) else: tuner = create_customized_class_instance( args.tuner_directory, args.tuner_class_filename, args.tuner_class_name, args.tuner_args) if tuner is None: raise AssertionError('Failed to create Tuner instance') if args.assessor_class_name: if args.assessor_class_name in ModuleName: assessor = create_builtin_class_instance( args.assessor_class_name, args.assessor_args) else: assessor = create_customized_class_instance( args.assessor_directory, args.assessor_class_filename, args.assessor_class_name, args.assessor_args) if assessor is None: raise AssertionError('Failed to create Assessor instance') if args.multi_phase: dispatcher = MultiPhaseMsgDispatcher(tuner, assessor) else: dispatcher = MsgDispatcher(tuner, assessor) try: dispatcher.run() tuner._on_exit() if assessor is not None: assessor._on_exit() except Exception as exception: logger.exception(exception) tuner._on_error() if assessor is not None: assessor._on_error() raise
[ "def", "main", "(", ")", ":", "args", "=", "parse_args", "(", ")", "if", "args", ".", "multi_thread", ":", "enable_multi_thread", "(", ")", "if", "args", ".", "advisor_class_name", ":", "# advisor is enabled and starts to run", "if", "args", ".", "multi_phase", ":", "raise", "AssertionError", "(", "'multi_phase has not been supported in advisor'", ")", "if", "args", ".", "advisor_class_name", "in", "AdvisorModuleName", ":", "dispatcher", "=", "create_builtin_class_instance", "(", "args", ".", "advisor_class_name", ",", "args", ".", "advisor_args", ",", "True", ")", "else", ":", "dispatcher", "=", "create_customized_class_instance", "(", "args", ".", "advisor_directory", ",", "args", ".", "advisor_class_filename", ",", "args", ".", "advisor_class_name", ",", "args", ".", "advisor_args", ")", "if", "dispatcher", "is", "None", ":", "raise", "AssertionError", "(", "'Failed to create Advisor instance'", ")", "try", ":", "dispatcher", ".", "run", "(", ")", "except", "Exception", "as", "exception", ":", "logger", ".", "exception", "(", "exception", ")", "raise", "else", ":", "# tuner (and assessor) is enabled and starts to run", "tuner", "=", "None", "assessor", "=", "None", "if", "args", ".", "tuner_class_name", "in", "ModuleName", ":", "tuner", "=", "create_builtin_class_instance", "(", "args", ".", "tuner_class_name", ",", "args", ".", "tuner_args", ")", "else", ":", "tuner", "=", "create_customized_class_instance", "(", "args", ".", "tuner_directory", ",", "args", ".", "tuner_class_filename", ",", "args", ".", "tuner_class_name", ",", "args", ".", "tuner_args", ")", "if", "tuner", "is", "None", ":", "raise", "AssertionError", "(", "'Failed to create Tuner instance'", ")", "if", "args", ".", "assessor_class_name", ":", "if", "args", ".", "assessor_class_name", "in", "ModuleName", ":", "assessor", "=", "create_builtin_class_instance", "(", "args", ".", "assessor_class_name", ",", "args", ".", "assessor_args", ")", "else", ":", "assessor", "=", "create_customized_class_instance", "(", "args", ".", "assessor_directory", ",", "args", ".", "assessor_class_filename", ",", "args", ".", "assessor_class_name", ",", "args", ".", "assessor_args", ")", "if", "assessor", "is", "None", ":", "raise", "AssertionError", "(", "'Failed to create Assessor instance'", ")", "if", "args", ".", "multi_phase", ":", "dispatcher", "=", "MultiPhaseMsgDispatcher", "(", "tuner", ",", "assessor", ")", "else", ":", "dispatcher", "=", "MsgDispatcher", "(", "tuner", ",", "assessor", ")", "try", ":", "dispatcher", ".", "run", "(", ")", "tuner", ".", "_on_exit", "(", ")", "if", "assessor", "is", "not", "None", ":", "assessor", ".", "_on_exit", "(", ")", "except", "Exception", "as", "exception", ":", "logger", ".", "exception", "(", "exception", ")", "tuner", ".", "_on_error", "(", ")", "if", "assessor", "is", "not", "None", ":", "assessor", ".", "_on_error", "(", ")", "raise" ]
main function.
[ "main", "function", "." ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/__main__.py#L121-L198
27,229
Microsoft/nni
tools/nni_cmd/common_utils.py
get_yml_content
def get_yml_content(file_path): '''Load yaml file content''' try: with open(file_path, 'r') as file: return yaml.load(file, Loader=yaml.Loader) except yaml.scanner.ScannerError as err: print_error('yaml file format error!') exit(1) except Exception as exception: print_error(exception) exit(1)
python
def get_yml_content(file_path): '''Load yaml file content''' try: with open(file_path, 'r') as file: return yaml.load(file, Loader=yaml.Loader) except yaml.scanner.ScannerError as err: print_error('yaml file format error!') exit(1) except Exception as exception: print_error(exception) exit(1)
[ "def", "get_yml_content", "(", "file_path", ")", ":", "try", ":", "with", "open", "(", "file_path", ",", "'r'", ")", "as", "file", ":", "return", "yaml", ".", "load", "(", "file", ",", "Loader", "=", "yaml", ".", "Loader", ")", "except", "yaml", ".", "scanner", ".", "ScannerError", "as", "err", ":", "print_error", "(", "'yaml file format error!'", ")", "exit", "(", "1", ")", "except", "Exception", "as", "exception", ":", "print_error", "(", "exception", ")", "exit", "(", "1", ")" ]
Load yaml file content
[ "Load", "yaml", "file", "content" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/common_utils.py#L30-L40
27,230
Microsoft/nni
tools/nni_cmd/common_utils.py
detect_port
def detect_port(port): '''Detect if the port is used''' socket_test = socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: socket_test.connect(('127.0.0.1', int(port))) socket_test.close() return True except: return False
python
def detect_port(port): '''Detect if the port is used''' socket_test = socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: socket_test.connect(('127.0.0.1', int(port))) socket_test.close() return True except: return False
[ "def", "detect_port", "(", "port", ")", ":", "socket_test", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "try", ":", "socket_test", ".", "connect", "(", "(", "'127.0.0.1'", ",", "int", "(", "port", ")", ")", ")", "socket_test", ".", "close", "(", ")", "return", "True", "except", ":", "return", "False" ]
Detect if the port is used
[ "Detect", "if", "the", "port", "is", "used" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/common_utils.py#L71-L79
27,231
Microsoft/nni
src/sdk/pynni/nni/metis_tuner/Regression_GMM/CreateModel.py
create_model
def create_model(samples_x, samples_y_aggregation, percentage_goodbatch=0.34): ''' Create the Gaussian Mixture Model ''' samples = [samples_x[i] + [samples_y_aggregation[i]] for i in range(0, len(samples_x))] # Sorts so that we can get the top samples samples = sorted(samples, key=itemgetter(-1)) samples_goodbatch_size = int(len(samples) * percentage_goodbatch) samples_goodbatch = samples[0:samples_goodbatch_size] samples_badbatch = samples[samples_goodbatch_size:] samples_x_goodbatch = [sample_goodbatch[0:-1] for sample_goodbatch in samples_goodbatch] #samples_y_goodbatch = [sample_goodbatch[-1] for sample_goodbatch in samples_goodbatch] samples_x_badbatch = [sample_badbatch[0:-1] for sample_badbatch in samples_badbatch] # === Trains GMM clustering models === # #sys.stderr.write("[%s] Train GMM's GMM model\n" % (os.path.basename(__file__))) bgmm_goodbatch = mm.BayesianGaussianMixture(n_components=max(1, samples_goodbatch_size - 1)) bad_n_components = max(1, len(samples_x) - samples_goodbatch_size - 1) bgmm_badbatch = mm.BayesianGaussianMixture(n_components=bad_n_components) bgmm_goodbatch.fit(samples_x_goodbatch) bgmm_badbatch.fit(samples_x_badbatch) model = {} model['clusteringmodel_good'] = bgmm_goodbatch model['clusteringmodel_bad'] = bgmm_badbatch return model
python
def create_model(samples_x, samples_y_aggregation, percentage_goodbatch=0.34): ''' Create the Gaussian Mixture Model ''' samples = [samples_x[i] + [samples_y_aggregation[i]] for i in range(0, len(samples_x))] # Sorts so that we can get the top samples samples = sorted(samples, key=itemgetter(-1)) samples_goodbatch_size = int(len(samples) * percentage_goodbatch) samples_goodbatch = samples[0:samples_goodbatch_size] samples_badbatch = samples[samples_goodbatch_size:] samples_x_goodbatch = [sample_goodbatch[0:-1] for sample_goodbatch in samples_goodbatch] #samples_y_goodbatch = [sample_goodbatch[-1] for sample_goodbatch in samples_goodbatch] samples_x_badbatch = [sample_badbatch[0:-1] for sample_badbatch in samples_badbatch] # === Trains GMM clustering models === # #sys.stderr.write("[%s] Train GMM's GMM model\n" % (os.path.basename(__file__))) bgmm_goodbatch = mm.BayesianGaussianMixture(n_components=max(1, samples_goodbatch_size - 1)) bad_n_components = max(1, len(samples_x) - samples_goodbatch_size - 1) bgmm_badbatch = mm.BayesianGaussianMixture(n_components=bad_n_components) bgmm_goodbatch.fit(samples_x_goodbatch) bgmm_badbatch.fit(samples_x_badbatch) model = {} model['clusteringmodel_good'] = bgmm_goodbatch model['clusteringmodel_bad'] = bgmm_badbatch return model
[ "def", "create_model", "(", "samples_x", ",", "samples_y_aggregation", ",", "percentage_goodbatch", "=", "0.34", ")", ":", "samples", "=", "[", "samples_x", "[", "i", "]", "+", "[", "samples_y_aggregation", "[", "i", "]", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "samples_x", ")", ")", "]", "# Sorts so that we can get the top samples", "samples", "=", "sorted", "(", "samples", ",", "key", "=", "itemgetter", "(", "-", "1", ")", ")", "samples_goodbatch_size", "=", "int", "(", "len", "(", "samples", ")", "*", "percentage_goodbatch", ")", "samples_goodbatch", "=", "samples", "[", "0", ":", "samples_goodbatch_size", "]", "samples_badbatch", "=", "samples", "[", "samples_goodbatch_size", ":", "]", "samples_x_goodbatch", "=", "[", "sample_goodbatch", "[", "0", ":", "-", "1", "]", "for", "sample_goodbatch", "in", "samples_goodbatch", "]", "#samples_y_goodbatch = [sample_goodbatch[-1] for sample_goodbatch in samples_goodbatch]", "samples_x_badbatch", "=", "[", "sample_badbatch", "[", "0", ":", "-", "1", "]", "for", "sample_badbatch", "in", "samples_badbatch", "]", "# === Trains GMM clustering models === #", "#sys.stderr.write(\"[%s] Train GMM's GMM model\\n\" % (os.path.basename(__file__)))", "bgmm_goodbatch", "=", "mm", ".", "BayesianGaussianMixture", "(", "n_components", "=", "max", "(", "1", ",", "samples_goodbatch_size", "-", "1", ")", ")", "bad_n_components", "=", "max", "(", "1", ",", "len", "(", "samples_x", ")", "-", "samples_goodbatch_size", "-", "1", ")", "bgmm_badbatch", "=", "mm", ".", "BayesianGaussianMixture", "(", "n_components", "=", "bad_n_components", ")", "bgmm_goodbatch", ".", "fit", "(", "samples_x_goodbatch", ")", "bgmm_badbatch", ".", "fit", "(", "samples_x_badbatch", ")", "model", "=", "{", "}", "model", "[", "'clusteringmodel_good'", "]", "=", "bgmm_goodbatch", "model", "[", "'clusteringmodel_bad'", "]", "=", "bgmm_badbatch", "return", "model" ]
Create the Gaussian Mixture Model
[ "Create", "the", "Gaussian", "Mixture", "Model" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/Regression_GMM/CreateModel.py#L30-L57
27,232
Microsoft/nni
src/sdk/pynni/nni/metis_tuner/Regression_GP/Selection.py
selection_r
def selection_r(acquisition_function, samples_y_aggregation, x_bounds, x_types, regressor_gp, num_starting_points=100, minimize_constraints_fun=None): ''' Selecte R value ''' minimize_starting_points = [lib_data.rand(x_bounds, x_types) \ for i in range(0, num_starting_points)] outputs = selection(acquisition_function, samples_y_aggregation, x_bounds, x_types, regressor_gp, minimize_starting_points, minimize_constraints_fun=minimize_constraints_fun) return outputs
python
def selection_r(acquisition_function, samples_y_aggregation, x_bounds, x_types, regressor_gp, num_starting_points=100, minimize_constraints_fun=None): ''' Selecte R value ''' minimize_starting_points = [lib_data.rand(x_bounds, x_types) \ for i in range(0, num_starting_points)] outputs = selection(acquisition_function, samples_y_aggregation, x_bounds, x_types, regressor_gp, minimize_starting_points, minimize_constraints_fun=minimize_constraints_fun) return outputs
[ "def", "selection_r", "(", "acquisition_function", ",", "samples_y_aggregation", ",", "x_bounds", ",", "x_types", ",", "regressor_gp", ",", "num_starting_points", "=", "100", ",", "minimize_constraints_fun", "=", "None", ")", ":", "minimize_starting_points", "=", "[", "lib_data", ".", "rand", "(", "x_bounds", ",", "x_types", ")", "for", "i", "in", "range", "(", "0", ",", "num_starting_points", ")", "]", "outputs", "=", "selection", "(", "acquisition_function", ",", "samples_y_aggregation", ",", "x_bounds", ",", "x_types", ",", "regressor_gp", ",", "minimize_starting_points", ",", "minimize_constraints_fun", "=", "minimize_constraints_fun", ")", "return", "outputs" ]
Selecte R value
[ "Selecte", "R", "value" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/Regression_GP/Selection.py#L37-L54
27,233
Microsoft/nni
examples/trials/network_morphism/FashionMNIST/FashionMNIST_pytorch.py
get_args
def get_args(): """ get args from command line """ parser = argparse.ArgumentParser("FashionMNIST") parser.add_argument("--batch_size", type=int, default=128, help="batch size") parser.add_argument("--optimizer", type=str, default="SGD", help="optimizer") parser.add_argument("--epochs", type=int, default=200, help="epoch limit") parser.add_argument( "--learning_rate", type=float, default=0.001, help="learning rate" ) parser.add_argument("--cutout", action="store_true", default=False, help="use cutout") parser.add_argument("--cutout_length", type=int, default=8, help="cutout length") parser.add_argument( "--model_path", type=str, default="./", help="Path to save the destination model" ) return parser.parse_args()
python
def get_args(): """ get args from command line """ parser = argparse.ArgumentParser("FashionMNIST") parser.add_argument("--batch_size", type=int, default=128, help="batch size") parser.add_argument("--optimizer", type=str, default="SGD", help="optimizer") parser.add_argument("--epochs", type=int, default=200, help="epoch limit") parser.add_argument( "--learning_rate", type=float, default=0.001, help="learning rate" ) parser.add_argument("--cutout", action="store_true", default=False, help="use cutout") parser.add_argument("--cutout_length", type=int, default=8, help="cutout length") parser.add_argument( "--model_path", type=str, default="./", help="Path to save the destination model" ) return parser.parse_args()
[ "def", "get_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "\"FashionMNIST\"", ")", "parser", ".", "add_argument", "(", "\"--batch_size\"", ",", "type", "=", "int", ",", "default", "=", "128", ",", "help", "=", "\"batch size\"", ")", "parser", ".", "add_argument", "(", "\"--optimizer\"", ",", "type", "=", "str", ",", "default", "=", "\"SGD\"", ",", "help", "=", "\"optimizer\"", ")", "parser", ".", "add_argument", "(", "\"--epochs\"", ",", "type", "=", "int", ",", "default", "=", "200", ",", "help", "=", "\"epoch limit\"", ")", "parser", ".", "add_argument", "(", "\"--learning_rate\"", ",", "type", "=", "float", ",", "default", "=", "0.001", ",", "help", "=", "\"learning rate\"", ")", "parser", ".", "add_argument", "(", "\"--cutout\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "help", "=", "\"use cutout\"", ")", "parser", ".", "add_argument", "(", "\"--cutout_length\"", ",", "type", "=", "int", ",", "default", "=", "8", ",", "help", "=", "\"cutout length\"", ")", "parser", ".", "add_argument", "(", "\"--model_path\"", ",", "type", "=", "str", ",", "default", "=", "\"./\"", ",", "help", "=", "\"Path to save the destination model\"", ")", "return", "parser", ".", "parse_args", "(", ")" ]
get args from command line
[ "get", "args", "from", "command", "line" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/network_morphism/FashionMNIST/FashionMNIST_pytorch.py#L47-L62
27,234
Microsoft/nni
examples/trials/network_morphism/FashionMNIST/FashionMNIST_pytorch.py
build_graph_from_json
def build_graph_from_json(ir_model_json): """build model from json representation """ graph = json_to_graph(ir_model_json) logging.debug(graph.operation_history) model = graph.produce_torch_model() return model
python
def build_graph_from_json(ir_model_json): """build model from json representation """ graph = json_to_graph(ir_model_json) logging.debug(graph.operation_history) model = graph.produce_torch_model() return model
[ "def", "build_graph_from_json", "(", "ir_model_json", ")", ":", "graph", "=", "json_to_graph", "(", "ir_model_json", ")", "logging", ".", "debug", "(", "graph", ".", "operation_history", ")", "model", "=", "graph", ".", "produce_torch_model", "(", ")", "return", "model" ]
build model from json representation
[ "build", "model", "from", "json", "representation" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/network_morphism/FashionMNIST/FashionMNIST_pytorch.py#L75-L81
27,235
Microsoft/nni
examples/trials/network_morphism/FashionMNIST/FashionMNIST_pytorch.py
train
def train(epoch): """ train model on each epoch in trainset """ global trainloader global testloader global net global criterion global optimizer logger.debug("Epoch: %d", epoch) net.train() train_loss = 0 correct = 0 total = 0 for batch_idx, (inputs, targets) in enumerate(trainloader): inputs, targets = inputs.to(device), targets.to(device) optimizer.zero_grad() outputs = net(inputs) loss = criterion(outputs, targets) loss.backward() optimizer.step() train_loss += loss.item() _, predicted = outputs.max(1) total += targets.size(0) correct += predicted.eq(targets).sum().item() acc = 100.0 * correct / total logger.debug( "Loss: %.3f | Acc: %.3f%% (%d/%d)", train_loss / (batch_idx + 1), 100.0 * correct / total, correct, total, ) return acc
python
def train(epoch): """ train model on each epoch in trainset """ global trainloader global testloader global net global criterion global optimizer logger.debug("Epoch: %d", epoch) net.train() train_loss = 0 correct = 0 total = 0 for batch_idx, (inputs, targets) in enumerate(trainloader): inputs, targets = inputs.to(device), targets.to(device) optimizer.zero_grad() outputs = net(inputs) loss = criterion(outputs, targets) loss.backward() optimizer.step() train_loss += loss.item() _, predicted = outputs.max(1) total += targets.size(0) correct += predicted.eq(targets).sum().item() acc = 100.0 * correct / total logger.debug( "Loss: %.3f | Acc: %.3f%% (%d/%d)", train_loss / (batch_idx + 1), 100.0 * correct / total, correct, total, ) return acc
[ "def", "train", "(", "epoch", ")", ":", "global", "trainloader", "global", "testloader", "global", "net", "global", "criterion", "global", "optimizer", "logger", ".", "debug", "(", "\"Epoch: %d\"", ",", "epoch", ")", "net", ".", "train", "(", ")", "train_loss", "=", "0", "correct", "=", "0", "total", "=", "0", "for", "batch_idx", ",", "(", "inputs", ",", "targets", ")", "in", "enumerate", "(", "trainloader", ")", ":", "inputs", ",", "targets", "=", "inputs", ".", "to", "(", "device", ")", ",", "targets", ".", "to", "(", "device", ")", "optimizer", ".", "zero_grad", "(", ")", "outputs", "=", "net", "(", "inputs", ")", "loss", "=", "criterion", "(", "outputs", ",", "targets", ")", "loss", ".", "backward", "(", ")", "optimizer", ".", "step", "(", ")", "train_loss", "+=", "loss", ".", "item", "(", ")", "_", ",", "predicted", "=", "outputs", ".", "max", "(", "1", ")", "total", "+=", "targets", ".", "size", "(", "0", ")", "correct", "+=", "predicted", ".", "eq", "(", "targets", ")", ".", "sum", "(", ")", ".", "item", "(", ")", "acc", "=", "100.0", "*", "correct", "/", "total", "logger", ".", "debug", "(", "\"Loss: %.3f | Acc: %.3f%% (%d/%d)\"", ",", "train_loss", "/", "(", "batch_idx", "+", "1", ")", ",", "100.0", "*", "correct", "/", "total", ",", "correct", ",", "total", ",", ")", "return", "acc" ]
train model on each epoch in trainset
[ "train", "model", "on", "each", "epoch", "in", "trainset" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/network_morphism/FashionMNIST/FashionMNIST_pytorch.py#L149-L188
27,236
Microsoft/nni
examples/trials/kaggle-tgs-salt/models.py
UNetResNetV4.freeze_bn
def freeze_bn(self): '''Freeze BatchNorm layers.''' for layer in self.modules(): if isinstance(layer, nn.BatchNorm2d): layer.eval()
python
def freeze_bn(self): '''Freeze BatchNorm layers.''' for layer in self.modules(): if isinstance(layer, nn.BatchNorm2d): layer.eval()
[ "def", "freeze_bn", "(", "self", ")", ":", "for", "layer", "in", "self", ".", "modules", "(", ")", ":", "if", "isinstance", "(", "layer", ",", "nn", ".", "BatchNorm2d", ")", ":", "layer", ".", "eval", "(", ")" ]
Freeze BatchNorm layers.
[ "Freeze", "BatchNorm", "layers", "." ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/kaggle-tgs-salt/models.py#L210-L214
27,237
tensorpack/tensorpack
tensorpack/utils/nvml.py
NvidiaDevice.memory
def memory(self): """Memory information in bytes Example: >>> print(ctx.device(0).memory()) {'total': 4238016512L, 'used': 434831360L, 'free': 3803185152L} Returns: total/used/free memory in bytes """ class GpuMemoryInfo(Structure): _fields_ = [ ('total', c_ulonglong), ('free', c_ulonglong), ('used', c_ulonglong), ] c_memory = GpuMemoryInfo() _check_return(_NVML.get_function( "nvmlDeviceGetMemoryInfo")(self.hnd, byref(c_memory))) return {'total': c_memory.total, 'free': c_memory.free, 'used': c_memory.used}
python
def memory(self): """Memory information in bytes Example: >>> print(ctx.device(0).memory()) {'total': 4238016512L, 'used': 434831360L, 'free': 3803185152L} Returns: total/used/free memory in bytes """ class GpuMemoryInfo(Structure): _fields_ = [ ('total', c_ulonglong), ('free', c_ulonglong), ('used', c_ulonglong), ] c_memory = GpuMemoryInfo() _check_return(_NVML.get_function( "nvmlDeviceGetMemoryInfo")(self.hnd, byref(c_memory))) return {'total': c_memory.total, 'free': c_memory.free, 'used': c_memory.used}
[ "def", "memory", "(", "self", ")", ":", "class", "GpuMemoryInfo", "(", "Structure", ")", ":", "_fields_", "=", "[", "(", "'total'", ",", "c_ulonglong", ")", ",", "(", "'free'", ",", "c_ulonglong", ")", ",", "(", "'used'", ",", "c_ulonglong", ")", ",", "]", "c_memory", "=", "GpuMemoryInfo", "(", ")", "_check_return", "(", "_NVML", ".", "get_function", "(", "\"nvmlDeviceGetMemoryInfo\"", ")", "(", "self", ".", "hnd", ",", "byref", "(", "c_memory", ")", ")", ")", "return", "{", "'total'", ":", "c_memory", ".", "total", ",", "'free'", ":", "c_memory", ".", "free", ",", "'used'", ":", "c_memory", ".", "used", "}" ]
Memory information in bytes Example: >>> print(ctx.device(0).memory()) {'total': 4238016512L, 'used': 434831360L, 'free': 3803185152L} Returns: total/used/free memory in bytes
[ "Memory", "information", "in", "bytes" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/nvml.py#L92-L113
27,238
tensorpack/tensorpack
tensorpack/utils/nvml.py
NvidiaDevice.utilization
def utilization(self): """Percent of time over the past second was utilized. Details: Percent of time over the past second during which one or more kernels was executing on the GPU. Percent of time over the past second during which global (device) memory was being read or written Example: >>> print(ctx.device(0).utilization()) {'gpu': 4L, 'memory': 6L} """ class GpuUtilizationInfo(Structure): _fields_ = [ ('gpu', c_uint), ('memory', c_uint), ] c_util = GpuUtilizationInfo() _check_return(_NVML.get_function( "nvmlDeviceGetUtilizationRates")(self.hnd, byref(c_util))) return {'gpu': c_util.gpu, 'memory': c_util.memory}
python
def utilization(self): """Percent of time over the past second was utilized. Details: Percent of time over the past second during which one or more kernels was executing on the GPU. Percent of time over the past second during which global (device) memory was being read or written Example: >>> print(ctx.device(0).utilization()) {'gpu': 4L, 'memory': 6L} """ class GpuUtilizationInfo(Structure): _fields_ = [ ('gpu', c_uint), ('memory', c_uint), ] c_util = GpuUtilizationInfo() _check_return(_NVML.get_function( "nvmlDeviceGetUtilizationRates")(self.hnd, byref(c_util))) return {'gpu': c_util.gpu, 'memory': c_util.memory}
[ "def", "utilization", "(", "self", ")", ":", "class", "GpuUtilizationInfo", "(", "Structure", ")", ":", "_fields_", "=", "[", "(", "'gpu'", ",", "c_uint", ")", ",", "(", "'memory'", ",", "c_uint", ")", ",", "]", "c_util", "=", "GpuUtilizationInfo", "(", ")", "_check_return", "(", "_NVML", ".", "get_function", "(", "\"nvmlDeviceGetUtilizationRates\"", ")", "(", "self", ".", "hnd", ",", "byref", "(", "c_util", ")", ")", ")", "return", "{", "'gpu'", ":", "c_util", ".", "gpu", ",", "'memory'", ":", "c_util", ".", "memory", "}" ]
Percent of time over the past second was utilized. Details: Percent of time over the past second during which one or more kernels was executing on the GPU. Percent of time over the past second during which global (device) memory was being read or written Example: >>> print(ctx.device(0).utilization()) {'gpu': 4L, 'memory': 6L}
[ "Percent", "of", "time", "over", "the", "past", "second", "was", "utilized", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/nvml.py#L115-L138
27,239
tensorpack/tensorpack
tensorpack/utils/nvml.py
NVMLContext.num_devices
def num_devices(self): """Get number of devices """ c_count = c_uint() _check_return(_NVML.get_function( "nvmlDeviceGetCount_v2")(byref(c_count))) return c_count.value
python
def num_devices(self): """Get number of devices """ c_count = c_uint() _check_return(_NVML.get_function( "nvmlDeviceGetCount_v2")(byref(c_count))) return c_count.value
[ "def", "num_devices", "(", "self", ")", ":", "c_count", "=", "c_uint", "(", ")", "_check_return", "(", "_NVML", ".", "get_function", "(", "\"nvmlDeviceGetCount_v2\"", ")", "(", "byref", "(", "c_count", ")", ")", ")", "return", "c_count", ".", "value" ]
Get number of devices
[ "Get", "number", "of", "devices" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/nvml.py#L171-L176
27,240
tensorpack/tensorpack
tensorpack/utils/nvml.py
NVMLContext.device
def device(self, idx): """Get a specific GPU device Args: idx: index of device Returns: NvidiaDevice: single GPU device """ class GpuDevice(Structure): pass c_nvmlDevice_t = POINTER(GpuDevice) c_index = c_uint(idx) device = c_nvmlDevice_t() _check_return(_NVML.get_function( "nvmlDeviceGetHandleByIndex_v2")(c_index, byref(device))) return NvidiaDevice(device)
python
def device(self, idx): """Get a specific GPU device Args: idx: index of device Returns: NvidiaDevice: single GPU device """ class GpuDevice(Structure): pass c_nvmlDevice_t = POINTER(GpuDevice) c_index = c_uint(idx) device = c_nvmlDevice_t() _check_return(_NVML.get_function( "nvmlDeviceGetHandleByIndex_v2")(c_index, byref(device))) return NvidiaDevice(device)
[ "def", "device", "(", "self", ",", "idx", ")", ":", "class", "GpuDevice", "(", "Structure", ")", ":", "pass", "c_nvmlDevice_t", "=", "POINTER", "(", "GpuDevice", ")", "c_index", "=", "c_uint", "(", "idx", ")", "device", "=", "c_nvmlDevice_t", "(", ")", "_check_return", "(", "_NVML", ".", "get_function", "(", "\"nvmlDeviceGetHandleByIndex_v2\"", ")", "(", "c_index", ",", "byref", "(", "device", ")", ")", ")", "return", "NvidiaDevice", "(", "device", ")" ]
Get a specific GPU device Args: idx: index of device Returns: NvidiaDevice: single GPU device
[ "Get", "a", "specific", "GPU", "device" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/nvml.py#L185-L204
27,241
tensorpack/tensorpack
tensorpack/dataflow/dataset/cifar.py
maybe_download_and_extract
def maybe_download_and_extract(dest_directory, cifar_classnum): """Download and extract the tarball from Alex's website. Copied from tensorflow example """ assert cifar_classnum == 10 or cifar_classnum == 100 if cifar_classnum == 10: cifar_foldername = 'cifar-10-batches-py' else: cifar_foldername = 'cifar-100-python' if os.path.isdir(os.path.join(dest_directory, cifar_foldername)): logger.info("Found cifar{} data in {}.".format(cifar_classnum, dest_directory)) return else: DATA_URL = DATA_URL_CIFAR_10 if cifar_classnum == 10 else DATA_URL_CIFAR_100 filename = DATA_URL[0].split('/')[-1] filepath = os.path.join(dest_directory, filename) download(DATA_URL[0], dest_directory, expect_size=DATA_URL[1]) tarfile.open(filepath, 'r:gz').extractall(dest_directory)
python
def maybe_download_and_extract(dest_directory, cifar_classnum): """Download and extract the tarball from Alex's website. Copied from tensorflow example """ assert cifar_classnum == 10 or cifar_classnum == 100 if cifar_classnum == 10: cifar_foldername = 'cifar-10-batches-py' else: cifar_foldername = 'cifar-100-python' if os.path.isdir(os.path.join(dest_directory, cifar_foldername)): logger.info("Found cifar{} data in {}.".format(cifar_classnum, dest_directory)) return else: DATA_URL = DATA_URL_CIFAR_10 if cifar_classnum == 10 else DATA_URL_CIFAR_100 filename = DATA_URL[0].split('/')[-1] filepath = os.path.join(dest_directory, filename) download(DATA_URL[0], dest_directory, expect_size=DATA_URL[1]) tarfile.open(filepath, 'r:gz').extractall(dest_directory)
[ "def", "maybe_download_and_extract", "(", "dest_directory", ",", "cifar_classnum", ")", ":", "assert", "cifar_classnum", "==", "10", "or", "cifar_classnum", "==", "100", "if", "cifar_classnum", "==", "10", ":", "cifar_foldername", "=", "'cifar-10-batches-py'", "else", ":", "cifar_foldername", "=", "'cifar-100-python'", "if", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "dest_directory", ",", "cifar_foldername", ")", ")", ":", "logger", ".", "info", "(", "\"Found cifar{} data in {}.\"", ".", "format", "(", "cifar_classnum", ",", "dest_directory", ")", ")", "return", "else", ":", "DATA_URL", "=", "DATA_URL_CIFAR_10", "if", "cifar_classnum", "==", "10", "else", "DATA_URL_CIFAR_100", "filename", "=", "DATA_URL", "[", "0", "]", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "filepath", "=", "os", ".", "path", ".", "join", "(", "dest_directory", ",", "filename", ")", "download", "(", "DATA_URL", "[", "0", "]", ",", "dest_directory", ",", "expect_size", "=", "DATA_URL", "[", "1", "]", ")", "tarfile", ".", "open", "(", "filepath", ",", "'r:gz'", ")", ".", "extractall", "(", "dest_directory", ")" ]
Download and extract the tarball from Alex's website. Copied from tensorflow example
[ "Download", "and", "extract", "the", "tarball", "from", "Alex", "s", "website", ".", "Copied", "from", "tensorflow", "example" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/cifar.py#L24-L39
27,242
tensorpack/tensorpack
tensorpack/graph_builder/model_desc.py
build_or_reuse_placeholder
def build_or_reuse_placeholder(tensor_spec): """ Build a tf.placeholder from the metadata in the given tensor spec, or return an existing one. Args: tensor_spec (tf.TensorSpec): Returns: tf.Tensor: """ g = tfv1.get_default_graph() name = tensor_spec.name try: tensor = g.get_tensor_by_name(name + ':0') assert "Placeholder" in tensor.op.type, "Tensor {} exists but is not a placeholder!".format(name) assert tensor_spec.is_compatible_with(tensor), \ "Tensor {} exists but is not compatible with the signature!".format(tensor) return tensor except KeyError: with tfv1.name_scope(None): # clear any name scope it might get called in ret = tfv1.placeholder( tensor_spec.dtype, shape=tensor_spec.shape, name=tensor_spec.name) return ret
python
def build_or_reuse_placeholder(tensor_spec): """ Build a tf.placeholder from the metadata in the given tensor spec, or return an existing one. Args: tensor_spec (tf.TensorSpec): Returns: tf.Tensor: """ g = tfv1.get_default_graph() name = tensor_spec.name try: tensor = g.get_tensor_by_name(name + ':0') assert "Placeholder" in tensor.op.type, "Tensor {} exists but is not a placeholder!".format(name) assert tensor_spec.is_compatible_with(tensor), \ "Tensor {} exists but is not compatible with the signature!".format(tensor) return tensor except KeyError: with tfv1.name_scope(None): # clear any name scope it might get called in ret = tfv1.placeholder( tensor_spec.dtype, shape=tensor_spec.shape, name=tensor_spec.name) return ret
[ "def", "build_or_reuse_placeholder", "(", "tensor_spec", ")", ":", "g", "=", "tfv1", ".", "get_default_graph", "(", ")", "name", "=", "tensor_spec", ".", "name", "try", ":", "tensor", "=", "g", ".", "get_tensor_by_name", "(", "name", "+", "':0'", ")", "assert", "\"Placeholder\"", "in", "tensor", ".", "op", ".", "type", ",", "\"Tensor {} exists but is not a placeholder!\"", ".", "format", "(", "name", ")", "assert", "tensor_spec", ".", "is_compatible_with", "(", "tensor", ")", ",", "\"Tensor {} exists but is not compatible with the signature!\"", ".", "format", "(", "tensor", ")", "return", "tensor", "except", "KeyError", ":", "with", "tfv1", ".", "name_scope", "(", "None", ")", ":", "# clear any name scope it might get called in", "ret", "=", "tfv1", ".", "placeholder", "(", "tensor_spec", ".", "dtype", ",", "shape", "=", "tensor_spec", ".", "shape", ",", "name", "=", "tensor_spec", ".", "name", ")", "return", "ret" ]
Build a tf.placeholder from the metadata in the given tensor spec, or return an existing one. Args: tensor_spec (tf.TensorSpec): Returns: tf.Tensor:
[ "Build", "a", "tf", ".", "placeholder", "from", "the", "metadata", "in", "the", "given", "tensor", "spec", "or", "return", "an", "existing", "one", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/model_desc.py#L19-L41
27,243
tensorpack/tensorpack
tensorpack/tfutils/dependency.py
dependency_of_targets
def dependency_of_targets(targets, op): """ Check that op is in the subgraph induced by the dependencies of targets. The result is memoized. This is useful if some SessionRunHooks should be run only together with certain ops. Args: targets: a tuple of ops or tensors. The targets to find dependencies of. op (tf.Operation or tf.Tensor): Returns: bool: True if any one of `targets` depend on `op`. """ # TODO tensorarray? sparsetensor? if isinstance(op, tf.Tensor): op = op.op assert isinstance(op, tf.Operation), op from tensorflow.contrib.graph_editor import get_backward_walk_ops # alternative implementation can use graph_util.extract_sub_graph dependent_ops = get_backward_walk_ops(targets, control_inputs=True) return op in dependent_ops
python
def dependency_of_targets(targets, op): """ Check that op is in the subgraph induced by the dependencies of targets. The result is memoized. This is useful if some SessionRunHooks should be run only together with certain ops. Args: targets: a tuple of ops or tensors. The targets to find dependencies of. op (tf.Operation or tf.Tensor): Returns: bool: True if any one of `targets` depend on `op`. """ # TODO tensorarray? sparsetensor? if isinstance(op, tf.Tensor): op = op.op assert isinstance(op, tf.Operation), op from tensorflow.contrib.graph_editor import get_backward_walk_ops # alternative implementation can use graph_util.extract_sub_graph dependent_ops = get_backward_walk_ops(targets, control_inputs=True) return op in dependent_ops
[ "def", "dependency_of_targets", "(", "targets", ",", "op", ")", ":", "# TODO tensorarray? sparsetensor?", "if", "isinstance", "(", "op", ",", "tf", ".", "Tensor", ")", ":", "op", "=", "op", ".", "op", "assert", "isinstance", "(", "op", ",", "tf", ".", "Operation", ")", ",", "op", "from", "tensorflow", ".", "contrib", ".", "graph_editor", "import", "get_backward_walk_ops", "# alternative implementation can use graph_util.extract_sub_graph", "dependent_ops", "=", "get_backward_walk_ops", "(", "targets", ",", "control_inputs", "=", "True", ")", "return", "op", "in", "dependent_ops" ]
Check that op is in the subgraph induced by the dependencies of targets. The result is memoized. This is useful if some SessionRunHooks should be run only together with certain ops. Args: targets: a tuple of ops or tensors. The targets to find dependencies of. op (tf.Operation or tf.Tensor): Returns: bool: True if any one of `targets` depend on `op`.
[ "Check", "that", "op", "is", "in", "the", "subgraph", "induced", "by", "the", "dependencies", "of", "targets", ".", "The", "result", "is", "memoized", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/dependency.py#L16-L38
27,244
tensorpack/tensorpack
tensorpack/tfutils/dependency.py
dependency_of_fetches
def dependency_of_fetches(fetches, op): """ Check that op is in the subgraph induced by the dependencies of fetches. fetches may have more general structure. Args: fetches: An argument to `sess.run`. Nested structure will affect performance. op (tf.Operation or tf.Tensor): Returns: bool: True if any of `fetches` depend on `op`. """ try: from tensorflow.python.client.session import _FetchHandler as FetchHandler # use the graph of the op, so that this function can be called without being under a default graph handler = FetchHandler(op.graph, fetches, {}) targets = tuple(handler.fetches() + handler.targets()) except ImportError: if isinstance(fetches, list): targets = tuple(fetches) elif isinstance(fetches, dict): raise ValueError("Don't know how to parse dictionary to fetch list! " "This is a bug of tensorpack.") else: targets = (fetches, ) return dependency_of_targets(targets, op)
python
def dependency_of_fetches(fetches, op): """ Check that op is in the subgraph induced by the dependencies of fetches. fetches may have more general structure. Args: fetches: An argument to `sess.run`. Nested structure will affect performance. op (tf.Operation or tf.Tensor): Returns: bool: True if any of `fetches` depend on `op`. """ try: from tensorflow.python.client.session import _FetchHandler as FetchHandler # use the graph of the op, so that this function can be called without being under a default graph handler = FetchHandler(op.graph, fetches, {}) targets = tuple(handler.fetches() + handler.targets()) except ImportError: if isinstance(fetches, list): targets = tuple(fetches) elif isinstance(fetches, dict): raise ValueError("Don't know how to parse dictionary to fetch list! " "This is a bug of tensorpack.") else: targets = (fetches, ) return dependency_of_targets(targets, op)
[ "def", "dependency_of_fetches", "(", "fetches", ",", "op", ")", ":", "try", ":", "from", "tensorflow", ".", "python", ".", "client", ".", "session", "import", "_FetchHandler", "as", "FetchHandler", "# use the graph of the op, so that this function can be called without being under a default graph", "handler", "=", "FetchHandler", "(", "op", ".", "graph", ",", "fetches", ",", "{", "}", ")", "targets", "=", "tuple", "(", "handler", ".", "fetches", "(", ")", "+", "handler", ".", "targets", "(", ")", ")", "except", "ImportError", ":", "if", "isinstance", "(", "fetches", ",", "list", ")", ":", "targets", "=", "tuple", "(", "fetches", ")", "elif", "isinstance", "(", "fetches", ",", "dict", ")", ":", "raise", "ValueError", "(", "\"Don't know how to parse dictionary to fetch list! \"", "\"This is a bug of tensorpack.\"", ")", "else", ":", "targets", "=", "(", "fetches", ",", ")", "return", "dependency_of_targets", "(", "targets", ",", "op", ")" ]
Check that op is in the subgraph induced by the dependencies of fetches. fetches may have more general structure. Args: fetches: An argument to `sess.run`. Nested structure will affect performance. op (tf.Operation or tf.Tensor): Returns: bool: True if any of `fetches` depend on `op`.
[ "Check", "that", "op", "is", "in", "the", "subgraph", "induced", "by", "the", "dependencies", "of", "fetches", ".", "fetches", "may", "have", "more", "general", "structure", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/dependency.py#L41-L66
27,245
tensorpack/tensorpack
tensorpack/tfutils/summary.py
add_tensor_summary
def add_tensor_summary(x, types, name=None, collections=None, main_tower_only=True): """ Summarize a tensor by different methods. Args: x (tf.Tensor): a tensor to summarize types (list[str]): summary types, can be scalar/histogram/sparsity/mean/rms name (str): summary name. Defaults to be the op name. collections (list[str]): collections of the summary ops. main_tower_only (bool): Only run under main training tower. If set to True, calling this function under other TowerContext has no effect. Example: .. code-block:: python with tf.name_scope('mysummaries'): # to not mess up tensorboard add_tensor_summary( tensor, ['histogram', 'rms', 'sparsity'], name='mytensor') """ types = set(types) if name is None: name = x.op.name ctx = get_current_tower_context() if main_tower_only and ctx is not None and not ctx.is_main_training_tower: return SUMMARY_TYPES_DIC = { 'scalar': lambda: tf.summary.scalar(name + '-summary', x, collections=collections), 'histogram': lambda: tf.summary.histogram(name + '-histogram', x, collections=collections), 'sparsity': lambda: tf.summary.scalar( name + '-sparsity', tf.nn.zero_fraction(x), collections=collections), 'mean': lambda: tf.summary.scalar( name + '-mean', tf.reduce_mean(x), collections=collections), 'rms': lambda: tf.summary.scalar( name + '-rms', rms(x), collections=collections) } for typ in types: SUMMARY_TYPES_DIC[typ]()
python
def add_tensor_summary(x, types, name=None, collections=None, main_tower_only=True): """ Summarize a tensor by different methods. Args: x (tf.Tensor): a tensor to summarize types (list[str]): summary types, can be scalar/histogram/sparsity/mean/rms name (str): summary name. Defaults to be the op name. collections (list[str]): collections of the summary ops. main_tower_only (bool): Only run under main training tower. If set to True, calling this function under other TowerContext has no effect. Example: .. code-block:: python with tf.name_scope('mysummaries'): # to not mess up tensorboard add_tensor_summary( tensor, ['histogram', 'rms', 'sparsity'], name='mytensor') """ types = set(types) if name is None: name = x.op.name ctx = get_current_tower_context() if main_tower_only and ctx is not None and not ctx.is_main_training_tower: return SUMMARY_TYPES_DIC = { 'scalar': lambda: tf.summary.scalar(name + '-summary', x, collections=collections), 'histogram': lambda: tf.summary.histogram(name + '-histogram', x, collections=collections), 'sparsity': lambda: tf.summary.scalar( name + '-sparsity', tf.nn.zero_fraction(x), collections=collections), 'mean': lambda: tf.summary.scalar( name + '-mean', tf.reduce_mean(x), collections=collections), 'rms': lambda: tf.summary.scalar( name + '-rms', rms(x), collections=collections) } for typ in types: SUMMARY_TYPES_DIC[typ]()
[ "def", "add_tensor_summary", "(", "x", ",", "types", ",", "name", "=", "None", ",", "collections", "=", "None", ",", "main_tower_only", "=", "True", ")", ":", "types", "=", "set", "(", "types", ")", "if", "name", "is", "None", ":", "name", "=", "x", ".", "op", ".", "name", "ctx", "=", "get_current_tower_context", "(", ")", "if", "main_tower_only", "and", "ctx", "is", "not", "None", "and", "not", "ctx", ".", "is_main_training_tower", ":", "return", "SUMMARY_TYPES_DIC", "=", "{", "'scalar'", ":", "lambda", ":", "tf", ".", "summary", ".", "scalar", "(", "name", "+", "'-summary'", ",", "x", ",", "collections", "=", "collections", ")", ",", "'histogram'", ":", "lambda", ":", "tf", ".", "summary", ".", "histogram", "(", "name", "+", "'-histogram'", ",", "x", ",", "collections", "=", "collections", ")", ",", "'sparsity'", ":", "lambda", ":", "tf", ".", "summary", ".", "scalar", "(", "name", "+", "'-sparsity'", ",", "tf", ".", "nn", ".", "zero_fraction", "(", "x", ")", ",", "collections", "=", "collections", ")", ",", "'mean'", ":", "lambda", ":", "tf", ".", "summary", ".", "scalar", "(", "name", "+", "'-mean'", ",", "tf", ".", "reduce_mean", "(", "x", ")", ",", "collections", "=", "collections", ")", ",", "'rms'", ":", "lambda", ":", "tf", ".", "summary", ".", "scalar", "(", "name", "+", "'-rms'", ",", "rms", "(", "x", ")", ",", "collections", "=", "collections", ")", "}", "for", "typ", "in", "types", ":", "SUMMARY_TYPES_DIC", "[", "typ", "]", "(", ")" ]
Summarize a tensor by different methods. Args: x (tf.Tensor): a tensor to summarize types (list[str]): summary types, can be scalar/histogram/sparsity/mean/rms name (str): summary name. Defaults to be the op name. collections (list[str]): collections of the summary ops. main_tower_only (bool): Only run under main training tower. If set to True, calling this function under other TowerContext has no effect. Example: .. code-block:: python with tf.name_scope('mysummaries'): # to not mess up tensorboard add_tensor_summary( tensor, ['histogram', 'rms', 'sparsity'], name='mytensor')
[ "Summarize", "a", "tensor", "by", "different", "methods", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/summary.py#L95-L137
27,246
tensorpack/tensorpack
tensorpack/tfutils/summary.py
add_param_summary
def add_param_summary(*summary_lists, **kwargs): """ Add summary ops for all trainable variables matching the regex, under a reused 'param-summary' name scope. This function is a no-op if not calling from main training tower. Args: summary_lists (list): each is (regex, [list of summary type]). Summary type is defined in :func:`add_tensor_summary`. collections (list[str]): collections of the summary ops. Example: .. code-block:: python add_param_summary( ('.*/W', ['histogram', 'rms']), ('.*/gamma', ['scalar']), ) """ collections = kwargs.pop('collections', None) assert len(kwargs) == 0, "Unknown kwargs: " + str(kwargs) ctx = get_current_tower_context() if ctx is not None and not ctx.is_main_training_tower: return params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES) with cached_name_scope('param-summary'): for p in params: name = p.op.name for rgx, actions in summary_lists: if not rgx.endswith('$'): rgx = rgx + '$' if re.match(rgx, name): add_tensor_summary(p, actions, name=name, collections=collections)
python
def add_param_summary(*summary_lists, **kwargs): """ Add summary ops for all trainable variables matching the regex, under a reused 'param-summary' name scope. This function is a no-op if not calling from main training tower. Args: summary_lists (list): each is (regex, [list of summary type]). Summary type is defined in :func:`add_tensor_summary`. collections (list[str]): collections of the summary ops. Example: .. code-block:: python add_param_summary( ('.*/W', ['histogram', 'rms']), ('.*/gamma', ['scalar']), ) """ collections = kwargs.pop('collections', None) assert len(kwargs) == 0, "Unknown kwargs: " + str(kwargs) ctx = get_current_tower_context() if ctx is not None and not ctx.is_main_training_tower: return params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES) with cached_name_scope('param-summary'): for p in params: name = p.op.name for rgx, actions in summary_lists: if not rgx.endswith('$'): rgx = rgx + '$' if re.match(rgx, name): add_tensor_summary(p, actions, name=name, collections=collections)
[ "def", "add_param_summary", "(", "*", "summary_lists", ",", "*", "*", "kwargs", ")", ":", "collections", "=", "kwargs", ".", "pop", "(", "'collections'", ",", "None", ")", "assert", "len", "(", "kwargs", ")", "==", "0", ",", "\"Unknown kwargs: \"", "+", "str", "(", "kwargs", ")", "ctx", "=", "get_current_tower_context", "(", ")", "if", "ctx", "is", "not", "None", "and", "not", "ctx", ".", "is_main_training_tower", ":", "return", "params", "=", "tf", ".", "get_collection", "(", "tf", ".", "GraphKeys", ".", "TRAINABLE_VARIABLES", ")", "with", "cached_name_scope", "(", "'param-summary'", ")", ":", "for", "p", "in", "params", ":", "name", "=", "p", ".", "op", ".", "name", "for", "rgx", ",", "actions", "in", "summary_lists", ":", "if", "not", "rgx", ".", "endswith", "(", "'$'", ")", ":", "rgx", "=", "rgx", "+", "'$'", "if", "re", ".", "match", "(", "rgx", ",", "name", ")", ":", "add_tensor_summary", "(", "p", ",", "actions", ",", "name", "=", "name", ",", "collections", "=", "collections", ")" ]
Add summary ops for all trainable variables matching the regex, under a reused 'param-summary' name scope. This function is a no-op if not calling from main training tower. Args: summary_lists (list): each is (regex, [list of summary type]). Summary type is defined in :func:`add_tensor_summary`. collections (list[str]): collections of the summary ops. Example: .. code-block:: python add_param_summary( ('.*/W', ['histogram', 'rms']), ('.*/gamma', ['scalar']), )
[ "Add", "summary", "ops", "for", "all", "trainable", "variables", "matching", "the", "regex", "under", "a", "reused", "param", "-", "summary", "name", "scope", ".", "This", "function", "is", "a", "no", "-", "op", "if", "not", "calling", "from", "main", "training", "tower", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/summary.py#L161-L195
27,247
tensorpack/tensorpack
tensorpack/tfutils/summary.py
add_moving_summary
def add_moving_summary(*args, **kwargs): """ Summarize the moving average for scalar tensors. This function is a no-op if not calling from main training tower. Args: args: scalar tensors to summarize decay (float): the decay rate. Defaults to 0.95. collection (str or None): the name of the collection to add EMA-maintaining ops. The default will work together with the default :class:`MovingAverageSummary` callback. summary_collections ([str]): the names of collections to add the summary op. Default is TF's default (`tf.GraphKeys.SUMMARIES`). Returns: [tf.Tensor]: list of tensors returned by assign_moving_average, which can be used to maintain the EMA. """ decay = kwargs.pop('decay', 0.95) coll = kwargs.pop('collection', MOVING_SUMMARY_OPS_KEY) summ_coll = kwargs.pop('summary_collections', None) assert len(kwargs) == 0, "Unknown arguments: " + str(kwargs) ctx = get_current_tower_context() # allow ctx to be none if ctx is not None and not ctx.is_main_training_tower: return [] graph = tf.get_default_graph() try: control_flow_ctx = graph._get_control_flow_context() # XLA does not support summaries anyway # However, this function will generate unnecessary dependency edges, # which makes the tower function harder to compile under XLA, so we skip it if control_flow_ctx is not None and control_flow_ctx.IsXLAContext(): return except Exception: pass if tf.get_variable_scope().reuse is True: logger.warn("add_moving_summary() called under reuse=True scope, ignored.") return [] for x in args: assert isinstance(x, (tf.Tensor, tf.Variable)), x assert x.get_shape().ndims == 0, \ "add_moving_summary() only accepts scalar tensor! Got one with {}".format(x.get_shape()) ema_ops = [] for c in args: name = re.sub('tower[0-9]+/', '', c.op.name) with tf.name_scope(None): if not c.dtype.is_floating: c = tf.cast(c, tf.float32) # assign_moving_average creates variables with op names, therefore clear ns first. with _enter_vs_reuse_ns('EMA') as vs: ema_var = tf.get_variable(name, shape=c.shape, dtype=c.dtype, initializer=tf.constant_initializer(), trainable=False) ns = vs.original_name_scope with tf.name_scope(ns): # reuse VS&NS so that EMA_1 won't appear ema_op = moving_averages.assign_moving_average( ema_var, c, decay, zero_debias=True, name=name + '_EMA_apply') ema_ops.append(ema_op) with tf.name_scope(None): tf.summary.scalar( name + '-summary', ema_op, collections=summ_coll) # write the EMA value as a summary if coll is not None: for op in ema_ops: tf.add_to_collection(coll, op) return ema_ops
python
def add_moving_summary(*args, **kwargs): """ Summarize the moving average for scalar tensors. This function is a no-op if not calling from main training tower. Args: args: scalar tensors to summarize decay (float): the decay rate. Defaults to 0.95. collection (str or None): the name of the collection to add EMA-maintaining ops. The default will work together with the default :class:`MovingAverageSummary` callback. summary_collections ([str]): the names of collections to add the summary op. Default is TF's default (`tf.GraphKeys.SUMMARIES`). Returns: [tf.Tensor]: list of tensors returned by assign_moving_average, which can be used to maintain the EMA. """ decay = kwargs.pop('decay', 0.95) coll = kwargs.pop('collection', MOVING_SUMMARY_OPS_KEY) summ_coll = kwargs.pop('summary_collections', None) assert len(kwargs) == 0, "Unknown arguments: " + str(kwargs) ctx = get_current_tower_context() # allow ctx to be none if ctx is not None and not ctx.is_main_training_tower: return [] graph = tf.get_default_graph() try: control_flow_ctx = graph._get_control_flow_context() # XLA does not support summaries anyway # However, this function will generate unnecessary dependency edges, # which makes the tower function harder to compile under XLA, so we skip it if control_flow_ctx is not None and control_flow_ctx.IsXLAContext(): return except Exception: pass if tf.get_variable_scope().reuse is True: logger.warn("add_moving_summary() called under reuse=True scope, ignored.") return [] for x in args: assert isinstance(x, (tf.Tensor, tf.Variable)), x assert x.get_shape().ndims == 0, \ "add_moving_summary() only accepts scalar tensor! Got one with {}".format(x.get_shape()) ema_ops = [] for c in args: name = re.sub('tower[0-9]+/', '', c.op.name) with tf.name_scope(None): if not c.dtype.is_floating: c = tf.cast(c, tf.float32) # assign_moving_average creates variables with op names, therefore clear ns first. with _enter_vs_reuse_ns('EMA') as vs: ema_var = tf.get_variable(name, shape=c.shape, dtype=c.dtype, initializer=tf.constant_initializer(), trainable=False) ns = vs.original_name_scope with tf.name_scope(ns): # reuse VS&NS so that EMA_1 won't appear ema_op = moving_averages.assign_moving_average( ema_var, c, decay, zero_debias=True, name=name + '_EMA_apply') ema_ops.append(ema_op) with tf.name_scope(None): tf.summary.scalar( name + '-summary', ema_op, collections=summ_coll) # write the EMA value as a summary if coll is not None: for op in ema_ops: tf.add_to_collection(coll, op) return ema_ops
[ "def", "add_moving_summary", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "decay", "=", "kwargs", ".", "pop", "(", "'decay'", ",", "0.95", ")", "coll", "=", "kwargs", ".", "pop", "(", "'collection'", ",", "MOVING_SUMMARY_OPS_KEY", ")", "summ_coll", "=", "kwargs", ".", "pop", "(", "'summary_collections'", ",", "None", ")", "assert", "len", "(", "kwargs", ")", "==", "0", ",", "\"Unknown arguments: \"", "+", "str", "(", "kwargs", ")", "ctx", "=", "get_current_tower_context", "(", ")", "# allow ctx to be none", "if", "ctx", "is", "not", "None", "and", "not", "ctx", ".", "is_main_training_tower", ":", "return", "[", "]", "graph", "=", "tf", ".", "get_default_graph", "(", ")", "try", ":", "control_flow_ctx", "=", "graph", ".", "_get_control_flow_context", "(", ")", "# XLA does not support summaries anyway", "# However, this function will generate unnecessary dependency edges,", "# which makes the tower function harder to compile under XLA, so we skip it", "if", "control_flow_ctx", "is", "not", "None", "and", "control_flow_ctx", ".", "IsXLAContext", "(", ")", ":", "return", "except", "Exception", ":", "pass", "if", "tf", ".", "get_variable_scope", "(", ")", ".", "reuse", "is", "True", ":", "logger", ".", "warn", "(", "\"add_moving_summary() called under reuse=True scope, ignored.\"", ")", "return", "[", "]", "for", "x", "in", "args", ":", "assert", "isinstance", "(", "x", ",", "(", "tf", ".", "Tensor", ",", "tf", ".", "Variable", ")", ")", ",", "x", "assert", "x", ".", "get_shape", "(", ")", ".", "ndims", "==", "0", ",", "\"add_moving_summary() only accepts scalar tensor! Got one with {}\"", ".", "format", "(", "x", ".", "get_shape", "(", ")", ")", "ema_ops", "=", "[", "]", "for", "c", "in", "args", ":", "name", "=", "re", ".", "sub", "(", "'tower[0-9]+/'", ",", "''", ",", "c", ".", "op", ".", "name", ")", "with", "tf", ".", "name_scope", "(", "None", ")", ":", "if", "not", "c", ".", "dtype", ".", "is_floating", ":", "c", "=", "tf", ".", "cast", "(", "c", ",", "tf", ".", "float32", ")", "# assign_moving_average creates variables with op names, therefore clear ns first.", "with", "_enter_vs_reuse_ns", "(", "'EMA'", ")", "as", "vs", ":", "ema_var", "=", "tf", ".", "get_variable", "(", "name", ",", "shape", "=", "c", ".", "shape", ",", "dtype", "=", "c", ".", "dtype", ",", "initializer", "=", "tf", ".", "constant_initializer", "(", ")", ",", "trainable", "=", "False", ")", "ns", "=", "vs", ".", "original_name_scope", "with", "tf", ".", "name_scope", "(", "ns", ")", ":", "# reuse VS&NS so that EMA_1 won't appear", "ema_op", "=", "moving_averages", ".", "assign_moving_average", "(", "ema_var", ",", "c", ",", "decay", ",", "zero_debias", "=", "True", ",", "name", "=", "name", "+", "'_EMA_apply'", ")", "ema_ops", ".", "append", "(", "ema_op", ")", "with", "tf", ".", "name_scope", "(", "None", ")", ":", "tf", ".", "summary", ".", "scalar", "(", "name", "+", "'-summary'", ",", "ema_op", ",", "collections", "=", "summ_coll", ")", "# write the EMA value as a summary", "if", "coll", "is", "not", "None", ":", "for", "op", "in", "ema_ops", ":", "tf", ".", "add_to_collection", "(", "coll", ",", "op", ")", "return", "ema_ops" ]
Summarize the moving average for scalar tensors. This function is a no-op if not calling from main training tower. Args: args: scalar tensors to summarize decay (float): the decay rate. Defaults to 0.95. collection (str or None): the name of the collection to add EMA-maintaining ops. The default will work together with the default :class:`MovingAverageSummary` callback. summary_collections ([str]): the names of collections to add the summary op. Default is TF's default (`tf.GraphKeys.SUMMARIES`). Returns: [tf.Tensor]: list of tensors returned by assign_moving_average, which can be used to maintain the EMA.
[ "Summarize", "the", "moving", "average", "for", "scalar", "tensors", ".", "This", "function", "is", "a", "no", "-", "op", "if", "not", "calling", "from", "main", "training", "tower", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/summary.py#L198-L270
27,248
tensorpack/tensorpack
examples/basics/export-model.py
export_serving
def export_serving(model_path): """Export trained model to use it in TensorFlow Serving or cloudML. """ pred_config = PredictConfig( session_init=get_model_loader(model_path), model=InferenceOnlyModel(), input_names=['input_img_bytes'], output_names=['prediction_img_bytes']) ModelExporter(pred_config).export_serving('/tmp/exported')
python
def export_serving(model_path): """Export trained model to use it in TensorFlow Serving or cloudML. """ pred_config = PredictConfig( session_init=get_model_loader(model_path), model=InferenceOnlyModel(), input_names=['input_img_bytes'], output_names=['prediction_img_bytes']) ModelExporter(pred_config).export_serving('/tmp/exported')
[ "def", "export_serving", "(", "model_path", ")", ":", "pred_config", "=", "PredictConfig", "(", "session_init", "=", "get_model_loader", "(", "model_path", ")", ",", "model", "=", "InferenceOnlyModel", "(", ")", ",", "input_names", "=", "[", "'input_img_bytes'", "]", ",", "output_names", "=", "[", "'prediction_img_bytes'", "]", ")", "ModelExporter", "(", "pred_config", ")", ".", "export_serving", "(", "'/tmp/exported'", ")" ]
Export trained model to use it in TensorFlow Serving or cloudML.
[ "Export", "trained", "model", "to", "use", "it", "in", "TensorFlow", "Serving", "or", "cloudML", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/export-model.py#L106-L113
27,249
tensorpack/tensorpack
examples/basics/export-model.py
export_compact
def export_compact(model_path): """Export trained model to use it as a frozen and pruned inference graph in mobile applications. """ pred_config = PredictConfig( session_init=get_model_loader(model_path), model=Model(), input_names=['input_img'], output_names=['prediction_img']) ModelExporter(pred_config).export_compact('/tmp/compact_graph.pb')
python
def export_compact(model_path): """Export trained model to use it as a frozen and pruned inference graph in mobile applications. """ pred_config = PredictConfig( session_init=get_model_loader(model_path), model=Model(), input_names=['input_img'], output_names=['prediction_img']) ModelExporter(pred_config).export_compact('/tmp/compact_graph.pb')
[ "def", "export_compact", "(", "model_path", ")", ":", "pred_config", "=", "PredictConfig", "(", "session_init", "=", "get_model_loader", "(", "model_path", ")", ",", "model", "=", "Model", "(", ")", ",", "input_names", "=", "[", "'input_img'", "]", ",", "output_names", "=", "[", "'prediction_img'", "]", ")", "ModelExporter", "(", "pred_config", ")", ".", "export_compact", "(", "'/tmp/compact_graph.pb'", ")" ]
Export trained model to use it as a frozen and pruned inference graph in mobile applications.
[ "Export", "trained", "model", "to", "use", "it", "as", "a", "frozen", "and", "pruned", "inference", "graph", "in", "mobile", "applications", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/export-model.py#L116-L124
27,250
tensorpack/tensorpack
examples/basics/export-model.py
apply
def apply(model_path): """Run inference from a training model checkpoint. """ pred_config = PredictConfig( session_init=get_model_loader(model_path), model=Model(), input_names=['input_img'], output_names=['prediction_img']) pred = OfflinePredictor(pred_config) img = cv2.imread('lena.png') prediction = pred([img])[0] cv2.imwrite('applied_default.jpg', prediction[0])
python
def apply(model_path): """Run inference from a training model checkpoint. """ pred_config = PredictConfig( session_init=get_model_loader(model_path), model=Model(), input_names=['input_img'], output_names=['prediction_img']) pred = OfflinePredictor(pred_config) img = cv2.imread('lena.png') prediction = pred([img])[0] cv2.imwrite('applied_default.jpg', prediction[0])
[ "def", "apply", "(", "model_path", ")", ":", "pred_config", "=", "PredictConfig", "(", "session_init", "=", "get_model_loader", "(", "model_path", ")", ",", "model", "=", "Model", "(", ")", ",", "input_names", "=", "[", "'input_img'", "]", ",", "output_names", "=", "[", "'prediction_img'", "]", ")", "pred", "=", "OfflinePredictor", "(", "pred_config", ")", "img", "=", "cv2", ".", "imread", "(", "'lena.png'", ")", "prediction", "=", "pred", "(", "[", "img", "]", ")", "[", "0", "]", "cv2", ".", "imwrite", "(", "'applied_default.jpg'", ",", "prediction", "[", "0", "]", ")" ]
Run inference from a training model checkpoint.
[ "Run", "inference", "from", "a", "training", "model", "checkpoint", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/export-model.py#L127-L138
27,251
tensorpack/tensorpack
examples/basics/export-model.py
apply_inference_graph
def apply_inference_graph(model_path): """Run inference from a different graph, which receives encoded images buffers. """ pred_config = PredictConfig( session_init=get_model_loader(model_path), model=InferenceOnlyModel(), input_names=['input_img_bytes'], output_names=['prediction_img_bytes']) pred = OfflinePredictor(pred_config) buf = open('lena.png', 'rb').read() prediction = pred([buf])[0] with open('applied_inference_graph.png', 'wb') as f: f.write(prediction[0])
python
def apply_inference_graph(model_path): """Run inference from a different graph, which receives encoded images buffers. """ pred_config = PredictConfig( session_init=get_model_loader(model_path), model=InferenceOnlyModel(), input_names=['input_img_bytes'], output_names=['prediction_img_bytes']) pred = OfflinePredictor(pred_config) buf = open('lena.png', 'rb').read() prediction = pred([buf])[0] with open('applied_inference_graph.png', 'wb') as f: f.write(prediction[0])
[ "def", "apply_inference_graph", "(", "model_path", ")", ":", "pred_config", "=", "PredictConfig", "(", "session_init", "=", "get_model_loader", "(", "model_path", ")", ",", "model", "=", "InferenceOnlyModel", "(", ")", ",", "input_names", "=", "[", "'input_img_bytes'", "]", ",", "output_names", "=", "[", "'prediction_img_bytes'", "]", ")", "pred", "=", "OfflinePredictor", "(", "pred_config", ")", "buf", "=", "open", "(", "'lena.png'", ",", "'rb'", ")", ".", "read", "(", ")", "prediction", "=", "pred", "(", "[", "buf", "]", ")", "[", "0", "]", "with", "open", "(", "'applied_inference_graph.png'", ",", "'wb'", ")", "as", "f", ":", "f", ".", "write", "(", "prediction", "[", "0", "]", ")" ]
Run inference from a different graph, which receives encoded images buffers.
[ "Run", "inference", "from", "a", "different", "graph", "which", "receives", "encoded", "images", "buffers", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/export-model.py#L141-L153
27,252
tensorpack/tensorpack
examples/basics/export-model.py
apply_compact
def apply_compact(graph_path): """Run the pruned and frozen inference graph. """ with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess: # Note, we just load the graph and do *not* need to initialize anything. with tf.gfile.GFile(graph_path, "rb") as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) tf.import_graph_def(graph_def) input_img = sess.graph.get_tensor_by_name('import/input_img:0') prediction_img = sess.graph.get_tensor_by_name('import/prediction_img:0') prediction = sess.run(prediction_img, {input_img: cv2.imread('lena.png')[None, ...]}) cv2.imwrite('applied_compact.png', prediction[0])
python
def apply_compact(graph_path): """Run the pruned and frozen inference graph. """ with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess: # Note, we just load the graph and do *not* need to initialize anything. with tf.gfile.GFile(graph_path, "rb") as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) tf.import_graph_def(graph_def) input_img = sess.graph.get_tensor_by_name('import/input_img:0') prediction_img = sess.graph.get_tensor_by_name('import/prediction_img:0') prediction = sess.run(prediction_img, {input_img: cv2.imread('lena.png')[None, ...]}) cv2.imwrite('applied_compact.png', prediction[0])
[ "def", "apply_compact", "(", "graph_path", ")", ":", "with", "tf", ".", "Session", "(", "config", "=", "tf", ".", "ConfigProto", "(", "allow_soft_placement", "=", "True", ")", ")", "as", "sess", ":", "# Note, we just load the graph and do *not* need to initialize anything.", "with", "tf", ".", "gfile", ".", "GFile", "(", "graph_path", ",", "\"rb\"", ")", "as", "f", ":", "graph_def", "=", "tf", ".", "GraphDef", "(", ")", "graph_def", ".", "ParseFromString", "(", "f", ".", "read", "(", ")", ")", "tf", ".", "import_graph_def", "(", "graph_def", ")", "input_img", "=", "sess", ".", "graph", ".", "get_tensor_by_name", "(", "'import/input_img:0'", ")", "prediction_img", "=", "sess", ".", "graph", ".", "get_tensor_by_name", "(", "'import/prediction_img:0'", ")", "prediction", "=", "sess", ".", "run", "(", "prediction_img", ",", "{", "input_img", ":", "cv2", ".", "imread", "(", "'lena.png'", ")", "[", "None", ",", "...", "]", "}", ")", "cv2", ".", "imwrite", "(", "'applied_compact.png'", ",", "prediction", "[", "0", "]", ")" ]
Run the pruned and frozen inference graph.
[ "Run", "the", "pruned", "and", "frozen", "inference", "graph", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/export-model.py#L156-L169
27,253
tensorpack/tensorpack
tensorpack/dataflow/common.py
PrintData._analyze_input_data
def _analyze_input_data(self, entry, k, depth=1, max_depth=3, max_list=3): """ Gather useful debug information from a datapoint. Args: entry: the datapoint component k (int): index of this component in current datapoint depth (int, optional): recursion depth max_depth, max_list: same as in :meth:`__init__`. Returns: string: debug message """ class _elementInfo(object): def __init__(self, el, pos, depth=0, max_list=3): self.shape = "" self.type = type(el).__name__ self.dtype = "" self.range = "" self.sub_elements = [] self.ident = " " * (depth * 2) self.pos = pos numpy_scalar_types = list(itertools.chain(*np.sctypes.values())) if isinstance(el, (int, float, bool)): self.range = " with value {}".format(el) elif type(el) is np.ndarray: self.shape = " of shape {}".format(el.shape) self.dtype = ":{}".format(str(el.dtype)) self.range = " in range [{}, {}]".format(el.min(), el.max()) elif type(el) in numpy_scalar_types: self.range = " with value {}".format(el) elif isinstance(el, (list)): self.shape = " of len {}".format(len(el)) if depth < max_depth: for k, subel in enumerate(el): if k < max_list: self.sub_elements.append(_elementInfo(subel, k, depth + 1, max_list)) else: self.sub_elements.append(" " * ((depth + 1) * 2) + '...') break else: if len(el) > 0: self.sub_elements.append(" " * ((depth + 1) * 2) + ' ...') def __str__(self): strings = [] vals = (self.ident, self.pos, self.type, self.dtype, self.shape, self.range) strings.append("{}{}: {}{}{}{}".format(*vals)) for k, el in enumerate(self.sub_elements): strings.append(str(el)) return "\n".join(strings) return str(_elementInfo(entry, k, depth, max_list))
python
def _analyze_input_data(self, entry, k, depth=1, max_depth=3, max_list=3): """ Gather useful debug information from a datapoint. Args: entry: the datapoint component k (int): index of this component in current datapoint depth (int, optional): recursion depth max_depth, max_list: same as in :meth:`__init__`. Returns: string: debug message """ class _elementInfo(object): def __init__(self, el, pos, depth=0, max_list=3): self.shape = "" self.type = type(el).__name__ self.dtype = "" self.range = "" self.sub_elements = [] self.ident = " " * (depth * 2) self.pos = pos numpy_scalar_types = list(itertools.chain(*np.sctypes.values())) if isinstance(el, (int, float, bool)): self.range = " with value {}".format(el) elif type(el) is np.ndarray: self.shape = " of shape {}".format(el.shape) self.dtype = ":{}".format(str(el.dtype)) self.range = " in range [{}, {}]".format(el.min(), el.max()) elif type(el) in numpy_scalar_types: self.range = " with value {}".format(el) elif isinstance(el, (list)): self.shape = " of len {}".format(len(el)) if depth < max_depth: for k, subel in enumerate(el): if k < max_list: self.sub_elements.append(_elementInfo(subel, k, depth + 1, max_list)) else: self.sub_elements.append(" " * ((depth + 1) * 2) + '...') break else: if len(el) > 0: self.sub_elements.append(" " * ((depth + 1) * 2) + ' ...') def __str__(self): strings = [] vals = (self.ident, self.pos, self.type, self.dtype, self.shape, self.range) strings.append("{}{}: {}{}{}{}".format(*vals)) for k, el in enumerate(self.sub_elements): strings.append(str(el)) return "\n".join(strings) return str(_elementInfo(entry, k, depth, max_list))
[ "def", "_analyze_input_data", "(", "self", ",", "entry", ",", "k", ",", "depth", "=", "1", ",", "max_depth", "=", "3", ",", "max_list", "=", "3", ")", ":", "class", "_elementInfo", "(", "object", ")", ":", "def", "__init__", "(", "self", ",", "el", ",", "pos", ",", "depth", "=", "0", ",", "max_list", "=", "3", ")", ":", "self", ".", "shape", "=", "\"\"", "self", ".", "type", "=", "type", "(", "el", ")", ".", "__name__", "self", ".", "dtype", "=", "\"\"", "self", ".", "range", "=", "\"\"", "self", ".", "sub_elements", "=", "[", "]", "self", ".", "ident", "=", "\" \"", "*", "(", "depth", "*", "2", ")", "self", ".", "pos", "=", "pos", "numpy_scalar_types", "=", "list", "(", "itertools", ".", "chain", "(", "*", "np", ".", "sctypes", ".", "values", "(", ")", ")", ")", "if", "isinstance", "(", "el", ",", "(", "int", ",", "float", ",", "bool", ")", ")", ":", "self", ".", "range", "=", "\" with value {}\"", ".", "format", "(", "el", ")", "elif", "type", "(", "el", ")", "is", "np", ".", "ndarray", ":", "self", ".", "shape", "=", "\" of shape {}\"", ".", "format", "(", "el", ".", "shape", ")", "self", ".", "dtype", "=", "\":{}\"", ".", "format", "(", "str", "(", "el", ".", "dtype", ")", ")", "self", ".", "range", "=", "\" in range [{}, {}]\"", ".", "format", "(", "el", ".", "min", "(", ")", ",", "el", ".", "max", "(", ")", ")", "elif", "type", "(", "el", ")", "in", "numpy_scalar_types", ":", "self", ".", "range", "=", "\" with value {}\"", ".", "format", "(", "el", ")", "elif", "isinstance", "(", "el", ",", "(", "list", ")", ")", ":", "self", ".", "shape", "=", "\" of len {}\"", ".", "format", "(", "len", "(", "el", ")", ")", "if", "depth", "<", "max_depth", ":", "for", "k", ",", "subel", "in", "enumerate", "(", "el", ")", ":", "if", "k", "<", "max_list", ":", "self", ".", "sub_elements", ".", "append", "(", "_elementInfo", "(", "subel", ",", "k", ",", "depth", "+", "1", ",", "max_list", ")", ")", "else", ":", "self", ".", "sub_elements", ".", "append", "(", "\" \"", "*", "(", "(", "depth", "+", "1", ")", "*", "2", ")", "+", "'...'", ")", "break", "else", ":", "if", "len", "(", "el", ")", ">", "0", ":", "self", ".", "sub_elements", ".", "append", "(", "\" \"", "*", "(", "(", "depth", "+", "1", ")", "*", "2", ")", "+", "' ...'", ")", "def", "__str__", "(", "self", ")", ":", "strings", "=", "[", "]", "vals", "=", "(", "self", ".", "ident", ",", "self", ".", "pos", ",", "self", ".", "type", ",", "self", ".", "dtype", ",", "self", ".", "shape", ",", "self", ".", "range", ")", "strings", ".", "append", "(", "\"{}{}: {}{}{}{}\"", ".", "format", "(", "*", "vals", ")", ")", "for", "k", ",", "el", "in", "enumerate", "(", "self", ".", "sub_elements", ")", ":", "strings", ".", "append", "(", "str", "(", "el", ")", ")", "return", "\"\\n\"", ".", "join", "(", "strings", ")", "return", "str", "(", "_elementInfo", "(", "entry", ",", "k", ",", "depth", ",", "max_list", ")", ")" ]
Gather useful debug information from a datapoint. Args: entry: the datapoint component k (int): index of this component in current datapoint depth (int, optional): recursion depth max_depth, max_list: same as in :meth:`__init__`. Returns: string: debug message
[ "Gather", "useful", "debug", "information", "from", "a", "datapoint", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/common.py#L745-L804
27,254
tensorpack/tensorpack
tensorpack/tfutils/optimizer.py
apply_grad_processors
def apply_grad_processors(opt, gradprocs): """ Wrapper around optimizers to apply gradient processors. Args: opt (tf.train.Optimizer): gradprocs (list[GradientProcessor]): gradient processors to add to the optimizer. Returns: a :class:`tf.train.Optimizer` instance which runs the gradient processors before updating the variables. """ assert isinstance(gradprocs, (list, tuple)), gradprocs for gp in gradprocs: assert isinstance(gp, GradientProcessor), gp class _ApplyGradientProcessor(ProxyOptimizer): def __init__(self, opt, gradprocs): self._gradprocs = gradprocs[:] super(_ApplyGradientProcessor, self).__init__(opt) def apply_gradients(self, grads_and_vars, global_step=None, name=None): g = self._apply(grads_and_vars) return self._opt.apply_gradients(g, global_step, name) def _apply(self, g): for proc in self._gradprocs: g = proc.process(g) return g return _ApplyGradientProcessor(opt, gradprocs)
python
def apply_grad_processors(opt, gradprocs): """ Wrapper around optimizers to apply gradient processors. Args: opt (tf.train.Optimizer): gradprocs (list[GradientProcessor]): gradient processors to add to the optimizer. Returns: a :class:`tf.train.Optimizer` instance which runs the gradient processors before updating the variables. """ assert isinstance(gradprocs, (list, tuple)), gradprocs for gp in gradprocs: assert isinstance(gp, GradientProcessor), gp class _ApplyGradientProcessor(ProxyOptimizer): def __init__(self, opt, gradprocs): self._gradprocs = gradprocs[:] super(_ApplyGradientProcessor, self).__init__(opt) def apply_gradients(self, grads_and_vars, global_step=None, name=None): g = self._apply(grads_and_vars) return self._opt.apply_gradients(g, global_step, name) def _apply(self, g): for proc in self._gradprocs: g = proc.process(g) return g return _ApplyGradientProcessor(opt, gradprocs)
[ "def", "apply_grad_processors", "(", "opt", ",", "gradprocs", ")", ":", "assert", "isinstance", "(", "gradprocs", ",", "(", "list", ",", "tuple", ")", ")", ",", "gradprocs", "for", "gp", "in", "gradprocs", ":", "assert", "isinstance", "(", "gp", ",", "GradientProcessor", ")", ",", "gp", "class", "_ApplyGradientProcessor", "(", "ProxyOptimizer", ")", ":", "def", "__init__", "(", "self", ",", "opt", ",", "gradprocs", ")", ":", "self", ".", "_gradprocs", "=", "gradprocs", "[", ":", "]", "super", "(", "_ApplyGradientProcessor", ",", "self", ")", ".", "__init__", "(", "opt", ")", "def", "apply_gradients", "(", "self", ",", "grads_and_vars", ",", "global_step", "=", "None", ",", "name", "=", "None", ")", ":", "g", "=", "self", ".", "_apply", "(", "grads_and_vars", ")", "return", "self", ".", "_opt", ".", "apply_gradients", "(", "g", ",", "global_step", ",", "name", ")", "def", "_apply", "(", "self", ",", "g", ")", ":", "for", "proc", "in", "self", ".", "_gradprocs", ":", "g", "=", "proc", ".", "process", "(", "g", ")", "return", "g", "return", "_ApplyGradientProcessor", "(", "opt", ",", "gradprocs", ")" ]
Wrapper around optimizers to apply gradient processors. Args: opt (tf.train.Optimizer): gradprocs (list[GradientProcessor]): gradient processors to add to the optimizer. Returns: a :class:`tf.train.Optimizer` instance which runs the gradient processors before updating the variables.
[ "Wrapper", "around", "optimizers", "to", "apply", "gradient", "processors", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/optimizer.py#L44-L76
27,255
tensorpack/tensorpack
examples/FasterRCNN/eval.py
multithread_predict_dataflow
def multithread_predict_dataflow(dataflows, model_funcs): """ Running multiple `predict_dataflow` in multiple threads, and aggregate the results. Args: dataflows: a list of DataFlow to be used in :func:`predict_dataflow` model_funcs: a list of callable to be used in :func:`predict_dataflow` Returns: list of dict, in the format used by `DetectionDataset.eval_or_save_inference_results` """ num_worker = len(model_funcs) assert len(dataflows) == num_worker if num_worker == 1: return predict_dataflow(dataflows[0], model_funcs[0]) kwargs = {'thread_name_prefix': 'EvalWorker'} if sys.version_info.minor >= 6 else {} with ThreadPoolExecutor(max_workers=num_worker, **kwargs) as executor, \ tqdm.tqdm(total=sum([df.size() for df in dataflows])) as pbar: futures = [] for dataflow, pred in zip(dataflows, model_funcs): futures.append(executor.submit(predict_dataflow, dataflow, pred, pbar)) all_results = list(itertools.chain(*[fut.result() for fut in futures])) return all_results
python
def multithread_predict_dataflow(dataflows, model_funcs): """ Running multiple `predict_dataflow` in multiple threads, and aggregate the results. Args: dataflows: a list of DataFlow to be used in :func:`predict_dataflow` model_funcs: a list of callable to be used in :func:`predict_dataflow` Returns: list of dict, in the format used by `DetectionDataset.eval_or_save_inference_results` """ num_worker = len(model_funcs) assert len(dataflows) == num_worker if num_worker == 1: return predict_dataflow(dataflows[0], model_funcs[0]) kwargs = {'thread_name_prefix': 'EvalWorker'} if sys.version_info.minor >= 6 else {} with ThreadPoolExecutor(max_workers=num_worker, **kwargs) as executor, \ tqdm.tqdm(total=sum([df.size() for df in dataflows])) as pbar: futures = [] for dataflow, pred in zip(dataflows, model_funcs): futures.append(executor.submit(predict_dataflow, dataflow, pred, pbar)) all_results = list(itertools.chain(*[fut.result() for fut in futures])) return all_results
[ "def", "multithread_predict_dataflow", "(", "dataflows", ",", "model_funcs", ")", ":", "num_worker", "=", "len", "(", "model_funcs", ")", "assert", "len", "(", "dataflows", ")", "==", "num_worker", "if", "num_worker", "==", "1", ":", "return", "predict_dataflow", "(", "dataflows", "[", "0", "]", ",", "model_funcs", "[", "0", "]", ")", "kwargs", "=", "{", "'thread_name_prefix'", ":", "'EvalWorker'", "}", "if", "sys", ".", "version_info", ".", "minor", ">=", "6", "else", "{", "}", "with", "ThreadPoolExecutor", "(", "max_workers", "=", "num_worker", ",", "*", "*", "kwargs", ")", "as", "executor", ",", "tqdm", ".", "tqdm", "(", "total", "=", "sum", "(", "[", "df", ".", "size", "(", ")", "for", "df", "in", "dataflows", "]", ")", ")", "as", "pbar", ":", "futures", "=", "[", "]", "for", "dataflow", ",", "pred", "in", "zip", "(", "dataflows", ",", "model_funcs", ")", ":", "futures", ".", "append", "(", "executor", ".", "submit", "(", "predict_dataflow", ",", "dataflow", ",", "pred", ",", "pbar", ")", ")", "all_results", "=", "list", "(", "itertools", ".", "chain", "(", "*", "[", "fut", ".", "result", "(", ")", "for", "fut", "in", "futures", "]", ")", ")", "return", "all_results" ]
Running multiple `predict_dataflow` in multiple threads, and aggregate the results. Args: dataflows: a list of DataFlow to be used in :func:`predict_dataflow` model_funcs: a list of callable to be used in :func:`predict_dataflow` Returns: list of dict, in the format used by `DetectionDataset.eval_or_save_inference_results`
[ "Running", "multiple", "predict_dataflow", "in", "multiple", "threads", "and", "aggregate", "the", "results", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/eval.py#L149-L172
27,256
tensorpack/tensorpack
tensorpack/models/fc.py
batch_flatten
def batch_flatten(x): """ Flatten the tensor except the first dimension. """ shape = x.get_shape().as_list()[1:] if None not in shape: return tf.reshape(x, [-1, int(np.prod(shape))]) return tf.reshape(x, tf.stack([tf.shape(x)[0], -1]))
python
def batch_flatten(x): """ Flatten the tensor except the first dimension. """ shape = x.get_shape().as_list()[1:] if None not in shape: return tf.reshape(x, [-1, int(np.prod(shape))]) return tf.reshape(x, tf.stack([tf.shape(x)[0], -1]))
[ "def", "batch_flatten", "(", "x", ")", ":", "shape", "=", "x", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", "1", ":", "]", "if", "None", "not", "in", "shape", ":", "return", "tf", ".", "reshape", "(", "x", ",", "[", "-", "1", ",", "int", "(", "np", ".", "prod", "(", "shape", ")", ")", "]", ")", "return", "tf", ".", "reshape", "(", "x", ",", "tf", ".", "stack", "(", "[", "tf", ".", "shape", "(", "x", ")", "[", "0", "]", ",", "-", "1", "]", ")", ")" ]
Flatten the tensor except the first dimension.
[ "Flatten", "the", "tensor", "except", "the", "first", "dimension", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/fc.py#L15-L22
27,257
tensorpack/tensorpack
tensorpack/predict/concurrency.py
MultiProcessPredictWorker._init_runtime
def _init_runtime(self): """ Call _init_runtime under different CUDA_VISIBLE_DEVICES, you'll have workers that run on multiGPUs """ if self.idx != 0: from tensorpack.models.registry import disable_layer_logging disable_layer_logging() self.predictor = OfflinePredictor(self.config) if self.idx == 0: with self.predictor.graph.as_default(): describe_trainable_vars()
python
def _init_runtime(self): """ Call _init_runtime under different CUDA_VISIBLE_DEVICES, you'll have workers that run on multiGPUs """ if self.idx != 0: from tensorpack.models.registry import disable_layer_logging disable_layer_logging() self.predictor = OfflinePredictor(self.config) if self.idx == 0: with self.predictor.graph.as_default(): describe_trainable_vars()
[ "def", "_init_runtime", "(", "self", ")", ":", "if", "self", ".", "idx", "!=", "0", ":", "from", "tensorpack", ".", "models", ".", "registry", "import", "disable_layer_logging", "disable_layer_logging", "(", ")", "self", ".", "predictor", "=", "OfflinePredictor", "(", "self", ".", "config", ")", "if", "self", ".", "idx", "==", "0", ":", "with", "self", ".", "predictor", ".", "graph", ".", "as_default", "(", ")", ":", "describe_trainable_vars", "(", ")" ]
Call _init_runtime under different CUDA_VISIBLE_DEVICES, you'll have workers that run on multiGPUs
[ "Call", "_init_runtime", "under", "different", "CUDA_VISIBLE_DEVICES", "you", "ll", "have", "workers", "that", "run", "on", "multiGPUs" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/predict/concurrency.py#L35-L45
27,258
tensorpack/tensorpack
tensorpack/predict/concurrency.py
PredictorWorkerThread.fetch_batch
def fetch_batch(self): """ Fetch a batch of data without waiting""" inp, f = self.queue.get() nr_input_var = len(inp) batched, futures = [[] for _ in range(nr_input_var)], [] for k in range(nr_input_var): batched[k].append(inp[k]) futures.append(f) while len(futures) < self.batch_size: try: inp, f = self.queue.get_nowait() for k in range(nr_input_var): batched[k].append(inp[k]) futures.append(f) except queue.Empty: break # do not wait for k in range(nr_input_var): batched[k] = np.asarray(batched[k]) return batched, futures
python
def fetch_batch(self): """ Fetch a batch of data without waiting""" inp, f = self.queue.get() nr_input_var = len(inp) batched, futures = [[] for _ in range(nr_input_var)], [] for k in range(nr_input_var): batched[k].append(inp[k]) futures.append(f) while len(futures) < self.batch_size: try: inp, f = self.queue.get_nowait() for k in range(nr_input_var): batched[k].append(inp[k]) futures.append(f) except queue.Empty: break # do not wait for k in range(nr_input_var): batched[k] = np.asarray(batched[k]) return batched, futures
[ "def", "fetch_batch", "(", "self", ")", ":", "inp", ",", "f", "=", "self", ".", "queue", ".", "get", "(", ")", "nr_input_var", "=", "len", "(", "inp", ")", "batched", ",", "futures", "=", "[", "[", "]", "for", "_", "in", "range", "(", "nr_input_var", ")", "]", ",", "[", "]", "for", "k", "in", "range", "(", "nr_input_var", ")", ":", "batched", "[", "k", "]", ".", "append", "(", "inp", "[", "k", "]", ")", "futures", ".", "append", "(", "f", ")", "while", "len", "(", "futures", ")", "<", "self", ".", "batch_size", ":", "try", ":", "inp", ",", "f", "=", "self", ".", "queue", ".", "get_nowait", "(", ")", "for", "k", "in", "range", "(", "nr_input_var", ")", ":", "batched", "[", "k", "]", ".", "append", "(", "inp", "[", "k", "]", ")", "futures", ".", "append", "(", "f", ")", "except", "queue", ".", "Empty", ":", "break", "# do not wait", "for", "k", "in", "range", "(", "nr_input_var", ")", ":", "batched", "[", "k", "]", "=", "np", ".", "asarray", "(", "batched", "[", "k", "]", ")", "return", "batched", ",", "futures" ]
Fetch a batch of data without waiting
[ "Fetch", "a", "batch", "of", "data", "without", "waiting" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/predict/concurrency.py#L110-L129
27,259
tensorpack/tensorpack
examples/GAN/DCGAN.py
Model.generator
def generator(self, z): """ return an image generated from z""" nf = 64 l = FullyConnected('fc0', z, nf * 8 * 4 * 4, activation=tf.identity) l = tf.reshape(l, [-1, 4, 4, nf * 8]) l = BNReLU(l) with argscope(Conv2DTranspose, activation=BNReLU, kernel_size=4, strides=2): l = Conv2DTranspose('deconv1', l, nf * 4) l = Conv2DTranspose('deconv2', l, nf * 2) l = Conv2DTranspose('deconv3', l, nf) l = Conv2DTranspose('deconv4', l, 3, activation=tf.identity) l = tf.tanh(l, name='gen') return l
python
def generator(self, z): """ return an image generated from z""" nf = 64 l = FullyConnected('fc0', z, nf * 8 * 4 * 4, activation=tf.identity) l = tf.reshape(l, [-1, 4, 4, nf * 8]) l = BNReLU(l) with argscope(Conv2DTranspose, activation=BNReLU, kernel_size=4, strides=2): l = Conv2DTranspose('deconv1', l, nf * 4) l = Conv2DTranspose('deconv2', l, nf * 2) l = Conv2DTranspose('deconv3', l, nf) l = Conv2DTranspose('deconv4', l, 3, activation=tf.identity) l = tf.tanh(l, name='gen') return l
[ "def", "generator", "(", "self", ",", "z", ")", ":", "nf", "=", "64", "l", "=", "FullyConnected", "(", "'fc0'", ",", "z", ",", "nf", "*", "8", "*", "4", "*", "4", ",", "activation", "=", "tf", ".", "identity", ")", "l", "=", "tf", ".", "reshape", "(", "l", ",", "[", "-", "1", ",", "4", ",", "4", ",", "nf", "*", "8", "]", ")", "l", "=", "BNReLU", "(", "l", ")", "with", "argscope", "(", "Conv2DTranspose", ",", "activation", "=", "BNReLU", ",", "kernel_size", "=", "4", ",", "strides", "=", "2", ")", ":", "l", "=", "Conv2DTranspose", "(", "'deconv1'", ",", "l", ",", "nf", "*", "4", ")", "l", "=", "Conv2DTranspose", "(", "'deconv2'", ",", "l", ",", "nf", "*", "2", ")", "l", "=", "Conv2DTranspose", "(", "'deconv3'", ",", "l", ",", "nf", ")", "l", "=", "Conv2DTranspose", "(", "'deconv4'", ",", "l", ",", "3", ",", "activation", "=", "tf", ".", "identity", ")", "l", "=", "tf", ".", "tanh", "(", "l", ",", "name", "=", "'gen'", ")", "return", "l" ]
return an image generated from z
[ "return", "an", "image", "generated", "from", "z" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/DCGAN.py#L46-L58
27,260
tensorpack/tensorpack
tensorpack/models/nonlin.py
BNReLU
def BNReLU(x, name=None): """ A shorthand of BatchNormalization + ReLU. """ x = BatchNorm('bn', x) x = tf.nn.relu(x, name=name) return x
python
def BNReLU(x, name=None): """ A shorthand of BatchNormalization + ReLU. """ x = BatchNorm('bn', x) x = tf.nn.relu(x, name=name) return x
[ "def", "BNReLU", "(", "x", ",", "name", "=", "None", ")", ":", "x", "=", "BatchNorm", "(", "'bn'", ",", "x", ")", "x", "=", "tf", ".", "nn", ".", "relu", "(", "x", ",", "name", "=", "name", ")", "return", "x" ]
A shorthand of BatchNormalization + ReLU.
[ "A", "shorthand", "of", "BatchNormalization", "+", "ReLU", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/nonlin.py#L64-L70
27,261
tensorpack/tensorpack
tensorpack/utils/develop.py
create_dummy_class
def create_dummy_class(klass, dependency): """ When a dependency of a class is not available, create a dummy class which throws ImportError when used. Args: klass (str): name of the class. dependency (str): name of the dependency. Returns: class: a class object """ assert not building_rtfd() class _DummyMetaClass(type): # throw error on class attribute access def __getattr__(_, __): raise AttributeError("Cannot import '{}', therefore '{}' is not available".format(dependency, klass)) @six.add_metaclass(_DummyMetaClass) class _Dummy(object): # throw error on constructor def __init__(self, *args, **kwargs): raise ImportError("Cannot import '{}', therefore '{}' is not available".format(dependency, klass)) return _Dummy
python
def create_dummy_class(klass, dependency): """ When a dependency of a class is not available, create a dummy class which throws ImportError when used. Args: klass (str): name of the class. dependency (str): name of the dependency. Returns: class: a class object """ assert not building_rtfd() class _DummyMetaClass(type): # throw error on class attribute access def __getattr__(_, __): raise AttributeError("Cannot import '{}', therefore '{}' is not available".format(dependency, klass)) @six.add_metaclass(_DummyMetaClass) class _Dummy(object): # throw error on constructor def __init__(self, *args, **kwargs): raise ImportError("Cannot import '{}', therefore '{}' is not available".format(dependency, klass)) return _Dummy
[ "def", "create_dummy_class", "(", "klass", ",", "dependency", ")", ":", "assert", "not", "building_rtfd", "(", ")", "class", "_DummyMetaClass", "(", "type", ")", ":", "# throw error on class attribute access", "def", "__getattr__", "(", "_", ",", "__", ")", ":", "raise", "AttributeError", "(", "\"Cannot import '{}', therefore '{}' is not available\"", ".", "format", "(", "dependency", ",", "klass", ")", ")", "@", "six", ".", "add_metaclass", "(", "_DummyMetaClass", ")", "class", "_Dummy", "(", "object", ")", ":", "# throw error on constructor", "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "raise", "ImportError", "(", "\"Cannot import '{}', therefore '{}' is not available\"", ".", "format", "(", "dependency", ",", "klass", ")", ")", "return", "_Dummy" ]
When a dependency of a class is not available, create a dummy class which throws ImportError when used. Args: klass (str): name of the class. dependency (str): name of the dependency. Returns: class: a class object
[ "When", "a", "dependency", "of", "a", "class", "is", "not", "available", "create", "a", "dummy", "class", "which", "throws", "ImportError", "when", "used", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/develop.py#L21-L45
27,262
tensorpack/tensorpack
tensorpack/utils/develop.py
create_dummy_func
def create_dummy_func(func, dependency): """ When a dependency of a function is not available, create a dummy function which throws ImportError when used. Args: func (str): name of the function. dependency (str or list[str]): name(s) of the dependency. Returns: function: a function object """ assert not building_rtfd() if isinstance(dependency, (list, tuple)): dependency = ','.join(dependency) def _dummy(*args, **kwargs): raise ImportError("Cannot import '{}', therefore '{}' is not available".format(dependency, func)) return _dummy
python
def create_dummy_func(func, dependency): """ When a dependency of a function is not available, create a dummy function which throws ImportError when used. Args: func (str): name of the function. dependency (str or list[str]): name(s) of the dependency. Returns: function: a function object """ assert not building_rtfd() if isinstance(dependency, (list, tuple)): dependency = ','.join(dependency) def _dummy(*args, **kwargs): raise ImportError("Cannot import '{}', therefore '{}' is not available".format(dependency, func)) return _dummy
[ "def", "create_dummy_func", "(", "func", ",", "dependency", ")", ":", "assert", "not", "building_rtfd", "(", ")", "if", "isinstance", "(", "dependency", ",", "(", "list", ",", "tuple", ")", ")", ":", "dependency", "=", "','", ".", "join", "(", "dependency", ")", "def", "_dummy", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "raise", "ImportError", "(", "\"Cannot import '{}', therefore '{}' is not available\"", ".", "format", "(", "dependency", ",", "func", ")", ")", "return", "_dummy" ]
When a dependency of a function is not available, create a dummy function which throws ImportError when used. Args: func (str): name of the function. dependency (str or list[str]): name(s) of the dependency. Returns: function: a function object
[ "When", "a", "dependency", "of", "a", "function", "is", "not", "available", "create", "a", "dummy", "function", "which", "throws", "ImportError", "when", "used", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/develop.py#L48-L66
27,263
tensorpack/tensorpack
tensorpack/utils/develop.py
log_deprecated
def log_deprecated(name="", text="", eos=""): """ Log deprecation warning. Args: name (str): name of the deprecated item. text (str, optional): information about the deprecation. eos (str, optional): end of service date such as "YYYY-MM-DD". """ assert name or text if eos: eos = "after " + datetime(*map(int, eos.split("-"))).strftime("%d %b") if name: if eos: warn_msg = "%s will be deprecated %s. %s" % (name, eos, text) else: warn_msg = "%s was deprecated. %s" % (name, text) else: warn_msg = text if eos: warn_msg += " Legacy period ends %s" % eos logger.warn("[Deprecated] " + warn_msg)
python
def log_deprecated(name="", text="", eos=""): """ Log deprecation warning. Args: name (str): name of the deprecated item. text (str, optional): information about the deprecation. eos (str, optional): end of service date such as "YYYY-MM-DD". """ assert name or text if eos: eos = "after " + datetime(*map(int, eos.split("-"))).strftime("%d %b") if name: if eos: warn_msg = "%s will be deprecated %s. %s" % (name, eos, text) else: warn_msg = "%s was deprecated. %s" % (name, text) else: warn_msg = text if eos: warn_msg += " Legacy period ends %s" % eos logger.warn("[Deprecated] " + warn_msg)
[ "def", "log_deprecated", "(", "name", "=", "\"\"", ",", "text", "=", "\"\"", ",", "eos", "=", "\"\"", ")", ":", "assert", "name", "or", "text", "if", "eos", ":", "eos", "=", "\"after \"", "+", "datetime", "(", "*", "map", "(", "int", ",", "eos", ".", "split", "(", "\"-\"", ")", ")", ")", ".", "strftime", "(", "\"%d %b\"", ")", "if", "name", ":", "if", "eos", ":", "warn_msg", "=", "\"%s will be deprecated %s. %s\"", "%", "(", "name", ",", "eos", ",", "text", ")", "else", ":", "warn_msg", "=", "\"%s was deprecated. %s\"", "%", "(", "name", ",", "text", ")", "else", ":", "warn_msg", "=", "text", "if", "eos", ":", "warn_msg", "+=", "\" Legacy period ends %s\"", "%", "eos", "logger", ".", "warn", "(", "\"[Deprecated] \"", "+", "warn_msg", ")" ]
Log deprecation warning. Args: name (str): name of the deprecated item. text (str, optional): information about the deprecation. eos (str, optional): end of service date such as "YYYY-MM-DD".
[ "Log", "deprecation", "warning", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/develop.py#L78-L99
27,264
tensorpack/tensorpack
tensorpack/input_source/input_source.py
QueueInput._create_ema_callback
def _create_ema_callback(self): """ Create a hook-only callback which maintain EMA of the queue size. Also tf.summary.scalar the EMA. """ with self.cached_name_scope(): # in TF there is no API to get queue capacity, so we can only summary the size size = tf.cast(self.queue.size(), tf.float32, name='queue_size') size_ema_op = add_moving_summary(size, collection=None, decay=0.5)[0].op ret = RunOp( lambda: size_ema_op, run_before=False, run_as_trigger=False, run_step=True) ret.name_scope = "InputSource/EMA" return ret
python
def _create_ema_callback(self): """ Create a hook-only callback which maintain EMA of the queue size. Also tf.summary.scalar the EMA. """ with self.cached_name_scope(): # in TF there is no API to get queue capacity, so we can only summary the size size = tf.cast(self.queue.size(), tf.float32, name='queue_size') size_ema_op = add_moving_summary(size, collection=None, decay=0.5)[0].op ret = RunOp( lambda: size_ema_op, run_before=False, run_as_trigger=False, run_step=True) ret.name_scope = "InputSource/EMA" return ret
[ "def", "_create_ema_callback", "(", "self", ")", ":", "with", "self", ".", "cached_name_scope", "(", ")", ":", "# in TF there is no API to get queue capacity, so we can only summary the size", "size", "=", "tf", ".", "cast", "(", "self", ".", "queue", ".", "size", "(", ")", ",", "tf", ".", "float32", ",", "name", "=", "'queue_size'", ")", "size_ema_op", "=", "add_moving_summary", "(", "size", ",", "collection", "=", "None", ",", "decay", "=", "0.5", ")", "[", "0", "]", ".", "op", "ret", "=", "RunOp", "(", "lambda", ":", "size_ema_op", ",", "run_before", "=", "False", ",", "run_as_trigger", "=", "False", ",", "run_step", "=", "True", ")", "ret", ".", "name_scope", "=", "\"InputSource/EMA\"", "return", "ret" ]
Create a hook-only callback which maintain EMA of the queue size. Also tf.summary.scalar the EMA.
[ "Create", "a", "hook", "-", "only", "callback", "which", "maintain", "EMA", "of", "the", "queue", "size", ".", "Also", "tf", ".", "summary", ".", "scalar", "the", "EMA", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/input_source/input_source.py#L248-L263
27,265
tensorpack/tensorpack
tensorpack/input_source/input_source.py
BatchQueueInput._setup
def _setup(self, inputs): logger.info("Setting up the queue for CPU prefetching ...") self.input_placehdrs = [build_or_reuse_placeholder(v) for v in inputs] assert len(self.input_placehdrs) > 0, \ "BatchQueueInput has to be used with some input signature!" # prepare placeholders without the first dimension placehdrs_nobatch = [] for p in self.input_placehdrs: placehdrs_nobatch.append(tfv1.placeholder( dtype=p.dtype, shape=p.get_shape().as_list()[1:], name=get_op_tensor_name(p.name)[0] + '-nobatch')) # dequeue_many requires fully-defined shapes shape_err = "Use of BatchQueueInput requires inputs to have fully-defined " "shapes except for the batch dimension" shapes = [] for p in placehdrs_nobatch: assert p.get_shape().is_fully_defined(), shape_err shapes.append(p.get_shape()) with self.cached_name_scope(): if self.queue is None: self.queue = tf.FIFOQueue( 3000, [x.dtype for x in self.input_placehdrs], shapes=shapes, name='input_queue') for shp in self.queue.shapes: assert shp.is_fully_defined(), shape_err self.thread = EnqueueThread(self.queue, self._inf_ds, placehdrs_nobatch)
python
def _setup(self, inputs): logger.info("Setting up the queue for CPU prefetching ...") self.input_placehdrs = [build_or_reuse_placeholder(v) for v in inputs] assert len(self.input_placehdrs) > 0, \ "BatchQueueInput has to be used with some input signature!" # prepare placeholders without the first dimension placehdrs_nobatch = [] for p in self.input_placehdrs: placehdrs_nobatch.append(tfv1.placeholder( dtype=p.dtype, shape=p.get_shape().as_list()[1:], name=get_op_tensor_name(p.name)[0] + '-nobatch')) # dequeue_many requires fully-defined shapes shape_err = "Use of BatchQueueInput requires inputs to have fully-defined " "shapes except for the batch dimension" shapes = [] for p in placehdrs_nobatch: assert p.get_shape().is_fully_defined(), shape_err shapes.append(p.get_shape()) with self.cached_name_scope(): if self.queue is None: self.queue = tf.FIFOQueue( 3000, [x.dtype for x in self.input_placehdrs], shapes=shapes, name='input_queue') for shp in self.queue.shapes: assert shp.is_fully_defined(), shape_err self.thread = EnqueueThread(self.queue, self._inf_ds, placehdrs_nobatch)
[ "def", "_setup", "(", "self", ",", "inputs", ")", ":", "logger", ".", "info", "(", "\"Setting up the queue for CPU prefetching ...\"", ")", "self", ".", "input_placehdrs", "=", "[", "build_or_reuse_placeholder", "(", "v", ")", "for", "v", "in", "inputs", "]", "assert", "len", "(", "self", ".", "input_placehdrs", ")", ">", "0", ",", "\"BatchQueueInput has to be used with some input signature!\"", "# prepare placeholders without the first dimension", "placehdrs_nobatch", "=", "[", "]", "for", "p", "in", "self", ".", "input_placehdrs", ":", "placehdrs_nobatch", ".", "append", "(", "tfv1", ".", "placeholder", "(", "dtype", "=", "p", ".", "dtype", ",", "shape", "=", "p", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", "1", ":", "]", ",", "name", "=", "get_op_tensor_name", "(", "p", ".", "name", ")", "[", "0", "]", "+", "'-nobatch'", ")", ")", "# dequeue_many requires fully-defined shapes", "shape_err", "=", "\"Use of BatchQueueInput requires inputs to have fully-defined \"", "shapes", "=", "[", "]", "for", "p", "in", "placehdrs_nobatch", ":", "assert", "p", ".", "get_shape", "(", ")", ".", "is_fully_defined", "(", ")", ",", "shape_err", "shapes", ".", "append", "(", "p", ".", "get_shape", "(", ")", ")", "with", "self", ".", "cached_name_scope", "(", ")", ":", "if", "self", ".", "queue", "is", "None", ":", "self", ".", "queue", "=", "tf", ".", "FIFOQueue", "(", "3000", ",", "[", "x", ".", "dtype", "for", "x", "in", "self", ".", "input_placehdrs", "]", ",", "shapes", "=", "shapes", ",", "name", "=", "'input_queue'", ")", "for", "shp", "in", "self", ".", "queue", ".", "shapes", ":", "assert", "shp", ".", "is_fully_defined", "(", ")", ",", "shape_err", "self", ".", "thread", "=", "EnqueueThread", "(", "self", ".", "queue", ",", "self", ".", "_inf_ds", ",", "placehdrs_nobatch", ")" ]
shapes except for the batch dimension
[ "shapes", "except", "for", "the", "batch", "dimension" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/input_source/input_source.py#L301-L331
27,266
tensorpack/tensorpack
tensorpack/input_source/input_source.py
TFDatasetInput.dataflow_to_dataset
def dataflow_to_dataset(df, types): """ Wrap a dataflow to tf.data.Dataset. This function will also reset the dataflow. If the dataflow itself is finite, the returned dataset is also finite. Therefore, if used for training, you'll need to add `.repeat()` on the returned dataset. Args: df (DataFlow): a dataflow which produces lists types([tf.DType]): list of types Returns: (tf.data.Dataset) """ # TODO theoretically it can support dict assert isinstance(df, DataFlow), df assert isinstance(types, (list, tuple)), types df = MapData(df, lambda dp: tuple(dp)) df.reset_state() ds = tf.data.Dataset.from_generator( df.get_data, tuple(types)) return ds
python
def dataflow_to_dataset(df, types): """ Wrap a dataflow to tf.data.Dataset. This function will also reset the dataflow. If the dataflow itself is finite, the returned dataset is also finite. Therefore, if used for training, you'll need to add `.repeat()` on the returned dataset. Args: df (DataFlow): a dataflow which produces lists types([tf.DType]): list of types Returns: (tf.data.Dataset) """ # TODO theoretically it can support dict assert isinstance(df, DataFlow), df assert isinstance(types, (list, tuple)), types df = MapData(df, lambda dp: tuple(dp)) df.reset_state() ds = tf.data.Dataset.from_generator( df.get_data, tuple(types)) return ds
[ "def", "dataflow_to_dataset", "(", "df", ",", "types", ")", ":", "# TODO theoretically it can support dict", "assert", "isinstance", "(", "df", ",", "DataFlow", ")", ",", "df", "assert", "isinstance", "(", "types", ",", "(", "list", ",", "tuple", ")", ")", ",", "types", "df", "=", "MapData", "(", "df", ",", "lambda", "dp", ":", "tuple", "(", "dp", ")", ")", "df", ".", "reset_state", "(", ")", "ds", "=", "tf", ".", "data", ".", "Dataset", ".", "from_generator", "(", "df", ".", "get_data", ",", "tuple", "(", "types", ")", ")", "return", "ds" ]
Wrap a dataflow to tf.data.Dataset. This function will also reset the dataflow. If the dataflow itself is finite, the returned dataset is also finite. Therefore, if used for training, you'll need to add `.repeat()` on the returned dataset. Args: df (DataFlow): a dataflow which produces lists types([tf.DType]): list of types Returns: (tf.data.Dataset)
[ "Wrap", "a", "dataflow", "to", "tf", ".", "data", ".", "Dataset", ".", "This", "function", "will", "also", "reset", "the", "dataflow", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/input_source/input_source.py#L496-L519
27,267
tensorpack/tensorpack
examples/FasterRCNN/utils/np_box_ops.py
ioa
def ioa(boxes1, boxes2): """Computes pairwise intersection-over-area between box collections. Intersection-over-area (ioa) between two boxes box1 and box2 is defined as their intersection area over box2's area. Note that ioa is not symmetric, that is, IOA(box1, box2) != IOA(box2, box1). Args: boxes1: a numpy array with shape [N, 4] holding N boxes. boxes2: a numpy array with shape [M, 4] holding N boxes. Returns: a numpy array with shape [N, M] representing pairwise ioa scores. """ intersect = intersection(boxes1, boxes2) inv_areas = np.expand_dims(1.0 / area(boxes2), axis=0) return intersect * inv_areas
python
def ioa(boxes1, boxes2): """Computes pairwise intersection-over-area between box collections. Intersection-over-area (ioa) between two boxes box1 and box2 is defined as their intersection area over box2's area. Note that ioa is not symmetric, that is, IOA(box1, box2) != IOA(box2, box1). Args: boxes1: a numpy array with shape [N, 4] holding N boxes. boxes2: a numpy array with shape [M, 4] holding N boxes. Returns: a numpy array with shape [N, M] representing pairwise ioa scores. """ intersect = intersection(boxes1, boxes2) inv_areas = np.expand_dims(1.0 / area(boxes2), axis=0) return intersect * inv_areas
[ "def", "ioa", "(", "boxes1", ",", "boxes2", ")", ":", "intersect", "=", "intersection", "(", "boxes1", ",", "boxes2", ")", "inv_areas", "=", "np", ".", "expand_dims", "(", "1.0", "/", "area", "(", "boxes2", ")", ",", "axis", "=", "0", ")", "return", "intersect", "*", "inv_areas" ]
Computes pairwise intersection-over-area between box collections. Intersection-over-area (ioa) between two boxes box1 and box2 is defined as their intersection area over box2's area. Note that ioa is not symmetric, that is, IOA(box1, box2) != IOA(box2, box1). Args: boxes1: a numpy array with shape [N, 4] holding N boxes. boxes2: a numpy array with shape [M, 4] holding N boxes. Returns: a numpy array with shape [N, M] representing pairwise ioa scores.
[ "Computes", "pairwise", "intersection", "-", "over", "-", "area", "between", "box", "collections", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/utils/np_box_ops.py#L81-L97
27,268
tensorpack/tensorpack
tensorpack/dataflow/dataset/caltech101.py
maybe_download
def maybe_download(url, work_directory): """Download the data from Marlin's website, unless it's already here.""" filename = url.split("/")[-1] filepath = os.path.join(work_directory, filename) if not os.path.exists(filepath): logger.info("Downloading to {}...".format(filepath)) download(url, work_directory) return filepath
python
def maybe_download(url, work_directory): """Download the data from Marlin's website, unless it's already here.""" filename = url.split("/")[-1] filepath = os.path.join(work_directory, filename) if not os.path.exists(filepath): logger.info("Downloading to {}...".format(filepath)) download(url, work_directory) return filepath
[ "def", "maybe_download", "(", "url", ",", "work_directory", ")", ":", "filename", "=", "url", ".", "split", "(", "\"/\"", ")", "[", "-", "1", "]", "filepath", "=", "os", ".", "path", ".", "join", "(", "work_directory", ",", "filename", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "filepath", ")", ":", "logger", ".", "info", "(", "\"Downloading to {}...\"", ".", "format", "(", "filepath", ")", ")", "download", "(", "url", ",", "work_directory", ")", "return", "filepath" ]
Download the data from Marlin's website, unless it's already here.
[ "Download", "the", "data", "from", "Marlin", "s", "website", "unless", "it", "s", "already", "here", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/caltech101.py#L15-L22
27,269
tensorpack/tensorpack
tensorpack/dataflow/dataset/ilsvrc.py
ILSVRCMeta.guess_dir_structure
def guess_dir_structure(dir): """ Return the directory structure of "dir". Args: dir(str): something like '/path/to/imagenet/val' Returns: either 'train' or 'original' """ subdir = os.listdir(dir)[0] # find a subdir starting with 'n' if subdir.startswith('n') and \ os.path.isdir(os.path.join(dir, subdir)): dir_structure = 'train' else: dir_structure = 'original' logger.info( "[ILSVRC12] Assuming directory {} has '{}' structure.".format( dir, dir_structure)) return dir_structure
python
def guess_dir_structure(dir): """ Return the directory structure of "dir". Args: dir(str): something like '/path/to/imagenet/val' Returns: either 'train' or 'original' """ subdir = os.listdir(dir)[0] # find a subdir starting with 'n' if subdir.startswith('n') and \ os.path.isdir(os.path.join(dir, subdir)): dir_structure = 'train' else: dir_structure = 'original' logger.info( "[ILSVRC12] Assuming directory {} has '{}' structure.".format( dir, dir_structure)) return dir_structure
[ "def", "guess_dir_structure", "(", "dir", ")", ":", "subdir", "=", "os", ".", "listdir", "(", "dir", ")", "[", "0", "]", "# find a subdir starting with 'n'", "if", "subdir", ".", "startswith", "(", "'n'", ")", "and", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "dir", ",", "subdir", ")", ")", ":", "dir_structure", "=", "'train'", "else", ":", "dir_structure", "=", "'original'", "logger", ".", "info", "(", "\"[ILSVRC12] Assuming directory {} has '{}' structure.\"", ".", "format", "(", "dir", ",", "dir_structure", ")", ")", "return", "dir_structure" ]
Return the directory structure of "dir". Args: dir(str): something like '/path/to/imagenet/val' Returns: either 'train' or 'original'
[ "Return", "the", "directory", "structure", "of", "dir", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/ilsvrc.py#L109-L129
27,270
tensorpack/tensorpack
examples/FasterRCNN/dataset.py
COCODetection._use_absolute_file_name
def _use_absolute_file_name(self, img): """ Change relative filename to abosolute file name. """ img['file_name'] = os.path.join( self._imgdir, img['file_name']) assert os.path.isfile(img['file_name']), img['file_name']
python
def _use_absolute_file_name(self, img): """ Change relative filename to abosolute file name. """ img['file_name'] = os.path.join( self._imgdir, img['file_name']) assert os.path.isfile(img['file_name']), img['file_name']
[ "def", "_use_absolute_file_name", "(", "self", ",", "img", ")", ":", "img", "[", "'file_name'", "]", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_imgdir", ",", "img", "[", "'file_name'", "]", ")", "assert", "os", ".", "path", ".", "isfile", "(", "img", "[", "'file_name'", "]", ")", ",", "img", "[", "'file_name'", "]" ]
Change relative filename to abosolute file name.
[ "Change", "relative", "filename", "to", "abosolute", "file", "name", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L104-L110
27,271
tensorpack/tensorpack
examples/FasterRCNN/dataset.py
COCODetection._add_detection_gt
def _add_detection_gt(self, img, add_mask): """ Add 'boxes', 'class', 'is_crowd' of this image to the dict, used by detection. If add_mask is True, also add 'segmentation' in coco poly format. """ # ann_ids = self.coco.getAnnIds(imgIds=img['image_id']) # objs = self.coco.loadAnns(ann_ids) objs = self.coco.imgToAnns[img['image_id']] # equivalent but faster than the above two lines # clean-up boxes valid_objs = [] width = img.pop('width') height = img.pop('height') for objid, obj in enumerate(objs): if obj.get('ignore', 0) == 1: continue x1, y1, w, h = obj['bbox'] # bbox is originally in float # x1/y1 means upper-left corner and w/h means true w/h. This can be verified by segmentation pixels. # But we do make an assumption here that (0.0, 0.0) is upper-left corner of the first pixel x1 = np.clip(float(x1), 0, width) y1 = np.clip(float(y1), 0, height) w = np.clip(float(x1 + w), 0, width) - x1 h = np.clip(float(y1 + h), 0, height) - y1 # Require non-zero seg area and more than 1x1 box size if obj['area'] > 1 and w > 0 and h > 0 and w * h >= 4: obj['bbox'] = [x1, y1, x1 + w, y1 + h] valid_objs.append(obj) if add_mask: segs = obj['segmentation'] if not isinstance(segs, list): assert obj['iscrowd'] == 1 obj['segmentation'] = None else: valid_segs = [np.asarray(p).reshape(-1, 2).astype('float32') for p in segs if len(p) >= 6] if len(valid_segs) == 0: logger.error("Object {} in image {} has no valid polygons!".format(objid, img['file_name'])) elif len(valid_segs) < len(segs): logger.warn("Object {} in image {} has invalid polygons!".format(objid, img['file_name'])) obj['segmentation'] = valid_segs # all geometrically-valid boxes are returned boxes = np.asarray([obj['bbox'] for obj in valid_objs], dtype='float32') # (n, 4) cls = np.asarray([ self.COCO_id_to_category_id[obj['category_id']] for obj in valid_objs], dtype='int32') # (n,) is_crowd = np.asarray([obj['iscrowd'] for obj in valid_objs], dtype='int8') # add the keys img['boxes'] = boxes # nx4 img['class'] = cls # n, always >0 img['is_crowd'] = is_crowd # n, if add_mask: # also required to be float32 img['segmentation'] = [ obj['segmentation'] for obj in valid_objs]
python
def _add_detection_gt(self, img, add_mask): """ Add 'boxes', 'class', 'is_crowd' of this image to the dict, used by detection. If add_mask is True, also add 'segmentation' in coco poly format. """ # ann_ids = self.coco.getAnnIds(imgIds=img['image_id']) # objs = self.coco.loadAnns(ann_ids) objs = self.coco.imgToAnns[img['image_id']] # equivalent but faster than the above two lines # clean-up boxes valid_objs = [] width = img.pop('width') height = img.pop('height') for objid, obj in enumerate(objs): if obj.get('ignore', 0) == 1: continue x1, y1, w, h = obj['bbox'] # bbox is originally in float # x1/y1 means upper-left corner and w/h means true w/h. This can be verified by segmentation pixels. # But we do make an assumption here that (0.0, 0.0) is upper-left corner of the first pixel x1 = np.clip(float(x1), 0, width) y1 = np.clip(float(y1), 0, height) w = np.clip(float(x1 + w), 0, width) - x1 h = np.clip(float(y1 + h), 0, height) - y1 # Require non-zero seg area and more than 1x1 box size if obj['area'] > 1 and w > 0 and h > 0 and w * h >= 4: obj['bbox'] = [x1, y1, x1 + w, y1 + h] valid_objs.append(obj) if add_mask: segs = obj['segmentation'] if not isinstance(segs, list): assert obj['iscrowd'] == 1 obj['segmentation'] = None else: valid_segs = [np.asarray(p).reshape(-1, 2).astype('float32') for p in segs if len(p) >= 6] if len(valid_segs) == 0: logger.error("Object {} in image {} has no valid polygons!".format(objid, img['file_name'])) elif len(valid_segs) < len(segs): logger.warn("Object {} in image {} has invalid polygons!".format(objid, img['file_name'])) obj['segmentation'] = valid_segs # all geometrically-valid boxes are returned boxes = np.asarray([obj['bbox'] for obj in valid_objs], dtype='float32') # (n, 4) cls = np.asarray([ self.COCO_id_to_category_id[obj['category_id']] for obj in valid_objs], dtype='int32') # (n,) is_crowd = np.asarray([obj['iscrowd'] for obj in valid_objs], dtype='int8') # add the keys img['boxes'] = boxes # nx4 img['class'] = cls # n, always >0 img['is_crowd'] = is_crowd # n, if add_mask: # also required to be float32 img['segmentation'] = [ obj['segmentation'] for obj in valid_objs]
[ "def", "_add_detection_gt", "(", "self", ",", "img", ",", "add_mask", ")", ":", "# ann_ids = self.coco.getAnnIds(imgIds=img['image_id'])", "# objs = self.coco.loadAnns(ann_ids)", "objs", "=", "self", ".", "coco", ".", "imgToAnns", "[", "img", "[", "'image_id'", "]", "]", "# equivalent but faster than the above two lines", "# clean-up boxes", "valid_objs", "=", "[", "]", "width", "=", "img", ".", "pop", "(", "'width'", ")", "height", "=", "img", ".", "pop", "(", "'height'", ")", "for", "objid", ",", "obj", "in", "enumerate", "(", "objs", ")", ":", "if", "obj", ".", "get", "(", "'ignore'", ",", "0", ")", "==", "1", ":", "continue", "x1", ",", "y1", ",", "w", ",", "h", "=", "obj", "[", "'bbox'", "]", "# bbox is originally in float", "# x1/y1 means upper-left corner and w/h means true w/h. This can be verified by segmentation pixels.", "# But we do make an assumption here that (0.0, 0.0) is upper-left corner of the first pixel", "x1", "=", "np", ".", "clip", "(", "float", "(", "x1", ")", ",", "0", ",", "width", ")", "y1", "=", "np", ".", "clip", "(", "float", "(", "y1", ")", ",", "0", ",", "height", ")", "w", "=", "np", ".", "clip", "(", "float", "(", "x1", "+", "w", ")", ",", "0", ",", "width", ")", "-", "x1", "h", "=", "np", ".", "clip", "(", "float", "(", "y1", "+", "h", ")", ",", "0", ",", "height", ")", "-", "y1", "# Require non-zero seg area and more than 1x1 box size", "if", "obj", "[", "'area'", "]", ">", "1", "and", "w", ">", "0", "and", "h", ">", "0", "and", "w", "*", "h", ">=", "4", ":", "obj", "[", "'bbox'", "]", "=", "[", "x1", ",", "y1", ",", "x1", "+", "w", ",", "y1", "+", "h", "]", "valid_objs", ".", "append", "(", "obj", ")", "if", "add_mask", ":", "segs", "=", "obj", "[", "'segmentation'", "]", "if", "not", "isinstance", "(", "segs", ",", "list", ")", ":", "assert", "obj", "[", "'iscrowd'", "]", "==", "1", "obj", "[", "'segmentation'", "]", "=", "None", "else", ":", "valid_segs", "=", "[", "np", ".", "asarray", "(", "p", ")", ".", "reshape", "(", "-", "1", ",", "2", ")", ".", "astype", "(", "'float32'", ")", "for", "p", "in", "segs", "if", "len", "(", "p", ")", ">=", "6", "]", "if", "len", "(", "valid_segs", ")", "==", "0", ":", "logger", ".", "error", "(", "\"Object {} in image {} has no valid polygons!\"", ".", "format", "(", "objid", ",", "img", "[", "'file_name'", "]", ")", ")", "elif", "len", "(", "valid_segs", ")", "<", "len", "(", "segs", ")", ":", "logger", ".", "warn", "(", "\"Object {} in image {} has invalid polygons!\"", ".", "format", "(", "objid", ",", "img", "[", "'file_name'", "]", ")", ")", "obj", "[", "'segmentation'", "]", "=", "valid_segs", "# all geometrically-valid boxes are returned", "boxes", "=", "np", ".", "asarray", "(", "[", "obj", "[", "'bbox'", "]", "for", "obj", "in", "valid_objs", "]", ",", "dtype", "=", "'float32'", ")", "# (n, 4)", "cls", "=", "np", ".", "asarray", "(", "[", "self", ".", "COCO_id_to_category_id", "[", "obj", "[", "'category_id'", "]", "]", "for", "obj", "in", "valid_objs", "]", ",", "dtype", "=", "'int32'", ")", "# (n,)", "is_crowd", "=", "np", ".", "asarray", "(", "[", "obj", "[", "'iscrowd'", "]", "for", "obj", "in", "valid_objs", "]", ",", "dtype", "=", "'int8'", ")", "# add the keys", "img", "[", "'boxes'", "]", "=", "boxes", "# nx4", "img", "[", "'class'", "]", "=", "cls", "# n, always >0", "img", "[", "'is_crowd'", "]", "=", "is_crowd", "# n,", "if", "add_mask", ":", "# also required to be float32", "img", "[", "'segmentation'", "]", "=", "[", "obj", "[", "'segmentation'", "]", "for", "obj", "in", "valid_objs", "]" ]
Add 'boxes', 'class', 'is_crowd' of this image to the dict, used by detection. If add_mask is True, also add 'segmentation' in coco poly format.
[ "Add", "boxes", "class", "is_crowd", "of", "this", "image", "to", "the", "dict", "used", "by", "detection", ".", "If", "add_mask", "is", "True", "also", "add", "segmentation", "in", "coco", "poly", "format", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L112-L170
27,272
tensorpack/tensorpack
examples/FasterRCNN/dataset.py
COCODetection.load_many
def load_many(basedir, names, add_gt=True, add_mask=False): """ Load and merges several instance files together. Returns the same format as :meth:`COCODetection.load`. """ if not isinstance(names, (list, tuple)): names = [names] ret = [] for n in names: coco = COCODetection(basedir, n) ret.extend(coco.load(add_gt, add_mask=add_mask)) return ret
python
def load_many(basedir, names, add_gt=True, add_mask=False): """ Load and merges several instance files together. Returns the same format as :meth:`COCODetection.load`. """ if not isinstance(names, (list, tuple)): names = [names] ret = [] for n in names: coco = COCODetection(basedir, n) ret.extend(coco.load(add_gt, add_mask=add_mask)) return ret
[ "def", "load_many", "(", "basedir", ",", "names", ",", "add_gt", "=", "True", ",", "add_mask", "=", "False", ")", ":", "if", "not", "isinstance", "(", "names", ",", "(", "list", ",", "tuple", ")", ")", ":", "names", "=", "[", "names", "]", "ret", "=", "[", "]", "for", "n", "in", "names", ":", "coco", "=", "COCODetection", "(", "basedir", ",", "n", ")", "ret", ".", "extend", "(", "coco", ".", "load", "(", "add_gt", ",", "add_mask", "=", "add_mask", ")", ")", "return", "ret" ]
Load and merges several instance files together. Returns the same format as :meth:`COCODetection.load`.
[ "Load", "and", "merges", "several", "instance", "files", "together", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L173-L185
27,273
tensorpack/tensorpack
tensorpack/utils/timer.py
timed_operation
def timed_operation(msg, log_start=False): """ Surround a context with a timer. Args: msg(str): the log to print. log_start(bool): whether to print also at the beginning. Example: .. code-block:: python with timed_operation('Good Stuff'): time.sleep(1) Will print: .. code-block:: python Good stuff finished, time:1sec. """ assert len(msg) if log_start: logger.info('Start {} ...'.format(msg)) start = timer() yield msg = msg[0].upper() + msg[1:] logger.info('{} finished, time:{:.4f} sec.'.format( msg, timer() - start))
python
def timed_operation(msg, log_start=False): """ Surround a context with a timer. Args: msg(str): the log to print. log_start(bool): whether to print also at the beginning. Example: .. code-block:: python with timed_operation('Good Stuff'): time.sleep(1) Will print: .. code-block:: python Good stuff finished, time:1sec. """ assert len(msg) if log_start: logger.info('Start {} ...'.format(msg)) start = timer() yield msg = msg[0].upper() + msg[1:] logger.info('{} finished, time:{:.4f} sec.'.format( msg, timer() - start))
[ "def", "timed_operation", "(", "msg", ",", "log_start", "=", "False", ")", ":", "assert", "len", "(", "msg", ")", "if", "log_start", ":", "logger", ".", "info", "(", "'Start {} ...'", ".", "format", "(", "msg", ")", ")", "start", "=", "timer", "(", ")", "yield", "msg", "=", "msg", "[", "0", "]", ".", "upper", "(", ")", "+", "msg", "[", "1", ":", "]", "logger", ".", "info", "(", "'{} finished, time:{:.4f} sec.'", ".", "format", "(", "msg", ",", "timer", "(", ")", "-", "start", ")", ")" ]
Surround a context with a timer. Args: msg(str): the log to print. log_start(bool): whether to print also at the beginning. Example: .. code-block:: python with timed_operation('Good Stuff'): time.sleep(1) Will print: .. code-block:: python Good stuff finished, time:1sec.
[ "Surround", "a", "context", "with", "a", "timer", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/timer.py#L23-L50
27,274
tensorpack/tensorpack
tensorpack/utils/timer.py
total_timer
def total_timer(msg): """ A context which add the time spent inside to TotalTimer. """ start = timer() yield t = timer() - start _TOTAL_TIMER_DATA[msg].feed(t)
python
def total_timer(msg): """ A context which add the time spent inside to TotalTimer. """ start = timer() yield t = timer() - start _TOTAL_TIMER_DATA[msg].feed(t)
[ "def", "total_timer", "(", "msg", ")", ":", "start", "=", "timer", "(", ")", "yield", "t", "=", "timer", "(", ")", "-", "start", "_TOTAL_TIMER_DATA", "[", "msg", "]", ".", "feed", "(", "t", ")" ]
A context which add the time spent inside to TotalTimer.
[ "A", "context", "which", "add", "the", "time", "spent", "inside", "to", "TotalTimer", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/timer.py#L57-L62
27,275
tensorpack/tensorpack
tensorpack/utils/timer.py
print_total_timer
def print_total_timer(): """ Print the content of the TotalTimer, if it's not empty. This function will automatically get called when program exits. """ if len(_TOTAL_TIMER_DATA) == 0: return for k, v in six.iteritems(_TOTAL_TIMER_DATA): logger.info("Total Time: {} -> {:.2f} sec, {} times, {:.3g} sec/time".format( k, v.sum, v.count, v.average))
python
def print_total_timer(): """ Print the content of the TotalTimer, if it's not empty. This function will automatically get called when program exits. """ if len(_TOTAL_TIMER_DATA) == 0: return for k, v in six.iteritems(_TOTAL_TIMER_DATA): logger.info("Total Time: {} -> {:.2f} sec, {} times, {:.3g} sec/time".format( k, v.sum, v.count, v.average))
[ "def", "print_total_timer", "(", ")", ":", "if", "len", "(", "_TOTAL_TIMER_DATA", ")", "==", "0", ":", "return", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "_TOTAL_TIMER_DATA", ")", ":", "logger", ".", "info", "(", "\"Total Time: {} -> {:.2f} sec, {} times, {:.3g} sec/time\"", ".", "format", "(", "k", ",", "v", ".", "sum", ",", "v", ".", "count", ",", "v", ".", "average", ")", ")" ]
Print the content of the TotalTimer, if it's not empty. This function will automatically get called when program exits.
[ "Print", "the", "content", "of", "the", "TotalTimer", "if", "it", "s", "not", "empty", ".", "This", "function", "will", "automatically", "get", "called", "when", "program", "exits", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/timer.py#L65-L74
27,276
tensorpack/tensorpack
tensorpack/dataflow/imgaug/base.py
AugmentorList.reset_state
def reset_state(self): """ Will reset state of each augmentor """ super(AugmentorList, self).reset_state() for a in self.augmentors: a.reset_state()
python
def reset_state(self): """ Will reset state of each augmentor """ super(AugmentorList, self).reset_state() for a in self.augmentors: a.reset_state()
[ "def", "reset_state", "(", "self", ")", ":", "super", "(", "AugmentorList", ",", "self", ")", ".", "reset_state", "(", ")", "for", "a", "in", "self", ".", "augmentors", ":", "a", ".", "reset_state", "(", ")" ]
Will reset state of each augmentor
[ "Will", "reset", "state", "of", "each", "augmentor" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/imgaug/base.py#L224-L228
27,277
tensorpack/tensorpack
tensorpack/utils/concurrency.py
ensure_proc_terminate
def ensure_proc_terminate(proc): """ Make sure processes terminate when main process exit. Args: proc (multiprocessing.Process or list) """ if isinstance(proc, list): for p in proc: ensure_proc_terminate(p) return def stop_proc_by_weak_ref(ref): proc = ref() if proc is None: return if not proc.is_alive(): return proc.terminate() proc.join() assert isinstance(proc, mp.Process) atexit.register(stop_proc_by_weak_ref, weakref.ref(proc))
python
def ensure_proc_terminate(proc): """ Make sure processes terminate when main process exit. Args: proc (multiprocessing.Process or list) """ if isinstance(proc, list): for p in proc: ensure_proc_terminate(p) return def stop_proc_by_weak_ref(ref): proc = ref() if proc is None: return if not proc.is_alive(): return proc.terminate() proc.join() assert isinstance(proc, mp.Process) atexit.register(stop_proc_by_weak_ref, weakref.ref(proc))
[ "def", "ensure_proc_terminate", "(", "proc", ")", ":", "if", "isinstance", "(", "proc", ",", "list", ")", ":", "for", "p", "in", "proc", ":", "ensure_proc_terminate", "(", "p", ")", "return", "def", "stop_proc_by_weak_ref", "(", "ref", ")", ":", "proc", "=", "ref", "(", ")", "if", "proc", "is", "None", ":", "return", "if", "not", "proc", ".", "is_alive", "(", ")", ":", "return", "proc", ".", "terminate", "(", ")", "proc", ".", "join", "(", ")", "assert", "isinstance", "(", "proc", ",", "mp", ".", "Process", ")", "atexit", ".", "register", "(", "stop_proc_by_weak_ref", ",", "weakref", ".", "ref", "(", "proc", ")", ")" ]
Make sure processes terminate when main process exit. Args: proc (multiprocessing.Process or list)
[ "Make", "sure", "processes", "terminate", "when", "main", "process", "exit", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L152-L174
27,278
tensorpack/tensorpack
tensorpack/utils/concurrency.py
enable_death_signal
def enable_death_signal(_warn=True): """ Set the "death signal" of the current process, so that the current process will be cleaned with guarantee in case the parent dies accidentally. """ if platform.system() != 'Linux': return try: import prctl # pip install python-prctl except ImportError: if _warn: log_once('"import prctl" failed! Install python-prctl so that processes can be cleaned with guarantee.', 'warn') return else: assert hasattr(prctl, 'set_pdeathsig'), \ "prctl.set_pdeathsig does not exist! Note that you need to install 'python-prctl' instead of 'prctl'." # is SIGHUP a good choice? prctl.set_pdeathsig(signal.SIGHUP)
python
def enable_death_signal(_warn=True): """ Set the "death signal" of the current process, so that the current process will be cleaned with guarantee in case the parent dies accidentally. """ if platform.system() != 'Linux': return try: import prctl # pip install python-prctl except ImportError: if _warn: log_once('"import prctl" failed! Install python-prctl so that processes can be cleaned with guarantee.', 'warn') return else: assert hasattr(prctl, 'set_pdeathsig'), \ "prctl.set_pdeathsig does not exist! Note that you need to install 'python-prctl' instead of 'prctl'." # is SIGHUP a good choice? prctl.set_pdeathsig(signal.SIGHUP)
[ "def", "enable_death_signal", "(", "_warn", "=", "True", ")", ":", "if", "platform", ".", "system", "(", ")", "!=", "'Linux'", ":", "return", "try", ":", "import", "prctl", "# pip install python-prctl", "except", "ImportError", ":", "if", "_warn", ":", "log_once", "(", "'\"import prctl\" failed! Install python-prctl so that processes can be cleaned with guarantee.'", ",", "'warn'", ")", "return", "else", ":", "assert", "hasattr", "(", "prctl", ",", "'set_pdeathsig'", ")", ",", "\"prctl.set_pdeathsig does not exist! Note that you need to install 'python-prctl' instead of 'prctl'.\"", "# is SIGHUP a good choice?", "prctl", ".", "set_pdeathsig", "(", "signal", ".", "SIGHUP", ")" ]
Set the "death signal" of the current process, so that the current process will be cleaned with guarantee in case the parent dies accidentally.
[ "Set", "the", "death", "signal", "of", "the", "current", "process", "so", "that", "the", "current", "process", "will", "be", "cleaned", "with", "guarantee", "in", "case", "the", "parent", "dies", "accidentally", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L177-L196
27,279
tensorpack/tensorpack
tensorpack/utils/concurrency.py
subproc_call
def subproc_call(cmd, timeout=None): """ Execute a command with timeout, and return STDOUT and STDERR Args: cmd(str): the command to execute. timeout(float): timeout in seconds. Returns: output(bytes), retcode(int). If timeout, retcode is -1. """ try: output = subprocess.check_output( cmd, stderr=subprocess.STDOUT, shell=True, timeout=timeout) return output, 0 except subprocess.TimeoutExpired as e: logger.warn("Command '{}' timeout!".format(cmd)) logger.warn(e.output.decode('utf-8')) return e.output, -1 except subprocess.CalledProcessError as e: logger.warn("Command '{}' failed, return code={}".format(cmd, e.returncode)) logger.warn(e.output.decode('utf-8')) return e.output, e.returncode except Exception: logger.warn("Command '{}' failed to run.".format(cmd)) return "", -2
python
def subproc_call(cmd, timeout=None): """ Execute a command with timeout, and return STDOUT and STDERR Args: cmd(str): the command to execute. timeout(float): timeout in seconds. Returns: output(bytes), retcode(int). If timeout, retcode is -1. """ try: output = subprocess.check_output( cmd, stderr=subprocess.STDOUT, shell=True, timeout=timeout) return output, 0 except subprocess.TimeoutExpired as e: logger.warn("Command '{}' timeout!".format(cmd)) logger.warn(e.output.decode('utf-8')) return e.output, -1 except subprocess.CalledProcessError as e: logger.warn("Command '{}' failed, return code={}".format(cmd, e.returncode)) logger.warn(e.output.decode('utf-8')) return e.output, e.returncode except Exception: logger.warn("Command '{}' failed to run.".format(cmd)) return "", -2
[ "def", "subproc_call", "(", "cmd", ",", "timeout", "=", "None", ")", ":", "try", ":", "output", "=", "subprocess", ".", "check_output", "(", "cmd", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "shell", "=", "True", ",", "timeout", "=", "timeout", ")", "return", "output", ",", "0", "except", "subprocess", ".", "TimeoutExpired", "as", "e", ":", "logger", ".", "warn", "(", "\"Command '{}' timeout!\"", ".", "format", "(", "cmd", ")", ")", "logger", ".", "warn", "(", "e", ".", "output", ".", "decode", "(", "'utf-8'", ")", ")", "return", "e", ".", "output", ",", "-", "1", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "logger", ".", "warn", "(", "\"Command '{}' failed, return code={}\"", ".", "format", "(", "cmd", ",", "e", ".", "returncode", ")", ")", "logger", ".", "warn", "(", "e", ".", "output", ".", "decode", "(", "'utf-8'", ")", ")", "return", "e", ".", "output", ",", "e", ".", "returncode", "except", "Exception", ":", "logger", ".", "warn", "(", "\"Command '{}' failed to run.\"", ".", "format", "(", "cmd", ")", ")", "return", "\"\"", ",", "-", "2" ]
Execute a command with timeout, and return STDOUT and STDERR Args: cmd(str): the command to execute. timeout(float): timeout in seconds. Returns: output(bytes), retcode(int). If timeout, retcode is -1.
[ "Execute", "a", "command", "with", "timeout", "and", "return", "STDOUT", "and", "STDERR" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L247-L273
27,280
tensorpack/tensorpack
tensorpack/utils/concurrency.py
StoppableThread.queue_put_stoppable
def queue_put_stoppable(self, q, obj): """ Put obj to queue, but will give up when the thread is stopped""" while not self.stopped(): try: q.put(obj, timeout=5) break except queue.Full: pass
python
def queue_put_stoppable(self, q, obj): """ Put obj to queue, but will give up when the thread is stopped""" while not self.stopped(): try: q.put(obj, timeout=5) break except queue.Full: pass
[ "def", "queue_put_stoppable", "(", "self", ",", "q", ",", "obj", ")", ":", "while", "not", "self", ".", "stopped", "(", ")", ":", "try", ":", "q", ".", "put", "(", "obj", ",", "timeout", "=", "5", ")", "break", "except", "queue", ".", "Full", ":", "pass" ]
Put obj to queue, but will give up when the thread is stopped
[ "Put", "obj", "to", "queue", "but", "will", "give", "up", "when", "the", "thread", "is", "stopped" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L59-L66
27,281
tensorpack/tensorpack
tensorpack/utils/concurrency.py
StoppableThread.queue_get_stoppable
def queue_get_stoppable(self, q): """ Take obj from queue, but will give up when the thread is stopped""" while not self.stopped(): try: return q.get(timeout=5) except queue.Empty: pass
python
def queue_get_stoppable(self, q): """ Take obj from queue, but will give up when the thread is stopped""" while not self.stopped(): try: return q.get(timeout=5) except queue.Empty: pass
[ "def", "queue_get_stoppable", "(", "self", ",", "q", ")", ":", "while", "not", "self", ".", "stopped", "(", ")", ":", "try", ":", "return", "q", ".", "get", "(", "timeout", "=", "5", ")", "except", "queue", ".", "Empty", ":", "pass" ]
Take obj from queue, but will give up when the thread is stopped
[ "Take", "obj", "from", "queue", "but", "will", "give", "up", "when", "the", "thread", "is", "stopped" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L68-L74
27,282
tensorpack/tensorpack
examples/basics/mnist-visualizations.py
visualize_conv_weights
def visualize_conv_weights(filters, name): """Visualize use weights in convolution filters. Args: filters: tensor containing the weights [H,W,Cin,Cout] name: label for tensorboard Returns: image of all weight """ with tf.name_scope('visualize_w_' + name): filters = tf.transpose(filters, (3, 2, 0, 1)) # [h, w, cin, cout] -> [cout, cin, h, w] filters = tf.unstack(filters) # --> cout * [cin, h, w] filters = tf.concat(filters, 1) # --> [cin, cout * h, w] filters = tf.unstack(filters) # --> cin * [cout * h, w] filters = tf.concat(filters, 1) # --> [cout * h, cin * w] filters = tf.expand_dims(filters, 0) filters = tf.expand_dims(filters, -1) tf.summary.image('visualize_w_' + name, filters)
python
def visualize_conv_weights(filters, name): """Visualize use weights in convolution filters. Args: filters: tensor containing the weights [H,W,Cin,Cout] name: label for tensorboard Returns: image of all weight """ with tf.name_scope('visualize_w_' + name): filters = tf.transpose(filters, (3, 2, 0, 1)) # [h, w, cin, cout] -> [cout, cin, h, w] filters = tf.unstack(filters) # --> cout * [cin, h, w] filters = tf.concat(filters, 1) # --> [cin, cout * h, w] filters = tf.unstack(filters) # --> cin * [cout * h, w] filters = tf.concat(filters, 1) # --> [cout * h, cin * w] filters = tf.expand_dims(filters, 0) filters = tf.expand_dims(filters, -1) tf.summary.image('visualize_w_' + name, filters)
[ "def", "visualize_conv_weights", "(", "filters", ",", "name", ")", ":", "with", "tf", ".", "name_scope", "(", "'visualize_w_'", "+", "name", ")", ":", "filters", "=", "tf", ".", "transpose", "(", "filters", ",", "(", "3", ",", "2", ",", "0", ",", "1", ")", ")", "# [h, w, cin, cout] -> [cout, cin, h, w]", "filters", "=", "tf", ".", "unstack", "(", "filters", ")", "# --> cout * [cin, h, w]", "filters", "=", "tf", ".", "concat", "(", "filters", ",", "1", ")", "# --> [cin, cout * h, w]", "filters", "=", "tf", ".", "unstack", "(", "filters", ")", "# --> cin * [cout * h, w]", "filters", "=", "tf", ".", "concat", "(", "filters", ",", "1", ")", "# --> [cout * h, cin * w]", "filters", "=", "tf", ".", "expand_dims", "(", "filters", ",", "0", ")", "filters", "=", "tf", ".", "expand_dims", "(", "filters", ",", "-", "1", ")", "tf", ".", "summary", ".", "image", "(", "'visualize_w_'", "+", "name", ",", "filters", ")" ]
Visualize use weights in convolution filters. Args: filters: tensor containing the weights [H,W,Cin,Cout] name: label for tensorboard Returns: image of all weight
[ "Visualize", "use", "weights", "in", "convolution", "filters", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/mnist-visualizations.py#L17-L36
27,283
tensorpack/tensorpack
examples/basics/mnist-visualizations.py
visualize_conv_activations
def visualize_conv_activations(activation, name): """Visualize activations for convolution layers. Remarks: This tries to place all activations into a square. Args: activation: tensor with the activation [B,H,W,C] name: label for tensorboard Returns: image of almost all activations """ import math with tf.name_scope('visualize_act_' + name): _, h, w, c = activation.get_shape().as_list() rows = [] c_per_row = int(math.sqrt(c)) for y in range(0, c - c_per_row, c_per_row): row = activation[:, :, :, y:y + c_per_row] # [?, H, W, 32] --> [?, H, W, 5] cols = tf.unstack(row, axis=3) # [?, H, W, 5] --> 5 * [?, H, W] row = tf.concat(cols, 1) rows.append(row) viz = tf.concat(rows, 2) tf.summary.image('visualize_act_' + name, tf.expand_dims(viz, -1))
python
def visualize_conv_activations(activation, name): """Visualize activations for convolution layers. Remarks: This tries to place all activations into a square. Args: activation: tensor with the activation [B,H,W,C] name: label for tensorboard Returns: image of almost all activations """ import math with tf.name_scope('visualize_act_' + name): _, h, w, c = activation.get_shape().as_list() rows = [] c_per_row = int(math.sqrt(c)) for y in range(0, c - c_per_row, c_per_row): row = activation[:, :, :, y:y + c_per_row] # [?, H, W, 32] --> [?, H, W, 5] cols = tf.unstack(row, axis=3) # [?, H, W, 5] --> 5 * [?, H, W] row = tf.concat(cols, 1) rows.append(row) viz = tf.concat(rows, 2) tf.summary.image('visualize_act_' + name, tf.expand_dims(viz, -1))
[ "def", "visualize_conv_activations", "(", "activation", ",", "name", ")", ":", "import", "math", "with", "tf", ".", "name_scope", "(", "'visualize_act_'", "+", "name", ")", ":", "_", ",", "h", ",", "w", ",", "c", "=", "activation", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "rows", "=", "[", "]", "c_per_row", "=", "int", "(", "math", ".", "sqrt", "(", "c", ")", ")", "for", "y", "in", "range", "(", "0", ",", "c", "-", "c_per_row", ",", "c_per_row", ")", ":", "row", "=", "activation", "[", ":", ",", ":", ",", ":", ",", "y", ":", "y", "+", "c_per_row", "]", "# [?, H, W, 32] --> [?, H, W, 5]", "cols", "=", "tf", ".", "unstack", "(", "row", ",", "axis", "=", "3", ")", "# [?, H, W, 5] --> 5 * [?, H, W]", "row", "=", "tf", ".", "concat", "(", "cols", ",", "1", ")", "rows", ".", "append", "(", "row", ")", "viz", "=", "tf", ".", "concat", "(", "rows", ",", "2", ")", "tf", ".", "summary", ".", "image", "(", "'visualize_act_'", "+", "name", ",", "tf", ".", "expand_dims", "(", "viz", ",", "-", "1", ")", ")" ]
Visualize activations for convolution layers. Remarks: This tries to place all activations into a square. Args: activation: tensor with the activation [B,H,W,C] name: label for tensorboard Returns: image of almost all activations
[ "Visualize", "activations", "for", "convolution", "layers", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/mnist-visualizations.py#L39-L64
27,284
tensorpack/tensorpack
examples/GAN/InfoGAN-mnist.py
shapeless_placeholder
def shapeless_placeholder(x, axis, name): """ Make the static shape of a tensor less specific. If you want to feed to a tensor, the shape of the feed value must match the tensor's static shape. This function creates a placeholder which defaults to x if not fed, but has a less specific static shape than x. See also `tensorflow#5680 <https://github.com/tensorflow/tensorflow/issues/5680>`_. Args: x: a tensor axis(int or list of ints): these axes of ``x.get_shape()`` will become None in the output. name(str): name of the output tensor Returns: a tensor equal to x, but shape information is partially cleared. """ shp = x.get_shape().as_list() if not isinstance(axis, list): axis = [axis] for a in axis: if shp[a] is None: raise ValueError("Axis {} of shape {} is already unknown!".format(a, shp)) shp[a] = None x = tf.placeholder_with_default(x, shape=shp, name=name) return x
python
def shapeless_placeholder(x, axis, name): """ Make the static shape of a tensor less specific. If you want to feed to a tensor, the shape of the feed value must match the tensor's static shape. This function creates a placeholder which defaults to x if not fed, but has a less specific static shape than x. See also `tensorflow#5680 <https://github.com/tensorflow/tensorflow/issues/5680>`_. Args: x: a tensor axis(int or list of ints): these axes of ``x.get_shape()`` will become None in the output. name(str): name of the output tensor Returns: a tensor equal to x, but shape information is partially cleared. """ shp = x.get_shape().as_list() if not isinstance(axis, list): axis = [axis] for a in axis: if shp[a] is None: raise ValueError("Axis {} of shape {} is already unknown!".format(a, shp)) shp[a] = None x = tf.placeholder_with_default(x, shape=shp, name=name) return x
[ "def", "shapeless_placeholder", "(", "x", ",", "axis", ",", "name", ")", ":", "shp", "=", "x", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "if", "not", "isinstance", "(", "axis", ",", "list", ")", ":", "axis", "=", "[", "axis", "]", "for", "a", "in", "axis", ":", "if", "shp", "[", "a", "]", "is", "None", ":", "raise", "ValueError", "(", "\"Axis {} of shape {} is already unknown!\"", ".", "format", "(", "a", ",", "shp", ")", ")", "shp", "[", "a", "]", "=", "None", "x", "=", "tf", ".", "placeholder_with_default", "(", "x", ",", "shape", "=", "shp", ",", "name", "=", "name", ")", "return", "x" ]
Make the static shape of a tensor less specific. If you want to feed to a tensor, the shape of the feed value must match the tensor's static shape. This function creates a placeholder which defaults to x if not fed, but has a less specific static shape than x. See also `tensorflow#5680 <https://github.com/tensorflow/tensorflow/issues/5680>`_. Args: x: a tensor axis(int or list of ints): these axes of ``x.get_shape()`` will become None in the output. name(str): name of the output tensor Returns: a tensor equal to x, but shape information is partially cleared.
[ "Make", "the", "static", "shape", "of", "a", "tensor", "less", "specific", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/InfoGAN-mnist.py#L40-L66
27,285
tensorpack/tensorpack
examples/GAN/InfoGAN-mnist.py
sample_prior
def sample_prior(batch_size): cat, _ = get_distributions(DIST_PRIOR_PARAM[:NUM_CLASS], DIST_PRIOR_PARAM[NUM_CLASS:]) sample_cat = tf.one_hot(cat.sample(batch_size), NUM_CLASS) """ OpenAI official code actually models the "uniform" latent code as a Gaussian distribution, but obtain the samples from a uniform distribution. """ sample_uni = tf.random_uniform([batch_size, NUM_UNIFORM], -1, 1) samples = tf.concat([sample_cat, sample_uni], axis=1) return samples
python
def sample_prior(batch_size): cat, _ = get_distributions(DIST_PRIOR_PARAM[:NUM_CLASS], DIST_PRIOR_PARAM[NUM_CLASS:]) sample_cat = tf.one_hot(cat.sample(batch_size), NUM_CLASS) """ OpenAI official code actually models the "uniform" latent code as a Gaussian distribution, but obtain the samples from a uniform distribution. """ sample_uni = tf.random_uniform([batch_size, NUM_UNIFORM], -1, 1) samples = tf.concat([sample_cat, sample_uni], axis=1) return samples
[ "def", "sample_prior", "(", "batch_size", ")", ":", "cat", ",", "_", "=", "get_distributions", "(", "DIST_PRIOR_PARAM", "[", ":", "NUM_CLASS", "]", ",", "DIST_PRIOR_PARAM", "[", "NUM_CLASS", ":", "]", ")", "sample_cat", "=", "tf", ".", "one_hot", "(", "cat", ".", "sample", "(", "batch_size", ")", ",", "NUM_CLASS", ")", "sample_uni", "=", "tf", ".", "random_uniform", "(", "[", "batch_size", ",", "NUM_UNIFORM", "]", ",", "-", "1", ",", "1", ")", "samples", "=", "tf", ".", "concat", "(", "[", "sample_cat", ",", "sample_uni", "]", ",", "axis", "=", "1", ")", "return", "samples" ]
OpenAI official code actually models the "uniform" latent code as a Gaussian distribution, but obtain the samples from a uniform distribution.
[ "OpenAI", "official", "code", "actually", "models", "the", "uniform", "latent", "code", "as", "a", "Gaussian", "distribution", "but", "obtain", "the", "samples", "from", "a", "uniform", "distribution", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/InfoGAN-mnist.py#L94-L104
27,286
tensorpack/tensorpack
examples/DynamicFilterNetwork/steering-filter.py
Model._parameter_net
def _parameter_net(self, theta, kernel_shape=9): """Estimate filters for convolution layers Args: theta: angle of filter kernel_shape: size of each filter Returns: learned filter as [B, k, k, 1] """ with argscope(FullyConnected, nl=tf.nn.leaky_relu): net = FullyConnected('fc1', theta, 64) net = FullyConnected('fc2', net, 128) pred_filter = FullyConnected('fc3', net, kernel_shape ** 2, nl=tf.identity) pred_filter = tf.reshape(pred_filter, [BATCH, kernel_shape, kernel_shape, 1], name="pred_filter") logger.info('Parameter net output: {}'.format(pred_filter.get_shape().as_list())) return pred_filter
python
def _parameter_net(self, theta, kernel_shape=9): """Estimate filters for convolution layers Args: theta: angle of filter kernel_shape: size of each filter Returns: learned filter as [B, k, k, 1] """ with argscope(FullyConnected, nl=tf.nn.leaky_relu): net = FullyConnected('fc1', theta, 64) net = FullyConnected('fc2', net, 128) pred_filter = FullyConnected('fc3', net, kernel_shape ** 2, nl=tf.identity) pred_filter = tf.reshape(pred_filter, [BATCH, kernel_shape, kernel_shape, 1], name="pred_filter") logger.info('Parameter net output: {}'.format(pred_filter.get_shape().as_list())) return pred_filter
[ "def", "_parameter_net", "(", "self", ",", "theta", ",", "kernel_shape", "=", "9", ")", ":", "with", "argscope", "(", "FullyConnected", ",", "nl", "=", "tf", ".", "nn", ".", "leaky_relu", ")", ":", "net", "=", "FullyConnected", "(", "'fc1'", ",", "theta", ",", "64", ")", "net", "=", "FullyConnected", "(", "'fc2'", ",", "net", ",", "128", ")", "pred_filter", "=", "FullyConnected", "(", "'fc3'", ",", "net", ",", "kernel_shape", "**", "2", ",", "nl", "=", "tf", ".", "identity", ")", "pred_filter", "=", "tf", ".", "reshape", "(", "pred_filter", ",", "[", "BATCH", ",", "kernel_shape", ",", "kernel_shape", ",", "1", "]", ",", "name", "=", "\"pred_filter\"", ")", "logger", ".", "info", "(", "'Parameter net output: {}'", ".", "format", "(", "pred_filter", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", ")", ")", "return", "pred_filter" ]
Estimate filters for convolution layers Args: theta: angle of filter kernel_shape: size of each filter Returns: learned filter as [B, k, k, 1]
[ "Estimate", "filters", "for", "convolution", "layers" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DynamicFilterNetwork/steering-filter.py#L103-L120
27,287
tensorpack/tensorpack
examples/DynamicFilterNetwork/steering-filter.py
ThetaImages.filter_with_theta
def filter_with_theta(image, theta, sigma=1., filter_size=9): """Implements a steerable Gaussian filter. This function can be used to evaluate the first directional derivative of an image, using the method outlined in W. T. Freeman and E. H. Adelson, "The Design and Use of Steerable Filters", IEEE PAMI, 1991. It evaluates the directional derivative of the input image I, oriented at THETA degrees with respect to the image rows. The standard deviation of the Gaussian kernel is given by SIGMA (assumed to be equal to unity by default). Args: image: any input image (only one channel) theta: orientation of filter [0, 2 * pi] sigma (float, optional): standard derivation of Gaussian filter_size (int, optional): filter support Returns: filtered image and the filter """ x = np.arange(-filter_size // 2 + 1, filter_size // 2 + 1) # 1D Gaussian g = np.array([np.exp(-(x**2) / (2 * sigma**2))]) # first-derivative of 1D Gaussian gp = np.array([-(x / sigma) * np.exp(-(x**2) / (2 * sigma**2))]) ix = convolve2d(image, -gp, mode='same', boundary='fill', fillvalue=0) ix = convolve2d(ix, g.T, mode='same', boundary='fill', fillvalue=0) iy = convolve2d(image, g, mode='same', boundary='fill', fillvalue=0) iy = convolve2d(iy, -gp.T, mode='same', boundary='fill', fillvalue=0) output = np.cos(theta) * ix + np.sin(theta) * iy # np.cos(theta) * np.matmul(g.T, gp) + np.sin(theta) * np.matmul(gp.T, g) gt_filter = np.matmul(g.T, gp) gt_filter = np.cos(theta) * gt_filter + np.sin(theta) * gt_filter.T return output, gt_filter
python
def filter_with_theta(image, theta, sigma=1., filter_size=9): """Implements a steerable Gaussian filter. This function can be used to evaluate the first directional derivative of an image, using the method outlined in W. T. Freeman and E. H. Adelson, "The Design and Use of Steerable Filters", IEEE PAMI, 1991. It evaluates the directional derivative of the input image I, oriented at THETA degrees with respect to the image rows. The standard deviation of the Gaussian kernel is given by SIGMA (assumed to be equal to unity by default). Args: image: any input image (only one channel) theta: orientation of filter [0, 2 * pi] sigma (float, optional): standard derivation of Gaussian filter_size (int, optional): filter support Returns: filtered image and the filter """ x = np.arange(-filter_size // 2 + 1, filter_size // 2 + 1) # 1D Gaussian g = np.array([np.exp(-(x**2) / (2 * sigma**2))]) # first-derivative of 1D Gaussian gp = np.array([-(x / sigma) * np.exp(-(x**2) / (2 * sigma**2))]) ix = convolve2d(image, -gp, mode='same', boundary='fill', fillvalue=0) ix = convolve2d(ix, g.T, mode='same', boundary='fill', fillvalue=0) iy = convolve2d(image, g, mode='same', boundary='fill', fillvalue=0) iy = convolve2d(iy, -gp.T, mode='same', boundary='fill', fillvalue=0) output = np.cos(theta) * ix + np.sin(theta) * iy # np.cos(theta) * np.matmul(g.T, gp) + np.sin(theta) * np.matmul(gp.T, g) gt_filter = np.matmul(g.T, gp) gt_filter = np.cos(theta) * gt_filter + np.sin(theta) * gt_filter.T return output, gt_filter
[ "def", "filter_with_theta", "(", "image", ",", "theta", ",", "sigma", "=", "1.", ",", "filter_size", "=", "9", ")", ":", "x", "=", "np", ".", "arange", "(", "-", "filter_size", "//", "2", "+", "1", ",", "filter_size", "//", "2", "+", "1", ")", "# 1D Gaussian", "g", "=", "np", ".", "array", "(", "[", "np", ".", "exp", "(", "-", "(", "x", "**", "2", ")", "/", "(", "2", "*", "sigma", "**", "2", ")", ")", "]", ")", "# first-derivative of 1D Gaussian", "gp", "=", "np", ".", "array", "(", "[", "-", "(", "x", "/", "sigma", ")", "*", "np", ".", "exp", "(", "-", "(", "x", "**", "2", ")", "/", "(", "2", "*", "sigma", "**", "2", ")", ")", "]", ")", "ix", "=", "convolve2d", "(", "image", ",", "-", "gp", ",", "mode", "=", "'same'", ",", "boundary", "=", "'fill'", ",", "fillvalue", "=", "0", ")", "ix", "=", "convolve2d", "(", "ix", ",", "g", ".", "T", ",", "mode", "=", "'same'", ",", "boundary", "=", "'fill'", ",", "fillvalue", "=", "0", ")", "iy", "=", "convolve2d", "(", "image", ",", "g", ",", "mode", "=", "'same'", ",", "boundary", "=", "'fill'", ",", "fillvalue", "=", "0", ")", "iy", "=", "convolve2d", "(", "iy", ",", "-", "gp", ".", "T", ",", "mode", "=", "'same'", ",", "boundary", "=", "'fill'", ",", "fillvalue", "=", "0", ")", "output", "=", "np", ".", "cos", "(", "theta", ")", "*", "ix", "+", "np", ".", "sin", "(", "theta", ")", "*", "iy", "# np.cos(theta) * np.matmul(g.T, gp) + np.sin(theta) * np.matmul(gp.T, g)", "gt_filter", "=", "np", ".", "matmul", "(", "g", ".", "T", ",", "gp", ")", "gt_filter", "=", "np", ".", "cos", "(", "theta", ")", "*", "gt_filter", "+", "np", ".", "sin", "(", "theta", ")", "*", "gt_filter", ".", "T", "return", "output", ",", "gt_filter" ]
Implements a steerable Gaussian filter. This function can be used to evaluate the first directional derivative of an image, using the method outlined in W. T. Freeman and E. H. Adelson, "The Design and Use of Steerable Filters", IEEE PAMI, 1991. It evaluates the directional derivative of the input image I, oriented at THETA degrees with respect to the image rows. The standard deviation of the Gaussian kernel is given by SIGMA (assumed to be equal to unity by default). Args: image: any input image (only one channel) theta: orientation of filter [0, 2 * pi] sigma (float, optional): standard derivation of Gaussian filter_size (int, optional): filter support Returns: filtered image and the filter
[ "Implements", "a", "steerable", "Gaussian", "filter", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DynamicFilterNetwork/steering-filter.py#L162-L204
27,288
tensorpack/tensorpack
examples/GAN/GAN.py
GANModelDesc.collect_variables
def collect_variables(self, g_scope='gen', d_scope='discrim'): """ Assign `self.g_vars` to the parameters under scope `g_scope`, and same with `self.d_vars`. """ self.g_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, g_scope) assert self.g_vars self.d_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, d_scope) assert self.d_vars
python
def collect_variables(self, g_scope='gen', d_scope='discrim'): """ Assign `self.g_vars` to the parameters under scope `g_scope`, and same with `self.d_vars`. """ self.g_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, g_scope) assert self.g_vars self.d_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, d_scope) assert self.d_vars
[ "def", "collect_variables", "(", "self", ",", "g_scope", "=", "'gen'", ",", "d_scope", "=", "'discrim'", ")", ":", "self", ".", "g_vars", "=", "tf", ".", "get_collection", "(", "tf", ".", "GraphKeys", ".", "TRAINABLE_VARIABLES", ",", "g_scope", ")", "assert", "self", ".", "g_vars", "self", ".", "d_vars", "=", "tf", ".", "get_collection", "(", "tf", ".", "GraphKeys", ".", "TRAINABLE_VARIABLES", ",", "d_scope", ")", "assert", "self", ".", "d_vars" ]
Assign `self.g_vars` to the parameters under scope `g_scope`, and same with `self.d_vars`.
[ "Assign", "self", ".", "g_vars", "to", "the", "parameters", "under", "scope", "g_scope", "and", "same", "with", "self", ".", "d_vars", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/GAN.py#L17-L25
27,289
tensorpack/tensorpack
examples/GAN/GAN.py
GANModelDesc.build_losses
def build_losses(self, logits_real, logits_fake): """ Build standard GAN loss and set `self.g_loss` and `self.d_loss`. D and G play two-player minimax game with value function V(G,D) min_G max _D V(D, G) = IE_{x ~ p_data} [log D(x)] + IE_{z ~ p_fake} [log (1 - D(G(z)))] Args: logits_real (tf.Tensor): discrim logits from real samples logits_fake (tf.Tensor): discrim logits from fake samples produced by generator """ with tf.name_scope("GAN_loss"): score_real = tf.sigmoid(logits_real) score_fake = tf.sigmoid(logits_fake) tf.summary.histogram('score-real', score_real) tf.summary.histogram('score-fake', score_fake) with tf.name_scope("discrim"): d_loss_pos = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits( logits=logits_real, labels=tf.ones_like(logits_real)), name='loss_real') d_loss_neg = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits( logits=logits_fake, labels=tf.zeros_like(logits_fake)), name='loss_fake') d_pos_acc = tf.reduce_mean(tf.cast(score_real > 0.5, tf.float32), name='accuracy_real') d_neg_acc = tf.reduce_mean(tf.cast(score_fake < 0.5, tf.float32), name='accuracy_fake') d_accuracy = tf.add(.5 * d_pos_acc, .5 * d_neg_acc, name='accuracy') self.d_loss = tf.add(.5 * d_loss_pos, .5 * d_loss_neg, name='loss') with tf.name_scope("gen"): self.g_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits( logits=logits_fake, labels=tf.ones_like(logits_fake)), name='loss') g_accuracy = tf.reduce_mean(tf.cast(score_fake > 0.5, tf.float32), name='accuracy') add_moving_summary(self.g_loss, self.d_loss, d_accuracy, g_accuracy)
python
def build_losses(self, logits_real, logits_fake): """ Build standard GAN loss and set `self.g_loss` and `self.d_loss`. D and G play two-player minimax game with value function V(G,D) min_G max _D V(D, G) = IE_{x ~ p_data} [log D(x)] + IE_{z ~ p_fake} [log (1 - D(G(z)))] Args: logits_real (tf.Tensor): discrim logits from real samples logits_fake (tf.Tensor): discrim logits from fake samples produced by generator """ with tf.name_scope("GAN_loss"): score_real = tf.sigmoid(logits_real) score_fake = tf.sigmoid(logits_fake) tf.summary.histogram('score-real', score_real) tf.summary.histogram('score-fake', score_fake) with tf.name_scope("discrim"): d_loss_pos = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits( logits=logits_real, labels=tf.ones_like(logits_real)), name='loss_real') d_loss_neg = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits( logits=logits_fake, labels=tf.zeros_like(logits_fake)), name='loss_fake') d_pos_acc = tf.reduce_mean(tf.cast(score_real > 0.5, tf.float32), name='accuracy_real') d_neg_acc = tf.reduce_mean(tf.cast(score_fake < 0.5, tf.float32), name='accuracy_fake') d_accuracy = tf.add(.5 * d_pos_acc, .5 * d_neg_acc, name='accuracy') self.d_loss = tf.add(.5 * d_loss_pos, .5 * d_loss_neg, name='loss') with tf.name_scope("gen"): self.g_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits( logits=logits_fake, labels=tf.ones_like(logits_fake)), name='loss') g_accuracy = tf.reduce_mean(tf.cast(score_fake > 0.5, tf.float32), name='accuracy') add_moving_summary(self.g_loss, self.d_loss, d_accuracy, g_accuracy)
[ "def", "build_losses", "(", "self", ",", "logits_real", ",", "logits_fake", ")", ":", "with", "tf", ".", "name_scope", "(", "\"GAN_loss\"", ")", ":", "score_real", "=", "tf", ".", "sigmoid", "(", "logits_real", ")", "score_fake", "=", "tf", ".", "sigmoid", "(", "logits_fake", ")", "tf", ".", "summary", ".", "histogram", "(", "'score-real'", ",", "score_real", ")", "tf", ".", "summary", ".", "histogram", "(", "'score-fake'", ",", "score_fake", ")", "with", "tf", ".", "name_scope", "(", "\"discrim\"", ")", ":", "d_loss_pos", "=", "tf", ".", "reduce_mean", "(", "tf", ".", "nn", ".", "sigmoid_cross_entropy_with_logits", "(", "logits", "=", "logits_real", ",", "labels", "=", "tf", ".", "ones_like", "(", "logits_real", ")", ")", ",", "name", "=", "'loss_real'", ")", "d_loss_neg", "=", "tf", ".", "reduce_mean", "(", "tf", ".", "nn", ".", "sigmoid_cross_entropy_with_logits", "(", "logits", "=", "logits_fake", ",", "labels", "=", "tf", ".", "zeros_like", "(", "logits_fake", ")", ")", ",", "name", "=", "'loss_fake'", ")", "d_pos_acc", "=", "tf", ".", "reduce_mean", "(", "tf", ".", "cast", "(", "score_real", ">", "0.5", ",", "tf", ".", "float32", ")", ",", "name", "=", "'accuracy_real'", ")", "d_neg_acc", "=", "tf", ".", "reduce_mean", "(", "tf", ".", "cast", "(", "score_fake", "<", "0.5", ",", "tf", ".", "float32", ")", ",", "name", "=", "'accuracy_fake'", ")", "d_accuracy", "=", "tf", ".", "add", "(", ".5", "*", "d_pos_acc", ",", ".5", "*", "d_neg_acc", ",", "name", "=", "'accuracy'", ")", "self", ".", "d_loss", "=", "tf", ".", "add", "(", ".5", "*", "d_loss_pos", ",", ".5", "*", "d_loss_neg", ",", "name", "=", "'loss'", ")", "with", "tf", ".", "name_scope", "(", "\"gen\"", ")", ":", "self", ".", "g_loss", "=", "tf", ".", "reduce_mean", "(", "tf", ".", "nn", ".", "sigmoid_cross_entropy_with_logits", "(", "logits", "=", "logits_fake", ",", "labels", "=", "tf", ".", "ones_like", "(", "logits_fake", ")", ")", ",", "name", "=", "'loss'", ")", "g_accuracy", "=", "tf", ".", "reduce_mean", "(", "tf", ".", "cast", "(", "score_fake", ">", "0.5", ",", "tf", ".", "float32", ")", ",", "name", "=", "'accuracy'", ")", "add_moving_summary", "(", "self", ".", "g_loss", ",", "self", ".", "d_loss", ",", "d_accuracy", ",", "g_accuracy", ")" ]
Build standard GAN loss and set `self.g_loss` and `self.d_loss`. D and G play two-player minimax game with value function V(G,D) min_G max _D V(D, G) = IE_{x ~ p_data} [log D(x)] + IE_{z ~ p_fake} [log (1 - D(G(z)))] Args: logits_real (tf.Tensor): discrim logits from real samples logits_fake (tf.Tensor): discrim logits from fake samples produced by generator
[ "Build", "standard", "GAN", "loss", "and", "set", "self", ".", "g_loss", "and", "self", ".", "d_loss", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/GAN.py#L27-L62
27,290
tensorpack/tensorpack
examples/GAN/GAN.py
GANTrainer._build_gan_trainer
def _build_gan_trainer(self, input, model): """ We need to set tower_func because it's a TowerTrainer, and only TowerTrainer supports automatic graph creation for inference during training. If we don't care about inference during training, using tower_func is not needed. Just calling model.build_graph directly is OK. """ # Build the graph self.tower_func = TowerFuncWrapper(model.build_graph, model.get_input_signature()) with TowerContext('', is_training=True): self.tower_func(*input.get_input_tensors()) opt = model.get_optimizer() # Define the training iteration # by default, run one d_min after one g_min with tf.name_scope('optimize'): g_min = opt.minimize(model.g_loss, var_list=model.g_vars, name='g_op') with tf.control_dependencies([g_min]): d_min = opt.minimize(model.d_loss, var_list=model.d_vars, name='d_op') self.train_op = d_min
python
def _build_gan_trainer(self, input, model): """ We need to set tower_func because it's a TowerTrainer, and only TowerTrainer supports automatic graph creation for inference during training. If we don't care about inference during training, using tower_func is not needed. Just calling model.build_graph directly is OK. """ # Build the graph self.tower_func = TowerFuncWrapper(model.build_graph, model.get_input_signature()) with TowerContext('', is_training=True): self.tower_func(*input.get_input_tensors()) opt = model.get_optimizer() # Define the training iteration # by default, run one d_min after one g_min with tf.name_scope('optimize'): g_min = opt.minimize(model.g_loss, var_list=model.g_vars, name='g_op') with tf.control_dependencies([g_min]): d_min = opt.minimize(model.d_loss, var_list=model.d_vars, name='d_op') self.train_op = d_min
[ "def", "_build_gan_trainer", "(", "self", ",", "input", ",", "model", ")", ":", "# Build the graph", "self", ".", "tower_func", "=", "TowerFuncWrapper", "(", "model", ".", "build_graph", ",", "model", ".", "get_input_signature", "(", ")", ")", "with", "TowerContext", "(", "''", ",", "is_training", "=", "True", ")", ":", "self", ".", "tower_func", "(", "*", "input", ".", "get_input_tensors", "(", ")", ")", "opt", "=", "model", ".", "get_optimizer", "(", ")", "# Define the training iteration", "# by default, run one d_min after one g_min", "with", "tf", ".", "name_scope", "(", "'optimize'", ")", ":", "g_min", "=", "opt", ".", "minimize", "(", "model", ".", "g_loss", ",", "var_list", "=", "model", ".", "g_vars", ",", "name", "=", "'g_op'", ")", "with", "tf", ".", "control_dependencies", "(", "[", "g_min", "]", ")", ":", "d_min", "=", "opt", ".", "minimize", "(", "model", ".", "d_loss", ",", "var_list", "=", "model", ".", "d_vars", ",", "name", "=", "'d_op'", ")", "self", ".", "train_op", "=", "d_min" ]
We need to set tower_func because it's a TowerTrainer, and only TowerTrainer supports automatic graph creation for inference during training. If we don't care about inference during training, using tower_func is not needed. Just calling model.build_graph directly is OK.
[ "We", "need", "to", "set", "tower_func", "because", "it", "s", "a", "TowerTrainer", "and", "only", "TowerTrainer", "supports", "automatic", "graph", "creation", "for", "inference", "during", "training", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/GAN.py#L99-L119
27,291
tensorpack/tensorpack
tensorpack/models/regularize.py
regularize_cost_from_collection
def regularize_cost_from_collection(name='regularize_cost'): """ Get the cost from the regularizers in ``tf.GraphKeys.REGULARIZATION_LOSSES``. If in replicated mode, will only regularize variables created within the current tower. Args: name (str): the name of the returned tensor Returns: tf.Tensor: a scalar, the total regularization cost. """ ctx = get_current_tower_context() if not ctx.is_training: # TODO Currently cannot build the wd_cost correctly at inference, # because ths vs_name used in inference can be '', therefore the # variable filter will fail return tf.constant(0, dtype=tf.float32, name='empty_' + name) # NOTE: this collection doesn't always grow with towers. # It only grows with actual variable creation, but not get_variable call. if ctx.has_own_variables: # be careful of the first tower (name='') losses = ctx.get_collection_in_tower(tfv1.GraphKeys.REGULARIZATION_LOSSES) else: losses = tfv1.get_collection(tfv1.GraphKeys.REGULARIZATION_LOSSES) if len(losses) > 0: logger.info("regularize_cost_from_collection() found {} regularizers " "in REGULARIZATION_LOSSES collection.".format(len(losses))) def maploss(l): assert l.dtype.is_floating, l if l.dtype != tf.float32: l = tf.cast(l, tf.float32) return l losses = [maploss(l) for l in losses] reg_loss = tf.add_n(losses, name=name) return reg_loss else: return tf.constant(0, dtype=tf.float32, name='empty_' + name)
python
def regularize_cost_from_collection(name='regularize_cost'): """ Get the cost from the regularizers in ``tf.GraphKeys.REGULARIZATION_LOSSES``. If in replicated mode, will only regularize variables created within the current tower. Args: name (str): the name of the returned tensor Returns: tf.Tensor: a scalar, the total regularization cost. """ ctx = get_current_tower_context() if not ctx.is_training: # TODO Currently cannot build the wd_cost correctly at inference, # because ths vs_name used in inference can be '', therefore the # variable filter will fail return tf.constant(0, dtype=tf.float32, name='empty_' + name) # NOTE: this collection doesn't always grow with towers. # It only grows with actual variable creation, but not get_variable call. if ctx.has_own_variables: # be careful of the first tower (name='') losses = ctx.get_collection_in_tower(tfv1.GraphKeys.REGULARIZATION_LOSSES) else: losses = tfv1.get_collection(tfv1.GraphKeys.REGULARIZATION_LOSSES) if len(losses) > 0: logger.info("regularize_cost_from_collection() found {} regularizers " "in REGULARIZATION_LOSSES collection.".format(len(losses))) def maploss(l): assert l.dtype.is_floating, l if l.dtype != tf.float32: l = tf.cast(l, tf.float32) return l losses = [maploss(l) for l in losses] reg_loss = tf.add_n(losses, name=name) return reg_loss else: return tf.constant(0, dtype=tf.float32, name='empty_' + name)
[ "def", "regularize_cost_from_collection", "(", "name", "=", "'regularize_cost'", ")", ":", "ctx", "=", "get_current_tower_context", "(", ")", "if", "not", "ctx", ".", "is_training", ":", "# TODO Currently cannot build the wd_cost correctly at inference,", "# because ths vs_name used in inference can be '', therefore the", "# variable filter will fail", "return", "tf", ".", "constant", "(", "0", ",", "dtype", "=", "tf", ".", "float32", ",", "name", "=", "'empty_'", "+", "name", ")", "# NOTE: this collection doesn't always grow with towers.", "# It only grows with actual variable creation, but not get_variable call.", "if", "ctx", ".", "has_own_variables", ":", "# be careful of the first tower (name='')", "losses", "=", "ctx", ".", "get_collection_in_tower", "(", "tfv1", ".", "GraphKeys", ".", "REGULARIZATION_LOSSES", ")", "else", ":", "losses", "=", "tfv1", ".", "get_collection", "(", "tfv1", ".", "GraphKeys", ".", "REGULARIZATION_LOSSES", ")", "if", "len", "(", "losses", ")", ">", "0", ":", "logger", ".", "info", "(", "\"regularize_cost_from_collection() found {} regularizers \"", "\"in REGULARIZATION_LOSSES collection.\"", ".", "format", "(", "len", "(", "losses", ")", ")", ")", "def", "maploss", "(", "l", ")", ":", "assert", "l", ".", "dtype", ".", "is_floating", ",", "l", "if", "l", ".", "dtype", "!=", "tf", ".", "float32", ":", "l", "=", "tf", ".", "cast", "(", "l", ",", "tf", ".", "float32", ")", "return", "l", "losses", "=", "[", "maploss", "(", "l", ")", "for", "l", "in", "losses", "]", "reg_loss", "=", "tf", ".", "add_n", "(", "losses", ",", "name", "=", "name", ")", "return", "reg_loss", "else", ":", "return", "tf", ".", "constant", "(", "0", ",", "dtype", "=", "tf", ".", "float32", ",", "name", "=", "'empty_'", "+", "name", ")" ]
Get the cost from the regularizers in ``tf.GraphKeys.REGULARIZATION_LOSSES``. If in replicated mode, will only regularize variables created within the current tower. Args: name (str): the name of the returned tensor Returns: tf.Tensor: a scalar, the total regularization cost.
[ "Get", "the", "cost", "from", "the", "regularizers", "in", "tf", ".", "GraphKeys", ".", "REGULARIZATION_LOSSES", ".", "If", "in", "replicated", "mode", "will", "only", "regularize", "variables", "created", "within", "the", "current", "tower", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/regularize.py#L103-L141
27,292
tensorpack/tensorpack
tensorpack/models/regularize.py
Dropout
def Dropout(x, *args, **kwargs): """ Same as `tf.layers.dropout`. However, for historical reasons, the first positional argument is interpreted as keep_prob rather than drop_prob. Explicitly use `rate=` keyword arguments to ensure things are consistent. """ if 'is_training' in kwargs: kwargs['training'] = kwargs.pop('is_training') if len(args) > 0: if args[0] != 0.5: logger.warn( "The first positional argument to tensorpack.Dropout is the probability to keep, rather than to drop. " "This is different from the rate argument in tf.layers.Dropout due to historical reasons. " "To mimic tf.layers.Dropout, explicitly use keyword argument 'rate' instead") rate = 1 - args[0] elif 'keep_prob' in kwargs: assert 'rate' not in kwargs, "Cannot set both keep_prob and rate!" rate = 1 - kwargs.pop('keep_prob') elif 'rate' in kwargs: rate = kwargs.pop('rate') else: rate = 0.5 if kwargs.get('training', None) is None: kwargs['training'] = get_current_tower_context().is_training if get_tf_version_tuple() <= (1, 12): return tf.layers.dropout(x, rate=rate, **kwargs) else: return tf.nn.dropout(x, rate=rate if kwargs['training'] else 0.)
python
def Dropout(x, *args, **kwargs): """ Same as `tf.layers.dropout`. However, for historical reasons, the first positional argument is interpreted as keep_prob rather than drop_prob. Explicitly use `rate=` keyword arguments to ensure things are consistent. """ if 'is_training' in kwargs: kwargs['training'] = kwargs.pop('is_training') if len(args) > 0: if args[0] != 0.5: logger.warn( "The first positional argument to tensorpack.Dropout is the probability to keep, rather than to drop. " "This is different from the rate argument in tf.layers.Dropout due to historical reasons. " "To mimic tf.layers.Dropout, explicitly use keyword argument 'rate' instead") rate = 1 - args[0] elif 'keep_prob' in kwargs: assert 'rate' not in kwargs, "Cannot set both keep_prob and rate!" rate = 1 - kwargs.pop('keep_prob') elif 'rate' in kwargs: rate = kwargs.pop('rate') else: rate = 0.5 if kwargs.get('training', None) is None: kwargs['training'] = get_current_tower_context().is_training if get_tf_version_tuple() <= (1, 12): return tf.layers.dropout(x, rate=rate, **kwargs) else: return tf.nn.dropout(x, rate=rate if kwargs['training'] else 0.)
[ "def", "Dropout", "(", "x", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'is_training'", "in", "kwargs", ":", "kwargs", "[", "'training'", "]", "=", "kwargs", ".", "pop", "(", "'is_training'", ")", "if", "len", "(", "args", ")", ">", "0", ":", "if", "args", "[", "0", "]", "!=", "0.5", ":", "logger", ".", "warn", "(", "\"The first positional argument to tensorpack.Dropout is the probability to keep, rather than to drop. \"", "\"This is different from the rate argument in tf.layers.Dropout due to historical reasons. \"", "\"To mimic tf.layers.Dropout, explicitly use keyword argument 'rate' instead\"", ")", "rate", "=", "1", "-", "args", "[", "0", "]", "elif", "'keep_prob'", "in", "kwargs", ":", "assert", "'rate'", "not", "in", "kwargs", ",", "\"Cannot set both keep_prob and rate!\"", "rate", "=", "1", "-", "kwargs", ".", "pop", "(", "'keep_prob'", ")", "elif", "'rate'", "in", "kwargs", ":", "rate", "=", "kwargs", ".", "pop", "(", "'rate'", ")", "else", ":", "rate", "=", "0.5", "if", "kwargs", ".", "get", "(", "'training'", ",", "None", ")", "is", "None", ":", "kwargs", "[", "'training'", "]", "=", "get_current_tower_context", "(", ")", ".", "is_training", "if", "get_tf_version_tuple", "(", ")", "<=", "(", "1", ",", "12", ")", ":", "return", "tf", ".", "layers", ".", "dropout", "(", "x", ",", "rate", "=", "rate", ",", "*", "*", "kwargs", ")", "else", ":", "return", "tf", ".", "nn", ".", "dropout", "(", "x", ",", "rate", "=", "rate", "if", "kwargs", "[", "'training'", "]", "else", "0.", ")" ]
Same as `tf.layers.dropout`. However, for historical reasons, the first positional argument is interpreted as keep_prob rather than drop_prob. Explicitly use `rate=` keyword arguments to ensure things are consistent.
[ "Same", "as", "tf", ".", "layers", ".", "dropout", ".", "However", "for", "historical", "reasons", "the", "first", "positional", "argument", "is", "interpreted", "as", "keep_prob", "rather", "than", "drop_prob", ".", "Explicitly", "use", "rate", "=", "keyword", "arguments", "to", "ensure", "things", "are", "consistent", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/regularize.py#L145-L175
27,293
tensorpack/tensorpack
tensorpack/dataflow/imgaug/paste.py
BackgroundFiller.fill
def fill(self, background_shape, img): """ Return a proper background image of background_shape, given img. Args: background_shape (tuple): a shape (h, w) img: an image Returns: a background image """ background_shape = tuple(background_shape) return self._fill(background_shape, img)
python
def fill(self, background_shape, img): """ Return a proper background image of background_shape, given img. Args: background_shape (tuple): a shape (h, w) img: an image Returns: a background image """ background_shape = tuple(background_shape) return self._fill(background_shape, img)
[ "def", "fill", "(", "self", ",", "background_shape", ",", "img", ")", ":", "background_shape", "=", "tuple", "(", "background_shape", ")", "return", "self", ".", "_fill", "(", "background_shape", ",", "img", ")" ]
Return a proper background image of background_shape, given img. Args: background_shape (tuple): a shape (h, w) img: an image Returns: a background image
[ "Return", "a", "proper", "background", "image", "of", "background_shape", "given", "img", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/imgaug/paste.py#L17-L28
27,294
tensorpack/tensorpack
tensorpack/models/linearwrap.py
LinearWrap.apply
def apply(self, func, *args, **kwargs): """ Apply a function on the wrapped tensor. Returns: LinearWrap: ``LinearWrap(func(self.tensor(), *args, **kwargs))``. """ ret = func(self._t, *args, **kwargs) return LinearWrap(ret)
python
def apply(self, func, *args, **kwargs): """ Apply a function on the wrapped tensor. Returns: LinearWrap: ``LinearWrap(func(self.tensor(), *args, **kwargs))``. """ ret = func(self._t, *args, **kwargs) return LinearWrap(ret)
[ "def", "apply", "(", "self", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "func", "(", "self", ".", "_t", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "LinearWrap", "(", "ret", ")" ]
Apply a function on the wrapped tensor. Returns: LinearWrap: ``LinearWrap(func(self.tensor(), *args, **kwargs))``.
[ "Apply", "a", "function", "on", "the", "wrapped", "tensor", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/linearwrap.py#L68-L76
27,295
tensorpack/tensorpack
tensorpack/models/linearwrap.py
LinearWrap.apply2
def apply2(self, func, *args, **kwargs): """ Apply a function on the wrapped tensor. The tensor will be the second argument of func. This is because many symbolic functions (such as tensorpack's layers) takes 'scope' as the first argument. Returns: LinearWrap: ``LinearWrap(func(args[0], self.tensor(), *args[1:], **kwargs))``. """ ret = func(args[0], self._t, *(args[1:]), **kwargs) return LinearWrap(ret)
python
def apply2(self, func, *args, **kwargs): """ Apply a function on the wrapped tensor. The tensor will be the second argument of func. This is because many symbolic functions (such as tensorpack's layers) takes 'scope' as the first argument. Returns: LinearWrap: ``LinearWrap(func(args[0], self.tensor(), *args[1:], **kwargs))``. """ ret = func(args[0], self._t, *(args[1:]), **kwargs) return LinearWrap(ret)
[ "def", "apply2", "(", "self", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "func", "(", "args", "[", "0", "]", ",", "self", ".", "_t", ",", "*", "(", "args", "[", "1", ":", "]", ")", ",", "*", "*", "kwargs", ")", "return", "LinearWrap", "(", "ret", ")" ]
Apply a function on the wrapped tensor. The tensor will be the second argument of func. This is because many symbolic functions (such as tensorpack's layers) takes 'scope' as the first argument. Returns: LinearWrap: ``LinearWrap(func(args[0], self.tensor(), *args[1:], **kwargs))``.
[ "Apply", "a", "function", "on", "the", "wrapped", "tensor", ".", "The", "tensor", "will", "be", "the", "second", "argument", "of", "func", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/linearwrap.py#L78-L90
27,296
tensorpack/tensorpack
tensorpack/callbacks/param.py
GraphVarParam.setup_graph
def setup_graph(self): """ Will setup the assign operator for that variable. """ all_vars = tfv1.global_variables() + tfv1.local_variables() for v in all_vars: if v.name == self.var_name: self.var = v break else: raise ValueError("{} is not a variable in the graph!".format(self.var_name))
python
def setup_graph(self): """ Will setup the assign operator for that variable. """ all_vars = tfv1.global_variables() + tfv1.local_variables() for v in all_vars: if v.name == self.var_name: self.var = v break else: raise ValueError("{} is not a variable in the graph!".format(self.var_name))
[ "def", "setup_graph", "(", "self", ")", ":", "all_vars", "=", "tfv1", ".", "global_variables", "(", ")", "+", "tfv1", ".", "local_variables", "(", ")", "for", "v", "in", "all_vars", ":", "if", "v", ".", "name", "==", "self", ".", "var_name", ":", "self", ".", "var", "=", "v", "break", "else", ":", "raise", "ValueError", "(", "\"{} is not a variable in the graph!\"", ".", "format", "(", "self", ".", "var_name", ")", ")" ]
Will setup the assign operator for that variable.
[ "Will", "setup", "the", "assign", "operator", "for", "that", "variable", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/param.py#L68-L76
27,297
tensorpack/tensorpack
tensorpack/callbacks/param.py
ScheduledHyperParamSetter._get_value_to_set_at_point
def _get_value_to_set_at_point(self, point): """ Using schedule, compute the value to be set at a given point. """ laste, lastv = None, None for e, v in self.schedule: if e == point: return v # meet the exact boundary, return directly if e > point: break laste, lastv = e, v if laste is None or laste == e: # hasn't reached the first scheduled point, or reached the end of all scheduled points return None if self.interp is None: # If no interpolation, nothing to do. return None v = (point - laste) * 1. / (e - laste) * (v - lastv) + lastv return v
python
def _get_value_to_set_at_point(self, point): """ Using schedule, compute the value to be set at a given point. """ laste, lastv = None, None for e, v in self.schedule: if e == point: return v # meet the exact boundary, return directly if e > point: break laste, lastv = e, v if laste is None or laste == e: # hasn't reached the first scheduled point, or reached the end of all scheduled points return None if self.interp is None: # If no interpolation, nothing to do. return None v = (point - laste) * 1. / (e - laste) * (v - lastv) + lastv return v
[ "def", "_get_value_to_set_at_point", "(", "self", ",", "point", ")", ":", "laste", ",", "lastv", "=", "None", ",", "None", "for", "e", ",", "v", "in", "self", ".", "schedule", ":", "if", "e", "==", "point", ":", "return", "v", "# meet the exact boundary, return directly", "if", "e", ">", "point", ":", "break", "laste", ",", "lastv", "=", "e", ",", "v", "if", "laste", "is", "None", "or", "laste", "==", "e", ":", "# hasn't reached the first scheduled point, or reached the end of all scheduled points", "return", "None", "if", "self", ".", "interp", "is", "None", ":", "# If no interpolation, nothing to do.", "return", "None", "v", "=", "(", "point", "-", "laste", ")", "*", "1.", "/", "(", "e", "-", "laste", ")", "*", "(", "v", "-", "lastv", ")", "+", "lastv", "return", "v" ]
Using schedule, compute the value to be set at a given point.
[ "Using", "schedule", "compute", "the", "value", "to", "be", "set", "at", "a", "given", "point", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/param.py#L283-L301
27,298
tensorpack/tensorpack
examples/ResNet/load-resnet.py
name_conversion
def name_conversion(caffe_layer_name): """ Convert a caffe parameter name to a tensorflow parameter name as defined in the above model """ # beginning & end mapping NAME_MAP = {'bn_conv1/beta': 'conv0/bn/beta', 'bn_conv1/gamma': 'conv0/bn/gamma', 'bn_conv1/mean/EMA': 'conv0/bn/mean/EMA', 'bn_conv1/variance/EMA': 'conv0/bn/variance/EMA', 'conv1/W': 'conv0/W', 'conv1/b': 'conv0/b', 'fc1000/W': 'linear/W', 'fc1000/b': 'linear/b'} if caffe_layer_name in NAME_MAP: return NAME_MAP[caffe_layer_name] s = re.search('([a-z]+)([0-9]+)([a-z]+)_', caffe_layer_name) if s is None: s = re.search('([a-z]+)([0-9]+)([a-z]+)([0-9]+)_', caffe_layer_name) layer_block_part1 = s.group(3) layer_block_part2 = s.group(4) assert layer_block_part1 in ['a', 'b'] layer_block = 0 if layer_block_part1 == 'a' else int(layer_block_part2) else: layer_block = ord(s.group(3)) - ord('a') layer_type = s.group(1) layer_group = s.group(2) layer_branch = int(re.search('_branch([0-9])', caffe_layer_name).group(1)) assert layer_branch in [1, 2] if layer_branch == 2: layer_id = re.search('_branch[0-9]([a-z])/', caffe_layer_name).group(1) layer_id = ord(layer_id) - ord('a') + 1 TYPE_DICT = {'res': 'conv{}', 'bn': 'conv{}/bn'} layer_type = TYPE_DICT[layer_type].format(layer_id if layer_branch == 2 else 'shortcut') tf_name = caffe_layer_name[caffe_layer_name.index('/'):] tf_name = 'group{}/block{}/{}'.format( int(layer_group) - 2, layer_block, layer_type) + tf_name return tf_name
python
def name_conversion(caffe_layer_name): """ Convert a caffe parameter name to a tensorflow parameter name as defined in the above model """ # beginning & end mapping NAME_MAP = {'bn_conv1/beta': 'conv0/bn/beta', 'bn_conv1/gamma': 'conv0/bn/gamma', 'bn_conv1/mean/EMA': 'conv0/bn/mean/EMA', 'bn_conv1/variance/EMA': 'conv0/bn/variance/EMA', 'conv1/W': 'conv0/W', 'conv1/b': 'conv0/b', 'fc1000/W': 'linear/W', 'fc1000/b': 'linear/b'} if caffe_layer_name in NAME_MAP: return NAME_MAP[caffe_layer_name] s = re.search('([a-z]+)([0-9]+)([a-z]+)_', caffe_layer_name) if s is None: s = re.search('([a-z]+)([0-9]+)([a-z]+)([0-9]+)_', caffe_layer_name) layer_block_part1 = s.group(3) layer_block_part2 = s.group(4) assert layer_block_part1 in ['a', 'b'] layer_block = 0 if layer_block_part1 == 'a' else int(layer_block_part2) else: layer_block = ord(s.group(3)) - ord('a') layer_type = s.group(1) layer_group = s.group(2) layer_branch = int(re.search('_branch([0-9])', caffe_layer_name).group(1)) assert layer_branch in [1, 2] if layer_branch == 2: layer_id = re.search('_branch[0-9]([a-z])/', caffe_layer_name).group(1) layer_id = ord(layer_id) - ord('a') + 1 TYPE_DICT = {'res': 'conv{}', 'bn': 'conv{}/bn'} layer_type = TYPE_DICT[layer_type].format(layer_id if layer_branch == 2 else 'shortcut') tf_name = caffe_layer_name[caffe_layer_name.index('/'):] tf_name = 'group{}/block{}/{}'.format( int(layer_group) - 2, layer_block, layer_type) + tf_name return tf_name
[ "def", "name_conversion", "(", "caffe_layer_name", ")", ":", "# beginning & end mapping", "NAME_MAP", "=", "{", "'bn_conv1/beta'", ":", "'conv0/bn/beta'", ",", "'bn_conv1/gamma'", ":", "'conv0/bn/gamma'", ",", "'bn_conv1/mean/EMA'", ":", "'conv0/bn/mean/EMA'", ",", "'bn_conv1/variance/EMA'", ":", "'conv0/bn/variance/EMA'", ",", "'conv1/W'", ":", "'conv0/W'", ",", "'conv1/b'", ":", "'conv0/b'", ",", "'fc1000/W'", ":", "'linear/W'", ",", "'fc1000/b'", ":", "'linear/b'", "}", "if", "caffe_layer_name", "in", "NAME_MAP", ":", "return", "NAME_MAP", "[", "caffe_layer_name", "]", "s", "=", "re", ".", "search", "(", "'([a-z]+)([0-9]+)([a-z]+)_'", ",", "caffe_layer_name", ")", "if", "s", "is", "None", ":", "s", "=", "re", ".", "search", "(", "'([a-z]+)([0-9]+)([a-z]+)([0-9]+)_'", ",", "caffe_layer_name", ")", "layer_block_part1", "=", "s", ".", "group", "(", "3", ")", "layer_block_part2", "=", "s", ".", "group", "(", "4", ")", "assert", "layer_block_part1", "in", "[", "'a'", ",", "'b'", "]", "layer_block", "=", "0", "if", "layer_block_part1", "==", "'a'", "else", "int", "(", "layer_block_part2", ")", "else", ":", "layer_block", "=", "ord", "(", "s", ".", "group", "(", "3", ")", ")", "-", "ord", "(", "'a'", ")", "layer_type", "=", "s", ".", "group", "(", "1", ")", "layer_group", "=", "s", ".", "group", "(", "2", ")", "layer_branch", "=", "int", "(", "re", ".", "search", "(", "'_branch([0-9])'", ",", "caffe_layer_name", ")", ".", "group", "(", "1", ")", ")", "assert", "layer_branch", "in", "[", "1", ",", "2", "]", "if", "layer_branch", "==", "2", ":", "layer_id", "=", "re", ".", "search", "(", "'_branch[0-9]([a-z])/'", ",", "caffe_layer_name", ")", ".", "group", "(", "1", ")", "layer_id", "=", "ord", "(", "layer_id", ")", "-", "ord", "(", "'a'", ")", "+", "1", "TYPE_DICT", "=", "{", "'res'", ":", "'conv{}'", ",", "'bn'", ":", "'conv{}/bn'", "}", "layer_type", "=", "TYPE_DICT", "[", "layer_type", "]", ".", "format", "(", "layer_id", "if", "layer_branch", "==", "2", "else", "'shortcut'", ")", "tf_name", "=", "caffe_layer_name", "[", "caffe_layer_name", ".", "index", "(", "'/'", ")", ":", "]", "tf_name", "=", "'group{}/block{}/{}'", ".", "format", "(", "int", "(", "layer_group", ")", "-", "2", ",", "layer_block", ",", "layer_type", ")", "+", "tf_name", "return", "tf_name" ]
Convert a caffe parameter name to a tensorflow parameter name as defined in the above model
[ "Convert", "a", "caffe", "parameter", "name", "to", "a", "tensorflow", "parameter", "name", "as", "defined", "in", "the", "above", "model" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/ResNet/load-resnet.py#L101-L138
27,299
tensorpack/tensorpack
tensorpack/tfutils/varreplace.py
remap_variables
def remap_variables(fn): """ Use fn to map the output of any variable getter. Args: fn (tf.Variable -> tf.Tensor) Returns: The current variable scope with a custom_getter that maps all the variables by fn. Example: .. code-block:: python with varreplace.remap_variables(lambda var: quantize(var)): x = FullyConnected('fc', x, 1000) # fc/{W,b} will be quantized """ def custom_getter(getter, *args, **kwargs): v = getter(*args, **kwargs) return fn(v) return custom_getter_scope(custom_getter)
python
def remap_variables(fn): """ Use fn to map the output of any variable getter. Args: fn (tf.Variable -> tf.Tensor) Returns: The current variable scope with a custom_getter that maps all the variables by fn. Example: .. code-block:: python with varreplace.remap_variables(lambda var: quantize(var)): x = FullyConnected('fc', x, 1000) # fc/{W,b} will be quantized """ def custom_getter(getter, *args, **kwargs): v = getter(*args, **kwargs) return fn(v) return custom_getter_scope(custom_getter)
[ "def", "remap_variables", "(", "fn", ")", ":", "def", "custom_getter", "(", "getter", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "v", "=", "getter", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "fn", "(", "v", ")", "return", "custom_getter_scope", "(", "custom_getter", ")" ]
Use fn to map the output of any variable getter. Args: fn (tf.Variable -> tf.Tensor) Returns: The current variable scope with a custom_getter that maps all the variables by fn. Example: .. code-block:: python with varreplace.remap_variables(lambda var: quantize(var)): x = FullyConnected('fc', x, 1000) # fc/{W,b} will be quantized
[ "Use", "fn", "to", "map", "the", "output", "of", "any", "variable", "getter", "." ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varreplace.py#L36-L56