utils.py 5.52 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Copyright (c) Microsoft Corporation
# All rights reserved.
#
# MIT License
#
# Permission is hereby granted, free of charge,
# to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and
# to permit persons to whom the Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Zejun Lin's avatar
Zejun Lin committed
21
import contextlib
22
import collections
Zejun Lin's avatar
Zejun Lin committed
23
import os
24
import socket
25
import sys
Zejun Lin's avatar
Zejun Lin committed
26
27
import subprocess
import requests
28
import time
29
import ruamel.yaml as yaml
Zejun Lin's avatar
Zejun Lin committed
30

chicm-ms's avatar
chicm-ms committed
31
EXPERIMENT_DONE_SIGNAL = 'Experiment done'
Zejun Lin's avatar
Zejun Lin committed
32

33
34
35
36
37
38
39
40
41
42
GREEN = '\33[32m'
RED = '\33[31m'
CLEAR = '\33[0m'

REST_ENDPOINT = 'http://localhost:8080/api/v1/nni'
EXPERIMENT_URL = REST_ENDPOINT + '/experiment'
STATUS_URL = REST_ENDPOINT + '/check-status'
TRIAL_JOBS_URL = REST_ENDPOINT + '/trial-jobs'
METRICS_URL = REST_ENDPOINT + '/metric-data'

Zejun Lin's avatar
Zejun Lin committed
43
def read_last_line(file_name):
44
    '''read last line of a file and return None if file not found'''
Zejun Lin's avatar
Zejun Lin committed
45
46
47
48
49
50
51
    try:
        *_, last_line = open(file_name)
        return last_line.strip()
    except (FileNotFoundError, ValueError):
        return None

def remove_files(file_list):
52
    '''remove a list of files'''
Zejun Lin's avatar
Zejun Lin committed
53
54
55
56
57
58
59
    for file_path in file_list:
        with contextlib.suppress(FileNotFoundError):
            os.remove(file_path)

def get_yml_content(file_path):
    '''Load yaml file content'''
    with open(file_path, 'r') as file:
60
        return yaml.load(file, Loader=yaml.Loader)
Zejun Lin's avatar
Zejun Lin committed
61
62
63
64
65
66

def dump_yml_content(file_path, content):
    '''Dump yaml file content'''
    with open(file_path, 'w') as file:
        file.write(yaml.dump(content, default_flow_style=False))

67
68
def setup_experiment(installed=True):
    '''setup the experiment if nni is not installed'''
Zejun Lin's avatar
Zejun Lin committed
69
    if not installed:
70
        os.environ['PATH'] = os.environ['PATH'] + ':' + os.getcwd()
Zejun Lin's avatar
Zejun Lin committed
71
72
73
74
75
76
77
78
79
        sdk_path = os.path.abspath('../src/sdk/pynni')
        cmd_path = os.path.abspath('../tools')
        pypath = os.environ.get('PYTHONPATH')
        if pypath:
            pypath = ':'.join([pypath, sdk_path, cmd_path])
        else:
            pypath = ':'.join([sdk_path, cmd_path])
        os.environ['PYTHONPATH'] = pypath

80
81
82
83
84
def get_experiment_id(experiment_url):
    experiment_id = requests.get(experiment_url).json()['id']
    return experiment_id

def get_nni_log_path(experiment_url):
85
    '''get nni's log path from nni's experiment url'''
86
    experiment_id = get_experiment_id(experiment_url)
87
    experiment_path = os.path.join(os.path.expanduser('~'), 'nni', 'experiments', experiment_id)
Zejun Lin's avatar
Zejun Lin committed
88
89
90
91
    nnimanager_log_path = os.path.join(experiment_path, 'log', 'nnimanager.log')

    return nnimanager_log_path

92
def is_experiment_done(nnimanager_log_path):
93
    '''check if the experiment is done successfully'''
Zejun Lin's avatar
Zejun Lin committed
94
    assert os.path.exists(nnimanager_log_path), 'Experiment starts failed'
chicm-ms's avatar
chicm-ms committed
95
96
97
98
99
    
    with open(nnimanager_log_path, 'r') as f:
        log_content = f.read()
    
    return EXPERIMENT_DONE_SIGNAL in log_content
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118

def get_experiment_status(status_url):
    nni_status = requests.get(status_url).json()
    return nni_status['status']

def get_succeeded_trial_num(trial_jobs_url):
    trial_jobs = requests.get(trial_jobs_url).json()
    print(trial_jobs)
    num_succeed = 0
    for trial_job in trial_jobs:
        if trial_job['status'] in ['SUCCEEDED', 'EARLY_STOPPED']:
            num_succeed += 1
    print('num_succeed:', num_succeed)
    return num_succeed

def print_stderr(trial_jobs_url):
    trial_jobs = requests.get(trial_jobs_url).json()
    for trial_job in trial_jobs:
        if trial_job['status'] == 'FAILED':
119
            if sys.platform == "win32":
chicm-ms's avatar
chicm-ms committed
120
121
                p = trial_job['stderrPath'].split(':')
                stderr_path = ':'.join([p[-2], p[-1]])
122
123
                subprocess.run(['type', stderr_path], shell=True)
            else:
chicm-ms's avatar
chicm-ms committed
124
                stderr_path = trial_job['stderrPath'].split(':')[-1]
125
                subprocess.run(['cat', stderr_path])
126
127
128
129
130
131

def parse_max_duration_time(max_exec_duration):
    unit = max_exec_duration[-1]
    time = max_exec_duration[:-1]
    units_dict = {'s':1, 'm':60, 'h':3600, 'd':86400}
    return int(time) * units_dict[unit]
132
133
134
135
136
137
138
139
140
141
142
143
144

def deep_update(source, overrides):
    """Update a nested dictionary or similar mapping.

    Modify ``source`` in place.
    """
    for key, value in overrides.items():
        if isinstance(value, collections.Mapping) and value:
            returned = deep_update(source.get(key, {}), value)
            source[key] = returned
        else:
            source[key] = overrides[key]
    return source
145
146
147
148
149
150
151
152
153
154
155
156
157
158

def detect_port(port):
    '''Detect if the port is used'''
    socket_test = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    try:
        socket_test.connect(('127.0.0.1', int(port)))
        socket_test.close()
        return True
    except:
        return False

def snooze():
    '''Sleep to make sure previous stopped exp has enough time to exit'''
    time.sleep(6)