gpuScheduler.ts 5.13 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
import { getLogger, Logger } from '../../common/log';
import { delay } from '../../common/utils';
30
import { GPUInfo, GPUSummary } from '../common/gpuData';
31
import { execKill, execMkdir, execRemove, execTail, getgpuMetricsCollectorScriptContent, getScriptName, runScript } from '../common/util';
Deshui Yu's avatar
Deshui Yu committed
32
33

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

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

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

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

61
    public getAvailableGPUIndices(useActiveGpu: boolean, occupiedGpuIndexNumMap: Map<number, number>): number[] {
Deshui Yu's avatar
Deshui Yu committed
62
        if (this.gpuSummary !== undefined) {
63
            if (process.platform === 'win32' || useActiveGpu) {
demianzhang's avatar
demianzhang committed
64
                return this.gpuSummary.gpuInfos.map((info: GPUInfo) => info.index);
65
66
67
68
69
            } else {
                return this.gpuSummary.gpuInfos.filter((info: GPUInfo) =>
                         occupiedGpuIndexNumMap.get(info.index) === undefined && info.activeProcessNum === 0 ||
                         occupiedGpuIndexNumMap.get(info.index) !== undefined)
                       .map((info: GPUInfo) => info.index);
demianzhang's avatar
demianzhang committed
70
            }
Deshui Yu's avatar
Deshui Yu committed
71
72
73
74
75
        }

        return [];
    }

76
77
78
79
80
81
82
83
84
    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
85
        this.stopping = true;
86
87
        try {
            const pid: string = await fs.promises.readFile(path.join(this.gpuMetricCollectorScriptFolder, 'pid'), 'utf8');
88
89
            await execKill(pid);
            await execRemove(this.gpuMetricCollectorScriptFolder);
90
        } catch (error) {
91
92
            this.log.error(`GPU scheduler error: ${error}`);
        }
Deshui Yu's avatar
Deshui Yu committed
93
94
    }

95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
    /**
     * 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 execMkdir(this.gpuMetricCollectorScriptFolder);
        //generate gpu_metrics_collector script
        const gpuMetricsCollectorScriptPath: string =
            path.join(this.gpuMetricCollectorScriptFolder, getScriptName('gpu_metrics_collector'));
        const gpuMetricsCollectorScriptContent: string = getgpuMetricsCollectorScriptContent(this.gpuMetricCollectorScriptFolder);
        await fs.promises.writeFile(gpuMetricsCollectorScriptPath, gpuMetricsCollectorScriptContent, { encoding: 'utf8' });
        runScript(gpuMetricsCollectorScriptPath);
    }

    // tslint:disable:non-literal-fs-path
110
    private async updateGPUSummary(): Promise<void> {
111
        const gpuMetricPath: string = path.join(this.gpuMetricCollectorScriptFolder, 'gpu_metrics');
112
113
        if (fs.existsSync(gpuMetricPath)) {
            const cmdresult: cpp.childProcessPromise.Result = await execTail(gpuMetricPath);
114
            if (cmdresult !== undefined && cmdresult.stdout !== undefined) {
115
116
117
118
                this.gpuSummary = <GPUSummary>JSON.parse(cmdresult.stdout);
            } else {
                this.log.error('Could not get gpu metrics information!');
            }
119
120
        } else {
            this.log.warning('gpu_metrics file does not exist!');
121
        }
Deshui Yu's avatar
Deshui Yu committed
122
123
124
125
    }
}

export { GPUScheduler };