gpuScheduler.ts 11.8 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 assert from 'assert';
Deshui Yu's avatar
Deshui Yu committed
23
import { getLogger, Logger } from '../../common/log';
24
import { TrialJobDetail } from '../../common/trainingService';
25
import { randomSelect } from '../../common/utils';
Deshui Yu's avatar
Deshui Yu committed
26
import { GPUInfo } from '../common/gpuData';
27
28
29
import {
    parseGpuIndices, RemoteMachineMeta, RemoteMachineScheduleResult, RemoteMachineTrialJobDetail, ScheduleResultType, SSHClientManager
} from './remoteMachineData';
Deshui Yu's avatar
Deshui Yu committed
30

chicm-ms's avatar
chicm-ms committed
31
32
type SCHEDULE_POLICY_NAME = 'random' | 'round-robin';

Deshui Yu's avatar
Deshui Yu committed
33
34
35
36
37
/**
 * A simple GPU scheduler implementation
 */
export class GPUScheduler {

SparkSnail's avatar
SparkSnail committed
38
    private readonly machineSSHClientMap : Map<RemoteMachineMeta, SSHClientManager>;
39
    private readonly log: Logger = getLogger();
chicm-ms's avatar
chicm-ms committed
40
41
42
    private readonly policyName: SCHEDULE_POLICY_NAME = 'round-robin';
    private roundRobinIndex: number = 0;
    private configuredRMs: RemoteMachineMeta[] = [];
Deshui Yu's avatar
Deshui Yu committed
43
44
45
46
47

    /**
     * Constructor
     * @param machineSSHClientMap map from remote machine to sshClient
     */
SparkSnail's avatar
SparkSnail committed
48
    constructor(machineSSHClientMap : Map<RemoteMachineMeta, SSHClientManager>) {
chicm-ms's avatar
chicm-ms committed
49
        assert(machineSSHClientMap.size > 0);
Deshui Yu's avatar
Deshui Yu committed
50
        this.machineSSHClientMap = machineSSHClientMap;
chicm-ms's avatar
chicm-ms committed
51
        this.configuredRMs = Array.from(machineSSHClientMap.keys());
Deshui Yu's avatar
Deshui Yu committed
52
53
54
55
56
57
    }

    /**
     * Schedule a machine according to the constraints (requiredGPUNum)
     * @param requiredGPUNum required GPU number
     */
SparkSnail's avatar
SparkSnail committed
58
59
60
61
    public scheduleMachine(requiredGPUNum: number | undefined, trialJobDetail : RemoteMachineTrialJobDetail) : RemoteMachineScheduleResult {
        if(requiredGPUNum === undefined) {
            requiredGPUNum = 0;
        }
62
63
64
65
66
67
        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
68
                 rmMeta.gpuSummary === undefined || requiredGPUNum === 0 || (requiredGPUNum !== undefined && rmMeta.gpuSummary.gpuCount >= requiredGPUNum));
69
        if (eligibleRM.length === 0) {
Deshui Yu's avatar
Deshui Yu committed
70
71
72
            // If the required gpu number exceeds the upper limit of all machine's GPU number
            // Return REQUIRE_EXCEED_TOTAL directly
            return ({
73
74
                resultType: ScheduleResultType.REQUIRE_EXCEED_TOTAL,
                scheduleInfo: undefined
Deshui Yu's avatar
Deshui Yu committed
75
76
77
            });
        }

78
79
80
81
        // 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
82
            const result: RemoteMachineScheduleResult | undefined = this.scheduleGPUHost(requiredGPUNum, trialJobDetail);
83
84
            if (result !== undefined) {
                return result;
Deshui Yu's avatar
Deshui Yu committed
85
            }
86
87
88
89
        } else {
            // Trail job does not need GPU
            const allocatedRm: RemoteMachineMeta = this.selectMachine(allRMs);

90
            return this.allocateHost(requiredGPUNum, allocatedRm, [], trialJobDetail);
91
        }
92
        this.log.warning(`Scheduler: trialJob id ${trialJobDetail.id}, no machine can be scheduled, return TMP_NO_AVAILABLE_GPU `);
93

Deshui Yu's avatar
Deshui Yu committed
94
95
96
97
98
99
        return {
            resultType : ScheduleResultType.TMP_NO_AVAILABLE_GPU,
            scheduleInfo : undefined
        };
    }

100
101
102
    /**
     * remove the job's gpu reversion
     */
103
    public removeGpuReservation(trialJobId: string, trialJobMap: Map<string, RemoteMachineTrialJobDetail>): void {
104
105
        const trialJobDetail: RemoteMachineTrialJobDetail | undefined = trialJobMap.get(trialJobId);
        if (trialJobDetail === undefined) {
106
            throw new Error(`could not get trialJobDetail by id ${trialJobId}`);
107
108
109
110
        }
        if (trialJobDetail.rmMeta !== undefined &&
            trialJobDetail.rmMeta.occupiedGpuIndexMap !== undefined &&
            trialJobDetail.gpuIndices !== undefined &&
111
112
            trialJobDetail.gpuIndices.length > 0) {
            for (const gpuInfo of trialJobDetail.gpuIndices) {
113
114
115
                const num: number | undefined = trialJobDetail.rmMeta.occupiedGpuIndexMap.get(gpuInfo.index);
                if (num !== undefined) {
                    if (num === 1) {
116
117
                        trialJobDetail.rmMeta.occupiedGpuIndexMap.delete(gpuInfo.index);
                    } else {
118
                        trialJobDetail.rmMeta.occupiedGpuIndexMap.set(gpuInfo.index, num - 1);
119
                    }
120
                }
121
            }
122
        }
123
124
        trialJobDetail.gpuIndices = [];
        trialJobMap.set(trialJobId, trialJobDetail);
125
126
    }

127
    private scheduleGPUHost(requiredGPUNum: number, trialJobDetail: RemoteMachineTrialJobDetail): RemoteMachineScheduleResult | undefined {
128
129
130
131
132
133
134
135
136
137
138
        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
139
                return this.allocateHost(requiredGPUNum, allocatedRm, gpuInfos, trialJobDetail);
140
141
142
143
144
145
            } else {
                assert(false, 'gpuInfos is undefined');
            }
        }
    }

Deshui Yu's avatar
Deshui Yu committed
146
147
148
149
150
151
152
    /**
     * 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
     */
153
    private gpuResourceDetection() : Map<RemoteMachineMeta, GPUInfo[]> {
Deshui Yu's avatar
Deshui Yu committed
154
        const totalResourceMap : Map<RemoteMachineMeta, GPUInfo[]> = new Map<RemoteMachineMeta, GPUInfo[]>();
SparkSnail's avatar
SparkSnail committed
155
        this.machineSSHClientMap.forEach((sshClientManager: SSHClientManager, rmMeta: RemoteMachineMeta) => {
Deshui Yu's avatar
Deshui Yu committed
156
            // Assgin totoal GPU count as init available GPU number
157
158
            if (rmMeta.gpuSummary !== undefined) {
                const availableGPUs: GPUInfo[] = [];
159
                const designatedGpuIndices: Set<number> | undefined = parseGpuIndices(rmMeta.gpuIndices);
160
161
162
163
164
165
166
                if (designatedGpuIndices !== undefined) {
                    for (const gpuIndex of designatedGpuIndices) {
                        if (gpuIndex >= rmMeta.gpuSummary.gpuCount) {
                            throw new Error(`Specified GPU index not found: ${gpuIndex}`);
                        }
                    }
                }
167
                this.log.debug(`designated gpu indices: ${designatedGpuIndices}`);
168
                // tslint:disable: strict-boolean-expressions
Deshui Yu's avatar
Deshui Yu committed
169
                rmMeta.gpuSummary.gpuInfos.forEach((gpuInfo: GPUInfo) => {
170
                    // if the GPU has active process, OR be reserved by a job,
171
                    // or index not in gpuIndices configuration in machineList,
172
                    // or trial number on a GPU reach max number,
Deshui Yu's avatar
Deshui Yu committed
173
                    // We should NOT allocate this GPU
174
175
                    // if users set useActiveGpu, use the gpu whether there is another activeProcess
                    if (designatedGpuIndices === undefined || designatedGpuIndices.has(gpuInfo.index)) {
176
177
178
179
                        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)) ||
180
181
182
183
184
185
                               (num !== undefined && num < maxTrialNumPerGpu)) {
                                availableGPUs.push(gpuInfo);
                            }
                        } else {
                            throw new Error(`occupiedGpuIndexMap initialize error!`);
                        }
Deshui Yu's avatar
Deshui Yu committed
186
187
188
189
190
191
192
193
                    }
                });
                totalResourceMap.set(rmMeta, availableGPUs);
            }
        });

        return totalResourceMap;
    }
194
    // tslint:enable: strict-boolean-expressions
195
196
197
198

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

chicm-ms's avatar
chicm-ms committed
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
        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];
214
215
216
217
218
219
220
221
    }

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

    private allocateHost(requiredGPUNum: number, rmMeta: RemoteMachineMeta,
222
                         gpuInfos: GPUInfo[], trialJobDetail: RemoteMachineTrialJobDetail): RemoteMachineScheduleResult {
223
224
225
        assert(gpuInfos.length >= requiredGPUNum);
        const allocatedGPUs: GPUInfo[] = this.selectGPUsForTrial(gpuInfos, requiredGPUNum);
        allocatedGPUs.forEach((gpuInfo: GPUInfo) => {
226
227
228
            if (rmMeta.occupiedGpuIndexMap !== undefined) {
                let num: number | undefined = rmMeta.occupiedGpuIndexMap.get(gpuInfo.index);
                if (num === undefined) {
229
230
231
                    num = 0;
                }
                rmMeta.occupiedGpuIndexMap.set(gpuInfo.index, num + 1);
232
            } else {
233
234
                throw new Error(`Machine ${rmMeta.ip} occupiedGpuIndexMap initialize error!`);
            }
235
        });
236
237
        trialJobDetail.gpuIndices = allocatedGPUs;
        trialJobDetail.rmMeta = rmMeta;
238

239
240
241
242
        return {
            resultType: ScheduleResultType.SUCCEED,
            scheduleInfo: {
                rmMeta: rmMeta,
243
244
245
246
247
                cuda_visible_device: allocatedGPUs
                                       .map((gpuInfo: GPUInfo) => {
                                            return gpuInfo.index;
                                        })
                                       .join(',')
248
249
250
            }
        };
    }
Deshui Yu's avatar
Deshui Yu committed
251
}