gpuScheduler.ts 4.88 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, runGpuMetricsCollector } 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()}/${os.userInfo().username}/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
            if (this.gpuSummary !== undefined && this.gpuSummary.gpuCount === 0) {
                throw new Error('GPU not available. Please check your CUDA configuration');
            }
Deshui Yu's avatar
Deshui Yu committed
60
61
62
63
            await delay(5000);
        }
    }

64
    public getAvailableGPUIndices(useActiveGpu: boolean, occupiedGpuIndexNumMap: Map<number, number>): number[] {
Deshui Yu's avatar
Deshui Yu committed
65
        if (this.gpuSummary !== undefined) {
66
            if (process.platform === 'win32' || useActiveGpu) {
demianzhang's avatar
demianzhang committed
67
                return this.gpuSummary.gpuInfos.map((info: GPUInfo) => info.index);
68
69
70
71
72
            } 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
73
            }
Deshui Yu's avatar
Deshui Yu committed
74
75
76
77
78
        }

        return [];
    }

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

98
99
100
101
102
    /**
     * 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> {
103
        await execMkdir(this.gpuMetricCollectorScriptFolder, true);
104
        runGpuMetricsCollector(this.gpuMetricCollectorScriptFolder);
105
106
107
    }

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

export { GPUScheduler };