Skip to content
This repository has been archived by the owner on Sep 18, 2024. It is now read-only.

Add nnictl ut #2912

Merged
merged 42 commits into from
Sep 28, 2020
Merged
Show file tree
Hide file tree
Changes from 38 commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
dcd2ffd
Merge pull request #251 from microsoft/master
SparkSnail May 29, 2020
3b8b6fb
Merge pull request #252 from microsoft/master
SparkSnail Jun 7, 2020
916e444
Merge pull request #253 from microsoft/master
SparkSnail Jun 15, 2020
caeffb8
Merge pull request #254 from microsoft/master
SparkSnail Jun 17, 2020
57c300e
Merge pull request #255 from microsoft/master
SparkSnail Jun 28, 2020
65660e6
Merge pull request #257 from microsoft/master
SparkSnail Jun 30, 2020
9376d6a
Merge pull request #258 from microsoft/master
SparkSnail Jul 1, 2020
5fef3cf
Merge pull request #259 from microsoft/master
SparkSnail Jul 3, 2020
5544ae8
Merge pull request #261 from microsoft/master
SparkSnail Jul 10, 2020
f9fdfee
Merge pull request #262 from microsoft/master
SparkSnail Jul 16, 2020
c5e26ef
add trial job detail link
SparkSnail Jul 19, 2020
10a04ba
Merge branch 'master' of https://github.com/SparkSnail/nni
SparkSnail Jul 23, 2020
aa64fe6
Merge pull request #263 from microsoft/master
SparkSnail Jul 27, 2020
4ed907f
Merge branch 'master' of https://github.com/SparkSnail/nni
SparkSnail Jul 27, 2020
c6a5f8c
Merge pull request #264 from microsoft/master
SparkSnail Jul 31, 2020
68abe2f
Merge pull request #265 from microsoft/master
SparkSnail Aug 4, 2020
c2b50d2
Merge branch 'master' of https://github.com/SparkSnail/nni
SparkSnail Aug 6, 2020
14e9619
Merge pull request #266 from microsoft/master
SparkSnail Aug 13, 2020
f69e206
Merge pull request #267 from microsoft/master
SparkSnail Aug 13, 2020
a5bb753
Merge branch 'master' of https://github.com/SparkSnail/nni
SparkSnail Aug 21, 2020
12ef0aa
Merge pull request #270 from microsoft/master
SparkSnail Sep 10, 2020
7600a0f
Merge branch 'master' of https://github.com/SparkSnail/nni
SparkSnail Sep 10, 2020
ddcf229
Merge pull request #271 from microsoft/master
SparkSnail Sep 15, 2020
bd327d4
Merge branch 'master' of https://github.com/SparkSnail/nni
SparkSnail Sep 15, 2020
4cbe98d
add nnictl ut
SparkSnail Sep 21, 2020
c4f6e66
Merge pull request #272 from microsoft/master
SparkSnail Sep 21, 2020
c5df4a9
remove unused code
SparkSnail Sep 21, 2020
c42d2cf
remove unsued code
SparkSnail Sep 21, 2020
ba6a531
Merge branch 'master' of https://github.com/SparkSnail/nni into dev-n…
SparkSnail Sep 21, 2020
c9a4ba5
add more test cases
SparkSnail Sep 21, 2020
4dd55e9
fix comments
SparkSnail Sep 21, 2020
b03ef78
fix build
SparkSnail Sep 21, 2020
c86736f
fix file path
SparkSnail Sep 21, 2020
35b4cb8
remove coef
SparkSnail Sep 21, 2020
6218fda
debug file path
SparkSnail Sep 21, 2020
cf4fda8
fix file path
SparkSnail Sep 21, 2020
cbdded8
remove unused print
SparkSnail Sep 21, 2020
537741c
fix build
SparkSnail Sep 21, 2020
77eb7ea
fix comments
SparkSnail Sep 25, 2020
2348ecf
remove unused import
SparkSnail Sep 25, 2020
09d38a2
fix buidl
SparkSnail Sep 25, 2020
465e8ad
fix comments
SparkSnail Sep 28, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions deployment/pypi/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
'ruamel.yaml',
'psutil',
'requests',
'responses',
'astor',
'PythonWebHDFS',
'hyperopt==0.1.2',
Expand Down
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ def read(fname):
'psutil',
'ruamel.yaml',
'requests',
'responses',
'scipy',
'schema',
'PythonWebHDFS',
Expand Down
10 changes: 5 additions & 5 deletions tools/nni_cmd/config_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@

class Config:
'''a util class to load and save config'''
def __init__(self, file_path):
config_path = os.path.join(NNICTL_HOME_DIR, str(file_path))
def __init__(self, file_path, home_dir = NNICTL_HOME_DIR):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

better to remove spaces around = for default values.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updated, seems pylint didn't check this

config_path = os.path.join(home_dir, str(file_path))
os.makedirs(config_path, exist_ok=True)
self.config_file = os.path.join(config_path, '.config')
self.config = self.read_file()
Expand Down Expand Up @@ -51,9 +51,9 @@ def read_file(self):

class Experiments:
'''Maintain experiment list'''
def __init__(self):
os.makedirs(NNICTL_HOME_DIR, exist_ok=True)
self.experiment_file = os.path.join(NNICTL_HOME_DIR, '.experiment')
def __init__(self, home_dir = NNICTL_HOME_DIR):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove spaces around =

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updated

os.makedirs(home_dir, exist_ok=True)
self.experiment_file = os.path.join(home_dir, '.experiment')
self.experiments = self.read_file()

def add_experiment(self, expId, port, startTime, file_name, platform, experiment_name, endTime='N/A', status='INITIALIZED'):
Expand Down
11 changes: 10 additions & 1 deletion tools/nni_cmd/nnictl_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,10 +213,11 @@ def check_rest(args):
nni_config = Config(get_config_filename(args))
rest_port = nni_config.get_config('restServerPort')
running, _ = check_rest_server_quick(rest_port)
if not running:
if running:
print_normal('Restful server is running...')
else:
print_normal('Restful server is not running...')
return running

def stop_experiment(args):
'''Stop the experiment which is running'''
Expand Down Expand Up @@ -284,10 +285,12 @@ def final_metric_data_cmp(lhs, rhs):
for index, value in enumerate(content):
content[index] = convert_time_stamp_to_date(value)
print(json.dumps(content, indent=4, sort_keys=True, separators=(',', ':')))
return content
else:
print_error('List trial failed...')
else:
print_error('Restful server is not running...')
return None

def trial_kill(args):
'''List trial'''
Expand All @@ -302,10 +305,12 @@ def trial_kill(args):
response = rest_delete(trial_job_id_url(rest_port, args.trial_id), REST_TIME_OUT)
if response and check_response(response):
print(response.text)
return True
else:
print_error('Kill trial job failed...')
else:
print_error('Restful server is not running...')
return False

def trial_codegen(args):
'''Generate code for a specific trial'''
Expand All @@ -332,10 +337,12 @@ def list_experiment(args):
if response and check_response(response):
content = convert_time_stamp_to_date(json.loads(response.text))
print(json.dumps(content, indent=4, sort_keys=True, separators=(',', ':')))
return content
else:
print_error('List experiment failed...')
else:
print_error('Restful server is not running...')
return None

def experiment_status(args):
'''Show the status of experiment'''
Expand All @@ -346,6 +353,7 @@ def experiment_status(args):
print_normal('Restful server is not running...')
else:
print(json.dumps(json.loads(response.text), indent=4, sort_keys=True, separators=(',', ':')))
return result

def log_internal(args, filetype):
'''internal function to call get_log_content'''
Expand Down Expand Up @@ -618,6 +626,7 @@ def experiment_list(args):
experiment_dict[key]['startTime'],
experiment_dict[key]['endTime'])
print(EXPERIMENT_INFORMATION_FORMAT % experiment_information)
return experiment_id_list

def get_time_interval(time1, time2):
'''get the interval of two times'''
Expand Down
1 change: 1 addition & 0 deletions tools/nni_cmd/tests/config_files/test_files/test_json.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"field":"test"}
chicm-ms marked this conversation as resolved.
Show resolved Hide resolved
1 change: 1 addition & 0 deletions tools/nni_cmd/tests/config_files/test_files/test_yaml.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
field: test
47 changes: 47 additions & 0 deletions tools/nni_cmd/tests/mock/experiment.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

import os
import argparse
from subprocess import Popen, call, check_call, CalledProcessError, PIPE, STDOUT
from nni_cmd.config_utils import Config, Experiments
from nni_cmd.common_utils import detect_process, print_green
from nni_cmd.command_utils import kill_command
from nni_cmd.nnictl_utils import get_yml_content
import json

def create_mock_experiment():
nnictl_experiment_config = Experiments()
nnictl_experiment_config.add_experiment('xOpEwA5w', '8080', '1970/01/1 01:01:01', 'aGew0x',
'local', 'example_sklearn-classification')
nni_config = Config('aGew0x')
# mock process
cmds = ['sleep', '3600000']
process = Popen(cmds, stdout=PIPE, stderr=STDOUT)
nni_config.set_config('restServerPid', process.pid)
nni_config.set_config('experimentId', 'xOpEwA5w')
nni_config.set_config('restServerPort', 8080)
nni_config.set_config('webuiUrl', ['http://localhost:8080'])
experiment_config = get_yml_content('./tests/config_files/valid/test.yml')
nni_config.set_config('experimentConfig', experiment_config)
print_green("expriment start success, experiment id: xOpEwA5w")

def stop_mock_experiment():
config = Config('config')
kill_command(config.get_config('restServerPid'))
nnictl_experiment_config = Experiments()
nnictl_experiment_config.remove_experiment('xOpEwA5w')

def generate_args_parser():
parser = argparse.ArgumentParser()
parser.add_argument('id', nargs='?')
parser.add_argument('--port', '-p', dest='port')
parser.add_argument('--all', '-a', action='store_true')
parser.add_argument('--head', type=int)
parser.add_argument('--tail', type=int)
return parser

def generate_args():
parser = generate_args_parser()
args = parser.parse_args(['xOpEwA5w'])
return args
1 change: 1 addition & 0 deletions tools/nni_cmd/tests/mock/nnictl_metadata/.experiment
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"xOpEwA5w": {"port": 8080, "startTime": "1970/01/1 01:01:01", "endTime": "1970-01-2 01:01:01", "status": "RUNNING", "fileName": "aGew0x", "platform": "local", "experimentName": "example_sklearn-classification"}}
chicm-ms marked this conversation as resolved.
Show resolved Hide resolved
1 change: 1 addition & 0 deletions tools/nni_cmd/tests/mock/nnictl_metadata/aGew0x/.config
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"experimentConfig": {"authorName": "default", "experimentName": "example_sklearn-classification", "trialConcurrency": 5, "maxExecDuration": 3600, "maxTrialNum": 100, "trainingServicePlatform": "local", "searchSpacePath": "../../../config_files/valid/search_space.json", "useAnnotation": false, "tuner": {"builtinTunerName": "TPE", "classArgs": {"optimize_mode": "maximize"}}, "trial": {"command": "python3 main.py", "codeDir": "../../../config_files/valid/.", "gpuNum": 0}}, "restServerPort": 8080, "restServerPid": 7952, "experimentId": "xOpEwA5w", "webuiUrl": ["http://localhost:8080"]}
1 change: 1 addition & 0 deletions tools/nni_cmd/tests/mock/nnictl_metadata/aGew0x/stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
stderr
1 change: 1 addition & 0 deletions tools/nni_cmd/tests/mock/nnictl_metadata/aGew0x/stdout
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
stdout
1 change: 1 addition & 0 deletions tools/nni_cmd/tests/mock/nnictl_metadata/config/.config
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"experimentId": "xOpEwA5w"}
186 changes: 186 additions & 0 deletions tools/nni_cmd/tests/mock/restful_server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

import responses

def mock_check_status():
responses.add(
responses.GET,
"http://localhost:8080/api/v1/nni/check-status",
json={"status":"RUNNING","errors":[]},
status=200
)

def mock_version():
responses.add(
responses.GET,
"http://localhost:8080/api/v1/nni/version",
json={'value':1.8},
status=200
)

def mock_get_experiment_profile():
responses.add(
responses.GET,
"http://localhost:8080/api/v1/nni/experiment",
json={"id":"bkfhOdUl","revision":5,"execDuration":10,"logDir":"/home/shinyang/nni-experiments/bkfhOdUl",
"nextSequenceId":2,"params":{"authorName":"default","experimentName":"example_sklearn-classification",
"trialConcurrency":1,"maxExecDuration":3600,"maxTrialNum":1,
"searchSpace":"{\"C\": {\"_type\": \"uniform\", \"_value\": [0.1, 1]}, \
\"kernel\": {\"_type\": \"choice\", \"_value\": [\"linear\", \"rbf\", \"poly\", \"sigmoid\"]}, \
\"degree\": {\"_type\": \"choice\", \"_value\": [1, 2, 3, 4]}, \"gamma\": {\"_type\": \"uniform\", \
\"_value\": [0.01, 0.1]}}", \
"trainingServicePlatform":"local","tuner":{"builtinTunerName":"TPE","classArgs":{"optimize_mode":"maximize"}, \
"checkpointDir":"/home/shinyang/nni-experiments/bkfhOdUl/checkpoint"},"versionCheck":"true", \
"clusterMetaData":[{"key":"codeDir","value":"/home/shinyang/folder/examples/trials/sklearn/classification/."}, \
{"key":"command","value":"python3 main.py"}]},"startTime":1600326895536,"endTime":1600326910605},
status=200
)

def mock_update_experiment_profile():
responses.add(
responses.PUT, 'http://localhost:8080/api/v1/nni/experiment',
json={"status":"RUNNING","errors":[]},
status=200,
content_type='application/json',
)

def mock_import_data():
responses.add(
responses.POST, 'http://localhost:8080/api/v1/nni/experiment/import-data',
json={"result":"data"},
status=200,
chicm-ms marked this conversation as resolved.
Show resolved Hide resolved
content_type='application/json',
)

def mock_start_experiment():
responses.add(
responses.POST, 'http://localhost:8080/api/v1/nni/experiment',
json={"status":"RUNNING","errors":[]},
status=200,
content_type='application/json',
)

def mock_get_trial_job_statistics():
responses.add(
responses.GET, 'http://localhost:8080/api/v1/nni/job-statistics',
json=[{"trialJobStatus":"SUCCEEDED","trialJobNumber":1}],
status=200,
content_type='application/json',
)

def mock_set_cluster_metadata():
responses.add(
responses.PUT, 'http://localhost:8080/api/v1/nni/experiment/cluster-metadata',
json=[{"trialJobStatus":"SUCCEEDED","trialJobNumber":1}],
status=200,
content_type='application/json',
)

def mock_list_trial_jobs():
responses.add(
responses.GET, 'http://localhost:8080/api/v1/nni/trial-jobs',
json=[{"id":"GPInz","status":"SUCCEEDED","hyperParameters":["{\"parameter_id\":0, \
\"parameter_source\":\"algorithm\",\"parameters\":{\"C\":0.8748364659110364, \
\"kernel\":\"linear\",\"degree\":1,\"gamma\":0.040451413392113666}, \
\"parameter_index\":0}"],"logPath":"file://localhost:/home/shinyang/nni-experiments/bkfhOdUl/trials/GPInz",
"startTime":1600326905581,"sequenceId":0,"endTime":1600326906629,
"finalMetricData":[{"timestamp":1600326906493,"trialJobId":"GPInz","parameterId":"0",
"type":"FINAL","sequence":0,"data":"\"0.9866666666666667\""}]}],
status=200,
content_type='application/json',
)

def mock_get_trial_job():
responses.add(
responses.GET, 'http://localhost:8080/api/v1/nni/trial-jobs/:id',
json={"id":"GPInz","status":"SUCCEEDED","hyperParameters":["{\"parameter_id\":0, \
\"parameter_source\":\"algorithm\",\"parameters\":{\"C\":0.8748364659110364, \
\"kernel\":\"linear\",\"degree\":1,\"gamma\":0.040451413392113666}, \
\"parameter_index\":0}"],"logPath":"file://localhost:/home/shinyang/nni-experiments/bkfhOdUl/trials/GPInz",
"startTime":1600326905581,"sequenceId":0,"endTime":1600326906629,
"finalMetricData":[{"timestamp":1600326906493,"trialJobId":"GPInz","parameterId":"0","type":"FINAL",
"sequence":0,"data":"\"0.9866666666666667\""}]},
status=200,
content_type='application/json',
)

def mock_add_trial_job():
responses.add(
responses.POST, 'http://localhost:8080/api/v1/nni/trial-jobs',
json=[{"trialJobStatus":"SUCCEEDED","trialJobNumber":1}],
status=200,
content_type='application/json',
)

def mock_cancel_trial_job():
responses.add(
responses.DELETE, 'http://localhost:8080/api/v1/nni/trial-jobs/:id',
json=[{"trialJobStatus":"SUCCEEDED","trialJobNumber":1}],
status=200,
content_type='application/json',
)

def mock_get_metric_data():
responses.add(
responses.DELETE, 'http://localhost:8080/api/v1/nni/metric-data/:job_id*?',
json=[{"timestamp":1600326906486,"trialJobId":"GPInz","parameterId":"0",
"type":"PERIODICAL","sequence":0,"data":"\"0.9866666666666667\""},
{"timestamp":1600326906493,"trialJobId":"GPInz","parameterId":"0",
"type":"FINAL","sequence":0,"data":"\"0.9866666666666667\""}],
status=200,
content_type='application/json',
)

def mock_get_metric_data_by_range():
responses.add(
responses.DELETE, 'http://localhost:8080/api/v1/nni/metric-data-range/:min_seq_id/:max_seq_id',
json=[{"timestamp":1600326906486,"trialJobId":"GPInz","parameterId":"0",
"type":"PERIODICAL","sequence":0,"data":"\"0.9866666666666667\""},
{"timestamp":1600326906493,"trialJobId":"GPInz","parameterId":"0",
"type":"FINAL","sequence":0,"data":"\"0.9866666666666667\""}],
status=200,
content_type='application/json',
)

def mock_get_latest_metric_data():
responses.add(
responses.DELETE, 'http://localhost:8080/api/v1/nni/metric-data-latest/',
json=[{"timestamp":1600326906493,"trialJobId":"GPInz","parameterId":"0",
"type":"FINAL","sequence":0,"data":"\"0.9866666666666667\""},{"timestamp":1600326906486,
"trialJobId":"GPInz","parameterId":"0","type":"PERIODICAL",
"sequence":0,"data":"\"0.9866666666666667\""}],
status=200,
content_type='application/json',
)

def mock_get_trial_log():
responses.add(
responses.DELETE, 'http://localhost:8080/api/v1/nni/trial-log/:id/:type',
json={"status":"RUNNING","errors":[]},
status=200,
content_type='application/json',
)

def mock_export_data():
responses.add(
responses.DELETE, 'http://localhost:8080/api/v1/nni/export-data',
json={"status":"RUNNING","errors":[]},
status=200,
content_type='application/json',
)

def init_response():
mock_check_status()
mock_version()
mock_get_experiment_profile()
mock_set_cluster_metadata()
mock_list_trial_jobs()
mock_get_trial_job()
mock_add_trial_job()
mock_cancel_trial_job()
mock_get_metric_data()
mock_get_metric_data_by_range()
mock_get_latest_metric_data()
mock_get_trial_log()
mock_export_data()
Loading