xuan-luo's picture
download
raw
5.84 kB
#!/usr/bin/env python3
"""Monitor NVIDIA GPU core temperatures without third-party Python dependencies."""
from __future__ import annotations
import argparse
import csv
import math
import os
import subprocess
import sys
import time
from datetime import datetime
from pathlib import Path
def read_temperatures(gpus: str | None) -> list[tuple[str, str, float]]:
command = [
"nvidia-smi", "--query-gpu=index,name,temperature.gpu",
"--format=csv,noheader,nounits",
]
if gpus:
command += ["--id", gpus]
result = subprocess.run(command, capture_output=True, text=True, timeout=10)
if result.returncode:
raise RuntimeError(result.stderr.strip() or result.stdout.strip() or "nvidia-smi failed")
readings = []
for row in csv.reader(result.stdout.splitlines(), skipinitialspace=True):
if len(row) != 3:
raise ValueError(f"Unexpected GPU reading: {row!r}")
index, name, temperature = (value.strip() for value in row)
value = float(temperature) # N/A must report a monitoring failure.
if not math.isfinite(value):
raise ValueError(f"Invalid temperature for GPU {index}: {temperature}")
readings.append((index, name, value))
if not readings:
raise RuntimeError("No GPU temperature readings returned")
return readings
def pid_alive(pid: int) -> bool:
try:
os.kill(pid, 0)
except ProcessLookupError:
return False
except PermissionError:
return True
# Linux zombies still respond to kill(pid, 0).
try:
state = Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()[0]
return state != "Z"
except (OSError, IndexError):
return True
class Alerts:
def __init__(self, warn: float, critical: float, cooldown: float):
self.warn = warn
self.critical = critical
self.cooldown = cooldown
self.states: dict[str, tuple[int, float]] = {}
def check(self, index: str, temperature: float, now: float) -> str | None:
level = 2 if temperature >= self.critical else 1 if temperature >= self.warn else 0
previous, last_alert = self.states.get(index, (0, -math.inf))
if level and (level != previous or now - last_alert >= self.cooldown):
self.states[index] = (level, now)
return "CRITICAL" if level == 2 else "WARNING"
self.states[index] = (level, last_alert)
return "RECOVERED" if previous and not level else None
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--gpus", help="Physical GPU indices or UUIDs, e.g. 0,1; default: all")
parser.add_argument("--warn", type=float, default=80, help="Warning core temperature in C (default: 80)")
parser.add_argument("--critical", type=float, default=85, help="Critical core temperature in C (default: 85)")
parser.add_argument("--interval", type=float, default=10, help="Polling interval in seconds")
parser.add_argument("--cooldown", type=float, default=300, help="Repeat alert interval per GPU in seconds")
parser.add_argument("--pid", type=int, help="Exit when this training process exits")
parser.add_argument("--log", type=Path, help="Append timestamped readings and alerts to this file")
parser.add_argument("--once", action="store_true", help="Read once; exit 1 on overheating, 2 on monitoring failure")
args = parser.parse_args()
if not all(math.isfinite(v) for v in (args.warn, args.critical, args.interval, args.cooldown)):
parser.error("Thresholds and intervals must be finite")
if not 0 < args.warn < args.critical or args.interval <= 0 or args.cooldown < 0:
parser.error("Require 0 < warn < critical, interval > 0, cooldown >= 0")
if args.pid is not None and args.pid <= 0:
parser.error("--pid must be positive")
alerts = Alerts(args.warn, args.critical, args.cooldown)
if args.log:
args.log.parent.mkdir(parents=True, exist_ok=True)
logfile = args.log.open("a", buffering=1) if args.log else None
def emit(message: str, alarm: bool = False) -> None:
line = f"{datetime.now().astimezone().isoformat(timespec='seconds')} {message}"
print(line, file=sys.stderr, flush=True)
if alarm and sys.stderr.isatty():
print("\a", end="", file=sys.stderr, flush=True)
if logfile:
logfile.write(line + "\n")
failed = False
try:
emit(f"START warn={args.warn:g}C critical={args.critical:g}C interval={args.interval:g}s")
while args.pid is None or pid_alive(args.pid):
try:
readings = read_temperatures(args.gpus)
except (OSError, subprocess.SubprocessError, ValueError, RuntimeError) as exc:
emit(f"MONITOR ERROR: {exc}", alarm=not failed)
failed = True
if args.once:
return 2
else:
if failed:
emit("MONITOR RECOVERED: temperature readings available")
failed = False
hot = False
for index, name, temperature in readings:
status = alerts.check(index, temperature, time.monotonic())
hot |= temperature >= args.warn
emit(f"{status or 'TEMP'} GPU {index} ({name}): {temperature:g}C",
alarm=status in ("WARNING", "CRITICAL"))
if args.once:
return int(hot)
time.sleep(args.interval)
emit(f"STOP: training PID {args.pid} exited")
except KeyboardInterrupt:
emit("STOP: interrupted")
finally:
if logfile:
logfile.close()
return 0
if __name__ == "__main__":
raise SystemExit(main())

Xet Storage Details

Size:
5.84 kB
·
Xet hash:
5c452e6bf66925adafd91c12b2e64b0b50dfbc087a6112d44de06bedc620cf84

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.