gpuScheduler.ts 4.46 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
/**
 * 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';

22
import * as cpp from 'child-process-promise';
23
import * as cp from 'child_process';
24
import * as fs from 'fs';
25
26
import * as os from 'os';
import * as path from 'path';
27
import { String } from 'typescript-string-operations';
28
29
30
import { getLogger, Logger } from '../../common/log';
import { delay } from '../../common/utils';
import { GPU_INFO_COLLECTOR_FORMAT, GPUInfo, GPUSummary } from '../common/gpuData';
Deshui Yu's avatar
Deshui Yu committed
31
32

/**
33
 * GPUScheduler for local training service
Deshui Yu's avatar
Deshui Yu committed
34
35
36
37
38
 */
class GPUScheduler {

    private gpuSummary!: GPUSummary;
    private stopping: boolean;
39
    private log: Logger;
40
    private gpuMetricCollectorScriptFolder: string;
Deshui Yu's avatar
Deshui Yu committed
41
42
43

    constructor() {
        this.stopping = false;
44
        this.log = getLogger();
45
        this.gpuMetricCollectorScriptFolder = `${os.tmpdir()}/nni/script`;
Deshui Yu's avatar
Deshui Yu committed
46
47
48
    }

    public async run(): Promise<void> {
49
        await this.runGpuMetricsCollectorScript();
Deshui Yu's avatar
Deshui Yu committed
50
51
        while (!this.stopping) {
            try {
52
                await this.updateGPUSummary();
Deshui Yu's avatar
Deshui Yu committed
53
            } catch (error) {
54
                this.log.error('Read GPU summary failed with error: ', error);
Deshui Yu's avatar
Deshui Yu committed
55
56
57
58
59
60
61
            }
            await delay(5000);
        }
    }

    public getAvailableGPUIndices(): number[] {
        if (this.gpuSummary !== undefined) {
62
63
            return this.gpuSummary.gpuInfos.filter((info: GPUInfo) => info.activeProcessNum === 0)
                .map((info: GPUInfo) => info.index);
Deshui Yu's avatar
Deshui Yu committed
64
65
66
67
68
        }

        return [];
    }

69
70
71
72
73
74
75
76
77
    public getSystemGpuCount(): number {
        if (this.gpuSummary !== undefined) {
            return this.gpuSummary.gpuCount;
        }

        return 0;
    }

    public async stop(): Promise<void> {
Deshui Yu's avatar
Deshui Yu committed
78
        this.stopping = true;
79
80
81
82
        try {
            const pid: string = await fs.promises.readFile(path.join(this.gpuMetricCollectorScriptFolder, 'pid'), 'utf8');
            await cpp.exec(`pkill -P ${pid}`);
            await cpp.exec(`rm -rf ${this.gpuMetricCollectorScriptFolder}`);
83
        } catch (error) {
84
85
            this.log.error(`GPU scheduler error: ${error}`);
        }
Deshui Yu's avatar
Deshui Yu committed
86
87
    }

88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
    /**
     * Generate gpu metric collector shell script in local machine,
     * used to run in remote machine, and will be deleted after uploaded from local.
     */
    private async runGpuMetricsCollectorScript(): Promise<void> {
        await cpp.exec(`mkdir -p ${this.gpuMetricCollectorScriptFolder}`);
        //generate gpu_metrics_collector.sh
        const gpuMetricsCollectorScriptPath: string = path.join(this.gpuMetricCollectorScriptFolder, 'gpu_metrics_collector.sh');
        const gpuMetricsCollectorScriptContent: string = String.Format(
            GPU_INFO_COLLECTOR_FORMAT,
            this.gpuMetricCollectorScriptFolder,
            path.join(this.gpuMetricCollectorScriptFolder, 'pid')
        );
        await fs.promises.writeFile(gpuMetricsCollectorScriptPath, gpuMetricsCollectorScriptContent, { encoding: 'utf8' });
        cp.exec(`bash ${gpuMetricsCollectorScriptPath}`);
    }

    private async updateGPUSummary(): Promise<void> {
        const cmdresult: cpp.childProcessPromise.Result =
            await cpp.exec(`tail -n 1 ${path.join(this.gpuMetricCollectorScriptFolder, 'gpu_metrics')}`);
        if (cmdresult && cmdresult.stdout) {
109
            this.gpuSummary = <GPUSummary>JSON.parse(cmdresult.stdout);
110
        } else {
111
            this.log.error('Could not get gpu metrics information!');
112
        }
Deshui Yu's avatar
Deshui Yu committed
113
114
115
116
    }
}

export { GPUScheduler };