gpuScheduler.ts 10.4 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 { randomSelect } from '../../common/utils';
9
10
import { GPUInfo, parseGpuIndices, ScheduleResultType } from '../common/gpuData';
import { ExecutorManager, RemoteMachineMeta, RemoteMachineScheduleResult, RemoteMachineTrialJobDetail } from './remoteMachineData';
Deshui Yu's avatar
Deshui Yu committed
11

chicm-ms's avatar
chicm-ms committed
12
13
type SCHEDULE_POLICY_NAME = 'random' | 'round-robin';

Deshui Yu's avatar
Deshui Yu committed
14
15
16
17
18
/**
 * A simple GPU scheduler implementation
 */
export class GPUScheduler {

19
    private readonly machineExecutorMap: Map<RemoteMachineMeta, ExecutorManager>;
20
    private readonly log: Logger = getLogger();
chicm-ms's avatar
chicm-ms committed
21
22
23
    private readonly policyName: SCHEDULE_POLICY_NAME = 'round-robin';
    private roundRobinIndex: number = 0;
    private configuredRMs: RemoteMachineMeta[] = [];
Deshui Yu's avatar
Deshui Yu committed
24
25
26

    /**
     * Constructor
27
     * @param machineExecutorMap map from remote machine to executor
Deshui Yu's avatar
Deshui Yu committed
28
     */
29
30
31
32
    constructor(machineExecutorMap: Map<RemoteMachineMeta, ExecutorManager>) {
        assert(machineExecutorMap.size > 0);
        this.machineExecutorMap = machineExecutorMap;
        this.configuredRMs = Array.from(machineExecutorMap.keys());
Deshui Yu's avatar
Deshui Yu committed
33
34
35
36
37
38
    }

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

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

59
60
61
62
        // 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
63
            const result: RemoteMachineScheduleResult | undefined = this.scheduleGPUHost(requiredGPUNum, trialJobDetail);
64
65
            if (result !== undefined) {
                return result;
Deshui Yu's avatar
Deshui Yu committed
66
            }
67
68
69
70
        } else {
            // Trail job does not need GPU
            const allocatedRm: RemoteMachineMeta = this.selectMachine(allRMs);

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

Deshui Yu's avatar
Deshui Yu committed
75
        return {
76
77
            resultType: ScheduleResultType.TMP_NO_AVAILABLE_GPU,
            scheduleInfo: undefined
Deshui Yu's avatar
Deshui Yu committed
78
79
80
        };
    }

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

108
    private scheduleGPUHost(requiredGPUNum: number, trialJobDetail: RemoteMachineTrialJobDetail): RemoteMachineScheduleResult | undefined {
109
110
111
112
113
114
115
116
117
118
119
        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
120
                return this.allocateHost(requiredGPUNum, allocatedRm, gpuInfos, trialJobDetail);
121
122
123
124
125
126
            } else {
                assert(false, 'gpuInfos is undefined');
            }
        }
    }

Deshui Yu's avatar
Deshui Yu committed
127
128
129
130
131
132
133
    /**
     * 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
     */
chicm-ms's avatar
chicm-ms committed
134
135
    private gpuResourceDetection(): Map<RemoteMachineMeta, GPUInfo[]> {
        const totalResourceMap: Map<RemoteMachineMeta, GPUInfo[]> = new Map<RemoteMachineMeta, GPUInfo[]>();
136
        this.machineExecutorMap.forEach((executorManager: ExecutorManager, rmMeta: RemoteMachineMeta) => {
Deshui Yu's avatar
Deshui Yu committed
137
            // Assgin totoal GPU count as init available GPU number
138
139
            if (rmMeta.gpuSummary !== undefined) {
                const availableGPUs: GPUInfo[] = [];
140
                const designatedGpuIndices: Set<number> | undefined = parseGpuIndices(rmMeta.gpuIndices);
141
142
143
144
145
146
147
                if (designatedGpuIndices !== undefined) {
                    for (const gpuIndex of designatedGpuIndices) {
                        if (gpuIndex >= rmMeta.gpuSummary.gpuCount) {
                            throw new Error(`Specified GPU index not found: ${gpuIndex}`);
                        }
                    }
                }
148
                this.log.debug(`designated gpu indices: ${designatedGpuIndices}`);
Deshui Yu's avatar
Deshui Yu committed
149
                rmMeta.gpuSummary.gpuInfos.forEach((gpuInfo: GPUInfo) => {
150
                    // if the GPU has active process, OR be reserved by a job,
151
                    // or index not in gpuIndices configuration in machineList,
152
                    // or trial number on a GPU reach max number,
Deshui Yu's avatar
Deshui Yu committed
153
                    // We should NOT allocate this GPU
154
155
                    // if users set useActiveGpu, use the gpu whether there is another activeProcess
                    if (designatedGpuIndices === undefined || designatedGpuIndices.has(gpuInfo.index)) {
156
157
158
159
                        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)) ||
160
                                (num !== undefined && num < maxTrialNumPerGpu)) {
161
162
163
164
165
                                availableGPUs.push(gpuInfo);
                            }
                        } else {
                            throw new Error(`occupiedGpuIndexMap initialize error!`);
                        }
Deshui Yu's avatar
Deshui Yu committed
166
167
168
169
170
171
172
173
                    }
                });
                totalResourceMap.set(rmMeta, availableGPUs);
            }
        });

        return totalResourceMap;
    }
174
175
176
177

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

chicm-ms's avatar
chicm-ms committed
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
        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];
193
194
195
196
197
198
199
200
    }

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

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

218
219
220
221
        return {
            resultType: ScheduleResultType.SUCCEED,
            scheduleInfo: {
                rmMeta: rmMeta,
chicm-ms's avatar
chicm-ms committed
222
                cudaVisibleDevice: allocatedGPUs
223
224
225
226
                    .map((gpuInfo: GPUInfo) => {
                        return gpuInfo.index;
                    })
                    .join(',')
227
228
229
            }
        };
    }
Deshui Yu's avatar
Deshui Yu committed
230
}