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",
"(",
"file",
")",
"except",
"ValueError",
":",
"return",
"{",
"}",
"return",
"{",
"}"
] | 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_file)['data']
for doc in data:
for paragraph in doc['paragraphs']:
passage = paragraph['context']
for qa_pair in paragraph['qas']:
question = qa_pair['question']
qa_id = qa_pair['id']
if not is_training:
qp_pairs.append(
{'passage': passage, 'question': question, 'id': qa_id})
else:
for answer in qa_pair['answers']:
answer_begin = int(answer['answer_start'])
answer_end = answer_begin + len(answer['text'])
qp_pairs.append({'passage': passage,
'question': question,
'id': qa_id,
'answer_begin': answer_begin,
'answer_end': answer_end})
else:
with open(path, newline='') as csvfile:
reader = csv.reader(csvfile, delimiter='\t')
line_num = 0
for row in reader:
qp_pairs.append(
{'passage': row[1], 'question': row[0], 'id': line_num})
line_num += 1
return qp_pairs | 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_file)['data']
for doc in data:
for paragraph in doc['paragraphs']:
passage = paragraph['context']
for qa_pair in paragraph['qas']:
question = qa_pair['question']
qa_id = qa_pair['id']
if not is_training:
qp_pairs.append(
{'passage': passage, 'question': question, 'id': qa_id})
else:
for answer in qa_pair['answers']:
answer_begin = int(answer['answer_start'])
answer_end = answer_begin + len(answer['text'])
qp_pairs.append({'passage': passage,
'question': question,
'id': qa_id,
'answer_begin': answer_begin,
'answer_end': answer_end})
else:
with open(path, newline='') as csvfile:
reader = csv.reader(csvfile, delimiter='\t')
line_num = 0
for row in reader:
qp_pairs.append(
{'passage': row[1], 'question': row[0], 'id': line_num})
line_num += 1
return qp_pairs | [
"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 or csv'",
"qp_pairs",
"=",
"[",
"]",
"if",
"fmt",
"==",
"'squad'",
":",
"with",
"open",
"(",
"path",
")",
"as",
"data_file",
":",
"data",
"=",
"json",
".",
"load",
"(",
"data_file",
")",
"[",
"'data'",
"]",
"for",
"doc",
"in",
"data",
":",
"for",
"paragraph",
"in",
"doc",
"[",
"'paragraphs'",
"]",
":",
"passage",
"=",
"paragraph",
"[",
"'context'",
"]",
"for",
"qa_pair",
"in",
"paragraph",
"[",
"'qas'",
"]",
":",
"question",
"=",
"qa_pair",
"[",
"'question'",
"]",
"qa_id",
"=",
"qa_pair",
"[",
"'id'",
"]",
"if",
"not",
"is_training",
":",
"qp_pairs",
".",
"append",
"(",
"{",
"'passage'",
":",
"passage",
",",
"'question'",
":",
"question",
",",
"'id'",
":",
"qa_id",
"}",
")",
"else",
":",
"for",
"answer",
"in",
"qa_pair",
"[",
"'answers'",
"]",
":",
"answer_begin",
"=",
"int",
"(",
"answer",
"[",
"'answer_start'",
"]",
")",
"answer_end",
"=",
"answer_begin",
"+",
"len",
"(",
"answer",
"[",
"'text'",
"]",
")",
"qp_pairs",
".",
"append",
"(",
"{",
"'passage'",
":",
"passage",
",",
"'question'",
":",
"question",
",",
"'id'",
":",
"qa_id",
",",
"'answer_begin'",
":",
"answer_begin",
",",
"'answer_end'",
":",
"answer_end",
"}",
")",
"else",
":",
"with",
"open",
"(",
"path",
",",
"newline",
"=",
"''",
")",
"as",
"csvfile",
":",
"reader",
"=",
"csv",
".",
"reader",
"(",
"csvfile",
",",
"delimiter",
"=",
"'\\t'",
")",
"line_num",
"=",
"0",
"for",
"row",
"in",
"reader",
":",
"qp_pairs",
".",
"append",
"(",
"{",
"'passage'",
":",
"row",
"[",
"1",
"]",
",",
"'question'",
":",
"row",
"[",
"0",
"]",
",",
"'id'",
":",
"line_num",
"}",
")",
"line_num",
"+=",
"1",
"return",
"qp_pairs"
] | 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_tokens[:300]
passage_tokens.insert(
0, {'word': '<BOS>', 'original_text': '<BOS>', 'char_begin': 0, 'char_end': 0})
passage_tokens.append(
{'word': '<EOS>', 'original_text': '<EOS>', 'char_begin': 0, 'char_end': 0})
qp_pair['question_tokens'] = question_tokens
qp_pair['passage_tokens'] = passage_tokens | 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_tokens[:300]
passage_tokens.insert(
0, {'word': '<BOS>', 'original_text': '<BOS>', 'char_begin': 0, 'char_end': 0})
passage_tokens.append(
{'word': '<EOS>', 'original_text': '<EOS>', 'char_begin': 0, 'char_end': 0})
qp_pair['question_tokens'] = question_tokens
qp_pair['passage_tokens'] = passage_tokens | [
"def",
"tokenize",
"(",
"qp_pair",
",",
"tokenizer",
"=",
"None",
",",
"is_training",
"=",
"False",
")",
":",
"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_tokens",
"[",
":",
"300",
"]",
"passage_tokens",
".",
"insert",
"(",
"0",
",",
"{",
"'word'",
":",
"'<BOS>'",
",",
"'original_text'",
":",
"'<BOS>'",
",",
"'char_begin'",
":",
"0",
",",
"'char_end'",
":",
"0",
"}",
")",
"passage_tokens",
".",
"append",
"(",
"{",
"'word'",
":",
"'<EOS>'",
",",
"'original_text'",
":",
"'<EOS>'",
",",
"'char_begin'",
":",
"0",
",",
"'char_end'",
":",
"0",
"}",
")",
"qp_pair",
"[",
"'question_tokens'",
"]",
"=",
"question_tokens",
"qp_pair",
"[",
"'passage_tokens'",
"]",
"=",
"passage_tokens"
] | 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'",
"]",
")",
"for",
"word",
"in",
"qp_pair",
"[",
"'passage_tokens'",
"]",
":",
"vocab",
".",
"add",
"(",
"word",
"[",
"'word'",
"]",
")",
"return",
"vocab"
] | 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",
"(",
"sub",
")",
"answer",
"+=",
"sub",
"return",
"answer"
] | 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 in range(0, len(qp_pairs), batch_size)]
shuffle(batches)
return batches | 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 in range(0, len(qp_pairs), batch_size)]
shuffle(batches)
return batches | [
"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'",
"]",
")",
",",
"qp",
"[",
"'id'",
"]",
")",
",",
"reverse",
"=",
"True",
")",
"batches",
"=",
"[",
"{",
"'qp_pairs'",
":",
"qp_pairs",
"[",
"i",
":",
"(",
"i",
"+",
"batch_size",
")",
"]",
"}",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"qp_pairs",
")",
",",
"batch_size",
")",
"]",
"shuffle",
"(",
"batches",
")",
"return",
"batches"
] | 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, batch_size), dtype=np.float32)
for batch_idx in range(0, min(len(data), batch_size)):
batch_data = data[batch_idx]
for sample_idx in range(0, min(len(batch_data), sequence_length)):
word = batch_data[sample_idx]['word']
char_lengths[sample_idx, batch_idx] = min(
len(word), max_char_length)
for i in range(0, min(len(word), max_char_length)):
char_id[i, sample_idx, batch_idx] = get_id(char_dict, word[i])
return char_id, char_lengths | 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, batch_size), dtype=np.float32)
for batch_idx in range(0, min(len(data), batch_size)):
batch_data = data[batch_idx]
for sample_idx in range(0, min(len(batch_data), sequence_length)):
word = batch_data[sample_idx]['word']
char_lengths[sample_idx, batch_idx] = min(
len(word), max_char_length)
for i in range(0, min(len(word), max_char_length)):
char_id[i, sample_idx, batch_idx] = get_id(char_dict, word[i])
return char_id, char_lengths | [
"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",
".",
"zeros",
"(",
"(",
"max_char_length",
",",
"sequence_length",
",",
"batch_size",
")",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
"char_lengths",
"=",
"np",
".",
"zeros",
"(",
"(",
"sequence_length",
",",
"batch_size",
")",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"for",
"batch_idx",
"in",
"range",
"(",
"0",
",",
"min",
"(",
"len",
"(",
"data",
")",
",",
"batch_size",
")",
")",
":",
"batch_data",
"=",
"data",
"[",
"batch_idx",
"]",
"for",
"sample_idx",
"in",
"range",
"(",
"0",
",",
"min",
"(",
"len",
"(",
"batch_data",
")",
",",
"sequence_length",
")",
")",
":",
"word",
"=",
"batch_data",
"[",
"sample_idx",
"]",
"[",
"'word'",
"]",
"char_lengths",
"[",
"sample_idx",
",",
"batch_idx",
"]",
"=",
"min",
"(",
"len",
"(",
"word",
")",
",",
"max_char_length",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"min",
"(",
"len",
"(",
"word",
")",
",",
"max_char_length",
")",
")",
":",
"char_id",
"[",
"i",
",",
"sample_idx",
",",
"batch_idx",
"]",
"=",
"get_id",
"(",
"char_dict",
",",
"word",
"[",
"i",
"]",
")",
"return",
"char_id",
",",
"char_lengths"
] | 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.float32)
ids = np.zeros((sequence_length, batch_size), dtype=np.int32)
masks = np.zeros((sequence_length, batch_size), dtype=np.float32)
lengths = np.zeros([batch_size], dtype=np.int32)
for batch_idx in range(0, min(len(data), batch_size)):
batch_data = data[batch_idx]
lengths[batch_idx] = len(batch_data)
for sample_idx in range(0, min(len(batch_data), sequence_length)):
word = batch_data[sample_idx]['word'].lower()
if word in word_dict.keys():
word_input[sample_idx, batch_idx] = embed[word_dict[word]]
ids[sample_idx, batch_idx] = word_dict[word]
masks[sample_idx, batch_idx] = 1
word_input = np.reshape(word_input, (-1, embed_dim))
return word_input, ids, masks, lengths | 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.float32)
ids = np.zeros((sequence_length, batch_size), dtype=np.int32)
masks = np.zeros((sequence_length, batch_size), dtype=np.float32)
lengths = np.zeros([batch_size], dtype=np.int32)
for batch_idx in range(0, min(len(data), batch_size)):
batch_data = data[batch_idx]
lengths[batch_idx] = len(batch_data)
for sample_idx in range(0, min(len(batch_data), sequence_length)):
word = batch_data[sample_idx]['word'].lower()
if word in word_dict.keys():
word_input[sample_idx, batch_idx] = embed[word_dict[word]]
ids[sample_idx, batch_idx] = word_dict[word]
masks[sample_idx, batch_idx] = 1
word_input = np.reshape(word_input, (-1, embed_dim))
return word_input, ids, masks, lengths | [
"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",
"=",
"max_sequence_length",
"word_input",
"=",
"np",
".",
"zeros",
"(",
"(",
"max_sequence_length",
",",
"batch_size",
",",
"embed_dim",
")",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"ids",
"=",
"np",
".",
"zeros",
"(",
"(",
"sequence_length",
",",
"batch_size",
")",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
"masks",
"=",
"np",
".",
"zeros",
"(",
"(",
"sequence_length",
",",
"batch_size",
")",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"lengths",
"=",
"np",
".",
"zeros",
"(",
"[",
"batch_size",
"]",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
"for",
"batch_idx",
"in",
"range",
"(",
"0",
",",
"min",
"(",
"len",
"(",
"data",
")",
",",
"batch_size",
")",
")",
":",
"batch_data",
"=",
"data",
"[",
"batch_idx",
"]",
"lengths",
"[",
"batch_idx",
"]",
"=",
"len",
"(",
"batch_data",
")",
"for",
"sample_idx",
"in",
"range",
"(",
"0",
",",
"min",
"(",
"len",
"(",
"batch_data",
")",
",",
"sequence_length",
")",
")",
":",
"word",
"=",
"batch_data",
"[",
"sample_idx",
"]",
"[",
"'word'",
"]",
".",
"lower",
"(",
")",
"if",
"word",
"in",
"word_dict",
".",
"keys",
"(",
")",
":",
"word_input",
"[",
"sample_idx",
",",
"batch_idx",
"]",
"=",
"embed",
"[",
"word_dict",
"[",
"word",
"]",
"]",
"ids",
"[",
"sample_idx",
",",
"batch_idx",
"]",
"=",
"word_dict",
"[",
"word",
"]",
"masks",
"[",
"sample_idx",
",",
"batch_idx",
"]",
"=",
"1",
"word_input",
"=",
"np",
".",
"reshape",
"(",
"word_input",
",",
"(",
"-",
"1",
",",
"embed_dim",
")",
")",
"return",
"word_input",
",",
"ids",
",",
"masks",
",",
"lengths"
] | 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'",
"]",
"<=",
"char_index",
"and",
"char_index",
"<=",
"token",
"[",
"'char_end'",
"]",
":",
"return",
"i",
"return",
"0"
] | 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_begin)
word_end = get_word_index(tokens, char_end)
begin.append(word_begin)
end.append(word_end)
return np.asarray(begin), np.asarray(end) | 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_begin)
word_end = get_word_index(tokens, char_end)
begin.append(word_begin)
end.append(word_end)
return np.asarray(begin), np.asarray(end) | [
"def",
"get_answer_begin_end",
"(",
"data",
")",
":",
"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_begin",
")",
"word_end",
"=",
"get_word_index",
"(",
"tokens",
",",
"char_end",
")",
"begin",
".",
"append",
"(",
"word_begin",
")",
"end",
".",
"append",
"(",
"word_end",
")",
"return",
"np",
".",
"asarray",
"(",
"begin",
")",
",",
"np",
".",
"asarray",
"(",
"end",
")"
] | 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)]
buckets[-1] = max_length
return buckets | 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)]
buckets[-1] = max_length
return buckets | [
"def",
"get_buckets",
"(",
"min_length",
",",
"max_length",
",",
"bucket_count",
")",
":",
"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",
")",
"]",
"buckets",
"[",
"-",
"1",
"]",
"=",
"max_length",
"return",
"buckets"
] | 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]
tokens.append({
'word': word,
'original_text': word,
'char_begin': start,
'char_end': i})
start = -1
else:
if start < 0:
start = i
if start >= 0:
tokens.append({
'word': text[start:len(text)],
'original_text': text[start:len(text)],
'char_begin': start,
'char_end': len(text)
})
return tokens | 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]
tokens.append({
'word': word,
'original_text': word,
'char_begin': start,
'char_end': i})
start = -1
else:
if start < 0:
start = i
if start >= 0:
tokens.append({
'word': text[start:len(text)],
'original_text': text[start:len(text)],
'char_begin': start,
'char_end': len(text)
})
return tokens | [
"def",
"tokenize",
"(",
"self",
",",
"text",
")",
":",
"start",
"=",
"-",
"1",
"tokens",
"=",
"[",
"]",
"for",
"i",
",",
"character",
"in",
"enumerate",
"(",
"text",
")",
":",
"if",
"character",
"==",
"' '",
"or",
"character",
"==",
"'\\t'",
":",
"if",
"start",
">=",
"0",
":",
"word",
"=",
"text",
"[",
"start",
":",
"i",
"]",
"tokens",
".",
"append",
"(",
"{",
"'word'",
":",
"word",
",",
"'original_text'",
":",
"word",
",",
"'char_begin'",
":",
"start",
",",
"'char_end'",
":",
"i",
"}",
")",
"start",
"=",
"-",
"1",
"else",
":",
"if",
"start",
"<",
"0",
":",
"start",
"=",
"i",
"if",
"start",
">=",
"0",
":",
"tokens",
".",
"append",
"(",
"{",
"'word'",
":",
"text",
"[",
"start",
":",
"len",
"(",
"text",
")",
"]",
",",
"'original_text'",
":",
"text",
"[",
"start",
":",
"len",
"(",
"text",
")",
"]",
",",
"'char_begin'",
":",
"start",
",",
"'char_end'",
":",
"len",
"(",
"text",
")",
"}",
")",
"return",
"tokens"
] | 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, output=[4, 5], size='x'), Layer(LayerType.input.value, output=[4, 5], size='y')],
output=[Layer(LayerType.output.value, inputs=[4], size='x'), Layer(LayerType.output.value, inputs=[5], size='y')],
hide=[Layer(LayerType.attention.value, inputs=[0, 1], output=[2]),
Layer(LayerType.attention.value, inputs=[1, 0], output=[3])])
for _ in range(population_size):
graph_tmp = copy.deepcopy(graph)
graph_tmp.mutation()
population.append(Individual(indiv_id=self.generate_new_id(), graph_cfg=graph_tmp, result=None))
return population | 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, output=[4, 5], size='x'), Layer(LayerType.input.value, output=[4, 5], size='y')],
output=[Layer(LayerType.output.value, inputs=[4], size='x'), Layer(LayerType.output.value, inputs=[5], size='y')],
hide=[Layer(LayerType.attention.value, inputs=[0, 1], output=[2]),
Layer(LayerType.attention.value, inputs=[1, 0], output=[3])])
for _ in range(population_size):
graph_tmp = copy.deepcopy(graph)
graph_tmp.mutation()
population.append(Individual(indiv_id=self.generate_new_id(), graph_cfg=graph_tmp, result=None))
return population | [
"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",
",",
"inputs",
"=",
"[",
"Layer",
"(",
"LayerType",
".",
"input",
".",
"value",
",",
"output",
"=",
"[",
"4",
",",
"5",
"]",
",",
"size",
"=",
"'x'",
")",
",",
"Layer",
"(",
"LayerType",
".",
"input",
".",
"value",
",",
"output",
"=",
"[",
"4",
",",
"5",
"]",
",",
"size",
"=",
"'y'",
")",
"]",
",",
"output",
"=",
"[",
"Layer",
"(",
"LayerType",
".",
"output",
".",
"value",
",",
"inputs",
"=",
"[",
"4",
"]",
",",
"size",
"=",
"'x'",
")",
",",
"Layer",
"(",
"LayerType",
".",
"output",
".",
"value",
",",
"inputs",
"=",
"[",
"5",
"]",
",",
"size",
"=",
"'y'",
")",
"]",
",",
"hide",
"=",
"[",
"Layer",
"(",
"LayerType",
".",
"attention",
".",
"value",
",",
"inputs",
"=",
"[",
"0",
",",
"1",
"]",
",",
"output",
"=",
"[",
"2",
"]",
")",
",",
"Layer",
"(",
"LayerType",
".",
"attention",
".",
"value",
",",
"inputs",
"=",
"[",
"1",
",",
"0",
"]",
",",
"output",
"=",
"[",
"3",
"]",
")",
"]",
")",
"for",
"_",
"in",
"range",
"(",
"population_size",
")",
":",
"graph_tmp",
"=",
"copy",
".",
"deepcopy",
"(",
"graph",
")",
"graph_tmp",
".",
"mutation",
"(",
")",
"population",
".",
"append",
"(",
"Individual",
"(",
"indiv_id",
"=",
"self",
".",
"generate_new_id",
"(",
")",
",",
"graph_cfg",
"=",
"graph_tmp",
",",
"result",
"=",
"None",
")",
")",
"return",
"population"
] | 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.Error, 'List hdfs directory {0} error: {1}'.format(hdfsDirectory, str(exception)))
raise exception
for f in listing:
if f.type == 'DIRECTORY':
subHdfsDirectory = posixpath.join(hdfsDirectory, f.pathSuffix)
subLocalDirectory = os.path.join(localDirectory, f.pathSuffix)
copyHdfsDirectoryToLocal(subHdfsDirectory, subLocalDirectory, hdfsClient)
elif f.type == 'FILE':
hdfsFilePath = posixpath.join(hdfsDirectory, f.pathSuffix)
localFilePath = os.path.join(localDirectory, f.pathSuffix)
copyHdfsFileToLocal(hdfsFilePath, localFilePath, hdfsClient)
else:
raise AssertionError('unexpected type {}'.format(f.type)) | 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.Error, 'List hdfs directory {0} error: {1}'.format(hdfsDirectory, str(exception)))
raise exception
for f in listing:
if f.type == 'DIRECTORY':
subHdfsDirectory = posixpath.join(hdfsDirectory, f.pathSuffix)
subLocalDirectory = os.path.join(localDirectory, f.pathSuffix)
copyHdfsDirectoryToLocal(subHdfsDirectory, subLocalDirectory, hdfsClient)
elif f.type == 'FILE':
hdfsFilePath = posixpath.join(hdfsDirectory, f.pathSuffix)
localFilePath = os.path.join(localDirectory, f.pathSuffix)
copyHdfsFileToLocal(hdfsFilePath, localFilePath, hdfsClient)
else:
raise AssertionError('unexpected type {}'.format(f.type)) | [
"def",
"copyHdfsDirectoryToLocal",
"(",
"hdfsDirectory",
",",
"localDirectory",
",",
"hdfsClient",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"localDirectory",
")",
":",
"os",
".",
"makedirs",
"(",
"localDirectory",
")",
"try",
":",
"listing",
"=",
"hdfsClient",
".",
"list_status",
"(",
"hdfsDirectory",
")",
"except",
"Exception",
"as",
"exception",
":",
"nni_log",
"(",
"LogType",
".",
"Error",
",",
"'List hdfs directory {0} error: {1}'",
".",
"format",
"(",
"hdfsDirectory",
",",
"str",
"(",
"exception",
")",
")",
")",
"raise",
"exception",
"for",
"f",
"in",
"listing",
":",
"if",
"f",
".",
"type",
"==",
"'DIRECTORY'",
":",
"subHdfsDirectory",
"=",
"posixpath",
".",
"join",
"(",
"hdfsDirectory",
",",
"f",
".",
"pathSuffix",
")",
"subLocalDirectory",
"=",
"os",
".",
"path",
".",
"join",
"(",
"localDirectory",
",",
"f",
".",
"pathSuffix",
")",
"copyHdfsDirectoryToLocal",
"(",
"subHdfsDirectory",
",",
"subLocalDirectory",
",",
"hdfsClient",
")",
"elif",
"f",
".",
"type",
"==",
"'FILE'",
":",
"hdfsFilePath",
"=",
"posixpath",
".",
"join",
"(",
"hdfsDirectory",
",",
"f",
".",
"pathSuffix",
")",
"localFilePath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"localDirectory",
",",
"f",
".",
"pathSuffix",
")",
"copyHdfsFileToLocal",
"(",
"hdfsFilePath",
",",
"localFilePath",
",",
"hdfsClient",
")",
"else",
":",
"raise",
"AssertionError",
"(",
"'unexpected type {}'",
".",
"format",
"(",
"f",
".",
"type",
")",
")"
] | 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)
if file_status.type != 'FILE':
raise Exception('HDFS file path {} is not a file'.format(hdfsFilePath))
except Exception as exception:
nni_log(LogType.Error, 'Get hdfs file {0} status error: {1}'.format(hdfsFilePath, str(exception)))
raise exception
if os.path.exists(localFilePath) and override:
os.remove(localFilePath)
try:
hdfsClient.copy_to_local(hdfsFilePath, localFilePath)
except Exception as exception:
nni_log(LogType.Error, 'Copy hdfs file {0} to {1} error: {2}'.format(hdfsFilePath, localFilePath, str(exception)))
raise exception
nni_log(LogType.Info, 'Successfully copied hdfs file {0} to {1}, {2} bytes'.format(hdfsFilePath, localFilePath, file_status.length)) | 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)
if file_status.type != 'FILE':
raise Exception('HDFS file path {} is not a file'.format(hdfsFilePath))
except Exception as exception:
nni_log(LogType.Error, 'Get hdfs file {0} status error: {1}'.format(hdfsFilePath, str(exception)))
raise exception
if os.path.exists(localFilePath) and override:
os.remove(localFilePath)
try:
hdfsClient.copy_to_local(hdfsFilePath, localFilePath)
except Exception as exception:
nni_log(LogType.Error, 'Copy hdfs file {0} to {1} error: {2}'.format(hdfsFilePath, localFilePath, str(exception)))
raise exception
nni_log(LogType.Info, 'Successfully copied hdfs file {0} to {1}, {2} bytes'.format(hdfsFilePath, localFilePath, file_status.length)) | [
"def",
"copyHdfsFileToLocal",
"(",
"hdfsFilePath",
",",
"localFilePath",
",",
"hdfsClient",
",",
"override",
"=",
"True",
")",
":",
"if",
"not",
"hdfsClient",
".",
"exists",
"(",
"hdfsFilePath",
")",
":",
"raise",
"Exception",
"(",
"'HDFS file {} does not exist!'",
".",
"format",
"(",
"hdfsFilePath",
")",
")",
"try",
":",
"file_status",
"=",
"hdfsClient",
".",
"get_file_status",
"(",
"hdfsFilePath",
")",
"if",
"file_status",
".",
"type",
"!=",
"'FILE'",
":",
"raise",
"Exception",
"(",
"'HDFS file path {} is not a file'",
".",
"format",
"(",
"hdfsFilePath",
")",
")",
"except",
"Exception",
"as",
"exception",
":",
"nni_log",
"(",
"LogType",
".",
"Error",
",",
"'Get hdfs file {0} status error: {1}'",
".",
"format",
"(",
"hdfsFilePath",
",",
"str",
"(",
"exception",
")",
")",
")",
"raise",
"exception",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"localFilePath",
")",
"and",
"override",
":",
"os",
".",
"remove",
"(",
"localFilePath",
")",
"try",
":",
"hdfsClient",
".",
"copy_to_local",
"(",
"hdfsFilePath",
",",
"localFilePath",
")",
"except",
"Exception",
"as",
"exception",
":",
"nni_log",
"(",
"LogType",
".",
"Error",
",",
"'Copy hdfs file {0} to {1} error: {2}'",
".",
"format",
"(",
"hdfsFilePath",
",",
"localFilePath",
",",
"str",
"(",
"exception",
")",
")",
")",
"raise",
"exception",
"nni_log",
"(",
"LogType",
".",
"Info",
",",
"'Successfully copied hdfs file {0} to {1}, {2} bytes'",
".",
"format",
"(",
"hdfsFilePath",
",",
"localFilePath",
",",
"file_status",
".",
"length",
")",
")"
] | 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):
file_path = os.path.join(localDirectory, file)
if os.path.isdir(file_path):
hdfs_directory = os.path.join(hdfsDirectory, file)
try:
result = result and copyDirectoryToHdfs(file_path, hdfs_directory, hdfsClient)
except Exception as exception:
nni_log(LogType.Error, 'Copy local directory {0} to hdfs directory {1} error: {2}'.format(file_path, hdfs_directory, str(exception)))
result = False
else:
hdfs_file_path = os.path.join(hdfsDirectory, file)
try:
result = result and copyFileToHdfs(file_path, hdfs_file_path, hdfsClient)
except Exception as exception:
nni_log(LogType.Error, 'Copy local file {0} to hdfs {1} error: {2}'.format(file_path, hdfs_file_path, str(exception)))
result = False
return result | 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):
file_path = os.path.join(localDirectory, file)
if os.path.isdir(file_path):
hdfs_directory = os.path.join(hdfsDirectory, file)
try:
result = result and copyDirectoryToHdfs(file_path, hdfs_directory, hdfsClient)
except Exception as exception:
nni_log(LogType.Error, 'Copy local directory {0} to hdfs directory {1} error: {2}'.format(file_path, hdfs_directory, str(exception)))
result = False
else:
hdfs_file_path = os.path.join(hdfsDirectory, file)
try:
result = result and copyFileToHdfs(file_path, hdfs_file_path, hdfsClient)
except Exception as exception:
nni_log(LogType.Error, 'Copy local file {0} to hdfs {1} error: {2}'.format(file_path, hdfs_file_path, str(exception)))
result = False
return result | [
"def",
"copyDirectoryToHdfs",
"(",
"localDirectory",
",",
"hdfsDirectory",
",",
"hdfsClient",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"localDirectory",
")",
":",
"raise",
"Exception",
"(",
"'Local Directory does not exist!'",
")",
"hdfsClient",
".",
"mkdirs",
"(",
"hdfsDirectory",
")",
"result",
"=",
"True",
"for",
"file",
"in",
"os",
".",
"listdir",
"(",
"localDirectory",
")",
":",
"file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"localDirectory",
",",
"file",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"file_path",
")",
":",
"hdfs_directory",
"=",
"os",
".",
"path",
".",
"join",
"(",
"hdfsDirectory",
",",
"file",
")",
"try",
":",
"result",
"=",
"result",
"and",
"copyDirectoryToHdfs",
"(",
"file_path",
",",
"hdfs_directory",
",",
"hdfsClient",
")",
"except",
"Exception",
"as",
"exception",
":",
"nni_log",
"(",
"LogType",
".",
"Error",
",",
"'Copy local directory {0} to hdfs directory {1} error: {2}'",
".",
"format",
"(",
"file_path",
",",
"hdfs_directory",
",",
"str",
"(",
"exception",
")",
")",
")",
"result",
"=",
"False",
"else",
":",
"hdfs_file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"hdfsDirectory",
",",
"file",
")",
"try",
":",
"result",
"=",
"result",
"and",
"copyFileToHdfs",
"(",
"file_path",
",",
"hdfs_file_path",
",",
"hdfsClient",
")",
"except",
"Exception",
"as",
"exception",
":",
"nni_log",
"(",
"LogType",
".",
"Error",
",",
"'Copy local file {0} to hdfs {1} error: {2}'",
".",
"format",
"(",
"file_path",
",",
"hdfs_file_path",
",",
"str",
"(",
"exception",
")",
")",
")",
"result",
"=",
"False",
"return",
"result"
] | 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!')
if hdfsClient.exists(hdfsFilePath):
if override:
hdfsClient.delete(hdfsFilePath)
else:
return False
try:
hdfsClient.copy_from_local(localFilePath, hdfsFilePath)
return True
except Exception as exception:
nni_log(LogType.Error, 'Copy local file {0} to hdfs file {1} error: {2}'.format(localFilePath, hdfsFilePath, str(exception)))
return False | 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!')
if hdfsClient.exists(hdfsFilePath):
if override:
hdfsClient.delete(hdfsFilePath)
else:
return False
try:
hdfsClient.copy_from_local(localFilePath, hdfsFilePath)
return True
except Exception as exception:
nni_log(LogType.Error, 'Copy local file {0} to hdfs file {1} error: {2}'.format(localFilePath, hdfsFilePath, str(exception)))
return False | [
"def",
"copyFileToHdfs",
"(",
"localFilePath",
",",
"hdfsFilePath",
",",
"hdfsClient",
",",
"override",
"=",
"True",
")",
":",
"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!'",
")",
"if",
"hdfsClient",
".",
"exists",
"(",
"hdfsFilePath",
")",
":",
"if",
"override",
":",
"hdfsClient",
".",
"delete",
"(",
"hdfsFilePath",
")",
"else",
":",
"return",
"False",
"try",
":",
"hdfsClient",
".",
"copy_from_local",
"(",
"localFilePath",
",",
"hdfsFilePath",
")",
"return",
"True",
"except",
"Exception",
"as",
"exception",
":",
"nni_log",
"(",
"LogType",
".",
"Error",
",",
"'Copy local file {0} to hdfs file {1} error: {2}'",
".",
"format",
"(",
"localFilePath",
",",
"hdfsFilePath",
",",
"str",
"(",
"exception",
")",
")",
")",
"return",
"False"
] | 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_train)
X_test = ss_X.transform(X_test)
y_train = ss_y.fit_transform(y_train[:, None])[:,0]
y_test = ss_y.transform(y_test[:, None])[:,0]
return X_train, X_test, y_train, y_test | 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_train)
X_test = ss_X.transform(X_test)
y_train = ss_y.fit_transform(y_train[:, None])[:,0]
y_test = ss_y.transform(y_test[:, None])[:,0]
return X_train, X_test, y_train, y_test | [
"def",
"load_data",
"(",
")",
":",
"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_train",
")",
"X_test",
"=",
"ss_X",
".",
"transform",
"(",
"X_test",
")",
"y_train",
"=",
"ss_y",
".",
"fit_transform",
"(",
"y_train",
"[",
":",
",",
"None",
"]",
")",
"[",
":",
",",
"0",
"]",
"y_test",
"=",
"ss_y",
".",
"transform",
"(",
"y_test",
"[",
":",
",",
"None",
"]",
")",
"[",
":",
",",
"0",
"]",
"return",
"X_train",
",",
"X_test",
",",
"y_train",
",",
"y_test"
] | 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",
"(",
"y_test",
",",
"predict_y",
")",
"LOG",
".",
"debug",
"(",
"'r2 score: %s'",
"%",
"score",
")",
"nni",
".",
"report_final_result",
"(",
"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",
",",
"\"type\"",
":",
"connection_type",
"}",
")",
"return",
"{",
"\"node_list\"",
":",
"self",
".",
"layers",
",",
"\"skip_list\"",
":",
"skip_list",
"}"
] | 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_id_to_input_node_ids[layer_id].append(input_id)
if output_id not in self.layer_id_to_output_node_ids[layer_id]:
self.layer_id_to_output_node_ids[layer_id].append(output_id)
else:
layer_id = len(self.layer_list)
self.layer_list.append(layer)
self.layer_to_id[layer] = layer_id
self.layer_id_to_input_node_ids[layer_id] = [input_id]
self.layer_id_to_output_node_ids[layer_id] = [output_id]
self.adj_list[input_id].append((output_id, layer_id))
self.reverse_adj_list[output_id].append((input_id, layer_id)) | 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_id_to_input_node_ids[layer_id].append(input_id)
if output_id not in self.layer_id_to_output_node_ids[layer_id]:
self.layer_id_to_output_node_ids[layer_id].append(output_id)
else:
layer_id = len(self.layer_list)
self.layer_list.append(layer)
self.layer_to_id[layer] = layer_id
self.layer_id_to_input_node_ids[layer_id] = [input_id]
self.layer_id_to_output_node_ids[layer_id] = [output_id]
self.adj_list[input_id].append((output_id, layer_id))
self.reverse_adj_list[output_id].append((input_id, layer_id)) | [
"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",
".",
"layer_id_to_input_node_ids",
"[",
"layer_id",
"]",
":",
"self",
".",
"layer_id_to_input_node_ids",
"[",
"layer_id",
"]",
".",
"append",
"(",
"input_id",
")",
"if",
"output_id",
"not",
"in",
"self",
".",
"layer_id_to_output_node_ids",
"[",
"layer_id",
"]",
":",
"self",
".",
"layer_id_to_output_node_ids",
"[",
"layer_id",
"]",
".",
"append",
"(",
"output_id",
")",
"else",
":",
"layer_id",
"=",
"len",
"(",
"self",
".",
"layer_list",
")",
"self",
".",
"layer_list",
".",
"append",
"(",
"layer",
")",
"self",
".",
"layer_to_id",
"[",
"layer",
"]",
"=",
"layer_id",
"self",
".",
"layer_id_to_input_node_ids",
"[",
"layer_id",
"]",
"=",
"[",
"input_id",
"]",
"self",
".",
"layer_id_to_output_node_ids",
"[",
"layer_id",
"]",
"=",
"[",
"output_id",
"]",
"self",
".",
"adj_list",
"[",
"input_id",
"]",
".",
"append",
"(",
"(",
"output_id",
",",
"layer_id",
")",
")",
"self",
".",
"reverse_adj_list",
"[",
"output_id",
"]",
".",
"append",
"(",
"(",
"input_id",
",",
"layer_id",
")",
")"
] | 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 enumerate(self.adj_list[u_id]):
if edge_tuple[0] == v_id:
layer_id = edge_tuple[1]
self.adj_list[u_id][index] = (new_v_id, layer_id)
self.layer_list[layer_id].output = self.node_list[new_v_id]
break
for index, edge_tuple in enumerate(self.reverse_adj_list[v_id]):
if edge_tuple[0] == u_id:
layer_id = edge_tuple[1]
self.reverse_adj_list[v_id].remove(edge_tuple)
break
self.reverse_adj_list[new_v_id].append((u_id, layer_id))
for index, value in enumerate(self.layer_id_to_output_node_ids[layer_id]):
if value == v_id:
self.layer_id_to_output_node_ids[layer_id][index] = new_v_id
break | 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 enumerate(self.adj_list[u_id]):
if edge_tuple[0] == v_id:
layer_id = edge_tuple[1]
self.adj_list[u_id][index] = (new_v_id, layer_id)
self.layer_list[layer_id].output = self.node_list[new_v_id]
break
for index, edge_tuple in enumerate(self.reverse_adj_list[v_id]):
if edge_tuple[0] == u_id:
layer_id = edge_tuple[1]
self.reverse_adj_list[v_id].remove(edge_tuple)
break
self.reverse_adj_list[new_v_id].append((u_id, layer_id))
for index, value in enumerate(self.layer_id_to_output_node_ids[layer_id]):
if value == v_id:
self.layer_id_to_output_node_ids[layer_id][index] = new_v_id
break | [
"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",
"[",
"0",
"]",
"==",
"v_id",
":",
"layer_id",
"=",
"edge_tuple",
"[",
"1",
"]",
"self",
".",
"adj_list",
"[",
"u_id",
"]",
"[",
"index",
"]",
"=",
"(",
"new_v_id",
",",
"layer_id",
")",
"self",
".",
"layer_list",
"[",
"layer_id",
"]",
".",
"output",
"=",
"self",
".",
"node_list",
"[",
"new_v_id",
"]",
"break",
"for",
"index",
",",
"edge_tuple",
"in",
"enumerate",
"(",
"self",
".",
"reverse_adj_list",
"[",
"v_id",
"]",
")",
":",
"if",
"edge_tuple",
"[",
"0",
"]",
"==",
"u_id",
":",
"layer_id",
"=",
"edge_tuple",
"[",
"1",
"]",
"self",
".",
"reverse_adj_list",
"[",
"v_id",
"]",
".",
"remove",
"(",
"edge_tuple",
")",
"break",
"self",
".",
"reverse_adj_list",
"[",
"new_v_id",
"]",
".",
"append",
"(",
"(",
"u_id",
",",
"layer_id",
")",
")",
"for",
"index",
",",
"value",
"in",
"enumerate",
"(",
"self",
".",
"layer_id_to_output_node_ids",
"[",
"layer_id",
"]",
")",
":",
"if",
"value",
"==",
"v_id",
":",
"self",
".",
"layer_id_to_output_node_ids",
"[",
"layer_id",
"]",
"[",
"index",
"]",
"=",
"new_v_id",
"break"
] | 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",
"the",
"same",
"."
] | 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] = new_layer
self.layer_to_id[new_layer] = layer_id
self.layer_to_id.pop(old_layer) | 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] = new_layer
self.layer_to_id[new_layer] = layer_id
self.layer_to_id.pop(old_layer) | [
"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",
".",
"output",
"new_layer",
".",
"output",
".",
"shape",
"=",
"new_layer",
".",
"output_shape",
"self",
".",
"layer_list",
"[",
"layer_id",
"]",
"=",
"new_layer",
"self",
".",
"layer_to_id",
"[",
"new_layer",
"]",
"=",
"layer_id",
"self",
".",
"layer_to_id",
".",
"pop",
"(",
"old_layer",
")"
] | 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]:
in_degree[v] += 1
for i in range(self.n_nodes):
if in_degree[i] == 0:
q.put(i)
order_list = []
while not q.empty():
u = q.get()
order_list.append(u)
for v, _ in self.adj_list[u]:
in_degree[v] -= 1
if in_degree[v] == 0:
q.put(v)
return order_list | 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]:
in_degree[v] += 1
for i in range(self.n_nodes):
if in_degree[i] == 0:
q.put(i)
order_list = []
while not q.empty():
u = q.get()
order_list.append(u)
for v, _ in self.adj_list[u]:
in_degree[v] -= 1
if in_degree[v] == 0:
q.put(v)
return order_list | [
"def",
"topological_order",
"(",
"self",
")",
":",
"q",
"=",
"Queue",
"(",
")",
"in_degree",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"n_nodes",
")",
":",
"in_degree",
"[",
"i",
"]",
"=",
"0",
"for",
"u",
"in",
"range",
"(",
"self",
".",
"n_nodes",
")",
":",
"for",
"v",
",",
"_",
"in",
"self",
".",
"adj_list",
"[",
"u",
"]",
":",
"in_degree",
"[",
"v",
"]",
"+=",
"1",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"n_nodes",
")",
":",
"if",
"in_degree",
"[",
"i",
"]",
"==",
"0",
":",
"q",
".",
"put",
"(",
"i",
")",
"order_list",
"=",
"[",
"]",
"while",
"not",
"q",
".",
"empty",
"(",
")",
":",
"u",
"=",
"q",
".",
"get",
"(",
")",
"order_list",
".",
"append",
"(",
"u",
")",
"for",
"v",
",",
"_",
"in",
"self",
".",
"adj_list",
"[",
"u",
"]",
":",
"in_degree",
"[",
"v",
"]",
"-=",
"1",
"if",
"in_degree",
"[",
"v",
"]",
"==",
"0",
":",
"q",
".",
"put",
"(",
"v",
")",
"return",
"order_list"
] | 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_list:
layer = self.layer_list[layer_id]
if is_layer(layer, "Pooling"):
ret.append(layer)
elif is_layer(layer, "Conv") and layer.stride != 1:
ret.append(layer)
return ret | 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_list:
layer = self.layer_list[layer_id]
if is_layer(layer, "Pooling"):
ret.append(layer)
elif is_layer(layer, "Conv") and layer.stride != 1:
ret.append(layer)
return ret | [
"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",
",",
"node_list",
")",
"ret",
"=",
"[",
"]",
"for",
"layer_id",
"in",
"layer_list",
":",
"layer",
"=",
"self",
".",
"layer_list",
"[",
"layer_id",
"]",
"if",
"is_layer",
"(",
"layer",
",",
"\"Pooling\"",
")",
":",
"ret",
".",
"append",
"(",
"layer",
")",
"elif",
"is_layer",
"(",
"layer",
",",
"\"Conv\"",
")",
"and",
"layer",
".",
"stride",
"!=",
"1",
":",
"ret",
".",
"append",
"(",
"layer",
")",
"return",
"ret"
] | 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
u = node_list[-1]
if u == target_id:
return True
for v, layer_id in self.adj_list[u]:
layer_id_list.append(layer_id)
node_list.append(v)
if self._depth_first_search(target_id, layer_id_list, node_list):
return True
layer_id_list.pop()
node_list.pop()
return False | 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
u = node_list[-1]
if u == target_id:
return True
for v, layer_id in self.adj_list[u]:
layer_id_list.append(layer_id)
node_list.append(v)
if self._depth_first_search(target_id, layer_id_list, node_list):
return True
layer_id_list.pop()
node_list.pop()
return False | [
"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",
":",
"return",
"True",
"for",
"v",
",",
"layer_id",
"in",
"self",
".",
"adj_list",
"[",
"u",
"]",
":",
"layer_id_list",
".",
"append",
"(",
"layer_id",
")",
"node_list",
".",
"append",
"(",
"v",
")",
"if",
"self",
".",
"_depth_first_search",
"(",
"target_id",
",",
"layer_id_list",
",",
"node_list",
")",
":",
"return",
"True",
"layer_id_list",
".",
"pop",
"(",
")",
"node_list",
".",
"pop",
"(",
")",
"return",
"False"
] | 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",
"target_id",
"."
] | 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 = self.add_layer(layer, temp_output_id)
self._add_edge(new_layers[-1], temp_output_id, end_node_id)
new_layers[-1].input = self.node_list[temp_output_id]
new_layers[-1].output = self.node_list[end_node_id]
self._redirect_edge(start_node_id, end_node_id, new_node_id) | 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 = self.add_layer(layer, temp_output_id)
self._add_edge(new_layers[-1], temp_output_id, end_node_id)
new_layers[-1].input = self.node_list[temp_output_id]
new_layers[-1].output = self.node_list[end_node_id]
self._redirect_edge(start_node_id, end_node_id, new_node_id) | [
"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",
"=",
"new_node_id",
"for",
"layer",
"in",
"new_layers",
"[",
":",
"-",
"1",
"]",
":",
"temp_output_id",
"=",
"self",
".",
"add_layer",
"(",
"layer",
",",
"temp_output_id",
")",
"self",
".",
"_add_edge",
"(",
"new_layers",
"[",
"-",
"1",
"]",
",",
"temp_output_id",
",",
"end_node_id",
")",
"new_layers",
"[",
"-",
"1",
"]",
".",
"input",
"=",
"self",
".",
"node_list",
"[",
"temp_output_id",
"]",
"new_layers",
"[",
"-",
"1",
"]",
".",
"output",
"=",
"self",
".",
"node_list",
"[",
"end_node_id",
"]",
"self",
".",
"_redirect_edge",
"(",
"start_node_id",
",",
"end_node_id",
",",
"new_node_id",
")"
] | 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()
for u in main_chain:
for v, layer_id in self.adj_list[u]:
if v not in index_in_main_chain:
continue
layer = self.layer_list[layer_id]
copied_layer = copy(layer)
copied_layer.weights = None
ret.add_layer(deepcopy(copied_layer))
for u in index_in_main_chain:
for v, layer_id in self.adj_list[u]:
if v not in index_in_main_chain:
temp_u = u
temp_v = v
temp_layer_id = layer_id
skip_type = None
while not (temp_v in index_in_main_chain and temp_u in index_in_main_chain):
if is_layer(self.layer_list[temp_layer_id], "Concatenate"):
skip_type = NetworkDescriptor.CONCAT_CONNECT
if is_layer(self.layer_list[temp_layer_id], "Add"):
skip_type = NetworkDescriptor.ADD_CONNECT
temp_u = temp_v
temp_v, temp_layer_id = self.adj_list[temp_v][0]
ret.add_skip_connection(
index_in_main_chain[u], index_in_main_chain[temp_u], skip_type
)
elif index_in_main_chain[v] - index_in_main_chain[u] != 1:
skip_type = None
if is_layer(self.layer_list[layer_id], "Concatenate"):
skip_type = NetworkDescriptor.CONCAT_CONNECT
if is_layer(self.layer_list[layer_id], "Add"):
skip_type = NetworkDescriptor.ADD_CONNECT
ret.add_skip_connection(
index_in_main_chain[u], index_in_main_chain[v], skip_type
)
return ret | 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()
for u in main_chain:
for v, layer_id in self.adj_list[u]:
if v not in index_in_main_chain:
continue
layer = self.layer_list[layer_id]
copied_layer = copy(layer)
copied_layer.weights = None
ret.add_layer(deepcopy(copied_layer))
for u in index_in_main_chain:
for v, layer_id in self.adj_list[u]:
if v not in index_in_main_chain:
temp_u = u
temp_v = v
temp_layer_id = layer_id
skip_type = None
while not (temp_v in index_in_main_chain and temp_u in index_in_main_chain):
if is_layer(self.layer_list[temp_layer_id], "Concatenate"):
skip_type = NetworkDescriptor.CONCAT_CONNECT
if is_layer(self.layer_list[temp_layer_id], "Add"):
skip_type = NetworkDescriptor.ADD_CONNECT
temp_u = temp_v
temp_v, temp_layer_id = self.adj_list[temp_v][0]
ret.add_skip_connection(
index_in_main_chain[u], index_in_main_chain[temp_u], skip_type
)
elif index_in_main_chain[v] - index_in_main_chain[u] != 1:
skip_type = None
if is_layer(self.layer_list[layer_id], "Concatenate"):
skip_type = NetworkDescriptor.CONCAT_CONNECT
if is_layer(self.layer_list[layer_id], "Add"):
skip_type = NetworkDescriptor.ADD_CONNECT
ret.add_skip_connection(
index_in_main_chain[u], index_in_main_chain[v], skip_type
)
return ret | [
"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",
"]",
"=",
"index",
"ret",
"=",
"NetworkDescriptor",
"(",
")",
"for",
"u",
"in",
"main_chain",
":",
"for",
"v",
",",
"layer_id",
"in",
"self",
".",
"adj_list",
"[",
"u",
"]",
":",
"if",
"v",
"not",
"in",
"index_in_main_chain",
":",
"continue",
"layer",
"=",
"self",
".",
"layer_list",
"[",
"layer_id",
"]",
"copied_layer",
"=",
"copy",
"(",
"layer",
")",
"copied_layer",
".",
"weights",
"=",
"None",
"ret",
".",
"add_layer",
"(",
"deepcopy",
"(",
"copied_layer",
")",
")",
"for",
"u",
"in",
"index_in_main_chain",
":",
"for",
"v",
",",
"layer_id",
"in",
"self",
".",
"adj_list",
"[",
"u",
"]",
":",
"if",
"v",
"not",
"in",
"index_in_main_chain",
":",
"temp_u",
"=",
"u",
"temp_v",
"=",
"v",
"temp_layer_id",
"=",
"layer_id",
"skip_type",
"=",
"None",
"while",
"not",
"(",
"temp_v",
"in",
"index_in_main_chain",
"and",
"temp_u",
"in",
"index_in_main_chain",
")",
":",
"if",
"is_layer",
"(",
"self",
".",
"layer_list",
"[",
"temp_layer_id",
"]",
",",
"\"Concatenate\"",
")",
":",
"skip_type",
"=",
"NetworkDescriptor",
".",
"CONCAT_CONNECT",
"if",
"is_layer",
"(",
"self",
".",
"layer_list",
"[",
"temp_layer_id",
"]",
",",
"\"Add\"",
")",
":",
"skip_type",
"=",
"NetworkDescriptor",
".",
"ADD_CONNECT",
"temp_u",
"=",
"temp_v",
"temp_v",
",",
"temp_layer_id",
"=",
"self",
".",
"adj_list",
"[",
"temp_v",
"]",
"[",
"0",
"]",
"ret",
".",
"add_skip_connection",
"(",
"index_in_main_chain",
"[",
"u",
"]",
",",
"index_in_main_chain",
"[",
"temp_u",
"]",
",",
"skip_type",
")",
"elif",
"index_in_main_chain",
"[",
"v",
"]",
"-",
"index_in_main_chain",
"[",
"u",
"]",
"!=",
"1",
":",
"skip_type",
"=",
"None",
"if",
"is_layer",
"(",
"self",
".",
"layer_list",
"[",
"layer_id",
"]",
",",
"\"Concatenate\"",
")",
":",
"skip_type",
"=",
"NetworkDescriptor",
".",
"CONCAT_CONNECT",
"if",
"is_layer",
"(",
"self",
".",
"layer_list",
"[",
"layer_id",
"]",
",",
"\"Add\"",
")",
":",
"skip_type",
"=",
"NetworkDescriptor",
".",
"ADD_CONNECT",
"ret",
".",
"add_skip_connection",
"(",
"index_in_main_chain",
"[",
"u",
"]",
",",
"index_in_main_chain",
"[",
"v",
"]",
",",
"skip_type",
")",
"return",
"ret"
] | 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(layer_id)
return ret | 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(layer_id)
return ret | [
"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",
"]",
":",
"if",
"v",
"in",
"main_chain",
"and",
"u",
"in",
"main_chain",
":",
"ret",
".",
"append",
"(",
"layer_id",
")",
"return",
"ret"
] | 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, _ in self.adj_list[u]:
if distance[u] + 1 > distance[v]:
distance[v] = distance[u] + 1
pre_node[v] = u
temp_id = 0
for i in range(self.n_nodes):
if distance[i] > distance[temp_id]:
temp_id = i
ret = []
for i in range(self.n_nodes + 5):
ret.append(temp_id)
if pre_node[temp_id] == temp_id:
break
temp_id = pre_node[temp_id]
assert temp_id == pre_node[temp_id]
ret.reverse()
return ret | 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, _ in self.adj_list[u]:
if distance[u] + 1 > distance[v]:
distance[v] = distance[u] + 1
pre_node[v] = u
temp_id = 0
for i in range(self.n_nodes):
if distance[i] > distance[temp_id]:
temp_id = i
ret = []
for i in range(self.n_nodes + 5):
ret.append(temp_id)
if pre_node[temp_id] == temp_id:
break
temp_id = pre_node[temp_id]
assert temp_id == pre_node[temp_id]
ret.reverse()
return ret | [
"def",
"get_main_chain",
"(",
"self",
")",
":",
"pre_node",
"=",
"{",
"}",
"distance",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"n_nodes",
")",
":",
"distance",
"[",
"i",
"]",
"=",
"0",
"pre_node",
"[",
"i",
"]",
"=",
"i",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"n_nodes",
"-",
"1",
")",
":",
"for",
"u",
"in",
"range",
"(",
"self",
".",
"n_nodes",
")",
":",
"for",
"v",
",",
"_",
"in",
"self",
".",
"adj_list",
"[",
"u",
"]",
":",
"if",
"distance",
"[",
"u",
"]",
"+",
"1",
">",
"distance",
"[",
"v",
"]",
":",
"distance",
"[",
"v",
"]",
"=",
"distance",
"[",
"u",
"]",
"+",
"1",
"pre_node",
"[",
"v",
"]",
"=",
"u",
"temp_id",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"n_nodes",
")",
":",
"if",
"distance",
"[",
"i",
"]",
">",
"distance",
"[",
"temp_id",
"]",
":",
"temp_id",
"=",
"i",
"ret",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"n_nodes",
"+",
"5",
")",
":",
"ret",
".",
"append",
"(",
"temp_id",
")",
"if",
"pre_node",
"[",
"temp_id",
"]",
"==",
"temp_id",
":",
"break",
"temp_id",
"=",
"pre_node",
"[",
"temp_id",
"]",
"assert",
"temp_id",
"==",
"pre_node",
"[",
"temp_id",
"]",
"ret",
".",
"reverse",
"(",
")",
"return",
"ret"
] | 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:
data = json_tricks.loads(data)
if command is None or command is CommandType.Terminate:
break
if multi_thread_enabled():
result = self.pool.map_async(self.process_command_thread, [(command, data)])
self.thread_results.append(result)
if any([thread_result.ready() and not thread_result.successful() for thread_result in self.thread_results]):
_logger.debug('Caught thread exception')
break
else:
self.enqueue_command(command, data)
if self.worker_exceptions:
break
_logger.info('Dispatcher exiting...')
self.stopping = True
if multi_thread_enabled():
self.pool.close()
self.pool.join()
else:
self.default_worker.join()
self.assessor_worker.join()
_logger.info('Terminated by NNI manager') | 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:
data = json_tricks.loads(data)
if command is None or command is CommandType.Terminate:
break
if multi_thread_enabled():
result = self.pool.map_async(self.process_command_thread, [(command, data)])
self.thread_results.append(result)
if any([thread_result.ready() and not thread_result.successful() for thread_result in self.thread_results]):
_logger.debug('Caught thread exception')
break
else:
self.enqueue_command(command, data)
if self.worker_exceptions:
break
_logger.info('Dispatcher exiting...')
self.stopping = True
if multi_thread_enabled():
self.pool.close()
self.pool.join()
else:
self.default_worker.join()
self.assessor_worker.join()
_logger.info('Terminated by NNI manager') | [
"def",
"run",
"(",
"self",
")",
":",
"_logger",
".",
"info",
"(",
"'Start dispatcher'",
")",
"if",
"dispatcher_env_vars",
".",
"NNI_MODE",
"==",
"'resume'",
":",
"self",
".",
"load_checkpoint",
"(",
")",
"while",
"True",
":",
"command",
",",
"data",
"=",
"receive",
"(",
")",
"if",
"data",
":",
"data",
"=",
"json_tricks",
".",
"loads",
"(",
"data",
")",
"if",
"command",
"is",
"None",
"or",
"command",
"is",
"CommandType",
".",
"Terminate",
":",
"break",
"if",
"multi_thread_enabled",
"(",
")",
":",
"result",
"=",
"self",
".",
"pool",
".",
"map_async",
"(",
"self",
".",
"process_command_thread",
",",
"[",
"(",
"command",
",",
"data",
")",
"]",
")",
"self",
".",
"thread_results",
".",
"append",
"(",
"result",
")",
"if",
"any",
"(",
"[",
"thread_result",
".",
"ready",
"(",
")",
"and",
"not",
"thread_result",
".",
"successful",
"(",
")",
"for",
"thread_result",
"in",
"self",
".",
"thread_results",
"]",
")",
":",
"_logger",
".",
"debug",
"(",
"'Caught thread exception'",
")",
"break",
"else",
":",
"self",
".",
"enqueue_command",
"(",
"command",
",",
"data",
")",
"if",
"self",
".",
"worker_exceptions",
":",
"break",
"_logger",
".",
"info",
"(",
"'Dispatcher exiting...'",
")",
"self",
".",
"stopping",
"=",
"True",
"if",
"multi_thread_enabled",
"(",
")",
":",
"self",
".",
"pool",
".",
"close",
"(",
")",
"self",
".",
"pool",
".",
"join",
"(",
")",
"else",
":",
"self",
".",
"default_worker",
".",
"join",
"(",
")",
"self",
".",
"assessor_worker",
".",
"join",
"(",
")",
"_logger",
".",
"info",
"(",
"'Terminated by NNI manager'",
")"
] | 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:
self.process_command(command, data)
except Exception as e:
_logger.exception(e)
self.worker_exceptions.append(e)
break
except Empty:
pass
if self.stopping and (_worker_fast_exit_on_terminate or command_queue.empty()):
break | 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:
self.process_command(command, data)
except Exception as e:
_logger.exception(e)
self.worker_exceptions.append(e)
break
except Empty:
pass
if self.stopping and (_worker_fast_exit_on_terminate or command_queue.empty()):
break | [
"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",
")",
"try",
":",
"self",
".",
"process_command",
"(",
"command",
",",
"data",
")",
"except",
"Exception",
"as",
"e",
":",
"_logger",
".",
"exception",
"(",
"e",
")",
"self",
".",
"worker_exceptions",
".",
"append",
"(",
"e",
")",
"break",
"except",
"Empty",
":",
"pass",
"if",
"self",
".",
"stopping",
"and",
"(",
"_worker_fast_exit_on_terminate",
"or",
"command_queue",
".",
"empty",
"(",
")",
")",
":",
"break"
] | 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.default_command_queue.put((command, data))
qsize = self.default_command_queue.qsize()
if qsize >= QUEUE_LEN_WARNING_MARK:
_logger.warning('default queue length: %d', qsize)
qsize = self.assessor_command_queue.qsize()
if qsize >= QUEUE_LEN_WARNING_MARK:
_logger.warning('assessor queue length: %d', qsize) | 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.default_command_queue.put((command, data))
qsize = self.default_command_queue.qsize()
if qsize >= QUEUE_LEN_WARNING_MARK:
_logger.warning('default queue length: %d', qsize)
qsize = self.assessor_command_queue.qsize()
if qsize >= QUEUE_LEN_WARNING_MARK:
_logger.warning('assessor queue length: %d', qsize) | [
"def",
"enqueue_command",
"(",
"self",
",",
"command",
",",
"data",
")",
":",
"if",
"command",
"==",
"CommandType",
".",
"TrialEnd",
"or",
"(",
"command",
"==",
"CommandType",
".",
"ReportMetricData",
"and",
"data",
"[",
"'type'",
"]",
"==",
"'PERIODICAL'",
")",
":",
"self",
".",
"assessor_command_queue",
".",
"put",
"(",
"(",
"command",
",",
"data",
")",
")",
"else",
":",
"self",
".",
"default_command_queue",
".",
"put",
"(",
"(",
"command",
",",
"data",
")",
")",
"qsize",
"=",
"self",
".",
"default_command_queue",
".",
"qsize",
"(",
")",
"if",
"qsize",
">=",
"QUEUE_LEN_WARNING_MARK",
":",
"_logger",
".",
"warning",
"(",
"'default queue length: %d'",
",",
"qsize",
")",
"qsize",
"=",
"self",
".",
"assessor_command_queue",
".",
"qsize",
"(",
")",
"if",
"qsize",
">=",
"QUEUE_LEN_WARNING_MARK",
":",
"_logger",
".",
"warning",
"(",
"'assessor queue length: %d'",
",",
"qsize",
")"
] | 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))
raise
else:
pass | 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))
raise
else:
pass | [
"def",
"process_command_thread",
"(",
"self",
",",
"request",
")",
":",
"command",
",",
"data",
"=",
"request",
"if",
"multi_thread_enabled",
"(",
")",
":",
"try",
":",
"self",
".",
"process_command",
"(",
"command",
",",
"data",
")",
"except",
"Exception",
"as",
"e",
":",
"_logger",
".",
"exception",
"(",
"str",
"(",
"e",
")",
")",
"raise",
"else",
":",
"pass"
] | 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.append(min(vals_bounds[i], key=lambda x: abs(x - vals[i])))
elif vals_types[i] == "range_int":
# Round down to the nearest integer
vals_new.append(math.floor(vals[i]))
elif vals_types[i] == "range_continuous":
# Don't do any processing for continous numbers
vals_new.append(vals[i])
else:
return None
return vals_new | 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.append(min(vals_bounds[i], key=lambda x: abs(x - vals[i])))
elif vals_types[i] == "range_int":
# Round down to the nearest integer
vals_new.append(math.floor(vals[i]))
elif vals_types[i] == "range_continuous":
# Don't do any processing for continous numbers
vals_new.append(vals[i])
else:
return None
return vals_new | [
"def",
"match_val_type",
"(",
"vals",
",",
"vals_bounds",
",",
"vals_types",
")",
":",
"vals_new",
"=",
"[",
"]",
"for",
"i",
",",
"_",
"in",
"enumerate",
"(",
"vals_types",
")",
":",
"if",
"vals_types",
"[",
"i",
"]",
"==",
"\"discrete_int\"",
":",
"# Find the closest integer in the array, vals_bounds",
"vals_new",
".",
"append",
"(",
"min",
"(",
"vals_bounds",
"[",
"i",
"]",
",",
"key",
"=",
"lambda",
"x",
":",
"abs",
"(",
"x",
"-",
"vals",
"[",
"i",
"]",
")",
")",
")",
"elif",
"vals_types",
"[",
"i",
"]",
"==",
"\"range_int\"",
":",
"# Round down to the nearest integer",
"vals_new",
".",
"append",
"(",
"math",
".",
"floor",
"(",
"vals",
"[",
"i",
"]",
")",
")",
"elif",
"vals_types",
"[",
"i",
"]",
"==",
"\"range_continuous\"",
":",
"# Don't do any processing for continous numbers",
"vals_new",
".",
"append",
"(",
"vals",
"[",
"i",
"]",
")",
"else",
":",
"return",
"None",
"return",
"vals_new"
] | 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_types[i] == "range_int":
temp = random.randint(x_bounds[i][0], x_bounds[i][1])
outputs.append(temp)
elif x_types[i] == "range_continuous":
temp = random.uniform(x_bounds[i][0], x_bounds[i][1])
outputs.append(temp)
else:
return None
return outputs | 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_types[i] == "range_int":
temp = random.randint(x_bounds[i][0], x_bounds[i][1])
outputs.append(temp)
elif x_types[i] == "range_continuous":
temp = random.uniform(x_bounds[i][0], x_bounds[i][1])
outputs.append(temp)
else:
return None
return outputs | [
"def",
"rand",
"(",
"x_bounds",
",",
"x_types",
")",
":",
"outputs",
"=",
"[",
"]",
"for",
"i",
",",
"_",
"in",
"enumerate",
"(",
"x_bounds",
")",
":",
"if",
"x_types",
"[",
"i",
"]",
"==",
"\"discrete_int\"",
":",
"temp",
"=",
"x_bounds",
"[",
"i",
"]",
"[",
"random",
".",
"randint",
"(",
"0",
",",
"len",
"(",
"x_bounds",
"[",
"i",
"]",
")",
"-",
"1",
")",
"]",
"outputs",
".",
"append",
"(",
"temp",
")",
"elif",
"x_types",
"[",
"i",
"]",
"==",
"\"range_int\"",
":",
"temp",
"=",
"random",
".",
"randint",
"(",
"x_bounds",
"[",
"i",
"]",
"[",
"0",
"]",
",",
"x_bounds",
"[",
"i",
"]",
"[",
"1",
"]",
")",
"outputs",
".",
"append",
"(",
"temp",
")",
"elif",
"x_types",
"[",
"i",
"]",
"==",
"\"range_continuous\"",
":",
"temp",
"=",
"random",
".",
"uniform",
"(",
"x_bounds",
"[",
"i",
"]",
"[",
"0",
"]",
",",
"x_bounds",
"[",
"i",
"]",
"[",
"1",
"]",
")",
"outputs",
".",
"append",
"(",
"temp",
")",
"else",
":",
"return",
"None",
"return",
"outputs"
] | 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_CONNECT, NetworkDescriptor.CONCAT_CONNECT]):
for index_a in range(len(weighted_layer_ids)):
for index_b in range(len(weighted_layer_ids))[index_a + 1 :]:
valid_connection.append((index_a, index_b, skip_type))
if not valid_connection:
return graph
for index_a, index_b, skip_type in sample(valid_connection, 1):
a_id = weighted_layer_ids[index_a]
b_id = weighted_layer_ids[index_b]
if skip_type == NetworkDescriptor.ADD_CONNECT:
graph.to_add_skip_model(a_id, b_id)
else:
graph.to_concat_skip_model(a_id, b_id)
return graph | 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_CONNECT, NetworkDescriptor.CONCAT_CONNECT]):
for index_a in range(len(weighted_layer_ids)):
for index_b in range(len(weighted_layer_ids))[index_a + 1 :]:
valid_connection.append((index_a, index_b, skip_type))
if not valid_connection:
return graph
for index_a, index_b, skip_type in sample(valid_connection, 1):
a_id = weighted_layer_ids[index_a]
b_id = weighted_layer_ids[index_b]
if skip_type == NetworkDescriptor.ADD_CONNECT:
graph.to_add_skip_model(a_id, b_id)
else:
graph.to_concat_skip_model(a_id, b_id)
return graph | [
"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",
"=",
"[",
"]",
"for",
"skip_type",
"in",
"sorted",
"(",
"[",
"NetworkDescriptor",
".",
"ADD_CONNECT",
",",
"NetworkDescriptor",
".",
"CONCAT_CONNECT",
"]",
")",
":",
"for",
"index_a",
"in",
"range",
"(",
"len",
"(",
"weighted_layer_ids",
")",
")",
":",
"for",
"index_b",
"in",
"range",
"(",
"len",
"(",
"weighted_layer_ids",
")",
")",
"[",
"index_a",
"+",
"1",
":",
"]",
":",
"valid_connection",
".",
"append",
"(",
"(",
"index_a",
",",
"index_b",
",",
"skip_type",
")",
")",
"if",
"not",
"valid_connection",
":",
"return",
"graph",
"for",
"index_a",
",",
"index_b",
",",
"skip_type",
"in",
"sample",
"(",
"valid_connection",
",",
"1",
")",
":",
"a_id",
"=",
"weighted_layer_ids",
"[",
"index_a",
"]",
"b_id",
"=",
"weighted_layer_ids",
"[",
"index_b",
"]",
"if",
"skip_type",
"==",
"NetworkDescriptor",
".",
"ADD_CONNECT",
":",
"graph",
".",
"to_add_skip_model",
"(",
"a_id",
",",
"b_id",
")",
"else",
":",
"graph",
".",
"to_concat_skip_model",
"(",
"a_id",
",",
"b_id",
")",
"return",
"graph"
] | 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"):
conv_deeper_classes = [get_conv_class(n_dim), get_batch_norm_class(n_dim)]
dense_deeper_classes = [StubDense, get_dropout_class(n_dim)]
elif is_layer(layer, "Dropout"):
dense_deeper_classes = [StubDense, StubReLU]
elif is_layer(layer, "BatchNormalization"):
conv_deeper_classes = [get_conv_class(n_dim), StubReLU]
layer_class = None
if len(input_shape) == 1:
# It is in the dense layer part.
layer_class = sample(dense_deeper_classes, 1)[0]
else:
# It is in the conv layer part.
layer_class = sample(conv_deeper_classes, 1)[0]
if layer_class == StubDense:
new_layer = StubDense(input_shape[0], input_shape[0])
elif layer_class == get_dropout_class(n_dim):
new_layer = layer_class(Constant.DENSE_DROPOUT_RATE)
elif layer_class == get_conv_class(n_dim):
new_layer = layer_class(
input_shape[-1], input_shape[-1], sample((1, 3, 5), 1)[0], stride=1
)
elif layer_class == get_batch_norm_class(n_dim):
new_layer = layer_class(input_shape[-1])
elif layer_class == get_pooling_class(n_dim):
new_layer = layer_class(sample((1, 3, 5), 1)[0])
else:
new_layer = layer_class()
return new_layer | 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"):
conv_deeper_classes = [get_conv_class(n_dim), get_batch_norm_class(n_dim)]
dense_deeper_classes = [StubDense, get_dropout_class(n_dim)]
elif is_layer(layer, "Dropout"):
dense_deeper_classes = [StubDense, StubReLU]
elif is_layer(layer, "BatchNormalization"):
conv_deeper_classes = [get_conv_class(n_dim), StubReLU]
layer_class = None
if len(input_shape) == 1:
# It is in the dense layer part.
layer_class = sample(dense_deeper_classes, 1)[0]
else:
# It is in the conv layer part.
layer_class = sample(conv_deeper_classes, 1)[0]
if layer_class == StubDense:
new_layer = StubDense(input_shape[0], input_shape[0])
elif layer_class == get_dropout_class(n_dim):
new_layer = layer_class(Constant.DENSE_DROPOUT_RATE)
elif layer_class == get_conv_class(n_dim):
new_layer = layer_class(
input_shape[-1], input_shape[-1], sample((1, 3, 5), 1)[0], stride=1
)
elif layer_class == get_batch_norm_class(n_dim):
new_layer = layer_class(input_shape[-1])
elif layer_class == get_pooling_class(n_dim):
new_layer = layer_class(sample((1, 3, 5), 1)[0])
else:
new_layer = layer_class()
return new_layer | [
"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",
"=",
"[",
"get_conv_class",
"(",
"n_dim",
")",
",",
"get_batch_norm_class",
"(",
"n_dim",
")",
",",
"StubReLU",
"]",
"if",
"is_layer",
"(",
"layer",
",",
"\"ReLU\"",
")",
":",
"conv_deeper_classes",
"=",
"[",
"get_conv_class",
"(",
"n_dim",
")",
",",
"get_batch_norm_class",
"(",
"n_dim",
")",
"]",
"dense_deeper_classes",
"=",
"[",
"StubDense",
",",
"get_dropout_class",
"(",
"n_dim",
")",
"]",
"elif",
"is_layer",
"(",
"layer",
",",
"\"Dropout\"",
")",
":",
"dense_deeper_classes",
"=",
"[",
"StubDense",
",",
"StubReLU",
"]",
"elif",
"is_layer",
"(",
"layer",
",",
"\"BatchNormalization\"",
")",
":",
"conv_deeper_classes",
"=",
"[",
"get_conv_class",
"(",
"n_dim",
")",
",",
"StubReLU",
"]",
"layer_class",
"=",
"None",
"if",
"len",
"(",
"input_shape",
")",
"==",
"1",
":",
"# It is in the dense layer part.",
"layer_class",
"=",
"sample",
"(",
"dense_deeper_classes",
",",
"1",
")",
"[",
"0",
"]",
"else",
":",
"# It is in the conv layer part.",
"layer_class",
"=",
"sample",
"(",
"conv_deeper_classes",
",",
"1",
")",
"[",
"0",
"]",
"if",
"layer_class",
"==",
"StubDense",
":",
"new_layer",
"=",
"StubDense",
"(",
"input_shape",
"[",
"0",
"]",
",",
"input_shape",
"[",
"0",
"]",
")",
"elif",
"layer_class",
"==",
"get_dropout_class",
"(",
"n_dim",
")",
":",
"new_layer",
"=",
"layer_class",
"(",
"Constant",
".",
"DENSE_DROPOUT_RATE",
")",
"elif",
"layer_class",
"==",
"get_conv_class",
"(",
"n_dim",
")",
":",
"new_layer",
"=",
"layer_class",
"(",
"input_shape",
"[",
"-",
"1",
"]",
",",
"input_shape",
"[",
"-",
"1",
"]",
",",
"sample",
"(",
"(",
"1",
",",
"3",
",",
"5",
")",
",",
"1",
")",
"[",
"0",
"]",
",",
"stride",
"=",
"1",
")",
"elif",
"layer_class",
"==",
"get_batch_norm_class",
"(",
"n_dim",
")",
":",
"new_layer",
"=",
"layer_class",
"(",
"input_shape",
"[",
"-",
"1",
"]",
")",
"elif",
"layer_class",
"==",
"get_pooling_class",
"(",
"n_dim",
")",
":",
"new_layer",
"=",
"layer_class",
"(",
"sample",
"(",
"(",
"1",
",",
"3",
",",
"5",
")",
",",
"1",
")",
"[",
"0",
"]",
")",
"else",
":",
"new_layer",
"=",
"layer_class",
"(",
")",
"return",
"new_layer"
] | 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",
")",
")",
":",
"return",
"False",
"return",
"True"
] | 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:
temp_graph = to_wider_graph(deepcopy(graph))
elif random_num == 2:
temp_graph = to_skip_connection_graph(deepcopy(graph))
if temp_graph is not None and temp_graph.size() <= Constant.MAX_MODEL_SIZE:
graphs.append(temp_graph)
if len(graphs) >= Constant.N_NEIGHBOURS:
break
return graphs | 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:
temp_graph = to_wider_graph(deepcopy(graph))
elif random_num == 2:
temp_graph = to_skip_connection_graph(deepcopy(graph))
if temp_graph is not None and temp_graph.size() <= Constant.MAX_MODEL_SIZE:
graphs.append(temp_graph)
if len(graphs) >= Constant.N_NEIGHBOURS:
break
return graphs | [
"def",
"transform",
"(",
"graph",
")",
":",
"graphs",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"Constant",
".",
"N_NEIGHBOURS",
"*",
"2",
")",
":",
"random_num",
"=",
"randrange",
"(",
"3",
")",
"temp_graph",
"=",
"None",
"if",
"random_num",
"==",
"0",
":",
"temp_graph",
"=",
"to_deeper_graph",
"(",
"deepcopy",
"(",
"graph",
")",
")",
"elif",
"random_num",
"==",
"1",
":",
"temp_graph",
"=",
"to_wider_graph",
"(",
"deepcopy",
"(",
"graph",
")",
")",
"elif",
"random_num",
"==",
"2",
":",
"temp_graph",
"=",
"to_skip_connection_graph",
"(",
"deepcopy",
"(",
"graph",
")",
")",
"if",
"temp_graph",
"is",
"not",
"None",
"and",
"temp_graph",
".",
"size",
"(",
")",
"<=",
"Constant",
".",
"MAX_MODEL_SIZE",
":",
"graphs",
".",
"append",
"(",
"temp_graph",
")",
"if",
"len",
"(",
"graphs",
")",
">=",
"Constant",
".",
"N_NEIGHBOURS",
":",
"break",
"return",
"graphs"
] | 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",
"=",
"regressor_gp",
".",
"predict",
"(",
"parameters_value",
",",
"return_std",
"=",
"True",
")",
"return",
"mu",
"[",
"0",
"]",
",",
"sigma",
"[",
"0",
"]"
] | 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
Returns
-------
bool
AssessResult.Good or AssessResult.Bad
Raises
------
Exception
unrecognize exception in curvefitting_assessor
"""
self.trial_job_id = trial_job_id
self.trial_history = trial_history
if not self.set_best_performance:
return AssessResult.Good
curr_step = len(trial_history)
if curr_step < self.start_step:
return AssessResult.Good
if trial_job_id in self.last_judgment_num.keys() and curr_step - self.last_judgment_num[trial_job_id] < self.gap:
return AssessResult.Good
self.last_judgment_num[trial_job_id] = curr_step
try:
start_time = datetime.datetime.now()
# Predict the final result
curvemodel = CurveModel(self.target_pos)
predict_y = curvemodel.predict(trial_history)
logger.info('Prediction done. Trial job id = ', trial_job_id, '. Predict value = ', predict_y)
if predict_y is None:
logger.info('wait for more information to predict precisely')
return AssessResult.Good
standard_performance = self.completed_best_performance * self.threshold
end_time = datetime.datetime.now()
if (end_time - start_time).seconds > 60:
logger.warning('Curve Fitting Assessor Runtime Exceeds 60s, Trial Id = ', self.trial_job_id, 'Trial History = ', self.trial_history)
if self.higher_better:
if predict_y > standard_performance:
return AssessResult.Good
return AssessResult.Bad
else:
if predict_y < standard_performance:
return AssessResult.Good
return AssessResult.Bad
except Exception as exception:
logger.exception('unrecognize exception in curvefitting_assessor', exception) | 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
Returns
-------
bool
AssessResult.Good or AssessResult.Bad
Raises
------
Exception
unrecognize exception in curvefitting_assessor
"""
self.trial_job_id = trial_job_id
self.trial_history = trial_history
if not self.set_best_performance:
return AssessResult.Good
curr_step = len(trial_history)
if curr_step < self.start_step:
return AssessResult.Good
if trial_job_id in self.last_judgment_num.keys() and curr_step - self.last_judgment_num[trial_job_id] < self.gap:
return AssessResult.Good
self.last_judgment_num[trial_job_id] = curr_step
try:
start_time = datetime.datetime.now()
# Predict the final result
curvemodel = CurveModel(self.target_pos)
predict_y = curvemodel.predict(trial_history)
logger.info('Prediction done. Trial job id = ', trial_job_id, '. Predict value = ', predict_y)
if predict_y is None:
logger.info('wait for more information to predict precisely')
return AssessResult.Good
standard_performance = self.completed_best_performance * self.threshold
end_time = datetime.datetime.now()
if (end_time - start_time).seconds > 60:
logger.warning('Curve Fitting Assessor Runtime Exceeds 60s, Trial Id = ', self.trial_job_id, 'Trial History = ', self.trial_history)
if self.higher_better:
if predict_y > standard_performance:
return AssessResult.Good
return AssessResult.Bad
else:
if predict_y < standard_performance:
return AssessResult.Good
return AssessResult.Bad
except Exception as exception:
logger.exception('unrecognize exception in curvefitting_assessor', exception) | [
"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",
"AssessResult",
".",
"Good",
"curr_step",
"=",
"len",
"(",
"trial_history",
")",
"if",
"curr_step",
"<",
"self",
".",
"start_step",
":",
"return",
"AssessResult",
".",
"Good",
"if",
"trial_job_id",
"in",
"self",
".",
"last_judgment_num",
".",
"keys",
"(",
")",
"and",
"curr_step",
"-",
"self",
".",
"last_judgment_num",
"[",
"trial_job_id",
"]",
"<",
"self",
".",
"gap",
":",
"return",
"AssessResult",
".",
"Good",
"self",
".",
"last_judgment_num",
"[",
"trial_job_id",
"]",
"=",
"curr_step",
"try",
":",
"start_time",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"# Predict the final result",
"curvemodel",
"=",
"CurveModel",
"(",
"self",
".",
"target_pos",
")",
"predict_y",
"=",
"curvemodel",
".",
"predict",
"(",
"trial_history",
")",
"logger",
".",
"info",
"(",
"'Prediction done. Trial job id = '",
",",
"trial_job_id",
",",
"'. Predict value = '",
",",
"predict_y",
")",
"if",
"predict_y",
"is",
"None",
":",
"logger",
".",
"info",
"(",
"'wait for more information to predict precisely'",
")",
"return",
"AssessResult",
".",
"Good",
"standard_performance",
"=",
"self",
".",
"completed_best_performance",
"*",
"self",
".",
"threshold",
"end_time",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"if",
"(",
"end_time",
"-",
"start_time",
")",
".",
"seconds",
">",
"60",
":",
"logger",
".",
"warning",
"(",
"'Curve Fitting Assessor Runtime Exceeds 60s, Trial Id = '",
",",
"self",
".",
"trial_job_id",
",",
"'Trial History = '",
",",
"self",
".",
"trial_history",
")",
"if",
"self",
".",
"higher_better",
":",
"if",
"predict_y",
">",
"standard_performance",
":",
"return",
"AssessResult",
".",
"Good",
"return",
"AssessResult",
".",
"Bad",
"else",
":",
"if",
"predict_y",
"<",
"standard_performance",
":",
"return",
"AssessResult",
".",
"Good",
"return",
"AssessResult",
".",
"Bad",
"except",
"Exception",
"as",
"exception",
":",
"logger",
".",
"exception",
"(",
"'unrecognize exception in curvefitting_assessor'",
",",
"exception",
")"
] | assess whether a trial should be early stop by curve fitting algorithm
Parameters
----------
trial_job_id: int
trial job id
trial_history: list
The history performance matrix of each trial
Returns
-------
bool
AssessResult.Good or AssessResult.Bad
Raises
------
Exception
unrecognize exception in curvefitting_assessor | [
"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_graph = None
if not self.training_queue:
new_father_id, generated_graph = self.generate()
new_model_id = self.model_count
self.model_count += 1
self.training_queue.append((generated_graph, new_father_id, new_model_id))
self.descriptors.append(generated_graph.extract_descriptor())
graph, father_id, model_id = self.training_queue.pop(0)
# from graph to json
json_model_path = os.path.join(self.path, str(model_id) + ".json")
json_out = graph_to_json(graph, json_model_path)
self.total_data[parameter_id] = (json_out, father_id, model_id)
return json_out | 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_graph = None
if not self.training_queue:
new_father_id, generated_graph = self.generate()
new_model_id = self.model_count
self.model_count += 1
self.training_queue.append((generated_graph, new_father_id, new_model_id))
self.descriptors.append(generated_graph.extract_descriptor())
graph, father_id, model_id = self.training_queue.pop(0)
# from graph to json
json_model_path = os.path.join(self.path, str(model_id) + ".json")
json_out = graph_to_json(graph, json_model_path)
self.total_data[parameter_id] = (json_out, father_id, model_id)
return json_out | [
"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",
":",
"new_father_id",
",",
"generated_graph",
"=",
"self",
".",
"generate",
"(",
")",
"new_model_id",
"=",
"self",
".",
"model_count",
"self",
".",
"model_count",
"+=",
"1",
"self",
".",
"training_queue",
".",
"append",
"(",
"(",
"generated_graph",
",",
"new_father_id",
",",
"new_model_id",
")",
")",
"self",
".",
"descriptors",
".",
"append",
"(",
"generated_graph",
".",
"extract_descriptor",
"(",
")",
")",
"graph",
",",
"father_id",
",",
"model_id",
"=",
"self",
".",
"training_queue",
".",
"pop",
"(",
"0",
")",
"# from graph to json",
"json_model_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"str",
"(",
"model_id",
")",
"+",
"\".json\"",
")",
"json_out",
"=",
"graph_to_json",
"(",
"graph",
",",
"json_model_path",
")",
"self",
".",
"total_data",
"[",
"parameter_id",
"]",
"=",
"(",
"json_out",
",",
"father_id",
",",
"model_id",
")",
"return",
"json_out"
] | 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.default_model_len, self.default_model_width
)
model_id = self.model_count
self.model_count += 1
self.training_queue.append((graph, -1, model_id))
self.descriptors.append(graph.extract_descriptor())
if self.verbose:
logger.info("Initialization finished.") | 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.default_model_len, self.default_model_width
)
model_id = self.model_count
self.model_count += 1
self.training_queue.append((graph, -1, model_id))
self.descriptors.append(graph.extract_descriptor())
if self.verbose:
logger.info("Initialization finished.") | [
"def",
"init_search",
"(",
"self",
")",
":",
"if",
"self",
".",
"verbose",
":",
"logger",
".",
"info",
"(",
"\"Initializing search.\"",
")",
"for",
"generator",
"in",
"self",
".",
"generators",
":",
"graph",
"=",
"generator",
"(",
"self",
".",
"n_classes",
",",
"self",
".",
"input_shape",
")",
".",
"generate",
"(",
"self",
".",
"default_model_len",
",",
"self",
".",
"default_model_width",
")",
"model_id",
"=",
"self",
".",
"model_count",
"self",
".",
"model_count",
"+=",
"1",
"self",
".",
"training_queue",
".",
"append",
"(",
"(",
"graph",
",",
"-",
"1",
",",
"model_id",
")",
")",
"self",
".",
"descriptors",
".",
"append",
"(",
"graph",
".",
"extract_descriptor",
"(",
")",
")",
"if",
"self",
".",
"verbose",
":",
"logger",
".",
"info",
"(",
"\"Initialization finished.\"",
")"
] | 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_graph, new_father_id = self.bo.generate(self.descriptors)
if new_father_id is None:
new_father_id = 0
generated_graph = self.generators[0](
self.n_classes, self.input_shape
).generate(self.default_model_len, self.default_model_width)
return new_father_id, generated_graph | 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_graph, new_father_id = self.bo.generate(self.descriptors)
if new_father_id is None:
new_father_id = 0
generated_graph = self.generators[0](
self.n_classes, self.input_shape
).generate(self.default_model_len, self.default_model_width)
return new_father_id, generated_graph | [
"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",
"=",
"self",
".",
"generators",
"[",
"0",
"]",
"(",
"self",
".",
"n_classes",
",",
"self",
".",
"input_shape",
")",
".",
"generate",
"(",
"self",
".",
"default_model_len",
",",
"self",
".",
"default_model_width",
")",
"return",
"new_father_id",
",",
"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 instance of Graph. The trained neural architecture.
metric_value: float
The final evaluated metric value.
model_id: int
"""
father_id = other_info
self.bo.fit([graph.extract_descriptor()], [metric_value])
self.bo.add_child(father_id, model_id) | 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 instance of Graph. The trained neural architecture.
metric_value: float
The final evaluated metric value.
model_id: int
"""
father_id = other_info
self.bo.fit([graph.extract_descriptor()], [metric_value])
self.bo.add_child(father_id, model_id) | [
"def",
"update",
"(",
"self",
",",
"other_info",
",",
"graph",
",",
"metric_value",
",",
"model_id",
")",
":",
"father_id",
"=",
"other_info",
"self",
".",
"bo",
".",
"fit",
"(",
"[",
"graph",
".",
"extract_descriptor",
"(",
")",
"]",
",",
"[",
"metric_value",
"]",
")",
"self",
".",
"bo",
".",
"add_child",
"(",
"father_id",
",",
"model_id",
")"
] | Update the controller with evaluation result of a neural architecture.
Parameters
----------
other_info: any object
In our case it is the father ID in the search tree.
graph: Graph
An instance of Graph. The trained neural architecture.
metric_value: float
The final evaluated metric value.
model_id: int | [
"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:
logger.info("Saving model.")
# Update best_model text file
ret = {"model_id": model_id, "metric_value": metric_value}
self.history.append(ret)
if model_id == self.get_best_model_id():
file = open(os.path.join(self.path, "best_model.txt"), "w")
file.write("best model: " + str(model_id))
file.close()
return ret | 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:
logger.info("Saving model.")
# Update best_model text file
ret = {"model_id": model_id, "metric_value": metric_value}
self.history.append(ret)
if model_id == self.get_best_model_id():
file = open(os.path.join(self.path, "best_model.txt"), "w")
file.write("best model: " + str(model_id))
file.close()
return ret | [
"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",
",",
"\"metric_value\"",
":",
"metric_value",
"}",
"self",
".",
"history",
".",
"append",
"(",
"ret",
")",
"if",
"model_id",
"==",
"self",
".",
"get_best_model_id",
"(",
")",
":",
"file",
"=",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"\"best_model.txt\"",
")",
",",
"\"w\"",
")",
"file",
".",
"write",
"(",
"\"best model: \"",
"+",
"str",
"(",
"model_id",
")",
")",
"file",
".",
"close",
"(",
")",
"return",
"ret"
] | 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"])["model_id"] | 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"])["model_id"] | [
"def",
"get_best_model_id",
"(",
"self",
")",
":",
"if",
"self",
".",
"optimize_mode",
"is",
"OptimizeMode",
".",
"Maximize",
":",
"return",
"max",
"(",
"self",
".",
"history",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"\"metric_value\"",
"]",
")",
"[",
"\"model_id\"",
"]",
"return",
"min",
"(",
"self",
".",
"history",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"\"metric_value\"",
"]",
")",
"[",
"\"model_id\"",
"]"
] | Get the 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.path, str(model_id) + ".json")) as fin:
json_str = fin.read().replace("\n", "")
load_model = json_to_graph(json_str)
return load_model | 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.path, str(model_id) + ".json")) as fin:
json_str = fin.read().replace("\n", "")
load_model = json_to_graph(json_str)
return load_model | [
"def",
"load_model_by_id",
"(",
"self",
",",
"model_id",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"str",
"(",
"model_id",
")",
"+",
"\".json\"",
")",
")",
"as",
"fin",
":",
"json_str",
"=",
"fin",
".",
"read",
"(",
")",
".",
"replace",
"(",
"\"\\n\"",
",",
"\"\"",
")",
"load_model",
"=",
"json_to_graph",
"(",
"json_str",
")",
"return",
"load_model"
] | 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(search_space))]
for key in search_space:
self.key_order.append(key)
key_type = {}
if isinstance(search_space, dict):
for key in search_space:
key_type = search_space[key]['_type']
key_range = search_space[key]['_value']
idx = self.key_order.index(key)
if key_type == 'quniform':
if key_range[2] == 1:
self.x_bounds[idx] = [key_range[0], key_range[1]]
self.x_types[idx] = 'range_int'
else:
bounds = []
for value in np.arange(key_range[0], key_range[1], key_range[2]):
bounds.append(value)
self.x_bounds[idx] = bounds
self.x_types[idx] = 'discrete_int'
elif key_type == 'randint':
self.x_bounds[idx] = [0, key_range[0]]
self.x_types[idx] = 'range_int'
elif key_type == 'uniform':
self.x_bounds[idx] = [key_range[0], key_range[1]]
self.x_types[idx] = 'range_continuous'
elif key_type == 'choice':
self.x_bounds[idx] = key_range
for key_value in key_range:
if not isinstance(key_value, (int, float)):
raise RuntimeError("Metis Tuner only support numerical choice.")
self.x_types[idx] = 'discrete_int'
else:
logger.info("Metis Tuner doesn't support this kind of variable: " + str(key_type))
raise RuntimeError("Metis Tuner doesn't support this kind of variable: " + str(key_type))
else:
logger.info("The format of search space is not a dict.")
raise RuntimeError("The format of search space is not a dict.")
self.minimize_starting_points = _rand_init(self.x_bounds, self.x_types, \
self.selection_num_starting_points) | 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(search_space))]
for key in search_space:
self.key_order.append(key)
key_type = {}
if isinstance(search_space, dict):
for key in search_space:
key_type = search_space[key]['_type']
key_range = search_space[key]['_value']
idx = self.key_order.index(key)
if key_type == 'quniform':
if key_range[2] == 1:
self.x_bounds[idx] = [key_range[0], key_range[1]]
self.x_types[idx] = 'range_int'
else:
bounds = []
for value in np.arange(key_range[0], key_range[1], key_range[2]):
bounds.append(value)
self.x_bounds[idx] = bounds
self.x_types[idx] = 'discrete_int'
elif key_type == 'randint':
self.x_bounds[idx] = [0, key_range[0]]
self.x_types[idx] = 'range_int'
elif key_type == 'uniform':
self.x_bounds[idx] = [key_range[0], key_range[1]]
self.x_types[idx] = 'range_continuous'
elif key_type == 'choice':
self.x_bounds[idx] = key_range
for key_value in key_range:
if not isinstance(key_value, (int, float)):
raise RuntimeError("Metis Tuner only support numerical choice.")
self.x_types[idx] = 'discrete_int'
else:
logger.info("Metis Tuner doesn't support this kind of variable: " + str(key_type))
raise RuntimeError("Metis Tuner doesn't support this kind of variable: " + str(key_type))
else:
logger.info("The format of search space is not a dict.")
raise RuntimeError("The format of search space is not a dict.")
self.minimize_starting_points = _rand_init(self.x_bounds, self.x_types, \
self.selection_num_starting_points) | [
"def",
"update_search_space",
"(",
"self",
",",
"search_space",
")",
":",
"self",
".",
"x_bounds",
"=",
"[",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"search_space",
")",
")",
"]",
"self",
".",
"x_types",
"=",
"[",
"NONE_TYPE",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"search_space",
")",
")",
"]",
"for",
"key",
"in",
"search_space",
":",
"self",
".",
"key_order",
".",
"append",
"(",
"key",
")",
"key_type",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"search_space",
",",
"dict",
")",
":",
"for",
"key",
"in",
"search_space",
":",
"key_type",
"=",
"search_space",
"[",
"key",
"]",
"[",
"'_type'",
"]",
"key_range",
"=",
"search_space",
"[",
"key",
"]",
"[",
"'_value'",
"]",
"idx",
"=",
"self",
".",
"key_order",
".",
"index",
"(",
"key",
")",
"if",
"key_type",
"==",
"'quniform'",
":",
"if",
"key_range",
"[",
"2",
"]",
"==",
"1",
":",
"self",
".",
"x_bounds",
"[",
"idx",
"]",
"=",
"[",
"key_range",
"[",
"0",
"]",
",",
"key_range",
"[",
"1",
"]",
"]",
"self",
".",
"x_types",
"[",
"idx",
"]",
"=",
"'range_int'",
"else",
":",
"bounds",
"=",
"[",
"]",
"for",
"value",
"in",
"np",
".",
"arange",
"(",
"key_range",
"[",
"0",
"]",
",",
"key_range",
"[",
"1",
"]",
",",
"key_range",
"[",
"2",
"]",
")",
":",
"bounds",
".",
"append",
"(",
"value",
")",
"self",
".",
"x_bounds",
"[",
"idx",
"]",
"=",
"bounds",
"self",
".",
"x_types",
"[",
"idx",
"]",
"=",
"'discrete_int'",
"elif",
"key_type",
"==",
"'randint'",
":",
"self",
".",
"x_bounds",
"[",
"idx",
"]",
"=",
"[",
"0",
",",
"key_range",
"[",
"0",
"]",
"]",
"self",
".",
"x_types",
"[",
"idx",
"]",
"=",
"'range_int'",
"elif",
"key_type",
"==",
"'uniform'",
":",
"self",
".",
"x_bounds",
"[",
"idx",
"]",
"=",
"[",
"key_range",
"[",
"0",
"]",
",",
"key_range",
"[",
"1",
"]",
"]",
"self",
".",
"x_types",
"[",
"idx",
"]",
"=",
"'range_continuous'",
"elif",
"key_type",
"==",
"'choice'",
":",
"self",
".",
"x_bounds",
"[",
"idx",
"]",
"=",
"key_range",
"for",
"key_value",
"in",
"key_range",
":",
"if",
"not",
"isinstance",
"(",
"key_value",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Metis Tuner only support numerical choice.\"",
")",
"self",
".",
"x_types",
"[",
"idx",
"]",
"=",
"'discrete_int'",
"else",
":",
"logger",
".",
"info",
"(",
"\"Metis Tuner doesn't support this kind of variable: \"",
"+",
"str",
"(",
"key_type",
")",
")",
"raise",
"RuntimeError",
"(",
"\"Metis Tuner doesn't support this kind of variable: \"",
"+",
"str",
"(",
"key_type",
")",
")",
"else",
":",
"logger",
".",
"info",
"(",
"\"The format of search space is not a dict.\"",
")",
"raise",
"RuntimeError",
"(",
"\"The format of search space is not a dict.\"",
")",
"self",
".",
"minimize_starting_points",
"=",
"_rand_init",
"(",
"self",
".",
"x_bounds",
",",
"self",
".",
"x_types",
",",
"self",
".",
"selection_num_starting_points",
")"
] | 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
return output | 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
return output | [
"def",
"_pack_output",
"(",
"self",
",",
"init_parameter",
")",
":",
"output",
"=",
"{",
"}",
"for",
"i",
",",
"param",
"in",
"enumerate",
"(",
"init_parameter",
")",
":",
"output",
"[",
"self",
".",
"key_order",
"[",
"i",
"]",
"]",
"=",
"param",
"return",
"output"
] | 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 Mixture Model.
Parameters
----------
parameter_id : int
Returns
-------
result : dict
"""
if len(self.samples_x) < self.cold_start_num:
init_parameter = _rand_init(self.x_bounds, self.x_types, 1)[0]
results = self._pack_output(init_parameter)
else:
self.minimize_starting_points = _rand_init(self.x_bounds, self.x_types, \
self.selection_num_starting_points)
results = self._selection(self.samples_x, self.samples_y_aggregation, self.samples_y,
self.x_bounds, self.x_types,
threshold_samplessize_resampling=(None if self.no_resampling is True else 50),
no_candidates=self.no_candidates,
minimize_starting_points=self.minimize_starting_points,
minimize_constraints_fun=self.minimize_constraints_fun)
logger.info("Generate paramageters:\n" + str(results))
return results | 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 Mixture Model.
Parameters
----------
parameter_id : int
Returns
-------
result : dict
"""
if len(self.samples_x) < self.cold_start_num:
init_parameter = _rand_init(self.x_bounds, self.x_types, 1)[0]
results = self._pack_output(init_parameter)
else:
self.minimize_starting_points = _rand_init(self.x_bounds, self.x_types, \
self.selection_num_starting_points)
results = self._selection(self.samples_x, self.samples_y_aggregation, self.samples_y,
self.x_bounds, self.x_types,
threshold_samplessize_resampling=(None if self.no_resampling is True else 50),
no_candidates=self.no_candidates,
minimize_starting_points=self.minimize_starting_points,
minimize_constraints_fun=self.minimize_constraints_fun)
logger.info("Generate paramageters:\n" + str(results))
return results | [
"def",
"generate_parameters",
"(",
"self",
",",
"parameter_id",
")",
":",
"if",
"len",
"(",
"self",
".",
"samples_x",
")",
"<",
"self",
".",
"cold_start_num",
":",
"init_parameter",
"=",
"_rand_init",
"(",
"self",
".",
"x_bounds",
",",
"self",
".",
"x_types",
",",
"1",
")",
"[",
"0",
"]",
"results",
"=",
"self",
".",
"_pack_output",
"(",
"init_parameter",
")",
"else",
":",
"self",
".",
"minimize_starting_points",
"=",
"_rand_init",
"(",
"self",
".",
"x_bounds",
",",
"self",
".",
"x_types",
",",
"self",
".",
"selection_num_starting_points",
")",
"results",
"=",
"self",
".",
"_selection",
"(",
"self",
".",
"samples_x",
",",
"self",
".",
"samples_y_aggregation",
",",
"self",
".",
"samples_y",
",",
"self",
".",
"x_bounds",
",",
"self",
".",
"x_types",
",",
"threshold_samplessize_resampling",
"=",
"(",
"None",
"if",
"self",
".",
"no_resampling",
"is",
"True",
"else",
"50",
")",
",",
"no_candidates",
"=",
"self",
".",
"no_candidates",
",",
"minimize_starting_points",
"=",
"self",
".",
"minimize_starting_points",
",",
"minimize_constraints_fun",
"=",
"self",
".",
"minimize_constraints_fun",
")",
"logger",
".",
"info",
"(",
"\"Generate paramageters:\\n\"",
"+",
"str",
"(",
"results",
")",
")",
"return",
"results"
] | Generate next parameter for trial
If the number of trial result is lower than cold start number,
metis will first random generate some parameters.
Otherwise, metis will choose the parameters by the Gussian Process Model and the Gussian Mixture Model.
Parameters
----------
parameter_id : int
Returns
-------
result : dict | [
"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",
"."
] | 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 = extract_scalar_reward(value)
if self.optimize_mode == OptimizeMode.Maximize:
value = -value
logger.info("Received trial result.")
logger.info("value is :" + str(value))
logger.info("parameter is : " + str(parameters))
# parse parameter to sample_x
sample_x = [0 for i in range(len(self.key_order))]
for key in parameters:
idx = self.key_order.index(key)
sample_x[idx] = parameters[key]
# parse value to sample_y
temp_y = []
if sample_x in self.samples_x:
idx = self.samples_x.index(sample_x)
temp_y = self.samples_y[idx]
temp_y.append(value)
self.samples_y[idx] = temp_y
# calculate y aggregation
median = get_median(temp_y)
self.samples_y_aggregation[idx] = [median]
else:
self.samples_x.append(sample_x)
self.samples_y.append([value])
# calculate y aggregation
self.samples_y_aggregation.append([value]) | 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 = extract_scalar_reward(value)
if self.optimize_mode == OptimizeMode.Maximize:
value = -value
logger.info("Received trial result.")
logger.info("value is :" + str(value))
logger.info("parameter is : " + str(parameters))
# parse parameter to sample_x
sample_x = [0 for i in range(len(self.key_order))]
for key in parameters:
idx = self.key_order.index(key)
sample_x[idx] = parameters[key]
# parse value to sample_y
temp_y = []
if sample_x in self.samples_x:
idx = self.samples_x.index(sample_x)
temp_y = self.samples_y[idx]
temp_y.append(value)
self.samples_y[idx] = temp_y
# calculate y aggregation
median = get_median(temp_y)
self.samples_y_aggregation[idx] = [median]
else:
self.samples_x.append(sample_x)
self.samples_y.append([value])
# calculate y aggregation
self.samples_y_aggregation.append([value]) | [
"def",
"receive_trial_result",
"(",
"self",
",",
"parameter_id",
",",
"parameters",
",",
"value",
")",
":",
"value",
"=",
"extract_scalar_reward",
"(",
"value",
")",
"if",
"self",
".",
"optimize_mode",
"==",
"OptimizeMode",
".",
"Maximize",
":",
"value",
"=",
"-",
"value",
"logger",
".",
"info",
"(",
"\"Received trial result.\"",
")",
"logger",
".",
"info",
"(",
"\"value is :\"",
"+",
"str",
"(",
"value",
")",
")",
"logger",
".",
"info",
"(",
"\"parameter is : \"",
"+",
"str",
"(",
"parameters",
")",
")",
"# parse parameter to sample_x",
"sample_x",
"=",
"[",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"key_order",
")",
")",
"]",
"for",
"key",
"in",
"parameters",
":",
"idx",
"=",
"self",
".",
"key_order",
".",
"index",
"(",
"key",
")",
"sample_x",
"[",
"idx",
"]",
"=",
"parameters",
"[",
"key",
"]",
"# parse value to sample_y",
"temp_y",
"=",
"[",
"]",
"if",
"sample_x",
"in",
"self",
".",
"samples_x",
":",
"idx",
"=",
"self",
".",
"samples_x",
".",
"index",
"(",
"sample_x",
")",
"temp_y",
"=",
"self",
".",
"samples_y",
"[",
"idx",
"]",
"temp_y",
".",
"append",
"(",
"value",
")",
"self",
".",
"samples_y",
"[",
"idx",
"]",
"=",
"temp_y",
"# calculate y aggregation",
"median",
"=",
"get_median",
"(",
"temp_y",
")",
"self",
".",
"samples_y_aggregation",
"[",
"idx",
"]",
"=",
"[",
"median",
"]",
"else",
":",
"self",
".",
"samples_x",
".",
"append",
"(",
"sample_x",
")",
"self",
".",
"samples_y",
".",
"append",
"(",
"[",
"value",
"]",
")",
"# calculate y aggregation",
"self",
".",
"samples_y_aggregation",
".",
"append",
"(",
"[",
"value",
"]",
")"
] | 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)) * \
gp.kernels.Matern(nu=1.5)
if is_white_kernel is True:
kernel += gp.kernels.WhiteKernel(noise_level=1, noise_level_bounds=(1e-12, 1e12))
regressor = gp.GaussianProcessRegressor(kernel=kernel,
n_restarts_optimizer=n_restarts_optimizer,
normalize_y=True,
alpha=1e-10)
regressor.fit(numpy.array(samples_x), numpy.array(samples_y_aggregation))
model = {}
model['model'] = regressor
model['kernel_prior'] = str(kernel)
model['kernel_posterior'] = str(regressor.kernel_)
model['model_loglikelihood'] = regressor.log_marginal_likelihood(regressor.kernel_.theta)
return model | 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)) * \
gp.kernels.Matern(nu=1.5)
if is_white_kernel is True:
kernel += gp.kernels.WhiteKernel(noise_level=1, noise_level_bounds=(1e-12, 1e12))
regressor = gp.GaussianProcessRegressor(kernel=kernel,
n_restarts_optimizer=n_restarts_optimizer,
normalize_y=True,
alpha=1e-10)
regressor.fit(numpy.array(samples_x), numpy.array(samples_y_aggregation))
model = {}
model['model'] = regressor
model['kernel_prior'] = str(kernel)
model['kernel_posterior'] = str(regressor.kernel_)
model['model_loglikelihood'] = regressor.log_marginal_likelihood(regressor.kernel_.theta)
return model | [
"def",
"create_model",
"(",
"samples_x",
",",
"samples_y_aggregation",
",",
"n_restarts_optimizer",
"=",
"250",
",",
"is_white_kernel",
"=",
"False",
")",
":",
"kernel",
"=",
"gp",
".",
"kernels",
".",
"ConstantKernel",
"(",
"constant_value",
"=",
"1",
",",
"constant_value_bounds",
"=",
"(",
"1e-12",
",",
"1e12",
")",
")",
"*",
"gp",
".",
"kernels",
".",
"Matern",
"(",
"nu",
"=",
"1.5",
")",
"if",
"is_white_kernel",
"is",
"True",
":",
"kernel",
"+=",
"gp",
".",
"kernels",
".",
"WhiteKernel",
"(",
"noise_level",
"=",
"1",
",",
"noise_level_bounds",
"=",
"(",
"1e-12",
",",
"1e12",
")",
")",
"regressor",
"=",
"gp",
".",
"GaussianProcessRegressor",
"(",
"kernel",
"=",
"kernel",
",",
"n_restarts_optimizer",
"=",
"n_restarts_optimizer",
",",
"normalize_y",
"=",
"True",
",",
"alpha",
"=",
"1e-10",
")",
"regressor",
".",
"fit",
"(",
"numpy",
".",
"array",
"(",
"samples_x",
")",
",",
"numpy",
".",
"array",
"(",
"samples_y_aggregation",
")",
")",
"model",
"=",
"{",
"}",
"model",
"[",
"'model'",
"]",
"=",
"regressor",
"model",
"[",
"'kernel_prior'",
"]",
"=",
"str",
"(",
"kernel",
")",
"model",
"[",
"'kernel_posterior'",
"]",
"=",
"str",
"(",
"regressor",
".",
"kernel_",
")",
"model",
"[",
"'model_loglikelihood'",
"]",
"=",
"regressor",
".",
"log_marginal_likelihood",
"(",
"regressor",
".",
"kernel_",
".",
"theta",
")",
"return",
"model"
] | 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 = (high - low) / (count - 1)
return [float(low + interval * i) for i in range(count)] | 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 = (high - low) / (count - 1)
return [float(low + interval * i) for i in range(count)] | [
"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_value",
"[",
"0",
"]",
",",
"param_value",
"[",
"1",
"]",
",",
"param_value",
"[",
"2",
"]",
"interval",
"=",
"(",
"high",
"-",
"low",
")",
"/",
"(",
"count",
"-",
"1",
")",
"return",
"[",
"float",
"(",
"low",
"+",
"interval",
"*",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"count",
")",
"]"
] | parse type of quniform 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._parse_quniform(param_value)))
raise RuntimeError("Not supported type: %s" % param_type) | 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._parse_quniform(param_value)))
raise RuntimeError("Not supported type: %s" % param_type) | [
"def",
"parse_qtype",
"(",
"self",
",",
"param_type",
",",
"param_value",
")",
":",
"if",
"param_type",
"==",
"'quniform'",
":",
"return",
"self",
".",
"_parse_quniform",
"(",
"param_value",
")",
"if",
"param_type",
"==",
"'qloguniform'",
":",
"param_value",
"[",
":",
"2",
"]",
"=",
"np",
".",
"log",
"(",
"param_value",
"[",
":",
"2",
"]",
")",
"return",
"list",
"(",
"np",
".",
"exp",
"(",
"self",
".",
"_parse_quniform",
"(",
"param_value",
")",
")",
")",
"raise",
"RuntimeError",
"(",
"\"Not supported type: %s\"",
"%",
"param_type",
")"
] | 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 self.log_collection == 'none':
# If not match metrics, do not put the line into queue
if not self.log_pattern.match(line):
continue
self.queue.put(line)
self.pipeReader.close() | 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 self.log_collection == 'none':
# If not match metrics, do not put the line into queue
if not self.log_pattern.match(line):
continue
self.queue.put(line)
self.pipeReader.close() | [
"def",
"run",
"(",
"self",
")",
":",
"for",
"line",
"in",
"iter",
"(",
"self",
".",
"pipeReader",
".",
"readline",
",",
"''",
")",
":",
"self",
".",
"orig_stdout",
".",
"write",
"(",
"line",
".",
"rstrip",
"(",
")",
"+",
"'\\n'",
")",
"self",
".",
"orig_stdout",
".",
"flush",
"(",
")",
"if",
"self",
".",
"log_collection",
"==",
"'none'",
":",
"# If not match metrics, do not put the line into queue",
"if",
"not",
"self",
".",
"log_pattern",
".",
"match",
"(",
"line",
")",
":",
"continue",
"self",
".",
"queue",
".",
"put",
"(",
"line",
")",
"self",
".",
"pipeReader",
".",
"close",
"(",
")"
] | 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(value, float) or isinstance(value, int):
reward = value
elif isinstance(value, dict) and scalar_key in value and isinstance(value[scalar_key], (float, int)):
reward = value[scalar_key]
else:
raise RuntimeError('Incorrect final result: the final result should be float/int, or a dict which has a key named "default" whose value is float/int.')
return reward | 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(value, float) or isinstance(value, int):
reward = value
elif isinstance(value, dict) and scalar_key in value and isinstance(value[scalar_key], (float, int)):
reward = value[scalar_key]
else:
raise RuntimeError('Incorrect final result: the final result should be float/int, or a dict which has a key named "default" whose value is float/int.')
return reward | [
"def",
"extract_scalar_reward",
"(",
"value",
",",
"scalar_key",
"=",
"'default'",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"float",
")",
"or",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"reward",
"=",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"dict",
")",
"and",
"scalar_key",
"in",
"value",
"and",
"isinstance",
"(",
"value",
"[",
"scalar_key",
"]",
",",
"(",
"float",
",",
"int",
")",
")",
":",
"reward",
"=",
"value",
"[",
"scalar_key",
"]",
"else",
":",
"raise",
"RuntimeError",
"(",
"'Incorrect final result: the final result should be float/int, or a dict which has a key named \"default\" whose value is float/int.'",
")",
"return",
"reward"
] | 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",
"tuple",
"(",
"sorted",
"(",
"value",
".",
"items",
"(",
")",
")",
")",
"else",
":",
"return",
"value"
] | 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, dispatcher_env_vars.NNI_LOG_LEVEL) | 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, dispatcher_env_vars.NNI_LOG_LEVEL) | [
"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",
".",
"NNI_LOG_DIRECTORY",
",",
"logger_file_path",
")",
"init_logger",
"(",
"logger_file_path",
",",
"dispatcher_env_vars",
".",
"NNI_LOG_LEVEL",
")"
] | 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
-------
config
return a valid configuration with parameters and budget
"""
logger.debug('start sampling a new configuration.')
sample = None
info_dict = {}
# If no model is available, sample from prior
# also mix in a fraction of random configs
if len(self.kde_models.keys()) == 0 or np.random.rand() < self.random_fraction:
sample = self.configspace.sample_configuration()
info_dict['model_based_pick'] = False
if sample is None:
sample, info_dict= self.sample_from_largest_budget(info_dict)
sample = ConfigSpace.util.deactivate_inactive_hyperparameters(
configuration_space=self.configspace,
configuration=sample.get_dictionary()
).get_dictionary()
logger.debug('done sampling a new configuration.')
sample['TRIAL_BUDGET'] = budget
return sample | 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
-------
config
return a valid configuration with parameters and budget
"""
logger.debug('start sampling a new configuration.')
sample = None
info_dict = {}
# If no model is available, sample from prior
# also mix in a fraction of random configs
if len(self.kde_models.keys()) == 0 or np.random.rand() < self.random_fraction:
sample = self.configspace.sample_configuration()
info_dict['model_based_pick'] = False
if sample is None:
sample, info_dict= self.sample_from_largest_budget(info_dict)
sample = ConfigSpace.util.deactivate_inactive_hyperparameters(
configuration_space=self.configspace,
configuration=sample.get_dictionary()
).get_dictionary()
logger.debug('done sampling a new configuration.')
sample['TRIAL_BUDGET'] = budget
return sample | [
"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 configs",
"if",
"len",
"(",
"self",
".",
"kde_models",
".",
"keys",
"(",
")",
")",
"==",
"0",
"or",
"np",
".",
"random",
".",
"rand",
"(",
")",
"<",
"self",
".",
"random_fraction",
":",
"sample",
"=",
"self",
".",
"configspace",
".",
"sample_configuration",
"(",
")",
"info_dict",
"[",
"'model_based_pick'",
"]",
"=",
"False",
"if",
"sample",
"is",
"None",
":",
"sample",
",",
"info_dict",
"=",
"self",
".",
"sample_from_largest_budget",
"(",
"info_dict",
")",
"sample",
"=",
"ConfigSpace",
".",
"util",
".",
"deactivate_inactive_hyperparameters",
"(",
"configuration_space",
"=",
"self",
".",
"configspace",
",",
"configuration",
"=",
"sample",
".",
"get_dictionary",
"(",
")",
")",
".",
"get_dictionary",
"(",
")",
"logger",
".",
"debug",
"(",
"'done sampling a new configuration.'",
")",
"sample",
"[",
"'TRIAL_BUDGET'",
"]",
"=",
"budget",
"return",
"sample"
] | Function to sample a new configuration
This function is called inside BOHB to query a new configuration
Parameters:
-----------
budget: float
the budget for which this configuration is scheduled
Returns
-------
config
return a valid configuration with parameters and budget | [
"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 parameters
budget: float
the budget of the parameters
parameters: dict
the parameters of this trial
update_model: bool
whether use this parameter to update BP model
Returns
-------
None
"""
if loss is None:
# One could skip crashed results, but we decided
# assign a +inf loss and count them as bad configurations
loss = np.inf
if budget not in self.configs.keys():
self.configs[budget] = []
self.losses[budget] = []
# skip model building if we already have a bigger model
if max(list(self.kde_models.keys()) + [-np.inf]) > budget:
return
# We want to get a numerical representation of the configuration in the original space
conf = ConfigSpace.Configuration(self.configspace, parameters)
self.configs[budget].append(conf.get_array())
self.losses[budget].append(loss)
# skip model building:
# a) if not enough points are available
if len(self.configs[budget]) <= self.min_points_in_model - 1:
logger.debug("Only %i run(s) for budget %f available, need more than %s \
-> can't build model!"%(len(self.configs[budget]), budget, self.min_points_in_model+1))
return
# b) during warnm starting when we feed previous results in and only update once
if not update_model:
return
train_configs = np.array(self.configs[budget])
train_losses = np.array(self.losses[budget])
n_good = max(self.min_points_in_model, (self.top_n_percent * train_configs.shape[0])//100)
n_bad = max(self.min_points_in_model, ((100-self.top_n_percent)*train_configs.shape[0])//100)
# Refit KDE for the current budget
idx = np.argsort(train_losses)
train_data_good = self.impute_conditional_data(train_configs[idx[:n_good]])
train_data_bad = self.impute_conditional_data(train_configs[idx[n_good:n_good+n_bad]])
if train_data_good.shape[0] <= train_data_good.shape[1]:
return
if train_data_bad.shape[0] <= train_data_bad.shape[1]:
return
#more expensive crossvalidation method
#bw_estimation = 'cv_ls'
# quick rule of thumb
bw_estimation = 'normal_reference'
bad_kde = sm.nonparametric.KDEMultivariate(data=train_data_bad, var_type=self.kde_vartypes, bw=bw_estimation)
good_kde = sm.nonparametric.KDEMultivariate(data=train_data_good, var_type=self.kde_vartypes, bw=bw_estimation)
bad_kde.bw = np.clip(bad_kde.bw, self.min_bandwidth, None)
good_kde.bw = np.clip(good_kde.bw, self.min_bandwidth, None)
self.kde_models[budget] = {
'good': good_kde,
'bad' : bad_kde
}
# update probs for the categorical parameters for later sampling
logger.debug('done building a new model for budget %f based on %i/%i split\nBest loss for this budget:%f\n'
%(budget, n_good, n_bad, np.min(train_losses))) | 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 parameters
budget: float
the budget of the parameters
parameters: dict
the parameters of this trial
update_model: bool
whether use this parameter to update BP model
Returns
-------
None
"""
if loss is None:
# One could skip crashed results, but we decided
# assign a +inf loss and count them as bad configurations
loss = np.inf
if budget not in self.configs.keys():
self.configs[budget] = []
self.losses[budget] = []
# skip model building if we already have a bigger model
if max(list(self.kde_models.keys()) + [-np.inf]) > budget:
return
# We want to get a numerical representation of the configuration in the original space
conf = ConfigSpace.Configuration(self.configspace, parameters)
self.configs[budget].append(conf.get_array())
self.losses[budget].append(loss)
# skip model building:
# a) if not enough points are available
if len(self.configs[budget]) <= self.min_points_in_model - 1:
logger.debug("Only %i run(s) for budget %f available, need more than %s \
-> can't build model!"%(len(self.configs[budget]), budget, self.min_points_in_model+1))
return
# b) during warnm starting when we feed previous results in and only update once
if not update_model:
return
train_configs = np.array(self.configs[budget])
train_losses = np.array(self.losses[budget])
n_good = max(self.min_points_in_model, (self.top_n_percent * train_configs.shape[0])//100)
n_bad = max(self.min_points_in_model, ((100-self.top_n_percent)*train_configs.shape[0])//100)
# Refit KDE for the current budget
idx = np.argsort(train_losses)
train_data_good = self.impute_conditional_data(train_configs[idx[:n_good]])
train_data_bad = self.impute_conditional_data(train_configs[idx[n_good:n_good+n_bad]])
if train_data_good.shape[0] <= train_data_good.shape[1]:
return
if train_data_bad.shape[0] <= train_data_bad.shape[1]:
return
#more expensive crossvalidation method
#bw_estimation = 'cv_ls'
# quick rule of thumb
bw_estimation = 'normal_reference'
bad_kde = sm.nonparametric.KDEMultivariate(data=train_data_bad, var_type=self.kde_vartypes, bw=bw_estimation)
good_kde = sm.nonparametric.KDEMultivariate(data=train_data_good, var_type=self.kde_vartypes, bw=bw_estimation)
bad_kde.bw = np.clip(bad_kde.bw, self.min_bandwidth, None)
good_kde.bw = np.clip(good_kde.bw, self.min_bandwidth, None)
self.kde_models[budget] = {
'good': good_kde,
'bad' : bad_kde
}
# update probs for the categorical parameters for later sampling
logger.debug('done building a new model for budget %f based on %i/%i split\nBest loss for this budget:%f\n'
%(budget, n_good, n_bad, np.min(train_losses))) | [
"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",
"loss",
"=",
"np",
".",
"inf",
"if",
"budget",
"not",
"in",
"self",
".",
"configs",
".",
"keys",
"(",
")",
":",
"self",
".",
"configs",
"[",
"budget",
"]",
"=",
"[",
"]",
"self",
".",
"losses",
"[",
"budget",
"]",
"=",
"[",
"]",
"# skip model building if we already have a bigger model",
"if",
"max",
"(",
"list",
"(",
"self",
".",
"kde_models",
".",
"keys",
"(",
")",
")",
"+",
"[",
"-",
"np",
".",
"inf",
"]",
")",
">",
"budget",
":",
"return",
"# We want to get a numerical representation of the configuration in the original space",
"conf",
"=",
"ConfigSpace",
".",
"Configuration",
"(",
"self",
".",
"configspace",
",",
"parameters",
")",
"self",
".",
"configs",
"[",
"budget",
"]",
".",
"append",
"(",
"conf",
".",
"get_array",
"(",
")",
")",
"self",
".",
"losses",
"[",
"budget",
"]",
".",
"append",
"(",
"loss",
")",
"# skip model building:",
"# a) if not enough points are available",
"if",
"len",
"(",
"self",
".",
"configs",
"[",
"budget",
"]",
")",
"<=",
"self",
".",
"min_points_in_model",
"-",
"1",
":",
"logger",
".",
"debug",
"(",
"\"Only %i run(s) for budget %f available, need more than %s \\\n -> can't build model!\"",
"%",
"(",
"len",
"(",
"self",
".",
"configs",
"[",
"budget",
"]",
")",
",",
"budget",
",",
"self",
".",
"min_points_in_model",
"+",
"1",
")",
")",
"return",
"# b) during warnm starting when we feed previous results in and only update once",
"if",
"not",
"update_model",
":",
"return",
"train_configs",
"=",
"np",
".",
"array",
"(",
"self",
".",
"configs",
"[",
"budget",
"]",
")",
"train_losses",
"=",
"np",
".",
"array",
"(",
"self",
".",
"losses",
"[",
"budget",
"]",
")",
"n_good",
"=",
"max",
"(",
"self",
".",
"min_points_in_model",
",",
"(",
"self",
".",
"top_n_percent",
"*",
"train_configs",
".",
"shape",
"[",
"0",
"]",
")",
"//",
"100",
")",
"n_bad",
"=",
"max",
"(",
"self",
".",
"min_points_in_model",
",",
"(",
"(",
"100",
"-",
"self",
".",
"top_n_percent",
")",
"*",
"train_configs",
".",
"shape",
"[",
"0",
"]",
")",
"//",
"100",
")",
"# Refit KDE for the current budget",
"idx",
"=",
"np",
".",
"argsort",
"(",
"train_losses",
")",
"train_data_good",
"=",
"self",
".",
"impute_conditional_data",
"(",
"train_configs",
"[",
"idx",
"[",
":",
"n_good",
"]",
"]",
")",
"train_data_bad",
"=",
"self",
".",
"impute_conditional_data",
"(",
"train_configs",
"[",
"idx",
"[",
"n_good",
":",
"n_good",
"+",
"n_bad",
"]",
"]",
")",
"if",
"train_data_good",
".",
"shape",
"[",
"0",
"]",
"<=",
"train_data_good",
".",
"shape",
"[",
"1",
"]",
":",
"return",
"if",
"train_data_bad",
".",
"shape",
"[",
"0",
"]",
"<=",
"train_data_bad",
".",
"shape",
"[",
"1",
"]",
":",
"return",
"#more expensive crossvalidation method",
"#bw_estimation = 'cv_ls'",
"# quick rule of thumb",
"bw_estimation",
"=",
"'normal_reference'",
"bad_kde",
"=",
"sm",
".",
"nonparametric",
".",
"KDEMultivariate",
"(",
"data",
"=",
"train_data_bad",
",",
"var_type",
"=",
"self",
".",
"kde_vartypes",
",",
"bw",
"=",
"bw_estimation",
")",
"good_kde",
"=",
"sm",
".",
"nonparametric",
".",
"KDEMultivariate",
"(",
"data",
"=",
"train_data_good",
",",
"var_type",
"=",
"self",
".",
"kde_vartypes",
",",
"bw",
"=",
"bw_estimation",
")",
"bad_kde",
".",
"bw",
"=",
"np",
".",
"clip",
"(",
"bad_kde",
".",
"bw",
",",
"self",
".",
"min_bandwidth",
",",
"None",
")",
"good_kde",
".",
"bw",
"=",
"np",
".",
"clip",
"(",
"good_kde",
".",
"bw",
",",
"self",
".",
"min_bandwidth",
",",
"None",
")",
"self",
".",
"kde_models",
"[",
"budget",
"]",
"=",
"{",
"'good'",
":",
"good_kde",
",",
"'bad'",
":",
"bad_kde",
"}",
"# update probs for the categorical parameters for later sampling",
"logger",
".",
"debug",
"(",
"'done building a new model for budget %f based on %i/%i split\\nBest loss for this budget:%f\\n'",
"%",
"(",
"budget",
",",
"n_good",
",",
"n_bad",
",",
"np",
".",
"min",
"(",
"train_losses",
")",
")",
")"
] | Function to register finished runs. Every time a run has finished, this function should be called
to register it with the loss.
Parameters:
-----------
loss: float
the loss of the parameters
budget: float
the budget of the parameters
parameters: dict
the parameters of this trial
update_model: bool
whether use this parameter to update BP model
Returns
-------
None | [
"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.
scope: Optional scope for `variable_scope`.
reuse: Boolean, whether to reuse the weights of a previous layer
by the same name.
Returns:
A tensor with the same shape and data dtype as `inputs`.
'''
with tf.variable_scope(scope):
inputs_shape = inputs.get_shape()
params_shape = inputs_shape[-1:]
mean, variance = tf.nn.moments(inputs, [-1], keep_dims=True)
beta = tf.Variable(tf.zeros(params_shape))
gamma = tf.Variable(tf.ones(params_shape))
normalized = (inputs - mean) / ((variance + epsilon) ** (.5))
outputs = gamma * normalized + beta
return outputs | 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.
scope: Optional scope for `variable_scope`.
reuse: Boolean, whether to reuse the weights of a previous layer
by the same name.
Returns:
A tensor with the same shape and data dtype as `inputs`.
'''
with tf.variable_scope(scope):
inputs_shape = inputs.get_shape()
params_shape = inputs_shape[-1:]
mean, variance = tf.nn.moments(inputs, [-1], keep_dims=True)
beta = tf.Variable(tf.zeros(params_shape))
gamma = tf.Variable(tf.ones(params_shape))
normalized = (inputs - mean) / ((variance + epsilon) ** (.5))
outputs = gamma * normalized + beta
return outputs | [
"def",
"normalize",
"(",
"inputs",
",",
"epsilon",
"=",
"1e-8",
",",
"scope",
"=",
"\"ln\"",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"scope",
")",
":",
"inputs_shape",
"=",
"inputs",
".",
"get_shape",
"(",
")",
"params_shape",
"=",
"inputs_shape",
"[",
"-",
"1",
":",
"]",
"mean",
",",
"variance",
"=",
"tf",
".",
"nn",
".",
"moments",
"(",
"inputs",
",",
"[",
"-",
"1",
"]",
",",
"keep_dims",
"=",
"True",
")",
"beta",
"=",
"tf",
".",
"Variable",
"(",
"tf",
".",
"zeros",
"(",
"params_shape",
")",
")",
"gamma",
"=",
"tf",
".",
"Variable",
"(",
"tf",
".",
"ones",
"(",
"params_shape",
")",
")",
"normalized",
"=",
"(",
"inputs",
"-",
"mean",
")",
"/",
"(",
"(",
"variance",
"+",
"epsilon",
")",
"**",
"(",
".5",
")",
")",
"outputs",
"=",
"gamma",
"*",
"normalized",
"+",
"beta",
"return",
"outputs"
] | Applies layer normalization.
Args:
inputs: A tensor with 2 or more dimensions, where the first dimension has
`batch_size`.
epsilon: A floating number. A very small number for preventing ZeroDivision Error.
scope: Optional scope for `variable_scope`.
reuse: Boolean, whether to reuse the weights of a previous layer
by the same name.
Returns:
A tensor with the same shape and data dtype as `inputs`. | [
"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 = Shape[0]
T = Shape[1]
num_units = Shape[2]
with tf.variable_scope(scope, reuse=reuse):
position_ind = tf.tile(tf.expand_dims(tf.range(T), 0), [N, 1])
# First part of the PE function: sin and cos argument
# Second part, apply the cosine to even columns and sin to odds.
X = tf.expand_dims(tf.cast(tf.range(T), tf.float32), axis=1)
Y = tf.expand_dims(
tf.cast(10000 ** -(2 * tf.range(num_units) / num_units), tf.float32), axis=0)
h1 = tf.cast((tf.range(num_units) + 1) % 2, tf.float32)
h2 = tf.cast((tf.range(num_units) % 2), tf.float32)
position_enc = tf.multiply(X, Y)
position_enc = tf.sin(position_enc) * tf.multiply(tf.ones_like(X), h1) + \
tf.cos(position_enc) * tf.multiply(tf.ones_like(X), h2)
# Convert to a tensor
lookup_table = position_enc
if zero_pad:
lookup_table = tf.concat((tf.zeros(shape=[1, num_units]),
lookup_table[1:, :]), 0)
outputs = tf.nn.embedding_lookup(lookup_table, position_ind)
if scale:
outputs = outputs * tf.sqrt(tf.cast(num_units, tf.float32))
return outputs | 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 = Shape[0]
T = Shape[1]
num_units = Shape[2]
with tf.variable_scope(scope, reuse=reuse):
position_ind = tf.tile(tf.expand_dims(tf.range(T), 0), [N, 1])
# First part of the PE function: sin and cos argument
# Second part, apply the cosine to even columns and sin to odds.
X = tf.expand_dims(tf.cast(tf.range(T), tf.float32), axis=1)
Y = tf.expand_dims(
tf.cast(10000 ** -(2 * tf.range(num_units) / num_units), tf.float32), axis=0)
h1 = tf.cast((tf.range(num_units) + 1) % 2, tf.float32)
h2 = tf.cast((tf.range(num_units) % 2), tf.float32)
position_enc = tf.multiply(X, Y)
position_enc = tf.sin(position_enc) * tf.multiply(tf.ones_like(X), h1) + \
tf.cos(position_enc) * tf.multiply(tf.ones_like(X), h2)
# Convert to a tensor
lookup_table = position_enc
if zero_pad:
lookup_table = tf.concat((tf.zeros(shape=[1, num_units]),
lookup_table[1:, :]), 0)
outputs = tf.nn.embedding_lookup(lookup_table, position_ind)
if scale:
outputs = outputs * tf.sqrt(tf.cast(num_units, tf.float32))
return outputs | [
"def",
"positional_encoding",
"(",
"inputs",
",",
"num_units",
"=",
"None",
",",
"zero_pad",
"=",
"True",
",",
"scale",
"=",
"True",
",",
"scope",
"=",
"\"positional_encoding\"",
",",
"reuse",
"=",
"None",
")",
":",
"Shape",
"=",
"tf",
".",
"shape",
"(",
"inputs",
")",
"N",
"=",
"Shape",
"[",
"0",
"]",
"T",
"=",
"Shape",
"[",
"1",
"]",
"num_units",
"=",
"Shape",
"[",
"2",
"]",
"with",
"tf",
".",
"variable_scope",
"(",
"scope",
",",
"reuse",
"=",
"reuse",
")",
":",
"position_ind",
"=",
"tf",
".",
"tile",
"(",
"tf",
".",
"expand_dims",
"(",
"tf",
".",
"range",
"(",
"T",
")",
",",
"0",
")",
",",
"[",
"N",
",",
"1",
"]",
")",
"# First part of the PE function: sin and cos argument",
"# Second part, apply the cosine to even columns and sin to odds.",
"X",
"=",
"tf",
".",
"expand_dims",
"(",
"tf",
".",
"cast",
"(",
"tf",
".",
"range",
"(",
"T",
")",
",",
"tf",
".",
"float32",
")",
",",
"axis",
"=",
"1",
")",
"Y",
"=",
"tf",
".",
"expand_dims",
"(",
"tf",
".",
"cast",
"(",
"10000",
"**",
"-",
"(",
"2",
"*",
"tf",
".",
"range",
"(",
"num_units",
")",
"/",
"num_units",
")",
",",
"tf",
".",
"float32",
")",
",",
"axis",
"=",
"0",
")",
"h1",
"=",
"tf",
".",
"cast",
"(",
"(",
"tf",
".",
"range",
"(",
"num_units",
")",
"+",
"1",
")",
"%",
"2",
",",
"tf",
".",
"float32",
")",
"h2",
"=",
"tf",
".",
"cast",
"(",
"(",
"tf",
".",
"range",
"(",
"num_units",
")",
"%",
"2",
")",
",",
"tf",
".",
"float32",
")",
"position_enc",
"=",
"tf",
".",
"multiply",
"(",
"X",
",",
"Y",
")",
"position_enc",
"=",
"tf",
".",
"sin",
"(",
"position_enc",
")",
"*",
"tf",
".",
"multiply",
"(",
"tf",
".",
"ones_like",
"(",
"X",
")",
",",
"h1",
")",
"+",
"tf",
".",
"cos",
"(",
"position_enc",
")",
"*",
"tf",
".",
"multiply",
"(",
"tf",
".",
"ones_like",
"(",
"X",
")",
",",
"h2",
")",
"# Convert to a tensor",
"lookup_table",
"=",
"position_enc",
"if",
"zero_pad",
":",
"lookup_table",
"=",
"tf",
".",
"concat",
"(",
"(",
"tf",
".",
"zeros",
"(",
"shape",
"=",
"[",
"1",
",",
"num_units",
"]",
")",
",",
"lookup_table",
"[",
"1",
":",
",",
":",
"]",
")",
",",
"0",
")",
"outputs",
"=",
"tf",
".",
"nn",
".",
"embedding_lookup",
"(",
"lookup_table",
",",
"position_ind",
")",
"if",
"scale",
":",
"outputs",
"=",
"outputs",
"*",
"tf",
".",
"sqrt",
"(",
"tf",
".",
"cast",
"(",
"num_units",
",",
"tf",
".",
"float32",
")",
")",
"return",
"outputs"
] | 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 reuse the weights of a previous layer
by the same name.
Returns:
A 3d tensor with the same shape and dtype as inputs
'''
with tf.variable_scope(scope):
# Inner layer
params = {"inputs": inputs, "filters": num_units[0], "kernel_size": 1,
"activation": tf.nn.relu, "use_bias": True}
outputs = tf.layers.conv1d(**params)
# Readout layer
params = {"inputs": outputs, "filters": num_units[1], "kernel_size": 1,
"activation": None, "use_bias": True}
outputs = tf.layers.conv1d(**params)
# Residual connection
outputs += inputs
# Normalize
outputs = normalize(outputs)
return outputs | 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 reuse the weights of a previous layer
by the same name.
Returns:
A 3d tensor with the same shape and dtype as inputs
'''
with tf.variable_scope(scope):
# Inner layer
params = {"inputs": inputs, "filters": num_units[0], "kernel_size": 1,
"activation": tf.nn.relu, "use_bias": True}
outputs = tf.layers.conv1d(**params)
# Readout layer
params = {"inputs": outputs, "filters": num_units[1], "kernel_size": 1,
"activation": None, "use_bias": True}
outputs = tf.layers.conv1d(**params)
# Residual connection
outputs += inputs
# Normalize
outputs = normalize(outputs)
return outputs | [
"def",
"feedforward",
"(",
"inputs",
",",
"num_units",
",",
"scope",
"=",
"\"multihead_attention\"",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"scope",
")",
":",
"# Inner layer",
"params",
"=",
"{",
"\"inputs\"",
":",
"inputs",
",",
"\"filters\"",
":",
"num_units",
"[",
"0",
"]",
",",
"\"kernel_size\"",
":",
"1",
",",
"\"activation\"",
":",
"tf",
".",
"nn",
".",
"relu",
",",
"\"use_bias\"",
":",
"True",
"}",
"outputs",
"=",
"tf",
".",
"layers",
".",
"conv1d",
"(",
"*",
"*",
"params",
")",
"# Readout layer",
"params",
"=",
"{",
"\"inputs\"",
":",
"outputs",
",",
"\"filters\"",
":",
"num_units",
"[",
"1",
"]",
",",
"\"kernel_size\"",
":",
"1",
",",
"\"activation\"",
":",
"None",
",",
"\"use_bias\"",
":",
"True",
"}",
"outputs",
"=",
"tf",
".",
"layers",
".",
"conv1d",
"(",
"*",
"*",
"params",
")",
"# Residual connection",
"outputs",
"+=",
"inputs",
"# Normalize",
"outputs",
"=",
"normalize",
"(",
"outputs",
")",
"return",
"outputs"
] | Point-wise feed forward net.
Args:
inputs: A 3d tensor with shape of [N, T, C].
num_units: A list of two integers.
scope: Optional scope for `variable_scope`.
reuse: Boolean, whether to reuse the weights of a previous layer
by the same name.
Returns:
A 3d tensor with the same shape and dtype as inputs | [
"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
else:
return False, response
else:
time.sleep(3)
return False, response | 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
else:
return False, response
else:
time.sleep(3)
return False, response | [
"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",
":",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"return",
"True",
",",
"response",
"else",
":",
"return",
"False",
",",
"response",
"else",
":",
"time",
".",
"sleep",
"(",
"3",
")",
"return",
"False",
",",
"response"
] | Check if restful server is ready | [
"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",
",",
"response",
"return",
"False",
",",
"None"
] | 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_DIR",
",",
"config_file_name",
",",
"'stderr'",
")",
"return",
"stdout_full_path",
",",
"stderr_full_path"
] | 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",
"(",
"'\\n\\n'",
")",
"print_normal",
"(",
"' Stderr:'",
")",
"print",
"(",
"check_output_command",
"(",
"stderr_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
'''
def _generate_installation_path(sitepackages_path):
python_dir = get_python_dir(sitepackages_path)
entry_file = os.path.join(python_dir, 'nni', 'main.js')
if os.path.isfile(entry_file):
return python_dir
return None
for sitepackage in sitepackages:
python_dir = _generate_installation_path(sitepackage)
if python_dir:
return python_dir
return None
if os.getenv('VIRTUAL_ENV'):
# if 'virtualenv' package is used, `site` has not attr getsitepackages, so we will instead use VIRTUAL_ENV
# Note that conda venv will not have VIRTUAL_ENV
python_dir = os.getenv('VIRTUAL_ENV')
else:
python_sitepackage = site.getsitepackages()[0]
# If system-wide python is used, we will give priority to using `local sitepackage`--"usersitepackages()" given that nni exists there
if python_sitepackage.startswith('/usr') or python_sitepackage.startswith('/Library'):
python_dir = try_installation_path_sequentially(site.getusersitepackages(), site.getsitepackages()[0])
else:
python_dir = try_installation_path_sequentially(site.getsitepackages()[0], site.getusersitepackages())
if python_dir:
entry_file = os.path.join(python_dir, 'nni', 'main.js')
if os.path.isfile(entry_file):
return os.path.join(python_dir, 'nni')
print_error('Fail to find nni under python library')
exit(1) | 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 _generate_installation_path(sitepackages_path):
python_dir = get_python_dir(sitepackages_path)
entry_file = os.path.join(python_dir, 'nni', 'main.js')
if os.path.isfile(entry_file):
return python_dir
return None
for sitepackage in sitepackages:
python_dir = _generate_installation_path(sitepackage)
if python_dir:
return python_dir
return None
if os.getenv('VIRTUAL_ENV'):
# if 'virtualenv' package is used, `site` has not attr getsitepackages, so we will instead use VIRTUAL_ENV
# Note that conda venv will not have VIRTUAL_ENV
python_dir = os.getenv('VIRTUAL_ENV')
else:
python_sitepackage = site.getsitepackages()[0]
# If system-wide python is used, we will give priority to using `local sitepackage`--"usersitepackages()" given that nni exists there
if python_sitepackage.startswith('/usr') or python_sitepackage.startswith('/Library'):
python_dir = try_installation_path_sequentially(site.getusersitepackages(), site.getsitepackages()[0])
else:
python_dir = try_installation_path_sequentially(site.getsitepackages()[0], site.getusersitepackages())
if python_dir:
entry_file = os.path.join(python_dir, 'nni', 'main.js')
if os.path.isfile(entry_file):
return os.path.join(python_dir, 'nni')
print_error('Fail to find nni under python library')
exit(1) | [
"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_path",
"(",
"sitepackages_path",
")",
":",
"python_dir",
"=",
"get_python_dir",
"(",
"sitepackages_path",
")",
"entry_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"python_dir",
",",
"'nni'",
",",
"'main.js'",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"entry_file",
")",
":",
"return",
"python_dir",
"return",
"None",
"for",
"sitepackage",
"in",
"sitepackages",
":",
"python_dir",
"=",
"_generate_installation_path",
"(",
"sitepackage",
")",
"if",
"python_dir",
":",
"return",
"python_dir",
"return",
"None",
"if",
"os",
".",
"getenv",
"(",
"'VIRTUAL_ENV'",
")",
":",
"# if 'virtualenv' package is used, `site` has not attr getsitepackages, so we will instead use VIRTUAL_ENV",
"# Note that conda venv will not have VIRTUAL_ENV",
"python_dir",
"=",
"os",
".",
"getenv",
"(",
"'VIRTUAL_ENV'",
")",
"else",
":",
"python_sitepackage",
"=",
"site",
".",
"getsitepackages",
"(",
")",
"[",
"0",
"]",
"# If system-wide python is used, we will give priority to using `local sitepackage`--\"usersitepackages()\" given that nni exists there",
"if",
"python_sitepackage",
".",
"startswith",
"(",
"'/usr'",
")",
"or",
"python_sitepackage",
".",
"startswith",
"(",
"'/Library'",
")",
":",
"python_dir",
"=",
"try_installation_path_sequentially",
"(",
"site",
".",
"getusersitepackages",
"(",
")",
",",
"site",
".",
"getsitepackages",
"(",
")",
"[",
"0",
"]",
")",
"else",
":",
"python_dir",
"=",
"try_installation_path_sequentially",
"(",
"site",
".",
"getsitepackages",
"(",
")",
"[",
"0",
"]",
",",
"site",
".",
"getusersitepackages",
"(",
")",
")",
"if",
"python_dir",
":",
"entry_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"python_dir",
",",
"'nni'",
",",
"'main.js'",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"entry_file",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"python_dir",
",",
"'nni'",
")",
"print_error",
"(",
"'Fail to find nni under python library'",
")",
"exit",
"(",
"1",
")"
] | 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 use \'nnictl create --help\' to get help information' % port)
exit(1)
if (platform != 'local') and detect_port(int(port) + 1):
print_error('PAI mode need an additional adjacent port %d, and the port %d is used by another process!\n' \
'You could set another port to start experiment!\n' \
'You could use \'nnictl create --help\' to get help information' % ((int(port) + 1), (int(port) + 1)))
exit(1)
print_normal('Starting restful server...')
entry_dir = get_nni_installation_path()
entry_file = os.path.join(entry_dir, 'main.js')
node_command = 'node'
if sys.platform == 'win32':
node_command = os.path.join(entry_dir[:-3], 'Scripts', 'node.exe')
cmds = [node_command, entry_file, '--port', str(port), '--mode', platform, '--start_mode', mode]
if log_dir is not None:
cmds += ['--log_dir', log_dir]
if log_level is not None:
cmds += ['--log_level', log_level]
if mode == 'resume':
cmds += ['--experiment_id', experiment_id]
stdout_full_path, stderr_full_path = get_log_path(config_file_name)
stdout_file = open(stdout_full_path, 'a+')
stderr_file = open(stderr_full_path, 'a+')
time_now = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
#add time information in the header of log files
log_header = LOG_HEADER % str(time_now)
stdout_file.write(log_header)
stderr_file.write(log_header)
if sys.platform == 'win32':
from subprocess import CREATE_NEW_PROCESS_GROUP
process = Popen(cmds, cwd=entry_dir, stdout=stdout_file, stderr=stderr_file, creationflags=CREATE_NEW_PROCESS_GROUP)
else:
process = Popen(cmds, cwd=entry_dir, stdout=stdout_file, stderr=stderr_file)
return process, str(time_now) | 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 use \'nnictl create --help\' to get help information' % port)
exit(1)
if (platform != 'local') and detect_port(int(port) + 1):
print_error('PAI mode need an additional adjacent port %d, and the port %d is used by another process!\n' \
'You could set another port to start experiment!\n' \
'You could use \'nnictl create --help\' to get help information' % ((int(port) + 1), (int(port) + 1)))
exit(1)
print_normal('Starting restful server...')
entry_dir = get_nni_installation_path()
entry_file = os.path.join(entry_dir, 'main.js')
node_command = 'node'
if sys.platform == 'win32':
node_command = os.path.join(entry_dir[:-3], 'Scripts', 'node.exe')
cmds = [node_command, entry_file, '--port', str(port), '--mode', platform, '--start_mode', mode]
if log_dir is not None:
cmds += ['--log_dir', log_dir]
if log_level is not None:
cmds += ['--log_level', log_level]
if mode == 'resume':
cmds += ['--experiment_id', experiment_id]
stdout_full_path, stderr_full_path = get_log_path(config_file_name)
stdout_file = open(stdout_full_path, 'a+')
stderr_file = open(stderr_full_path, 'a+')
time_now = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
#add time information in the header of log files
log_header = LOG_HEADER % str(time_now)
stdout_file.write(log_header)
stderr_file.write(log_header)
if sys.platform == 'win32':
from subprocess import CREATE_NEW_PROCESS_GROUP
process = Popen(cmds, cwd=entry_dir, stdout=stdout_file, stderr=stderr_file, creationflags=CREATE_NEW_PROCESS_GROUP)
else:
process = Popen(cmds, cwd=entry_dir, stdout=stdout_file, stderr=stderr_file)
return process, str(time_now) | [
"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",
")",
"if",
"detect_port",
"(",
"port",
")",
":",
"print_error",
"(",
"'Port %s is used by another process, please reset the port!\\n'",
"'You could use \\'nnictl create --help\\' to get help information'",
"%",
"port",
")",
"exit",
"(",
"1",
")",
"if",
"(",
"platform",
"!=",
"'local'",
")",
"and",
"detect_port",
"(",
"int",
"(",
"port",
")",
"+",
"1",
")",
":",
"print_error",
"(",
"'PAI mode need an additional adjacent port %d, and the port %d is used by another process!\\n'",
"'You could set another port to start experiment!\\n'",
"'You could use \\'nnictl create --help\\' to get help information'",
"%",
"(",
"(",
"int",
"(",
"port",
")",
"+",
"1",
")",
",",
"(",
"int",
"(",
"port",
")",
"+",
"1",
")",
")",
")",
"exit",
"(",
"1",
")",
"print_normal",
"(",
"'Starting restful server...'",
")",
"entry_dir",
"=",
"get_nni_installation_path",
"(",
")",
"entry_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"entry_dir",
",",
"'main.js'",
")",
"node_command",
"=",
"'node'",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"node_command",
"=",
"os",
".",
"path",
".",
"join",
"(",
"entry_dir",
"[",
":",
"-",
"3",
"]",
",",
"'Scripts'",
",",
"'node.exe'",
")",
"cmds",
"=",
"[",
"node_command",
",",
"entry_file",
",",
"'--port'",
",",
"str",
"(",
"port",
")",
",",
"'--mode'",
",",
"platform",
",",
"'--start_mode'",
",",
"mode",
"]",
"if",
"log_dir",
"is",
"not",
"None",
":",
"cmds",
"+=",
"[",
"'--log_dir'",
",",
"log_dir",
"]",
"if",
"log_level",
"is",
"not",
"None",
":",
"cmds",
"+=",
"[",
"'--log_level'",
",",
"log_level",
"]",
"if",
"mode",
"==",
"'resume'",
":",
"cmds",
"+=",
"[",
"'--experiment_id'",
",",
"experiment_id",
"]",
"stdout_full_path",
",",
"stderr_full_path",
"=",
"get_log_path",
"(",
"config_file_name",
")",
"stdout_file",
"=",
"open",
"(",
"stdout_full_path",
",",
"'a+'",
")",
"stderr_file",
"=",
"open",
"(",
"stderr_full_path",
",",
"'a+'",
")",
"time_now",
"=",
"time",
".",
"strftime",
"(",
"'%Y-%m-%d %H:%M:%S'",
",",
"time",
".",
"localtime",
"(",
"time",
".",
"time",
"(",
")",
")",
")",
"#add time information in the header of log files",
"log_header",
"=",
"LOG_HEADER",
"%",
"str",
"(",
"time_now",
")",
"stdout_file",
".",
"write",
"(",
"log_header",
")",
"stderr_file",
".",
"write",
"(",
"log_header",
")",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"from",
"subprocess",
"import",
"CREATE_NEW_PROCESS_GROUP",
"process",
"=",
"Popen",
"(",
"cmds",
",",
"cwd",
"=",
"entry_dir",
",",
"stdout",
"=",
"stdout_file",
",",
"stderr",
"=",
"stderr_file",
",",
"creationflags",
"=",
"CREATE_NEW_PROCESS_GROUP",
")",
"else",
":",
"process",
"=",
"Popen",
"(",
"cmds",
",",
"cwd",
"=",
"entry_dir",
",",
"stdout",
"=",
"stdout_file",
",",
"stderr",
"=",
"stderr_file",
")",
"return",
"process",
",",
"str",
"(",
"time_now",
")"
] | 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):
return True
else:
print('Error message is {}'.format(response.text))
_, stderr_full_path = get_log_path(config_file_name)
if response:
with open(stderr_full_path, 'a+') as fout:
fout.write(json.dumps(json.loads(response.text), indent=4, sort_keys=True, separators=(',', ':')))
return False | 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):
return True
else:
print('Error message is {}'.format(response.text))
_, stderr_full_path = get_log_path(config_file_name)
if response:
with open(stderr_full_path, 'a+') as fout:
fout.write(json.dumps(json.loads(response.text), indent=4, sort_keys=True, separators=(',', ':')))
return False | [
"def",
"set_trial_config",
"(",
"experiment_config",
",",
"port",
",",
"config_file_name",
")",
":",
"request_data",
"=",
"dict",
"(",
")",
"request_data",
"[",
"'trial_config'",
"]",
"=",
"experiment_config",
"[",
"'trial'",
"]",
"response",
"=",
"rest_put",
"(",
"cluster_metadata_url",
"(",
"port",
")",
",",
"json",
".",
"dumps",
"(",
"request_data",
")",
",",
"REST_TIME_OUT",
")",
"if",
"check_response",
"(",
"response",
")",
":",
"return",
"True",
"else",
":",
"print",
"(",
"'Error message is {}'",
".",
"format",
"(",
"response",
".",
"text",
")",
")",
"_",
",",
"stderr_full_path",
"=",
"get_log_path",
"(",
"config_file_name",
")",
"if",
"response",
":",
"with",
"open",
"(",
"stderr_full_path",
",",
"'a+'",
")",
"as",
"fout",
":",
"fout",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"json",
".",
"loads",
"(",
"response",
".",
"text",
")",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
",",
"separators",
"=",
"(",
"','",
",",
"':'",
")",
")",
")",
"return",
"False"
] | set 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['local_config'].get('gpuIndices') \
and isinstance(request_data['local_config'].get('gpuIndices'), int):
request_data['local_config']['gpuIndices'] = str(request_data['local_config'].get('gpuIndices'))
response = rest_put(cluster_metadata_url(port), json.dumps(request_data), REST_TIME_OUT)
err_message = ''
if not response or not check_response(response):
if response is not None:
err_message = response.text
_, stderr_full_path = get_log_path(config_file_name)
with open(stderr_full_path, 'a+') as fout:
fout.write(json.dumps(json.loads(err_message), indent=4, sort_keys=True, separators=(',', ':')))
return False, err_message
return set_trial_config(experiment_config, port, config_file_name) | 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['local_config'].get('gpuIndices') \
and isinstance(request_data['local_config'].get('gpuIndices'), int):
request_data['local_config']['gpuIndices'] = str(request_data['local_config'].get('gpuIndices'))
response = rest_put(cluster_metadata_url(port), json.dumps(request_data), REST_TIME_OUT)
err_message = ''
if not response or not check_response(response):
if response is not None:
err_message = response.text
_, stderr_full_path = get_log_path(config_file_name)
with open(stderr_full_path, 'a+') as fout:
fout.write(json.dumps(json.loads(err_message), indent=4, sort_keys=True, separators=(',', ':')))
return False, err_message
return set_trial_config(experiment_config, port, config_file_name) | [
"def",
"set_local_config",
"(",
"experiment_config",
",",
"port",
",",
"config_file_name",
")",
":",
"#set machine_list",
"request_data",
"=",
"dict",
"(",
")",
"if",
"experiment_config",
".",
"get",
"(",
"'localConfig'",
")",
":",
"request_data",
"[",
"'local_config'",
"]",
"=",
"experiment_config",
"[",
"'localConfig'",
"]",
"if",
"request_data",
"[",
"'local_config'",
"]",
"and",
"request_data",
"[",
"'local_config'",
"]",
".",
"get",
"(",
"'gpuIndices'",
")",
"and",
"isinstance",
"(",
"request_data",
"[",
"'local_config'",
"]",
".",
"get",
"(",
"'gpuIndices'",
")",
",",
"int",
")",
":",
"request_data",
"[",
"'local_config'",
"]",
"[",
"'gpuIndices'",
"]",
"=",
"str",
"(",
"request_data",
"[",
"'local_config'",
"]",
".",
"get",
"(",
"'gpuIndices'",
")",
")",
"response",
"=",
"rest_put",
"(",
"cluster_metadata_url",
"(",
"port",
")",
",",
"json",
".",
"dumps",
"(",
"request_data",
")",
",",
"REST_TIME_OUT",
")",
"err_message",
"=",
"''",
"if",
"not",
"response",
"or",
"not",
"check_response",
"(",
"response",
")",
":",
"if",
"response",
"is",
"not",
"None",
":",
"err_message",
"=",
"response",
".",
"text",
"_",
",",
"stderr_full_path",
"=",
"get_log_path",
"(",
"config_file_name",
")",
"with",
"open",
"(",
"stderr_full_path",
",",
"'a+'",
")",
"as",
"fout",
":",
"fout",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"json",
".",
"loads",
"(",
"err_message",
")",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
",",
"separators",
"=",
"(",
"','",
",",
"':'",
")",
")",
")",
"return",
"False",
",",
"err_message",
"return",
"set_trial_config",
"(",
"experiment_config",
",",
"port",
",",
"config_file_name",
")"
] | 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'])):
if isinstance(request_data['machine_list'][i].get('gpuIndices'), int):
request_data['machine_list'][i]['gpuIndices'] = str(request_data['machine_list'][i].get('gpuIndices'))
response = rest_put(cluster_metadata_url(port), json.dumps(request_data), REST_TIME_OUT)
err_message = ''
if not response or not check_response(response):
if response is not None:
err_message = response.text
_, stderr_full_path = get_log_path(config_file_name)
with open(stderr_full_path, 'a+') as fout:
fout.write(json.dumps(json.loads(err_message), indent=4, sort_keys=True, separators=(',', ':')))
return False, err_message
result, message = setNNIManagerIp(experiment_config, port, config_file_name)
if not result:
return result, message
#set trial_config
return set_trial_config(experiment_config, port, config_file_name), err_message | 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'])):
if isinstance(request_data['machine_list'][i].get('gpuIndices'), int):
request_data['machine_list'][i]['gpuIndices'] = str(request_data['machine_list'][i].get('gpuIndices'))
response = rest_put(cluster_metadata_url(port), json.dumps(request_data), REST_TIME_OUT)
err_message = ''
if not response or not check_response(response):
if response is not None:
err_message = response.text
_, stderr_full_path = get_log_path(config_file_name)
with open(stderr_full_path, 'a+') as fout:
fout.write(json.dumps(json.loads(err_message), indent=4, sort_keys=True, separators=(',', ':')))
return False, err_message
result, message = setNNIManagerIp(experiment_config, port, config_file_name)
if not result:
return result, message
#set trial_config
return set_trial_config(experiment_config, port, config_file_name), err_message | [
"def",
"set_remote_config",
"(",
"experiment_config",
",",
"port",
",",
"config_file_name",
")",
":",
"#set machine_list",
"request_data",
"=",
"dict",
"(",
")",
"request_data",
"[",
"'machine_list'",
"]",
"=",
"experiment_config",
"[",
"'machineList'",
"]",
"if",
"request_data",
"[",
"'machine_list'",
"]",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"request_data",
"[",
"'machine_list'",
"]",
")",
")",
":",
"if",
"isinstance",
"(",
"request_data",
"[",
"'machine_list'",
"]",
"[",
"i",
"]",
".",
"get",
"(",
"'gpuIndices'",
")",
",",
"int",
")",
":",
"request_data",
"[",
"'machine_list'",
"]",
"[",
"i",
"]",
"[",
"'gpuIndices'",
"]",
"=",
"str",
"(",
"request_data",
"[",
"'machine_list'",
"]",
"[",
"i",
"]",
".",
"get",
"(",
"'gpuIndices'",
")",
")",
"response",
"=",
"rest_put",
"(",
"cluster_metadata_url",
"(",
"port",
")",
",",
"json",
".",
"dumps",
"(",
"request_data",
")",
",",
"REST_TIME_OUT",
")",
"err_message",
"=",
"''",
"if",
"not",
"response",
"or",
"not",
"check_response",
"(",
"response",
")",
":",
"if",
"response",
"is",
"not",
"None",
":",
"err_message",
"=",
"response",
".",
"text",
"_",
",",
"stderr_full_path",
"=",
"get_log_path",
"(",
"config_file_name",
")",
"with",
"open",
"(",
"stderr_full_path",
",",
"'a+'",
")",
"as",
"fout",
":",
"fout",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"json",
".",
"loads",
"(",
"err_message",
")",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
",",
"separators",
"=",
"(",
"','",
",",
"':'",
")",
")",
")",
"return",
"False",
",",
"err_message",
"result",
",",
"message",
"=",
"setNNIManagerIp",
"(",
"experiment_config",
",",
"port",
",",
"config_file_name",
")",
"if",
"not",
"result",
":",
"return",
"result",
",",
"message",
"#set trial_config",
"return",
"set_trial_config",
"(",
"experiment_config",
",",
"port",
",",
"config_file_name",
")",
",",
"err_message"
] | 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_url(port), json.dumps(frameworkcontroller_config_data), REST_TIME_OUT)
err_message = None
if not response or not response.status_code == 200:
if response is not None:
err_message = response.text
_, stderr_full_path = get_log_path(config_file_name)
with open(stderr_full_path, 'a+') as fout:
fout.write(json.dumps(json.loads(err_message), indent=4, sort_keys=True, separators=(',', ':')))
return False, err_message
result, message = setNNIManagerIp(experiment_config, port, config_file_name)
if not result:
return result, message
#set trial_config
return set_trial_config(experiment_config, port, config_file_name), err_message | 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_url(port), json.dumps(frameworkcontroller_config_data), REST_TIME_OUT)
err_message = None
if not response or not response.status_code == 200:
if response is not None:
err_message = response.text
_, stderr_full_path = get_log_path(config_file_name)
with open(stderr_full_path, 'a+') as fout:
fout.write(json.dumps(json.loads(err_message), indent=4, sort_keys=True, separators=(',', ':')))
return False, err_message
result, message = setNNIManagerIp(experiment_config, port, config_file_name)
if not result:
return result, message
#set trial_config
return set_trial_config(experiment_config, port, config_file_name), err_message | [
"def",
"set_frameworkcontroller_config",
"(",
"experiment_config",
",",
"port",
",",
"config_file_name",
")",
":",
"frameworkcontroller_config_data",
"=",
"dict",
"(",
")",
"frameworkcontroller_config_data",
"[",
"'frameworkcontroller_config'",
"]",
"=",
"experiment_config",
"[",
"'frameworkcontrollerConfig'",
"]",
"response",
"=",
"rest_put",
"(",
"cluster_metadata_url",
"(",
"port",
")",
",",
"json",
".",
"dumps",
"(",
"frameworkcontroller_config_data",
")",
",",
"REST_TIME_OUT",
")",
"err_message",
"=",
"None",
"if",
"not",
"response",
"or",
"not",
"response",
".",
"status_code",
"==",
"200",
":",
"if",
"response",
"is",
"not",
"None",
":",
"err_message",
"=",
"response",
".",
"text",
"_",
",",
"stderr_full_path",
"=",
"get_log_path",
"(",
"config_file_name",
")",
"with",
"open",
"(",
"stderr_full_path",
",",
"'a+'",
")",
"as",
"fout",
":",
"fout",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"json",
".",
"loads",
"(",
"err_message",
")",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
",",
"separators",
"=",
"(",
"','",
",",
"':'",
")",
")",
")",
"return",
"False",
",",
"err_message",
"result",
",",
"message",
"=",
"setNNIManagerIp",
"(",
"experiment_config",
",",
"port",
",",
"config_file_name",
")",
"if",
"not",
"result",
":",
"return",
"result",
",",
"message",
"#set trial_config",
"return",
"set_trial_config",
"(",
"experiment_config",
",",
"port",
",",
"config_file_name",
")",
",",
"err_message"
] | 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! \nYou could use \'nnictl resume {id}\' to resume a stopped experiment!\n' \
'You could use \'nnictl experiment list all\' to show all of stopped experiments!')
exit(1)
else:
if experiment_dict.get(args.id) is None:
print_error('Id %s not exist!' % args.id)
exit(1)
if experiment_dict[args.id]['status'] != 'STOPPED':
print_error('Experiment %s is running!' % args.id)
exit(1)
experiment_id = args.id
print_normal('Resuming experiment %s...' % experiment_id)
nni_config = Config(experiment_dict[experiment_id]['fileName'])
experiment_config = nni_config.get_config('experimentConfig')
experiment_id = nni_config.get_config('experimentId')
new_config_file_name = ''.join(random.sample(string.ascii_letters + string.digits, 8))
new_nni_config = Config(new_config_file_name)
new_nni_config.set_config('experimentConfig', experiment_config)
launch_experiment(args, experiment_config, 'resume', new_config_file_name, experiment_id)
new_nni_config.set_config('restServerPort', args.port) | 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! \nYou could use \'nnictl resume {id}\' to resume a stopped experiment!\n' \
'You could use \'nnictl experiment list all\' to show all of stopped experiments!')
exit(1)
else:
if experiment_dict.get(args.id) is None:
print_error('Id %s not exist!' % args.id)
exit(1)
if experiment_dict[args.id]['status'] != 'STOPPED':
print_error('Experiment %s is running!' % args.id)
exit(1)
experiment_id = args.id
print_normal('Resuming experiment %s...' % experiment_id)
nni_config = Config(experiment_dict[experiment_id]['fileName'])
experiment_config = nni_config.get_config('experimentConfig')
experiment_id = nni_config.get_config('experimentId')
new_config_file_name = ''.join(random.sample(string.ascii_letters + string.digits, 8))
new_nni_config = Config(new_config_file_name)
new_nni_config.set_config('experimentConfig', experiment_config)
launch_experiment(args, experiment_config, 'resume', new_config_file_name, experiment_id)
new_nni_config.set_config('restServerPort', args.port) | [
"def",
"resume_experiment",
"(",
"args",
")",
":",
"experiment_config",
"=",
"Experiments",
"(",
")",
"experiment_dict",
"=",
"experiment_config",
".",
"get_all_experiments",
"(",
")",
"experiment_id",
"=",
"None",
"experiment_endTime",
"=",
"None",
"#find the latest stopped experiment",
"if",
"not",
"args",
".",
"id",
":",
"print_error",
"(",
"'Please set experiment id! \\nYou could use \\'nnictl resume {id}\\' to resume a stopped experiment!\\n'",
"'You could use \\'nnictl experiment list all\\' to show all of stopped experiments!'",
")",
"exit",
"(",
"1",
")",
"else",
":",
"if",
"experiment_dict",
".",
"get",
"(",
"args",
".",
"id",
")",
"is",
"None",
":",
"print_error",
"(",
"'Id %s not exist!'",
"%",
"args",
".",
"id",
")",
"exit",
"(",
"1",
")",
"if",
"experiment_dict",
"[",
"args",
".",
"id",
"]",
"[",
"'status'",
"]",
"!=",
"'STOPPED'",
":",
"print_error",
"(",
"'Experiment %s is running!'",
"%",
"args",
".",
"id",
")",
"exit",
"(",
"1",
")",
"experiment_id",
"=",
"args",
".",
"id",
"print_normal",
"(",
"'Resuming experiment %s...'",
"%",
"experiment_id",
")",
"nni_config",
"=",
"Config",
"(",
"experiment_dict",
"[",
"experiment_id",
"]",
"[",
"'fileName'",
"]",
")",
"experiment_config",
"=",
"nni_config",
".",
"get_config",
"(",
"'experimentConfig'",
")",
"experiment_id",
"=",
"nni_config",
".",
"get_config",
"(",
"'experimentId'",
")",
"new_config_file_name",
"=",
"''",
".",
"join",
"(",
"random",
".",
"sample",
"(",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
",",
"8",
")",
")",
"new_nni_config",
"=",
"Config",
"(",
"new_config_file_name",
")",
"new_nni_config",
".",
"set_config",
"(",
"'experimentConfig'",
",",
"experiment_config",
")",
"launch_experiment",
"(",
"args",
",",
"experiment_config",
",",
"'resume'",
",",
"new_config_file_name",
",",
"experiment_id",
")",
"new_nni_config",
".",
"set_config",
"(",
"'restServerPort'",
",",
"args",
".",
"port",
")"
] | 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 config path!')
exit(1)
experiment_config = get_yml_content(config_path)
validate_all_content(experiment_config, config_path)
nni_config.set_config('experimentConfig', experiment_config)
launch_experiment(args, experiment_config, 'new', config_file_name)
nni_config.set_config('restServerPort', args.port) | 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 config path!')
exit(1)
experiment_config = get_yml_content(config_path)
validate_all_content(experiment_config, config_path)
nni_config.set_config('experimentConfig', experiment_config)
launch_experiment(args, experiment_config, 'new', config_file_name)
nni_config.set_config('restServerPort', args.port) | [
"def",
"create_experiment",
"(",
"args",
")",
":",
"config_file_name",
"=",
"''",
".",
"join",
"(",
"random",
".",
"sample",
"(",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
",",
"8",
")",
")",
"nni_config",
"=",
"Config",
"(",
"config_file_name",
")",
"config_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"args",
".",
"config",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"config_path",
")",
":",
"print_error",
"(",
"'Please set correct config path!'",
")",
"exit",
"(",
"1",
")",
"experiment_config",
"=",
"get_yml_content",
"(",
"config_path",
")",
"validate_all_content",
"(",
"experiment_config",
",",
"config_path",
")",
"nni_config",
".",
"set_config",
"(",
"'experimentConfig'",
",",
"experiment_config",
")",
"launch_experiment",
"(",
"args",
",",
"experiment_config",
",",
"'new'",
",",
"config_file_name",
")",
"nni_config",
".",
"set_config",
"(",
"'restServerPort'",
",",
"args",
".",
"port",
")"
] | 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}
Returns
-------
int
The expected matrix at pos with all the active function's prediction
"""
ret = 0
for i in range(self.effective_model_num):
model = self.effective_model[i]
y = self.predict_y(model, pos)
ret += sample[i] * y
return ret | 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}
Returns
-------
int
The expected matrix at pos with all the active function's prediction
"""
ret = 0
for i in range(self.effective_model_num):
model = self.effective_model[i]
y = self.predict_y(model, pos)
ret += sample[i] * y
return ret | [
"def",
"f_comb",
"(",
"self",
",",
"pos",
",",
"sample",
")",
":",
"ret",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"effective_model_num",
")",
":",
"model",
"=",
"self",
".",
"effective_model",
"[",
"i",
"]",
"y",
"=",
"self",
".",
"predict_y",
"(",
"model",
",",
"pos",
")",
"ret",
"+=",
"sample",
"[",
"i",
"]",
"*",
"y",
"return",
"ret"
] | 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
The expected matrix at pos with all the active function's prediction | [
"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
# Create a diagnostic regression model which removes the sample that we want to evaluate
diagnostic_regressor_gp = gp_create_model.create_model(\
samples_x[0:samples_idx] + samples_x[samples_idx + 1:],\
samples_y_aggregation[0:samples_idx] + samples_y_aggregation[samples_idx + 1:])
mu, sigma = gp_prediction.predict(samples_x[samples_idx], diagnostic_regressor_gp['model'])
# 2.33 is the z-score for 98% confidence level
if abs(samples_y_aggregation[samples_idx] - mu) > (2.33 * sigma):
outlier = {"samples_idx": samples_idx,
"expected_mu": mu,
"expected_sigma": sigma,
"difference": abs(samples_y_aggregation[samples_idx] - mu) - (2.33 * sigma)}
return outlier | 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
# Create a diagnostic regression model which removes the sample that we want to evaluate
diagnostic_regressor_gp = gp_create_model.create_model(\
samples_x[0:samples_idx] + samples_x[samples_idx + 1:],\
samples_y_aggregation[0:samples_idx] + samples_y_aggregation[samples_idx + 1:])
mu, sigma = gp_prediction.predict(samples_x[samples_idx], diagnostic_regressor_gp['model'])
# 2.33 is the z-score for 98% confidence level
if abs(samples_y_aggregation[samples_idx] - mu) > (2.33 * sigma):
outlier = {"samples_idx": samples_idx,
"expected_mu": mu,
"expected_sigma": sigma,
"difference": abs(samples_y_aggregation[samples_idx] - mu) - (2.33 * sigma)}
return outlier | [
"def",
"_outlierDetection_threaded",
"(",
"inputs",
")",
":",
"[",
"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",
"# Create a diagnostic regression model which removes the sample that we want to evaluate",
"diagnostic_regressor_gp",
"=",
"gp_create_model",
".",
"create_model",
"(",
"samples_x",
"[",
"0",
":",
"samples_idx",
"]",
"+",
"samples_x",
"[",
"samples_idx",
"+",
"1",
":",
"]",
",",
"samples_y_aggregation",
"[",
"0",
":",
"samples_idx",
"]",
"+",
"samples_y_aggregation",
"[",
"samples_idx",
"+",
"1",
":",
"]",
")",
"mu",
",",
"sigma",
"=",
"gp_prediction",
".",
"predict",
"(",
"samples_x",
"[",
"samples_idx",
"]",
",",
"diagnostic_regressor_gp",
"[",
"'model'",
"]",
")",
"# 2.33 is the z-score for 98% confidence level",
"if",
"abs",
"(",
"samples_y_aggregation",
"[",
"samples_idx",
"]",
"-",
"mu",
")",
">",
"(",
"2.33",
"*",
"sigma",
")",
":",
"outlier",
"=",
"{",
"\"samples_idx\"",
":",
"samples_idx",
",",
"\"expected_mu\"",
":",
"mu",
",",
"\"expected_sigma\"",
":",
"sigma",
",",
"\"difference\"",
":",
"abs",
"(",
"samples_y_aggregation",
"[",
"samples_idx",
"]",
"-",
"mu",
")",
"-",
"(",
"2.33",
"*",
"sigma",
")",
"}",
"return",
"outlier"
] | 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(4, len(threads_inputs)))
threads_results = threads_pool.map(_outlierDetection_threaded, threads_inputs)
threads_pool.close()
threads_pool.join()
for threads_result in threads_results:
if threads_result is not None:
outliers.append(threads_result)
else:
print("error here.")
outliers = None if len(outliers) == 0 else outliers
return outliers | 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(4, len(threads_inputs)))
threads_results = threads_pool.map(_outlierDetection_threaded, threads_inputs)
threads_pool.close()
threads_pool.join()
for threads_result in threads_results:
if threads_result is not None:
outliers.append(threads_result)
else:
print("error here.")
outliers = None if len(outliers) == 0 else outliers
return outliers | [
"def",
"outlierDetection_threaded",
"(",
"samples_x",
",",
"samples_y_aggregation",
")",
":",
"outliers",
"=",
"[",
"]",
"threads_inputs",
"=",
"[",
"[",
"samples_idx",
",",
"samples_x",
",",
"samples_y_aggregation",
"]",
"for",
"samples_idx",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"samples_x",
")",
")",
"]",
"threads_pool",
"=",
"ThreadPool",
"(",
"min",
"(",
"4",
",",
"len",
"(",
"threads_inputs",
")",
")",
")",
"threads_results",
"=",
"threads_pool",
".",
"map",
"(",
"_outlierDetection_threaded",
",",
"threads_inputs",
")",
"threads_pool",
".",
"close",
"(",
")",
"threads_pool",
".",
"join",
"(",
")",
"for",
"threads_result",
"in",
"threads_results",
":",
"if",
"threads_result",
"is",
"not",
"None",
":",
"outliers",
".",
"append",
"(",
"threads_result",
")",
"else",
":",
"print",
"(",
"\"error here.\"",
")",
"outliers",
"=",
"None",
"if",
"len",
"(",
"outliers",
")",
"==",
"0",
"else",
"outliers",
"return",
"outliers"
] | 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), filter_shape))
for i in range(n_filters):
filter_weight = np.zeros((n_filters,) + filter_shape)
index = (i,) + center
filter_weight[index] = 1
weight[i, ...] = filter_weight
bias = np.zeros(n_filters)
new_conv_layer = get_conv_class(n_dim)(
conv_layer.filters, n_filters, kernel_size=kernel_size
)
bn = get_batch_norm_class(n_dim)(n_filters)
if weighted:
new_conv_layer.set_weights(
(add_noise(weight, np.array([0, 1])), add_noise(bias, np.array([0, 1])))
)
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, dtype=np.float32), np.array([0, 1])),
add_noise(np.ones(n_filters, dtype=np.float32), np.array([0, 1])),
]
bn.set_weights(new_weights)
return [StubReLU(), new_conv_layer, bn] | 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), filter_shape))
for i in range(n_filters):
filter_weight = np.zeros((n_filters,) + filter_shape)
index = (i,) + center
filter_weight[index] = 1
weight[i, ...] = filter_weight
bias = np.zeros(n_filters)
new_conv_layer = get_conv_class(n_dim)(
conv_layer.filters, n_filters, kernel_size=kernel_size
)
bn = get_batch_norm_class(n_dim)(n_filters)
if weighted:
new_conv_layer.set_weights(
(add_noise(weight, np.array([0, 1])), add_noise(bias, np.array([0, 1])))
)
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, dtype=np.float32), np.array([0, 1])),
add_noise(np.ones(n_filters, dtype=np.float32), np.array([0, 1])),
]
bn.set_weights(new_weights)
return [StubReLU(), new_conv_layer, bn] | [
"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",
".",
"filters",
"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",
")",
":",
"filter_weight",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_filters",
",",
")",
"+",
"filter_shape",
")",
"index",
"=",
"(",
"i",
",",
")",
"+",
"center",
"filter_weight",
"[",
"index",
"]",
"=",
"1",
"weight",
"[",
"i",
",",
"...",
"]",
"=",
"filter_weight",
"bias",
"=",
"np",
".",
"zeros",
"(",
"n_filters",
")",
"new_conv_layer",
"=",
"get_conv_class",
"(",
"n_dim",
")",
"(",
"conv_layer",
".",
"filters",
",",
"n_filters",
",",
"kernel_size",
"=",
"kernel_size",
")",
"bn",
"=",
"get_batch_norm_class",
"(",
"n_dim",
")",
"(",
"n_filters",
")",
"if",
"weighted",
":",
"new_conv_layer",
".",
"set_weights",
"(",
"(",
"add_noise",
"(",
"weight",
",",
"np",
".",
"array",
"(",
"[",
"0",
",",
"1",
"]",
")",
")",
",",
"add_noise",
"(",
"bias",
",",
"np",
".",
"array",
"(",
"[",
"0",
",",
"1",
"]",
")",
")",
")",
")",
"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",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
",",
"np",
".",
"array",
"(",
"[",
"0",
",",
"1",
"]",
")",
")",
",",
"add_noise",
"(",
"np",
".",
"ones",
"(",
"n_filters",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
",",
"np",
".",
"array",
"(",
"[",
"0",
",",
"1",
"]",
")",
")",
",",
"]",
"bn",
".",
"set_weights",
"(",
"new_weights",
")",
"return",
"[",
"StubReLU",
"(",
")",
",",
"new_conv_layer",
",",
"bn",
"]"
] | 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])), add_noise(bias, np.array([0, 1])))
)
return [StubReLU(), new_dense_layer] | 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])), add_noise(bias, np.array([0, 1])))
)
return [StubReLU(), new_dense_layer] | [
"def",
"dense_to_deeper_block",
"(",
"dense_layer",
",",
"weighted",
"=",
"True",
")",
":",
"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",
"]",
")",
")",
",",
"add_noise",
"(",
"bias",
",",
"np",
".",
"array",
"(",
"[",
"0",
",",
"1",
"]",
")",
")",
")",
")",
"return",
"[",
"StubReLU",
"(",
")",
",",
"new_dense_layer",
"]"
] | 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 = teacher_w.copy()
student_b = teacher_b.copy()
# target layer update (i)
for i in range(n_add):
teacher_index = rand[i]
new_weight = teacher_w[teacher_index, :]
new_weight = new_weight[np.newaxis, :]
student_w = np.concatenate((student_w, add_noise(new_weight, student_w)), axis=0)
student_b = np.append(student_b, add_noise(teacher_b[teacher_index], student_b))
new_pre_layer = StubDense(layer.input_units, n_units2 + n_add)
new_pre_layer.set_weights((student_w, student_b))
return new_pre_layer | 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 = teacher_w.copy()
student_b = teacher_b.copy()
# target layer update (i)
for i in range(n_add):
teacher_index = rand[i]
new_weight = teacher_w[teacher_index, :]
new_weight = new_weight[np.newaxis, :]
student_w = np.concatenate((student_w, add_noise(new_weight, student_w)), axis=0)
student_b = np.append(student_b, add_noise(teacher_b[teacher_index], student_b))
new_pre_layer = StubDense(layer.input_units, n_units2 + n_add)
new_pre_layer.set_weights((student_w, student_b))
return new_pre_layer | [
"def",
"wider_pre_dense",
"(",
"layer",
",",
"n_add",
",",
"weighted",
"=",
"True",
")",
":",
"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",
"=",
"teacher_w",
".",
"copy",
"(",
")",
"student_b",
"=",
"teacher_b",
".",
"copy",
"(",
")",
"# target layer update (i)",
"for",
"i",
"in",
"range",
"(",
"n_add",
")",
":",
"teacher_index",
"=",
"rand",
"[",
"i",
"]",
"new_weight",
"=",
"teacher_w",
"[",
"teacher_index",
",",
":",
"]",
"new_weight",
"=",
"new_weight",
"[",
"np",
".",
"newaxis",
",",
":",
"]",
"student_w",
"=",
"np",
".",
"concatenate",
"(",
"(",
"student_w",
",",
"add_noise",
"(",
"new_weight",
",",
"student_w",
")",
")",
",",
"axis",
"=",
"0",
")",
"student_b",
"=",
"np",
".",
"append",
"(",
"student_b",
",",
"add_noise",
"(",
"teacher_b",
"[",
"teacher_index",
"]",
",",
"student_b",
")",
")",
"new_pre_layer",
"=",
"StubDense",
"(",
"layer",
".",
"input_units",
",",
"n_units2",
"+",
"n_add",
")",
"new_pre_layer",
".",
"set_weights",
"(",
"(",
"student_w",
",",
"student_b",
")",
")",
"return",
"new_pre_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,
)
n_pre_filters = layer.filters
rand = np.random.randint(n_pre_filters, size=n_add_filters)
teacher_w, teacher_b = layer.get_weights()
student_w = teacher_w.copy()
student_b = teacher_b.copy()
# target layer update (i)
for i in range(len(rand)):
teacher_index = rand[i]
new_weight = teacher_w[teacher_index, ...]
new_weight = new_weight[np.newaxis, ...]
student_w = np.concatenate((student_w, new_weight), axis=0)
student_b = np.append(student_b, teacher_b[teacher_index])
new_pre_layer = get_conv_class(n_dim)(
layer.input_channel, n_pre_filters + n_add_filters, layer.kernel_size
)
new_pre_layer.set_weights(
(add_noise(student_w, teacher_w), add_noise(student_b, teacher_b))
)
return new_pre_layer | 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,
)
n_pre_filters = layer.filters
rand = np.random.randint(n_pre_filters, size=n_add_filters)
teacher_w, teacher_b = layer.get_weights()
student_w = teacher_w.copy()
student_b = teacher_b.copy()
# target layer update (i)
for i in range(len(rand)):
teacher_index = rand[i]
new_weight = teacher_w[teacher_index, ...]
new_weight = new_weight[np.newaxis, ...]
student_w = np.concatenate((student_w, new_weight), axis=0)
student_b = np.append(student_b, teacher_b[teacher_index])
new_pre_layer = get_conv_class(n_dim)(
layer.input_channel, n_pre_filters + n_add_filters, layer.kernel_size
)
new_pre_layer.set_weights(
(add_noise(student_w, teacher_w), add_noise(student_b, teacher_b))
)
return new_pre_layer | [
"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_channel",
",",
"layer",
".",
"filters",
"+",
"n_add_filters",
",",
"kernel_size",
"=",
"layer",
".",
"kernel_size",
",",
")",
"n_pre_filters",
"=",
"layer",
".",
"filters",
"rand",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"n_pre_filters",
",",
"size",
"=",
"n_add_filters",
")",
"teacher_w",
",",
"teacher_b",
"=",
"layer",
".",
"get_weights",
"(",
")",
"student_w",
"=",
"teacher_w",
".",
"copy",
"(",
")",
"student_b",
"=",
"teacher_b",
".",
"copy",
"(",
")",
"# target layer update (i)",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"rand",
")",
")",
":",
"teacher_index",
"=",
"rand",
"[",
"i",
"]",
"new_weight",
"=",
"teacher_w",
"[",
"teacher_index",
",",
"...",
"]",
"new_weight",
"=",
"new_weight",
"[",
"np",
".",
"newaxis",
",",
"...",
"]",
"student_w",
"=",
"np",
".",
"concatenate",
"(",
"(",
"student_w",
",",
"new_weight",
")",
",",
"axis",
"=",
"0",
")",
"student_b",
"=",
"np",
".",
"append",
"(",
"student_b",
",",
"teacher_b",
"[",
"teacher_index",
"]",
")",
"new_pre_layer",
"=",
"get_conv_class",
"(",
"n_dim",
")",
"(",
"layer",
".",
"input_channel",
",",
"n_pre_filters",
"+",
"n_add_filters",
",",
"layer",
".",
"kernel_size",
")",
"new_pre_layer",
".",
"set_weights",
"(",
"(",
"add_noise",
"(",
"student_w",
",",
"teacher_w",
")",
",",
"add_noise",
"(",
"student_b",
",",
"teacher_b",
")",
")",
")",
"return",
"new_pre_layer"
] | 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,
kernel_size=layer.kernel_size,
stride=layer.stride)
n_filters = layer.filters
teacher_w, teacher_b = layer.get_weights()
new_weight_shape = list(teacher_w.shape)
new_weight_shape[1] = n_add
new_weight = np.zeros(tuple(new_weight_shape))
student_w = np.concatenate((teacher_w[:, :start_dim, ...].copy(),
add_noise(new_weight, teacher_w),
teacher_w[:, start_dim:total_dim, ...].copy()), axis=1)
new_layer = get_conv_class(n_dim)(layer.input_channel + n_add,
n_filters,
kernel_size=layer.kernel_size,
stride=layer.stride)
new_layer.set_weights((student_w, teacher_b))
return new_layer | 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,
kernel_size=layer.kernel_size,
stride=layer.stride)
n_filters = layer.filters
teacher_w, teacher_b = layer.get_weights()
new_weight_shape = list(teacher_w.shape)
new_weight_shape[1] = n_add
new_weight = np.zeros(tuple(new_weight_shape))
student_w = np.concatenate((teacher_w[:, :start_dim, ...].copy(),
add_noise(new_weight, teacher_w),
teacher_w[:, start_dim:total_dim, ...].copy()), axis=1)
new_layer = get_conv_class(n_dim)(layer.input_channel + n_add,
n_filters,
kernel_size=layer.kernel_size,
stride=layer.stride)
new_layer.set_weights((student_w, teacher_b))
return new_layer | [
"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",
")",
"(",
"layer",
".",
"input_channel",
"+",
"n_add",
",",
"layer",
".",
"filters",
",",
"kernel_size",
"=",
"layer",
".",
"kernel_size",
",",
"stride",
"=",
"layer",
".",
"stride",
")",
"n_filters",
"=",
"layer",
".",
"filters",
"teacher_w",
",",
"teacher_b",
"=",
"layer",
".",
"get_weights",
"(",
")",
"new_weight_shape",
"=",
"list",
"(",
"teacher_w",
".",
"shape",
")",
"new_weight_shape",
"[",
"1",
"]",
"=",
"n_add",
"new_weight",
"=",
"np",
".",
"zeros",
"(",
"tuple",
"(",
"new_weight_shape",
")",
")",
"student_w",
"=",
"np",
".",
"concatenate",
"(",
"(",
"teacher_w",
"[",
":",
",",
":",
"start_dim",
",",
"...",
"]",
".",
"copy",
"(",
")",
",",
"add_noise",
"(",
"new_weight",
",",
"teacher_w",
")",
",",
"teacher_w",
"[",
":",
",",
"start_dim",
":",
"total_dim",
",",
"...",
"]",
".",
"copy",
"(",
")",
")",
",",
"axis",
"=",
"1",
")",
"new_layer",
"=",
"get_conv_class",
"(",
"n_dim",
")",
"(",
"layer",
".",
"input_channel",
"+",
"n_add",
",",
"n_filters",
",",
"kernel_size",
"=",
"layer",
".",
"kernel_size",
",",
"stride",
"=",
"layer",
".",
"stride",
")",
"new_layer",
".",
"set_weights",
"(",
"(",
"student_w",
",",
"teacher_b",
")",
")",
"return",
"new_layer"
] | 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=np.float32), np.array([0, 1])),
add_noise(np.zeros(n_add, dtype=np.float32), np.array([0, 1])),
add_noise(np.zeros(n_add, dtype=np.float32), np.array([0, 1])),
add_noise(np.ones(n_add, dtype=np.float32), np.array([0, 1])),
]
student_w = tuple()
for weight, new_weight in zip(weights, new_weights):
temp_w = weight.copy()
temp_w = np.concatenate(
(temp_w[:start_dim], new_weight, temp_w[start_dim:total_dim])
)
student_w += (temp_w,)
new_layer = get_batch_norm_class(n_dim)(layer.num_features + n_add)
new_layer.set_weights(student_w)
return new_layer | 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=np.float32), np.array([0, 1])),
add_noise(np.zeros(n_add, dtype=np.float32), np.array([0, 1])),
add_noise(np.zeros(n_add, dtype=np.float32), np.array([0, 1])),
add_noise(np.ones(n_add, dtype=np.float32), np.array([0, 1])),
]
student_w = tuple()
for weight, new_weight in zip(weights, new_weights):
temp_w = weight.copy()
temp_w = np.concatenate(
(temp_w[:start_dim], new_weight, temp_w[start_dim:total_dim])
)
student_w += (temp_w,)
new_layer = get_batch_norm_class(n_dim)(layer.num_features + n_add)
new_layer.set_weights(student_w)
return new_layer | [
"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",
")",
"(",
"layer",
".",
"num_features",
"+",
"n_add",
")",
"weights",
"=",
"layer",
".",
"get_weights",
"(",
")",
"new_weights",
"=",
"[",
"add_noise",
"(",
"np",
".",
"ones",
"(",
"n_add",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
",",
"np",
".",
"array",
"(",
"[",
"0",
",",
"1",
"]",
")",
")",
",",
"add_noise",
"(",
"np",
".",
"zeros",
"(",
"n_add",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
",",
"np",
".",
"array",
"(",
"[",
"0",
",",
"1",
"]",
")",
")",
",",
"add_noise",
"(",
"np",
".",
"zeros",
"(",
"n_add",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
",",
"np",
".",
"array",
"(",
"[",
"0",
",",
"1",
"]",
")",
")",
",",
"add_noise",
"(",
"np",
".",
"ones",
"(",
"n_add",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
",",
"np",
".",
"array",
"(",
"[",
"0",
",",
"1",
"]",
")",
")",
",",
"]",
"student_w",
"=",
"tuple",
"(",
")",
"for",
"weight",
",",
"new_weight",
"in",
"zip",
"(",
"weights",
",",
"new_weights",
")",
":",
"temp_w",
"=",
"weight",
".",
"copy",
"(",
")",
"temp_w",
"=",
"np",
".",
"concatenate",
"(",
"(",
"temp_w",
"[",
":",
"start_dim",
"]",
",",
"new_weight",
",",
"temp_w",
"[",
"start_dim",
":",
"total_dim",
"]",
")",
")",
"student_w",
"+=",
"(",
"temp_w",
",",
")",
"new_layer",
"=",
"get_batch_norm_class",
"(",
"n_dim",
")",
"(",
"layer",
".",
"num_features",
"+",
"n_add",
")",
"new_layer",
".",
"set_weights",
"(",
"student_w",
")",
"return",
"new_layer"
] | 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.shape[1] / total_dim)
new_weight = np.zeros((teacher_w.shape[0], n_add * n_units_each_channel))
student_w = np.concatenate(
(
student_w[:, : start_dim * n_units_each_channel],
add_noise(new_weight, student_w),
student_w[
:, start_dim * n_units_each_channel : total_dim * n_units_each_channel
],
),
axis=1,
)
new_layer = StubDense(layer.input_units + n_add, layer.units)
new_layer.set_weights((student_w, teacher_b))
return new_layer | 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.shape[1] / total_dim)
new_weight = np.zeros((teacher_w.shape[0], n_add * n_units_each_channel))
student_w = np.concatenate(
(
student_w[:, : start_dim * n_units_each_channel],
add_noise(new_weight, student_w),
student_w[
:, start_dim * n_units_each_channel : total_dim * n_units_each_channel
],
),
axis=1,
)
new_layer = StubDense(layer.input_units + n_add, layer.units)
new_layer.set_weights((student_w, teacher_b))
return new_layer | [
"def",
"wider_next_dense",
"(",
"layer",
",",
"start_dim",
",",
"total_dim",
",",
"n_add",
",",
"weighted",
"=",
"True",
")",
":",
"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",
".",
"shape",
"[",
"1",
"]",
"/",
"total_dim",
")",
"new_weight",
"=",
"np",
".",
"zeros",
"(",
"(",
"teacher_w",
".",
"shape",
"[",
"0",
"]",
",",
"n_add",
"*",
"n_units_each_channel",
")",
")",
"student_w",
"=",
"np",
".",
"concatenate",
"(",
"(",
"student_w",
"[",
":",
",",
":",
"start_dim",
"*",
"n_units_each_channel",
"]",
",",
"add_noise",
"(",
"new_weight",
",",
"student_w",
")",
",",
"student_w",
"[",
":",
",",
"start_dim",
"*",
"n_units_each_channel",
":",
"total_dim",
"*",
"n_units_each_channel",
"]",
",",
")",
",",
"axis",
"=",
"1",
",",
")",
"new_layer",
"=",
"StubDense",
"(",
"layer",
".",
"input_units",
"+",
"n_add",
",",
"layer",
".",
"units",
")",
"new_layer",
".",
"set_weights",
"(",
"(",
"student_w",
",",
"teacher_b",
")",
")",
"return",
"new_layer"
] | 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",
"(",
"-",
"noise_range",
"/",
"2.0",
",",
"noise_range",
"/",
"2.0",
",",
"weights",
".",
"shape",
")",
"return",
"np",
".",
"add",
"(",
"noise",
",",
"weights",
")"
] | 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",
"(",
"weight",
",",
"np",
".",
"array",
"(",
"[",
"0",
",",
"1",
"]",
")",
")",
",",
"add_noise",
"(",
"bias",
",",
"np",
".",
"array",
"(",
"[",
"0",
",",
"1",
"]",
")",
")",
")",
")"
] | 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):
filter_weight = np.zeros((n_filters,) + filter_shape)
index = (i,) + center
filter_weight[index] = 1
weight[i, ...] = filter_weight
bias = np.zeros(n_filters)
layer.set_weights(
(add_noise(weight, np.array([0, 1])), add_noise(bias, np.array([0, 1])))
) | 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):
filter_weight = np.zeros((n_filters,) + filter_shape)
index = (i,) + center
filter_weight[index] = 1
weight[i, ...] = filter_weight
bias = np.zeros(n_filters)
layer.set_weights(
(add_noise(weight, np.array([0, 1])), add_noise(bias, np.array([0, 1])))
) | [
"def",
"init_conv_weight",
"(",
"layer",
")",
":",
"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",
")",
":",
"filter_weight",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_filters",
",",
")",
"+",
"filter_shape",
")",
"index",
"=",
"(",
"i",
",",
")",
"+",
"center",
"filter_weight",
"[",
"index",
"]",
"=",
"1",
"weight",
"[",
"i",
",",
"...",
"]",
"=",
"filter_weight",
"bias",
"=",
"np",
".",
"zeros",
"(",
"n_filters",
")",
"layer",
".",
"set_weights",
"(",
"(",
"add_noise",
"(",
"weight",
",",
"np",
".",
"array",
"(",
"[",
"0",
",",
"1",
"]",
")",
")",
",",
"add_noise",
"(",
"bias",
",",
"np",
".",
"array",
"(",
"[",
"0",
",",
"1",
"]",
")",
")",
")",
")"
] | 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, dtype=np.float32), np.array([0, 1])),
add_noise(np.ones(n_filters, dtype=np.float32), np.array([0, 1])),
]
layer.set_weights(new_weights) | 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, dtype=np.float32), np.array([0, 1])),
add_noise(np.ones(n_filters, dtype=np.float32), np.array([0, 1])),
]
layer.set_weights(new_weights) | [
"def",
"init_bn_weight",
"(",
"layer",
")",
":",
"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",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
",",
"np",
".",
"array",
"(",
"[",
"0",
",",
"1",
"]",
")",
")",
",",
"add_noise",
"(",
"np",
".",
"ones",
"(",
"n_filters",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
",",
"np",
".",
"array",
"(",
"[",
"0",
",",
"1",
"]",
")",
")",
",",
"]",
"layer",
".",
"set_weights",
"(",
"new_weights",
")"
] | 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>.*)'
match = re.search(pattern,trial['logPath'])
if match:
path_list.append(match.group('path'))
host_list.append(match.group('host'))
if not path_list:
print_error('Trial id %s error!' % args.trial_id)
exit(1)
return path_list, host_list | 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>.*)'
match = re.search(pattern,trial['logPath'])
if match:
path_list.append(match.group('path'))
host_list.append(match.group('host'))
if not path_list:
print_error('Trial id %s error!' % args.trial_id)
exit(1)
return path_list, host_list | [
"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",
"trial",
".",
"get",
"(",
"'id'",
")",
"!=",
"args",
".",
"trial_id",
":",
"continue",
"pattern",
"=",
"r'(?P<head>.+)://(?P<host>.+):(?P<path>.*)'",
"match",
"=",
"re",
".",
"search",
"(",
"pattern",
",",
"trial",
"[",
"'logPath'",
"]",
")",
"if",
"match",
":",
"path_list",
".",
"append",
"(",
"match",
".",
"group",
"(",
"'path'",
")",
")",
"host_list",
".",
"append",
"(",
"match",
".",
"group",
"(",
"'host'",
")",
")",
"if",
"not",
"path_list",
":",
"print_error",
"(",
"'Trial id %s error!'",
"%",
"args",
".",
"trial_id",
")",
"exit",
"(",
"1",
")",
"return",
"path_list",
",",
"host_list"
] | 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 machine_list:
machine_dict[machine['ip']] = {'port': machine['port'], 'passwd': machine['passwd'], 'username': machine['username']}
for index, host in enumerate(host_list):
local_path = os.path.join(temp_nni_path, trial_content[index].get('id'))
local_path_list.append(local_path)
print_normal('Copying log data from %s to %s' % (host + ':' + path_list[index], local_path))
sftp = create_ssh_sftp_client(host, machine_dict[host]['port'], machine_dict[host]['username'], machine_dict[host]['passwd'])
copy_remote_directory_to_local(sftp, path_list[index], local_path)
print_normal('Copy done!')
return local_path_list | 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 machine_list:
machine_dict[machine['ip']] = {'port': machine['port'], 'passwd': machine['passwd'], 'username': machine['username']}
for index, host in enumerate(host_list):
local_path = os.path.join(temp_nni_path, trial_content[index].get('id'))
local_path_list.append(local_path)
print_normal('Copying log data from %s to %s' % (host + ':' + path_list[index], local_path))
sftp = create_ssh_sftp_client(host, machine_dict[host]['port'], machine_dict[host]['username'], machine_dict[host]['passwd'])
copy_remote_directory_to_local(sftp, path_list[index], local_path)
print_normal('Copy done!')
return local_path_list | [
"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",
"(",
"'machineList'",
")",
"machine_dict",
"=",
"{",
"}",
"local_path_list",
"=",
"[",
"]",
"for",
"machine",
"in",
"machine_list",
":",
"machine_dict",
"[",
"machine",
"[",
"'ip'",
"]",
"]",
"=",
"{",
"'port'",
":",
"machine",
"[",
"'port'",
"]",
",",
"'passwd'",
":",
"machine",
"[",
"'passwd'",
"]",
",",
"'username'",
":",
"machine",
"[",
"'username'",
"]",
"}",
"for",
"index",
",",
"host",
"in",
"enumerate",
"(",
"host_list",
")",
":",
"local_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"temp_nni_path",
",",
"trial_content",
"[",
"index",
"]",
".",
"get",
"(",
"'id'",
")",
")",
"local_path_list",
".",
"append",
"(",
"local_path",
")",
"print_normal",
"(",
"'Copying log data from %s to %s'",
"%",
"(",
"host",
"+",
"':'",
"+",
"path_list",
"[",
"index",
"]",
",",
"local_path",
")",
")",
"sftp",
"=",
"create_ssh_sftp_client",
"(",
"host",
",",
"machine_dict",
"[",
"host",
"]",
"[",
"'port'",
"]",
",",
"machine_dict",
"[",
"host",
"]",
"[",
"'username'",
"]",
",",
"machine_dict",
"[",
"host",
"]",
"[",
"'passwd'",
"]",
")",
"copy_remote_directory_to_local",
"(",
"sftp",
",",
"path_list",
"[",
"index",
"]",
",",
"local_path",
")",
"print_normal",
"(",
"'Copy done!'",
")",
"return",
"local_path_list"
] | 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_normal('Log path: %s' % ' '.join(path_list))
return path_list
elif platform == 'remote':
path_list = copy_data_from_remote(args, nni_config, trial_content, path_list, host_list, temp_nni_path)
print_normal('Log path: %s' % ' '.join(path_list))
return path_list
else:
print_error('Not supported platform!')
exit(1) | 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_normal('Log path: %s' % ' '.join(path_list))
return path_list
elif platform == 'remote':
path_list = copy_data_from_remote(args, nni_config, trial_content, path_list, host_list, temp_nni_path)
print_normal('Log path: %s' % ' '.join(path_list))
return path_list
else:
print_error('Not supported platform!')
exit(1) | [
"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",
"(",
"'experimentConfig'",
")",
".",
"get",
"(",
"'trainingServicePlatform'",
")",
"if",
"platform",
"==",
"'local'",
":",
"print_normal",
"(",
"'Log path: %s'",
"%",
"' '",
".",
"join",
"(",
"path_list",
")",
")",
"return",
"path_list",
"elif",
"platform",
"==",
"'remote'",
":",
"path_list",
"=",
"copy_data_from_remote",
"(",
"args",
",",
"nni_config",
",",
"trial_content",
",",
"path_list",
",",
"host_list",
",",
"temp_nni_path",
")",
"print_normal",
"(",
"'Log path: %s'",
"%",
"' '",
".",
"join",
"(",
"path_list",
")",
")",
"return",
"path_list",
"else",
":",
"print_error",
"(",
"'Not supported platform!'",
")",
"exit",
"(",
"1",
")"
] | 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.