device_manager.py 15.2 KB
Newer Older
1
2
3
4
5
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

"""Device Managerment Library Utility."""

6
from typing import Optional
7
8
9

from superbench.common.utils import logger
from superbench.common.utils import process
10
11
12
13
14
from superbench.common.devices import GPU

gpu = GPU()
if gpu.vendor == 'nvidia' or gpu.vendor == 'nvidia-graphics':
    import py3nvml.py3nvml as nvml
one's avatar
one committed
15
elif gpu.vendor == 'amd' or gpu.vendor == 'amd-graphics' or gpu.vendor == 'hygon':
16
    import amdsmi as rocml
17
18
19


class DeviceManager:
20
    """Device management base module."""
21
22
23
    def __init__(self):
        """Constructor."""
        self._device_count = self.get_device_count()
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127

    def get_device_count(self):
        """Get the number of device.

        Return:
            count (int): count of device.
        """
        return 0

    def get_device_compute_capability(self):
        """Get the compute capability of device.

        Return:
            cap (float): the compute capability of device, None means failed to get the data.
        """
        return None

    def get_device_utilization(self, idx):
        """Get the utilization of device.

        Args:
            idx (int): device index.

        Return:
            util (int): the utilization of device, None means failed to get the data.
        """
        return None

    def get_device_temperature(self, idx):
        """Get the temperature of device, unit: celsius.

        Args:
            idx (int): device index.

        Return:
            temp (int): the temperature of device, None means failed to get the data.
        """
        return None

    def get_device_power(self, idx):
        """Get the realtime power of device, unit: watt.

        Args:
            idx (int): device index.

        Return:
            temp (int): the realtime power of device, None means failed to get the data.
        """
        return None

    def get_device_power_limit(self, idx):
        """Get the power management limit of device, unit: watt.

        Args:
            idx (int): device index.

        Return:
            temp (int): the power management limit of device, None means failed to get the data.
        """
        return None

    def get_device_memory(self, idx):
        """Get the memory information of device, unit: byte.

        Args:
            idx (int): device index.

        Return:
            used (int): the used device memory in bytes, None means failed to get the data.
            total (int): the total device memory in bytes, None means failed to get the data.
        """
        return None, None

    def get_device_row_remapped_info(self, idx):
        """Get the row remapped information of device.

        Args:
            idx (int): device index.

        Return:
            remapped_metrics (dict): the row remapped information, None means failed to get the data.
        """
        return None

    def get_device_ecc_error(self, idx):
        """Get the ecc error information of device.

        Args:
            idx (int): device index.

        Return:
            corrected_ecc (int)  : the count of single bit ecc error.
            uncorrected_ecc (int): the count of double bit ecc error.
        """
        return None, None


class NvidiaDeviceManager(DeviceManager):
    """Device management module for Nvidia."""
    def __init__(self):
        """Constructor."""
        nvml.nvmlInit()
        super().__init__()

128
129
130
131
        self._device_handlers = list()
        for i in range(self._device_count):
            self._device_handlers.append(nvml.nvmlDeviceGetHandleByIndex(i))

132
133
134
135
    def __del__(self):
        """Destructor."""
        nvml.nvmlShutdown()

136
    def get_device_count(self):
137
        """Get the number of device.
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152

        Return:
            count (int): count of device.
        """
        return nvml.nvmlDeviceGetCount()

    def get_device_compute_capability(self):
        """Get the compute capability of device.

        Return:
            cap (float): the compute capability of device, None means failed to get the data.
        """
        try:
            cap = nvml.nvmlDeviceGetCudaComputeCapability(self._device_handlers[0])
        except Exception as err:
153
            logger.warning('Get device compute capability failed: {}'.format(str(err)))
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
            return None
        return cap

    def get_device_utilization(self, idx):
        """Get the utilization of device.

        Args:
            idx (int): device index.

        Return:
            util (int): the utilization of device, None means failed to get the data.
        """
        try:
            util = nvml.nvmlDeviceGetUtilizationRates(self._device_handlers[idx])
        except Exception as err:
169
            logger.warning('Get device utilization failed: {}'.format(str(err)))
170
171
172
173
174
175
176
177
178
179
180
181
            return None
        return util.gpu

    def get_device_temperature(self, idx):
        """Get the temperature of device, unit: celsius.

        Args:
            idx (int): device index.

        Return:
            temp (int): the temperature of device, None means failed to get the data.
        """
182
        temp = None
183
184
185
        try:
            temp = nvml.nvmlDeviceGetTemperature(self._device_handlers[idx], nvml.NVML_TEMPERATURE_GPU)
        except Exception as err:
186
            logger.warning('Get device temperature failed: {}'.format(str(err)))
187
188
        return temp

189
190
191
192
193
194
195
    def get_device_power(self, idx):
        """Get the realtime power of device, unit: watt.

        Args:
            idx (int): device index.

        Return:
196
            temp (int): the realtime power of device, None means failed to get the data.
197
198
199
200
        """
        try:
            power = nvml.nvmlDeviceGetPowerUsage(self._device_handlers[idx])
        except Exception as err:
201
            logger.warning('Get device power failed: {}'.format(str(err)))
202
203
204
            return None
        return int(int(power) / 1000)

205
206
207
208
209
210
211
    def get_device_power_limit(self, idx):
        """Get the power management limit of device, unit: watt.

        Args:
            idx (int): device index.

        Return:
212
            temp (int): the power management limit of device, None means failed to get the data.
213
214
215
216
        """
        try:
            powerlimit = nvml.nvmlDeviceGetPowerManagementLimit(self._device_handlers[idx])
        except Exception as err:
217
            logger.warning('Get device power limitation failed: {}'.format(str(err)))
218
219
220
221
222
223
224
225
226
227
            return None
        return int(int(powerlimit) / 1000)

    def get_device_memory(self, idx):
        """Get the memory information of device, unit: byte.

        Args:
            idx (int): device index.

        Return:
228
229
            used (int): the used device memory in bytes, None means failed to get the data.
            total (int): the total device memory in bytes, None means failed to get the data.
230
231
232
233
        """
        try:
            mem = nvml.nvmlDeviceGetMemoryInfo(self._device_handlers[idx])
        except Exception as err:
234
            logger.warning('Get device memory failed: {}'.format(str(err)))
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
            return None, None
        return mem.used, mem.total

    def get_device_row_remapped_info(self, idx):
        """Get the row remapped information of device.

        The command 'nvidia-smi -i idx -q' contains the following output:
            Remapped Rows
                Correctable Error                 : 0
                Uncorrectable Error               : 0
                Pending                           : No
                Remapping Failure Occurred        : No
                Bank Remap Availability Histogram
                    Max                           : 640 bank(s)
                    High                          : 0 bank(s)
                    Partial                       : 0 bank(s)
                    Low                           : 0 bank(s)
                    None                          : 0 bank(s)
            Temperature
                GPU Current Temp                  : 36 C

        Args:
            idx (int): device index.

        Return:
            remapped_metrics (dict): the row remapped information, None means failed to get the data.
        """
262
        output = process.run_command('nvidia-smi -i {} -q'.format(idx), quiet=True)
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
        if output.returncode == 0:
            begin = output.stdout.find('Remapped Rows')
            end = output.stdout.find('Temperature', begin)
            if begin != -1 and end != -1:
                remapped_info = output.stdout[begin:end]
                remapped_info = remapped_info.split('\n')
                remapped_info = [item for item in remapped_info if ':' in item]
                remapped_metrics = dict()
                for item in remapped_info:
                    key_value = item.split(':')
                    key = 'gpu_remap_' + key_value[0].lower().strip().replace(' ', '_')
                    value = key_value[1].replace('bank(s)', '').strip()
                    try:
                        value = int(value)
                        remapped_metrics[key] = value
                    except Exception:
                        continue

                return remapped_metrics

        return None

    def get_device_ecc_error(self, idx):
        """Get the ecc error information of device.

        Args:
            idx (int): device index.

        Return:
            corrected_ecc (int)  : the count of single bit ecc error.
            uncorrected_ecc (int): the count of double bit ecc error.
        """
        corrected_ecc = 0
        uncorrected_ecc = 0
        for location_idx in range(nvml.NVML_MEMORY_LOCATION_COUNT):
            try:
                count = nvml.nvmlDeviceGetMemoryErrorCounter(
                    self._device_handlers[idx], nvml.NVML_MEMORY_ERROR_TYPE_CORRECTED, nvml.NVML_VOLATILE_ECC,
                    location_idx
                )
                corrected_ecc += count
            except nvml.NVMLError:
                pass
            except Exception as err:
307
                logger.warning('Get device ECC information failed: {}'.format(str(err)))
308
309
310
311
312
313
314
315
316
317
318
                return None, None

            try:
                count = nvml.nvmlDeviceGetMemoryErrorCounter(
                    self._device_handlers[idx], nvml.NVML_MEMORY_ERROR_TYPE_UNCORRECTED, nvml.NVML_VOLATILE_ECC,
                    location_idx
                )
                uncorrected_ecc += count
            except nvml.NVMLError:
                pass
            except Exception as err:
319
                logger.warning('Get device ECC information failed: {}'.format(str(err)))
320
321
322
323
324
                return None, None

        return corrected_ecc, uncorrected_ecc


325
326
327
328
class AmdDeviceManager(DeviceManager):
    """Device management module for AMD."""
    def __init__(self):
        """Constructor."""
329
330
        rocml.amdsmi_init()
        self._device_handlers = rocml.amdsmi_get_processor_handles()
331
332
333
334
        super().__init__()

    def __del__(self):
        """Destructor."""
335
        rocml.amdsmi_shut_down()
336
337
338
339
340
341
342

    def get_device_count(self):
        """Get the number of device.

        Return:
            count (int): count of device.
        """
343
        return len(self._device_handlers)
344
345
346
347
348
349
350
351
352
353
354

    def get_device_utilization(self, idx):
        """Get the utilization of device.

        Args:
            idx (int): device index.

        Return:
            util (int): the utilization of device, None means failed to get the data.
        """
        try:
355
            engine_usage = rocml.amdsmi_get_gpu_activity(self._device_handlers[idx])
356
        except Exception as err:
357
            logger.warning('Get device utilization failed: {}'.format(str(err)))
358
            return None
359
        return engine_usage['gfx_activity']
360
361
362
363
364
365
366
367
368
369

    def get_device_temperature(self, idx):
        """Get the temperature of device, unit: celsius.

        Args:
            idx (int): device index.

        Return:
            temp (int): the temperature of device, None means failed to get the data.
        """
370
        temp = None
371
372
373
374
375
376
377
378
379
        try:
            temp = rocml.amdsmi_get_temp_metric(
                self._device_handlers[idx], rocml.AmdSmiTemperatureType.EDGE, rocml.AmdSmiTemperatureMetric.CURRENT
            )
        except (rocml.AmdSmiLibraryException, rocml.AmdSmiParameterException):
            pass
        except Exception as err:
            logger.warning('Get device temperature failed: {}'.format(str(err)))
        return temp
380
381
382
383
384
385
386
387
388
389
390

    def get_device_power(self, idx):
        """Get the realtime power of device, unit: watt.

        Args:
            idx (int): device index.

        Return:
            temp (int): the realtime power of device, None means failed to get the data.
        """
        try:
391
            power_measure = rocml.amdsmi_get_power_info(self._device_handlers[idx])
392
        except Exception as err:
393
            logger.warning('Get device power failed: {}'.format(str(err)))
394
            return None
395
        return int(power_measure['average_socket_power'])
396
397
398
399
400
401
402
403
404
405

    def get_device_power_limit(self, idx):
        """Get the power management limit of device, unit: watt.

        Args:
            idx (int): device index.

        Return:
            temp (int): the power management limit of device, None means failed to get the data.
        """
406
407
408
409
410
411
        try:
            power_measure = rocml.amdsmi_get_power_info(self._device_handlers[idx])
        except Exception as err:
            logger.warning('Get device power limit failed: {}'.format(str(err)))
            return None
        return int(power_measure['power_limit'])
412
413
414
415
416
417
418
419
420
421
422
423

    def get_device_memory(self, idx):
        """Get the memory information of device, unit: byte.

        Args:
            idx (int): device index.

        Return:
            used (int): the used device memory in bytes, None means failed to get the data.
            total (int): the total device memory in bytes, None means failed to get the data.
        """
        try:
424
425
            mem_used = rocml.amdsmi_get_gpu_memory_usage(self._device_handlers[idx], rocml.AmdSmiMemoryType.VRAM)
            mem_total = rocml.amdsmi_get_gpu_memory_total(self._device_handlers[idx], rocml.AmdSmiMemoryType.VRAM)
426
        except Exception as err:
427
            logger.warning('Get device memory failed: {}'.format(str(err)))
428
429
430
431
432
433
434
435
436
437
438
439
440
            return None, None
        return mem_used, mem_total

    def get_device_ecc_error(self, idx):
        """Get the ecc error information of device.

        Args:
            idx (int): device index.

        Return:
            corrected_ecc (int)  : the count of single bit ecc error.
            uncorrected_ecc (int): the count of double bit ecc error.
        """
441
442
443
444
445
446
447
448
449
450
451
452
453
        corrected_ecc = 0
        uncorrected_ecc = 0
        for block in rocml.AmdSmiGpuBlock:
            try:
                ecc_count = rocml.amdsmi_get_gpu_ecc_count(self._device_handlers[idx], block)
                corrected_ecc += ecc_count['correctable_count']
                uncorrected_ecc += ecc_count['uncorrectable_count']
            except (rocml.AmdSmiLibraryException, rocml.AmdSmiParameterException):
                pass
            except Exception as err:
                logger.info('Get device ECC information failed: {}'.format(str(err)))

        return corrected_ecc, uncorrected_ecc
454
455
456
457
458


device_manager: Optional[DeviceManager] = DeviceManager()
if gpu.vendor == 'nvidia' or gpu.vendor == 'nvidia-graphics':
    device_manager = NvidiaDeviceManager()
one's avatar
one committed
459
elif gpu.vendor == 'amd' or gpu.vendor == 'amd-graphics' or gpu.vendor == 'hygon':
460
    device_manager = AmdDeviceManager()