localTrainingService.ts 22.9 KB
Newer Older
Deshui Yu's avatar
Deshui Yu 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
/**
 * Copyright (c) Microsoft Corporation
 * All rights reserved.
 *
 * MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
 * to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

'use strict';

import * as cpp from 'child-process-promise';
import * as cp from 'child_process';
import { EventEmitter } from 'events';
import * as fs from 'fs';
import * as path from 'path';
import * as ts from 'tail-stream';
28
import { NNIError, NNIErrorNames } from '../../common/errors';
29
import { getInitTrialSequenceId } from '../../common/experimentStartupInfo';
30
import { getLogger, Logger } from '../../common/log';
Deshui Yu's avatar
Deshui Yu committed
31
import {
32
    HostJobApplicationForm, HyperParameters, JobApplicationForm, TrainingService, TrialJobApplicationForm,
Deshui Yu's avatar
Deshui Yu committed
33
34
    TrialJobDetail, TrialJobMetric, TrialJobStatus
} from '../../common/trainingService';
35
36
37
38
import { delay, generateParamFileName, getExperimentRootDir, getJobCancelStatus, uniqueString } from '../../common/utils';
import { TrialConfig } from '../common/trialConfig';
import { TrialConfigMetadataKey } from '../common/trialConfigMetadataKey';
import { GPUScheduler } from './gpuScheduler';
Deshui Yu's avatar
Deshui Yu committed
39
40
41
42
43
44
45
46
47
48

const tkill = require('tree-kill');

/**
 * Decode a command
 * @param Buffer binary incoming data
 * @returns a tuple of (success, commandType, content, remain)
 *          success: true if the buffer contains at least one complete command; otherwise false
 *          remain: remaining data after the first command
 */
49
// tslint:disable-next-line:informative-docs
Deshui Yu's avatar
Deshui Yu committed
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
function decodeCommand(data: Buffer): [boolean, string, string, Buffer] {
    if (data.length < 8) {
        return [false, '', '', data];
    }
    const commandType: string = data.slice(0, 2).toString();
    const contentLength: number = parseInt(data.slice(2, 8).toString(), 10);
    if (data.length < contentLength + 8) {
        return [false, '', '', data];
    }
    const content: string = data.slice(8, contentLength + 8).toString();
    const remain: Buffer = data.slice(contentLength + 8);

    return [true, commandType, content, remain];
}

/**
 * LocalTrialJobDetail
 */
class LocalTrialJobDetail implements TrialJobDetail {
    public id: string;
    public status: TrialJobStatus;
71
72
73
    public submitTime: number;
    public startTime?: number;
    public endTime?: number;
Deshui Yu's avatar
Deshui Yu committed
74
75
76
77
    public tags?: string[];
    public url?: string;
    public workingDirectory: string;
    public form: JobApplicationForm;
78
    public sequenceId: number;
Deshui Yu's avatar
Deshui Yu committed
79
    public pid?: number;
80
    public gpuIndices?: number[];
Deshui Yu's avatar
Deshui Yu committed
81

82
83
    constructor(
        id: string, status: TrialJobStatus, submitTime: number,
84
        workingDirectory: string, form: JobApplicationForm, sequenceId: number) {
Deshui Yu's avatar
Deshui Yu committed
85
86
87
88
89
90
        this.id = id;
        this.status = status;
        this.submitTime = submitTime;
        this.workingDirectory = workingDirectory;
        this.form = form;
        this.url = `file://localhost:${workingDirectory}`;
91
        this.sequenceId = sequenceId;
92
93
94
95
96
97
98
99
100
101
102
103
104
        this.gpuIndices = [];
    }
}

/**
 * Local training service config
 */
class LocalConfig {
    public gpuIndices?: string;
    constructor(gpuIndices?: string) {
        if (gpuIndices !== undefined) {
            this.gpuIndices = gpuIndices;
        }
Deshui Yu's avatar
Deshui Yu committed
105
106
107
108
    }
}

/**
chicm-ms's avatar
chicm-ms committed
109
 * Local machine training service
Deshui Yu's avatar
Deshui Yu committed
110
111
112
113
114
115
116
117
 */
class LocalTrainingService implements TrainingService {
    private eventEmitter: EventEmitter;
    private jobMap: Map<string, LocalTrialJobDetail>;
    private jobQueue: string[];
    private initialized: boolean;
    private stopping: boolean;
    private rootDir!: string;
118
    private trialSequenceId: number;
119
120
121
122
123
124
    private gpuScheduler!: GPUScheduler;
    private occupiedGpuIndices: Set<number>;
    private designatedGpuIndices!: Set<number>;
    private log: Logger;
    private localTrailConfig?: TrialConfig;
    private localConfig?: LocalConfig;
125
    private isMultiPhase: boolean = false;
126
    private jobStreamMap: Map<string, ts.Stream>;
Deshui Yu's avatar
Deshui Yu committed
127
128
129
130
131
132
133
134

    constructor() {
        this.eventEmitter = new EventEmitter();
        this.jobMap = new Map<string, LocalTrialJobDetail>();
        this.jobQueue = [];
        this.initialized = false;
        this.stopping = false;
        this.log = getLogger();
135
        this.trialSequenceId = -1;
136
        this.jobStreamMap = new Map<string, ts.Stream>();
chicm-ms's avatar
chicm-ms committed
137
        this.log.info('Construct local machine training service.');
138
        this.occupiedGpuIndices = new Set<number>();
Deshui Yu's avatar
Deshui Yu committed
139
140
141
    }

    public async run(): Promise<void> {
chicm-ms's avatar
chicm-ms committed
142
        this.log.info('Run local machine training service.');
143
144
145
        const longRunningTasks: Promise<void>[] = [this.runJobLoop()];
        if (this.gpuScheduler !== undefined) {
            longRunningTasks.push(this.gpuScheduler.run());
Deshui Yu's avatar
Deshui Yu committed
146
        }
147
        await Promise.all(longRunningTasks);
chicm-ms's avatar
chicm-ms committed
148
        this.log.info('Local machine training service exit.');
Deshui Yu's avatar
Deshui Yu committed
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
    }

    public async listTrialJobs(): Promise<TrialJobDetail[]> {
        const jobs: TrialJobDetail[] = [];
        for (const key of this.jobMap.keys()) {
            const trialJob: TrialJobDetail = await this.getTrialJob(key);
            if (trialJob.form.jobType === 'TRIAL') {
                jobs.push(trialJob);
            }
        }

        return jobs;
    }

    public async getTrialJob(trialJobId: string): Promise<TrialJobDetail> {
        const trialJob: LocalTrialJobDetail | undefined = this.jobMap.get(trialJobId);
        if (trialJob === undefined) {
            throw new NNIError(NNIErrorNames.NOT_FOUND, 'Trial job not found');
        }
        if (trialJob.form.jobType === 'HOST') {
            return this.getHostJob(trialJobId);
        }
        if (trialJob.status === 'RUNNING') {
            let alive: boolean = false;
            try {
                await cpp.exec(`kill -0 ${trialJob.pid}`);
                alive = true;
            } catch (error) {
                //ignore
            }

            if (!alive) {
181
                trialJob.endTime = Date.now();
Deshui Yu's avatar
Deshui Yu committed
182
183
184
                this.setTrialJobStatus(trialJob, 'FAILED');
                try {
                    const state: string = await fs.promises.readFile(path.join(trialJob.workingDirectory, '.nni', 'state'), 'utf8');
185
186
                    const match: RegExpMatchArray | null = state.trim()
                        .match(/^(\d+)\s+(\d+)/);
Deshui Yu's avatar
Deshui Yu committed
187
188
189
190
191
                    if (match !== null) {
                        const { 1: code, 2: timestamp } = match;
                        if (parseInt(code, 10) === 0) {
                            this.setTrialJobStatus(trialJob, 'SUCCEEDED');
                        }
192
                        trialJob.endTime = parseInt(timestamp, 10);
Deshui Yu's avatar
Deshui Yu committed
193
194
195
196
                    }
                } catch (error) {
                    //ignore
                }
chicm-ms's avatar
chicm-ms committed
197
                this.log.debug(`trailJob status update: ${trialJobId}, ${trialJob.status}`);
Deshui Yu's avatar
Deshui Yu committed
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
            }
        }

        return trialJob;
    }

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

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

    public submitTrialJob(form: JobApplicationForm): Promise<TrialJobDetail> {
        if (form.jobType === 'HOST') {
            return this.runHostJob(<HostJobApplicationForm>form);
        } else if (form.jobType === 'TRIAL') {
            const trialJobId: string = uniqueString(5);
            const trialJobDetail: LocalTrialJobDetail = new LocalTrialJobDetail(
                trialJobId,
                'WAITING',
220
                Date.now(),
Deshui Yu's avatar
Deshui Yu committed
221
                path.join(this.rootDir, 'trials', trialJobId),
222
223
224
                form,
                this.generateSequenceId()
            );
Deshui Yu's avatar
Deshui Yu committed
225
226
227
228
229
230
231
232
233
234
235
            this.jobQueue.push(trialJobId);
            this.jobMap.set(trialJobId, trialJobDetail);

            this.log.debug(`submitTrialJob: return: ${JSON.stringify(trialJobDetail)} `);

            return Promise.resolve(trialJobDetail);
        } else {
            return Promise.reject(new Error(`Job form not supported: ${JSON.stringify(form)}`));
        }
    }

236
237
238
239
240
    /**
     * Update trial job for multi-phase
     * @param trialJobId trial job id
     * @param form job application form
     */
chicm-ms's avatar
chicm-ms committed
241
242
243
244
245
246
247
248
249
250
251
252
    public async updateTrialJob(trialJobId: string, form: JobApplicationForm): Promise<TrialJobDetail> {
        const trialJobDetail: undefined | TrialJobDetail = this.jobMap.get(trialJobId);
        if (trialJobDetail === undefined) {
            throw new Error(`updateTrialJob failed: ${trialJobId} not found`);
        }
        if (form.jobType === 'TRIAL') {
            await this.writeParameterFile(trialJobDetail.workingDirectory, (<TrialJobApplicationForm>form).hyperParameters);
        } else {
            throw new Error(`updateTrialJob failed: jobType ${form.jobType} not supported.`);
        }

        return trialJobDetail;
253
254
255
256
257
258
    }

    /**
     * Is multiphase job supported in current training service
     */
    public get isMultiPhaseJobSupported(): boolean {
259
        return true;
260
261
    }

QuanluZhang's avatar
QuanluZhang committed
262
    public async cancelTrialJob(trialJobId: string, isEarlyStopped: boolean = false): Promise<void> {
Deshui Yu's avatar
Deshui Yu committed
263
264
265
266
        const trialJob: LocalTrialJobDetail | undefined = this.jobMap.get(trialJobId);
        if (trialJob === undefined) {
            throw new NNIError(NNIErrorNames.NOT_FOUND, 'Trial job not found');
        }
267
        if (trialJob.pid === undefined) {
268
            this.setTrialJobStatus(trialJob, 'USER_CANCELED');
269

SparkSnail's avatar
SparkSnail committed
270
            return Promise.resolve();
271
        }
Deshui Yu's avatar
Deshui Yu committed
272
273
274
275
276
277
278
        if (trialJob.form.jobType === 'TRIAL') {
            await tkill(trialJob.pid, 'SIGKILL');
        } else if (trialJob.form.jobType === 'HOST') {
            await cpp.exec(`pkill -9 -P ${trialJob.pid}`);
        } else {
            throw new Error(`Job type not supported: ${trialJob.form.jobType}`);
        }
QuanluZhang's avatar
QuanluZhang committed
279
        this.setTrialJobStatus(trialJob, getJobCancelStatus(isEarlyStopped));
280

SparkSnail's avatar
SparkSnail committed
281
        return Promise.resolve();
Deshui Yu's avatar
Deshui Yu committed
282
283
284
285
286
287
288
289
290
    }

    public async setClusterMetadata(key: string, value: string): Promise<void> {
        if (!this.initialized) {
            this.rootDir = getExperimentRootDir();
            await cpp.exec(`mkdir -p ${this.rootDir}`);
            this.initialized = true;
        }
        switch (key) {
291
292
293
294
295
296
            case TrialConfigMetadataKey.TRIAL_CONFIG:
                this.localTrailConfig = <TrialConfig>JSON.parse(value);
                // Parse trial config failed, throw Error
                if (!this.localTrailConfig) {
                    throw new Error('trial config parsed failed');
                }
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
                this.log.info(`required GPU number is ${this.localTrailConfig.gpuNum}`);
                if (this.gpuScheduler === undefined && this.localTrailConfig.gpuNum > 0) {
                    this.gpuScheduler = new GPUScheduler();
                }
                break;
            case TrialConfigMetadataKey.LOCAL_CONFIG:
                this.localConfig = <LocalConfig>JSON.parse(value);
                this.log.info(`Specified GPU indices: ${this.localConfig.gpuIndices}`);
                if (this.localConfig.gpuIndices !== undefined) {
                    this.designatedGpuIndices = new Set(this.localConfig.gpuIndices.split(',')
                            .map((x: string) => parseInt(x, 10)));
                    if (this.designatedGpuIndices.size === 0) {
                        throw new Error('gpuIndices can not be empty if specified.');
                    }
                }
Deshui Yu's avatar
Deshui Yu committed
312
                break;
313
314
315
            case TrialConfigMetadataKey.MULTI_PHASE:
                this.isMultiPhase = (value === 'true' || value === 'True');
                break;
Deshui Yu's avatar
Deshui Yu committed
316
317
318
319
320
321
            default:
        }
    }

    public getClusterMetadata(key: string): Promise<string> {
        switch (key) {
322
            case TrialConfigMetadataKey.TRIAL_CONFIG:
323
324
                let getResult: Promise<string>;
                if (!this.localTrailConfig) {
325
326
                    getResult = Promise.reject(new NNIError(NNIErrorNames.NOT_FOUND, `${key} is never set yet`));
                } else {
327
                    getResult = Promise.resolve(!this.localTrailConfig ? '' : JSON.stringify(this.localTrailConfig));
328
                }
329

330
                return getResult;
Deshui Yu's avatar
Deshui Yu committed
331
332
333
334
335
            default:
                return Promise.reject(new NNIError(NNIErrorNames.NOT_FOUND, 'Key not found'));
        }
    }

336
    public async cleanUp(): Promise<void> {
chicm-ms's avatar
chicm-ms committed
337
        this.log.info('Stopping local machine training service...');
Deshui Yu's avatar
Deshui Yu committed
338
        this.stopping = true;
339
        for (const stream of this.jobStreamMap.values()) {
340
341
            stream.destroy();
        }
342
343
344
345
        if (this.gpuScheduler !== undefined) {
            await this.gpuScheduler.stop();
        }

Deshui Yu's avatar
Deshui Yu committed
346
347
348
        return Promise.resolve();
    }

349
    private onTrialJobStatusChanged(trialJob: LocalTrialJobDetail, oldStatus: TrialJobStatus): void {
350
        //if job is not running, destory job stream
351
352
353
354
        if (['SUCCEEDED', 'FAILED', 'USER_CANCELED', 'SYS_CANCELED', 'EARLY_STOPPED'].includes(trialJob.status)) {
            if (this.jobStreamMap.has(trialJob.id)) {
                const stream: ts.Stream | undefined = this.jobStreamMap.get(trialJob.id);
                if (!stream) {
355
356
357
358
359
360
                    throw new Error(`Could not find stream in trial ${trialJob.id}`);
                }
                stream.destroy();
                this.jobStreamMap.delete(trialJob.id);
            }
        }
361
362
363
364
365
366
367
        if (trialJob.gpuIndices !== undefined && trialJob.gpuIndices.length > 0 && this.gpuScheduler !== undefined) {
            if (oldStatus === 'RUNNING' && trialJob.status !== 'RUNNING') {
                for (const index of trialJob.gpuIndices) {
                    this.occupiedGpuIndices.delete(index);
                }
            }
        }
Deshui Yu's avatar
Deshui Yu committed
368
369
    }

370
371
    private getEnvironmentVariables(
        trialJobDetail: TrialJobDetail,
chicm-ms's avatar
chicm-ms committed
372
        resource: { gpuIndices: number[] }): { key: string; value: string }[] {
373
        const envVariables: { key: string; value: string }[] = [
Deshui Yu's avatar
Deshui Yu committed
374
375
376
            { key: 'NNI_PLATFORM', value: 'local' },
            { key: 'NNI_SYS_DIR', value: trialJobDetail.workingDirectory },
            { key: 'NNI_TRIAL_JOB_ID', value: trialJobDetail.id },
377
            { key: 'NNI_OUTPUT_DIR', value: trialJobDetail.workingDirectory },
378
            { key: 'NNI_TRIAL_SEQ_ID', value: trialJobDetail.sequenceId.toString() },
379
            { key: 'MULTI_PHASE', value: this.isMultiPhase.toString() }
Deshui Yu's avatar
Deshui Yu committed
380
        ];
381

chicm-ms's avatar
chicm-ms committed
382
383
384
385
        envVariables.push({
            key: 'CUDA_VISIBLE_DEVICES',
            value: this.gpuScheduler === undefined ? '' : resource.gpuIndices.join(',')
        });
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

        return envVariables;
    }

    private setExtraProperties(trialJobDetail: LocalTrialJobDetail, resource: { gpuIndices: number[] }): void {
        trialJobDetail.gpuIndices = resource.gpuIndices;
    }

    private tryGetAvailableResource(): [boolean, { gpuIndices: number[]}] {
        if (this.localTrailConfig === undefined) {
            throw new Error('localTrailConfig is not initialized!');
        }

        const resource: { gpuIndices: number[] } = { gpuIndices: [] };
        if (this.gpuScheduler === undefined) {
            return [true, resource];
        }

        let selectedGPUIndices: number[] = this.gpuScheduler.getAvailableGPUIndices()
            .filter((index: number) => !this.occupiedGpuIndices.has(index));

        if (this.designatedGpuIndices !== undefined) {
            this.checkSpecifiedGpuIndices();
            selectedGPUIndices = selectedGPUIndices.filter((index: number) => this.designatedGpuIndices.has(index));
        }

        if (selectedGPUIndices.length < this.localTrailConfig.gpuNum) {
            return [false, resource];
        }

        selectedGPUIndices.splice(this.localTrailConfig.gpuNum);
        Object.assign(resource, { gpuIndices: selectedGPUIndices });

        return [true, resource];
Deshui Yu's avatar
Deshui Yu committed
420
421
    }

422
423
424
425
426
427
428
429
430
    private checkSpecifiedGpuIndices(): void {
        const gpuCount: number = this.gpuScheduler.getSystemGpuCount();
        if (this.designatedGpuIndices !== undefined) {
            for (const index of this.designatedGpuIndices) {
                if (index >= gpuCount) {
                    throw new Error(`Specified GPU index not found: ${index}`);
                }
            }
        }
Deshui Yu's avatar
Deshui Yu committed
431
432
    }

433
434
435
436
437
438
    private occupyResource(resource: {gpuIndices: number[]}): void {
        if (this.gpuScheduler !== undefined) {
            for (const index of resource.gpuIndices) {
                this.occupiedGpuIndices.add(index);
            }
        }
Deshui Yu's avatar
Deshui Yu committed
439
440
    }

441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
    private async runJobLoop(): Promise<void> {
        while (!this.stopping) {
            while (!this.stopping && this.jobQueue.length !== 0) {
                const trialJobId: string = this.jobQueue[0];
                const trialJobDeatil: LocalTrialJobDetail | undefined = this.jobMap.get(trialJobId);
                if (trialJobDeatil !== undefined && trialJobDeatil.status === 'WAITING') {
                    const [success, resource] = this.tryGetAvailableResource();
                    if (!success) {
                        break;
                    }
                    this.occupyResource(resource);
                    await this.runTrialJob(trialJobId, resource);
                }
                this.jobQueue.shift();
            }
            await delay(5000);
        }
Deshui Yu's avatar
Deshui Yu committed
458
459
460
461
462
463
464
465
466
467
    }

    private setTrialJobStatus(trialJob: LocalTrialJobDetail, newStatus: TrialJobStatus): void {
        if (trialJob.status !== newStatus) {
            const oldStatus: TrialJobStatus = trialJob.status;
            trialJob.status = newStatus;
            this.onTrialJobStatusChanged(trialJob, oldStatus);
        }
    }

468
    private async runTrialJob(trialJobId: string, resource: {gpuIndices: number[]}): Promise<void> {
Deshui Yu's avatar
Deshui Yu committed
469
470
471
472
        const trialJobDetail: LocalTrialJobDetail = <LocalTrialJobDetail>this.jobMap.get(trialJobId);
        const variables: { key: string; value: string }[] = this.getEnvironmentVariables(trialJobDetail, resource);

        const runScriptLines: string[] = [];
473
474
475
476

        if (!this.localTrailConfig) {
            throw new Error('trial config is not initialized');
        }
Deshui Yu's avatar
Deshui Yu committed
477
478
        runScriptLines.push(
            '#!/bin/bash',
479
            `cd ${this.localTrailConfig.codeDir}`);
Deshui Yu's avatar
Deshui Yu committed
480
481
482
483
        for (const variable of variables) {
            runScriptLines.push(`export ${variable.key}=${variable.value}`);
        }
        runScriptLines.push(
484
            `eval ${this.localTrailConfig.command} 2>${path.join(trialJobDetail.workingDirectory, 'stderr')}`,
485
            `echo $? \`date +%s000\` >${path.join(trialJobDetail.workingDirectory, '.nni', 'state')}`);
Deshui Yu's avatar
Deshui Yu committed
486
487
488
489

        await cpp.exec(`mkdir -p ${trialJobDetail.workingDirectory}`);
        await cpp.exec(`mkdir -p ${path.join(trialJobDetail.workingDirectory, '.nni')}`);
        await cpp.exec(`touch ${path.join(trialJobDetail.workingDirectory, '.nni', 'metrics')}`);
490
491
        await fs.promises.writeFile(
            path.join(trialJobDetail.workingDirectory, 'run.sh'), runScriptLines.join('\n'), { encoding: 'utf8', mode: 0o777 });
chicm-ms's avatar
chicm-ms committed
492
        await this.writeParameterFile(trialJobDetail.workingDirectory, (<TrialJobApplicationForm>trialJobDetail.form).hyperParameters);
Deshui Yu's avatar
Deshui Yu committed
493
494
495
        const process: cp.ChildProcess = cp.exec(`bash ${path.join(trialJobDetail.workingDirectory, 'run.sh')}`);

        this.setTrialJobStatus(trialJobDetail, 'RUNNING');
496
        trialJobDetail.startTime = Date.now();
Deshui Yu's avatar
Deshui Yu committed
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
        trialJobDetail.pid = process.pid;
        this.setExtraProperties(trialJobDetail, resource);

        let buffer: Buffer = Buffer.alloc(0);
        const stream: ts.Stream = ts.createReadStream(path.join(trialJobDetail.workingDirectory, '.nni', 'metrics'));
        stream.on('data', (data: Buffer) => {
            buffer = Buffer.concat([buffer, data]);
            while (buffer.length > 0) {
                const [success, , content, remain] = decodeCommand(buffer);
                if (!success) {
                    break;
                }
                this.eventEmitter.emit('metric', {
                    id: trialJobDetail.id,
                    data: content
                });
                this.log.debug(`Sending metrics, job id: ${trialJobDetail.id}, metrics: ${content}`);
                buffer = remain;
            }
        });
517

518
        this.jobStreamMap.set(trialJobDetail.id, stream);
Deshui Yu's avatar
Deshui Yu committed
519
520
521
522
523
524
525
526
527
528
529
530
    }

    private async runHostJob(form: HostJobApplicationForm): Promise<TrialJobDetail> {
        const jobId: string = uniqueString(5);
        const workDir: string = path.join(this.rootDir, 'hostjobs', jobId);
        await cpp.exec(`mkdir -p ${workDir}`);
        const wrappedCmd: string = `cd ${workDir} && ${form.cmd}>stdout 2>stderr`;
        this.log.debug(`runHostJob: command: ${wrappedCmd}`);
        const process: cp.ChildProcess = cp.exec(wrappedCmd);
        const jobDetail: LocalTrialJobDetail = {
            id: jobId,
            status: 'RUNNING',
531
            submitTime: Date.now(),
Deshui Yu's avatar
Deshui Yu committed
532
533
            workingDirectory: workDir,
            form: form,
534
            sequenceId: this.generateSequenceId(),
Deshui Yu's avatar
Deshui Yu committed
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
            pid: process.pid
        };
        this.jobMap.set(jobId, jobDetail);
        this.log.debug(`runHostJob: return: ${JSON.stringify(jobDetail)} `);

        return jobDetail;
    }

    private async getHostJob(jobId: string): Promise<TrialJobDetail> {
        const jobDetail: LocalTrialJobDetail | undefined = this.jobMap.get(jobId);
        if (jobDetail === undefined) {
            throw new NNIError(NNIErrorNames.NOT_FOUND, `Host Job not found: ${jobId}`);
        }
        try {
            await cpp.exec(`kill -0 ${jobDetail.pid}`);

            return jobDetail;
        } catch (error) {
            if (error instanceof Error) {
                this.log.debug(`getHostJob: error: ${error.message}`);
                this.jobMap.delete(jobId);
                throw new NNIError(NNIErrorNames.NOT_FOUND, `Host Job not found: ${error.message}`);
            } else {
                throw error;
            }
        }
    }
chicm-ms's avatar
chicm-ms committed
562
563

    private async writeParameterFile(directory: string, hyperParameters: HyperParameters): Promise<void> {
564
        const filepath: string = path.join(directory, generateParamFileName(hyperParameters));
chicm-ms's avatar
chicm-ms committed
565
566
        await fs.promises.writeFile(filepath, hyperParameters.value, { encoding: 'utf8' });
    }
567
568

    private generateSequenceId(): number {
569
570
571
572
        if (this.trialSequenceId === -1) {
            this.trialSequenceId = getInitTrialSequenceId();
        }

573
574
        return this.trialSequenceId++;
    }
Deshui Yu's avatar
Deshui Yu committed
575
576
577
}

export { LocalTrainingService };