Skip to content

Commit 0550a55

Browse files
authored
Separate script for setting modes. (#848)
1 parent cf5f549 commit 0550a55

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

scalene/scalene_nvidia_gpu.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -45,9 +45,13 @@ def __del__(self) -> None:
4545
file=sys.stderr,
4646
)
4747
print(
48-
"Run once as Administrator or root (i.e., prefixed with `sudo`) to enable per-process GPU accounting.",
48+
"If you have sudo privileges, you can run this command (Linux only) to enable per-process GPU accounting:",
4949
file=sys.stderr,
5050
)
51+
print(
52+
" python3 -m scalene.set_nvidia_gpu_modes",
53+
file=sys.stderr
54+
)
5155

5256
def _set_accounting_mode(self) -> bool:
5357
"""Returns true iff the accounting mode was set already for all GPUs or is now set."""

scalene/set_nvidia_gpu_modes.py

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import os
2+
import sys
3+
import subprocess
4+
5+
def set_nvidia_gpu_modes():
6+
import pynvml
7+
try:
8+
# Initialize NVML
9+
pynvml.nvmlInit()
10+
11+
# Get the number of GPUs
12+
device_count = pynvml.nvmlDeviceGetCount()
13+
14+
for i in range(device_count):
15+
handle = pynvml.nvmlDeviceGetHandleByIndex(i)
16+
17+
# Enable persistence mode
18+
pynvml.nvmlDeviceSetPersistenceMode(handle, pynvml.NVML_FEATURE_ENABLED)
19+
20+
# Enable accounting mode
21+
pynvml.nvmlDeviceSetAccountingMode(handle, pynvml.NVML_FEATURE_ENABLED)
22+
23+
print("Persistence and accounting mode set for all GPUs.")
24+
return True
25+
26+
except pynvml.NVMLError as e:
27+
print(f"An NVML error occurred: {e}")
28+
return False
29+
30+
finally:
31+
# Shutdown NVML
32+
pynvml.nvmlShutdown()
33+
34+
if __name__ == "__main__":
35+
# Check if the script is running as root
36+
if os.geteuid() != 0:
37+
print("This script needs to be run as root. Attempting to rerun with sudo...")
38+
try:
39+
# Attempt to rerun the script with sudo
40+
subprocess.check_call(['sudo', sys.executable] + sys.argv)
41+
except subprocess.CalledProcessError as e:
42+
print(f"Failed to run as root: {e}")
43+
sys.exit(1)
44+
else:
45+
# Run the function if already root
46+
set_nvidia_gpu_modes()

0 commit comments

Comments
 (0)