gpuScheduler.ts 3.84 KB
Newer Older
liuzhe-lz's avatar
liuzhe-lz committed
1
2
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
Deshui Yu's avatar
Deshui Yu committed
3
4
5

'use strict';

6
import * as cpp from 'child-process-promise';
7
import * as cp from 'child_process';
8
import * as fs from 'fs';
9
10
import * as os from 'os';
import * as path from 'path';
11
import { String } from 'typescript-string-operations';
12
13
import { getLogger, Logger } from '../../common/log';
import { delay } from '../../common/utils';
14
import { GPUInfo, GPUSummary } from '../common/gpuData';
15
import { execKill, execMkdir, execRemove, execTail, runGpuMetricsCollector } from '../common/util';
Deshui Yu's avatar
Deshui Yu committed
16
17

/**
18
 * GPUScheduler for local training service
Deshui Yu's avatar
Deshui Yu committed
19
20
21
22
23
 */
class GPUScheduler {

    private gpuSummary!: GPUSummary;
    private stopping: boolean;
24
25
    private readonly log: Logger;
    private readonly gpuMetricCollectorScriptFolder: string;
Deshui Yu's avatar
Deshui Yu committed
26
27
28

    constructor() {
        this.stopping = false;
29
        this.log = getLogger();
30
        this.gpuMetricCollectorScriptFolder = `${os.tmpdir()}/${os.userInfo().username}/nni/script`;
Deshui Yu's avatar
Deshui Yu committed
31
32
33
    }

    public async run(): Promise<void> {
34
        await this.runGpuMetricsCollectorScript();
Deshui Yu's avatar
Deshui Yu committed
35
36
        while (!this.stopping) {
            try {
37
                await this.updateGPUSummary();
Deshui Yu's avatar
Deshui Yu committed
38
            } catch (error) {
39
                this.log.error('Read GPU summary failed with error: ', error);
Deshui Yu's avatar
Deshui Yu committed
40
            }
41
42
43
            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
44
45
46
47
            await delay(5000);
        }
    }

48
    public getAvailableGPUIndices(useActiveGpu: boolean, occupiedGpuIndexNumMap: Map<number, number>): number[] {
Deshui Yu's avatar
Deshui Yu committed
49
        if (this.gpuSummary !== undefined) {
50
            if (process.platform === 'win32' || useActiveGpu) {
demianzhang's avatar
demianzhang committed
51
                return this.gpuSummary.gpuInfos.map((info: GPUInfo) => info.index);
52
53
54
55
56
            } 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
57
            }
Deshui Yu's avatar
Deshui Yu committed
58
59
60
61
62
        }

        return [];
    }

63
64
65
66
67
68
69
70
71
    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
72
        this.stopping = true;
73
74
        try {
            const pid: string = await fs.promises.readFile(path.join(this.gpuMetricCollectorScriptFolder, 'pid'), 'utf8');
75
76
            await execKill(pid);
            await execRemove(this.gpuMetricCollectorScriptFolder);
77
        } catch (error) {
78
79
            this.log.error(`GPU scheduler error: ${error}`);
        }
Deshui Yu's avatar
Deshui Yu committed
80
81
    }

82
83
84
85
86
    /**
     * 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> {
87
        await execMkdir(this.gpuMetricCollectorScriptFolder, true);
88
        runGpuMetricsCollector(this.gpuMetricCollectorScriptFolder);
89
90
91
    }

    // tslint:disable:non-literal-fs-path
92
    private async updateGPUSummary(): Promise<void> {
93
        const gpuMetricPath: string = path.join(this.gpuMetricCollectorScriptFolder, 'gpu_metrics');
94
95
        if (fs.existsSync(gpuMetricPath)) {
            const cmdresult: cpp.childProcessPromise.Result = await execTail(gpuMetricPath);
96
            if (cmdresult !== undefined && cmdresult.stdout !== undefined) {
97
98
99
100
                this.gpuSummary = <GPUSummary>JSON.parse(cmdresult.stdout);
            } else {
                this.log.error('Could not get gpu metrics information!');
            }
101
102
        } else {
            this.log.warning('gpu_metrics file does not exist!');
103
        }
Deshui Yu's avatar
Deshui Yu committed
104
105
106
107
    }
}

export { GPUScheduler };