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,100 | Microsoft/nni | tools/nni_cmd/config_utils.py | Experiments.remove_experiment | def remove_experiment(self, id):
'''remove an experiment by id'''
if id in self.experiments:
self.experiments.pop(id)
self.write_file() | python | def remove_experiment(self, id):
'''remove an experiment by id'''
if id in self.experiments:
self.experiments.pop(id)
self.write_file() | [
"def",
"remove_experiment",
"(",
"self",
",",
"id",
")",
":",
"if",
"id",
"in",
"self",
".",
"experiments",
":",
"self",
".",
"experiments",
".",
"pop",
"(",
"id",
")",
"self",
".",
"write_file",
"(",
")"
] | remove an experiment by id | [
"remove",
"an",
"experiment",
"by",
"id"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/config_utils.py#L95-L99 |
27,101 | Microsoft/nni | tools/nni_cmd/config_utils.py | Experiments.read_file | def read_file(self):
'''load config from local file'''
if os.path.exists(self.experiment_file):
try:
with open(self.experiment_file, 'r') as file:
return json.load(file)
except ValueError:
return {}
return {} | python | def read_file(self):
'''load config from local file'''
if os.path.exists(self.experiment_file):
try:
with open(self.experiment_file, 'r') as file:
return json.load(file)
except ValueError:
return {}
return {} | [
"def",
"read_file",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"experiment_file",
")",
":",
"try",
":",
"with",
"open",
"(",
"self",
".",
"experiment_file",
",",
"'r'",
")",
"as",
"file",
":",
"return",
"json",
... | load config from local file | [
"load",
"config",
"from",
"local",
"file"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/config_utils.py#L114-L122 |
27,102 | Microsoft/nni | examples/trials/weight_sharing/ga_squad/data.py | load_from_file | def load_from_file(path, fmt=None, is_training=True):
'''
load data from file
'''
if fmt is None:
fmt = 'squad'
assert fmt in ['squad', 'csv'], 'input format must be squad or csv'
qp_pairs = []
if fmt == 'squad':
with open(path) as data_file:
data = json.load(data... | python | def load_from_file(path, fmt=None, is_training=True):
'''
load data from file
'''
if fmt is None:
fmt = 'squad'
assert fmt in ['squad', 'csv'], 'input format must be squad or csv'
qp_pairs = []
if fmt == 'squad':
with open(path) as data_file:
data = json.load(data... | [
"def",
"load_from_file",
"(",
"path",
",",
"fmt",
"=",
"None",
",",
"is_training",
"=",
"True",
")",
":",
"if",
"fmt",
"is",
"None",
":",
"fmt",
"=",
"'squad'",
"assert",
"fmt",
"in",
"[",
"'squad'",
",",
"'csv'",
"]",
",",
"'input format must be squad o... | load data from file | [
"load",
"data",
"from",
"file"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/data.py#L67-L104 |
27,103 | Microsoft/nni | examples/trials/weight_sharing/ga_squad/data.py | tokenize | def tokenize(qp_pair, tokenizer=None, is_training=False):
'''
tokenize function.
'''
question_tokens = tokenizer.tokenize(qp_pair['question'])
passage_tokens = tokenizer.tokenize(qp_pair['passage'])
if is_training:
question_tokens = question_tokens[:300]
passage_tokens = passage_... | python | def tokenize(qp_pair, tokenizer=None, is_training=False):
'''
tokenize function.
'''
question_tokens = tokenizer.tokenize(qp_pair['question'])
passage_tokens = tokenizer.tokenize(qp_pair['passage'])
if is_training:
question_tokens = question_tokens[:300]
passage_tokens = passage_... | [
"def",
"tokenize",
"(",
"qp_pair",
",",
"tokenizer",
"=",
"None",
",",
"is_training",
"=",
"False",
")",
":",
"question_tokens",
"=",
"tokenizer",
".",
"tokenize",
"(",
"qp_pair",
"[",
"'question'",
"]",
")",
"passage_tokens",
"=",
"tokenizer",
".",
"tokeniz... | tokenize function. | [
"tokenize",
"function",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/data.py#L107-L121 |
27,104 | Microsoft/nni | examples/trials/weight_sharing/ga_squad/data.py | collect_vocab | def collect_vocab(qp_pairs):
'''
Build the vocab from corpus.
'''
vocab = set()
for qp_pair in qp_pairs:
for word in qp_pair['question_tokens']:
vocab.add(word['word'])
for word in qp_pair['passage_tokens']:
vocab.add(word['word'])
return vocab | python | def collect_vocab(qp_pairs):
'''
Build the vocab from corpus.
'''
vocab = set()
for qp_pair in qp_pairs:
for word in qp_pair['question_tokens']:
vocab.add(word['word'])
for word in qp_pair['passage_tokens']:
vocab.add(word['word'])
return vocab | [
"def",
"collect_vocab",
"(",
"qp_pairs",
")",
":",
"vocab",
"=",
"set",
"(",
")",
"for",
"qp_pair",
"in",
"qp_pairs",
":",
"for",
"word",
"in",
"qp_pair",
"[",
"'question_tokens'",
"]",
":",
"vocab",
".",
"add",
"(",
"word",
"[",
"'word'",
"]",
")",
... | Build the vocab from corpus. | [
"Build",
"the",
"vocab",
"from",
"corpus",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/data.py#L124-L134 |
27,105 | Microsoft/nni | examples/trials/weight_sharing/ga_squad/data.py | shuffle_step | def shuffle_step(entries, step):
'''
Shuffle the step
'''
answer = []
for i in range(0, len(entries), step):
sub = entries[i:i+step]
shuffle(sub)
answer += sub
return answer | python | def shuffle_step(entries, step):
'''
Shuffle the step
'''
answer = []
for i in range(0, len(entries), step):
sub = entries[i:i+step]
shuffle(sub)
answer += sub
return answer | [
"def",
"shuffle_step",
"(",
"entries",
",",
"step",
")",
":",
"answer",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"entries",
")",
",",
"step",
")",
":",
"sub",
"=",
"entries",
"[",
"i",
":",
"i",
"+",
"step",
"]",
"... | Shuffle the step | [
"Shuffle",
"the",
"step"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/data.py#L137-L146 |
27,106 | Microsoft/nni | examples/trials/weight_sharing/ga_squad/data.py | get_batches | def get_batches(qp_pairs, batch_size, need_sort=True):
'''
Get batches data and shuffle.
'''
if need_sort:
qp_pairs = sorted(qp_pairs, key=lambda qp: (
len(qp['passage_tokens']), qp['id']), reverse=True)
batches = [{'qp_pairs': qp_pairs[i:(i + batch_size)]}
for i i... | python | def get_batches(qp_pairs, batch_size, need_sort=True):
'''
Get batches data and shuffle.
'''
if need_sort:
qp_pairs = sorted(qp_pairs, key=lambda qp: (
len(qp['passage_tokens']), qp['id']), reverse=True)
batches = [{'qp_pairs': qp_pairs[i:(i + batch_size)]}
for i i... | [
"def",
"get_batches",
"(",
"qp_pairs",
",",
"batch_size",
",",
"need_sort",
"=",
"True",
")",
":",
"if",
"need_sort",
":",
"qp_pairs",
"=",
"sorted",
"(",
"qp_pairs",
",",
"key",
"=",
"lambda",
"qp",
":",
"(",
"len",
"(",
"qp",
"[",
"'passage_tokens'",
... | Get batches data and shuffle. | [
"Get",
"batches",
"data",
"and",
"shuffle",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/data.py#L149-L159 |
27,107 | Microsoft/nni | examples/trials/weight_sharing/ga_squad/data.py | get_char_input | def get_char_input(data, char_dict, max_char_length):
'''
Get char input.
'''
batch_size = len(data)
sequence_length = max(len(d) for d in data)
char_id = np.zeros((max_char_length, sequence_length,
batch_size), dtype=np.int32)
char_lengths = np.zeros((sequence_length... | python | def get_char_input(data, char_dict, max_char_length):
'''
Get char input.
'''
batch_size = len(data)
sequence_length = max(len(d) for d in data)
char_id = np.zeros((max_char_length, sequence_length,
batch_size), dtype=np.int32)
char_lengths = np.zeros((sequence_length... | [
"def",
"get_char_input",
"(",
"data",
",",
"char_dict",
",",
"max_char_length",
")",
":",
"batch_size",
"=",
"len",
"(",
"data",
")",
"sequence_length",
"=",
"max",
"(",
"len",
"(",
"d",
")",
"for",
"d",
"in",
"data",
")",
"char_id",
"=",
"np",
".",
... | Get char input. | [
"Get",
"char",
"input",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/data.py#L162-L179 |
27,108 | Microsoft/nni | examples/trials/weight_sharing/ga_squad/data.py | get_word_input | def get_word_input(data, word_dict, embed, embed_dim):
'''
Get word input.
'''
batch_size = len(data)
max_sequence_length = max(len(d) for d in data)
sequence_length = max_sequence_length
word_input = np.zeros((max_sequence_length, batch_size,
embed_dim), dtype=np.... | python | def get_word_input(data, word_dict, embed, embed_dim):
'''
Get word input.
'''
batch_size = len(data)
max_sequence_length = max(len(d) for d in data)
sequence_length = max_sequence_length
word_input = np.zeros((max_sequence_length, batch_size,
embed_dim), dtype=np.... | [
"def",
"get_word_input",
"(",
"data",
",",
"word_dict",
",",
"embed",
",",
"embed_dim",
")",
":",
"batch_size",
"=",
"len",
"(",
"data",
")",
"max_sequence_length",
"=",
"max",
"(",
"len",
"(",
"d",
")",
"for",
"d",
"in",
"data",
")",
"sequence_length",
... | Get word input. | [
"Get",
"word",
"input",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/data.py#L182-L208 |
27,109 | Microsoft/nni | examples/trials/weight_sharing/ga_squad/data.py | get_word_index | def get_word_index(tokens, char_index):
'''
Given word return word index.
'''
for (i, token) in enumerate(tokens):
if token['char_end'] == 0:
continue
if token['char_begin'] <= char_index and char_index <= token['char_end']:
return i
return 0 | python | def get_word_index(tokens, char_index):
'''
Given word return word index.
'''
for (i, token) in enumerate(tokens):
if token['char_end'] == 0:
continue
if token['char_begin'] <= char_index and char_index <= token['char_end']:
return i
return 0 | [
"def",
"get_word_index",
"(",
"tokens",
",",
"char_index",
")",
":",
"for",
"(",
"i",
",",
"token",
")",
"in",
"enumerate",
"(",
"tokens",
")",
":",
"if",
"token",
"[",
"'char_end'",
"]",
"==",
"0",
":",
"continue",
"if",
"token",
"[",
"'char_begin'",
... | Given word return word index. | [
"Given",
"word",
"return",
"word",
"index",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/data.py#L211-L220 |
27,110 | Microsoft/nni | examples/trials/weight_sharing/ga_squad/data.py | get_answer_begin_end | def get_answer_begin_end(data):
'''
Get answer's index of begin and end.
'''
begin = []
end = []
for qa_pair in data:
tokens = qa_pair['passage_tokens']
char_begin = qa_pair['answer_begin']
char_end = qa_pair['answer_end']
word_begin = get_word_index(tokens, char_... | python | def get_answer_begin_end(data):
'''
Get answer's index of begin and end.
'''
begin = []
end = []
for qa_pair in data:
tokens = qa_pair['passage_tokens']
char_begin = qa_pair['answer_begin']
char_end = qa_pair['answer_end']
word_begin = get_word_index(tokens, char_... | [
"def",
"get_answer_begin_end",
"(",
"data",
")",
":",
"begin",
"=",
"[",
"]",
"end",
"=",
"[",
"]",
"for",
"qa_pair",
"in",
"data",
":",
"tokens",
"=",
"qa_pair",
"[",
"'passage_tokens'",
"]",
"char_begin",
"=",
"qa_pair",
"[",
"'answer_begin'",
"]",
"ch... | Get answer's index of begin and end. | [
"Get",
"answer",
"s",
"index",
"of",
"begin",
"and",
"end",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/data.py#L223-L237 |
27,111 | Microsoft/nni | examples/trials/weight_sharing/ga_squad/data.py | get_buckets | def get_buckets(min_length, max_length, bucket_count):
'''
Get bucket by length.
'''
if bucket_count <= 0:
return [max_length]
unit_length = int((max_length - min_length) // (bucket_count))
buckets = [min_length + unit_length *
(i + 1) for i in range(0, bucket_count)]
... | python | def get_buckets(min_length, max_length, bucket_count):
'''
Get bucket by length.
'''
if bucket_count <= 0:
return [max_length]
unit_length = int((max_length - min_length) // (bucket_count))
buckets = [min_length + unit_length *
(i + 1) for i in range(0, bucket_count)]
... | [
"def",
"get_buckets",
"(",
"min_length",
",",
"max_length",
",",
"bucket_count",
")",
":",
"if",
"bucket_count",
"<=",
"0",
":",
"return",
"[",
"max_length",
"]",
"unit_length",
"=",
"int",
"(",
"(",
"max_length",
"-",
"min_length",
")",
"//",
"(",
"bucket... | Get bucket by length. | [
"Get",
"bucket",
"by",
"length",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/data.py#L249-L259 |
27,112 | Microsoft/nni | examples/trials/weight_sharing/ga_squad/data.py | WhitespaceTokenizer.tokenize | def tokenize(self, text):
'''
tokenize function in Tokenizer.
'''
start = -1
tokens = []
for i, character in enumerate(text):
if character == ' ' or character == '\t':
if start >= 0:
word = text[start:i]
... | python | def tokenize(self, text):
'''
tokenize function in Tokenizer.
'''
start = -1
tokens = []
for i, character in enumerate(text):
if character == ' ' or character == '\t':
if start >= 0:
word = text[start:i]
... | [
"def",
"tokenize",
"(",
"self",
",",
"text",
")",
":",
"start",
"=",
"-",
"1",
"tokens",
"=",
"[",
"]",
"for",
"i",
",",
"character",
"in",
"enumerate",
"(",
"text",
")",
":",
"if",
"character",
"==",
"' '",
"or",
"character",
"==",
"'\\t'",
":",
... | tokenize function in Tokenizer. | [
"tokenize",
"function",
"in",
"Tokenizer",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/data.py#L38-L64 |
27,113 | Microsoft/nni | examples/tuners/weight_sharing/ga_customer_tuner/customer_tuner.py | CustomerTuner.generate_new_id | def generate_new_id(self):
"""
generate new id and event hook for new Individual
"""
self.events.append(Event())
indiv_id = self.indiv_counter
self.indiv_counter += 1
return indiv_id | python | def generate_new_id(self):
"""
generate new id and event hook for new Individual
"""
self.events.append(Event())
indiv_id = self.indiv_counter
self.indiv_counter += 1
return indiv_id | [
"def",
"generate_new_id",
"(",
"self",
")",
":",
"self",
".",
"events",
".",
"append",
"(",
"Event",
"(",
")",
")",
"indiv_id",
"=",
"self",
".",
"indiv_counter",
"self",
".",
"indiv_counter",
"+=",
"1",
"return",
"indiv_id"
] | generate new id and event hook for new Individual | [
"generate",
"new",
"id",
"and",
"event",
"hook",
"for",
"new",
"Individual"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/tuners/weight_sharing/ga_customer_tuner/customer_tuner.py#L84-L91 |
27,114 | Microsoft/nni | examples/tuners/weight_sharing/ga_customer_tuner/customer_tuner.py | CustomerTuner.init_population | def init_population(self, population_size, graph_max_layer, graph_min_layer):
"""
initialize populations for evolution tuner
"""
population = []
graph = Graph(max_layer_num=graph_max_layer, min_layer_num=graph_min_layer,
inputs=[Layer(LayerType.input.value, ... | python | def init_population(self, population_size, graph_max_layer, graph_min_layer):
"""
initialize populations for evolution tuner
"""
population = []
graph = Graph(max_layer_num=graph_max_layer, min_layer_num=graph_min_layer,
inputs=[Layer(LayerType.input.value, ... | [
"def",
"init_population",
"(",
"self",
",",
"population_size",
",",
"graph_max_layer",
",",
"graph_min_layer",
")",
":",
"population",
"=",
"[",
"]",
"graph",
"=",
"Graph",
"(",
"max_layer_num",
"=",
"graph_max_layer",
",",
"min_layer_num",
"=",
"graph_min_layer",... | initialize populations for evolution tuner | [
"initialize",
"populations",
"for",
"evolution",
"tuner"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/tuners/weight_sharing/ga_customer_tuner/customer_tuner.py#L99-L113 |
27,115 | Microsoft/nni | tools/nni_trial_tool/hdfsClientUtility.py | copyHdfsDirectoryToLocal | def copyHdfsDirectoryToLocal(hdfsDirectory, localDirectory, hdfsClient):
'''Copy directory from HDFS to local'''
if not os.path.exists(localDirectory):
os.makedirs(localDirectory)
try:
listing = hdfsClient.list_status(hdfsDirectory)
except Exception as exception:
nni_log(LogType.... | python | def copyHdfsDirectoryToLocal(hdfsDirectory, localDirectory, hdfsClient):
'''Copy directory from HDFS to local'''
if not os.path.exists(localDirectory):
os.makedirs(localDirectory)
try:
listing = hdfsClient.list_status(hdfsDirectory)
except Exception as exception:
nni_log(LogType.... | [
"def",
"copyHdfsDirectoryToLocal",
"(",
"hdfsDirectory",
",",
"localDirectory",
",",
"hdfsClient",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"localDirectory",
")",
":",
"os",
".",
"makedirs",
"(",
"localDirectory",
")",
"try",
":",
"listi... | Copy directory from HDFS to local | [
"Copy",
"directory",
"from",
"HDFS",
"to",
"local"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_trial_tool/hdfsClientUtility.py#L26-L46 |
27,116 | Microsoft/nni | tools/nni_trial_tool/hdfsClientUtility.py | copyHdfsFileToLocal | def copyHdfsFileToLocal(hdfsFilePath, localFilePath, hdfsClient, override=True):
'''Copy file from HDFS to local'''
if not hdfsClient.exists(hdfsFilePath):
raise Exception('HDFS file {} does not exist!'.format(hdfsFilePath))
try:
file_status = hdfsClient.get_file_status(hdfsFilePath)
... | python | def copyHdfsFileToLocal(hdfsFilePath, localFilePath, hdfsClient, override=True):
'''Copy file from HDFS to local'''
if not hdfsClient.exists(hdfsFilePath):
raise Exception('HDFS file {} does not exist!'.format(hdfsFilePath))
try:
file_status = hdfsClient.get_file_status(hdfsFilePath)
... | [
"def",
"copyHdfsFileToLocal",
"(",
"hdfsFilePath",
",",
"localFilePath",
",",
"hdfsClient",
",",
"override",
"=",
"True",
")",
":",
"if",
"not",
"hdfsClient",
".",
"exists",
"(",
"hdfsFilePath",
")",
":",
"raise",
"Exception",
"(",
"'HDFS file {} does not exist!'"... | Copy file from HDFS to local | [
"Copy",
"file",
"from",
"HDFS",
"to",
"local"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_trial_tool/hdfsClientUtility.py#L48-L67 |
27,117 | Microsoft/nni | tools/nni_trial_tool/hdfsClientUtility.py | copyDirectoryToHdfs | def copyDirectoryToHdfs(localDirectory, hdfsDirectory, hdfsClient):
'''Copy directory from local to HDFS'''
if not os.path.exists(localDirectory):
raise Exception('Local Directory does not exist!')
hdfsClient.mkdirs(hdfsDirectory)
result = True
for file in os.listdir(localDirectory):
... | python | def copyDirectoryToHdfs(localDirectory, hdfsDirectory, hdfsClient):
'''Copy directory from local to HDFS'''
if not os.path.exists(localDirectory):
raise Exception('Local Directory does not exist!')
hdfsClient.mkdirs(hdfsDirectory)
result = True
for file in os.listdir(localDirectory):
... | [
"def",
"copyDirectoryToHdfs",
"(",
"localDirectory",
",",
"hdfsDirectory",
",",
"hdfsClient",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"localDirectory",
")",
":",
"raise",
"Exception",
"(",
"'Local Directory does not exist!'",
")",
"hdfsClient... | Copy directory from local to HDFS | [
"Copy",
"directory",
"from",
"local",
"to",
"HDFS"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_trial_tool/hdfsClientUtility.py#L69-L91 |
27,118 | Microsoft/nni | tools/nni_trial_tool/hdfsClientUtility.py | copyFileToHdfs | def copyFileToHdfs(localFilePath, hdfsFilePath, hdfsClient, override=True):
'''Copy a local file to HDFS directory'''
if not os.path.exists(localFilePath):
raise Exception('Local file Path does not exist!')
if os.path.isdir(localFilePath):
raise Exception('localFile should not a directory!')... | python | def copyFileToHdfs(localFilePath, hdfsFilePath, hdfsClient, override=True):
'''Copy a local file to HDFS directory'''
if not os.path.exists(localFilePath):
raise Exception('Local file Path does not exist!')
if os.path.isdir(localFilePath):
raise Exception('localFile should not a directory!')... | [
"def",
"copyFileToHdfs",
"(",
"localFilePath",
",",
"hdfsFilePath",
",",
"hdfsClient",
",",
"override",
"=",
"True",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"localFilePath",
")",
":",
"raise",
"Exception",
"(",
"'Local file Path does not ... | Copy a local file to HDFS directory | [
"Copy",
"a",
"local",
"file",
"to",
"HDFS",
"directory"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_trial_tool/hdfsClientUtility.py#L93-L109 |
27,119 | Microsoft/nni | examples/trials/sklearn/regression/main.py | load_data | def load_data():
'''Load dataset, use boston dataset'''
boston = load_boston()
X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=99, test_size=0.25)
#normalize data
ss_X = StandardScaler()
ss_y = StandardScaler()
X_train = ss_X.fit_transform(X_trai... | python | def load_data():
'''Load dataset, use boston dataset'''
boston = load_boston()
X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=99, test_size=0.25)
#normalize data
ss_X = StandardScaler()
ss_y = StandardScaler()
X_train = ss_X.fit_transform(X_trai... | [
"def",
"load_data",
"(",
")",
":",
"boston",
"=",
"load_boston",
"(",
")",
"X_train",
",",
"X_test",
",",
"y_train",
",",
"y_test",
"=",
"train_test_split",
"(",
"boston",
".",
"data",
",",
"boston",
".",
"target",
",",
"random_state",
"=",
"99",
",",
... | Load dataset, use boston dataset | [
"Load",
"dataset",
"use",
"boston",
"dataset"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/sklearn/regression/main.py#L33-L46 |
27,120 | Microsoft/nni | examples/trials/sklearn/regression/main.py | run | def run(X_train, X_test, y_train, y_test, PARAMS):
'''Train model and predict result'''
model.fit(X_train, y_train)
predict_y = model.predict(X_test)
score = r2_score(y_test, predict_y)
LOG.debug('r2 score: %s' % score)
nni.report_final_result(score) | python | def run(X_train, X_test, y_train, y_test, PARAMS):
'''Train model and predict result'''
model.fit(X_train, y_train)
predict_y = model.predict(X_test)
score = r2_score(y_test, predict_y)
LOG.debug('r2 score: %s' % score)
nni.report_final_result(score) | [
"def",
"run",
"(",
"X_train",
",",
"X_test",
",",
"y_train",
",",
"y_test",
",",
"PARAMS",
")",
":",
"model",
".",
"fit",
"(",
"X_train",
",",
"y_train",
")",
"predict_y",
"=",
"model",
".",
"predict",
"(",
"X_test",
")",
"score",
"=",
"r2_score",
"(... | Train model and predict result | [
"Train",
"model",
"and",
"predict",
"result"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/sklearn/regression/main.py#L80-L86 |
27,121 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/graph.py | NetworkDescriptor.to_json | def to_json(self):
''' NetworkDescriptor to json representation
'''
skip_list = []
for u, v, connection_type in self.skip_connections:
skip_list.append({"from": u, "to": v, "type": connection_type})
return {"node_list": self.layers, "skip_list": skip_list} | python | def to_json(self):
''' NetworkDescriptor to json representation
'''
skip_list = []
for u, v, connection_type in self.skip_connections:
skip_list.append({"from": u, "to": v, "type": connection_type})
return {"node_list": self.layers, "skip_list": skip_list} | [
"def",
"to_json",
"(",
"self",
")",
":",
"skip_list",
"=",
"[",
"]",
"for",
"u",
",",
"v",
",",
"connection_type",
"in",
"self",
".",
"skip_connections",
":",
"skip_list",
".",
"append",
"(",
"{",
"\"from\"",
":",
"u",
",",
"\"to\"",
":",
"v",
",",
... | NetworkDescriptor to json representation | [
"NetworkDescriptor",
"to",
"json",
"representation"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph.py#L89-L96 |
27,122 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/graph.py | Graph._add_edge | def _add_edge(self, layer, input_id, output_id):
"""Add a new layer to the graph. The nodes should be created in advance."""
if layer in self.layer_to_id:
layer_id = self.layer_to_id[layer]
if input_id not in self.layer_id_to_input_node_ids[layer_id]:
self.layer_... | python | def _add_edge(self, layer, input_id, output_id):
"""Add a new layer to the graph. The nodes should be created in advance."""
if layer in self.layer_to_id:
layer_id = self.layer_to_id[layer]
if input_id not in self.layer_id_to_input_node_ids[layer_id]:
self.layer_... | [
"def",
"_add_edge",
"(",
"self",
",",
"layer",
",",
"input_id",
",",
"output_id",
")",
":",
"if",
"layer",
"in",
"self",
".",
"layer_to_id",
":",
"layer_id",
"=",
"self",
".",
"layer_to_id",
"[",
"layer",
"]",
"if",
"input_id",
"not",
"in",
"self",
"."... | Add a new layer to the graph. The nodes should be created in advance. | [
"Add",
"a",
"new",
"layer",
"to",
"the",
"graph",
".",
"The",
"nodes",
"should",
"be",
"created",
"in",
"advance",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph.py#L214-L231 |
27,123 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/graph.py | Graph._redirect_edge | def _redirect_edge(self, u_id, v_id, new_v_id):
"""Redirect the layer to a new node.
Change the edge originally from `u_id` to `v_id` into an edge from `u_id` to `new_v_id`
while keeping all other property of the edge the same.
"""
layer_id = None
for index, edge_tuple in... | python | def _redirect_edge(self, u_id, v_id, new_v_id):
"""Redirect the layer to a new node.
Change the edge originally from `u_id` to `v_id` into an edge from `u_id` to `new_v_id`
while keeping all other property of the edge the same.
"""
layer_id = None
for index, edge_tuple in... | [
"def",
"_redirect_edge",
"(",
"self",
",",
"u_id",
",",
"v_id",
",",
"new_v_id",
")",
":",
"layer_id",
"=",
"None",
"for",
"index",
",",
"edge_tuple",
"in",
"enumerate",
"(",
"self",
".",
"adj_list",
"[",
"u_id",
"]",
")",
":",
"if",
"edge_tuple",
"[",... | Redirect the layer to a new node.
Change the edge originally from `u_id` to `v_id` into an edge from `u_id` to `new_v_id`
while keeping all other property of the edge the same. | [
"Redirect",
"the",
"layer",
"to",
"a",
"new",
"node",
".",
"Change",
"the",
"edge",
"originally",
"from",
"u_id",
"to",
"v_id",
"into",
"an",
"edge",
"from",
"u_id",
"to",
"new_v_id",
"while",
"keeping",
"all",
"other",
"property",
"of",
"the",
"edge",
"... | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph.py#L233-L255 |
27,124 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/graph.py | Graph._replace_layer | def _replace_layer(self, layer_id, new_layer):
"""Replace the layer with a new layer."""
old_layer = self.layer_list[layer_id]
new_layer.input = old_layer.input
new_layer.output = old_layer.output
new_layer.output.shape = new_layer.output_shape
self.layer_list[layer_id] =... | python | def _replace_layer(self, layer_id, new_layer):
"""Replace the layer with a new layer."""
old_layer = self.layer_list[layer_id]
new_layer.input = old_layer.input
new_layer.output = old_layer.output
new_layer.output.shape = new_layer.output_shape
self.layer_list[layer_id] =... | [
"def",
"_replace_layer",
"(",
"self",
",",
"layer_id",
",",
"new_layer",
")",
":",
"old_layer",
"=",
"self",
".",
"layer_list",
"[",
"layer_id",
"]",
"new_layer",
".",
"input",
"=",
"old_layer",
".",
"input",
"new_layer",
".",
"output",
"=",
"old_layer",
"... | Replace the layer with a new layer. | [
"Replace",
"the",
"layer",
"with",
"a",
"new",
"layer",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph.py#L257-L265 |
27,125 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/graph.py | Graph.topological_order | def topological_order(self):
"""Return the topological order of the node IDs from the input node to the output node."""
q = Queue()
in_degree = {}
for i in range(self.n_nodes):
in_degree[i] = 0
for u in range(self.n_nodes):
for v, _ in self.adj_list[u]:
... | python | def topological_order(self):
"""Return the topological order of the node IDs from the input node to the output node."""
q = Queue()
in_degree = {}
for i in range(self.n_nodes):
in_degree[i] = 0
for u in range(self.n_nodes):
for v, _ in self.adj_list[u]:
... | [
"def",
"topological_order",
"(",
"self",
")",
":",
"q",
"=",
"Queue",
"(",
")",
"in_degree",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"n_nodes",
")",
":",
"in_degree",
"[",
"i",
"]",
"=",
"0",
"for",
"u",
"in",
"range",
"(",
... | Return the topological order of the node IDs from the input node to the output node. | [
"Return",
"the",
"topological",
"order",
"of",
"the",
"node",
"IDs",
"from",
"the",
"input",
"node",
"to",
"the",
"output",
"node",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph.py#L268-L289 |
27,126 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/graph.py | Graph._get_pooling_layers | def _get_pooling_layers(self, start_node_id, end_node_id):
"""Given two node IDs, return all the pooling layers between them."""
layer_list = []
node_list = [start_node_id]
assert self._depth_first_search(end_node_id, layer_list, node_list)
ret = []
for layer_id in layer_... | python | def _get_pooling_layers(self, start_node_id, end_node_id):
"""Given two node IDs, return all the pooling layers between them."""
layer_list = []
node_list = [start_node_id]
assert self._depth_first_search(end_node_id, layer_list, node_list)
ret = []
for layer_id in layer_... | [
"def",
"_get_pooling_layers",
"(",
"self",
",",
"start_node_id",
",",
"end_node_id",
")",
":",
"layer_list",
"=",
"[",
"]",
"node_list",
"=",
"[",
"start_node_id",
"]",
"assert",
"self",
".",
"_depth_first_search",
"(",
"end_node_id",
",",
"layer_list",
",",
"... | Given two node IDs, return all the pooling layers between them. | [
"Given",
"two",
"node",
"IDs",
"return",
"all",
"the",
"pooling",
"layers",
"between",
"them",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph.py#L291-L303 |
27,127 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/graph.py | Graph._depth_first_search | def _depth_first_search(self, target_id, layer_id_list, node_list):
"""Search for all the layers and nodes down the path.
A recursive function to search all the layers and nodes between the node in the node_list
and the node with target_id."""
assert len(node_list) <= self.n_nodes
... | python | def _depth_first_search(self, target_id, layer_id_list, node_list):
"""Search for all the layers and nodes down the path.
A recursive function to search all the layers and nodes between the node in the node_list
and the node with target_id."""
assert len(node_list) <= self.n_nodes
... | [
"def",
"_depth_first_search",
"(",
"self",
",",
"target_id",
",",
"layer_id_list",
",",
"node_list",
")",
":",
"assert",
"len",
"(",
"node_list",
")",
"<=",
"self",
".",
"n_nodes",
"u",
"=",
"node_list",
"[",
"-",
"1",
"]",
"if",
"u",
"==",
"target_id",
... | Search for all the layers and nodes down the path.
A recursive function to search all the layers and nodes between the node in the node_list
and the node with target_id. | [
"Search",
"for",
"all",
"the",
"layers",
"and",
"nodes",
"down",
"the",
"path",
".",
"A",
"recursive",
"function",
"to",
"search",
"all",
"the",
"layers",
"and",
"nodes",
"between",
"the",
"node",
"in",
"the",
"node_list",
"and",
"the",
"node",
"with",
"... | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph.py#L305-L322 |
27,128 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/graph.py | Graph._insert_new_layers | def _insert_new_layers(self, new_layers, start_node_id, end_node_id):
"""Insert the new_layers after the node with start_node_id."""
new_node_id = self._add_node(deepcopy(self.node_list[end_node_id]))
temp_output_id = new_node_id
for layer in new_layers[:-1]:
temp_output_id =... | python | def _insert_new_layers(self, new_layers, start_node_id, end_node_id):
"""Insert the new_layers after the node with start_node_id."""
new_node_id = self._add_node(deepcopy(self.node_list[end_node_id]))
temp_output_id = new_node_id
for layer in new_layers[:-1]:
temp_output_id =... | [
"def",
"_insert_new_layers",
"(",
"self",
",",
"new_layers",
",",
"start_node_id",
",",
"end_node_id",
")",
":",
"new_node_id",
"=",
"self",
".",
"_add_node",
"(",
"deepcopy",
"(",
"self",
".",
"node_list",
"[",
"end_node_id",
"]",
")",
")",
"temp_output_id",
... | Insert the new_layers after the node with start_node_id. | [
"Insert",
"the",
"new_layers",
"after",
"the",
"node",
"with",
"start_node_id",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph.py#L438-L448 |
27,129 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/graph.py | Graph.extract_descriptor | def extract_descriptor(self):
"""Extract the the description of the Graph as an instance of NetworkDescriptor."""
main_chain = self.get_main_chain()
index_in_main_chain = {}
for index, u in enumerate(main_chain):
index_in_main_chain[u] = index
ret = NetworkDescriptor... | python | def extract_descriptor(self):
"""Extract the the description of the Graph as an instance of NetworkDescriptor."""
main_chain = self.get_main_chain()
index_in_main_chain = {}
for index, u in enumerate(main_chain):
index_in_main_chain[u] = index
ret = NetworkDescriptor... | [
"def",
"extract_descriptor",
"(",
"self",
")",
":",
"main_chain",
"=",
"self",
".",
"get_main_chain",
"(",
")",
"index_in_main_chain",
"=",
"{",
"}",
"for",
"index",
",",
"u",
"in",
"enumerate",
"(",
"main_chain",
")",
":",
"index_in_main_chain",
"[",
"u",
... | Extract the the description of the Graph as an instance of NetworkDescriptor. | [
"Extract",
"the",
"the",
"description",
"of",
"the",
"Graph",
"as",
"an",
"instance",
"of",
"NetworkDescriptor",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph.py#L580-L625 |
27,130 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/graph.py | Graph.clear_weights | def clear_weights(self):
''' clear weights of the graph
'''
self.weighted = False
for layer in self.layer_list:
layer.weights = None | python | def clear_weights(self):
''' clear weights of the graph
'''
self.weighted = False
for layer in self.layer_list:
layer.weights = None | [
"def",
"clear_weights",
"(",
"self",
")",
":",
"self",
".",
"weighted",
"=",
"False",
"for",
"layer",
"in",
"self",
".",
"layer_list",
":",
"layer",
".",
"weights",
"=",
"None"
] | clear weights of the graph | [
"clear",
"weights",
"of",
"the",
"graph"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph.py#L627-L632 |
27,131 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/graph.py | Graph.get_main_chain_layers | def get_main_chain_layers(self):
"""Return a list of layer IDs in the main chain."""
main_chain = self.get_main_chain()
ret = []
for u in main_chain:
for v, layer_id in self.adj_list[u]:
if v in main_chain and u in main_chain:
ret.append(la... | python | def get_main_chain_layers(self):
"""Return a list of layer IDs in the main chain."""
main_chain = self.get_main_chain()
ret = []
for u in main_chain:
for v, layer_id in self.adj_list[u]:
if v in main_chain and u in main_chain:
ret.append(la... | [
"def",
"get_main_chain_layers",
"(",
"self",
")",
":",
"main_chain",
"=",
"self",
".",
"get_main_chain",
"(",
")",
"ret",
"=",
"[",
"]",
"for",
"u",
"in",
"main_chain",
":",
"for",
"v",
",",
"layer_id",
"in",
"self",
".",
"adj_list",
"[",
"u",
"]",
"... | Return a list of layer IDs in the main chain. | [
"Return",
"a",
"list",
"of",
"layer",
"IDs",
"in",
"the",
"main",
"chain",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph.py#L680-L688 |
27,132 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/graph.py | Graph.get_main_chain | def get_main_chain(self):
"""Returns the main chain node ID list."""
pre_node = {}
distance = {}
for i in range(self.n_nodes):
distance[i] = 0
pre_node[i] = i
for i in range(self.n_nodes - 1):
for u in range(self.n_nodes):
for v... | python | def get_main_chain(self):
"""Returns the main chain node ID list."""
pre_node = {}
distance = {}
for i in range(self.n_nodes):
distance[i] = 0
pre_node[i] = i
for i in range(self.n_nodes - 1):
for u in range(self.n_nodes):
for v... | [
"def",
"get_main_chain",
"(",
"self",
")",
":",
"pre_node",
"=",
"{",
"}",
"distance",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"n_nodes",
")",
":",
"distance",
"[",
"i",
"]",
"=",
"0",
"pre_node",
"[",
"i",
"]",
"=",
"i",
"f... | Returns the main chain node ID list. | [
"Returns",
"the",
"main",
"chain",
"node",
"ID",
"list",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph.py#L723-L748 |
27,133 | Microsoft/nni | src/sdk/pynni/nni/msg_dispatcher_base.py | MsgDispatcherBase.run | def run(self):
"""Run the tuner.
This function will never return unless raise.
"""
_logger.info('Start dispatcher')
if dispatcher_env_vars.NNI_MODE == 'resume':
self.load_checkpoint()
while True:
command, data = receive()
if data:
... | python | def run(self):
"""Run the tuner.
This function will never return unless raise.
"""
_logger.info('Start dispatcher')
if dispatcher_env_vars.NNI_MODE == 'resume':
self.load_checkpoint()
while True:
command, data = receive()
if data:
... | [
"def",
"run",
"(",
"self",
")",
":",
"_logger",
".",
"info",
"(",
"'Start dispatcher'",
")",
"if",
"dispatcher_env_vars",
".",
"NNI_MODE",
"==",
"'resume'",
":",
"self",
".",
"load_checkpoint",
"(",
")",
"while",
"True",
":",
"command",
",",
"data",
"=",
... | Run the tuner.
This function will never return unless raise. | [
"Run",
"the",
"tuner",
".",
"This",
"function",
"will",
"never",
"return",
"unless",
"raise",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/msg_dispatcher_base.py#L57-L92 |
27,134 | Microsoft/nni | src/sdk/pynni/nni/msg_dispatcher_base.py | MsgDispatcherBase.command_queue_worker | def command_queue_worker(self, command_queue):
"""Process commands in command queues.
"""
while True:
try:
# set timeout to ensure self.stopping is checked periodically
command, data = command_queue.get(timeout=3)
try:
... | python | def command_queue_worker(self, command_queue):
"""Process commands in command queues.
"""
while True:
try:
# set timeout to ensure self.stopping is checked periodically
command, data = command_queue.get(timeout=3)
try:
... | [
"def",
"command_queue_worker",
"(",
"self",
",",
"command_queue",
")",
":",
"while",
"True",
":",
"try",
":",
"# set timeout to ensure self.stopping is checked periodically",
"command",
",",
"data",
"=",
"command_queue",
".",
"get",
"(",
"timeout",
"=",
"3",
")",
... | Process commands in command queues. | [
"Process",
"commands",
"in",
"command",
"queues",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/msg_dispatcher_base.py#L94-L110 |
27,135 | Microsoft/nni | src/sdk/pynni/nni/msg_dispatcher_base.py | MsgDispatcherBase.enqueue_command | def enqueue_command(self, command, data):
"""Enqueue command into command queues
"""
if command == CommandType.TrialEnd or (command == CommandType.ReportMetricData and data['type'] == 'PERIODICAL'):
self.assessor_command_queue.put((command, data))
else:
self.defau... | python | def enqueue_command(self, command, data):
"""Enqueue command into command queues
"""
if command == CommandType.TrialEnd or (command == CommandType.ReportMetricData and data['type'] == 'PERIODICAL'):
self.assessor_command_queue.put((command, data))
else:
self.defau... | [
"def",
"enqueue_command",
"(",
"self",
",",
"command",
",",
"data",
")",
":",
"if",
"command",
"==",
"CommandType",
".",
"TrialEnd",
"or",
"(",
"command",
"==",
"CommandType",
".",
"ReportMetricData",
"and",
"data",
"[",
"'type'",
"]",
"==",
"'PERIODICAL'",
... | Enqueue command into command queues | [
"Enqueue",
"command",
"into",
"command",
"queues"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/msg_dispatcher_base.py#L112-L126 |
27,136 | Microsoft/nni | src/sdk/pynni/nni/msg_dispatcher_base.py | MsgDispatcherBase.process_command_thread | def process_command_thread(self, request):
"""Worker thread to process a command.
"""
command, data = request
if multi_thread_enabled():
try:
self.process_command(command, data)
except Exception as e:
_logger.exception(str(e))
... | python | def process_command_thread(self, request):
"""Worker thread to process a command.
"""
command, data = request
if multi_thread_enabled():
try:
self.process_command(command, data)
except Exception as e:
_logger.exception(str(e))
... | [
"def",
"process_command_thread",
"(",
"self",
",",
"request",
")",
":",
"command",
",",
"data",
"=",
"request",
"if",
"multi_thread_enabled",
"(",
")",
":",
"try",
":",
"self",
".",
"process_command",
"(",
"command",
",",
"data",
")",
"except",
"Exception",
... | Worker thread to process a command. | [
"Worker",
"thread",
"to",
"process",
"a",
"command",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/msg_dispatcher_base.py#L128-L139 |
27,137 | Microsoft/nni | src/sdk/pynni/nni/metis_tuner/lib_data.py | match_val_type | def match_val_type(vals, vals_bounds, vals_types):
'''
Update values in the array, to match their corresponding type
'''
vals_new = []
for i, _ in enumerate(vals_types):
if vals_types[i] == "discrete_int":
# Find the closest integer in the array, vals_bounds
vals_new... | python | def match_val_type(vals, vals_bounds, vals_types):
'''
Update values in the array, to match their corresponding type
'''
vals_new = []
for i, _ in enumerate(vals_types):
if vals_types[i] == "discrete_int":
# Find the closest integer in the array, vals_bounds
vals_new... | [
"def",
"match_val_type",
"(",
"vals",
",",
"vals_bounds",
",",
"vals_types",
")",
":",
"vals_new",
"=",
"[",
"]",
"for",
"i",
",",
"_",
"in",
"enumerate",
"(",
"vals_types",
")",
":",
"if",
"vals_types",
"[",
"i",
"]",
"==",
"\"discrete_int\"",
":",
"#... | Update values in the array, to match their corresponding type | [
"Update",
"values",
"in",
"the",
"array",
"to",
"match",
"their",
"corresponding",
"type"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/lib_data.py#L25-L44 |
27,138 | Microsoft/nni | src/sdk/pynni/nni/metis_tuner/lib_data.py | rand | def rand(x_bounds, x_types):
'''
Random generate variable value within their bounds
'''
outputs = []
for i, _ in enumerate(x_bounds):
if x_types[i] == "discrete_int":
temp = x_bounds[i][random.randint(0, len(x_bounds[i]) - 1)]
outputs.append(temp)
elif x_type... | python | def rand(x_bounds, x_types):
'''
Random generate variable value within their bounds
'''
outputs = []
for i, _ in enumerate(x_bounds):
if x_types[i] == "discrete_int":
temp = x_bounds[i][random.randint(0, len(x_bounds[i]) - 1)]
outputs.append(temp)
elif x_type... | [
"def",
"rand",
"(",
"x_bounds",
",",
"x_types",
")",
":",
"outputs",
"=",
"[",
"]",
"for",
"i",
",",
"_",
"in",
"enumerate",
"(",
"x_bounds",
")",
":",
"if",
"x_types",
"[",
"i",
"]",
"==",
"\"discrete_int\"",
":",
"temp",
"=",
"x_bounds",
"[",
"i"... | Random generate variable value within their bounds | [
"Random",
"generate",
"variable",
"value",
"within",
"their",
"bounds"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/lib_data.py#L47-L66 |
27,139 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/graph_transformer.py | to_skip_connection_graph | def to_skip_connection_graph(graph):
''' skip connection graph
'''
# The last conv layer cannot be widen since wider operator cannot be done over the two sides of flatten.
weighted_layer_ids = graph.skip_connection_layer_ids()
valid_connection = []
for skip_type in sorted([NetworkDescriptor.ADD_... | python | def to_skip_connection_graph(graph):
''' skip connection graph
'''
# The last conv layer cannot be widen since wider operator cannot be done over the two sides of flatten.
weighted_layer_ids = graph.skip_connection_layer_ids()
valid_connection = []
for skip_type in sorted([NetworkDescriptor.ADD_... | [
"def",
"to_skip_connection_graph",
"(",
"graph",
")",
":",
"# The last conv layer cannot be widen since wider operator cannot be done over the two sides of flatten.",
"weighted_layer_ids",
"=",
"graph",
".",
"skip_connection_layer_ids",
"(",
")",
"valid_connection",
"=",
"[",
"]",
... | skip connection graph | [
"skip",
"connection",
"graph"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph_transformer.py#L58-L78 |
27,140 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/graph_transformer.py | create_new_layer | def create_new_layer(layer, n_dim):
''' create new layer for the graph
'''
input_shape = layer.output.shape
dense_deeper_classes = [StubDense, get_dropout_class(n_dim), StubReLU]
conv_deeper_classes = [get_conv_class(n_dim), get_batch_norm_class(n_dim), StubReLU]
if is_layer(layer, "ReLU"):
... | python | def create_new_layer(layer, n_dim):
''' create new layer for the graph
'''
input_shape = layer.output.shape
dense_deeper_classes = [StubDense, get_dropout_class(n_dim), StubReLU]
conv_deeper_classes = [get_conv_class(n_dim), get_batch_norm_class(n_dim), StubReLU]
if is_layer(layer, "ReLU"):
... | [
"def",
"create_new_layer",
"(",
"layer",
",",
"n_dim",
")",
":",
"input_shape",
"=",
"layer",
".",
"output",
".",
"shape",
"dense_deeper_classes",
"=",
"[",
"StubDense",
",",
"get_dropout_class",
"(",
"n_dim",
")",
",",
"StubReLU",
"]",
"conv_deeper_classes",
... | create new layer for the graph | [
"create",
"new",
"layer",
"for",
"the",
"graph"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph_transformer.py#L81-L124 |
27,141 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/graph_transformer.py | legal_graph | def legal_graph(graph):
'''judge if a graph is legal or not.
'''
descriptor = graph.extract_descriptor()
skips = descriptor.skip_connections
if len(skips) != len(set(skips)):
return False
return True | python | def legal_graph(graph):
'''judge if a graph is legal or not.
'''
descriptor = graph.extract_descriptor()
skips = descriptor.skip_connections
if len(skips) != len(set(skips)):
return False
return True | [
"def",
"legal_graph",
"(",
"graph",
")",
":",
"descriptor",
"=",
"graph",
".",
"extract_descriptor",
"(",
")",
"skips",
"=",
"descriptor",
".",
"skip_connections",
"if",
"len",
"(",
"skips",
")",
"!=",
"len",
"(",
"set",
"(",
"skips",
")",
")",
":",
"r... | judge if a graph is legal or not. | [
"judge",
"if",
"a",
"graph",
"is",
"legal",
"or",
"not",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph_transformer.py#L144-L152 |
27,142 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/graph_transformer.py | transform | def transform(graph):
'''core transform function for graph.
'''
graphs = []
for _ in range(Constant.N_NEIGHBOURS * 2):
random_num = randrange(3)
temp_graph = None
if random_num == 0:
temp_graph = to_deeper_graph(deepcopy(graph))
elif random_num == 1:
... | python | def transform(graph):
'''core transform function for graph.
'''
graphs = []
for _ in range(Constant.N_NEIGHBOURS * 2):
random_num = randrange(3)
temp_graph = None
if random_num == 0:
temp_graph = to_deeper_graph(deepcopy(graph))
elif random_num == 1:
... | [
"def",
"transform",
"(",
"graph",
")",
":",
"graphs",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"Constant",
".",
"N_NEIGHBOURS",
"*",
"2",
")",
":",
"random_num",
"=",
"randrange",
"(",
"3",
")",
"temp_graph",
"=",
"None",
"if",
"random_num",
"=... | core transform function for graph. | [
"core",
"transform",
"function",
"for",
"graph",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph_transformer.py#L155-L176 |
27,143 | Microsoft/nni | src/sdk/pynni/nni/metis_tuner/Regression_GP/Prediction.py | predict | def predict(parameters_value, regressor_gp):
'''
Predict by Gaussian Process Model
'''
parameters_value = numpy.array(parameters_value).reshape(-1, len(parameters_value))
mu, sigma = regressor_gp.predict(parameters_value, return_std=True)
return mu[0], sigma[0] | python | def predict(parameters_value, regressor_gp):
'''
Predict by Gaussian Process Model
'''
parameters_value = numpy.array(parameters_value).reshape(-1, len(parameters_value))
mu, sigma = regressor_gp.predict(parameters_value, return_std=True)
return mu[0], sigma[0] | [
"def",
"predict",
"(",
"parameters_value",
",",
"regressor_gp",
")",
":",
"parameters_value",
"=",
"numpy",
".",
"array",
"(",
"parameters_value",
")",
".",
"reshape",
"(",
"-",
"1",
",",
"len",
"(",
"parameters_value",
")",
")",
"mu",
",",
"sigma",
"=",
... | Predict by Gaussian Process Model | [
"Predict",
"by",
"Gaussian",
"Process",
"Model"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/Regression_GP/Prediction.py#L29-L36 |
27,144 | Microsoft/nni | src/sdk/pynni/nni/curvefitting_assessor/curvefitting_assessor.py | CurvefittingAssessor.assess_trial | def assess_trial(self, trial_job_id, trial_history):
"""assess whether a trial should be early stop by curve fitting algorithm
Parameters
----------
trial_job_id: int
trial job id
trial_history: list
The history performance matrix of each trial
R... | python | def assess_trial(self, trial_job_id, trial_history):
"""assess whether a trial should be early stop by curve fitting algorithm
Parameters
----------
trial_job_id: int
trial job id
trial_history: list
The history performance matrix of each trial
R... | [
"def",
"assess_trial",
"(",
"self",
",",
"trial_job_id",
",",
"trial_history",
")",
":",
"self",
".",
"trial_job_id",
"=",
"trial_job_id",
"self",
".",
"trial_history",
"=",
"trial_history",
"if",
"not",
"self",
".",
"set_best_performance",
":",
"return",
"Asses... | assess whether a trial should be early stop by curve fitting algorithm
Parameters
----------
trial_job_id: int
trial job id
trial_history: list
The history performance matrix of each trial
Returns
-------
bool
AssessResult.Goo... | [
"assess",
"whether",
"a",
"trial",
"should",
"be",
"early",
"stop",
"by",
"curve",
"fitting",
"algorithm"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/curvefitting_assessor/curvefitting_assessor.py#L88-L145 |
27,145 | Microsoft/nni | src/sdk/pynni/nni/multi_phase/multi_phase_dispatcher.py | MultiPhaseMsgDispatcher.handle_initialize | def handle_initialize(self, data):
'''
data is search space
'''
self.tuner.update_search_space(data)
send(CommandType.Initialized, '')
return True | python | def handle_initialize(self, data):
'''
data is search space
'''
self.tuner.update_search_space(data)
send(CommandType.Initialized, '')
return True | [
"def",
"handle_initialize",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"tuner",
".",
"update_search_space",
"(",
"data",
")",
"send",
"(",
"CommandType",
".",
"Initialized",
",",
"''",
")",
"return",
"True"
] | data is search space | [
"data",
"is",
"search",
"space"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/multi_phase/multi_phase_dispatcher.py#L94-L100 |
27,146 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/networkmorphism_tuner.py | NetworkMorphismTuner.generate_parameters | def generate_parameters(self, parameter_id):
"""
Returns a set of trial neural architecture, as a serializable object.
Parameters
----------
parameter_id : int
"""
if not self.history:
self.init_search()
new_father_id = None
generated... | python | def generate_parameters(self, parameter_id):
"""
Returns a set of trial neural architecture, as a serializable object.
Parameters
----------
parameter_id : int
"""
if not self.history:
self.init_search()
new_father_id = None
generated... | [
"def",
"generate_parameters",
"(",
"self",
",",
"parameter_id",
")",
":",
"if",
"not",
"self",
".",
"history",
":",
"self",
".",
"init_search",
"(",
")",
"new_father_id",
"=",
"None",
"generated_graph",
"=",
"None",
"if",
"not",
"self",
".",
"training_queue"... | Returns a set of trial neural architecture, as a serializable object.
Parameters
----------
parameter_id : int | [
"Returns",
"a",
"set",
"of",
"trial",
"neural",
"architecture",
"as",
"a",
"serializable",
"object",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/networkmorphism_tuner.py#L126-L153 |
27,147 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/networkmorphism_tuner.py | NetworkMorphismTuner.init_search | def init_search(self):
"""Call the generators to generate the initial architectures for the search."""
if self.verbose:
logger.info("Initializing search.")
for generator in self.generators:
graph = generator(self.n_classes, self.input_shape).generate(
self... | python | def init_search(self):
"""Call the generators to generate the initial architectures for the search."""
if self.verbose:
logger.info("Initializing search.")
for generator in self.generators:
graph = generator(self.n_classes, self.input_shape).generate(
self... | [
"def",
"init_search",
"(",
"self",
")",
":",
"if",
"self",
".",
"verbose",
":",
"logger",
".",
"info",
"(",
"\"Initializing search.\"",
")",
"for",
"generator",
"in",
"self",
".",
"generators",
":",
"graph",
"=",
"generator",
"(",
"self",
".",
"n_classes",... | Call the generators to generate the initial architectures for the search. | [
"Call",
"the",
"generators",
"to",
"generate",
"the",
"initial",
"architectures",
"for",
"the",
"search",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/networkmorphism_tuner.py#L178-L192 |
27,148 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/networkmorphism_tuner.py | NetworkMorphismTuner.generate | def generate(self):
"""Generate the next neural architecture.
Returns
-------
other_info: any object
Anything to be saved in the training queue together with the architecture.
generated_graph: Graph
An instance of Graph.
"""
generated_grap... | python | def generate(self):
"""Generate the next neural architecture.
Returns
-------
other_info: any object
Anything to be saved in the training queue together with the architecture.
generated_graph: Graph
An instance of Graph.
"""
generated_grap... | [
"def",
"generate",
"(",
"self",
")",
":",
"generated_graph",
",",
"new_father_id",
"=",
"self",
".",
"bo",
".",
"generate",
"(",
"self",
".",
"descriptors",
")",
"if",
"new_father_id",
"is",
"None",
":",
"new_father_id",
"=",
"0",
"generated_graph",
"=",
"... | Generate the next neural architecture.
Returns
-------
other_info: any object
Anything to be saved in the training queue together with the architecture.
generated_graph: Graph
An instance of Graph. | [
"Generate",
"the",
"next",
"neural",
"architecture",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/networkmorphism_tuner.py#L194-L211 |
27,149 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/networkmorphism_tuner.py | NetworkMorphismTuner.update | def update(self, other_info, graph, metric_value, model_id):
""" Update the controller with evaluation result of a neural architecture.
Parameters
----------
other_info: any object
In our case it is the father ID in the search tree.
graph: Graph
An instan... | python | def update(self, other_info, graph, metric_value, model_id):
""" Update the controller with evaluation result of a neural architecture.
Parameters
----------
other_info: any object
In our case it is the father ID in the search tree.
graph: Graph
An instan... | [
"def",
"update",
"(",
"self",
",",
"other_info",
",",
"graph",
",",
"metric_value",
",",
"model_id",
")",
":",
"father_id",
"=",
"other_info",
"self",
".",
"bo",
".",
"fit",
"(",
"[",
"graph",
".",
"extract_descriptor",
"(",
")",
"]",
",",
"[",
"metric... | Update the controller with evaluation result of a neural architecture.
Parameters
----------
other_info: any object
In our case it is the father ID in the search tree.
graph: Graph
An instance of Graph. The trained neural architecture.
metric_value: float... | [
"Update",
"the",
"controller",
"with",
"evaluation",
"result",
"of",
"a",
"neural",
"architecture",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/networkmorphism_tuner.py#L213-L228 |
27,150 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/networkmorphism_tuner.py | NetworkMorphismTuner.add_model | def add_model(self, metric_value, model_id):
""" Add model to the history, x_queue and y_queue
Parameters
----------
metric_value : float
graph : dict
model_id : int
Returns
-------
model : dict
"""
if self.verbose:
lo... | python | def add_model(self, metric_value, model_id):
""" Add model to the history, x_queue and y_queue
Parameters
----------
metric_value : float
graph : dict
model_id : int
Returns
-------
model : dict
"""
if self.verbose:
lo... | [
"def",
"add_model",
"(",
"self",
",",
"metric_value",
",",
"model_id",
")",
":",
"if",
"self",
".",
"verbose",
":",
"logger",
".",
"info",
"(",
"\"Saving model.\"",
")",
"# Update best_model text file",
"ret",
"=",
"{",
"\"model_id\"",
":",
"model_id",
",",
... | Add model to the history, x_queue and y_queue
Parameters
----------
metric_value : float
graph : dict
model_id : int
Returns
-------
model : dict | [
"Add",
"model",
"to",
"the",
"history",
"x_queue",
"and",
"y_queue"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/networkmorphism_tuner.py#L230-L253 |
27,151 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/networkmorphism_tuner.py | NetworkMorphismTuner.get_best_model_id | def get_best_model_id(self):
""" Get the best model_id from history using the metric value
"""
if self.optimize_mode is OptimizeMode.Maximize:
return max(self.history, key=lambda x: x["metric_value"])["model_id"]
return min(self.history, key=lambda x: x["metric_value"])["mod... | python | def get_best_model_id(self):
""" Get the best model_id from history using the metric value
"""
if self.optimize_mode is OptimizeMode.Maximize:
return max(self.history, key=lambda x: x["metric_value"])["model_id"]
return min(self.history, key=lambda x: x["metric_value"])["mod... | [
"def",
"get_best_model_id",
"(",
"self",
")",
":",
"if",
"self",
".",
"optimize_mode",
"is",
"OptimizeMode",
".",
"Maximize",
":",
"return",
"max",
"(",
"self",
".",
"history",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"\"metric_value\"",
"]",
")",
... | Get the best model_id from history using the metric value | [
"Get",
"the",
"best",
"model_id",
"from",
"history",
"using",
"the",
"metric",
"value"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/networkmorphism_tuner.py#L255-L261 |
27,152 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/networkmorphism_tuner.py | NetworkMorphismTuner.load_model_by_id | def load_model_by_id(self, model_id):
"""Get the model by model_id
Parameters
----------
model_id : int
model index
Returns
-------
load_model : Graph
the model graph representation
"""
with open(os.path.join(self... | python | def load_model_by_id(self, model_id):
"""Get the model by model_id
Parameters
----------
model_id : int
model index
Returns
-------
load_model : Graph
the model graph representation
"""
with open(os.path.join(self... | [
"def",
"load_model_by_id",
"(",
"self",
",",
"model_id",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"str",
"(",
"model_id",
")",
"+",
"\".json\"",
")",
")",
"as",
"fin",
":",
"json_str",
"=",
"fin"... | Get the model by model_id
Parameters
----------
model_id : int
model index
Returns
-------
load_model : Graph
the model graph representation | [
"Get",
"the",
"model",
"by",
"model_id"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/networkmorphism_tuner.py#L263-L281 |
27,153 | Microsoft/nni | src/sdk/pynni/nni/metis_tuner/metis_tuner.py | _rand_init | def _rand_init(x_bounds, x_types, selection_num_starting_points):
'''
Random sample some init seed within bounds.
'''
return [lib_data.rand(x_bounds, x_types) for i \
in range(0, selection_num_starting_points)] | python | def _rand_init(x_bounds, x_types, selection_num_starting_points):
'''
Random sample some init seed within bounds.
'''
return [lib_data.rand(x_bounds, x_types) for i \
in range(0, selection_num_starting_points)] | [
"def",
"_rand_init",
"(",
"x_bounds",
",",
"x_types",
",",
"selection_num_starting_points",
")",
":",
"return",
"[",
"lib_data",
".",
"rand",
"(",
"x_bounds",
",",
"x_types",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"selection_num_starting_points",
")",
... | Random sample some init seed within bounds. | [
"Random",
"sample",
"some",
"init",
"seed",
"within",
"bounds",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/metis_tuner.py#L493-L498 |
27,154 | Microsoft/nni | src/sdk/pynni/nni/metis_tuner/metis_tuner.py | MetisTuner.update_search_space | def update_search_space(self, search_space):
"""Update the self.x_bounds and self.x_types by the search_space.json
Parameters
----------
search_space : dict
"""
self.x_bounds = [[] for i in range(len(search_space))]
self.x_types = [NONE_TYPE for i in range(len(se... | python | def update_search_space(self, search_space):
"""Update the self.x_bounds and self.x_types by the search_space.json
Parameters
----------
search_space : dict
"""
self.x_bounds = [[] for i in range(len(search_space))]
self.x_types = [NONE_TYPE for i in range(len(se... | [
"def",
"update_search_space",
"(",
"self",
",",
"search_space",
")",
":",
"self",
".",
"x_bounds",
"=",
"[",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"search_space",
")",
")",
"]",
"self",
".",
"x_types",
"=",
"[",
"NONE_TYPE",
"for",
"i... | Update the self.x_bounds and self.x_types by the search_space.json
Parameters
----------
search_space : dict | [
"Update",
"the",
"self",
".",
"x_bounds",
"and",
"self",
".",
"x_types",
"by",
"the",
"search_space",
".",
"json"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/metis_tuner.py#L113-L164 |
27,155 | Microsoft/nni | src/sdk/pynni/nni/metis_tuner/metis_tuner.py | MetisTuner._pack_output | def _pack_output(self, init_parameter):
"""Pack the output
Parameters
----------
init_parameter : dict
Returns
-------
output : dict
"""
output = {}
for i, param in enumerate(init_parameter):
output[self.key_order[i]] = param
... | python | def _pack_output(self, init_parameter):
"""Pack the output
Parameters
----------
init_parameter : dict
Returns
-------
output : dict
"""
output = {}
for i, param in enumerate(init_parameter):
output[self.key_order[i]] = param
... | [
"def",
"_pack_output",
"(",
"self",
",",
"init_parameter",
")",
":",
"output",
"=",
"{",
"}",
"for",
"i",
",",
"param",
"in",
"enumerate",
"(",
"init_parameter",
")",
":",
"output",
"[",
"self",
".",
"key_order",
"[",
"i",
"]",
"]",
"=",
"param",
"re... | Pack the output
Parameters
----------
init_parameter : dict
Returns
-------
output : dict | [
"Pack",
"the",
"output"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/metis_tuner.py#L167-L181 |
27,156 | Microsoft/nni | src/sdk/pynni/nni/metis_tuner/metis_tuner.py | MetisTuner.generate_parameters | def generate_parameters(self, parameter_id):
"""Generate next parameter for trial
If the number of trial result is lower than cold start number,
metis will first random generate some parameters.
Otherwise, metis will choose the parameters by the Gussian Process Model and the Gussian Mixt... | python | def generate_parameters(self, parameter_id):
"""Generate next parameter for trial
If the number of trial result is lower than cold start number,
metis will first random generate some parameters.
Otherwise, metis will choose the parameters by the Gussian Process Model and the Gussian Mixt... | [
"def",
"generate_parameters",
"(",
"self",
",",
"parameter_id",
")",
":",
"if",
"len",
"(",
"self",
".",
"samples_x",
")",
"<",
"self",
".",
"cold_start_num",
":",
"init_parameter",
"=",
"_rand_init",
"(",
"self",
".",
"x_bounds",
",",
"self",
".",
"x_type... | Generate next parameter for trial
If the number of trial result is lower than cold start number,
metis will first random generate some parameters.
Otherwise, metis will choose the parameters by the Gussian Process Model and the Gussian Mixture Model.
Parameters
----------
... | [
"Generate",
"next",
"parameter",
"for",
"trial",
"If",
"the",
"number",
"of",
"trial",
"result",
"is",
"lower",
"than",
"cold",
"start",
"number",
"metis",
"will",
"first",
"random",
"generate",
"some",
"parameters",
".",
"Otherwise",
"metis",
"will",
"choose"... | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/metis_tuner.py#L184-L212 |
27,157 | Microsoft/nni | src/sdk/pynni/nni/metis_tuner/metis_tuner.py | MetisTuner.receive_trial_result | def receive_trial_result(self, parameter_id, parameters, value):
"""Tuner receive result from trial.
Parameters
----------
parameter_id : int
parameters : dict
value : dict/float
if value is dict, it should have "default" key.
"""
value = extr... | python | def receive_trial_result(self, parameter_id, parameters, value):
"""Tuner receive result from trial.
Parameters
----------
parameter_id : int
parameters : dict
value : dict/float
if value is dict, it should have "default" key.
"""
value = extr... | [
"def",
"receive_trial_result",
"(",
"self",
",",
"parameter_id",
",",
"parameters",
",",
"value",
")",
":",
"value",
"=",
"extract_scalar_reward",
"(",
"value",
")",
"if",
"self",
".",
"optimize_mode",
"==",
"OptimizeMode",
".",
"Maximize",
":",
"value",
"=",
... | Tuner receive result from trial.
Parameters
----------
parameter_id : int
parameters : dict
value : dict/float
if value is dict, it should have "default" key. | [
"Tuner",
"receive",
"result",
"from",
"trial",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/metis_tuner.py#L215-L255 |
27,158 | Microsoft/nni | src/sdk/pynni/nni/metis_tuner/Regression_GP/CreateModel.py | create_model | def create_model(samples_x, samples_y_aggregation,
n_restarts_optimizer=250, is_white_kernel=False):
'''
Trains GP regression model
'''
kernel = gp.kernels.ConstantKernel(constant_value=1,
constant_value_bounds=(1e-12, 1e12)) * \
... | python | def create_model(samples_x, samples_y_aggregation,
n_restarts_optimizer=250, is_white_kernel=False):
'''
Trains GP regression model
'''
kernel = gp.kernels.ConstantKernel(constant_value=1,
constant_value_bounds=(1e-12, 1e12)) * \
... | [
"def",
"create_model",
"(",
"samples_x",
",",
"samples_y_aggregation",
",",
"n_restarts_optimizer",
"=",
"250",
",",
"is_white_kernel",
"=",
"False",
")",
":",
"kernel",
"=",
"gp",
".",
"kernels",
".",
"ConstantKernel",
"(",
"constant_value",
"=",
"1",
",",
"c... | Trains GP regression model | [
"Trains",
"GP",
"regression",
"model"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/Regression_GP/CreateModel.py#L30-L52 |
27,159 | Microsoft/nni | src/sdk/pynni/nni/gridsearch_tuner/gridsearch_tuner.py | GridSearchTuner._parse_quniform | def _parse_quniform(self, param_value):
'''parse type of quniform parameter and return a list'''
if param_value[2] < 2:
raise RuntimeError("The number of values sampled (q) should be at least 2")
low, high, count = param_value[0], param_value[1], param_value[2]
interval = (hi... | python | def _parse_quniform(self, param_value):
'''parse type of quniform parameter and return a list'''
if param_value[2] < 2:
raise RuntimeError("The number of values sampled (q) should be at least 2")
low, high, count = param_value[0], param_value[1], param_value[2]
interval = (hi... | [
"def",
"_parse_quniform",
"(",
"self",
",",
"param_value",
")",
":",
"if",
"param_value",
"[",
"2",
"]",
"<",
"2",
":",
"raise",
"RuntimeError",
"(",
"\"The number of values sampled (q) should be at least 2\"",
")",
"low",
",",
"high",
",",
"count",
"=",
"param_... | parse type of quniform parameter and return a list | [
"parse",
"type",
"of",
"quniform",
"parameter",
"and",
"return",
"a",
"list"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/gridsearch_tuner/gridsearch_tuner.py#L96-L102 |
27,160 | Microsoft/nni | src/sdk/pynni/nni/gridsearch_tuner/gridsearch_tuner.py | GridSearchTuner.parse_qtype | def parse_qtype(self, param_type, param_value):
'''parse type of quniform or qloguniform'''
if param_type == 'quniform':
return self._parse_quniform(param_value)
if param_type == 'qloguniform':
param_value[:2] = np.log(param_value[:2])
return list(np.exp(self.... | python | def parse_qtype(self, param_type, param_value):
'''parse type of quniform or qloguniform'''
if param_type == 'quniform':
return self._parse_quniform(param_value)
if param_type == 'qloguniform':
param_value[:2] = np.log(param_value[:2])
return list(np.exp(self.... | [
"def",
"parse_qtype",
"(",
"self",
",",
"param_type",
",",
"param_value",
")",
":",
"if",
"param_type",
"==",
"'quniform'",
":",
"return",
"self",
".",
"_parse_quniform",
"(",
"param_value",
")",
"if",
"param_type",
"==",
"'qloguniform'",
":",
"param_value",
"... | parse type of quniform or qloguniform | [
"parse",
"type",
"of",
"quniform",
"or",
"qloguniform"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/gridsearch_tuner/gridsearch_tuner.py#L104-L112 |
27,161 | Microsoft/nni | tools/nni_trial_tool/log_utils.py | nni_log | def nni_log(log_type, log_message):
'''Log message into stdout'''
dt = datetime.now()
print('[{0}] {1} {2}'.format(dt, log_type.value, log_message)) | python | def nni_log(log_type, log_message):
'''Log message into stdout'''
dt = datetime.now()
print('[{0}] {1} {2}'.format(dt, log_type.value, log_message)) | [
"def",
"nni_log",
"(",
"log_type",
",",
"log_message",
")",
":",
"dt",
"=",
"datetime",
".",
"now",
"(",
")",
"print",
"(",
"'[{0}] {1} {2}'",
".",
"format",
"(",
"dt",
",",
"log_type",
".",
"value",
",",
"log_message",
")",
")"
] | Log message into stdout | [
"Log",
"message",
"into",
"stdout"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_trial_tool/log_utils.py#L54-L57 |
27,162 | Microsoft/nni | tools/nni_trial_tool/log_utils.py | PipeLogReader.run | def run(self):
"""Run the thread, logging everything.
If the log_collection is 'none', the log content will not be enqueued
"""
for line in iter(self.pipeReader.readline, ''):
self.orig_stdout.write(line.rstrip() + '\n')
self.orig_stdout.flush()
if ... | python | def run(self):
"""Run the thread, logging everything.
If the log_collection is 'none', the log content will not be enqueued
"""
for line in iter(self.pipeReader.readline, ''):
self.orig_stdout.write(line.rstrip() + '\n')
self.orig_stdout.flush()
if ... | [
"def",
"run",
"(",
"self",
")",
":",
"for",
"line",
"in",
"iter",
"(",
"self",
".",
"pipeReader",
".",
"readline",
",",
"''",
")",
":",
"self",
".",
"orig_stdout",
".",
"write",
"(",
"line",
".",
"rstrip",
"(",
")",
"+",
"'\\n'",
")",
"self",
"."... | Run the thread, logging everything.
If the log_collection is 'none', the log content will not be enqueued | [
"Run",
"the",
"thread",
"logging",
"everything",
".",
"If",
"the",
"log_collection",
"is",
"none",
"the",
"log",
"content",
"will",
"not",
"be",
"enqueued"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_trial_tool/log_utils.py#L168-L181 |
27,163 | Microsoft/nni | src/sdk/pynni/nni/utils.py | extract_scalar_reward | def extract_scalar_reward(value, scalar_key='default'):
"""
Extract scalar reward from trial result.
Raises
------
RuntimeError
Incorrect final result: the final result should be float/int,
or a dict which has a key named "default" whose value is float/int.
"""
if isinstance... | python | def extract_scalar_reward(value, scalar_key='default'):
"""
Extract scalar reward from trial result.
Raises
------
RuntimeError
Incorrect final result: the final result should be float/int,
or a dict which has a key named "default" whose value is float/int.
"""
if isinstance... | [
"def",
"extract_scalar_reward",
"(",
"value",
",",
"scalar_key",
"=",
"'default'",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"float",
")",
"or",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"reward",
"=",
"value",
"elif",
"isinstance",
"(",
"... | Extract scalar reward from trial result.
Raises
------
RuntimeError
Incorrect final result: the final result should be float/int,
or a dict which has a key named "default" whose value is float/int. | [
"Extract",
"scalar",
"reward",
"from",
"trial",
"result",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/utils.py#L25-L41 |
27,164 | Microsoft/nni | src/sdk/pynni/nni/utils.py | convert_dict2tuple | def convert_dict2tuple(value):
"""
convert dict type to tuple to solve unhashable problem.
"""
if isinstance(value, dict):
for _keys in value:
value[_keys] = convert_dict2tuple(value[_keys])
return tuple(sorted(value.items()))
else:
return value | python | def convert_dict2tuple(value):
"""
convert dict type to tuple to solve unhashable problem.
"""
if isinstance(value, dict):
for _keys in value:
value[_keys] = convert_dict2tuple(value[_keys])
return tuple(sorted(value.items()))
else:
return value | [
"def",
"convert_dict2tuple",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"for",
"_keys",
"in",
"value",
":",
"value",
"[",
"_keys",
"]",
"=",
"convert_dict2tuple",
"(",
"value",
"[",
"_keys",
"]",
")",
"return",
"tu... | convert dict type to tuple to solve unhashable problem. | [
"convert",
"dict",
"type",
"to",
"tuple",
"to",
"solve",
"unhashable",
"problem",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/utils.py#L43-L52 |
27,165 | Microsoft/nni | src/sdk/pynni/nni/utils.py | init_dispatcher_logger | def init_dispatcher_logger():
""" Initialize dispatcher logging configuration"""
logger_file_path = 'dispatcher.log'
if dispatcher_env_vars.NNI_LOG_DIRECTORY is not None:
logger_file_path = os.path.join(dispatcher_env_vars.NNI_LOG_DIRECTORY, logger_file_path)
init_logger(logger_file_path, dispat... | python | def init_dispatcher_logger():
""" Initialize dispatcher logging configuration"""
logger_file_path = 'dispatcher.log'
if dispatcher_env_vars.NNI_LOG_DIRECTORY is not None:
logger_file_path = os.path.join(dispatcher_env_vars.NNI_LOG_DIRECTORY, logger_file_path)
init_logger(logger_file_path, dispat... | [
"def",
"init_dispatcher_logger",
"(",
")",
":",
"logger_file_path",
"=",
"'dispatcher.log'",
"if",
"dispatcher_env_vars",
".",
"NNI_LOG_DIRECTORY",
"is",
"not",
"None",
":",
"logger_file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dispatcher_env_vars",
".",
... | Initialize dispatcher logging configuration | [
"Initialize",
"dispatcher",
"logging",
"configuration"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/utils.py#L54-L59 |
27,166 | Microsoft/nni | src/sdk/pynni/nni/bohb_advisor/config_generator.py | CG_BOHB.get_config | def get_config(self, budget):
"""Function to sample a new configuration
This function is called inside BOHB to query a new configuration
Parameters:
-----------
budget: float
the budget for which this configuration is scheduled
Returns
-------
... | python | def get_config(self, budget):
"""Function to sample a new configuration
This function is called inside BOHB to query a new configuration
Parameters:
-----------
budget: float
the budget for which this configuration is scheduled
Returns
-------
... | [
"def",
"get_config",
"(",
"self",
",",
"budget",
")",
":",
"logger",
".",
"debug",
"(",
"'start sampling a new configuration.'",
")",
"sample",
"=",
"None",
"info_dict",
"=",
"{",
"}",
"# If no model is available, sample from prior",
"# also mix in a fraction of random co... | Function to sample a new configuration
This function is called inside BOHB to query a new configuration
Parameters:
-----------
budget: float
the budget for which this configuration is scheduled
Returns
-------
config
return a valid confi... | [
"Function",
"to",
"sample",
"a",
"new",
"configuration",
"This",
"function",
"is",
"called",
"inside",
"BOHB",
"to",
"query",
"a",
"new",
"configuration"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/bohb_advisor/config_generator.py#L207-L241 |
27,167 | Microsoft/nni | src/sdk/pynni/nni/bohb_advisor/config_generator.py | CG_BOHB.new_result | def new_result(self, loss, budget, parameters, update_model=True):
"""
Function to register finished runs. Every time a run has finished, this function should be called
to register it with the loss.
Parameters:
-----------
loss: float
the loss of the paramete... | python | def new_result(self, loss, budget, parameters, update_model=True):
"""
Function to register finished runs. Every time a run has finished, this function should be called
to register it with the loss.
Parameters:
-----------
loss: float
the loss of the paramete... | [
"def",
"new_result",
"(",
"self",
",",
"loss",
",",
"budget",
",",
"parameters",
",",
"update_model",
"=",
"True",
")",
":",
"if",
"loss",
"is",
"None",
":",
"# One could skip crashed results, but we decided",
"# assign a +inf loss and count them as bad configurations",
... | Function to register finished runs. Every time a run has finished, this function should be called
to register it with the loss.
Parameters:
-----------
loss: float
the loss of the parameters
budget: float
the budget of the parameters
parameters: d... | [
"Function",
"to",
"register",
"finished",
"runs",
".",
"Every",
"time",
"a",
"run",
"has",
"finished",
"this",
"function",
"should",
"be",
"called",
"to",
"register",
"it",
"with",
"the",
"loss",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/bohb_advisor/config_generator.py#L266-L349 |
27,168 | Microsoft/nni | examples/trials/weight_sharing/ga_squad/graph_to_tf.py | normalize | def normalize(inputs,
epsilon=1e-8,
scope="ln"):
'''Applies layer normalization.
Args:
inputs: A tensor with 2 or more dimensions, where the first dimension has
`batch_size`.
epsilon: A floating number. A very small number for preventing ZeroDivision Error.
... | python | def normalize(inputs,
epsilon=1e-8,
scope="ln"):
'''Applies layer normalization.
Args:
inputs: A tensor with 2 or more dimensions, where the first dimension has
`batch_size`.
epsilon: A floating number. A very small number for preventing ZeroDivision Error.
... | [
"def",
"normalize",
"(",
"inputs",
",",
"epsilon",
"=",
"1e-8",
",",
"scope",
"=",
"\"ln\"",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"scope",
")",
":",
"inputs_shape",
"=",
"inputs",
".",
"get_shape",
"(",
")",
"params_shape",
"=",
"inputs_sh... | Applies layer normalization.
Args:
inputs: A tensor with 2 or more dimensions, where the first dimension has
`batch_size`.
epsilon: A floating number. A very small number for preventing ZeroDivision Error.
scope: Optional scope for `variable_scope`.
reuse: Boolean, whether to reuse ... | [
"Applies",
"layer",
"normalization",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/graph_to_tf.py#L28-L54 |
27,169 | Microsoft/nni | examples/trials/weight_sharing/ga_squad/graph_to_tf.py | positional_encoding | def positional_encoding(inputs,
num_units=None,
zero_pad=True,
scale=True,
scope="positional_encoding",
reuse=None):
'''
Return positinal embedding.
'''
Shape = tf.shape(inputs)
N ... | python | def positional_encoding(inputs,
num_units=None,
zero_pad=True,
scale=True,
scope="positional_encoding",
reuse=None):
'''
Return positinal embedding.
'''
Shape = tf.shape(inputs)
N ... | [
"def",
"positional_encoding",
"(",
"inputs",
",",
"num_units",
"=",
"None",
",",
"zero_pad",
"=",
"True",
",",
"scale",
"=",
"True",
",",
"scope",
"=",
"\"positional_encoding\"",
",",
"reuse",
"=",
"None",
")",
":",
"Shape",
"=",
"tf",
".",
"shape",
"(",... | Return positinal embedding. | [
"Return",
"positinal",
"embedding",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/graph_to_tf.py#L167-L205 |
27,170 | Microsoft/nni | examples/trials/weight_sharing/ga_squad/graph_to_tf.py | feedforward | def feedforward(inputs,
num_units,
scope="multihead_attention"):
'''Point-wise feed forward net.
Args:
inputs: A 3d tensor with shape of [N, T, C].
num_units: A list of two integers.
scope: Optional scope for `variable_scope`.
reuse: Boolean, whether to r... | python | def feedforward(inputs,
num_units,
scope="multihead_attention"):
'''Point-wise feed forward net.
Args:
inputs: A 3d tensor with shape of [N, T, C].
num_units: A list of two integers.
scope: Optional scope for `variable_scope`.
reuse: Boolean, whether to r... | [
"def",
"feedforward",
"(",
"inputs",
",",
"num_units",
",",
"scope",
"=",
"\"multihead_attention\"",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"scope",
")",
":",
"# Inner layer",
"params",
"=",
"{",
"\"inputs\"",
":",
"inputs",
",",
"\"filters\"",
... | Point-wise feed forward net.
Args:
inputs: A 3d tensor with shape of [N, T, C].
num_units: A list of two integers.
scope: Optional scope for `variable_scope`.
reuse: Boolean, whether to reuse the weights of a previous layer
by the same name.
Returns:
A 3d tensor with the ... | [
"Point",
"-",
"wise",
"feed",
"forward",
"net",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/graph_to_tf.py#L208-L240 |
27,171 | Microsoft/nni | tools/nni_cmd/rest_utils.py | check_rest_server | def check_rest_server(rest_port):
'''Check if restful server is ready'''
retry_count = 5
for _ in range(retry_count):
response = rest_get(check_status_url(rest_port), REST_TIME_OUT)
if response:
if response.status_code == 200:
return True, response
els... | python | def check_rest_server(rest_port):
'''Check if restful server is ready'''
retry_count = 5
for _ in range(retry_count):
response = rest_get(check_status_url(rest_port), REST_TIME_OUT)
if response:
if response.status_code == 200:
return True, response
els... | [
"def",
"check_rest_server",
"(",
"rest_port",
")",
":",
"retry_count",
"=",
"5",
"for",
"_",
"in",
"range",
"(",
"retry_count",
")",
":",
"response",
"=",
"rest_get",
"(",
"check_status_url",
"(",
"rest_port",
")",
",",
"REST_TIME_OUT",
")",
"if",
"response"... | Check if restful server is ready | [
"Check",
"if",
"restful",
"server",
"is",
"ready"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/rest_utils.py#L70-L82 |
27,172 | Microsoft/nni | tools/nni_cmd/rest_utils.py | check_rest_server_quick | def check_rest_server_quick(rest_port):
'''Check if restful server is ready, only check once'''
response = rest_get(check_status_url(rest_port), 5)
if response and response.status_code == 200:
return True, response
return False, None | python | def check_rest_server_quick(rest_port):
'''Check if restful server is ready, only check once'''
response = rest_get(check_status_url(rest_port), 5)
if response and response.status_code == 200:
return True, response
return False, None | [
"def",
"check_rest_server_quick",
"(",
"rest_port",
")",
":",
"response",
"=",
"rest_get",
"(",
"check_status_url",
"(",
"rest_port",
")",
",",
"5",
")",
"if",
"response",
"and",
"response",
".",
"status_code",
"==",
"200",
":",
"return",
"True",
",",
"respo... | Check if restful server is ready, only check once | [
"Check",
"if",
"restful",
"server",
"is",
"ready",
"only",
"check",
"once"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/rest_utils.py#L84-L89 |
27,173 | Microsoft/nni | tools/nni_cmd/launcher.py | get_log_path | def get_log_path(config_file_name):
'''generate stdout and stderr log path'''
stdout_full_path = os.path.join(NNICTL_HOME_DIR, config_file_name, 'stdout')
stderr_full_path = os.path.join(NNICTL_HOME_DIR, config_file_name, 'stderr')
return stdout_full_path, stderr_full_path | python | def get_log_path(config_file_name):
'''generate stdout and stderr log path'''
stdout_full_path = os.path.join(NNICTL_HOME_DIR, config_file_name, 'stdout')
stderr_full_path = os.path.join(NNICTL_HOME_DIR, config_file_name, 'stderr')
return stdout_full_path, stderr_full_path | [
"def",
"get_log_path",
"(",
"config_file_name",
")",
":",
"stdout_full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"NNICTL_HOME_DIR",
",",
"config_file_name",
",",
"'stdout'",
")",
"stderr_full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"NNICTL_HOME... | generate stdout and stderr log path | [
"generate",
"stdout",
"and",
"stderr",
"log",
"path"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher.py#L43-L47 |
27,174 | Microsoft/nni | tools/nni_cmd/launcher.py | print_log_content | def print_log_content(config_file_name):
'''print log information'''
stdout_full_path, stderr_full_path = get_log_path(config_file_name)
print_normal(' Stdout:')
print(check_output_command(stdout_full_path))
print('\n\n')
print_normal(' Stderr:')
print(check_output_command(stderr_full_path)) | python | def print_log_content(config_file_name):
'''print log information'''
stdout_full_path, stderr_full_path = get_log_path(config_file_name)
print_normal(' Stdout:')
print(check_output_command(stdout_full_path))
print('\n\n')
print_normal(' Stderr:')
print(check_output_command(stderr_full_path)) | [
"def",
"print_log_content",
"(",
"config_file_name",
")",
":",
"stdout_full_path",
",",
"stderr_full_path",
"=",
"get_log_path",
"(",
"config_file_name",
")",
"print_normal",
"(",
"' Stdout:'",
")",
"print",
"(",
"check_output_command",
"(",
"stdout_full_path",
")",
"... | print log information | [
"print",
"log",
"information"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher.py#L49-L56 |
27,175 | Microsoft/nni | tools/nni_cmd/launcher.py | get_nni_installation_path | def get_nni_installation_path():
''' Find nni lib from the following locations in order
Return nni root directory if it exists
'''
def try_installation_path_sequentially(*sitepackages):
'''Try different installation path sequentially util nni is found.
Return None if nothing is found
... | python | def get_nni_installation_path():
''' Find nni lib from the following locations in order
Return nni root directory if it exists
'''
def try_installation_path_sequentially(*sitepackages):
'''Try different installation path sequentially util nni is found.
Return None if nothing is found
... | [
"def",
"get_nni_installation_path",
"(",
")",
":",
"def",
"try_installation_path_sequentially",
"(",
"*",
"sitepackages",
")",
":",
"'''Try different installation path sequentially util nni is found.\n Return None if nothing is found\n '''",
"def",
"_generate_installation_p... | Find nni lib from the following locations in order
Return nni root directory if it exists | [
"Find",
"nni",
"lib",
"from",
"the",
"following",
"locations",
"in",
"order",
"Return",
"nni",
"root",
"directory",
"if",
"it",
"exists"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher.py#L58-L96 |
27,176 | Microsoft/nni | tools/nni_cmd/launcher.py | start_rest_server | def start_rest_server(port, platform, mode, config_file_name, experiment_id=None, log_dir=None, log_level=None):
'''Run nni manager process'''
nni_config = Config(config_file_name)
if detect_port(port):
print_error('Port %s is used by another process, please reset the port!\n' \
'You could u... | python | def start_rest_server(port, platform, mode, config_file_name, experiment_id=None, log_dir=None, log_level=None):
'''Run nni manager process'''
nni_config = Config(config_file_name)
if detect_port(port):
print_error('Port %s is used by another process, please reset the port!\n' \
'You could u... | [
"def",
"start_rest_server",
"(",
"port",
",",
"platform",
",",
"mode",
",",
"config_file_name",
",",
"experiment_id",
"=",
"None",
",",
"log_dir",
"=",
"None",
",",
"log_level",
"=",
"None",
")",
":",
"nni_config",
"=",
"Config",
"(",
"config_file_name",
")"... | Run nni manager process | [
"Run",
"nni",
"manager",
"process"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher.py#L98-L140 |
27,177 | Microsoft/nni | tools/nni_cmd/launcher.py | set_trial_config | def set_trial_config(experiment_config, port, config_file_name):
'''set trial configuration'''
request_data = dict()
request_data['trial_config'] = experiment_config['trial']
response = rest_put(cluster_metadata_url(port), json.dumps(request_data), REST_TIME_OUT)
if check_response(response):
... | python | def set_trial_config(experiment_config, port, config_file_name):
'''set trial configuration'''
request_data = dict()
request_data['trial_config'] = experiment_config['trial']
response = rest_put(cluster_metadata_url(port), json.dumps(request_data), REST_TIME_OUT)
if check_response(response):
... | [
"def",
"set_trial_config",
"(",
"experiment_config",
",",
"port",
",",
"config_file_name",
")",
":",
"request_data",
"=",
"dict",
"(",
")",
"request_data",
"[",
"'trial_config'",
"]",
"=",
"experiment_config",
"[",
"'trial'",
"]",
"response",
"=",
"rest_put",
"(... | set trial configuration | [
"set",
"trial",
"configuration"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher.py#L142-L155 |
27,178 | Microsoft/nni | tools/nni_cmd/launcher.py | set_local_config | def set_local_config(experiment_config, port, config_file_name):
'''set local configuration'''
#set machine_list
request_data = dict()
if experiment_config.get('localConfig'):
request_data['local_config'] = experiment_config['localConfig']
if request_data['local_config'] and request_data... | python | def set_local_config(experiment_config, port, config_file_name):
'''set local configuration'''
#set machine_list
request_data = dict()
if experiment_config.get('localConfig'):
request_data['local_config'] = experiment_config['localConfig']
if request_data['local_config'] and request_data... | [
"def",
"set_local_config",
"(",
"experiment_config",
",",
"port",
",",
"config_file_name",
")",
":",
"#set machine_list",
"request_data",
"=",
"dict",
"(",
")",
"if",
"experiment_config",
".",
"get",
"(",
"'localConfig'",
")",
":",
"request_data",
"[",
"'local_con... | set local configuration | [
"set",
"local",
"configuration"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher.py#L157-L176 |
27,179 | Microsoft/nni | tools/nni_cmd/launcher.py | set_remote_config | def set_remote_config(experiment_config, port, config_file_name):
'''Call setClusterMetadata to pass trial'''
#set machine_list
request_data = dict()
request_data['machine_list'] = experiment_config['machineList']
if request_data['machine_list']:
for i in range(len(request_data['machine_list... | python | def set_remote_config(experiment_config, port, config_file_name):
'''Call setClusterMetadata to pass trial'''
#set machine_list
request_data = dict()
request_data['machine_list'] = experiment_config['machineList']
if request_data['machine_list']:
for i in range(len(request_data['machine_list... | [
"def",
"set_remote_config",
"(",
"experiment_config",
",",
"port",
",",
"config_file_name",
")",
":",
"#set machine_list",
"request_data",
"=",
"dict",
"(",
")",
"request_data",
"[",
"'machine_list'",
"]",
"=",
"experiment_config",
"[",
"'machineList'",
"]",
"if",
... | Call setClusterMetadata to pass trial | [
"Call",
"setClusterMetadata",
"to",
"pass",
"trial"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher.py#L178-L200 |
27,180 | Microsoft/nni | tools/nni_cmd/launcher.py | set_frameworkcontroller_config | def set_frameworkcontroller_config(experiment_config, port, config_file_name):
'''set kubeflow configuration'''
frameworkcontroller_config_data = dict()
frameworkcontroller_config_data['frameworkcontroller_config'] = experiment_config['frameworkcontrollerConfig']
response = rest_put(cluster_metadata_ur... | python | def set_frameworkcontroller_config(experiment_config, port, config_file_name):
'''set kubeflow configuration'''
frameworkcontroller_config_data = dict()
frameworkcontroller_config_data['frameworkcontroller_config'] = experiment_config['frameworkcontrollerConfig']
response = rest_put(cluster_metadata_ur... | [
"def",
"set_frameworkcontroller_config",
"(",
"experiment_config",
",",
"port",
",",
"config_file_name",
")",
":",
"frameworkcontroller_config_data",
"=",
"dict",
"(",
")",
"frameworkcontroller_config_data",
"[",
"'frameworkcontroller_config'",
"]",
"=",
"experiment_config",
... | set kubeflow configuration | [
"set",
"kubeflow",
"configuration"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher.py#L257-L274 |
27,181 | Microsoft/nni | tools/nni_cmd/launcher.py | resume_experiment | def resume_experiment(args):
'''resume an experiment'''
experiment_config = Experiments()
experiment_dict = experiment_config.get_all_experiments()
experiment_id = None
experiment_endTime = None
#find the latest stopped experiment
if not args.id:
print_error('Please set experiment id... | python | def resume_experiment(args):
'''resume an experiment'''
experiment_config = Experiments()
experiment_dict = experiment_config.get_all_experiments()
experiment_id = None
experiment_endTime = None
#find the latest stopped experiment
if not args.id:
print_error('Please set experiment id... | [
"def",
"resume_experiment",
"(",
"args",
")",
":",
"experiment_config",
"=",
"Experiments",
"(",
")",
"experiment_dict",
"=",
"experiment_config",
".",
"get_all_experiments",
"(",
")",
"experiment_id",
"=",
"None",
"experiment_endTime",
"=",
"None",
"#find the latest ... | resume an experiment | [
"resume",
"an",
"experiment"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher.py#L494-L521 |
27,182 | Microsoft/nni | tools/nni_cmd/launcher.py | create_experiment | def create_experiment(args):
'''start a new experiment'''
config_file_name = ''.join(random.sample(string.ascii_letters + string.digits, 8))
nni_config = Config(config_file_name)
config_path = os.path.abspath(args.config)
if not os.path.exists(config_path):
print_error('Please set correct co... | python | def create_experiment(args):
'''start a new experiment'''
config_file_name = ''.join(random.sample(string.ascii_letters + string.digits, 8))
nni_config = Config(config_file_name)
config_path = os.path.abspath(args.config)
if not os.path.exists(config_path):
print_error('Please set correct co... | [
"def",
"create_experiment",
"(",
"args",
")",
":",
"config_file_name",
"=",
"''",
".",
"join",
"(",
"random",
".",
"sample",
"(",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
",",
"8",
")",
")",
"nni_config",
"=",
"Config",
"(",
"config_... | start a new experiment | [
"start",
"a",
"new",
"experiment"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher.py#L523-L536 |
27,183 | Microsoft/nni | src/sdk/pynni/nni/curvefitting_assessor/model_factory.py | CurveModel.f_comb | def f_comb(self, pos, sample):
"""return the value of the f_comb when epoch = pos
Parameters
----------
pos: int
the epoch number of the position you want to predict
sample: list
sample is a (1 * NUM_OF_FUNCTIONS) matrix, representing{w1, w2, ... wk}
... | python | def f_comb(self, pos, sample):
"""return the value of the f_comb when epoch = pos
Parameters
----------
pos: int
the epoch number of the position you want to predict
sample: list
sample is a (1 * NUM_OF_FUNCTIONS) matrix, representing{w1, w2, ... wk}
... | [
"def",
"f_comb",
"(",
"self",
",",
"pos",
",",
"sample",
")",
":",
"ret",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"effective_model_num",
")",
":",
"model",
"=",
"self",
".",
"effective_model",
"[",
"i",
"]",
"y",
"=",
"self",
".",
... | return the value of the f_comb when epoch = pos
Parameters
----------
pos: int
the epoch number of the position you want to predict
sample: list
sample is a (1 * NUM_OF_FUNCTIONS) matrix, representing{w1, w2, ... wk}
Returns
-------
int
... | [
"return",
"the",
"value",
"of",
"the",
"f_comb",
"when",
"epoch",
"=",
"pos"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/curvefitting_assessor/model_factory.py#L141-L161 |
27,184 | Microsoft/nni | src/sdk/pynni/nni/metis_tuner/Regression_GP/OutlierDetection.py | _outlierDetection_threaded | def _outlierDetection_threaded(inputs):
'''
Detect the outlier
'''
[samples_idx, samples_x, samples_y_aggregation] = inputs
sys.stderr.write("[%s] DEBUG: Evaluating %dth of %d samples\n"\
% (os.path.basename(__file__), samples_idx + 1, len(samples_x)))
outlier = None
... | python | def _outlierDetection_threaded(inputs):
'''
Detect the outlier
'''
[samples_idx, samples_x, samples_y_aggregation] = inputs
sys.stderr.write("[%s] DEBUG: Evaluating %dth of %d samples\n"\
% (os.path.basename(__file__), samples_idx + 1, len(samples_x)))
outlier = None
... | [
"def",
"_outlierDetection_threaded",
"(",
"inputs",
")",
":",
"[",
"samples_idx",
",",
"samples_x",
",",
"samples_y_aggregation",
"]",
"=",
"inputs",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"[%s] DEBUG: Evaluating %dth of %d samples\\n\"",
"%",
"(",
"os",
".",
... | Detect the outlier | [
"Detect",
"the",
"outlier"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/Regression_GP/OutlierDetection.py#L32-L53 |
27,185 | Microsoft/nni | src/sdk/pynni/nni/metis_tuner/Regression_GP/OutlierDetection.py | outlierDetection_threaded | def outlierDetection_threaded(samples_x, samples_y_aggregation):
'''
Use Multi-thread to detect the outlier
'''
outliers = []
threads_inputs = [[samples_idx, samples_x, samples_y_aggregation]\
for samples_idx in range(0, len(samples_x))]
threads_pool = ThreadPool(min... | python | def outlierDetection_threaded(samples_x, samples_y_aggregation):
'''
Use Multi-thread to detect the outlier
'''
outliers = []
threads_inputs = [[samples_idx, samples_x, samples_y_aggregation]\
for samples_idx in range(0, len(samples_x))]
threads_pool = ThreadPool(min... | [
"def",
"outlierDetection_threaded",
"(",
"samples_x",
",",
"samples_y_aggregation",
")",
":",
"outliers",
"=",
"[",
"]",
"threads_inputs",
"=",
"[",
"[",
"samples_idx",
",",
"samples_x",
",",
"samples_y_aggregation",
"]",
"for",
"samples_idx",
"in",
"range",
"(",
... | Use Multi-thread to detect the outlier | [
"Use",
"Multi",
"-",
"thread",
"to",
"detect",
"the",
"outlier"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/Regression_GP/OutlierDetection.py#L55-L75 |
27,186 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/layer_transformer.py | deeper_conv_block | def deeper_conv_block(conv_layer, kernel_size, weighted=True):
'''deeper conv layer.
'''
n_dim = get_n_dim(conv_layer)
filter_shape = (kernel_size,) * 2
n_filters = conv_layer.filters
weight = np.zeros((n_filters, n_filters) + filter_shape)
center = tuple(map(lambda x: int((x - 1) / 2), filt... | python | def deeper_conv_block(conv_layer, kernel_size, weighted=True):
'''deeper conv layer.
'''
n_dim = get_n_dim(conv_layer)
filter_shape = (kernel_size,) * 2
n_filters = conv_layer.filters
weight = np.zeros((n_filters, n_filters) + filter_shape)
center = tuple(map(lambda x: int((x - 1) / 2), filt... | [
"def",
"deeper_conv_block",
"(",
"conv_layer",
",",
"kernel_size",
",",
"weighted",
"=",
"True",
")",
":",
"n_dim",
"=",
"get_n_dim",
"(",
"conv_layer",
")",
"filter_shape",
"=",
"(",
"kernel_size",
",",
")",
"*",
"2",
"n_filters",
"=",
"conv_layer",
".",
... | deeper conv layer. | [
"deeper",
"conv",
"layer",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/layer_transformer.py#L34-L65 |
27,187 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/layer_transformer.py | dense_to_deeper_block | def dense_to_deeper_block(dense_layer, weighted=True):
'''deeper dense layer.
'''
units = dense_layer.units
weight = np.eye(units)
bias = np.zeros(units)
new_dense_layer = StubDense(units, units)
if weighted:
new_dense_layer.set_weights(
(add_noise(weight, np.array([0, 1]... | python | def dense_to_deeper_block(dense_layer, weighted=True):
'''deeper dense layer.
'''
units = dense_layer.units
weight = np.eye(units)
bias = np.zeros(units)
new_dense_layer = StubDense(units, units)
if weighted:
new_dense_layer.set_weights(
(add_noise(weight, np.array([0, 1]... | [
"def",
"dense_to_deeper_block",
"(",
"dense_layer",
",",
"weighted",
"=",
"True",
")",
":",
"units",
"=",
"dense_layer",
".",
"units",
"weight",
"=",
"np",
".",
"eye",
"(",
"units",
")",
"bias",
"=",
"np",
".",
"zeros",
"(",
"units",
")",
"new_dense_laye... | deeper dense layer. | [
"deeper",
"dense",
"layer",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/layer_transformer.py#L68-L79 |
27,188 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/layer_transformer.py | wider_pre_dense | def wider_pre_dense(layer, n_add, weighted=True):
'''wider previous dense layer.
'''
if not weighted:
return StubDense(layer.input_units, layer.units + n_add)
n_units2 = layer.units
teacher_w, teacher_b = layer.get_weights()
rand = np.random.randint(n_units2, size=n_add)
student_w ... | python | def wider_pre_dense(layer, n_add, weighted=True):
'''wider previous dense layer.
'''
if not weighted:
return StubDense(layer.input_units, layer.units + n_add)
n_units2 = layer.units
teacher_w, teacher_b = layer.get_weights()
rand = np.random.randint(n_units2, size=n_add)
student_w ... | [
"def",
"wider_pre_dense",
"(",
"layer",
",",
"n_add",
",",
"weighted",
"=",
"True",
")",
":",
"if",
"not",
"weighted",
":",
"return",
"StubDense",
"(",
"layer",
".",
"input_units",
",",
"layer",
".",
"units",
"+",
"n_add",
")",
"n_units2",
"=",
"layer",
... | wider previous dense layer. | [
"wider",
"previous",
"dense",
"layer",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/layer_transformer.py#L82-L106 |
27,189 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/layer_transformer.py | wider_pre_conv | def wider_pre_conv(layer, n_add_filters, weighted=True):
'''wider previous conv layer.
'''
n_dim = get_n_dim(layer)
if not weighted:
return get_conv_class(n_dim)(
layer.input_channel,
layer.filters + n_add_filters,
kernel_size=layer.kernel_size,
)
... | python | def wider_pre_conv(layer, n_add_filters, weighted=True):
'''wider previous conv layer.
'''
n_dim = get_n_dim(layer)
if not weighted:
return get_conv_class(n_dim)(
layer.input_channel,
layer.filters + n_add_filters,
kernel_size=layer.kernel_size,
)
... | [
"def",
"wider_pre_conv",
"(",
"layer",
",",
"n_add_filters",
",",
"weighted",
"=",
"True",
")",
":",
"n_dim",
"=",
"get_n_dim",
"(",
"layer",
")",
"if",
"not",
"weighted",
":",
"return",
"get_conv_class",
"(",
"n_dim",
")",
"(",
"layer",
".",
"input_channe... | wider previous conv layer. | [
"wider",
"previous",
"conv",
"layer",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/layer_transformer.py#L109-L139 |
27,190 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/layer_transformer.py | wider_next_conv | def wider_next_conv(layer, start_dim, total_dim, n_add, weighted=True):
'''wider next conv layer.
'''
n_dim = get_n_dim(layer)
if not weighted:
return get_conv_class(n_dim)(layer.input_channel + n_add,
layer.filters,
kerne... | python | def wider_next_conv(layer, start_dim, total_dim, n_add, weighted=True):
'''wider next conv layer.
'''
n_dim = get_n_dim(layer)
if not weighted:
return get_conv_class(n_dim)(layer.input_channel + n_add,
layer.filters,
kerne... | [
"def",
"wider_next_conv",
"(",
"layer",
",",
"start_dim",
",",
"total_dim",
",",
"n_add",
",",
"weighted",
"=",
"True",
")",
":",
"n_dim",
"=",
"get_n_dim",
"(",
"layer",
")",
"if",
"not",
"weighted",
":",
"return",
"get_conv_class",
"(",
"n_dim",
")",
"... | wider next conv layer. | [
"wider",
"next",
"conv",
"layer",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/layer_transformer.py#L142-L166 |
27,191 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/layer_transformer.py | wider_bn | def wider_bn(layer, start_dim, total_dim, n_add, weighted=True):
'''wider batch norm layer.
'''
n_dim = get_n_dim(layer)
if not weighted:
return get_batch_norm_class(n_dim)(layer.num_features + n_add)
weights = layer.get_weights()
new_weights = [
add_noise(np.ones(n_add, dtype=... | python | def wider_bn(layer, start_dim, total_dim, n_add, weighted=True):
'''wider batch norm layer.
'''
n_dim = get_n_dim(layer)
if not weighted:
return get_batch_norm_class(n_dim)(layer.num_features + n_add)
weights = layer.get_weights()
new_weights = [
add_noise(np.ones(n_add, dtype=... | [
"def",
"wider_bn",
"(",
"layer",
",",
"start_dim",
",",
"total_dim",
",",
"n_add",
",",
"weighted",
"=",
"True",
")",
":",
"n_dim",
"=",
"get_n_dim",
"(",
"layer",
")",
"if",
"not",
"weighted",
":",
"return",
"get_batch_norm_class",
"(",
"n_dim",
")",
"(... | wider batch norm layer. | [
"wider",
"batch",
"norm",
"layer",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/layer_transformer.py#L169-L194 |
27,192 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/layer_transformer.py | wider_next_dense | def wider_next_dense(layer, start_dim, total_dim, n_add, weighted=True):
'''wider next dense layer.
'''
if not weighted:
return StubDense(layer.input_units + n_add, layer.units)
teacher_w, teacher_b = layer.get_weights()
student_w = teacher_w.copy()
n_units_each_channel = int(teacher_w.s... | python | def wider_next_dense(layer, start_dim, total_dim, n_add, weighted=True):
'''wider next dense layer.
'''
if not weighted:
return StubDense(layer.input_units + n_add, layer.units)
teacher_w, teacher_b = layer.get_weights()
student_w = teacher_w.copy()
n_units_each_channel = int(teacher_w.s... | [
"def",
"wider_next_dense",
"(",
"layer",
",",
"start_dim",
",",
"total_dim",
",",
"n_add",
",",
"weighted",
"=",
"True",
")",
":",
"if",
"not",
"weighted",
":",
"return",
"StubDense",
"(",
"layer",
".",
"input_units",
"+",
"n_add",
",",
"layer",
".",
"un... | wider next dense layer. | [
"wider",
"next",
"dense",
"layer",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/layer_transformer.py#L197-L220 |
27,193 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/layer_transformer.py | add_noise | def add_noise(weights, other_weights):
'''add noise to the layer.
'''
w_range = np.ptp(other_weights.flatten())
noise_range = NOISE_RATIO * w_range
noise = np.random.uniform(-noise_range / 2.0, noise_range / 2.0, weights.shape)
return np.add(noise, weights) | python | def add_noise(weights, other_weights):
'''add noise to the layer.
'''
w_range = np.ptp(other_weights.flatten())
noise_range = NOISE_RATIO * w_range
noise = np.random.uniform(-noise_range / 2.0, noise_range / 2.0, weights.shape)
return np.add(noise, weights) | [
"def",
"add_noise",
"(",
"weights",
",",
"other_weights",
")",
":",
"w_range",
"=",
"np",
".",
"ptp",
"(",
"other_weights",
".",
"flatten",
"(",
")",
")",
"noise_range",
"=",
"NOISE_RATIO",
"*",
"w_range",
"noise",
"=",
"np",
".",
"random",
".",
"uniform... | add noise to the layer. | [
"add",
"noise",
"to",
"the",
"layer",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/layer_transformer.py#L223-L229 |
27,194 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/layer_transformer.py | init_dense_weight | def init_dense_weight(layer):
'''initilize dense layer weight.
'''
units = layer.units
weight = np.eye(units)
bias = np.zeros(units)
layer.set_weights(
(add_noise(weight, np.array([0, 1])), add_noise(bias, np.array([0, 1])))
) | python | def init_dense_weight(layer):
'''initilize dense layer weight.
'''
units = layer.units
weight = np.eye(units)
bias = np.zeros(units)
layer.set_weights(
(add_noise(weight, np.array([0, 1])), add_noise(bias, np.array([0, 1])))
) | [
"def",
"init_dense_weight",
"(",
"layer",
")",
":",
"units",
"=",
"layer",
".",
"units",
"weight",
"=",
"np",
".",
"eye",
"(",
"units",
")",
"bias",
"=",
"np",
".",
"zeros",
"(",
"units",
")",
"layer",
".",
"set_weights",
"(",
"(",
"add_noise",
"(",
... | initilize dense layer weight. | [
"initilize",
"dense",
"layer",
"weight",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/layer_transformer.py#L232-L240 |
27,195 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/layer_transformer.py | init_conv_weight | def init_conv_weight(layer):
'''initilize conv layer weight.
'''
n_filters = layer.filters
filter_shape = (layer.kernel_size,) * get_n_dim(layer)
weight = np.zeros((n_filters, n_filters) + filter_shape)
center = tuple(map(lambda x: int((x - 1) / 2), filter_shape))
for i in range(n_filters):... | python | def init_conv_weight(layer):
'''initilize conv layer weight.
'''
n_filters = layer.filters
filter_shape = (layer.kernel_size,) * get_n_dim(layer)
weight = np.zeros((n_filters, n_filters) + filter_shape)
center = tuple(map(lambda x: int((x - 1) / 2), filter_shape))
for i in range(n_filters):... | [
"def",
"init_conv_weight",
"(",
"layer",
")",
":",
"n_filters",
"=",
"layer",
".",
"filters",
"filter_shape",
"=",
"(",
"layer",
".",
"kernel_size",
",",
")",
"*",
"get_n_dim",
"(",
"layer",
")",
"weight",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_filters",
... | initilize conv layer weight. | [
"initilize",
"conv",
"layer",
"weight",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/layer_transformer.py#L243-L260 |
27,196 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/layer_transformer.py | init_bn_weight | def init_bn_weight(layer):
'''initilize batch norm layer weight.
'''
n_filters = layer.num_features
new_weights = [
add_noise(np.ones(n_filters, dtype=np.float32), np.array([0, 1])),
add_noise(np.zeros(n_filters, dtype=np.float32), np.array([0, 1])),
add_noise(np.zeros(n_filters,... | python | def init_bn_weight(layer):
'''initilize batch norm layer weight.
'''
n_filters = layer.num_features
new_weights = [
add_noise(np.ones(n_filters, dtype=np.float32), np.array([0, 1])),
add_noise(np.zeros(n_filters, dtype=np.float32), np.array([0, 1])),
add_noise(np.zeros(n_filters,... | [
"def",
"init_bn_weight",
"(",
"layer",
")",
":",
"n_filters",
"=",
"layer",
".",
"num_features",
"new_weights",
"=",
"[",
"add_noise",
"(",
"np",
".",
"ones",
"(",
"n_filters",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
",",
"np",
".",
"array",
"(",... | initilize batch norm layer weight. | [
"initilize",
"batch",
"norm",
"layer",
"weight",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/layer_transformer.py#L263-L273 |
27,197 | Microsoft/nni | tools/nni_cmd/tensorboard_utils.py | parse_log_path | def parse_log_path(args, trial_content):
'''parse log path'''
path_list = []
host_list = []
for trial in trial_content:
if args.trial_id and args.trial_id != 'all' and trial.get('id') != args.trial_id:
continue
pattern = r'(?P<head>.+)://(?P<host>.+):(?P<path>.*)'
mat... | python | def parse_log_path(args, trial_content):
'''parse log path'''
path_list = []
host_list = []
for trial in trial_content:
if args.trial_id and args.trial_id != 'all' and trial.get('id') != args.trial_id:
continue
pattern = r'(?P<head>.+)://(?P<host>.+):(?P<path>.*)'
mat... | [
"def",
"parse_log_path",
"(",
"args",
",",
"trial_content",
")",
":",
"path_list",
"=",
"[",
"]",
"host_list",
"=",
"[",
"]",
"for",
"trial",
"in",
"trial_content",
":",
"if",
"args",
".",
"trial_id",
"and",
"args",
".",
"trial_id",
"!=",
"'all'",
"and",... | parse log path | [
"parse",
"log",
"path"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/tensorboard_utils.py#L38-L53 |
27,198 | Microsoft/nni | tools/nni_cmd/tensorboard_utils.py | copy_data_from_remote | def copy_data_from_remote(args, nni_config, trial_content, path_list, host_list, temp_nni_path):
'''use ssh client to copy data from remote machine to local machien'''
machine_list = nni_config.get_config('experimentConfig').get('machineList')
machine_dict = {}
local_path_list = []
for machine in ma... | python | def copy_data_from_remote(args, nni_config, trial_content, path_list, host_list, temp_nni_path):
'''use ssh client to copy data from remote machine to local machien'''
machine_list = nni_config.get_config('experimentConfig').get('machineList')
machine_dict = {}
local_path_list = []
for machine in ma... | [
"def",
"copy_data_from_remote",
"(",
"args",
",",
"nni_config",
",",
"trial_content",
",",
"path_list",
",",
"host_list",
",",
"temp_nni_path",
")",
":",
"machine_list",
"=",
"nni_config",
".",
"get_config",
"(",
"'experimentConfig'",
")",
".",
"get",
"(",
"'mac... | use ssh client to copy data from remote machine to local machien | [
"use",
"ssh",
"client",
"to",
"copy",
"data",
"from",
"remote",
"machine",
"to",
"local",
"machien"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/tensorboard_utils.py#L55-L69 |
27,199 | Microsoft/nni | tools/nni_cmd/tensorboard_utils.py | get_path_list | def get_path_list(args, nni_config, trial_content, temp_nni_path):
'''get path list according to different platform'''
path_list, host_list = parse_log_path(args, trial_content)
platform = nni_config.get_config('experimentConfig').get('trainingServicePlatform')
if platform == 'local':
print_norm... | python | def get_path_list(args, nni_config, trial_content, temp_nni_path):
'''get path list according to different platform'''
path_list, host_list = parse_log_path(args, trial_content)
platform = nni_config.get_config('experimentConfig').get('trainingServicePlatform')
if platform == 'local':
print_norm... | [
"def",
"get_path_list",
"(",
"args",
",",
"nni_config",
",",
"trial_content",
",",
"temp_nni_path",
")",
":",
"path_list",
",",
"host_list",
"=",
"parse_log_path",
"(",
"args",
",",
"trial_content",
")",
"platform",
"=",
"nni_config",
".",
"get_config",
"(",
"... | get path list according to different platform | [
"get",
"path",
"list",
"according",
"to",
"different",
"platform"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/tensorboard_utils.py#L71-L84 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.