-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathGPU.py
75 lines (61 loc) · 2.14 KB
/
GPU.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
#-*- coding:utf-8 -*-
import os, sys, subprocess, random, time, re
from IPyRSSA import General
if 'getstatusoutput' in dir(subprocess):
from subprocess import getstatusoutput
else:
from commands import getstatusoutput
class GPUProcess(object):
def __init__(self, gpuid, pid, ptype, pname, memo):
super(GPUProcess, self).__init__()
self.gpuid = gpuid
self.pid = pid
self.ptype = ptype
self.pname = pname
self.memo = memo
def __str__(self):
return "__GPU(%s)__PID(%s)__Proc(%s)__" % (self.gpuid, self.gpuid, self.pname)
def __repr__(self):
return "__GPU(%s)__PID(%s)__Proc(%s)__" % (self.gpuid, self.gpuid, self.pname)
def get_gpu_processes():
"""
Get a list of GPUProcess objects
Require: nvidia-smi
"""
NVIDIASMI = General.require_exec("nvidia-smi", exception=False)
lines = getstatusoutput(NVIDIASMI)[1].strip().split('\n')
sl = 0
while "Processes" not in lines[sl]:
sl += 1
GPUProc_List = []
for line in lines[sl+3:-1]:
if "No running processes found" in line: break
data = line.strip('|').strip().split()
gpu_id = int(data[0])
pid = int(data[1])
ptype = data[2]
memo = int(data[-1].rstrip('MiB'))
pname = " ".join(data[3:-1])
proc = GPUProcess(gpu_id, pid, ptype, pname, memo)
GPUProc_List.append(proc)
return GPUProc_List
def get_gpu_list():
"""
Get a list of available gpu
Require: nvidia-smi
"""
NVIDIASMI = General.require_exec("nvidia-smi", exception=False)
lines = getstatusoutput(NVIDIASMI+" -L")[1].strip().split('\n')
gpuids = [ int(line.split()[1].rstrip(':')) for line in lines ]
return gpuids
def get_free_gpus():
"""
Get a list of GPU id without process run on it
example:
[3,4]
"""
gpu_list = set(get_gpu_list())
gpu_processes = get_gpu_processes()
busy_gpus = set([ i.gpuid for i in gpu_processes ])
free_gpus = list( gpu_list - busy_gpus )
return sorted( free_gpus )