trialmanager.ts 11.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';
5
import { requestAxios, parseMetrics } from '../function';
6
import { AllTrialsIntermediateChart } from '../interface';
7

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

21
22
23
24
25
26
27
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
28
29
30
31
32
33
34
35
    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
36
37
38
39
40
41
42
43
44
45
    private metricsList: Array<MetricDataRecord> = [];
    private trialJobList: Array<TrialJobInfo> = [];

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

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

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

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

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

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

    public table(trialIds: string[]): TableRecord[] {
Lijiao's avatar
Lijiao committed
72
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
        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');
    }

90
91
92
93
    public notWaittingTrials(): Trial[] {
        return this.filter(trial => trial.status !== 'WAITING');
    }

94
95
    public allTrialsIntermediateChart(): AllTrialsIntermediateChart[] {
        const ret: AllTrialsIntermediateChart[] = [];
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
        for (const trial of this.trials.values()) {
            const mediate: number[] = [];
            for (const items of trial.intermediates) {
                if (typeof parseMetrics(items!.data) === 'object') {
                    mediate.push(parseMetrics(items!.data).default);
                } else {
                    mediate.push(parseMetrics(items!.data));
                }
            }
            ret.push({
                name: trial.id,
                sequenceId: trial.sequenceId,
                data: mediate,
                parameter: trial.parameter,
                type: 'line'
            });
        }

        return ret;
    }

117
118
119
    public finalKeys(): string[] {
        const succeedTrialsList = this.filter(trial => trial.status === 'SUCCEEDED');
        if (succeedTrialsList !== undefined && succeedTrialsList[0] !== undefined) {
120
            return succeedTrialsList[0].acc !== undefined ? Object.keys(succeedTrialsList[0].acc) : [];
121
        } else {
122
            return ['default'];
123
124
125
        }
    }

126
    public sort(): Trial[] {
Lijiao's avatar
Lijiao committed
127
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
128
129
130
131
132
        return this.filter(trial => trial.sortable).sort((trial1, trial2) => trial1.compareAccuracy(trial2)!);
    }

    public countStatus(): Map<string, number> {
        const cnt = new Map<string, number>([
133
134
135
136
137
138
139
            ['UNKNOWN', 0],
            ['WAITING', 0],
            ['RUNNING', 0],
            ['SUCCEEDED', 0],
            ['FAILED', 0],
            ['USER_CANCELED', 0],
            ['SYS_CANCELED', 0],
140
            ['EARLY_STOPPED', 0]
141
142
143
        ]);
        for (const trial of this.trials.values()) {
            if (trial.initialized()) {
Lijiao's avatar
Lijiao committed
144
                // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
145
146
147
148
149
150
                cnt.set(trial.info.status, cnt.get(trial.info.status)! + 1);
            }
        }
        return cnt;
    }

151
152
153
154
155
156
157
158
159
    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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
    // 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;
    }

198
199
    private async updateInfo(): Promise<boolean> {
        let updated = false;
Lijiaoa's avatar
Lijiaoa committed
200
201
        requestAxios(`${MANAGER_IP}/trial-jobs`)
            .then(data => {
202
                this.trialJobList = data;
Lijiaoa's avatar
Lijiaoa committed
203
                for (const trialInfo of data as TrialJobInfo[]) {
J-shang's avatar
J-shang committed
204
                    if (this.trials.has(trialInfo.trialJobId)) {
Lijiaoa's avatar
Lijiaoa committed
205
                        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
J-shang's avatar
J-shang committed
206
                        updated = this.trials.get(trialInfo.trialJobId)!.updateTrialJobInfo(trialInfo) || updated;
Lijiaoa's avatar
Lijiaoa committed
207
                    } else {
J-shang's avatar
J-shang committed
208
                        this.trials.set(trialInfo.trialJobId, new Trial(trialInfo, undefined));
Lijiaoa's avatar
Lijiaoa committed
209
210
211
                        updated = true;
                    }
                    this.maxSequenceId = Math.max(this.maxSequenceId, trialInfo.sequenceId);
212
                }
Lijiaoa's avatar
Lijiaoa committed
213
214
215
216
217
218
219
220
221
                this.infoInitialized = true;
            })
            .catch(error => {
                this.isJobListError = true;
                this.jobErrorMessage = error.message;
                this.infoInitialized = true;
                updated = true;
            });

222
        return updated;
223
224
225
226
227
228
229
230
231
232
233
234
235
236
    }

    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
237
        return requestAxios(`${MANAGER_IP}/metric-data`)
238
239
240
241
            .then(data => {
                this.metricsList = data;
                return this.doUpdateMetrics(data as any, false);
            })
Lijiaoa's avatar
Lijiaoa committed
242
243
244
245
246
247
            .catch(error => {
                this.isMetricdataError = true;
                this.MetricdataErrorMessage = `${error.message}`;
                this.doUpdateMetrics([], false);
                return true;
            });
248
249
250
    }

    private async updateLatestMetrics(): Promise<boolean> {
Lijiaoa's avatar
Lijiaoa committed
251
252
253
254
255
256
257
258
        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;
            });
259
260
261
262
263
264
265
    }

    private async updateManyMetrics(): Promise<void> {
        if (this.doingBatchUpdate) {
            return;
        }
        this.doingBatchUpdate = true;
266
267
268
269
270
        for (
            let i = 0;
            i < this.maxSequenceId && this.isMetricdataRangeError === false;
            i += METRIC_GROUP_UPDATE_SIZE
        ) {
Lijiaoa's avatar
Lijiaoa committed
271
272
273
274
275
276
277
278
279
            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}`;
                });
280
281
282
283
284
285
        }
        this.doingBatchUpdate = false;
    }

    private doUpdateMetrics(allMetrics: MetricDataRecord[], latestOnly: boolean): boolean {
        let updated = false;
286
        for (const [trialId, metrics] of groupMetricsByTrial(allMetrics).entries()) {
287
288
            const trial = this.trials.get(trialId);
            if (trial !== undefined) {
289
290
291
292
293
294
295
296
297
298
299
300
                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 };