gpuScheduler.ts 10.7 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 assert from 'assert';
Deshui Yu's avatar
Deshui Yu committed
7
import { getLogger, Logger } from '../../common/log';
8
import { TrialJobDetail } from '../../common/trainingService';
9
import { randomSelect } from '../../common/utils';
Deshui Yu's avatar
Deshui Yu committed
10
import { GPUInfo } from '../common/gpuData';
11
12
13
import {
    parseGpuIndices, RemoteMachineMeta, RemoteMachineScheduleResult, RemoteMachineTrialJobDetail, ScheduleResultType, SSHClientManager
} from './remoteMachineData';
Deshui Yu's avatar
Deshui Yu committed
14

chicm-ms's avatar
chicm-ms committed
15
16
type SCHEDULE_POLICY_NAME = 'random' | 'round-robin';

Deshui Yu's avatar
Deshui Yu committed
17
18
19
20
21
/**
 * A simple GPU scheduler implementation
 */
export class GPUScheduler {

SparkSnail's avatar
SparkSnail committed
22
    private readonly machineSSHClientMap : Map<RemoteMachineMeta, SSHClientManager>;
23
    private readonly log: Logger = getLogger();
chicm-ms's avatar
chicm-ms committed
24
25
26
    private readonly policyName: SCHEDULE_POLICY_NAME = 'round-robin';
    private roundRobinIndex: number = 0;
    private configuredRMs: RemoteMachineMeta[] = [];
Deshui Yu's avatar
Deshui Yu committed
27
28
29
30
31

    /**
     * Constructor
     * @param machineSSHClientMap map from remote machine to sshClient
     */
SparkSnail's avatar
SparkSnail committed
32
    constructor(machineSSHClientMap : Map<RemoteMachineMeta, SSHClientManager>) {
chicm-ms's avatar
chicm-ms committed
33
        assert(machineSSHClientMap.size > 0);
Deshui Yu's avatar
Deshui Yu committed
34
        this.machineSSHClientMap = machineSSHClientMap;
chicm-ms's avatar
chicm-ms committed
35
        this.configuredRMs = Array.from(machineSSHClientMap.keys());
Deshui Yu's avatar
Deshui Yu committed
36
37
38
39
40
41
    }

    /**
     * Schedule a machine according to the constraints (requiredGPUNum)
     * @param requiredGPUNum required GPU number
     */
SparkSnail's avatar
SparkSnail committed
42
43
44
45
    public scheduleMachine(requiredGPUNum: number | undefined, trialJobDetail : RemoteMachineTrialJobDetail) : RemoteMachineScheduleResult {
        if(requiredGPUNum === undefined) {
            requiredGPUNum = 0;
        }
46
47
48
49
50
51
        assert(requiredGPUNum >= 0);
        const allRMs: RemoteMachineMeta[] = Array.from(this.machineSSHClientMap.keys());
        assert(allRMs.length > 0);

        // Step 1: Check if required GPU number not exceeds the total GPU number in all machines
        const eligibleRM: RemoteMachineMeta[] = allRMs.filter((rmMeta : RemoteMachineMeta) =>
SparkSnail's avatar
SparkSnail committed
52
                 rmMeta.gpuSummary === undefined || requiredGPUNum === 0 || (requiredGPUNum !== undefined && rmMeta.gpuSummary.gpuCount >= requiredGPUNum));
53
        if (eligibleRM.length === 0) {
Deshui Yu's avatar
Deshui Yu committed
54
55
56
            // If the required gpu number exceeds the upper limit of all machine's GPU number
            // Return REQUIRE_EXCEED_TOTAL directly
            return ({
57
58
                resultType: ScheduleResultType.REQUIRE_EXCEED_TOTAL,
                scheduleInfo: undefined
Deshui Yu's avatar
Deshui Yu committed
59
60
61
            });
        }

62
63
64
65
        // Step 2: Allocate Host/GPU for specified trial job
        // Currenty the requireGPUNum parameter for all trial jobs are identical.
        if (requiredGPUNum > 0) {
            // Trial job requires GPU
66
            const result: RemoteMachineScheduleResult | undefined = this.scheduleGPUHost(requiredGPUNum, trialJobDetail);
67
68
            if (result !== undefined) {
                return result;
Deshui Yu's avatar
Deshui Yu committed
69
            }
70
71
72
73
        } else {
            // Trail job does not need GPU
            const allocatedRm: RemoteMachineMeta = this.selectMachine(allRMs);

74
            return this.allocateHost(requiredGPUNum, allocatedRm, [], trialJobDetail);
75
        }
76
        this.log.warning(`Scheduler: trialJob id ${trialJobDetail.id}, no machine can be scheduled, return TMP_NO_AVAILABLE_GPU `);
77

Deshui Yu's avatar
Deshui Yu committed
78
79
80
81
82
83
        return {
            resultType : ScheduleResultType.TMP_NO_AVAILABLE_GPU,
            scheduleInfo : undefined
        };
    }

84
85
86
    /**
     * remove the job's gpu reversion
     */
87
    public removeGpuReservation(trialJobId: string, trialJobMap: Map<string, RemoteMachineTrialJobDetail>): void {
88
89
        const trialJobDetail: RemoteMachineTrialJobDetail | undefined = trialJobMap.get(trialJobId);
        if (trialJobDetail === undefined) {
90
            throw new Error(`could not get trialJobDetail by id ${trialJobId}`);
91
92
93
94
        }
        if (trialJobDetail.rmMeta !== undefined &&
            trialJobDetail.rmMeta.occupiedGpuIndexMap !== undefined &&
            trialJobDetail.gpuIndices !== undefined &&
95
96
            trialJobDetail.gpuIndices.length > 0) {
            for (const gpuInfo of trialJobDetail.gpuIndices) {
97
98
99
                const num: number | undefined = trialJobDetail.rmMeta.occupiedGpuIndexMap.get(gpuInfo.index);
                if (num !== undefined) {
                    if (num === 1) {
100
101
                        trialJobDetail.rmMeta.occupiedGpuIndexMap.delete(gpuInfo.index);
                    } else {
102
                        trialJobDetail.rmMeta.occupiedGpuIndexMap.set(gpuInfo.index, num - 1);
103
                    }
104
                }
105
            }
106
        }
107
108
        trialJobDetail.gpuIndices = [];
        trialJobMap.set(trialJobId, trialJobDetail);
109
110
    }

111
    private scheduleGPUHost(requiredGPUNum: number, trialJobDetail: RemoteMachineTrialJobDetail): RemoteMachineScheduleResult | undefined {
112
113
114
115
116
117
118
119
120
121
122
        const totalResourceMap: Map<RemoteMachineMeta, GPUInfo[]> = this.gpuResourceDetection();
        const qualifiedRMs: RemoteMachineMeta[] = [];
        totalResourceMap.forEach((gpuInfos: GPUInfo[], rmMeta: RemoteMachineMeta) => {
            if (gpuInfos !== undefined && gpuInfos.length >= requiredGPUNum) {
                qualifiedRMs.push(rmMeta);
            }
        });
        if (qualifiedRMs.length > 0) {
            const allocatedRm: RemoteMachineMeta = this.selectMachine(qualifiedRMs);
            const gpuInfos: GPUInfo[] | undefined = totalResourceMap.get(allocatedRm);
            if (gpuInfos !== undefined) { // should always true
123
                return this.allocateHost(requiredGPUNum, allocatedRm, gpuInfos, trialJobDetail);
124
125
126
127
128
129
            } else {
                assert(false, 'gpuInfos is undefined');
            }
        }
    }

Deshui Yu's avatar
Deshui Yu committed
130
131
132
133
134
135
136
    /**
     * Detect available GPU resource for a remote machine
     * @param rmMeta Remote machine metadata
     * @param requiredGPUNum required GPU number by application
     * @param availableGPUMap available GPU resource filled by this detection
     * @returns Available GPU number on this remote machine
     */
137
    private gpuResourceDetection() : Map<RemoteMachineMeta, GPUInfo[]> {
Deshui Yu's avatar
Deshui Yu committed
138
        const totalResourceMap : Map<RemoteMachineMeta, GPUInfo[]> = new Map<RemoteMachineMeta, GPUInfo[]>();
SparkSnail's avatar
SparkSnail committed
139
        this.machineSSHClientMap.forEach((sshClientManager: SSHClientManager, rmMeta: RemoteMachineMeta) => {
Deshui Yu's avatar
Deshui Yu committed
140
            // Assgin totoal GPU count as init available GPU number
141
142
            if (rmMeta.gpuSummary !== undefined) {
                const availableGPUs: GPUInfo[] = [];
143
                const designatedGpuIndices: Set<number> | undefined = parseGpuIndices(rmMeta.gpuIndices);
144
145
146
147
148
149
150
                if (designatedGpuIndices !== undefined) {
                    for (const gpuIndex of designatedGpuIndices) {
                        if (gpuIndex >= rmMeta.gpuSummary.gpuCount) {
                            throw new Error(`Specified GPU index not found: ${gpuIndex}`);
                        }
                    }
                }
151
                this.log.debug(`designated gpu indices: ${designatedGpuIndices}`);
152
                // tslint:disable: strict-boolean-expressions
Deshui Yu's avatar
Deshui Yu committed
153
                rmMeta.gpuSummary.gpuInfos.forEach((gpuInfo: GPUInfo) => {
154
                    // if the GPU has active process, OR be reserved by a job,
155
                    // or index not in gpuIndices configuration in machineList,
156
                    // or trial number on a GPU reach max number,
Deshui Yu's avatar
Deshui Yu committed
157
                    // We should NOT allocate this GPU
158
159
                    // if users set useActiveGpu, use the gpu whether there is another activeProcess
                    if (designatedGpuIndices === undefined || designatedGpuIndices.has(gpuInfo.index)) {
160
161
162
163
                        if (rmMeta.occupiedGpuIndexMap !== undefined) {
                            const num: number | undefined = rmMeta.occupiedGpuIndexMap.get(gpuInfo.index);
                            const maxTrialNumPerGpu: number = rmMeta.maxTrialNumPerGpu ? rmMeta.maxTrialNumPerGpu : 1;
                            if ((num === undefined && (!rmMeta.useActiveGpu && gpuInfo.activeProcessNum === 0 || rmMeta.useActiveGpu)) ||
164
165
166
167
168
169
                               (num !== undefined && num < maxTrialNumPerGpu)) {
                                availableGPUs.push(gpuInfo);
                            }
                        } else {
                            throw new Error(`occupiedGpuIndexMap initialize error!`);
                        }
Deshui Yu's avatar
Deshui Yu committed
170
171
172
173
174
175
176
177
                    }
                });
                totalResourceMap.set(rmMeta, availableGPUs);
            }
        });

        return totalResourceMap;
    }
178
    // tslint:enable: strict-boolean-expressions
179
180
181
182

    private selectMachine(rmMetas: RemoteMachineMeta[]): RemoteMachineMeta {
        assert(rmMetas !== undefined && rmMetas.length > 0);

chicm-ms's avatar
chicm-ms committed
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
        if (this.policyName === 'random') {
            return randomSelect(rmMetas);
        } else if (this.policyName === 'round-robin') {
            return this.roundRobinSelect(rmMetas);
        } else {
            throw new Error(`Unsupported schedule policy: ${this.policyName}`);
        }
    }

    private roundRobinSelect(rmMetas: RemoteMachineMeta[]): RemoteMachineMeta {
        while (!rmMetas.includes(this.configuredRMs[this.roundRobinIndex % this.configuredRMs.length])) {
            this.roundRobinIndex++;
        }

        return this.configuredRMs[this.roundRobinIndex++ % this.configuredRMs.length];
198
199
200
201
202
203
204
205
    }

    private selectGPUsForTrial(gpuInfos: GPUInfo[], requiredGPUNum: number): GPUInfo[] {
        // Sequentially allocate GPUs
        return gpuInfos.slice(0, requiredGPUNum);
    }

    private allocateHost(requiredGPUNum: number, rmMeta: RemoteMachineMeta,
206
                         gpuInfos: GPUInfo[], trialJobDetail: RemoteMachineTrialJobDetail): RemoteMachineScheduleResult {
207
208
209
        assert(gpuInfos.length >= requiredGPUNum);
        const allocatedGPUs: GPUInfo[] = this.selectGPUsForTrial(gpuInfos, requiredGPUNum);
        allocatedGPUs.forEach((gpuInfo: GPUInfo) => {
210
211
212
            if (rmMeta.occupiedGpuIndexMap !== undefined) {
                let num: number | undefined = rmMeta.occupiedGpuIndexMap.get(gpuInfo.index);
                if (num === undefined) {
213
214
215
                    num = 0;
                }
                rmMeta.occupiedGpuIndexMap.set(gpuInfo.index, num + 1);
216
            } else {
217
218
                throw new Error(`Machine ${rmMeta.ip} occupiedGpuIndexMap initialize error!`);
            }
219
        });
220
221
        trialJobDetail.gpuIndices = allocatedGPUs;
        trialJobDetail.rmMeta = rmMeta;
222

223
224
225
226
        return {
            resultType: ScheduleResultType.SUCCEED,
            scheduleInfo: {
                rmMeta: rmMeta,
227
228
229
230
231
                cuda_visible_device: allocatedGPUs
                                       .map((gpuInfo: GPUInfo) => {
                                            return gpuInfo.index;
                                        })
                                       .join(',')
232
233
234
            }
        };
    }
Deshui Yu's avatar
Deshui Yu committed
235
}