repo stringclasses 85
values | path stringlengths 8 121 | func_name stringlengths 1 82 | original_string stringlengths 112 65.5k | language stringclasses 1
value | code stringlengths 112 65.5k | code_tokens listlengths 20 4.09k | docstring stringlengths 3 46.3k | docstring_tokens listlengths 1 564 | sha stringclasses 85
values | url stringlengths 93 218 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
Microsoft/nni | examples/trials/kaggle-tgs-salt/lovasz_losses.py | iou | def iou(preds, labels, C, EMPTY=1., ignore=None, per_image=False):
"""
Array of IoU for each (non ignored) class
"""
if not per_image:
preds, labels = (preds,), (labels,)
ious = []
for pred, label in zip(preds, labels):
iou = []
for i in range(C):
if i != ... | python | def iou(preds, labels, C, EMPTY=1., ignore=None, per_image=False):
"""
Array of IoU for each (non ignored) class
"""
if not per_image:
preds, labels = (preds,), (labels,)
ious = []
for pred, label in zip(preds, labels):
iou = []
for i in range(C):
if i != ... | [
"def",
"iou",
"(",
"preds",
",",
"labels",
",",
"C",
",",
"EMPTY",
"=",
"1.",
",",
"ignore",
"=",
"None",
",",
"per_image",
"=",
"False",
")",
":",
"if",
"not",
"per_image",
":",
"preds",
",",
"labels",
"=",
"(",
"preds",
",",
")",
",",
"(",
"l... | Array of IoU for each (non ignored) class | [
"Array",
"of",
"IoU",
"for",
"each",
"(",
"non",
"ignored",
")",
"class"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/kaggle-tgs-salt/lovasz_losses.py#L71-L90 | train |
Microsoft/nni | examples/trials/kaggle-tgs-salt/lovasz_losses.py | lovasz_hinge | def lovasz_hinge(logits, labels, per_image=True, ignore=None):
"""
Binary Lovasz hinge loss
logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty)
labels: [B, H, W] Tensor, binary ground truth masks (0 or 1)
per_image: compute the loss per image instead of per batch
... | python | def lovasz_hinge(logits, labels, per_image=True, ignore=None):
"""
Binary Lovasz hinge loss
logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty)
labels: [B, H, W] Tensor, binary ground truth masks (0 or 1)
per_image: compute the loss per image instead of per batch
... | [
"def",
"lovasz_hinge",
"(",
"logits",
",",
"labels",
",",
"per_image",
"=",
"True",
",",
"ignore",
"=",
"None",
")",
":",
"if",
"per_image",
":",
"loss",
"=",
"mean",
"(",
"lovasz_hinge_flat",
"(",
"*",
"flatten_binary_scores",
"(",
"log",
".",
"unsqueeze"... | Binary Lovasz hinge loss
logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty)
labels: [B, H, W] Tensor, binary ground truth masks (0 or 1)
per_image: compute the loss per image instead of per batch
ignore: void class id | [
"Binary",
"Lovasz",
"hinge",
"loss",
"logits",
":",
"[",
"B",
"H",
"W",
"]",
"Variable",
"logits",
"at",
"each",
"pixel",
"(",
"between",
"-",
"\\",
"infty",
"and",
"+",
"\\",
"infty",
")",
"labels",
":",
"[",
"B",
"H",
"W",
"]",
"Tensor",
"binary"... | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/kaggle-tgs-salt/lovasz_losses.py#L96-L109 | train |
Microsoft/nni | examples/trials/kaggle-tgs-salt/lovasz_losses.py | lovasz_hinge_flat | def lovasz_hinge_flat(logits, labels):
"""
Binary Lovasz hinge loss
logits: [P] Variable, logits at each prediction (between -\infty and +\infty)
labels: [P] Tensor, binary ground truth labels (0 or 1)
ignore: label to ignore
"""
if len(labels) == 0:
# only void pixels, the gra... | python | def lovasz_hinge_flat(logits, labels):
"""
Binary Lovasz hinge loss
logits: [P] Variable, logits at each prediction (between -\infty and +\infty)
labels: [P] Tensor, binary ground truth labels (0 or 1)
ignore: label to ignore
"""
if len(labels) == 0:
# only void pixels, the gra... | [
"def",
"lovasz_hinge_flat",
"(",
"logits",
",",
"labels",
")",
":",
"if",
"len",
"(",
"labels",
")",
"==",
"0",
":",
"# only void pixels, the gradients should be 0",
"return",
"logits",
".",
"sum",
"(",
")",
"*",
"0.",
"signs",
"=",
"2.",
"*",
"labels",
".... | Binary Lovasz hinge loss
logits: [P] Variable, logits at each prediction (between -\infty and +\infty)
labels: [P] Tensor, binary ground truth labels (0 or 1)
ignore: label to ignore | [
"Binary",
"Lovasz",
"hinge",
"loss",
"logits",
":",
"[",
"P",
"]",
"Variable",
"logits",
"at",
"each",
"prediction",
"(",
"between",
"-",
"\\",
"infty",
"and",
"+",
"\\",
"infty",
")",
"labels",
":",
"[",
"P",
"]",
"Tensor",
"binary",
"ground",
"truth"... | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/kaggle-tgs-salt/lovasz_losses.py#L112-L131 | train |
Microsoft/nni | examples/trials/kaggle-tgs-salt/lovasz_losses.py | flatten_binary_scores | def flatten_binary_scores(scores, labels, ignore=None):
"""
Flattens predictions in the batch (binary case)
Remove labels equal to 'ignore'
"""
scores = scores.view(-1)
labels = labels.view(-1)
if ignore is None:
return scores, labels
valid = (labels != ignore)
vscores = scor... | python | def flatten_binary_scores(scores, labels, ignore=None):
"""
Flattens predictions in the batch (binary case)
Remove labels equal to 'ignore'
"""
scores = scores.view(-1)
labels = labels.view(-1)
if ignore is None:
return scores, labels
valid = (labels != ignore)
vscores = scor... | [
"def",
"flatten_binary_scores",
"(",
"scores",
",",
"labels",
",",
"ignore",
"=",
"None",
")",
":",
"scores",
"=",
"scores",
".",
"view",
"(",
"-",
"1",
")",
"labels",
"=",
"labels",
".",
"view",
"(",
"-",
"1",
")",
"if",
"ignore",
"is",
"None",
":... | Flattens predictions in the batch (binary case)
Remove labels equal to 'ignore' | [
"Flattens",
"predictions",
"in",
"the",
"batch",
"(",
"binary",
"case",
")",
"Remove",
"labels",
"equal",
"to",
"ignore"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/kaggle-tgs-salt/lovasz_losses.py#L134-L146 | train |
Microsoft/nni | examples/trials/kaggle-tgs-salt/lovasz_losses.py | binary_xloss | def binary_xloss(logits, labels, ignore=None):
"""
Binary Cross entropy loss
logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty)
labels: [B, H, W] Tensor, binary ground truth masks (0 or 1)
ignore: void class id
"""
logits, labels = flatten_binary_scores(logi... | python | def binary_xloss(logits, labels, ignore=None):
"""
Binary Cross entropy loss
logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty)
labels: [B, H, W] Tensor, binary ground truth masks (0 or 1)
ignore: void class id
"""
logits, labels = flatten_binary_scores(logi... | [
"def",
"binary_xloss",
"(",
"logits",
",",
"labels",
",",
"ignore",
"=",
"None",
")",
":",
"logits",
",",
"labels",
"=",
"flatten_binary_scores",
"(",
"logits",
",",
"labels",
",",
"ignore",
")",
"loss",
"=",
"StableBCELoss",
"(",
")",
"(",
"logits",
","... | Binary Cross entropy loss
logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty)
labels: [B, H, W] Tensor, binary ground truth masks (0 or 1)
ignore: void class id | [
"Binary",
"Cross",
"entropy",
"loss",
"logits",
":",
"[",
"B",
"H",
"W",
"]",
"Variable",
"logits",
"at",
"each",
"pixel",
"(",
"between",
"-",
"\\",
"infty",
"and",
"+",
"\\",
"infty",
")",
"labels",
":",
"[",
"B",
"H",
"W",
"]",
"Tensor",
"binary... | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/kaggle-tgs-salt/lovasz_losses.py#L158-L167 | train |
Microsoft/nni | examples/trials/kaggle-tgs-salt/lovasz_losses.py | lovasz_softmax | def lovasz_softmax(probas, labels, only_present=False, per_image=False, ignore=None):
"""
Multi-class Lovasz-Softmax loss
probas: [B, C, H, W] Variable, class probabilities at each prediction (between 0 and 1)
labels: [B, H, W] Tensor, ground truth labels (between 0 and C - 1)
only_present: av... | python | def lovasz_softmax(probas, labels, only_present=False, per_image=False, ignore=None):
"""
Multi-class Lovasz-Softmax loss
probas: [B, C, H, W] Variable, class probabilities at each prediction (between 0 and 1)
labels: [B, H, W] Tensor, ground truth labels (between 0 and C - 1)
only_present: av... | [
"def",
"lovasz_softmax",
"(",
"probas",
",",
"labels",
",",
"only_present",
"=",
"False",
",",
"per_image",
"=",
"False",
",",
"ignore",
"=",
"None",
")",
":",
"if",
"per_image",
":",
"loss",
"=",
"mean",
"(",
"lovasz_softmax_flat",
"(",
"*",
"flatten_prob... | Multi-class Lovasz-Softmax loss
probas: [B, C, H, W] Variable, class probabilities at each prediction (between 0 and 1)
labels: [B, H, W] Tensor, ground truth labels (between 0 and C - 1)
only_present: average only on classes present in ground truth
per_image: compute the loss per image instead ... | [
"Multi",
"-",
"class",
"Lovasz",
"-",
"Softmax",
"loss",
"probas",
":",
"[",
"B",
"C",
"H",
"W",
"]",
"Variable",
"class",
"probabilities",
"at",
"each",
"prediction",
"(",
"between",
"0",
"and",
"1",
")",
"labels",
":",
"[",
"B",
"H",
"W",
"]",
"T... | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/kaggle-tgs-salt/lovasz_losses.py#L173-L187 | train |
Microsoft/nni | examples/trials/kaggle-tgs-salt/lovasz_losses.py | lovasz_softmax_flat | def lovasz_softmax_flat(probas, labels, only_present=False):
"""
Multi-class Lovasz-Softmax loss
probas: [P, C] Variable, class probabilities at each prediction (between 0 and 1)
labels: [P] Tensor, ground truth labels (between 0 and C - 1)
only_present: average only on classes present in grou... | python | def lovasz_softmax_flat(probas, labels, only_present=False):
"""
Multi-class Lovasz-Softmax loss
probas: [P, C] Variable, class probabilities at each prediction (between 0 and 1)
labels: [P] Tensor, ground truth labels (between 0 and C - 1)
only_present: average only on classes present in grou... | [
"def",
"lovasz_softmax_flat",
"(",
"probas",
",",
"labels",
",",
"only_present",
"=",
"False",
")",
":",
"C",
"=",
"probas",
".",
"size",
"(",
"1",
")",
"losses",
"=",
"[",
"]",
"for",
"c",
"in",
"range",
"(",
"C",
")",
":",
"fg",
"=",
"(",
"labe... | Multi-class Lovasz-Softmax loss
probas: [P, C] Variable, class probabilities at each prediction (between 0 and 1)
labels: [P] Tensor, ground truth labels (between 0 and C - 1)
only_present: average only on classes present in ground truth | [
"Multi",
"-",
"class",
"Lovasz",
"-",
"Softmax",
"loss",
"probas",
":",
"[",
"P",
"C",
"]",
"Variable",
"class",
"probabilities",
"at",
"each",
"prediction",
"(",
"between",
"0",
"and",
"1",
")",
"labels",
":",
"[",
"P",
"]",
"Tensor",
"ground",
"truth... | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/kaggle-tgs-salt/lovasz_losses.py#L190-L208 | train |
Microsoft/nni | examples/trials/kaggle-tgs-salt/lovasz_losses.py | flatten_probas | def flatten_probas(probas, labels, ignore=None):
"""
Flattens predictions in the batch
"""
B, C, H, W = probas.size()
probas = probas.permute(0, 2, 3, 1).contiguous().view(-1, C) # B * H * W, C = P, C
labels = labels.view(-1)
if ignore is None:
return probas, labels
valid = (lab... | python | def flatten_probas(probas, labels, ignore=None):
"""
Flattens predictions in the batch
"""
B, C, H, W = probas.size()
probas = probas.permute(0, 2, 3, 1).contiguous().view(-1, C) # B * H * W, C = P, C
labels = labels.view(-1)
if ignore is None:
return probas, labels
valid = (lab... | [
"def",
"flatten_probas",
"(",
"probas",
",",
"labels",
",",
"ignore",
"=",
"None",
")",
":",
"B",
",",
"C",
",",
"H",
",",
"W",
"=",
"probas",
".",
"size",
"(",
")",
"probas",
"=",
"probas",
".",
"permute",
"(",
"0",
",",
"2",
",",
"3",
",",
... | Flattens predictions in the batch | [
"Flattens",
"predictions",
"in",
"the",
"batch"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/kaggle-tgs-salt/lovasz_losses.py#L211-L223 | train |
Microsoft/nni | examples/trials/kaggle-tgs-salt/lovasz_losses.py | xloss | def xloss(logits, labels, ignore=None):
"""
Cross entropy loss
"""
return F.cross_entropy(logits, Variable(labels), ignore_index=255) | python | def xloss(logits, labels, ignore=None):
"""
Cross entropy loss
"""
return F.cross_entropy(logits, Variable(labels), ignore_index=255) | [
"def",
"xloss",
"(",
"logits",
",",
"labels",
",",
"ignore",
"=",
"None",
")",
":",
"return",
"F",
".",
"cross_entropy",
"(",
"logits",
",",
"Variable",
"(",
"labels",
")",
",",
"ignore_index",
"=",
"255",
")"
] | Cross entropy loss | [
"Cross",
"entropy",
"loss"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/kaggle-tgs-salt/lovasz_losses.py#L225-L229 | train |
Microsoft/nni | examples/trials/kaggle-tgs-salt/lovasz_losses.py | mean | def mean(l, ignore_nan=False, empty=0):
"""
nanmean compatible with generators.
"""
l = iter(l)
if ignore_nan:
l = ifilterfalse(np.isnan, l)
try:
n = 1
acc = next(l)
except StopIteration:
if empty == 'raise':
raise ValueError('Empty mean')
... | python | def mean(l, ignore_nan=False, empty=0):
"""
nanmean compatible with generators.
"""
l = iter(l)
if ignore_nan:
l = ifilterfalse(np.isnan, l)
try:
n = 1
acc = next(l)
except StopIteration:
if empty == 'raise':
raise ValueError('Empty mean')
... | [
"def",
"mean",
"(",
"l",
",",
"ignore_nan",
"=",
"False",
",",
"empty",
"=",
"0",
")",
":",
"l",
"=",
"iter",
"(",
"l",
")",
"if",
"ignore_nan",
":",
"l",
"=",
"ifilterfalse",
"(",
"np",
".",
"isnan",
",",
"l",
")",
"try",
":",
"n",
"=",
"1",... | nanmean compatible with generators. | [
"nanmean",
"compatible",
"with",
"generators",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/kaggle-tgs-salt/lovasz_losses.py#L234-L252 | train |
Microsoft/nni | tools/nni_trial_tool/trial_keeper.py | main_loop | def main_loop(args):
'''main loop logic for trial keeper'''
if not os.path.exists(LOG_DIR):
os.makedirs(LOG_DIR)
stdout_file = open(STDOUT_FULL_PATH, 'a+')
stderr_file = open(STDERR_FULL_PATH, 'a+')
trial_keeper_syslogger = RemoteLogger(args.nnimanager_ip, args.nnimanager_port, 'tr... | python | def main_loop(args):
'''main loop logic for trial keeper'''
if not os.path.exists(LOG_DIR):
os.makedirs(LOG_DIR)
stdout_file = open(STDOUT_FULL_PATH, 'a+')
stderr_file = open(STDERR_FULL_PATH, 'a+')
trial_keeper_syslogger = RemoteLogger(args.nnimanager_ip, args.nnimanager_port, 'tr... | [
"def",
"main_loop",
"(",
"args",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"LOG_DIR",
")",
":",
"os",
".",
"makedirs",
"(",
"LOG_DIR",
")",
"stdout_file",
"=",
"open",
"(",
"STDOUT_FULL_PATH",
",",
"'a+'",
")",
"stderr_file",
"=",
... | main loop logic for trial keeper | [
"main",
"loop",
"logic",
"for",
"trial",
"keeper"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_trial_tool/trial_keeper.py#L43-L105 | train |
Microsoft/nni | examples/trials/cifar10_pytorch/models/shufflenet.py | ShuffleBlock.forward | def forward(self, x):
'''Channel shuffle: [N,C,H,W] -> [N,g,C/g,H,W] -> [N,C/g,g,H,w] -> [N,C,H,W]'''
N,C,H,W = x.size()
g = self.groups
return x.view(N,g,C/g,H,W).permute(0,2,1,3,4).contiguous().view(N,C,H,W) | python | def forward(self, x):
'''Channel shuffle: [N,C,H,W] -> [N,g,C/g,H,W] -> [N,C/g,g,H,w] -> [N,C,H,W]'''
N,C,H,W = x.size()
g = self.groups
return x.view(N,g,C/g,H,W).permute(0,2,1,3,4).contiguous().view(N,C,H,W) | [
"def",
"forward",
"(",
"self",
",",
"x",
")",
":",
"N",
",",
"C",
",",
"H",
",",
"W",
"=",
"x",
".",
"size",
"(",
")",
"g",
"=",
"self",
".",
"groups",
"return",
"x",
".",
"view",
"(",
"N",
",",
"g",
",",
"C",
"/",
"g",
",",
"H",
",",
... | Channel shuffle: [N,C,H,W] -> [N,g,C/g,H,W] -> [N,C/g,g,H,w] -> [N,C,H,W] | [
"Channel",
"shuffle",
":",
"[",
"N",
"C",
"H",
"W",
"]",
"-",
">",
"[",
"N",
"g",
"C",
"/",
"g",
"H",
"W",
"]",
"-",
">",
"[",
"N",
"C",
"/",
"g",
"g",
"H",
"w",
"]",
"-",
">",
"[",
"N",
"C",
"H",
"W",
"]"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/cifar10_pytorch/models/shufflenet.py#L15-L19 | train |
Microsoft/nni | examples/trials/ga_squad/trial.py | load_embedding | def load_embedding(path):
'''
return embedding for a specific file by given file path.
'''
EMBEDDING_DIM = 300
embedding_dict = {}
with open(path, 'r', encoding='utf-8') as file:
pairs = [line.strip('\r\n').split() for line in file.readlines()]
for pair in pairs:
if l... | python | def load_embedding(path):
'''
return embedding for a specific file by given file path.
'''
EMBEDDING_DIM = 300
embedding_dict = {}
with open(path, 'r', encoding='utf-8') as file:
pairs = [line.strip('\r\n').split() for line in file.readlines()]
for pair in pairs:
if l... | [
"def",
"load_embedding",
"(",
"path",
")",
":",
"EMBEDDING_DIM",
"=",
"300",
"embedding_dict",
"=",
"{",
"}",
"with",
"open",
"(",
"path",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"file",
":",
"pairs",
"=",
"[",
"line",
".",
"strip",
"... | return embedding for a specific file by given file path. | [
"return",
"embedding",
"for",
"a",
"specific",
"file",
"by",
"given",
"file",
"path",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/ga_squad/trial.py#L87-L99 | train |
Microsoft/nni | examples/trials/ga_squad/trial.py | generate_predict_json | def generate_predict_json(position1_result, position2_result, ids, passage_tokens):
'''
Generate json by prediction.
'''
predict_len = len(position1_result)
logger.debug('total prediction num is %s', str(predict_len))
answers = {}
for i in range(predict_len):
sample_id = ids[i]
... | python | def generate_predict_json(position1_result, position2_result, ids, passage_tokens):
'''
Generate json by prediction.
'''
predict_len = len(position1_result)
logger.debug('total prediction num is %s', str(predict_len))
answers = {}
for i in range(predict_len):
sample_id = ids[i]
... | [
"def",
"generate_predict_json",
"(",
"position1_result",
",",
"position2_result",
",",
"ids",
",",
"passage_tokens",
")",
":",
"predict_len",
"=",
"len",
"(",
"position1_result",
")",
"logger",
".",
"debug",
"(",
"'total prediction num is %s'",
",",
"str",
"(",
"p... | Generate json by prediction. | [
"Generate",
"json",
"by",
"prediction",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/ga_squad/trial.py#L252-L269 | train |
Microsoft/nni | examples/trials/ga_squad/trial.py | generate_data | def generate_data(path, tokenizer, char_vcb, word_vcb, is_training=False):
'''
Generate data
'''
global root_path
qp_pairs = data.load_from_file(path=path, is_training=is_training)
tokenized_sent = 0
# qp_pairs = qp_pairs[:1000]1
for qp_pair in qp_pairs:
tokenized_sent += 1
... | python | def generate_data(path, tokenizer, char_vcb, word_vcb, is_training=False):
'''
Generate data
'''
global root_path
qp_pairs = data.load_from_file(path=path, is_training=is_training)
tokenized_sent = 0
# qp_pairs = qp_pairs[:1000]1
for qp_pair in qp_pairs:
tokenized_sent += 1
... | [
"def",
"generate_data",
"(",
"path",
",",
"tokenizer",
",",
"char_vcb",
",",
"word_vcb",
",",
"is_training",
"=",
"False",
")",
":",
"global",
"root_path",
"qp_pairs",
"=",
"data",
".",
"load_from_file",
"(",
"path",
"=",
"path",
",",
"is_training",
"=",
"... | Generate data | [
"Generate",
"data"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/ga_squad/trial.py#L272-L299 | train |
Microsoft/nni | examples/trials/ga_squad/evaluate.py | f1_score | def f1_score(prediction, ground_truth):
'''
Calculate the f1 score.
'''
prediction_tokens = normalize_answer(prediction).split()
ground_truth_tokens = normalize_answer(ground_truth).split()
common = Counter(prediction_tokens) & Counter(ground_truth_tokens)
num_same = sum(common.values())
... | python | def f1_score(prediction, ground_truth):
'''
Calculate the f1 score.
'''
prediction_tokens = normalize_answer(prediction).split()
ground_truth_tokens = normalize_answer(ground_truth).split()
common = Counter(prediction_tokens) & Counter(ground_truth_tokens)
num_same = sum(common.values())
... | [
"def",
"f1_score",
"(",
"prediction",
",",
"ground_truth",
")",
":",
"prediction_tokens",
"=",
"normalize_answer",
"(",
"prediction",
")",
".",
"split",
"(",
")",
"ground_truth_tokens",
"=",
"normalize_answer",
"(",
"ground_truth",
")",
".",
"split",
"(",
")",
... | Calculate the f1 score. | [
"Calculate",
"the",
"f1",
"score",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/ga_squad/evaluate.py#L63-L76 | train |
Microsoft/nni | examples/trials/ga_squad/evaluate.py | _evaluate | def _evaluate(dataset, predictions):
'''
Evaluate function.
'''
f1_result = exact_match = total = 0
count = 0
for article in dataset:
for paragraph in article['paragraphs']:
for qa_pair in paragraph['qas']:
total += 1
if qa_pair['id'] not in pr... | python | def _evaluate(dataset, predictions):
'''
Evaluate function.
'''
f1_result = exact_match = total = 0
count = 0
for article in dataset:
for paragraph in article['paragraphs']:
for qa_pair in paragraph['qas']:
total += 1
if qa_pair['id'] not in pr... | [
"def",
"_evaluate",
"(",
"dataset",
",",
"predictions",
")",
":",
"f1_result",
"=",
"exact_match",
"=",
"total",
"=",
"0",
"count",
"=",
"0",
"for",
"article",
"in",
"dataset",
":",
"for",
"paragraph",
"in",
"article",
"[",
"'paragraphs'",
"]",
":",
"for... | Evaluate function. | [
"Evaluate",
"function",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/ga_squad/evaluate.py#L94-L116 | train |
Microsoft/nni | examples/trials/ga_squad/evaluate.py | evaluate | def evaluate(data_file, pred_file):
'''
Evaluate.
'''
expected_version = '1.1'
with open(data_file) as dataset_file:
dataset_json = json.load(dataset_file)
if dataset_json['version'] != expected_version:
print('Evaluation expects v-' + expected_version +
... | python | def evaluate(data_file, pred_file):
'''
Evaluate.
'''
expected_version = '1.1'
with open(data_file) as dataset_file:
dataset_json = json.load(dataset_file)
if dataset_json['version'] != expected_version:
print('Evaluation expects v-' + expected_version +
... | [
"def",
"evaluate",
"(",
"data_file",
",",
"pred_file",
")",
":",
"expected_version",
"=",
"'1.1'",
"with",
"open",
"(",
"data_file",
")",
"as",
"dataset_file",
":",
"dataset_json",
"=",
"json",
".",
"load",
"(",
"dataset_file",
")",
"if",
"dataset_json",
"["... | Evaluate. | [
"Evaluate",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/ga_squad/evaluate.py#L118-L135 | train |
Microsoft/nni | examples/trials/ga_squad/evaluate.py | evaluate_with_predictions | def evaluate_with_predictions(data_file, predictions):
'''
Evalutate with predictions/
'''
expected_version = '1.1'
with open(data_file) as dataset_file:
dataset_json = json.load(dataset_file)
if dataset_json['version'] != expected_version:
print('Evaluation expects v-' +... | python | def evaluate_with_predictions(data_file, predictions):
'''
Evalutate with predictions/
'''
expected_version = '1.1'
with open(data_file) as dataset_file:
dataset_json = json.load(dataset_file)
if dataset_json['version'] != expected_version:
print('Evaluation expects v-' +... | [
"def",
"evaluate_with_predictions",
"(",
"data_file",
",",
"predictions",
")",
":",
"expected_version",
"=",
"'1.1'",
"with",
"open",
"(",
"data_file",
")",
"as",
"dataset_file",
":",
"dataset_json",
"=",
"json",
".",
"load",
"(",
"dataset_file",
")",
"if",
"d... | Evalutate with predictions/ | [
"Evalutate",
"with",
"predictions",
"/"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/ga_squad/evaluate.py#L137-L150 | train |
Microsoft/nni | src/sdk/pynni/nni/protocol.py | send | def send(command, data):
"""Send command to Training Service.
command: CommandType object.
data: string payload.
"""
global _lock
try:
_lock.acquire()
data = data.encode('utf8')
assert len(data) < 1000000, 'Command too long'
msg = b'%b%06d%b' % (command.value, len... | python | def send(command, data):
"""Send command to Training Service.
command: CommandType object.
data: string payload.
"""
global _lock
try:
_lock.acquire()
data = data.encode('utf8')
assert len(data) < 1000000, 'Command too long'
msg = b'%b%06d%b' % (command.value, len... | [
"def",
"send",
"(",
"command",
",",
"data",
")",
":",
"global",
"_lock",
"try",
":",
"_lock",
".",
"acquire",
"(",
")",
"data",
"=",
"data",
".",
"encode",
"(",
"'utf8'",
")",
"assert",
"len",
"(",
"data",
")",
"<",
"1000000",
",",
"'Command too long... | Send command to Training Service.
command: CommandType object.
data: string payload. | [
"Send",
"command",
"to",
"Training",
"Service",
".",
"command",
":",
"CommandType",
"object",
".",
"data",
":",
"string",
"payload",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/protocol.py#L56-L71 | train |
Microsoft/nni | src/sdk/pynni/nni/protocol.py | receive | def receive():
"""Receive a command from Training Service.
Returns a tuple of command (CommandType) and payload (str)
"""
header = _in_file.read(8)
logging.getLogger(__name__).debug('Received command, header: [%s]' % header)
if header is None or len(header) < 8:
# Pipe EOF encountered
... | python | def receive():
"""Receive a command from Training Service.
Returns a tuple of command (CommandType) and payload (str)
"""
header = _in_file.read(8)
logging.getLogger(__name__).debug('Received command, header: [%s]' % header)
if header is None or len(header) < 8:
# Pipe EOF encountered
... | [
"def",
"receive",
"(",
")",
":",
"header",
"=",
"_in_file",
".",
"read",
"(",
"8",
")",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
".",
"debug",
"(",
"'Received command, header: [%s]'",
"%",
"header",
")",
"if",
"header",
"is",
"None",
"or",
"len... | Receive a command from Training Service.
Returns a tuple of command (CommandType) and payload (str) | [
"Receive",
"a",
"command",
"from",
"Training",
"Service",
".",
"Returns",
"a",
"tuple",
"of",
"command",
"(",
"CommandType",
")",
"and",
"payload",
"(",
"str",
")"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/protocol.py#L74-L89 | train |
Microsoft/nni | src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py | json2space | def json2space(in_x, name=ROOT):
"""
Change json to search space in hyperopt.
Parameters
----------
in_x : dict/list/str/int/float
The part of json.
name : str
name could be ROOT, TYPE, VALUE or INDEX.
"""
out_y = copy.deepcopy(in_x)
if isinstance(in_x, dict):
... | python | def json2space(in_x, name=ROOT):
"""
Change json to search space in hyperopt.
Parameters
----------
in_x : dict/list/str/int/float
The part of json.
name : str
name could be ROOT, TYPE, VALUE or INDEX.
"""
out_y = copy.deepcopy(in_x)
if isinstance(in_x, dict):
... | [
"def",
"json2space",
"(",
"in_x",
",",
"name",
"=",
"ROOT",
")",
":",
"out_y",
"=",
"copy",
".",
"deepcopy",
"(",
"in_x",
")",
"if",
"isinstance",
"(",
"in_x",
",",
"dict",
")",
":",
"if",
"TYPE",
"in",
"in_x",
".",
"keys",
"(",
")",
":",
"_type"... | Change json to search space in hyperopt.
Parameters
----------
in_x : dict/list/str/int/float
The part of json.
name : str
name could be ROOT, TYPE, VALUE or INDEX. | [
"Change",
"json",
"to",
"search",
"space",
"in",
"hyperopt",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py#L52-L85 | train |
Microsoft/nni | src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py | json2parameter | def json2parameter(in_x, parameter, name=ROOT):
"""
Change json to parameters.
"""
out_y = copy.deepcopy(in_x)
if isinstance(in_x, dict):
if TYPE in in_x.keys():
_type = in_x[TYPE]
name = name + '-' + _type
if _type == 'choice':
_index = pa... | python | def json2parameter(in_x, parameter, name=ROOT):
"""
Change json to parameters.
"""
out_y = copy.deepcopy(in_x)
if isinstance(in_x, dict):
if TYPE in in_x.keys():
_type = in_x[TYPE]
name = name + '-' + _type
if _type == 'choice':
_index = pa... | [
"def",
"json2parameter",
"(",
"in_x",
",",
"parameter",
",",
"name",
"=",
"ROOT",
")",
":",
"out_y",
"=",
"copy",
".",
"deepcopy",
"(",
"in_x",
")",
"if",
"isinstance",
"(",
"in_x",
",",
"dict",
")",
":",
"if",
"TYPE",
"in",
"in_x",
".",
"keys",
"(... | Change json to parameters. | [
"Change",
"json",
"to",
"parameters",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py#L88-L116 | train |
Microsoft/nni | src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py | _add_index | def _add_index(in_x, parameter):
"""
change parameters in NNI format to parameters in hyperopt format(This function also support nested dict.).
For example, receive parameters like:
{'dropout_rate': 0.8, 'conv_size': 3, 'hidden_size': 512}
Will change to format in hyperopt, like:
{'dropo... | python | def _add_index(in_x, parameter):
"""
change parameters in NNI format to parameters in hyperopt format(This function also support nested dict.).
For example, receive parameters like:
{'dropout_rate': 0.8, 'conv_size': 3, 'hidden_size': 512}
Will change to format in hyperopt, like:
{'dropo... | [
"def",
"_add_index",
"(",
"in_x",
",",
"parameter",
")",
":",
"if",
"TYPE",
"not",
"in",
"in_x",
":",
"# if at the top level",
"out_y",
"=",
"dict",
"(",
")",
"for",
"key",
",",
"value",
"in",
"parameter",
".",
"items",
"(",
")",
":",
"out_y",
"[",
"... | change parameters in NNI format to parameters in hyperopt format(This function also support nested dict.).
For example, receive parameters like:
{'dropout_rate': 0.8, 'conv_size': 3, 'hidden_size': 512}
Will change to format in hyperopt, like:
{'dropout_rate': 0.8, 'conv_size': {'_index': 1, '_v... | [
"change",
"parameters",
"in",
"NNI",
"format",
"to",
"parameters",
"in",
"hyperopt",
"format",
"(",
"This",
"function",
"also",
"support",
"nested",
"dict",
".",
")",
".",
"For",
"example",
"receive",
"parameters",
"like",
":",
"{",
"dropout_rate",
":",
"0",... | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py#L142-L169 | train |
Microsoft/nni | src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py | _split_index | def _split_index(params):
"""
Delete index infromation from params
"""
if isinstance(params, list):
return [params[0], _split_index(params[1])]
elif isinstance(params, dict):
if INDEX in params.keys():
return _split_index(params[VALUE])
result = dict()
for... | python | def _split_index(params):
"""
Delete index infromation from params
"""
if isinstance(params, list):
return [params[0], _split_index(params[1])]
elif isinstance(params, dict):
if INDEX in params.keys():
return _split_index(params[VALUE])
result = dict()
for... | [
"def",
"_split_index",
"(",
"params",
")",
":",
"if",
"isinstance",
"(",
"params",
",",
"list",
")",
":",
"return",
"[",
"params",
"[",
"0",
"]",
",",
"_split_index",
"(",
"params",
"[",
"1",
"]",
")",
"]",
"elif",
"isinstance",
"(",
"params",
",",
... | Delete index infromation from params | [
"Delete",
"index",
"infromation",
"from",
"params"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py#L171-L185 | train |
Microsoft/nni | src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py | HyperoptTuner._choose_tuner | def _choose_tuner(self, algorithm_name):
"""
Parameters
----------
algorithm_name : str
algorithm_name includes "tpe", "random_search" and anneal"
"""
if algorithm_name == 'tpe':
return hp.tpe.suggest
if algorithm_name == 'random_search':
... | python | def _choose_tuner(self, algorithm_name):
"""
Parameters
----------
algorithm_name : str
algorithm_name includes "tpe", "random_search" and anneal"
"""
if algorithm_name == 'tpe':
return hp.tpe.suggest
if algorithm_name == 'random_search':
... | [
"def",
"_choose_tuner",
"(",
"self",
",",
"algorithm_name",
")",
":",
"if",
"algorithm_name",
"==",
"'tpe'",
":",
"return",
"hp",
".",
"tpe",
".",
"suggest",
"if",
"algorithm_name",
"==",
"'random_search'",
":",
"return",
"hp",
".",
"rand",
".",
"suggest",
... | Parameters
----------
algorithm_name : str
algorithm_name includes "tpe", "random_search" and anneal" | [
"Parameters",
"----------",
"algorithm_name",
":",
"str",
"algorithm_name",
"includes",
"tpe",
"random_search",
"and",
"anneal"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py#L208-L221 | train |
Microsoft/nni | src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py | HyperoptTuner.update_search_space | def update_search_space(self, search_space):
"""
Update search space definition in tuner by search_space in parameters.
Will called when first setup experiemnt or update search space in WebUI.
Parameters
----------
search_space : dict
"""
self.json = sea... | python | def update_search_space(self, search_space):
"""
Update search space definition in tuner by search_space in parameters.
Will called when first setup experiemnt or update search space in WebUI.
Parameters
----------
search_space : dict
"""
self.json = sea... | [
"def",
"update_search_space",
"(",
"self",
",",
"search_space",
")",
":",
"self",
".",
"json",
"=",
"search_space",
"search_space_instance",
"=",
"json2space",
"(",
"self",
".",
"json",
")",
"rstate",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
")",
... | Update search space definition in tuner by search_space in parameters.
Will called when first setup experiemnt or update search space in WebUI.
Parameters
----------
search_space : dict | [
"Update",
"search",
"space",
"definition",
"in",
"tuner",
"by",
"search_space",
"in",
"parameters",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py#L223-L242 | train |
Microsoft/nni | src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py | HyperoptTuner.generate_parameters | def generate_parameters(self, parameter_id):
"""
Returns a set of trial (hyper-)parameters, as a serializable object.
Parameters
----------
parameter_id : int
Returns
-------
params : dict
"""
total_params = self.get_suggestion(random_sea... | python | def generate_parameters(self, parameter_id):
"""
Returns a set of trial (hyper-)parameters, as a serializable object.
Parameters
----------
parameter_id : int
Returns
-------
params : dict
"""
total_params = self.get_suggestion(random_sea... | [
"def",
"generate_parameters",
"(",
"self",
",",
"parameter_id",
")",
":",
"total_params",
"=",
"self",
".",
"get_suggestion",
"(",
"random_search",
"=",
"False",
")",
"# avoid generating same parameter with concurrent trials because hyperopt doesn't support parallel mode",
"if"... | Returns a set of trial (hyper-)parameters, as a serializable object.
Parameters
----------
parameter_id : int
Returns
-------
params : dict | [
"Returns",
"a",
"set",
"of",
"trial",
"(",
"hyper",
"-",
")",
"parameters",
"as",
"a",
"serializable",
"object",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py#L244-L263 | train |
Microsoft/nni | src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py | HyperoptTuner.receive_trial_result | def receive_trial_result(self, parameter_id, parameters, value):
"""
Record an observation of the objective function
Parameters
----------
parameter_id : int
parameters : dict
value : dict/float
if value is dict, it should have "default" key.
... | python | def receive_trial_result(self, parameter_id, parameters, value):
"""
Record an observation of the objective function
Parameters
----------
parameter_id : int
parameters : dict
value : dict/float
if value is dict, it should have "default" key.
... | [
"def",
"receive_trial_result",
"(",
"self",
",",
"parameter_id",
",",
"parameters",
",",
"value",
")",
":",
"reward",
"=",
"extract_scalar_reward",
"(",
"value",
")",
"# restore the paramsters contains '_index'",
"if",
"parameter_id",
"not",
"in",
"self",
".",
"tota... | Record an observation of the objective function
Parameters
----------
parameter_id : int
parameters : dict
value : dict/float
if value is dict, it should have "default" key.
value is final metrics of the trial. | [
"Record",
"an",
"observation",
"of",
"the",
"objective",
"function"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py#L265-L319 | train |
Microsoft/nni | src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py | HyperoptTuner.miscs_update_idxs_vals | def miscs_update_idxs_vals(self, miscs, idxs, vals,
assert_all_vals_used=True,
idxs_map=None):
"""
Unpack the idxs-vals format into the list of dictionaries that is
`misc`.
Parameters
----------
idxs_map : dic... | python | def miscs_update_idxs_vals(self, miscs, idxs, vals,
assert_all_vals_used=True,
idxs_map=None):
"""
Unpack the idxs-vals format into the list of dictionaries that is
`misc`.
Parameters
----------
idxs_map : dic... | [
"def",
"miscs_update_idxs_vals",
"(",
"self",
",",
"miscs",
",",
"idxs",
",",
"vals",
",",
"assert_all_vals_used",
"=",
"True",
",",
"idxs_map",
"=",
"None",
")",
":",
"if",
"idxs_map",
"is",
"None",
":",
"idxs_map",
"=",
"{",
"}",
"assert",
"set",
"(",
... | Unpack the idxs-vals format into the list of dictionaries that is
`misc`.
Parameters
----------
idxs_map : dict
idxs_map is a dictionary of id->id mappings so that the misc['idxs'] can
contain different numbers than the idxs argument. | [
"Unpack",
"the",
"idxs",
"-",
"vals",
"format",
"into",
"the",
"list",
"of",
"dictionaries",
"that",
"is",
"misc",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py#L321-L350 | train |
Microsoft/nni | src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py | HyperoptTuner.get_suggestion | def get_suggestion(self, random_search=False):
"""get suggestion from hyperopt
Parameters
----------
random_search : bool
flag to indicate random search or not (default: {False})
Returns
----------
total_params : dict
parameter suggestion... | python | def get_suggestion(self, random_search=False):
"""get suggestion from hyperopt
Parameters
----------
random_search : bool
flag to indicate random search or not (default: {False})
Returns
----------
total_params : dict
parameter suggestion... | [
"def",
"get_suggestion",
"(",
"self",
",",
"random_search",
"=",
"False",
")",
":",
"rval",
"=",
"self",
".",
"rval",
"trials",
"=",
"rval",
".",
"trials",
"algorithm",
"=",
"rval",
".",
"algo",
"new_ids",
"=",
"rval",
".",
"trials",
".",
"new_trial_ids"... | get suggestion from hyperopt
Parameters
----------
random_search : bool
flag to indicate random search or not (default: {False})
Returns
----------
total_params : dict
parameter suggestion | [
"get",
"suggestion",
"from",
"hyperopt"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py#L352-L387 | train |
Microsoft/nni | src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py | HyperoptTuner.import_data | def import_data(self, data):
"""Import additional data for tuning
Parameters
----------
data:
a list of dictionarys, each of which has at least two keys, 'parameter' and 'value'
"""
_completed_num = 0
for trial_info in data:
logger.info("I... | python | def import_data(self, data):
"""Import additional data for tuning
Parameters
----------
data:
a list of dictionarys, each of which has at least two keys, 'parameter' and 'value'
"""
_completed_num = 0
for trial_info in data:
logger.info("I... | [
"def",
"import_data",
"(",
"self",
",",
"data",
")",
":",
"_completed_num",
"=",
"0",
"for",
"trial_info",
"in",
"data",
":",
"logger",
".",
"info",
"(",
"\"Importing data, current processing progress %s / %s\"",
"%",
"(",
"_completed_num",
",",
"len",
"(",
"dat... | Import additional data for tuning
Parameters
----------
data:
a list of dictionarys, each of which has at least two keys, 'parameter' and 'value' | [
"Import",
"additional",
"data",
"for",
"tuning"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py#L389-L414 | train |
Microsoft/nni | src/sdk/pynni/nni/metis_tuner/lib_acquisition_function.py | next_hyperparameter_lowest_mu | def next_hyperparameter_lowest_mu(fun_prediction,
fun_prediction_args,
x_bounds, x_types,
minimize_starting_points,
minimize_constraints_fun=None):
'''
"Lowest Mu" acquisition ... | python | def next_hyperparameter_lowest_mu(fun_prediction,
fun_prediction_args,
x_bounds, x_types,
minimize_starting_points,
minimize_constraints_fun=None):
'''
"Lowest Mu" acquisition ... | [
"def",
"next_hyperparameter_lowest_mu",
"(",
"fun_prediction",
",",
"fun_prediction_args",
",",
"x_bounds",
",",
"x_types",
",",
"minimize_starting_points",
",",
"minimize_constraints_fun",
"=",
"None",
")",
":",
"best_x",
"=",
"None",
"best_acquisition_value",
"=",
"No... | "Lowest Mu" acquisition function | [
"Lowest",
"Mu",
"acquisition",
"function"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/lib_acquisition_function.py#L154-L187 | train |
Microsoft/nni | src/sdk/pynni/nni/metis_tuner/lib_acquisition_function.py | _lowest_mu | def _lowest_mu(x, fun_prediction, fun_prediction_args,
x_bounds, x_types, minimize_constraints_fun):
'''
Calculate the lowest mu
'''
# This is only for step-wise optimization
x = lib_data.match_val_type(x, x_bounds, x_types)
mu = sys.maxsize
if (minimize_constraints_fun is No... | python | def _lowest_mu(x, fun_prediction, fun_prediction_args,
x_bounds, x_types, minimize_constraints_fun):
'''
Calculate the lowest mu
'''
# This is only for step-wise optimization
x = lib_data.match_val_type(x, x_bounds, x_types)
mu = sys.maxsize
if (minimize_constraints_fun is No... | [
"def",
"_lowest_mu",
"(",
"x",
",",
"fun_prediction",
",",
"fun_prediction_args",
",",
"x_bounds",
",",
"x_types",
",",
"minimize_constraints_fun",
")",
":",
"# This is only for step-wise optimization",
"x",
"=",
"lib_data",
".",
"match_val_type",
"(",
"x",
",",
"x_... | Calculate the lowest mu | [
"Calculate",
"the",
"lowest",
"mu"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/lib_acquisition_function.py#L190-L201 | train |
Microsoft/nni | examples/trials/weight_sharing/ga_squad/train_model.py | GAG.build_char_states | def build_char_states(self, char_embed, is_training, reuse, char_ids, char_lengths):
"""Build char embedding network for the QA model."""
max_char_length = self.cfg.max_char_length
inputs = dropout(tf.nn.embedding_lookup(char_embed, char_ids),
self.cfg.dropout, is_train... | python | def build_char_states(self, char_embed, is_training, reuse, char_ids, char_lengths):
"""Build char embedding network for the QA model."""
max_char_length = self.cfg.max_char_length
inputs = dropout(tf.nn.embedding_lookup(char_embed, char_ids),
self.cfg.dropout, is_train... | [
"def",
"build_char_states",
"(",
"self",
",",
"char_embed",
",",
"is_training",
",",
"reuse",
",",
"char_ids",
",",
"char_lengths",
")",
":",
"max_char_length",
"=",
"self",
".",
"cfg",
".",
"max_char_length",
"inputs",
"=",
"dropout",
"(",
"tf",
".",
"nn",
... | Build char embedding network for the QA model. | [
"Build",
"char",
"embedding",
"network",
"for",
"the",
"QA",
"model",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/train_model.py#L234-L263 | train |
Microsoft/nni | src/sdk/pynni/nni/msg_dispatcher.py | MsgDispatcher.handle_report_metric_data | def handle_report_metric_data(self, data):
"""
data: a dict received from nni_manager, which contains:
- 'parameter_id': id of the trial
- 'value': metric value reported by nni.report_final_result()
- 'type': report type, support {'FINAL', 'PERIODICAL'}
... | python | def handle_report_metric_data(self, data):
"""
data: a dict received from nni_manager, which contains:
- 'parameter_id': id of the trial
- 'value': metric value reported by nni.report_final_result()
- 'type': report type, support {'FINAL', 'PERIODICAL'}
... | [
"def",
"handle_report_metric_data",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
"[",
"'type'",
"]",
"==",
"'FINAL'",
":",
"self",
".",
"_handle_final_metric_data",
"(",
"data",
")",
"elif",
"data",
"[",
"'type'",
"]",
"==",
"'PERIODICAL'",
":",
"if",... | data: a dict received from nni_manager, which contains:
- 'parameter_id': id of the trial
- 'value': metric value reported by nni.report_final_result()
- 'type': report type, support {'FINAL', 'PERIODICAL'} | [
"data",
":",
"a",
"dict",
"received",
"from",
"nni_manager",
"which",
"contains",
":",
"-",
"parameter_id",
":",
"id",
"of",
"the",
"trial",
"-",
"value",
":",
"metric",
"value",
"reported",
"by",
"nni",
".",
"report_final_result",
"()",
"-",
"type",
":",
... | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/msg_dispatcher.py#L124-L139 | train |
Microsoft/nni | src/sdk/pynni/nni/msg_dispatcher.py | MsgDispatcher.handle_trial_end | def handle_trial_end(self, data):
"""
data: it has three keys: trial_job_id, event, hyper_params
- trial_job_id: the id generated by training service
- event: the job's state
- hyper_params: the hyperparameters generated and returned by tuner
"""
tr... | python | def handle_trial_end(self, data):
"""
data: it has three keys: trial_job_id, event, hyper_params
- trial_job_id: the id generated by training service
- event: the job's state
- hyper_params: the hyperparameters generated and returned by tuner
"""
tr... | [
"def",
"handle_trial_end",
"(",
"self",
",",
"data",
")",
":",
"trial_job_id",
"=",
"data",
"[",
"'trial_job_id'",
"]",
"_ended_trials",
".",
"add",
"(",
"trial_job_id",
")",
"if",
"trial_job_id",
"in",
"_trial_history",
":",
"_trial_history",
".",
"pop",
"(",... | data: it has three keys: trial_job_id, event, hyper_params
- trial_job_id: the id generated by training service
- event: the job's state
- hyper_params: the hyperparameters generated and returned by tuner | [
"data",
":",
"it",
"has",
"three",
"keys",
":",
"trial_job_id",
"event",
"hyper_params",
"-",
"trial_job_id",
":",
"the",
"id",
"generated",
"by",
"training",
"service",
"-",
"event",
":",
"the",
"job",
"s",
"state",
"-",
"hyper_params",
":",
"the",
"hyper... | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/msg_dispatcher.py#L141-L155 | train |
Microsoft/nni | src/sdk/pynni/nni/msg_dispatcher.py | MsgDispatcher._handle_final_metric_data | def _handle_final_metric_data(self, data):
"""Call tuner to process final results
"""
id_ = data['parameter_id']
value = data['value']
if id_ in _customized_parameter_ids:
self.tuner.receive_customized_trial_result(id_, _trial_params[id_], value)
else:
... | python | def _handle_final_metric_data(self, data):
"""Call tuner to process final results
"""
id_ = data['parameter_id']
value = data['value']
if id_ in _customized_parameter_ids:
self.tuner.receive_customized_trial_result(id_, _trial_params[id_], value)
else:
... | [
"def",
"_handle_final_metric_data",
"(",
"self",
",",
"data",
")",
":",
"id_",
"=",
"data",
"[",
"'parameter_id'",
"]",
"value",
"=",
"data",
"[",
"'value'",
"]",
"if",
"id_",
"in",
"_customized_parameter_ids",
":",
"self",
".",
"tuner",
".",
"receive_custom... | Call tuner to process final results | [
"Call",
"tuner",
"to",
"process",
"final",
"results"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/msg_dispatcher.py#L157-L165 | train |
Microsoft/nni | src/sdk/pynni/nni/msg_dispatcher.py | MsgDispatcher._handle_intermediate_metric_data | def _handle_intermediate_metric_data(self, data):
"""Call assessor to process intermediate results
"""
if data['type'] != 'PERIODICAL':
return
if self.assessor is None:
return
trial_job_id = data['trial_job_id']
if trial_job_id in _ended_trials:
... | python | def _handle_intermediate_metric_data(self, data):
"""Call assessor to process intermediate results
"""
if data['type'] != 'PERIODICAL':
return
if self.assessor is None:
return
trial_job_id = data['trial_job_id']
if trial_job_id in _ended_trials:
... | [
"def",
"_handle_intermediate_metric_data",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
"[",
"'type'",
"]",
"!=",
"'PERIODICAL'",
":",
"return",
"if",
"self",
".",
"assessor",
"is",
"None",
":",
"return",
"trial_job_id",
"=",
"data",
"[",
"'trial_job_id... | Call assessor to process intermediate results | [
"Call",
"assessor",
"to",
"process",
"intermediate",
"results"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/msg_dispatcher.py#L167-L204 | train |
Microsoft/nni | src/sdk/pynni/nni/msg_dispatcher.py | MsgDispatcher._earlystop_notify_tuner | def _earlystop_notify_tuner(self, data):
"""Send last intermediate result as final result to tuner in case the
trial is early stopped.
"""
_logger.debug('Early stop notify tuner data: [%s]', data)
data['type'] = 'FINAL'
if multi_thread_enabled():
self._handle_... | python | def _earlystop_notify_tuner(self, data):
"""Send last intermediate result as final result to tuner in case the
trial is early stopped.
"""
_logger.debug('Early stop notify tuner data: [%s]', data)
data['type'] = 'FINAL'
if multi_thread_enabled():
self._handle_... | [
"def",
"_earlystop_notify_tuner",
"(",
"self",
",",
"data",
")",
":",
"_logger",
".",
"debug",
"(",
"'Early stop notify tuner data: [%s]'",
",",
"data",
")",
"data",
"[",
"'type'",
"]",
"=",
"'FINAL'",
"if",
"multi_thread_enabled",
"(",
")",
":",
"self",
".",
... | Send last intermediate result as final result to tuner in case the
trial is early stopped. | [
"Send",
"last",
"intermediate",
"result",
"as",
"final",
"result",
"to",
"tuner",
"in",
"case",
"the",
"trial",
"is",
"early",
"stopped",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/msg_dispatcher.py#L206-L215 | train |
Microsoft/nni | examples/trials/network_morphism/FashionMNIST/FashionMNIST_keras.py | parse_rev_args | def parse_rev_args(receive_msg):
""" parse reveive msgs to global variable
"""
global trainloader
global testloader
global net
# Loading Data
logger.debug("Preparing data..")
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()
y_train = to_categorical(y_train, 10)
... | python | def parse_rev_args(receive_msg):
""" parse reveive msgs to global variable
"""
global trainloader
global testloader
global net
# Loading Data
logger.debug("Preparing data..")
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()
y_train = to_categorical(y_train, 10)
... | [
"def",
"parse_rev_args",
"(",
"receive_msg",
")",
":",
"global",
"trainloader",
"global",
"testloader",
"global",
"net",
"# Loading Data",
"logger",
".",
"debug",
"(",
"\"Preparing data..\"",
")",
"(",
"x_train",
",",
"y_train",
")",
",",
"(",
"x_test",
",",
"... | parse reveive msgs to global variable | [
"parse",
"reveive",
"msgs",
"to",
"global",
"variable"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/network_morphism/FashionMNIST/FashionMNIST_keras.py#L90-L140 | train |
Microsoft/nni | examples/trials/network_morphism/FashionMNIST/FashionMNIST_keras.py | train_eval | def train_eval():
""" train and eval the model
"""
global trainloader
global testloader
global net
(x_train, y_train) = trainloader
(x_test, y_test) = testloader
# train procedure
net.fit(
x=x_train,
y=y_train,
batch_size=args.batch_size,
validation... | python | def train_eval():
""" train and eval the model
"""
global trainloader
global testloader
global net
(x_train, y_train) = trainloader
(x_test, y_test) = testloader
# train procedure
net.fit(
x=x_train,
y=y_train,
batch_size=args.batch_size,
validation... | [
"def",
"train_eval",
"(",
")",
":",
"global",
"trainloader",
"global",
"testloader",
"global",
"net",
"(",
"x_train",
",",
"y_train",
")",
"=",
"trainloader",
"(",
"x_test",
",",
"y_test",
")",
"=",
"testloader",
"# train procedure",
"net",
".",
"fit",
"(",
... | train and eval the model | [
"train",
"and",
"eval",
"the",
"model"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/network_morphism/FashionMNIST/FashionMNIST_keras.py#L159-L188 | train |
Microsoft/nni | examples/trials/network_morphism/FashionMNIST/FashionMNIST_keras.py | SendMetrics.on_epoch_end | def on_epoch_end(self, epoch, logs=None):
"""
Run on end of each epoch
"""
if logs is None:
logs = dict()
logger.debug(logs)
nni.report_intermediate_result(logs["val_acc"]) | python | def on_epoch_end(self, epoch, logs=None):
"""
Run on end of each epoch
"""
if logs is None:
logs = dict()
logger.debug(logs)
nni.report_intermediate_result(logs["val_acc"]) | [
"def",
"on_epoch_end",
"(",
"self",
",",
"epoch",
",",
"logs",
"=",
"None",
")",
":",
"if",
"logs",
"is",
"None",
":",
"logs",
"=",
"dict",
"(",
")",
"logger",
".",
"debug",
"(",
"logs",
")",
"nni",
".",
"report_intermediate_result",
"(",
"logs",
"["... | Run on end of each epoch | [
"Run",
"on",
"end",
"of",
"each",
"epoch"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/network_morphism/FashionMNIST/FashionMNIST_keras.py#L148-L155 | train |
Microsoft/nni | src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py | create_bracket_parameter_id | def create_bracket_parameter_id(brackets_id, brackets_curr_decay, increased_id=-1):
"""Create a full id for a specific bracket's hyperparameter configuration
Parameters
----------
brackets_id: int
brackets id
brackets_curr_decay:
brackets curr decay
increased_id: int
... | python | def create_bracket_parameter_id(brackets_id, brackets_curr_decay, increased_id=-1):
"""Create a full id for a specific bracket's hyperparameter configuration
Parameters
----------
brackets_id: int
brackets id
brackets_curr_decay:
brackets curr decay
increased_id: int
... | [
"def",
"create_bracket_parameter_id",
"(",
"brackets_id",
",",
"brackets_curr_decay",
",",
"increased_id",
"=",
"-",
"1",
")",
":",
"if",
"increased_id",
"==",
"-",
"1",
":",
"increased_id",
"=",
"str",
"(",
"create_parameter_id",
"(",
")",
")",
"params_id",
"... | Create a full id for a specific bracket's hyperparameter configuration
Parameters
----------
brackets_id: int
brackets id
brackets_curr_decay:
brackets curr decay
increased_id: int
increased id
Returns
-------
int
params id | [
"Create",
"a",
"full",
"id",
"for",
"a",
"specific",
"bracket",
"s",
"hyperparameter",
"configuration",
"Parameters",
"----------",
"brackets_id",
":",
"int",
"brackets",
"id",
"brackets_curr_decay",
":",
"brackets",
"curr",
"decay",
"increased_id",
":",
"int",
"i... | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py#L61-L83 | train |
Microsoft/nni | src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py | json2paramater | def json2paramater(ss_spec, random_state):
"""Randomly generate values for hyperparameters from hyperparameter space i.e., x.
Parameters
----------
ss_spec:
hyperparameter space
random_state:
random operator to generate random values
Returns
-------
Parameter:
... | python | def json2paramater(ss_spec, random_state):
"""Randomly generate values for hyperparameters from hyperparameter space i.e., x.
Parameters
----------
ss_spec:
hyperparameter space
random_state:
random operator to generate random values
Returns
-------
Parameter:
... | [
"def",
"json2paramater",
"(",
"ss_spec",
",",
"random_state",
")",
":",
"if",
"isinstance",
"(",
"ss_spec",
",",
"dict",
")",
":",
"if",
"'_type'",
"in",
"ss_spec",
".",
"keys",
"(",
")",
":",
"_type",
"=",
"ss_spec",
"[",
"'_type'",
"]",
"_value",
"="... | Randomly generate values for hyperparameters from hyperparameter space i.e., x.
Parameters
----------
ss_spec:
hyperparameter space
random_state:
random operator to generate random values
Returns
-------
Parameter:
Parameters in this experiment | [
"Randomly",
"generate",
"values",
"for",
"hyperparameters",
"from",
"hyperparameter",
"space",
"i",
".",
"e",
".",
"x",
".",
"Parameters",
"----------",
"ss_spec",
":",
"hyperparameter",
"space",
"random_state",
":",
"random",
"operator",
"to",
"generate",
"random... | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py#L85-L120 | train |
Microsoft/nni | src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py | Bracket.get_n_r | def get_n_r(self):
"""return the values of n and r for the next round"""
return math.floor(self.n / self.eta**self.i + _epsilon), math.floor(self.r * self.eta**self.i + _epsilon) | python | def get_n_r(self):
"""return the values of n and r for the next round"""
return math.floor(self.n / self.eta**self.i + _epsilon), math.floor(self.r * self.eta**self.i + _epsilon) | [
"def",
"get_n_r",
"(",
"self",
")",
":",
"return",
"math",
".",
"floor",
"(",
"self",
".",
"n",
"/",
"self",
".",
"eta",
"**",
"self",
".",
"i",
"+",
"_epsilon",
")",
",",
"math",
".",
"floor",
"(",
"self",
".",
"r",
"*",
"self",
".",
"eta",
... | return the values of n and r for the next round | [
"return",
"the",
"values",
"of",
"n",
"and",
"r",
"for",
"the",
"next",
"round"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py#L159-L161 | train |
Microsoft/nni | src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py | Bracket.increase_i | def increase_i(self):
"""i means the ith round. Increase i by 1"""
self.i += 1
if self.i > self.bracket_id:
self.no_more_trial = True | python | def increase_i(self):
"""i means the ith round. Increase i by 1"""
self.i += 1
if self.i > self.bracket_id:
self.no_more_trial = True | [
"def",
"increase_i",
"(",
"self",
")",
":",
"self",
".",
"i",
"+=",
"1",
"if",
"self",
".",
"i",
">",
"self",
".",
"bracket_id",
":",
"self",
".",
"no_more_trial",
"=",
"True"
] | i means the ith round. Increase i by 1 | [
"i",
"means",
"the",
"ith",
"round",
".",
"Increase",
"i",
"by",
"1"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py#L163-L167 | train |
Microsoft/nni | src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py | Bracket.set_config_perf | def set_config_perf(self, i, parameter_id, seq, value):
"""update trial's latest result with its sequence number, e.g., epoch number or batch number
Parameters
----------
i: int
the ith round
parameter_id: int
the id of the trial/parameter
... | python | def set_config_perf(self, i, parameter_id, seq, value):
"""update trial's latest result with its sequence number, e.g., epoch number or batch number
Parameters
----------
i: int
the ith round
parameter_id: int
the id of the trial/parameter
... | [
"def",
"set_config_perf",
"(",
"self",
",",
"i",
",",
"parameter_id",
",",
"seq",
",",
"value",
")",
":",
"if",
"parameter_id",
"in",
"self",
".",
"configs_perf",
"[",
"i",
"]",
":",
"if",
"self",
".",
"configs_perf",
"[",
"i",
"]",
"[",
"parameter_id"... | update trial's latest result with its sequence number, e.g., epoch number or batch number
Parameters
----------
i: int
the ith round
parameter_id: int
the id of the trial/parameter
seq: int
sequence number, e.g., epoch number or batch ... | [
"update",
"trial",
"s",
"latest",
"result",
"with",
"its",
"sequence",
"number",
"e",
".",
"g",
".",
"epoch",
"number",
"or",
"batch",
"number",
"Parameters",
"----------",
"i",
":",
"int",
"the",
"ith",
"round",
"parameter_id",
":",
"int",
"the",
"id",
... | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py#L169-L191 | train |
Microsoft/nni | src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py | Bracket.inform_trial_end | def inform_trial_end(self, i):
"""If the trial is finished and the corresponding round (i.e., i) has all its trials finished,
it will choose the top k trials for the next round (i.e., i+1)
Parameters
----------
i: int
the ith round
"""
global _KEY # p... | python | def inform_trial_end(self, i):
"""If the trial is finished and the corresponding round (i.e., i) has all its trials finished,
it will choose the top k trials for the next round (i.e., i+1)
Parameters
----------
i: int
the ith round
"""
global _KEY # p... | [
"def",
"inform_trial_end",
"(",
"self",
",",
"i",
")",
":",
"global",
"_KEY",
"# pylint: disable=global-statement",
"self",
".",
"num_finished_configs",
"[",
"i",
"]",
"+=",
"1",
"_logger",
".",
"debug",
"(",
"'bracket id: %d, round: %d %d, finished: %d, all: %d'",
",... | If the trial is finished and the corresponding round (i.e., i) has all its trials finished,
it will choose the top k trials for the next round (i.e., i+1)
Parameters
----------
i: int
the ith round | [
"If",
"the",
"trial",
"is",
"finished",
"and",
"the",
"corresponding",
"round",
"(",
"i",
".",
"e",
".",
"i",
")",
"has",
"all",
"its",
"trials",
"finished",
"it",
"will",
"choose",
"the",
"top",
"k",
"trials",
"for",
"the",
"next",
"round",
"(",
"i"... | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py#L194-L229 | train |
Microsoft/nni | src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py | Bracket.get_hyperparameter_configurations | def get_hyperparameter_configurations(self, num, r, searchspace_json, random_state): # pylint: disable=invalid-name
"""Randomly generate num hyperparameter configurations from search space
Parameters
----------
num: int
the number of hyperparameter configurations
... | python | def get_hyperparameter_configurations(self, num, r, searchspace_json, random_state): # pylint: disable=invalid-name
"""Randomly generate num hyperparameter configurations from search space
Parameters
----------
num: int
the number of hyperparameter configurations
... | [
"def",
"get_hyperparameter_configurations",
"(",
"self",
",",
"num",
",",
"r",
",",
"searchspace_json",
",",
"random_state",
")",
":",
"# pylint: disable=invalid-name",
"global",
"_KEY",
"# pylint: disable=global-statement",
"assert",
"self",
".",
"i",
"==",
"0",
"hyp... | Randomly generate num hyperparameter configurations from search space
Parameters
----------
num: int
the number of hyperparameter configurations
Returns
-------
list
a list of hyperparameter configurations. Format: [[key1, value1], [key2,... | [
"Randomly",
"generate",
"num",
"hyperparameter",
"configurations",
"from",
"search",
"space"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py#L231-L253 | train |
Microsoft/nni | src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py | Bracket._record_hyper_configs | def _record_hyper_configs(self, hyper_configs):
"""after generating one round of hyperconfigs, this function records the generated hyperconfigs,
creates a dict to record the performance when those hyperconifgs are running, set the number of finished configs
in this round to be 0, and increase th... | python | def _record_hyper_configs(self, hyper_configs):
"""after generating one round of hyperconfigs, this function records the generated hyperconfigs,
creates a dict to record the performance when those hyperconifgs are running, set the number of finished configs
in this round to be 0, and increase th... | [
"def",
"_record_hyper_configs",
"(",
"self",
",",
"hyper_configs",
")",
":",
"self",
".",
"hyper_configs",
".",
"append",
"(",
"hyper_configs",
")",
"self",
".",
"configs_perf",
".",
"append",
"(",
"dict",
"(",
")",
")",
"self",
".",
"num_finished_configs",
... | after generating one round of hyperconfigs, this function records the generated hyperconfigs,
creates a dict to record the performance when those hyperconifgs are running, set the number of finished configs
in this round to be 0, and increase the round number.
Parameters
----------
... | [
"after",
"generating",
"one",
"round",
"of",
"hyperconfigs",
"this",
"function",
"records",
"the",
"generated",
"hyperconfigs",
"creates",
"a",
"dict",
"to",
"record",
"the",
"performance",
"when",
"those",
"hyperconifgs",
"are",
"running",
"set",
"the",
"number",... | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py#L255-L269 | train |
Microsoft/nni | src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py | Hyperband._request_one_trial_job | def _request_one_trial_job(self):
"""get one trial job, i.e., one hyperparameter configuration."""
if not self.generated_hyper_configs:
if self.curr_s < 0:
self.curr_s = self.s_max
_logger.debug('create a new bracket, self.curr_s=%d', self.curr_s)
self... | python | def _request_one_trial_job(self):
"""get one trial job, i.e., one hyperparameter configuration."""
if not self.generated_hyper_configs:
if self.curr_s < 0:
self.curr_s = self.s_max
_logger.debug('create a new bracket, self.curr_s=%d', self.curr_s)
self... | [
"def",
"_request_one_trial_job",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"generated_hyper_configs",
":",
"if",
"self",
".",
"curr_s",
"<",
"0",
":",
"self",
".",
"curr_s",
"=",
"self",
".",
"s_max",
"_logger",
".",
"debug",
"(",
"'create a new bra... | get one trial job, i.e., one hyperparameter configuration. | [
"get",
"one",
"trial",
"job",
"i",
".",
"e",
".",
"one",
"hyperparameter",
"configuration",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py#L331-L354 | train |
Microsoft/nni | src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py | Hyperband.handle_update_search_space | def handle_update_search_space(self, data):
"""data: JSON object, which is search space
Parameters
----------
data: int
number of trial jobs
"""
self.searchspace_json = data
self.random_state = np.random.RandomState() | python | def handle_update_search_space(self, data):
"""data: JSON object, which is search space
Parameters
----------
data: int
number of trial jobs
"""
self.searchspace_json = data
self.random_state = np.random.RandomState() | [
"def",
"handle_update_search_space",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"searchspace_json",
"=",
"data",
"self",
".",
"random_state",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
")"
] | data: JSON object, which is search space
Parameters
----------
data: int
number of trial jobs | [
"data",
":",
"JSON",
"object",
"which",
"is",
"search",
"space",
"Parameters",
"----------",
"data",
":",
"int",
"number",
"of",
"trial",
"jobs"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py#L356-L365 | train |
Microsoft/nni | src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py | Hyperband.handle_trial_end | def handle_trial_end(self, data):
"""
Parameters
----------
data: dict()
it has three keys: trial_job_id, event, hyper_params
trial_job_id: the id generated by training service
event: the job's state
hyper_params: the hyperparameters (a str... | python | def handle_trial_end(self, data):
"""
Parameters
----------
data: dict()
it has three keys: trial_job_id, event, hyper_params
trial_job_id: the id generated by training service
event: the job's state
hyper_params: the hyperparameters (a str... | [
"def",
"handle_trial_end",
"(",
"self",
",",
"data",
")",
":",
"hyper_params",
"=",
"json_tricks",
".",
"loads",
"(",
"data",
"[",
"'hyper_params'",
"]",
")",
"bracket_id",
",",
"i",
",",
"_",
"=",
"hyper_params",
"[",
"'parameter_id'",
"]",
".",
"split",
... | Parameters
----------
data: dict()
it has three keys: trial_job_id, event, hyper_params
trial_job_id: the id generated by training service
event: the job's state
hyper_params: the hyperparameters (a string) generated and returned by tuner | [
"Parameters",
"----------",
"data",
":",
"dict",
"()",
"it",
"has",
"three",
"keys",
":",
"trial_job_id",
"event",
"hyper_params",
"trial_job_id",
":",
"the",
"id",
"generated",
"by",
"training",
"service",
"event",
":",
"the",
"job",
"s",
"state",
"hyper_para... | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py#L367-L393 | train |
Microsoft/nni | src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py | Hyperband.handle_report_metric_data | def handle_report_metric_data(self, data):
"""
Parameters
----------
data:
it is an object which has keys 'parameter_id', 'value', 'trial_job_id', 'type', 'sequence'.
Raises
------
ValueError
Data type not supported
"""
... | python | def handle_report_metric_data(self, data):
"""
Parameters
----------
data:
it is an object which has keys 'parameter_id', 'value', 'trial_job_id', 'type', 'sequence'.
Raises
------
ValueError
Data type not supported
"""
... | [
"def",
"handle_report_metric_data",
"(",
"self",
",",
"data",
")",
":",
"value",
"=",
"extract_scalar_reward",
"(",
"data",
"[",
"'value'",
"]",
")",
"bracket_id",
",",
"i",
",",
"_",
"=",
"data",
"[",
"'parameter_id'",
"]",
".",
"split",
"(",
"'_'",
")"... | Parameters
----------
data:
it is an object which has keys 'parameter_id', 'value', 'trial_job_id', 'type', 'sequence'.
Raises
------
ValueError
Data type not supported | [
"Parameters",
"----------",
"data",
":",
"it",
"is",
"an",
"object",
"which",
"has",
"keys",
"parameter_id",
"value",
"trial_job_id",
"type",
"sequence",
".",
"Raises",
"------",
"ValueError",
"Data",
"type",
"not",
"supported"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py#L395-L418 | train |
Microsoft/nni | examples/tuners/ga_customer_tuner/customer_tuner.py | CustomerTuner.generate_parameters | def generate_parameters(self, parameter_id):
"""Returns a set of trial graph config, as a serializable object.
parameter_id : int
"""
if len(self.population) <= 0:
logger.debug("the len of poplution lower than zero.")
raise Exception('The population is empty')
... | python | def generate_parameters(self, parameter_id):
"""Returns a set of trial graph config, as a serializable object.
parameter_id : int
"""
if len(self.population) <= 0:
logger.debug("the len of poplution lower than zero.")
raise Exception('The population is empty')
... | [
"def",
"generate_parameters",
"(",
"self",
",",
"parameter_id",
")",
":",
"if",
"len",
"(",
"self",
".",
"population",
")",
"<=",
"0",
":",
"logger",
".",
"debug",
"(",
"\"the len of poplution lower than zero.\"",
")",
"raise",
"Exception",
"(",
"'The population... | Returns a set of trial graph config, as a serializable object.
parameter_id : int | [
"Returns",
"a",
"set",
"of",
"trial",
"graph",
"config",
"as",
"a",
"serializable",
"object",
".",
"parameter_id",
":",
"int"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/tuners/ga_customer_tuner/customer_tuner.py#L82-L109 | train |
Microsoft/nni | examples/tuners/ga_customer_tuner/customer_tuner.py | CustomerTuner.receive_trial_result | def receive_trial_result(self, parameter_id, parameters, value):
'''
Record an observation of the objective function
parameter_id : int
parameters : dict of parameters
value: final metrics of the trial, including reward
'''
reward = extract_scalar_reward(value)
... | python | def receive_trial_result(self, parameter_id, parameters, value):
'''
Record an observation of the objective function
parameter_id : int
parameters : dict of parameters
value: final metrics of the trial, including reward
'''
reward = extract_scalar_reward(value)
... | [
"def",
"receive_trial_result",
"(",
"self",
",",
"parameter_id",
",",
"parameters",
",",
"value",
")",
":",
"reward",
"=",
"extract_scalar_reward",
"(",
"value",
")",
"if",
"self",
".",
"optimize_mode",
"is",
"OptimizeMode",
".",
"Minimize",
":",
"reward",
"="... | Record an observation of the objective function
parameter_id : int
parameters : dict of parameters
value: final metrics of the trial, including reward | [
"Record",
"an",
"observation",
"of",
"the",
"objective",
"function",
"parameter_id",
":",
"int",
"parameters",
":",
"dict",
"of",
"parameters",
"value",
":",
"final",
"metrics",
"of",
"the",
"trial",
"including",
"reward"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/tuners/ga_customer_tuner/customer_tuner.py#L112-L129 | train |
Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/nn.py | CnnGenerator.generate | def generate(self, model_len=None, model_width=None):
"""Generates a CNN.
Args:
model_len: An integer. Number of convolutional layers.
model_width: An integer. Number of filters for the convolutional layers.
Returns:
An instance of the class Graph. Represents ... | python | def generate(self, model_len=None, model_width=None):
"""Generates a CNN.
Args:
model_len: An integer. Number of convolutional layers.
model_width: An integer. Number of filters for the convolutional layers.
Returns:
An instance of the class Graph. Represents ... | [
"def",
"generate",
"(",
"self",
",",
"model_len",
"=",
"None",
",",
"model_width",
"=",
"None",
")",
":",
"if",
"model_len",
"is",
"None",
":",
"model_len",
"=",
"Constant",
".",
"MODEL_LEN",
"if",
"model_width",
"is",
"None",
":",
"model_width",
"=",
"C... | Generates a CNN.
Args:
model_len: An integer. Number of convolutional layers.
model_width: An integer. Number of filters for the convolutional layers.
Returns:
An instance of the class Graph. Represents the neural architecture graph of the generated model. | [
"Generates",
"a",
"CNN",
".",
"Args",
":",
"model_len",
":",
"An",
"integer",
".",
"Number",
"of",
"convolutional",
"layers",
".",
"model_width",
":",
"An",
"integer",
".",
"Number",
"of",
"filters",
"for",
"the",
"convolutional",
"layers",
".",
"Returns",
... | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/nn.py#L74-L115 | train |
Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/nn.py | MlpGenerator.generate | def generate(self, model_len=None, model_width=None):
"""Generates a Multi-Layer Perceptron.
Args:
model_len: An integer. Number of hidden layers.
model_width: An integer or a list of integers of length `model_len`. If it is a list, it represents the
number of nod... | python | def generate(self, model_len=None, model_width=None):
"""Generates a Multi-Layer Perceptron.
Args:
model_len: An integer. Number of hidden layers.
model_width: An integer or a list of integers of length `model_len`. If it is a list, it represents the
number of nod... | [
"def",
"generate",
"(",
"self",
",",
"model_len",
"=",
"None",
",",
"model_width",
"=",
"None",
")",
":",
"if",
"model_len",
"is",
"None",
":",
"model_len",
"=",
"Constant",
".",
"MODEL_LEN",
"if",
"model_width",
"is",
"None",
":",
"model_width",
"=",
"C... | Generates a Multi-Layer Perceptron.
Args:
model_len: An integer. Number of hidden layers.
model_width: An integer or a list of integers of length `model_len`. If it is a list, it represents the
number of nodes in each hidden layer. If it is an integer, all hidden layers h... | [
"Generates",
"a",
"Multi",
"-",
"Layer",
"Perceptron",
".",
"Args",
":",
"model_len",
":",
"An",
"integer",
".",
"Number",
"of",
"hidden",
"layers",
".",
"model_width",
":",
"An",
"integer",
"or",
"a",
"list",
"of",
"integers",
"of",
"length",
"model_len",... | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/nn.py#L133-L166 | train |
Microsoft/nni | tools/nni_annotation/__init__.py | generate_search_space | def generate_search_space(code_dir):
"""Generate search space from Python source code.
Return a serializable search space object.
code_dir: directory path of source files (str)
"""
search_space = {}
if code_dir.endswith(slash):
code_dir = code_dir[:-1]
for subdir, _, files in o... | python | def generate_search_space(code_dir):
"""Generate search space from Python source code.
Return a serializable search space object.
code_dir: directory path of source files (str)
"""
search_space = {}
if code_dir.endswith(slash):
code_dir = code_dir[:-1]
for subdir, _, files in o... | [
"def",
"generate_search_space",
"(",
"code_dir",
")",
":",
"search_space",
"=",
"{",
"}",
"if",
"code_dir",
".",
"endswith",
"(",
"slash",
")",
":",
"code_dir",
"=",
"code_dir",
"[",
":",
"-",
"1",
"]",
"for",
"subdir",
",",
"_",
",",
"files",
"in",
... | Generate search space from Python source code.
Return a serializable search space object.
code_dir: directory path of source files (str) | [
"Generate",
"search",
"space",
"from",
"Python",
"source",
"code",
".",
"Return",
"a",
"serializable",
"search",
"space",
"object",
".",
"code_dir",
":",
"directory",
"path",
"of",
"source",
"files",
"(",
"str",
")"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_annotation/__init__.py#L36-L61 | train |
Microsoft/nni | tools/nni_annotation/__init__.py | expand_annotations | def expand_annotations(src_dir, dst_dir):
"""Expand annotations in user code.
Return dst_dir if annotation detected; return src_dir if not.
src_dir: directory path of user code (str)
dst_dir: directory to place generated files (str)
"""
if src_dir[-1] == slash:
src_dir = src_dir[:-1]
... | python | def expand_annotations(src_dir, dst_dir):
"""Expand annotations in user code.
Return dst_dir if annotation detected; return src_dir if not.
src_dir: directory path of user code (str)
dst_dir: directory to place generated files (str)
"""
if src_dir[-1] == slash:
src_dir = src_dir[:-1]
... | [
"def",
"expand_annotations",
"(",
"src_dir",
",",
"dst_dir",
")",
":",
"if",
"src_dir",
"[",
"-",
"1",
"]",
"==",
"slash",
":",
"src_dir",
"=",
"src_dir",
"[",
":",
"-",
"1",
"]",
"if",
"dst_dir",
"[",
"-",
"1",
"]",
"==",
"slash",
":",
"dst_dir",
... | Expand annotations in user code.
Return dst_dir if annotation detected; return src_dir if not.
src_dir: directory path of user code (str)
dst_dir: directory to place generated files (str) | [
"Expand",
"annotations",
"in",
"user",
"code",
".",
"Return",
"dst_dir",
"if",
"annotation",
"detected",
";",
"return",
"src_dir",
"if",
"not",
".",
"src_dir",
":",
"directory",
"path",
"of",
"user",
"code",
"(",
"str",
")",
"dst_dir",
":",
"directory",
"t... | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_annotation/__init__.py#L77-L107 | train |
Microsoft/nni | tools/nni_trial_tool/url_utils.py | gen_send_stdout_url | def gen_send_stdout_url(ip, port):
'''Generate send stdout url'''
return '{0}:{1}{2}{3}/{4}/{5}'.format(BASE_URL.format(ip), port, API_ROOT_URL, STDOUT_API, NNI_EXP_ID, NNI_TRIAL_JOB_ID) | python | def gen_send_stdout_url(ip, port):
'''Generate send stdout url'''
return '{0}:{1}{2}{3}/{4}/{5}'.format(BASE_URL.format(ip), port, API_ROOT_URL, STDOUT_API, NNI_EXP_ID, NNI_TRIAL_JOB_ID) | [
"def",
"gen_send_stdout_url",
"(",
"ip",
",",
"port",
")",
":",
"return",
"'{0}:{1}{2}{3}/{4}/{5}'",
".",
"format",
"(",
"BASE_URL",
".",
"format",
"(",
"ip",
")",
",",
"port",
",",
"API_ROOT_URL",
",",
"STDOUT_API",
",",
"NNI_EXP_ID",
",",
"NNI_TRIAL_JOB_ID",... | Generate send stdout url | [
"Generate",
"send",
"stdout",
"url"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_trial_tool/url_utils.py#L23-L25 | train |
Microsoft/nni | tools/nni_trial_tool/url_utils.py | gen_send_version_url | def gen_send_version_url(ip, port):
'''Generate send error url'''
return '{0}:{1}{2}{3}/{4}/{5}'.format(BASE_URL.format(ip), port, API_ROOT_URL, VERSION_API, NNI_EXP_ID, NNI_TRIAL_JOB_ID) | python | def gen_send_version_url(ip, port):
'''Generate send error url'''
return '{0}:{1}{2}{3}/{4}/{5}'.format(BASE_URL.format(ip), port, API_ROOT_URL, VERSION_API, NNI_EXP_ID, NNI_TRIAL_JOB_ID) | [
"def",
"gen_send_version_url",
"(",
"ip",
",",
"port",
")",
":",
"return",
"'{0}:{1}{2}{3}/{4}/{5}'",
".",
"format",
"(",
"BASE_URL",
".",
"format",
"(",
"ip",
")",
",",
"port",
",",
"API_ROOT_URL",
",",
"VERSION_API",
",",
"NNI_EXP_ID",
",",
"NNI_TRIAL_JOB_ID... | Generate send error url | [
"Generate",
"send",
"error",
"url"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_trial_tool/url_utils.py#L27-L29 | train |
Microsoft/nni | tools/nni_cmd/updater.py | validate_digit | def validate_digit(value, start, end):
'''validate if a digit is valid'''
if not str(value).isdigit() or int(value) < start or int(value) > end:
raise ValueError('%s must be a digit from %s to %s' % (value, start, end)) | python | def validate_digit(value, start, end):
'''validate if a digit is valid'''
if not str(value).isdigit() or int(value) < start or int(value) > end:
raise ValueError('%s must be a digit from %s to %s' % (value, start, end)) | [
"def",
"validate_digit",
"(",
"value",
",",
"start",
",",
"end",
")",
":",
"if",
"not",
"str",
"(",
"value",
")",
".",
"isdigit",
"(",
")",
"or",
"int",
"(",
"value",
")",
"<",
"start",
"or",
"int",
"(",
"value",
")",
">",
"end",
":",
"raise",
... | validate if a digit is valid | [
"validate",
"if",
"a",
"digit",
"is",
"valid"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/updater.py#L32-L35 | train |
Microsoft/nni | tools/nni_cmd/updater.py | validate_dispatcher | def validate_dispatcher(args):
'''validate if the dispatcher of the experiment supports importing data'''
nni_config = Config(get_config_filename(args)).get_config('experimentConfig')
if nni_config.get('tuner') and nni_config['tuner'].get('builtinTunerName'):
dispatcher_name = nni_config['tuner']['b... | python | def validate_dispatcher(args):
'''validate if the dispatcher of the experiment supports importing data'''
nni_config = Config(get_config_filename(args)).get_config('experimentConfig')
if nni_config.get('tuner') and nni_config['tuner'].get('builtinTunerName'):
dispatcher_name = nni_config['tuner']['b... | [
"def",
"validate_dispatcher",
"(",
"args",
")",
":",
"nni_config",
"=",
"Config",
"(",
"get_config_filename",
"(",
"args",
")",
")",
".",
"get_config",
"(",
"'experimentConfig'",
")",
"if",
"nni_config",
".",
"get",
"(",
"'tuner'",
")",
"and",
"nni_config",
... | validate if the dispatcher of the experiment supports importing data | [
"validate",
"if",
"the",
"dispatcher",
"of",
"the",
"experiment",
"supports",
"importing",
"data"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/updater.py#L42-L57 | train |
Microsoft/nni | tools/nni_cmd/updater.py | load_search_space | def load_search_space(path):
'''load search space content'''
content = json.dumps(get_json_content(path))
if not content:
raise ValueError('searchSpace file should not be empty')
return content | python | def load_search_space(path):
'''load search space content'''
content = json.dumps(get_json_content(path))
if not content:
raise ValueError('searchSpace file should not be empty')
return content | [
"def",
"load_search_space",
"(",
"path",
")",
":",
"content",
"=",
"json",
".",
"dumps",
"(",
"get_json_content",
"(",
"path",
")",
")",
"if",
"not",
"content",
":",
"raise",
"ValueError",
"(",
"'searchSpace file should not be empty'",
")",
"return",
"content"
] | load search space content | [
"load",
"search",
"space",
"content"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/updater.py#L59-L64 | train |
Microsoft/nni | tools/nni_cmd/updater.py | update_experiment_profile | def update_experiment_profile(args, key, value):
'''call restful server to update experiment profile'''
nni_config = Config(get_config_filename(args))
rest_port = nni_config.get_config('restServerPort')
running, _ = check_rest_server_quick(rest_port)
if running:
response = rest_get(experimen... | python | def update_experiment_profile(args, key, value):
'''call restful server to update experiment profile'''
nni_config = Config(get_config_filename(args))
rest_port = nni_config.get_config('restServerPort')
running, _ = check_rest_server_quick(rest_port)
if running:
response = rest_get(experimen... | [
"def",
"update_experiment_profile",
"(",
"args",
",",
"key",
",",
"value",
")",
":",
"nni_config",
"=",
"Config",
"(",
"get_config_filename",
"(",
"args",
")",
")",
"rest_port",
"=",
"nni_config",
".",
"get_config",
"(",
"'restServerPort'",
")",
"running",
","... | call restful server to update experiment profile | [
"call",
"restful",
"server",
"to",
"update",
"experiment",
"profile"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/updater.py#L77-L92 | train |
Microsoft/nni | tools/nni_cmd/updater.py | import_data | def import_data(args):
'''import additional data to the experiment'''
validate_file(args.filename)
validate_dispatcher(args)
content = load_search_space(args.filename)
args.port = get_experiment_port(args)
if args.port is not None:
if import_data_to_restful_server(args, content):
... | python | def import_data(args):
'''import additional data to the experiment'''
validate_file(args.filename)
validate_dispatcher(args)
content = load_search_space(args.filename)
args.port = get_experiment_port(args)
if args.port is not None:
if import_data_to_restful_server(args, content):
... | [
"def",
"import_data",
"(",
"args",
")",
":",
"validate_file",
"(",
"args",
".",
"filename",
")",
"validate_dispatcher",
"(",
"args",
")",
"content",
"=",
"load_search_space",
"(",
"args",
".",
"filename",
")",
"args",
".",
"port",
"=",
"get_experiment_port",
... | import additional data to the experiment | [
"import",
"additional",
"data",
"to",
"the",
"experiment"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/updater.py#L131-L141 | train |
Microsoft/nni | tools/nni_cmd/updater.py | import_data_to_restful_server | def import_data_to_restful_server(args, content):
'''call restful server to import data to the experiment'''
nni_config = Config(get_config_filename(args))
rest_port = nni_config.get_config('restServerPort')
running, _ = check_rest_server_quick(rest_port)
if running:
response = rest_post(imp... | python | def import_data_to_restful_server(args, content):
'''call restful server to import data to the experiment'''
nni_config = Config(get_config_filename(args))
rest_port = nni_config.get_config('restServerPort')
running, _ = check_rest_server_quick(rest_port)
if running:
response = rest_post(imp... | [
"def",
"import_data_to_restful_server",
"(",
"args",
",",
"content",
")",
":",
"nni_config",
"=",
"Config",
"(",
"get_config_filename",
"(",
"args",
")",
")",
"rest_port",
"=",
"nni_config",
".",
"get_config",
"(",
"'restServerPort'",
")",
"running",
",",
"_",
... | call restful server to import data to the experiment | [
"call",
"restful",
"server",
"to",
"import",
"data",
"to",
"the",
"experiment"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/updater.py#L143-L154 | train |
Microsoft/nni | tools/nni_cmd/config_schema.py | setType | def setType(key, type):
'''check key type'''
return And(type, error=SCHEMA_TYPE_ERROR % (key, type.__name__)) | python | def setType(key, type):
'''check key type'''
return And(type, error=SCHEMA_TYPE_ERROR % (key, type.__name__)) | [
"def",
"setType",
"(",
"key",
",",
"type",
")",
":",
"return",
"And",
"(",
"type",
",",
"error",
"=",
"SCHEMA_TYPE_ERROR",
"%",
"(",
"key",
",",
"type",
".",
"__name__",
")",
")"
] | check key type | [
"check",
"key",
"type"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/config_schema.py#L26-L28 | train |
Microsoft/nni | tools/nni_cmd/config_schema.py | setChoice | def setChoice(key, *args):
'''check choice'''
return And(lambda n: n in args, error=SCHEMA_RANGE_ERROR % (key, str(args))) | python | def setChoice(key, *args):
'''check choice'''
return And(lambda n: n in args, error=SCHEMA_RANGE_ERROR % (key, str(args))) | [
"def",
"setChoice",
"(",
"key",
",",
"*",
"args",
")",
":",
"return",
"And",
"(",
"lambda",
"n",
":",
"n",
"in",
"args",
",",
"error",
"=",
"SCHEMA_RANGE_ERROR",
"%",
"(",
"key",
",",
"str",
"(",
"args",
")",
")",
")"
] | check choice | [
"check",
"choice"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/config_schema.py#L30-L32 | train |
Microsoft/nni | tools/nni_cmd/config_schema.py | setNumberRange | def setNumberRange(key, keyType, start, end):
'''check number range'''
return And(
And(keyType, error=SCHEMA_TYPE_ERROR % (key, keyType.__name__)),
And(lambda n: start <= n <= end, error=SCHEMA_RANGE_ERROR % (key, '(%s,%s)' % (start, end))),
) | python | def setNumberRange(key, keyType, start, end):
'''check number range'''
return And(
And(keyType, error=SCHEMA_TYPE_ERROR % (key, keyType.__name__)),
And(lambda n: start <= n <= end, error=SCHEMA_RANGE_ERROR % (key, '(%s,%s)' % (start, end))),
) | [
"def",
"setNumberRange",
"(",
"key",
",",
"keyType",
",",
"start",
",",
"end",
")",
":",
"return",
"And",
"(",
"And",
"(",
"keyType",
",",
"error",
"=",
"SCHEMA_TYPE_ERROR",
"%",
"(",
"key",
",",
"keyType",
".",
"__name__",
")",
")",
",",
"And",
"(",... | check number range | [
"check",
"number",
"range"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/config_schema.py#L34-L39 | train |
Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/layers.py | keras_dropout | def keras_dropout(layer, rate):
'''keras dropout layer.
'''
from keras import layers
input_dim = len(layer.input.shape)
if input_dim == 2:
return layers.SpatialDropout1D(rate)
elif input_dim == 3:
return layers.SpatialDropout2D(rate)
elif input_dim == 4:
return laye... | python | def keras_dropout(layer, rate):
'''keras dropout layer.
'''
from keras import layers
input_dim = len(layer.input.shape)
if input_dim == 2:
return layers.SpatialDropout1D(rate)
elif input_dim == 3:
return layers.SpatialDropout2D(rate)
elif input_dim == 4:
return laye... | [
"def",
"keras_dropout",
"(",
"layer",
",",
"rate",
")",
":",
"from",
"keras",
"import",
"layers",
"input_dim",
"=",
"len",
"(",
"layer",
".",
"input",
".",
"shape",
")",
"if",
"input_dim",
"==",
"2",
":",
"return",
"layers",
".",
"SpatialDropout1D",
"(",... | keras dropout layer. | [
"keras",
"dropout",
"layer",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/layers.py#L530-L544 | train |
Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/layers.py | to_real_keras_layer | def to_real_keras_layer(layer):
''' real keras layer.
'''
from keras import layers
if is_layer(layer, "Dense"):
return layers.Dense(layer.units, input_shape=(layer.input_units,))
if is_layer(layer, "Conv"):
return layers.Conv2D(
layer.filters,
layer.kernel_si... | python | def to_real_keras_layer(layer):
''' real keras layer.
'''
from keras import layers
if is_layer(layer, "Dense"):
return layers.Dense(layer.units, input_shape=(layer.input_units,))
if is_layer(layer, "Conv"):
return layers.Conv2D(
layer.filters,
layer.kernel_si... | [
"def",
"to_real_keras_layer",
"(",
"layer",
")",
":",
"from",
"keras",
"import",
"layers",
"if",
"is_layer",
"(",
"layer",
",",
"\"Dense\"",
")",
":",
"return",
"layers",
".",
"Dense",
"(",
"layer",
".",
"units",
",",
"input_shape",
"=",
"(",
"layer",
".... | real keras layer. | [
"real",
"keras",
"layer",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/layers.py#L547-L578 | train |
Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/layers.py | is_layer | def is_layer(layer, layer_type):
'''judge the layer type.
Returns:
boolean -- True or False
'''
if layer_type == "Input":
return isinstance(layer, StubInput)
elif layer_type == "Conv":
return isinstance(layer, StubConv)
elif layer_type == "Dense":
return isinstan... | python | def is_layer(layer, layer_type):
'''judge the layer type.
Returns:
boolean -- True or False
'''
if layer_type == "Input":
return isinstance(layer, StubInput)
elif layer_type == "Conv":
return isinstance(layer, StubConv)
elif layer_type == "Dense":
return isinstan... | [
"def",
"is_layer",
"(",
"layer",
",",
"layer_type",
")",
":",
"if",
"layer_type",
"==",
"\"Input\"",
":",
"return",
"isinstance",
"(",
"layer",
",",
"StubInput",
")",
"elif",
"layer_type",
"==",
"\"Conv\"",
":",
"return",
"isinstance",
"(",
"layer",
",",
"... | judge the layer type.
Returns:
boolean -- True or False | [
"judge",
"the",
"layer",
"type",
".",
"Returns",
":",
"boolean",
"--",
"True",
"or",
"False"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/layers.py#L581-L610 | train |
Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/layers.py | layer_description_extractor | def layer_description_extractor(layer, node_to_id):
'''get layer description.
'''
layer_input = layer.input
layer_output = layer.output
if layer_input is not None:
if isinstance(layer_input, Iterable):
layer_input = list(map(lambda x: node_to_id[x], layer_input))
else:
... | python | def layer_description_extractor(layer, node_to_id):
'''get layer description.
'''
layer_input = layer.input
layer_output = layer.output
if layer_input is not None:
if isinstance(layer_input, Iterable):
layer_input = list(map(lambda x: node_to_id[x], layer_input))
else:
... | [
"def",
"layer_description_extractor",
"(",
"layer",
",",
"node_to_id",
")",
":",
"layer_input",
"=",
"layer",
".",
"input",
"layer_output",
"=",
"layer",
".",
"output",
"if",
"layer_input",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"layer_input",
",",... | get layer description. | [
"get",
"layer",
"description",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/layers.py#L613-L661 | train |
Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/layers.py | layer_description_builder | def layer_description_builder(layer_information, id_to_node):
'''build layer from description.
'''
# pylint: disable=W0123
layer_type = layer_information[0]
layer_input_ids = layer_information[1]
if isinstance(layer_input_ids, Iterable):
layer_input = list(map(lambda x: id_to_node[x], l... | python | def layer_description_builder(layer_information, id_to_node):
'''build layer from description.
'''
# pylint: disable=W0123
layer_type = layer_information[0]
layer_input_ids = layer_information[1]
if isinstance(layer_input_ids, Iterable):
layer_input = list(map(lambda x: id_to_node[x], l... | [
"def",
"layer_description_builder",
"(",
"layer_information",
",",
"id_to_node",
")",
":",
"# pylint: disable=W0123",
"layer_type",
"=",
"layer_information",
"[",
"0",
"]",
"layer_input_ids",
"=",
"layer_information",
"[",
"1",
"]",
"if",
"isinstance",
"(",
"layer_inp... | build layer from description. | [
"build",
"layer",
"from",
"description",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/layers.py#L664-L700 | train |
Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/layers.py | layer_width | def layer_width(layer):
'''get layer width.
'''
if is_layer(layer, "Dense"):
return layer.units
if is_layer(layer, "Conv"):
return layer.filters
raise TypeError("The layer should be either Dense or Conv layer.") | python | def layer_width(layer):
'''get layer width.
'''
if is_layer(layer, "Dense"):
return layer.units
if is_layer(layer, "Conv"):
return layer.filters
raise TypeError("The layer should be either Dense or Conv layer.") | [
"def",
"layer_width",
"(",
"layer",
")",
":",
"if",
"is_layer",
"(",
"layer",
",",
"\"Dense\"",
")",
":",
"return",
"layer",
".",
"units",
"if",
"is_layer",
"(",
"layer",
",",
"\"Conv\"",
")",
":",
"return",
"layer",
".",
"filters",
"raise",
"TypeError",... | get layer width. | [
"get",
"layer",
"width",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/layers.py#L703-L711 | train |
Microsoft/nni | examples/trials/weight_sharing/ga_squad/rnn.py | GRU.define_params | def define_params(self):
'''
Define parameters.
'''
input_dim = self.input_dim
hidden_dim = self.hidden_dim
prefix = self.name
self.w_matrix = tf.Variable(tf.random_normal([input_dim, 3 * hidden_dim], stddev=0.1),
name='/'.join(... | python | def define_params(self):
'''
Define parameters.
'''
input_dim = self.input_dim
hidden_dim = self.hidden_dim
prefix = self.name
self.w_matrix = tf.Variable(tf.random_normal([input_dim, 3 * hidden_dim], stddev=0.1),
name='/'.join(... | [
"def",
"define_params",
"(",
"self",
")",
":",
"input_dim",
"=",
"self",
".",
"input_dim",
"hidden_dim",
"=",
"self",
".",
"hidden_dim",
"prefix",
"=",
"self",
".",
"name",
"self",
".",
"w_matrix",
"=",
"tf",
".",
"Variable",
"(",
"tf",
".",
"random_norm... | Define parameters. | [
"Define",
"parameters",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/rnn.py#L38-L51 | train |
Microsoft/nni | examples/trials/weight_sharing/ga_squad/rnn.py | GRU.build | def build(self, x, h, mask=None):
'''
Build the GRU cell.
'''
xw = tf.split(tf.matmul(x, self.w_matrix) + self.bias, 3, 1)
hu = tf.split(tf.matmul(h, self.U), 3, 1)
r = tf.sigmoid(xw[0] + hu[0])
z = tf.sigmoid(xw[1] + hu[1])
h1 = tf.tanh(xw[2] + r * hu[2])... | python | def build(self, x, h, mask=None):
'''
Build the GRU cell.
'''
xw = tf.split(tf.matmul(x, self.w_matrix) + self.bias, 3, 1)
hu = tf.split(tf.matmul(h, self.U), 3, 1)
r = tf.sigmoid(xw[0] + hu[0])
z = tf.sigmoid(xw[1] + hu[1])
h1 = tf.tanh(xw[2] + r * hu[2])... | [
"def",
"build",
"(",
"self",
",",
"x",
",",
"h",
",",
"mask",
"=",
"None",
")",
":",
"xw",
"=",
"tf",
".",
"split",
"(",
"tf",
".",
"matmul",
"(",
"x",
",",
"self",
".",
"w_matrix",
")",
"+",
"self",
".",
"bias",
",",
"3",
",",
"1",
")",
... | Build the GRU cell. | [
"Build",
"the",
"GRU",
"cell",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/rnn.py#L53-L65 | train |
Microsoft/nni | examples/trials/weight_sharing/ga_squad/rnn.py | GRU.build_sequence | def build_sequence(self, xs, masks, init, is_left_to_right):
'''
Build GRU sequence.
'''
states = []
last = init
if is_left_to_right:
for i, xs_i in enumerate(xs):
h = self.build(xs_i, last, masks[i])
states.append(h)
... | python | def build_sequence(self, xs, masks, init, is_left_to_right):
'''
Build GRU sequence.
'''
states = []
last = init
if is_left_to_right:
for i, xs_i in enumerate(xs):
h = self.build(xs_i, last, masks[i])
states.append(h)
... | [
"def",
"build_sequence",
"(",
"self",
",",
"xs",
",",
"masks",
",",
"init",
",",
"is_left_to_right",
")",
":",
"states",
"=",
"[",
"]",
"last",
"=",
"init",
"if",
"is_left_to_right",
":",
"for",
"i",
",",
"xs_i",
"in",
"enumerate",
"(",
"xs",
")",
":... | Build GRU sequence. | [
"Build",
"GRU",
"sequence",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/rnn.py#L67-L83 | train |
Microsoft/nni | tools/nni_annotation/examples/mnist_without_annotation.py | conv2d | def conv2d(x_input, w_matrix):
"""conv2d returns a 2d convolution layer with full stride."""
return tf.nn.conv2d(x_input, w_matrix, strides=[1, 1, 1, 1], padding='SAME') | python | def conv2d(x_input, w_matrix):
"""conv2d returns a 2d convolution layer with full stride."""
return tf.nn.conv2d(x_input, w_matrix, strides=[1, 1, 1, 1], padding='SAME') | [
"def",
"conv2d",
"(",
"x_input",
",",
"w_matrix",
")",
":",
"return",
"tf",
".",
"nn",
".",
"conv2d",
"(",
"x_input",
",",
"w_matrix",
",",
"strides",
"=",
"[",
"1",
",",
"1",
",",
"1",
",",
"1",
"]",
",",
"padding",
"=",
"'SAME'",
")"
] | conv2d returns a 2d convolution layer with full stride. | [
"conv2d",
"returns",
"a",
"2d",
"convolution",
"layer",
"with",
"full",
"stride",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_annotation/examples/mnist_without_annotation.py#L149-L151 | train |
Microsoft/nni | tools/nni_annotation/examples/mnist_without_annotation.py | max_pool | def max_pool(x_input, pool_size):
"""max_pool downsamples a feature map by 2X."""
return tf.nn.max_pool(x_input, ksize=[1, pool_size, pool_size, 1],
strides=[1, pool_size, pool_size, 1], padding='SAME') | python | def max_pool(x_input, pool_size):
"""max_pool downsamples a feature map by 2X."""
return tf.nn.max_pool(x_input, ksize=[1, pool_size, pool_size, 1],
strides=[1, pool_size, pool_size, 1], padding='SAME') | [
"def",
"max_pool",
"(",
"x_input",
",",
"pool_size",
")",
":",
"return",
"tf",
".",
"nn",
".",
"max_pool",
"(",
"x_input",
",",
"ksize",
"=",
"[",
"1",
",",
"pool_size",
",",
"pool_size",
",",
"1",
"]",
",",
"strides",
"=",
"[",
"1",
",",
"pool_siz... | max_pool downsamples a feature map by 2X. | [
"max_pool",
"downsamples",
"a",
"feature",
"map",
"by",
"2X",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_annotation/examples/mnist_without_annotation.py#L154-L157 | train |
Microsoft/nni | tools/nni_annotation/examples/mnist_without_annotation.py | main | def main(params):
'''
Main function, build mnist network, run and send result to NNI.
'''
# Import data
mnist = download_mnist_retry(params['data_dir'])
print('Mnist download data done.')
logger.debug('Mnist download data done.')
# Create the model
# Build the graph for the deep net... | python | def main(params):
'''
Main function, build mnist network, run and send result to NNI.
'''
# Import data
mnist = download_mnist_retry(params['data_dir'])
print('Mnist download data done.')
logger.debug('Mnist download data done.')
# Create the model
# Build the graph for the deep net... | [
"def",
"main",
"(",
"params",
")",
":",
"# Import data",
"mnist",
"=",
"download_mnist_retry",
"(",
"params",
"[",
"'data_dir'",
"]",
")",
"print",
"(",
"'Mnist download data done.'",
")",
"logger",
".",
"debug",
"(",
"'Mnist download data done.'",
")",
"# Create ... | Main function, build mnist network, run and send result to NNI. | [
"Main",
"function",
"build",
"mnist",
"network",
"run",
"and",
"send",
"result",
"to",
"NNI",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_annotation/examples/mnist_without_annotation.py#L185-L237 | train |
Microsoft/nni | examples/trials/ga_squad/train_model.py | GAG.build_net | def build_net(self, is_training):
"""Build the whole neural network for the QA model."""
cfg = self.cfg
with tf.device('/cpu:0'):
word_embed = tf.get_variable(
name='word_embed', initializer=self.embed, dtype=tf.float32, trainable=False)
char_embed = tf.ge... | python | def build_net(self, is_training):
"""Build the whole neural network for the QA model."""
cfg = self.cfg
with tf.device('/cpu:0'):
word_embed = tf.get_variable(
name='word_embed', initializer=self.embed, dtype=tf.float32, trainable=False)
char_embed = tf.ge... | [
"def",
"build_net",
"(",
"self",
",",
"is_training",
")",
":",
"cfg",
"=",
"self",
".",
"cfg",
"with",
"tf",
".",
"device",
"(",
"'/cpu:0'",
")",
":",
"word_embed",
"=",
"tf",
".",
"get_variable",
"(",
"name",
"=",
"'word_embed'",
",",
"initializer",
"... | Build the whole neural network for the QA model. | [
"Build",
"the",
"whole",
"neural",
"network",
"for",
"the",
"QA",
"model",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/ga_squad/train_model.py#L87-L233 | train |
Microsoft/nni | tools/nni_cmd/command_utils.py | check_output_command | def check_output_command(file_path, head=None, tail=None):
'''call check_output command to read content from a file'''
if os.path.exists(file_path):
if sys.platform == 'win32':
cmds = ['powershell.exe', 'type', file_path]
if head:
cmds += ['|', 'select', '-first',... | python | def check_output_command(file_path, head=None, tail=None):
'''call check_output command to read content from a file'''
if os.path.exists(file_path):
if sys.platform == 'win32':
cmds = ['powershell.exe', 'type', file_path]
if head:
cmds += ['|', 'select', '-first',... | [
"def",
"check_output_command",
"(",
"file_path",
",",
"head",
"=",
"None",
",",
"tail",
"=",
"None",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"file_path",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"cmds",
"=",
"[",
... | call check_output command to read content from a file | [
"call",
"check_output",
"command",
"to",
"read",
"content",
"from",
"a",
"file"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/command_utils.py#L8-L27 | train |
Microsoft/nni | tools/nni_cmd/command_utils.py | kill_command | def kill_command(pid):
'''kill command'''
if sys.platform == 'win32':
process = psutil.Process(pid=pid)
process.send_signal(signal.CTRL_BREAK_EVENT)
else:
cmds = ['kill', str(pid)]
call(cmds) | python | def kill_command(pid):
'''kill command'''
if sys.platform == 'win32':
process = psutil.Process(pid=pid)
process.send_signal(signal.CTRL_BREAK_EVENT)
else:
cmds = ['kill', str(pid)]
call(cmds) | [
"def",
"kill_command",
"(",
"pid",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"process",
"=",
"psutil",
".",
"Process",
"(",
"pid",
"=",
"pid",
")",
"process",
".",
"send_signal",
"(",
"signal",
".",
"CTRL_BREAK_EVENT",
")",
"else",
... | kill command | [
"kill",
"command"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/command_utils.py#L29-L36 | train |
Microsoft/nni | tools/nni_cmd/command_utils.py | install_package_command | def install_package_command(package_name):
'''install python package from pip'''
#TODO refactor python logic
if sys.platform == "win32":
cmds = 'python -m pip install --user {0}'.format(package_name)
else:
cmds = 'python3 -m pip install --user {0}'.format(package_name)
call(cmds, she... | python | def install_package_command(package_name):
'''install python package from pip'''
#TODO refactor python logic
if sys.platform == "win32":
cmds = 'python -m pip install --user {0}'.format(package_name)
else:
cmds = 'python3 -m pip install --user {0}'.format(package_name)
call(cmds, she... | [
"def",
"install_package_command",
"(",
"package_name",
")",
":",
"#TODO refactor python logic",
"if",
"sys",
".",
"platform",
"==",
"\"win32\"",
":",
"cmds",
"=",
"'python -m pip install --user {0}'",
".",
"format",
"(",
"package_name",
")",
"else",
":",
"cmds",
"="... | install python package from pip | [
"install",
"python",
"package",
"from",
"pip"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/command_utils.py#L38-L45 | train |
Microsoft/nni | tools/nni_cmd/command_utils.py | install_requirements_command | def install_requirements_command(requirements_path):
'''install requirements.txt'''
cmds = 'cd ' + requirements_path + ' && {0} -m pip install --user -r requirements.txt'
#TODO refactor python logic
if sys.platform == "win32":
cmds = cmds.format('python')
else:
cmds = cmds.format('py... | python | def install_requirements_command(requirements_path):
'''install requirements.txt'''
cmds = 'cd ' + requirements_path + ' && {0} -m pip install --user -r requirements.txt'
#TODO refactor python logic
if sys.platform == "win32":
cmds = cmds.format('python')
else:
cmds = cmds.format('py... | [
"def",
"install_requirements_command",
"(",
"requirements_path",
")",
":",
"cmds",
"=",
"'cd '",
"+",
"requirements_path",
"+",
"' && {0} -m pip install --user -r requirements.txt'",
"#TODO refactor python logic",
"if",
"sys",
".",
"platform",
"==",
"\"win32\"",
":",
"cmds"... | install requirements.txt | [
"install",
"requirements",
".",
"txt"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/command_utils.py#L47-L55 | train |
Microsoft/nni | examples/trials/mnist-advisor/mnist.py | get_params | def get_params():
''' Get parameters from command line '''
parser = argparse.ArgumentParser()
parser.add_argument("--data_dir", type=str, default='/tmp/tensorflow/mnist/input_data', help="data directory")
parser.add_argument("--dropout_rate", type=float, default=0.5, help="dropout rate")
parser.add_... | python | def get_params():
''' Get parameters from command line '''
parser = argparse.ArgumentParser()
parser.add_argument("--data_dir", type=str, default='/tmp/tensorflow/mnist/input_data', help="data directory")
parser.add_argument("--dropout_rate", type=float, default=0.5, help="dropout rate")
parser.add_... | [
"def",
"get_params",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"\"--data_dir\"",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'/tmp/tensorflow/mnist/input_data'",
",",
"help",
"=",
"\"data ... | Get parameters from command line | [
"Get",
"parameters",
"from",
"command",
"line"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/mnist-advisor/mnist.py#L211-L226 | train |
Microsoft/nni | examples/trials/mnist-advisor/mnist.py | MnistNetwork.build_network | def build_network(self):
'''
Building network for mnist
'''
# Reshape to use within a convolutional neural net.
# Last dimension is for "features" - there is only one here, since images are
# grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc.
with tf.n... | python | def build_network(self):
'''
Building network for mnist
'''
# Reshape to use within a convolutional neural net.
# Last dimension is for "features" - there is only one here, since images are
# grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc.
with tf.n... | [
"def",
"build_network",
"(",
"self",
")",
":",
"# Reshape to use within a convolutional neural net.",
"# Last dimension is for \"features\" - there is only one here, since images are",
"# grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc.",
"with",
"tf",
".",
"name_scope",
"(",
... | Building network for mnist | [
"Building",
"network",
"for",
"mnist"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/mnist-advisor/mnist.py#L48-L122 | train |
Microsoft/nni | tools/nni_cmd/nnictl_utils.py | get_experiment_time | def get_experiment_time(port):
'''get the startTime and endTime of an experiment'''
response = rest_get(experiment_url(port), REST_TIME_OUT)
if response and check_response(response):
content = convert_time_stamp_to_date(json.loads(response.text))
return content.get('startTime'), content.get(... | python | def get_experiment_time(port):
'''get the startTime and endTime of an experiment'''
response = rest_get(experiment_url(port), REST_TIME_OUT)
if response and check_response(response):
content = convert_time_stamp_to_date(json.loads(response.text))
return content.get('startTime'), content.get(... | [
"def",
"get_experiment_time",
"(",
"port",
")",
":",
"response",
"=",
"rest_get",
"(",
"experiment_url",
"(",
"port",
")",
",",
"REST_TIME_OUT",
")",
"if",
"response",
"and",
"check_response",
"(",
"response",
")",
":",
"content",
"=",
"convert_time_stamp_to_dat... | get the startTime and endTime of an experiment | [
"get",
"the",
"startTime",
"and",
"endTime",
"of",
"an",
"experiment"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L36-L42 | train |
Microsoft/nni | tools/nni_cmd/nnictl_utils.py | get_experiment_status | def get_experiment_status(port):
'''get the status of an experiment'''
result, response = check_rest_server_quick(port)
if result:
return json.loads(response.text).get('status')
return None | python | def get_experiment_status(port):
'''get the status of an experiment'''
result, response = check_rest_server_quick(port)
if result:
return json.loads(response.text).get('status')
return None | [
"def",
"get_experiment_status",
"(",
"port",
")",
":",
"result",
",",
"response",
"=",
"check_rest_server_quick",
"(",
"port",
")",
"if",
"result",
":",
"return",
"json",
".",
"loads",
"(",
"response",
".",
"text",
")",
".",
"get",
"(",
"'status'",
")",
... | get the status of an experiment | [
"get",
"the",
"status",
"of",
"an",
"experiment"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L44-L49 | train |
Microsoft/nni | tools/nni_cmd/nnictl_utils.py | update_experiment | def update_experiment():
'''Update the experiment status in config file'''
experiment_config = Experiments()
experiment_dict = experiment_config.get_all_experiments()
if not experiment_dict:
return None
for key in experiment_dict.keys():
if isinstance(experiment_dict[key], dict):
... | python | def update_experiment():
'''Update the experiment status in config file'''
experiment_config = Experiments()
experiment_dict = experiment_config.get_all_experiments()
if not experiment_dict:
return None
for key in experiment_dict.keys():
if isinstance(experiment_dict[key], dict):
... | [
"def",
"update_experiment",
"(",
")",
":",
"experiment_config",
"=",
"Experiments",
"(",
")",
"experiment_dict",
"=",
"experiment_config",
".",
"get_all_experiments",
"(",
")",
"if",
"not",
"experiment_dict",
":",
"return",
"None",
"for",
"key",
"in",
"experiment_... | Update the experiment status in config file | [
"Update",
"the",
"experiment",
"status",
"in",
"config",
"file"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L51-L73 | train |
Microsoft/nni | tools/nni_cmd/nnictl_utils.py | check_experiment_id | def check_experiment_id(args):
'''check if the id is valid
'''
update_experiment()
experiment_config = Experiments()
experiment_dict = experiment_config.get_all_experiments()
if not experiment_dict:
print_normal('There is no experiment running...')
return None
if not args.id:... | python | def check_experiment_id(args):
'''check if the id is valid
'''
update_experiment()
experiment_config = Experiments()
experiment_dict = experiment_config.get_all_experiments()
if not experiment_dict:
print_normal('There is no experiment running...')
return None
if not args.id:... | [
"def",
"check_experiment_id",
"(",
"args",
")",
":",
"update_experiment",
"(",
")",
"experiment_config",
"=",
"Experiments",
"(",
")",
"experiment_dict",
"=",
"experiment_config",
".",
"get_all_experiments",
"(",
")",
"if",
"not",
"experiment_dict",
":",
"print_norm... | check if the id is valid | [
"check",
"if",
"the",
"id",
"is",
"valid"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L75-L110 | train |
Microsoft/nni | tools/nni_cmd/nnictl_utils.py | parse_ids | def parse_ids(args):
'''Parse the arguments for nnictl stop
1.If there is an id specified, return the corresponding id
2.If there is no id specified, and there is an experiment running, return the id, or return Error
3.If the id matches an experiment, nnictl will return the id.
4.If the id ends with... | python | def parse_ids(args):
'''Parse the arguments for nnictl stop
1.If there is an id specified, return the corresponding id
2.If there is no id specified, and there is an experiment running, return the id, or return Error
3.If the id matches an experiment, nnictl will return the id.
4.If the id ends with... | [
"def",
"parse_ids",
"(",
"args",
")",
":",
"update_experiment",
"(",
")",
"experiment_config",
"=",
"Experiments",
"(",
")",
"experiment_dict",
"=",
"experiment_config",
".",
"get_all_experiments",
"(",
")",
"if",
"not",
"experiment_dict",
":",
"print_normal",
"("... | Parse the arguments for nnictl stop
1.If there is an id specified, return the corresponding id
2.If there is no id specified, and there is an experiment running, return the id, or return Error
3.If the id matches an experiment, nnictl will return the id.
4.If the id ends with *, nnictl will match all id... | [
"Parse",
"the",
"arguments",
"for",
"nnictl",
"stop",
"1",
".",
"If",
"there",
"is",
"an",
"id",
"specified",
"return",
"the",
"corresponding",
"id",
"2",
".",
"If",
"there",
"is",
"no",
"id",
"specified",
"and",
"there",
"is",
"an",
"experiment",
"runni... | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L112-L166 | train |
Microsoft/nni | tools/nni_cmd/nnictl_utils.py | get_config_filename | def get_config_filename(args):
'''get the file name of config file'''
experiment_id = check_experiment_id(args)
if experiment_id is None:
print_error('Please set the experiment id!')
exit(1)
experiment_config = Experiments()
experiment_dict = experiment_config.get_all_experiments()
... | python | def get_config_filename(args):
'''get the file name of config file'''
experiment_id = check_experiment_id(args)
if experiment_id is None:
print_error('Please set the experiment id!')
exit(1)
experiment_config = Experiments()
experiment_dict = experiment_config.get_all_experiments()
... | [
"def",
"get_config_filename",
"(",
"args",
")",
":",
"experiment_id",
"=",
"check_experiment_id",
"(",
"args",
")",
"if",
"experiment_id",
"is",
"None",
":",
"print_error",
"(",
"'Please set the experiment id!'",
")",
"exit",
"(",
"1",
")",
"experiment_config",
"=... | get the file name of config file | [
"get",
"the",
"file",
"name",
"of",
"config",
"file"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L168-L176 | train |
Microsoft/nni | tools/nni_cmd/nnictl_utils.py | convert_time_stamp_to_date | def convert_time_stamp_to_date(content):
'''Convert time stamp to date time format'''
start_time_stamp = content.get('startTime')
end_time_stamp = content.get('endTime')
if start_time_stamp:
start_time = datetime.datetime.utcfromtimestamp(start_time_stamp // 1000).strftime("%Y/%m/%d %H:%M:%S")
... | python | def convert_time_stamp_to_date(content):
'''Convert time stamp to date time format'''
start_time_stamp = content.get('startTime')
end_time_stamp = content.get('endTime')
if start_time_stamp:
start_time = datetime.datetime.utcfromtimestamp(start_time_stamp // 1000).strftime("%Y/%m/%d %H:%M:%S")
... | [
"def",
"convert_time_stamp_to_date",
"(",
"content",
")",
":",
"start_time_stamp",
"=",
"content",
".",
"get",
"(",
"'startTime'",
")",
"end_time_stamp",
"=",
"content",
".",
"get",
"(",
"'endTime'",
")",
"if",
"start_time_stamp",
":",
"start_time",
"=",
"dateti... | Convert time stamp to date time format | [
"Convert",
"time",
"stamp",
"to",
"date",
"time",
"format"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L188-L198 | train |
Microsoft/nni | tools/nni_cmd/nnictl_utils.py | check_rest | def check_rest(args):
'''check if restful server is running'''
nni_config = Config(get_config_filename(args))
rest_port = nni_config.get_config('restServerPort')
running, _ = check_rest_server_quick(rest_port)
if not running:
print_normal('Restful server is running...')
else:
pri... | python | def check_rest(args):
'''check if restful server is running'''
nni_config = Config(get_config_filename(args))
rest_port = nni_config.get_config('restServerPort')
running, _ = check_rest_server_quick(rest_port)
if not running:
print_normal('Restful server is running...')
else:
pri... | [
"def",
"check_rest",
"(",
"args",
")",
":",
"nni_config",
"=",
"Config",
"(",
"get_config_filename",
"(",
"args",
")",
")",
"rest_port",
"=",
"nni_config",
".",
"get_config",
"(",
"'restServerPort'",
")",
"running",
",",
"_",
"=",
"check_rest_server_quick",
"(... | check if restful server is running | [
"check",
"if",
"restful",
"server",
"is",
"running"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L200-L208 | train |
Microsoft/nni | tools/nni_cmd/nnictl_utils.py | stop_experiment | def stop_experiment(args):
'''Stop the experiment which is running'''
experiment_id_list = parse_ids(args)
if experiment_id_list:
experiment_config = Experiments()
experiment_dict = experiment_config.get_all_experiments()
for experiment_id in experiment_id_list:
print_nor... | python | def stop_experiment(args):
'''Stop the experiment which is running'''
experiment_id_list = parse_ids(args)
if experiment_id_list:
experiment_config = Experiments()
experiment_dict = experiment_config.get_all_experiments()
for experiment_id in experiment_id_list:
print_nor... | [
"def",
"stop_experiment",
"(",
"args",
")",
":",
"experiment_id_list",
"=",
"parse_ids",
"(",
"args",
")",
"if",
"experiment_id_list",
":",
"experiment_config",
"=",
"Experiments",
"(",
")",
"experiment_dict",
"=",
"experiment_config",
".",
"get_all_experiments",
"(... | Stop the experiment which is running | [
"Stop",
"the",
"experiment",
"which",
"is",
"running"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L210-L234 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.