dltsTrainingService.ts 22.3 KB
Newer Older
George Cheng's avatar
George Cheng committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

'use strict';

import * as fs from 'fs';
import * as path from 'path';
import * as request from 'request';

import * as component from '../../common/component';
import { EventEmitter } from 'events';
import { String } from 'typescript-string-operations';
import { getExperimentId } from '../../common/experimentStartupInfo';
import { getLogger, Logger } from '../../common/log';
import {
    NNIManagerIpConfig, TrainingService,
    TrialJobApplicationForm, TrialJobDetail, TrialJobMetric
} from '../../common/trainingService';
import { DLTS_TRIAL_COMMAND_FORMAT } from './dltsData';
import { CONTAINER_INSTALL_NNI_SHELL_FORMAT } from '../common/containerJobData';
import { execMkdir, validateCodeDir } from '../common/util';
import { delay, uniqueString, getIPV4Address, getExperimentRootDir, getVersion, generateParamFileName } from '../../common/utils';
import { DLTSJobRestServer } from './dltsJobRestServer';
import { TrialConfigMetadataKey } from '../../training_service/common/trialConfigMetadataKey';
import { DLTSJobConfig } from './dltsJobConfig';
import { DLTSClusterConfig } from './dltsClusterConfig';
import { DLTSTrialConfig } from './dltsTrialConfig';
import { DLTSTrialJobDetail } from './dltsTrialJobDetail';

@component.Singleton
class DLTSTrainingService implements TrainingService {
    private readonly log!: Logger;
    private readonly metricsEmitter: EventEmitter;
    //private readonly expRootDir: string;
    private readonly jobQueue: string[];
    private stopping: boolean = false;
    private readonly experimentId!: string;
    private versionCheck: boolean = true;
    private logCollection: string = 'none';
    private isMultiPhase: boolean = false;
41
    private dltsRestServerHost: string;
George Cheng's avatar
George Cheng committed
42
    private dltsRestServerPort?: number;
43
    private jobMode: boolean;
George Cheng's avatar
George Cheng committed
44
45
46
47
48
49
50
51
52
53
54
55

    private readonly trialJobsMap: Map<string, DLTSTrialJobDetail>;
    private nniManagerIpConfig?: NNIManagerIpConfig;
    private dltsClusterConfig?: DLTSClusterConfig;
    private dltsTrialConfig?: DLTSTrialConfig;

    constructor() {
        this.log = getLogger();
        this.metricsEmitter = new EventEmitter();
        this.trialJobsMap = new Map();
        this.jobQueue = [];
        this.experimentId = getExperimentId();
56
57
58
        this.dltsRestServerHost = getIPV4Address();
        this.jobMode = 'DLTS_JOB_ID' in process.env;
        this.log.info(`Construct DLTS training service in ${this.jobMode ? 'job mode' : 'local mode'}.`);
George Cheng's avatar
George Cheng committed
59
60
61
62
63
64
65
66
    }

    public async run(): Promise<void> {
        this.log.info('Run DLTS training service.');
        const restServer: DLTSJobRestServer = component.get(DLTSJobRestServer);
        await restServer.start();
        restServer.setEnableVersionCheck = this.versionCheck;
        this.log.info(`DLTS Training service rest server listening on: ${restServer.endPoint}`);
67
68
69
70
71
        if (this.jobMode) {
            await this.exposeRestServerPort(restServer.clusterRestServerPort);
        } else {
            this.dltsRestServerPort = restServer.clusterRestServerPort
        }
George Cheng's avatar
George Cheng committed
72
73
74
75
76
77
        await Promise.all([
            this.statusCheckingLoop(),
            this.submitJobLoop()]);
        this.log.info('DLTS training service exit.');
    }

78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
    private async exposeRestServerPort(port: number): Promise<void> {
        if (this.dltsClusterConfig == null) {
            throw Error('Cluster config is not set');
        }
        const { dashboard, cluster, email, password } = this.dltsClusterConfig;
        const jobId = process.env['DLTS_JOB_ID'] + '';
        const uri = `${dashboard}api/clusters/${cluster}/jobs/${jobId}/endpoints`;
        const qs = { email, password };

        do {
            this.log.debug('Checking endpoints');
            const endpoints = await new Promise((resolve, reject) => {
                request.get(uri, { qs, json: true }, function (error, response, body) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(body);
                    }
                });
            });
            this.log.debug('Endpoints: %o', endpoints);
            if (Array.isArray(endpoints)) {
                const restServerEndpoint = endpoints.find(({ podPort }) => podPort === port);
                if (restServerEndpoint == null) {
                    this.log.debug('Exposing %d', port);
                    await new Promise((resolve, reject) => {
                        request.post(uri, {
                            qs,
                            json: true,
                            body: {
                                endpoints: [{
                                    name: "nni-rest-server",
                                    podPort: port
                                }]
                            }
                        }, function (error) {
                            if (error) {
                                reject(error);
                            } else {
                                resolve();
                            }
                        });
                    });
                } else if (restServerEndpoint['status'] === 'running') {
                    // We get an exposed restserver port
                    this.dltsRestServerHost = restServerEndpoint['nodeName'];
                    this.dltsRestServerPort = restServerEndpoint['port'];
                    break;
                }
            }
        } while (await new Promise(resolve => setTimeout(resolve, 1000, true)));
    }

George Cheng's avatar
George Cheng committed
131
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
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
    private async statusCheckingLoop(): Promise<void> {
        while (!this.stopping) {
            const updateDLTSTrialJobs: Promise<void>[] = [];
            for (const [trialJobId, dltsTrialJob] of this.trialJobsMap) {
                updateDLTSTrialJobs.push(this.getDLTSTrialJobInfo(dltsTrialJob));
            }
    
            await Promise.all(updateDLTSTrialJobs);

            // Calcel paused dlts job
            const cancelPausedJobPromises: Promise<void>[] = [];
            for (const [trialJobId, dltsTrialJob] of this.trialJobsMap) {
                if (dltsTrialJob.dltsPaused && dltsTrialJob.status === 'RUNNING') {
                    cancelPausedJobPromises.push(this.cancelTrialJob(trialJobId));
                }
            }
            await Promise.all(cancelPausedJobPromises);

            const restServer: DLTSJobRestServer = component.get(DLTSJobRestServer);
            if (restServer.getErrorMessage !== undefined) {
                throw new Error(restServer.getErrorMessage);
            }
            await delay(3000);
        }
    }

    private async getDLTSTrialJobInfo(dltsTrialJob: DLTSTrialJobDetail): Promise<void> {
        if (this.dltsClusterConfig == null) {
            throw Error('Cluster config is not set');
        }
        const requestOptions: request.Options = {
            uri: `${this.dltsClusterConfig.dashboard}api/v2/clusters/${this.dltsClusterConfig.cluster}/jobs/${dltsTrialJob.dltsJobId}`,
            qs: {
                email: this.dltsClusterConfig.email,
                password: this.dltsClusterConfig.password
            },
            json: true
        };
        const body = await new Promise((resolve, reject) => {
            request(requestOptions, (error, response, body) => {
                if (error != null) {
                    reject(error)
                } else {
                    resolve(body)
                }
            })
        }) as any;
        void ((): void => {
            switch (body['jobStatus']) {
                case 'unapproved':
                case 'queued':
                case 'scheduling':
                    dltsTrialJob.status = "WAITING";
                    break;
                case 'running':
                    dltsTrialJob.status = "RUNNING";
                    if (dltsTrialJob.startTime === undefined) {
                        dltsTrialJob.startTime = Date.parse(body['jobStatusDetail'][0]['startedAt'])
                    }
                    if (dltsTrialJob.url === undefined) {
                        dltsTrialJob.url = `${this.dltsClusterConfig.dashboard}job/${this.dltsClusterConfig.team}/${this.dltsClusterConfig.cluster}/${dltsTrialJob.dltsJobId}`
                    }
                    break;
                case 'finished':
                    dltsTrialJob.status = "SUCCEEDED";
                    break;
                case 'failed':
                    dltsTrialJob.status = "FAILED";
                    break;
                case 'pausing':
                case 'paused':
                    dltsTrialJob.status = "RUNNING";
                    dltsTrialJob.dltsPaused = true;
                    break;
                case 'killing':
                case 'killed':
                    if (dltsTrialJob.isEarlyStopped !== undefined) {
                        dltsTrialJob.status = dltsTrialJob.isEarlyStopped === true
                            ? 'EARLY_STOPPED' : 'USER_CANCELED';
                    } else {
                        dltsTrialJob.status = 'SYS_CANCELED';
                    }
                    break;
                default:
                    dltsTrialJob.status = "UNKNOWN";
            }
        }) ();
    }

    private async submitJobLoop(): Promise<void> {
        while (!this.stopping) {
            while (!this.stopping && this.jobQueue.length > 0) {
                const trialJobId: string = this.jobQueue[0];
                this.log.info(`Got job ${trialJobId}`);
                if (await this.submitTrialJobToDLTS(trialJobId)) {
                    // Remove trial job with trialJobId from job queue
                    this.jobQueue.shift();
                } else {
                    // Break the while loop since failed to submitJob
                    break;
                }
            }
            await delay(3000);
        }
    }

    public async listTrialJobs(): Promise<TrialJobDetail[]> {
        return Array.from(this.trialJobsMap.values());
    }

    public async getTrialJob(trialJobId: string): Promise<TrialJobDetail> {
        const trialJob = this.trialJobsMap.get(trialJobId);
        if (trialJob === undefined) {
            throw Error(`Trial job ${trialJobId} not found.`)
        }
        return trialJob
    }

    public addTrialJobMetricListener(listener: (metric: TrialJobMetric) => void): void {
        this.metricsEmitter.on('metric', listener);
    }

    public removeTrialJobMetricListener(listener: (metric: TrialJobMetric) => void): void {
        this.metricsEmitter.off('metric', listener);
    }

    public get MetricsEmitter(): EventEmitter {
        return this.metricsEmitter;
    }

    public async submitTrialJob(form: TrialJobApplicationForm): Promise<TrialJobDetail> {
        const trialJobId: string = uniqueString(5);
        const trialWorkingFolder: string = path.join(
            '/nni/experiments', getExperimentId(),
            '/trials/', trialJobId);
        const trialJobDetail = new DLTSTrialJobDetail(
            trialJobId, // id
            'WAITING', // status
            Date.now(), // submitTime
            trialWorkingFolder, // workingDirectory
            form,
            `nni_exp_${this.experimentId}_trial_${trialJobId}`
        );

        this.trialJobsMap.set(trialJobId, trialJobDetail);
        this.jobQueue.push(trialJobId);

        return trialJobDetail;
    }

    public async cancelTrialJob(trialJobId: string, isEarlyStopped: boolean = false): Promise<void> {
        const trialJobDetail: DLTSTrialJobDetail | undefined =  this.trialJobsMap.get(trialJobId);
        if (trialJobDetail === undefined) {
            throw Error(`cancelTrialJob: trial job id ${trialJobId} not found`);
        }

        if (this.dltsClusterConfig === undefined) {
            throw Error('DLTS Cluster config is not initialized');
        }

        const options: request.Options = {
            method: 'PUT',
            uri: `${this.dltsClusterConfig.dashboard}api/clusters/${this.dltsClusterConfig.cluster}/jobs/${trialJobDetail.dltsJobId}/status`,
            qs: {
                email: this.dltsClusterConfig.email,
                password: this.dltsClusterConfig.password
            },
            body: {
                status: 'killing'
            },
            json: true
        };

        // Set trialjobDetail's early stopped field, to mark the job's cancellation source
        trialJobDetail.isEarlyStopped = isEarlyStopped;

        await new Promise((resolve, reject) => {
            request(options, (error: Error, response: request.Response, body: any) => {
                if (error) {
                    reject(error);
                } else {
                    resolve(body);
                }
            });
        });
    }

    private async getGpuType(): Promise<string> {
        if (this.dltsClusterConfig === undefined) {
            throw new Error('DLTS Cluster config is not initialized');
        }
        const gpuRequestOptions: request.Options = {
            method: 'GET',
            qs: {
                email: this.dltsClusterConfig.email,
                password: this.dltsClusterConfig.password
            },
            uri: `${this.dltsClusterConfig.dashboard}api/teams/${this.dltsClusterConfig.team}/clusters/${this.dltsClusterConfig.cluster}`,
            json: true
        };
        return new Promise<string>((resolve, reject) => {
            request(gpuRequestOptions, (error, response, data) => {
                if (error) {
                    return reject(error)
                }
                try {
                    const metadata = JSON.parse(data['metadata'])
                    resolve(Object.keys(metadata)[0])
                } catch (error) {
                    reject(error)
                }
            })
        });
    }

    public async setClusterMetadata(key: string, value: string): Promise<void> {
        switch (key) {
            case TrialConfigMetadataKey.NNI_MANAGER_IP:
                this.nniManagerIpConfig = <NNIManagerIpConfig>JSON.parse(value);
                break;

            case TrialConfigMetadataKey.DLTS_CLUSTER_CONFIG:
                this.dltsClusterConfig = <DLTSClusterConfig>JSON.parse(value);
                if (!this.dltsClusterConfig.cluster) {
                    this.dltsClusterConfig.cluster = '.default'
                }
                if (!this.dltsClusterConfig.email) {
                    if (process.env['DLWS_USER_EMAIL']) {
                        this.dltsClusterConfig.email = process.env['DLWS_USER_EMAIL'] as string
                    } else {
                        throw Error('`email` field in `dltsConfig` is not configured.')
                    }
                }
                if (!this.dltsClusterConfig.password) {
                    if (process.env['DLTS_JOB_TOKEN']) {
                        this.dltsClusterConfig.password = process.env['DLTS_JOB_TOKEN'] as string
                    } else {
                        throw Error('`password` field in `dltsConfig` is not configured.')
                    }
                }
                if (!this.dltsClusterConfig.team) {
                    if (process.env['DLWS_VC_NAME']) {
                        this.dltsClusterConfig.team = process.env['DLWS_VC_NAME'] as string
                    } else {
                        throw Error('`team` field in `dltsConfig` is not configured.')
                    }
                }
                this.dltsClusterConfig.gpuType = await this.getGpuType();
                break;

            case TrialConfigMetadataKey.TRIAL_CONFIG:
                this.dltsTrialConfig = <DLTSTrialConfig>JSON.parse(value);

                // Validate to make sure codeDir doesn't have too many files
                try {
                    await validateCodeDir(this.dltsTrialConfig.codeDir);
                } catch (error) {
                    this.log.error(error);
                    throw error;
                }
           
                break;
            case TrialConfigMetadataKey.VERSION_CHECK:
                this.versionCheck = (value === 'true' || value === 'True');
                break;
            case TrialConfigMetadataKey.LOG_COLLECTION:
                this.logCollection = value;
                break;
            case TrialConfigMetadataKey.MULTI_PHASE:
                this.isMultiPhase = (value === 'true' || value === 'True');
                break;
            default:
                //Reject for unknown keys
                throw new Error(`Uknown key: ${key}`);
        }
    }

    public async getClusterMetadata(key: string): Promise<string> {
        return '';
    }

    public async cleanUp(): Promise<void> {
        this.log.info('Stopping DLTS training service...');
        this.stopping = true;

        const restServer: DLTSJobRestServer = component.get(DLTSJobRestServer);
        try {
            await restServer.stop();
            this.log.info('DLTS Training service rest server stopped successfully.');
            return;
        } catch (error) {
            // tslint:disable-next-line: no-unsafe-any
            this.log.error(`DLTS Training service rest server stopped failed, error: ${error.message}`);
            throw error;
        }
    }

    private async submitTrialJobToDLTS(trialJobId: string): Promise<boolean> {
        const trialJobDetail: DLTSTrialJobDetail | undefined = this.trialJobsMap.get(trialJobId);

        if (trialJobDetail === undefined) {
            throw new Error(`Failed to find DLTSTrialJobDetail for job ${trialJobId}`);
        }

        if (this.dltsClusterConfig === undefined) {
            throw new Error('DLTS Cluster config is not initialized');
        }
        if (this.dltsTrialConfig === undefined) {
            throw new Error('trial config is not initialized');
        }

        if (this.dltsRestServerPort === undefined) {
            const restServer: DLTSJobRestServer = component.get(DLTSJobRestServer);
            this.dltsRestServerPort = restServer.clusterRestServerPort;
        }

        // Step 1. Prepare DLTS job configuration

        const trialLocalFolder = path.join(getExperimentRootDir(), 'trials-local', trialJobId);
        //create tmp trial working folder locally.
        await execMkdir(trialLocalFolder);

        const runScriptContent: string = CONTAINER_INSTALL_NNI_SHELL_FORMAT;
        // Write NNI installation file to local tmp files
        await fs.promises.writeFile(path.join(trialLocalFolder, 'install_nni.sh'), runScriptContent, { encoding: 'utf8' });

        // Write file content ( parameter.cfg ) to local tmp folders
        if (trialJobDetail.form !== undefined) {
            await fs.promises.writeFile(
                path.join(trialLocalFolder, generateParamFileName(trialJobDetail.form.hyperParameters)),
                trialJobDetail.form.hyperParameters.value, { encoding: 'utf8' }
            );
        }
        // tslint:disable-next-line: strict-boolean-expressions
465
        const nniManagerIp: string = this.nniManagerIpConfig ? this.nniManagerIpConfig.nniManagerIp : this.dltsRestServerHost;
George Cheng's avatar
George Cheng committed
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
        const version: string = this.versionCheck ? await getVersion() : '';
        const nniDLTSTrialCommand: string = String.Format(
            DLTS_TRIAL_COMMAND_FORMAT,
            trialLocalFolder,
            path.join(trialLocalFolder, 'nnioutput'),
            trialJobId,
            this.experimentId,
            trialJobDetail.form.sequenceId,
            false,
            this.dltsTrialConfig.codeDir,
            this.dltsTrialConfig.command,
            nniManagerIp,
            this.dltsRestServerPort,
            version,
            this.logCollection
        )
        .replace(/\r\n|\n|\r/gm, '');

        // Step 2. Submit DLTS job via Rest call
        const dltsJobConfig: DLTSJobConfig = new DLTSJobConfig(
            this.dltsClusterConfig,
            trialJobDetail.dltsJobName,
            this.dltsTrialConfig.gpuNum,
            this.dltsTrialConfig.image,
            nniDLTSTrialCommand,
            []
        );
        const submitJobRequest: request.Options = {
            method: 'POST',
            uri: `${this.dltsClusterConfig.dashboard}api/clusters/${this.dltsClusterConfig.cluster}/jobs`,
            qs: {
                email: this.dltsClusterConfig.email,
                password: this.dltsClusterConfig.password
            },
            body: dltsJobConfig,
            json: true
        }
        const responseData = await new Promise<any>((resolve, reject) => {
            request(submitJobRequest, function (error, response, data) {
                if (error) {
                    return reject(error)
                } else {
                    return resolve(data)
                }
            })
        });

        trialJobDetail.dltsJobId = responseData['jobId']

        return true;
    }

    public async updateTrialJob(trialJobId: string, form: TrialJobApplicationForm): Promise<TrialJobDetail> {
        const trialJobDetail: undefined | TrialJobDetail = this.trialJobsMap.get(trialJobId);
        if (trialJobDetail === undefined) {
            throw new Error(`updateTrialJob failed: ${trialJobId} not found`);
        }
        if (this.dltsClusterConfig === undefined) {
            throw new Error('DLTS Cluster config is not initialized');
        }
        if (this.dltsTrialConfig === undefined) {
            throw new Error('DLTS trial config is not initialized');
        }

        const hyperParameters = form.hyperParameters;
        const trialLocalTempFolder: string = path.join(getExperimentRootDir(), 'trials-local', trialJobId);
        const hpFileName: string = generateParamFileName(hyperParameters);
        const localFilepath: string = path.join(trialLocalTempFolder, hpFileName);
        await fs.promises.writeFile(localFilepath, hyperParameters.value, { encoding: 'utf8' });

        const parameterFileMeta = {
            experimentId: this.experimentId,
            trialId: trialJobId
        };
        const restServer: DLTSJobRestServer = component.get(DLTSJobRestServer);
        const req: request.Options = {
            uri: `${restServer.endPoint}${restServer.apiRootUrl}/parameter-file-meta`,
            method: 'POST',
            json: true,
            body: parameterFileMeta
        };
        await new Promise((resolve, reject) => {
            request(req, (err: Error, res: request.Response) => {
                if (err) {
                    reject(err);
                } else {
                    resolve();
                }
            });
        });

        return trialJobDetail;
    }

    public get isMultiPhaseJobSupported(): boolean {
        return false;
    }
}

export { DLTSTrainingService };