Skip to content

Commit 1af543e

Browse files
committed
Merge branch 'dev' into feature/cpu-torch
2 parents edd291a + 4913825 commit 1af543e

File tree

6 files changed

+109
-111
lines changed

6 files changed

+109
-111
lines changed

poetry.lock

Lines changed: 30 additions & 30 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

simvue/metrics.py

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import contextlib
12
import logging
23

34
from .pynvml import (
@@ -20,10 +21,8 @@ def get_process_memory(processes):
2021
"""
2122
rss = 0
2223
for process in processes:
23-
try:
24+
with contextlib.suppress(Exception):
2425
rss += process.memory_info().rss / 1024 / 1024
25-
except:
26-
pass
2726

2827
return rss
2928

@@ -34,10 +33,8 @@ def get_process_cpu(processes):
3433
"""
3534
cpu_percent = 0
3635
for process in processes:
37-
try:
36+
with contextlib.suppress(Exception):
3837
cpu_percent += process.cpu_percent()
39-
except:
40-
pass
4138

4239
return cpu_percent
4340

@@ -64,7 +61,7 @@ def get_gpu_metrics(processes):
6461
"""
6562
gpu_metrics = {}
6663

67-
try:
64+
with contextlib.suppress(Exception):
6865
nvmlInit()
6966
device_count = nvmlDeviceGetCount()
7067
for i in range(device_count):
@@ -79,7 +76,5 @@ def get_gpu_metrics(processes):
7976
gpu_metrics[f"resources/gpu.memory.percent.{i}"] = memory_percent
8077

8178
nvmlShutdown()
82-
except:
83-
pass
8479

8580
return gpu_metrics

simvue/pynvml.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1049,7 +1049,7 @@ def _nvmlGetFunctionPointer(name):
10491049
libLoadLock.acquire()
10501050
try:
10511051
# ensure library was loaded
1052-
if nvmlLib == None:
1052+
if nvmlLib is None:
10531053
raise NVMLError(NVML_ERROR_UNINITIALIZED)
10541054
try:
10551055
_nvmlGetFunctionPointer_cache[name] = getattr(nvmlLib, name)
@@ -1310,7 +1310,7 @@ class nvmlClkMonStatus_t(Structure):
13101310
# On Windows with the WDDM driver, usedGpuMemory is reported as None
13111311
# Code that processes this structure should check for None, I.E.
13121312
#
1313-
# if (info.usedGpuMemory == None):
1313+
# if (info.usedGpuMemory is None):
13141314
# # TODO handle the error
13151315
# pass
13161316
# else:
@@ -2022,13 +2022,13 @@ def _LoadNvmlLibrary():
20222022
"""
20232023
global nvmlLib
20242024

2025-
if nvmlLib == None:
2025+
if nvmlLib is None:
20262026
# lock to ensure only one caller loads the library
20272027
libLoadLock.acquire()
20282028

20292029
try:
20302030
# ensure the library still isn't loaded
2031-
if nvmlLib == None:
2031+
if nvmlLib is None:
20322032
try:
20332033
if sys.platform[:3] == "win":
20342034
# cdecl calling convention
@@ -2040,7 +2040,7 @@ def _LoadNvmlLibrary():
20402040
"System32/nvml.dll",
20412041
)
20422042
)
2043-
except OSError as ose:
2043+
except OSError:
20442044
# If nvml.dll is not found in System32, it should be in ProgramFiles
20452045
# load nvml.dll from %ProgramFiles%/NVIDIA Corporation/NVSMI/nvml.dll
20462046
nvmlLib = CDLL(
@@ -2052,9 +2052,9 @@ def _LoadNvmlLibrary():
20522052
else:
20532053
# assume linux
20542054
nvmlLib = CDLL("libnvidia-ml.so.1")
2055-
except OSError as ose:
2055+
except OSError:
20562056
_nvmlCheckReturn(NVML_ERROR_LIBRARY_NOT_FOUND)
2057-
if nvmlLib == None:
2057+
if nvmlLib is None:
20582058
_nvmlCheckReturn(NVML_ERROR_LIBRARY_NOT_FOUND)
20592059
finally:
20602060
# lock is always freed

simvue/system.py

Lines changed: 27 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22
import platform
33
import socket
44
import subprocess
5+
import shutil
56
import sys
7+
import contextlib
68
import typing
79

810

@@ -13,31 +15,28 @@ def get_cpu_info():
1315
model_name = ""
1416
arch = ""
1517

16-
try:
17-
info = subprocess.check_output("lscpu").decode().strip()
18-
for line in info.split("\n"):
19-
if "Model name" in line:
20-
model_name = line.split(":")[1].strip()
21-
if "Architecture" in line:
22-
arch = line.split(":")[1].strip()
23-
except:
24-
# TODO: Try /proc/cpuinfo
25-
pass
18+
if shutil.which("lscpu"):
19+
with contextlib.suppress(subprocess.CalledProcessError):
20+
info = subprocess.check_output("lscpu").decode().strip()
21+
for line in info.split("\n"):
22+
if "Model name" in line:
23+
model_name = line.split(":")[1].strip()
24+
if "Architecture" in line:
25+
arch = line.split(":")[1].strip()
2626

27-
if arch == "":
28-
arch = platform.machine()
27+
# TODO: Try /proc/cpuinfo if process fails
2928

30-
if model_name == "":
31-
try:
29+
arch = arch or platform.machine()
30+
31+
if not model_name and shutil.which("sysctl"):
32+
with contextlib.suppress(subprocess.CalledProcessError):
3233
info = (
3334
subprocess.check_output(["sysctl", "machdep.cpu.brand_string"])
3435
.decode()
3536
.strip()
3637
)
3738
if "machdep.cpu.brand_string:" in info:
3839
model_name = info.split("machdep.cpu.brand_string: ")[1]
39-
except:
40-
pass
4140

4241
return model_name, arch
4342

@@ -46,16 +45,19 @@ def get_gpu_info():
4645
"""
4746
Get GPU info
4847
"""
49-
try:
50-
output = subprocess.check_output(
51-
["nvidia-smi", "--query-gpu=name,driver_version", "--format=csv"]
52-
)
53-
lines = output.split(b"\n")
54-
tokens = lines[1].split(b", ")
55-
except:
56-
return {"name": "", "driver_version": ""}
48+
_gpu_info: dict[str, str] = {"name": "", "driver_version": ""}
49+
50+
if shutil.which("nvidia-smi"):
51+
with contextlib.suppress(subprocess.CalledProcessError, IndexError):
52+
output = subprocess.check_output(
53+
["nvidia-smi", "--query-gpu=name,driver_version", "--format=csv"]
54+
)
55+
lines = output.split(b"\n")
56+
tokens = lines[1].split(b", ")
57+
_gpu_info["name"] = tokens[0].decode()
58+
_gpu_info["driver_version"] = tokens[1].decode()
5759

58-
return {"name": tokens[0].decode(), "driver_version": tokens[1].decode()}
60+
return _gpu_info
5961

6062

6163
def get_system() -> dict[str, typing.Any]:

simvue/utilities.py

Lines changed: 30 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -2,43 +2,45 @@
22
import datetime
33
import hashlib
44
import logging
5+
import importlib.util
6+
import contextlib
57
import os
68
import typing
79

810
import jwt
911

1012
CHECKSUM_BLOCK_SIZE = 4096
13+
EXTRAS: tuple[str, ...] = ("plot", "torch", "dataset")
1114

1215
logger = logging.getLogger(__name__)
1316

1417

1518
def check_extra(extra_name: str) -> typing.Callable:
1619
def decorator(class_func: typing.Callable) -> typing.Callable:
1720
def wrapper(self, *args, **kwargs) -> typing.Any:
18-
if extra_name == "plot":
19-
try:
20-
import matplotlib
21-
import plotly
22-
except ImportError:
23-
raise RuntimeError(
24-
f"Plotting features require the '{extra_name}' extension to Simvue"
25-
)
26-
elif extra_name == "torch":
27-
try:
28-
import torch
29-
except ImportError:
30-
raise RuntimeError(
31-
"PyTorch features require the 'torch' module to be installed"
32-
)
33-
elif extra_name == "dataset":
34-
try:
35-
import numpy
36-
import pandas
37-
except ImportError:
38-
raise RuntimeError(
39-
f"Dataset features require the '{extra_name}' extension to Simvue"
40-
)
41-
else:
21+
if extra_name == "plot" and not all(
22+
[
23+
importlib.util.find_spec("matplotlib"),
24+
importlib.util.find_spec("plotly"),
25+
]
26+
):
27+
raise RuntimeError(
28+
f"Plotting features require the '{extra_name}' extension to Simvue"
29+
)
30+
elif extra_name == "torch" and not importlib.util.find_spec("torch"):
31+
raise RuntimeError(
32+
"PyTorch features require the 'torch' module to be installed"
33+
)
34+
elif extra_name == "dataset" and not all(
35+
[
36+
importlib.util.find_spec("numpy"),
37+
importlib.util.find_spec("pandas"),
38+
]
39+
):
40+
raise RuntimeError(
41+
f"Dataset features require the '{extra_name}' extension to Simvue"
42+
)
43+
elif extra_name not in EXTRAS:
4244
raise RuntimeError(f"Unrecognised extra '{extra_name}'")
4345
return class_func(self, *args, **kwargs)
4446

@@ -103,13 +105,11 @@ def get_auth():
103105
os.path.join(os.path.expanduser("~"), ".simvue.ini"),
104106
"simvue.ini",
105107
):
106-
try:
108+
with contextlib.suppress(Exception):
107109
config = configparser.ConfigParser()
108110
config.read(filename)
109111
token = config.get("server", "token")
110112
url = config.get("server", "url")
111-
except:
112-
pass
113113

114114
# Try environment variables
115115
token = os.getenv("SIMVUE_TOKEN", token)
@@ -128,12 +128,10 @@ def get_offline_directory():
128128
os.path.join(os.path.expanduser("~"), ".simvue.ini"),
129129
"simvue.ini",
130130
):
131-
try:
131+
with contextlib.suppress(Exception):
132132
config = configparser.ConfigParser()
133133
config.read(filename)
134134
directory = config.get("offline", "cache")
135-
except:
136-
pass
137135

138136
if not directory:
139137
directory = os.path.join(os.path.expanduser("~"), ".simvue")
@@ -168,10 +166,9 @@ def get_expiry(token):
168166
Get expiry date from a JWT token
169167
"""
170168
expiry = 0
171-
try:
169+
with contextlib.suppress(jwt.DecodeError):
172170
expiry = jwt.decode(token, options={"verify_signature": False})["exp"]
173-
except:
174-
pass
171+
175172
return expiry
176173

177174

0 commit comments

Comments
 (0)