trialmanager.ts 10.1 KB
Newer Older
1
import { MANAGER_IP, METRIC_GROUP_UPDATE_THRESHOLD, METRIC_GROUP_UPDATE_SIZE } from '../const';
2
import { MetricDataRecord, TableRecord, TrialJobInfo, MultipleAxes } from '../interface';
3
import { Trial } from './trial';
4
import { SearchSpace, MetricSpace } from './searchspace';
Lijiaoa's avatar
Lijiaoa committed
5
import { requestAxios } from '../function';
6

chicm-ms's avatar
chicm-ms committed
7
8
9
function groupMetricsByTrial(metrics: MetricDataRecord[]): Map<string, MetricDataRecord[]> {
    const ret = new Map<string, MetricDataRecord[]>();
    for (const metric of metrics) {
Lijiaoa's avatar
Lijiaoa committed
10
        if (ret.has(metric.trialJobId)) {
Lijiao's avatar
Lijiao committed
11
            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
Lijiaoa's avatar
Lijiaoa committed
12
            ret.get(metric.trialJobId)!.push(metric);
chicm-ms's avatar
chicm-ms committed
13
        } else {
14
            ret.set(metric.trialJobId, [metric]);
chicm-ms's avatar
chicm-ms committed
15
16
17
18
19
        }
    }
    return ret;
}

20
21
22
23
24
25
26
class TrialManager {
    private trials: Map<string, Trial> = new Map<string, Trial>();
    private infoInitialized: boolean = false;
    private metricInitialized: boolean = false;
    private maxSequenceId: number = 0;
    private doingBatchUpdate: boolean = false;
    private batchUpdatedAfterReading: boolean = false;
Lijiaoa's avatar
Lijiaoa committed
27
28
29
30
31
32
33
34
    private isJobListError: boolean = false; // trial-jobs api error filed
    private jobErrorMessage: string = ''; // trial-jobs error message
    private isMetricdataError: boolean = false; // metric-data api error filed
    private MetricdataErrorMessage: string = ''; // metric-data error message
    private isLatestMetricdataError: boolean = false; // metric-data-latest api error filed
    private latestMetricdataErrorMessage: string = ''; // metric-data-latest error message
    private isMetricdataRangeError: boolean = false; // metric-data-range api error filed
    private metricdataRangeErrorMessage: string = ''; // metric-data-latest error message
35
36
37
38
39
40
41
42
43
44
    private metricsList: Array<MetricDataRecord> = [];
    private trialJobList: Array<TrialJobInfo> = [];

    public getMetricsList(): Array<MetricDataRecord> {
        return this.metricsList;
    }

    public getTrialJobList(): Array<TrialJobInfo> {
        return this.trialJobList;
    }
45
46
47

    public async init(): Promise<void> {
        while (!this.infoInitialized || !this.metricInitialized) {
Lijiaoa's avatar
Lijiaoa committed
48
49
50
            if (this.isMetricdataError) {
                return;
            }
51
52
53
54
55
            await this.update();
        }
    }

    public async update(lastTime?: boolean): Promise<boolean> {
56
        const [infoUpdated, metricUpdated] = await Promise.all([this.updateInfo(), this.updateMetrics(lastTime)]);
57
58
59
60
        return infoUpdated || metricUpdated;
    }

    public getTrial(trialId: string): Trial {
Lijiao's avatar
Lijiao committed
61
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
62
63
64
65
        return this.trials.get(trialId)!;
    }

    public getTrials(trialIds: string[]): Trial[] {
Lijiao's avatar
Lijiao committed
66
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
67
68
69
70
        return trialIds.map(trialId => this.trials.get(trialId)!);
    }

    public table(trialIds: string[]): TableRecord[] {
Lijiao's avatar
Lijiao committed
71
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
        return trialIds.map(trialId => this.trials.get(trialId)!.tableRecord);
    }

    public toArray(): Trial[] {
        const trials = Array.from(this.trials.values()).filter(trial => trial.initialized());
        return trials.sort((trial1, trial2) => trial1.sequenceId - trial2.sequenceId);
    }

    public filter(callback: (trial: Trial) => boolean): Trial[] {
        const trials = Array.from(this.trials.values()).filter(trial => trial.initialized() && callback(trial));
        return trials.sort((trial1, trial2) => trial1.sequenceId - trial2.sequenceId);
    }

    public succeededTrials(): Trial[] {
        return this.filter(trial => trial.status === 'SUCCEEDED');
    }

89
90
91
92
93
    public finalKeys(): string[] {
        const succeedTrialsList = this.filter(trial => trial.status === 'SUCCEEDED');
        if (succeedTrialsList !== undefined && succeedTrialsList[0] !== undefined) {
            return succeedTrialsList[0].finalKeys();
        } else {
94
            return ['default'];
95
96
97
        }
    }

98
    public sort(): Trial[] {
Lijiao's avatar
Lijiao committed
99
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
100
101
102
103
104
        return this.filter(trial => trial.sortable).sort((trial1, trial2) => trial1.compareAccuracy(trial2)!);
    }

    public countStatus(): Map<string, number> {
        const cnt = new Map<string, number>([
105
106
107
108
109
110
111
            ['UNKNOWN', 0],
            ['WAITING', 0],
            ['RUNNING', 0],
            ['SUCCEEDED', 0],
            ['FAILED', 0],
            ['USER_CANCELED', 0],
            ['SYS_CANCELED', 0],
112
            ['EARLY_STOPPED', 0]
113
114
115
        ]);
        for (const trial of this.trials.values()) {
            if (trial.initialized()) {
Lijiao's avatar
Lijiao committed
116
                // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
117
118
119
120
121
122
                cnt.set(trial.info.status, cnt.get(trial.info.status)! + 1);
            }
        }
        return cnt;
    }

123
124
125
126
127
128
129
130
131
    public inferredSearchSpace(expSearchSpace: SearchSpace): MultipleAxes {
        // The search space inferred from trial parameters
        return SearchSpace.inferFromTrials(expSearchSpace, [...this.trials.values()]);
    }

    public inferredMetricSpace(): MultipleAxes {
        return new MetricSpace([...this.trials.values()]);
    }

Lijiaoa's avatar
Lijiaoa committed
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
    // if this.jobListError = true, show trial error message [/trial-jobs]
    public jobListError(): boolean {
        return this.isJobListError;
    }

    // trial error message's content [/trial-jobs]
    public getJobErrorMessage(): string {
        return this.jobErrorMessage;
    }

    // [/metric-data]
    public MetricDataError(): boolean {
        return this.isMetricdataError;
    }

    // [/metric-data]
    public getMetricDataErrorMessage(): string {
        return this.MetricdataErrorMessage;
    }

    // [/metric-data-latest]
    public latestMetricDataError(): boolean {
        return this.isLatestMetricdataError;
    }

    // [/metric-data-latest]
    public getLatestMetricDataErrorMessage(): string {
        return this.latestMetricdataErrorMessage;
    }

    public metricDataRangeError(): boolean {
        return this.isMetricdataRangeError;
    }

    public metricDataRangeErrorMessage(): string {
        return this.metricdataRangeErrorMessage;
    }

170
171
    private async updateInfo(): Promise<boolean> {
        let updated = false;
Lijiaoa's avatar
Lijiaoa committed
172
173
        requestAxios(`${MANAGER_IP}/trial-jobs`)
            .then(data => {
174
                this.trialJobList = data;
Lijiaoa's avatar
Lijiaoa committed
175
                for (const trialInfo of data as TrialJobInfo[]) {
J-shang's avatar
J-shang committed
176
                    if (this.trials.has(trialInfo.trialJobId)) {
Lijiaoa's avatar
Lijiaoa committed
177
                        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
J-shang's avatar
J-shang committed
178
                        updated = this.trials.get(trialInfo.trialJobId)!.updateTrialJobInfo(trialInfo) || updated;
Lijiaoa's avatar
Lijiaoa committed
179
                    } else {
J-shang's avatar
J-shang committed
180
                        this.trials.set(trialInfo.trialJobId, new Trial(trialInfo, undefined));
Lijiaoa's avatar
Lijiaoa committed
181
182
183
                        updated = true;
                    }
                    this.maxSequenceId = Math.max(this.maxSequenceId, trialInfo.sequenceId);
184
                }
Lijiaoa's avatar
Lijiaoa committed
185
186
187
188
189
190
191
192
193
                this.infoInitialized = true;
            })
            .catch(error => {
                this.isJobListError = true;
                this.jobErrorMessage = error.message;
                this.infoInitialized = true;
                updated = true;
            });

194
        return updated;
195
196
197
198
199
200
201
202
203
204
205
206
207
208
    }

    private async updateMetrics(lastTime?: boolean): Promise<boolean> {
        if (this.trials.size < METRIC_GROUP_UPDATE_THRESHOLD || lastTime) {
            return await this.updateAllMetrics();
        } else {
            this.updateManyMetrics();
            const ret = (await this.updateLatestMetrics()) || this.batchUpdatedAfterReading;
            this.batchUpdatedAfterReading = false;
            return ret;
        }
    }

    private async updateAllMetrics(): Promise<boolean> {
Lijiaoa's avatar
Lijiaoa committed
209
        return requestAxios(`${MANAGER_IP}/metric-data`)
210
211
212
213
            .then(data => {
                this.metricsList = data;
                return this.doUpdateMetrics(data as any, false);
            })
Lijiaoa's avatar
Lijiaoa committed
214
215
216
217
218
219
            .catch(error => {
                this.isMetricdataError = true;
                this.MetricdataErrorMessage = `${error.message}`;
                this.doUpdateMetrics([], false);
                return true;
            });
220
221
222
    }

    private async updateLatestMetrics(): Promise<boolean> {
Lijiaoa's avatar
Lijiaoa committed
223
224
225
226
227
228
229
230
        return requestAxios(`${MANAGER_IP}/metric-data-latest`)
            .then(data => this.doUpdateMetrics(data as any, true))
            .catch(error => {
                this.isLatestMetricdataError = true;
                this.latestMetricdataErrorMessage = `${error.message}`;
                this.doUpdateMetrics([], true);
                return true;
            });
231
232
233
234
235
236
237
    }

    private async updateManyMetrics(): Promise<void> {
        if (this.doingBatchUpdate) {
            return;
        }
        this.doingBatchUpdate = true;
238
239
240
241
242
        for (
            let i = 0;
            i < this.maxSequenceId && this.isMetricdataRangeError === false;
            i += METRIC_GROUP_UPDATE_SIZE
        ) {
Lijiaoa's avatar
Lijiaoa committed
243
244
245
246
247
248
249
250
251
            requestAxios(`${MANAGER_IP}/metric-data-range/${i}/${i + METRIC_GROUP_UPDATE_SIZE}`)
                .then(data => {
                    const updated = this.doUpdateMetrics(data as any, false);
                    this.batchUpdatedAfterReading = this.batchUpdatedAfterReading || updated;
                })
                .catch(error => {
                    this.isMetricdataRangeError = true;
                    this.metricdataRangeErrorMessage = `${error.message}`;
                });
252
253
254
255
256
257
        }
        this.doingBatchUpdate = false;
    }

    private doUpdateMetrics(allMetrics: MetricDataRecord[], latestOnly: boolean): boolean {
        let updated = false;
258
        for (const [trialId, metrics] of groupMetricsByTrial(allMetrics).entries()) {
259
260
            const trial = this.trials.get(trialId);
            if (trial !== undefined) {
261
262
263
264
265
266
267
268
269
270
271
272
                updated = (latestOnly ? trial.updateLatestMetrics(metrics) : trial.updateMetrics(metrics)) || updated;
            } else {
                this.trials.set(trialId, new Trial(undefined, metrics));
                updated = true;
            }
        }
        this.metricInitialized = true;
        return updated;
    }
}

export { TrialManager };