utils.py 5.36 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
Zejun Lin's avatar
Zejun Lin committed
13

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

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

chicm-ms's avatar
chicm-ms committed
20
21
22
23
24
25
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'
26

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

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

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

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

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

68
69
def get_experiment_dir(experiment_url):
    '''get experiment root directory'''
70
    experiment_id = get_experiment_id(experiment_url)
71
    return os.path.join(os.path.expanduser('~'), 'nni', 'experiments', experiment_id)
Zejun Lin's avatar
Zejun Lin committed
72

73
74
75
76
77
78
79
def get_nni_log_dir(experiment_url):
    '''get nni's log directory from nni's experiment url'''
    return os.path.join(get_experiment_dir(experiment_url), 'log')

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
80

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

chicm-ms's avatar
chicm-ms committed
88
    return EXPERIMENT_DONE_SIGNAL in log_content
89
90
91
92
93

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

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

chicm-ms's avatar
chicm-ms committed
101
def get_trial_jobs(trial_jobs_url, status=None):
102
    '''Return failed trial jobs'''
103
    trial_jobs = requests.get(trial_jobs_url).json()
chicm-ms's avatar
chicm-ms committed
104
    res = []
105
    for trial_job in trial_jobs:
chicm-ms's avatar
chicm-ms committed
106
107
108
109
110
111
112
113
114
115
116
117
118
        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)
119

chicm-ms's avatar
chicm-ms committed
120
121
def print_trial_job_log(training_service, trial_jobs_url):
    trial_jobs = get_trial_jobs(trial_jobs_url)
122
    for trial_job in trial_jobs:
chicm-ms's avatar
chicm-ms committed
123
124
125
126
127
128
129
130
131
132
        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))

def print_experiment_log(experiment_url):
    log_dir = get_nni_log_dir(experiment_url)
    for log_file in ['dispatcher.log', 'nnimanager.log']:
        filepath = os.path.join(log_dir, log_file)
        print_file_content(filepath)
133
134
135
136
137
138

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]
139
140
141
142
143
144
145
146
147
148
149
150
151

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
152
153
154
155
156
157
158
159
160
161
162
163
164

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'''
liuzhe-lz's avatar
liuzhe-lz committed
165
    time.sleep(6)