gpu_metrics_collector.py 4.61 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
22
23
#!/usr/bin/python
# 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.

import json
import os
import subprocess
import sys
import time
24
import traceback
Deshui Yu's avatar
Deshui Yu committed
25
26
27
28

from xml.dom import minidom

def check_ready_to_run():
29
    if sys.platform == 'win32':
chicm-ms's avatar
chicm-ms committed
30
31
        pgrep_output = subprocess.check_output(
            'wmic process where "CommandLine like \'%nni_gpu_tool.gpu_metrics_collector%\' and name like \'%python%\'" get processId')
32
33
34
35
        pidList = pgrep_output.decode("utf-8").strip().split()
        pidList.pop(0) # remove the key word 'ProcessId'
        pidList = list(map(int, pidList))
        pidList.remove(os.getpid())
chicm-ms's avatar
chicm-ms committed
36
        return not pidList
37
    else:
38
        pgrep_output = subprocess.check_output('pgrep -fxu "$(whoami)" \'python3 -m nni_gpu_tool.gpu_metrics_collector\'', shell=True)
39
40
41
42
        pidList = []
        for pid in pgrep_output.splitlines():
            pidList.append(int(pid))
        pidList.remove(os.getpid())
chicm-ms's avatar
chicm-ms committed
43
        return not pidList
Deshui Yu's avatar
Deshui Yu committed
44
45

def main(argv):
SparkSnail's avatar
SparkSnail committed
46
    metrics_output_dir = os.environ['METRIC_OUTPUT_DIR']
Deshui Yu's avatar
Deshui Yu committed
47
48
49
    if check_ready_to_run() == False:
        # GPU metrics collector is already running. Exit
        exit(2)
50
    cmd = 'nvidia-smi -q -x'.split()
Deshui Yu's avatar
Deshui Yu committed
51
52
    while(True):
        try:
53
54
55
56
57
58
            smi_output = subprocess.check_output(cmd)
        except Exception:
            traceback.print_exc()
            gen_empty_gpu_metric(metrics_output_dir)
            break
        parse_nvidia_smi_result(smi_output, metrics_output_dir)
Deshui Yu's avatar
Deshui Yu committed
59
60
61
62
63
        # TODO: change to sleep time configurable via arguments
        time.sleep(5)

def parse_nvidia_smi_result(smi, outputDir):
    try:
64
        old_umask = os.umask(0)
Deshui Yu's avatar
Deshui Yu committed
65
66
67
68
69
70
71
72
        xmldoc = minidom.parseString(smi)
        gpuList = xmldoc.getElementsByTagName('gpu')
        with open(os.path.join(outputDir, "gpu_metrics"), 'a') as outputFile:
            outPut = {}
            outPut["Timestamp"] = time.asctime(time.localtime())
            outPut["gpuCount"] = len(gpuList)
            outPut["gpuInfos"] = []
            for gpuIndex, gpu in enumerate(gpuList):
chicm-ms's avatar
chicm-ms committed
73
                gpuInfo = {}
Deshui Yu's avatar
Deshui Yu committed
74
                gpuInfo['index'] = gpuIndex
chicm-ms's avatar
chicm-ms committed
75
76
77
78
79
80
                gpuInfo['gpuUtil'] = gpu.getElementsByTagName('utilization')[0]\
                    .getElementsByTagName('gpu_util')[0]\
                    .childNodes[0].data.replace("%", "").strip()
                gpuInfo['gpuMemUtil'] = gpu.getElementsByTagName('utilization')[0]\
                    .getElementsByTagName('memory_util')[0]\
                    .childNodes[0].data.replace("%", "").strip()
Deshui Yu's avatar
Deshui Yu committed
81
82
83
84
85
86
87
88
                processes = gpu.getElementsByTagName('processes')
                runningProNumber = len(processes[0].getElementsByTagName('process_info'))
                gpuInfo['activeProcessNum'] = runningProNumber

                outPut["gpuInfos"].append(gpuInfo)
            print(outPut)
            outputFile.write("{}\n".format(json.dumps(outPut, sort_keys=True)))
            outputFile.flush();
chicm-ms's avatar
chicm-ms committed
89
90
    except:
        # e_info = sys.exc_info()
Deshui Yu's avatar
Deshui Yu committed
91
        print('xmldoc paring error')
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
    finally:
        os.umask(old_umask)

def gen_empty_gpu_metric(outputDir):
    try:
        old_umask = os.umask(0)
        with open(os.path.join(outputDir, "gpu_metrics"), 'a') as outputFile:
            outPut = {}
            outPut["Timestamp"] = time.asctime(time.localtime())
            outPut["gpuCount"] = 0
            outPut["gpuInfos"] = []
            print(outPut)
            outputFile.write("{}\n".format(json.dumps(outPut, sort_keys=True)))
            outputFile.flush()
    except Exception:
        traceback.print_exc()
    finally:
        os.umask(old_umask)
Deshui Yu's avatar
Deshui Yu committed
110
111
112
113


if __name__ == "__main__":
    main(sys.argv[1:])