utils.py 5.96 KB
Newer Older
liuzhe-lz's avatar
liuzhe-lz committed
1
2
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
3

Zejun Lin's avatar
Zejun Lin committed
4
import contextlib
5
import collections
Zejun Lin's avatar
Zejun Lin committed
6
import os
7
import socket
8
import sys
Zejun Lin's avatar
Zejun Lin committed
9
10
import subprocess
import requests
11
import time
12
import ruamel.yaml as yaml
13
import shlex
Zejun Lin's avatar
Zejun Lin committed
14

chicm-ms's avatar
chicm-ms committed
15
EXPERIMENT_DONE_SIGNAL = 'Experiment done'
Zejun Lin's avatar
Zejun Lin committed
16

17
18
19
20
GREEN = '\33[32m'
RED = '\33[31m'
CLEAR = '\33[0m'

chicm-ms's avatar
chicm-ms committed
21
22
23
24
25
26
REST_ENDPOINT = 'http://localhost:8080'
API_ROOT_URL = REST_ENDPOINT + '/api/v1/nni'
EXPERIMENT_URL = API_ROOT_URL + '/experiment'
STATUS_URL = API_ROOT_URL + '/check-status'
TRIAL_JOBS_URL = API_ROOT_URL + '/trial-jobs'
METRICS_URL = API_ROOT_URL + '/metric-data'
27

Zejun Lin's avatar
Zejun Lin committed
28
def read_last_line(file_name):
29
    '''read last line of a file and return None if file not found'''
Zejun Lin's avatar
Zejun Lin committed
30
31
32
33
34
35
36
    try:
        *_, last_line = open(file_name)
        return last_line.strip()
    except (FileNotFoundError, ValueError):
        return None

def remove_files(file_list):
37
    '''remove a list of files'''
Zejun Lin's avatar
Zejun Lin committed
38
39
40
41
42
43
44
    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:
45
        return yaml.load(file, Loader=yaml.Loader)
Zejun Lin's avatar
Zejun Lin committed
46
47
48
49
50
51

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))

52
53
def setup_experiment(installed=True):
    '''setup the experiment if nni is not installed'''
Zejun Lin's avatar
Zejun Lin committed
54
    if not installed:
55
        os.environ['PATH'] = os.environ['PATH'] + ':' + os.getcwd()
Zejun Lin's avatar
Zejun Lin committed
56
57
58
59
60
61
62
63
64
        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

65
66
67
68
def get_experiment_id(experiment_url):
    experiment_id = requests.get(experiment_url).json()['id']
    return experiment_id

69
def get_experiment_dir(experiment_url=None, experiment_id=None):
70
    '''get experiment root directory'''
71
72
73
    assert any([experiment_url, experiment_id])
    if experiment_id is None:
        experiment_id = get_experiment_id(experiment_url)
chicm-ms's avatar
chicm-ms committed
74
    return os.path.join(os.path.expanduser('~'), 'nni-experiments', experiment_id)
Zejun Lin's avatar
Zejun Lin committed
75

76
def get_nni_log_dir(experiment_url=None, experiment_id=None):
77
    '''get nni's log directory from nni's experiment url'''
78
    return os.path.join(get_experiment_dir(experiment_url, experiment_id), 'log')
79
80
81
82

def get_nni_log_path(experiment_url):
    '''get nni's log path from nni's experiment url'''
    return os.path.join(get_nni_log_dir(experiment_url), 'nnimanager.log')
Zejun Lin's avatar
Zejun Lin committed
83

84
def is_experiment_done(nnimanager_log_path):
85
    '''check if the experiment is done successfully'''
Zejun Lin's avatar
Zejun Lin committed
86
    assert os.path.exists(nnimanager_log_path), 'Experiment starts failed'
chicm-ms's avatar
chicm-ms committed
87
88
89
    
    with open(nnimanager_log_path, 'r') as f:
        log_content = f.read()
90

chicm-ms's avatar
chicm-ms committed
91
    return EXPERIMENT_DONE_SIGNAL in log_content
92
93
94
95
96

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

chicm-ms's avatar
chicm-ms committed
97
def get_trial_stats(trial_jobs_url):
98
    trial_jobs = requests.get(trial_jobs_url).json()
chicm-ms's avatar
chicm-ms committed
99
    trial_stats = collections.defaultdict(int)
100
    for trial_job in trial_jobs:
chicm-ms's avatar
chicm-ms committed
101
102
        trial_stats[trial_job['status']] += 1
    return trial_stats
103

chicm-ms's avatar
chicm-ms committed
104
def get_trial_jobs(trial_jobs_url, status=None):
105
    '''Return failed trial jobs'''
106
    trial_jobs = requests.get(trial_jobs_url).json()
chicm-ms's avatar
chicm-ms committed
107
    res = []
108
    for trial_job in trial_jobs:
chicm-ms's avatar
chicm-ms committed
109
110
111
112
113
114
115
116
117
118
119
120
121
        if status is None or trial_job['status'] == status:
            res.append(trial_job)
    return res

def get_failed_trial_jobs(trial_jobs_url):
    '''Return failed trial jobs'''
    return get_trial_jobs(trial_jobs_url, 'FAILED')

def print_file_content(filepath):
    with open(filepath, 'r') as f:
        content = f.read()
        print(filepath, flush=True)
        print(content, flush=True)
122

chicm-ms's avatar
chicm-ms committed
123
124
def print_trial_job_log(training_service, trial_jobs_url):
    trial_jobs = get_trial_jobs(trial_jobs_url)
125
    for trial_job in trial_jobs:
chicm-ms's avatar
chicm-ms committed
126
127
128
129
130
        trial_log_dir = os.path.join(get_experiment_dir(EXPERIMENT_URL), 'trials', trial_job['id'])
        log_files = ['stderr', 'trial.log'] if training_service == 'local' else ['stdout_log_collection.log']
        for log_file in log_files:
            print_file_content(os.path.join(trial_log_dir, log_file))

131
132
def print_experiment_log(experiment_id):
    log_dir = get_nni_log_dir(experiment_id=experiment_id)
chicm-ms's avatar
chicm-ms committed
133
134
135
    for log_file in ['dispatcher.log', 'nnimanager.log']:
        filepath = os.path.join(log_dir, log_file)
        print_file_content(filepath)
136

137
138
139
140
141
    print('nnictl log stderr:')
    subprocess.run(shlex.split('nnictl log stderr {}'.format(experiment_id)))
    print('nnictl log stdout:')
    subprocess.run(shlex.split('nnictl log stdout {}'.format(experiment_id)))

142
143
144
145
146
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]
147
148
149
150
151
152
153
154
155
156
157
158
159

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
160
161
162
163
164
165
166
167
168
169
170

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

171
172
173
174
175
176
177
178
179
180

def wait_for_port_available(port, timeout):
    begin_time = time.time()
    while True:
        if not detect_port(port):
            return
        if time.time() - begin_time > timeout:
            msg = 'port {} is not available in {} seconds.'.format(port, timeout)
            raise RuntimeError(msg)
        time.sleep(1)