Files
nvdriver/tools/nv-nice

563 lines
22 KiB
Python
Executable File

#!/usr/bin/env python3
"""nv-nice: Unix-idiomatic GPU nice / renice and desktop priority tool for nvidia_rs."""
from __future__ import annotations
import argparse
import json
import os
import sys
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
DEFAULT_PROC_PATH = "/proc/driver/nvidia/gpu-prio"
PRESETS: Dict[str, int] = {
"rt": -20,
"desktop": -5,
"normal": 0,
"bg": 10,
"idle": 19,
}
class LaunchError(OSError):
"""Raised when launching the target executable fails."""
class ProcAccessError(FileNotFoundError):
"""Raised when accessing the nvidia_rs procfs priority interface fails."""
def unescape_comm(raw: str) -> str:
"""Decodes kernel procfs `\\xHH` / `\\\\` escapes in a COMM token as UTF-8.
Invalid UTF-8 byte sequences are preserved losslessly with `backslashreplace`
so callers and JSON output never fail on arbitrary kernel `task->comm` bytes.
"""
buf = bytearray()
i = 0
n = len(raw)
while i < n:
ch = raw[i]
if ch == "\\" and i + 1 < n:
nxt = raw[i + 1]
if nxt == "\\":
buf.extend(b"\\")
i += 2
continue
if nxt == "x" and i + 3 < n:
hex_part = raw[i + 2 : i + 4]
try:
buf.append(int(hex_part, 16))
i += 4
continue
except ValueError:
pass
buf.extend(ch.encode("utf-8"))
i += 1
return buf.decode("utf-8", errors="backslashreplace")
def escape_control_chars(text: str) -> str:
"""Escapes control characters for terminal table output while preserving spaces."""
out: List[str] = []
for ch in text:
code = ord(ch)
if code < 0x20 or code == 0x7F or (0x80 <= code <= 0x9F):
out.append(f"\\x{code:02x}")
else:
out.append(ch)
return "".join(out)
def validate_desktop_comm_name(name: str) -> str:
"""Validates a `--desktop-comm` name against the kernel's single-token ASCII format."""
try:
raw = name.encode("ascii")
except UnicodeEncodeError as exc:
raise ValueError(f"invalid --desktop-comm name {name!r}: must be printable ASCII") from exc
if not raw or len(raw) > 15:
raise ValueError(f"invalid --desktop-comm name {name!r}: must be 1..15 ASCII bytes")
for b in raw:
if b <= 0x20 or b >= 0x7F or b in (ord(","), ord("\\")):
raise ValueError(
f"invalid --desktop-comm name {name!r}: whitespace, control characters, ',' and '\\\\' are not allowed"
)
return name
def parse_gpu_prio_text(text: str) -> Dict[str, Any]:
"""Parses `/proc/driver/nvidia/gpu-prio` output into structured policy + rows."""
policy: Dict[str, Any] = {}
desktop_comms: Dict[str, List[str]] = {"builtin": [], "custom": []}
rows: List[Dict[str, Any]] = []
headers: List[str] = []
unavailable = False
for raw_line in text.splitlines():
line = raw_line.strip()
if not line:
continue
if line == "# unavailable" or line.startswith("# unavailable "):
unavailable = True
continue
if line.startswith("# policy:"):
for tok in line[len("# policy:") :].split():
if "=" in tok:
k, v = tok.split("=", 1)
try:
policy[k] = int(v)
except ValueError:
policy[k] = v
continue
if line.startswith("# desktop_comms:"):
for tok in line[len("# desktop_comms:") :].split():
if "=" in tok:
k, v = tok.split("=", 1)
desktop_comms[k] = [unescape_comm(x) for x in v.split(",") if x]
continue
if line.startswith("#"):
continue
if line.startswith("PID ") or line.startswith("PID\t"):
headers = line.split()
continue
parts = line.split()
if len(parts) >= 14:
pid_tok = parts[0]
retired = pid_tok == "retired"
pid_val: Optional[int] = None if retired else int(pid_tok)
comm = unescape_comm(" ".join(parts[2:-11]))
tail = parts[-11:]
raw_intlv = tail[4]
if "/" in raw_intlv:
req_intlv, sub_tag = raw_intlv.split("/", 1)
submitted_intlv = "UNIFORM" if sub_tag == "unif" else sub_tag
else:
req_intlv = raw_intlv
submitted_intlv = raw_intlv
rows.append(
{
"pid": pid_val,
"retired": retired,
"uid": int(parts[1]),
"comm": comm,
"linux_nice": int(tail[0]),
"gpu_nice": int(tail[1]),
"override": tail[2],
"class": tail[3],
"interleave": raw_intlv,
"requested_interleave": req_intlv,
"submitted_interleave": submitted_intlv,
"timeslice_us": int(tail[5]),
"tsgs_gr": int(tail[6]),
"tsgs_ce": int(tail[7]),
"tsgs_other": int(tail[8]),
"preempt": tail[9],
"desktop": tail[10] == "yes",
}
)
return {
"unavailable": unavailable,
"policy": policy,
"desktop_comms": desktop_comms,
"rows": rows,
"headers": headers,
}
def format_table(data: Dict[str, Any], use_color: bool = False) -> str:
if data.get("unavailable"):
return "nvidia_rs gpu-prio: unavailable"
policy = data.get("policy", {})
rows = data.get("rows", [])
lines: List[str] = []
auto_on = policy.get("auto", "?")
desk_on = policy.get("desktop_boost", "?")
preempt_on = policy.get("preempt", "?")
pids = policy.get("tracked_pids", len(rows))
tsgs = policy.get("active_tsgs", sum(r["tsgs_gr"] + r["tsgs_ce"] + r["tsgs_other"] for r in rows))
lines.append(
f"nvidia_rs gpu-prio: auto={auto_on} desktop_boost={desk_on} preempt={preempt_on} "
f"tracked_pids={pids} active_tsgs={tsgs}"
)
if not rows:
lines.append("(no active GPU TSGs)")
return "\n".join(lines)
hdr = (
f"{'PID':>7} {'UID':>6} {'COMM':<16} {'LNICE':>5} {'GNICE':>5} "
f"{'MODE':<8} {'CLASS':<7} {'INTLV':<9} {'SLICE_US':>8} "
f"{'GR/CE/OTH':<9} {'PREEMPT':<9} {'DESK'}"
)
lines.append(hdr)
lines.append("-" * len(hdr))
for r in rows:
tsg_str = f"{r['tsgs_gr']}/{r['tsgs_ce']}/{r['tsgs_other']}"
desk_str = "yes" if r["desktop"] else "no"
pid_disp = "retired" if r.get("retired") or r["pid"] is None else str(r["pid"])
comm_disp = escape_control_chars(r["comm"])
cls = r["class"]
if use_color:
if cls in ("rt", "desktop"):
cls_disp = f"\033[32m{cls:<7}\033[0m"
elif cls in ("bg", "idle"):
cls_disp = f"\033[33m{cls:<7}\033[0m"
else:
cls_disp = f"{cls:<7}"
else:
cls_disp = f"{cls:<7}"
lines.append(
f"{pid_disp:>7} {r['uid']:>6} {comm_disp:<16} {r['linux_nice']:>5} "
f"{r['gpu_nice']:>5} {r['override']:<8} {cls_disp} {r['interleave']:<9} "
f"{r['timeslice_us']:>8} {tsg_str:<9} {r['preempt']:<9} {desk_str}"
)
return "\n".join(lines)
def resolve_pgid_pids(pgid: int, proc_root: str = "/proc") -> List[int]:
"""Returns PIDs in process group `pgid` from `/proc/<pid>/stat`."""
found: List[int] = []
root = Path(proc_root)
for entry in root.iterdir():
if not entry.name.isdigit():
continue
try:
stat_text = (entry / "stat").read_text(encoding="utf-8", errors="ignore")
except OSError:
continue
rparen = stat_text.rfind(")")
if rparen < 0:
continue
rest = stat_text[rparen + 2 :].split()
if len(rest) >= 3:
try:
proc_pgid = int(rest[2])
except ValueError:
continue
if proc_pgid == pgid:
found.append(int(entry.name))
return sorted(found)
def write_proc_cmd(proc_path: str, command: str) -> None:
with open(proc_path, "w", encoding="utf-8") as fh:
fh.write(command + "\n")
def read_proc_data(proc_path: str) -> Dict[str, Any]:
with open(proc_path, "r", encoding="utf-8") as fh:
return parse_gpu_prio_text(fh.read())
def parse_nice_value(raw: str) -> int:
val = int(raw, 10)
if val < -20 or val > 19:
raise ValueError(f"nice value {val} out of range -20..19")
return val
def resolve_target_spec(args: argparse.Namespace) -> Tuple[Optional[int], bool, bool]:
"""Returns `(nice_value, is_auto, is_desktop)` from CLI flags/presets."""
if args.auto:
return (None, True, False)
for preset_name, preset_val in PRESETS.items():
if getattr(args, preset_name, False):
return (preset_val, False, preset_name == "desktop")
if args.nice is not None:
return (parse_nice_value(str(args.nice)), False, False)
return (None, False, False)
def resolve_target_level(args: argparse.Namespace) -> Tuple[Optional[int], bool]:
"""Returns `(nice_value, is_auto)` from CLI flags/presets."""
target_nice, is_auto, _ = resolve_target_spec(args)
return (target_nice, is_auto)
def build_parser() -> argparse.ArgumentParser:
p = argparse.ArgumentParser(
prog="nv-nice",
description="Inspect or control GPU process priority (nice/renice + desktop protection) on nvidia_rs.",
epilog=(
"Examples:\n"
" nv-nice List active GPU processes & TSG scheduling state\n"
" nv-nice -n 19 blender -b a.blend Launch blender at Linux+GPU nice +19\n"
" nv-nice --bg python train.py Launch training job as background (nice +10)\n"
" nv-nice -p 1234 19 Live-renice running PID 1234 to +19\n"
" nv-nice --desktop -p 890 Boost compositor PID 890 (desktop trust + GPU nice -5)\n"
" nv-nice --auto -p 1234 Revert PID 1234 to automatic Linux nice tracking\n"
" nv-nice --gpu-only -g 4567 15 Set GPU-only nice +15 for all GPU PIDs in PGID 4567\n"
),
formatter_class=argparse.RawDescriptionHelpFormatter,
)
p.add_argument("-l", "--list", action="store_true", help="List active GPU processes and TSGs")
p.add_argument("--json", action="store_true", help="Output list in JSON format")
p.add_argument("-n", "--nice", type=int, default=None, help="Nice value (-20..19)")
p.add_argument("-p", "--pid", action="append", default=[], help="Target PID (repeatable or comma-separated)")
p.add_argument("-g", "--pgid", action="append", default=[], help="Target process group ID (PGID)")
p.add_argument("--gpu-only", action="store_true", help="Only set GPU priority (do not change Linux CPU nice)")
p.add_argument("--auto", action="store_true", help="Revert target PID(s) to automatic Linux nice tracking")
p.add_argument("--rt", action="store_true", help="Preset: realtime (-20)")
p.add_argument("--desktop", action="store_true", help="Preset: desktop/compositor (-5)")
p.add_argument("--normal", action="store_true", help="Preset: normal (0)")
p.add_argument("--bg", action="store_true", help="Preset: background (+10)")
p.add_argument("--idle", action="store_true", help="Preset: idle (+19)")
p.add_argument("--policy", action="append", default=[], help="Set policy knob: auto=0|1, desktop_boost=0|1, preempt=0|1")
p.add_argument("--desktop-comm", nargs=2, metavar=("add|del", "NAME"), help="Add or remove a compositor comm name")
p.add_argument("--sync", action="store_true", help="Trigger immediate kernel nice sync")
p.add_argument("--proc-file", default=DEFAULT_PROC_PATH, help=argparse.SUPPRESS)
p.add_argument("rest", nargs=argparse.REMAINDER, help="Positional nice value (with -p/-g) or command to launch")
return p
def _expand_ids(raw_list: Sequence[str]) -> List[int]:
out: List[int] = []
for item in raw_list:
for tok in item.split(","):
tok = tok.strip()
if tok:
val = int(tok, 10)
if val <= 0:
raise ValueError(f"invalid positive ID: {val}")
out.append(val)
return out
def _proc_write(write_fn: Callable[[str, str], None], proc_file: str, command: str) -> None:
try:
write_fn(proc_file, command)
except FileNotFoundError as exc:
raise ProcAccessError(exc.errno, exc.strerror or str(exc), exc.filename or proc_file) from exc
def _proc_read(read_fn: Callable[[str], Dict[str, Any]], proc_file: str) -> Dict[str, Any]:
try:
return read_fn(proc_file)
except FileNotFoundError as exc:
raise ProcAccessError(exc.errno, exc.strerror or str(exc), exc.filename or proc_file) from exc
def run(
argv: Sequence[str],
write_fn: Optional[Callable[[str, str], None]] = None,
read_fn: Optional[Callable[[str], Dict[str, Any]]] = None,
getpriority_fn: Optional[Callable[[int], int]] = None,
setpriority_fn: Optional[Callable[[int, int], None]] = None,
exec_fn: Optional[Callable[[str, List[str]], None]] = None,
getpid_fn: Optional[Callable[[], int]] = None,
pgid_resolver: Optional[Callable[[int], List[int]]] = None,
) -> int:
if write_fn is None:
write_fn = write_proc_cmd
if read_fn is None:
read_fn = read_proc_data
if getpriority_fn is None:
getpriority_fn = lambda pid: os.getpriority(os.PRIO_PROCESS, pid)
if setpriority_fn is None:
setpriority_fn = lambda pid, val: os.setpriority(os.PRIO_PROCESS, pid, val)
if exec_fn is None:
exec_fn = os.execvp
if getpid_fn is None:
getpid_fn = os.getpid
if pgid_resolver is None:
pgid_resolver = resolve_pgid_pids
parser = build_parser()
args = parser.parse_args(list(argv))
rest = list(args.rest)
if rest and rest[0] == "--":
rest = rest[1:]
# Policy / desktop_comm / sync commands
if args.policy or args.desktop_comm or args.sync:
commands = []
for item in args.policy:
if "=" not in item:
raise ValueError(f"expected key=0|1, got {item!r}")
k, v = item.split("=", 1)
if k not in ("auto", "desktop_boost", "preempt") or v not in ("0", "1"):
raise ValueError(f"invalid policy setting: {item!r}")
commands.append(f"{k} {v}")
if args.desktop_comm:
op, name = args.desktop_comm
if op not in ("add", "del") or not name:
raise ValueError("expected --desktop-comm add|del <NAME>")
validate_desktop_comm_name(name)
commands.append(f"desktop_comm {op} {name}")
if args.sync:
commands.append("sync")
for command in commands:
_proc_write(write_fn, args.proc_file, command)
if not (args.pid or args.pgid or rest or args.list or args.json):
return 0
pids = _expand_ids(args.pid)
pgids = _expand_ids(args.pgid)
if args.pid and not pids:
raise ValueError("invalid -p/--pid target list: no valid PIDs")
if args.pgid and not pgids:
raise ValueError("invalid -g/--pgid target list: no valid PGIDs")
if pids or pgids:
target_nice, is_auto, is_desktop = resolve_target_spec(args)
if not is_auto and target_nice is None:
if not rest:
raise ValueError("specify a nice level (-20..19), preset (--bg/--idle/--desktop), or --auto")
target_nice = parse_nice_value(rest[0])
rest = rest[1:]
if rest:
raise ValueError(f"unexpected trailing arguments for -p/-g: {rest}")
target_pids = list(pids)
if pgids:
proc_data = _proc_read(read_fn, args.proc_file)
if proc_data.get("unavailable"):
raise ValueError("nvidia_rs gpu-prio is unavailable")
tracked_pids = {
r["pid"]
for r in proc_data.get("rows", [])
if not r.get("retired")
and r.get("pid")
and (r.get("tsgs_gr", 0) + r.get("tsgs_ce", 0) + r.get("tsgs_other", 0)) > 0
}
for pgid in pgids:
members = pgid_resolver(pgid)
gpu_members = [m for m in members if m in tracked_pids]
if args.gpu_only:
target_pids.extend(gpu_members)
else:
target_pids.extend(gpu_members if gpu_members else members)
if not target_pids:
if args.gpu_only and pgids and not pids:
raise ValueError("no matching GPU PIDs found")
raise ValueError("no matching PIDs found")
linux_failed = False
for pid in dict.fromkeys(target_pids):
if is_auto:
_proc_write(write_fn, args.proc_file, f"pid {pid} auto")
else:
assert target_nice is not None
linux_changed = False
linux_err: Optional[OSError] = None
if not args.gpu_only:
try:
setpriority_fn(pid, target_nice)
linux_changed = True
except PermissionError:
raise
except OSError as exc:
linux_failed = True
linux_err = exc
proc_arg = "desktop" if is_desktop else str(target_nice)
try:
_proc_write(write_fn, args.proc_file, f"pid {pid} {proc_arg}")
except (PermissionError, OSError) as exc:
if linux_changed:
msg = (
f"partial success for PID {pid}: Linux nice changed to {target_nice}, "
f"but GPU priority update failed: {exc}"
)
err_cls = PermissionError if isinstance(exc, PermissionError) else OSError
wrapped = err_cls(msg)
wrapped.errno = getattr(exc, "errno", None)
raise wrapped from exc
raise
if linux_err is not None:
print(
f"warning: setpriority(pid={pid}, {target_nice}) failed ({linux_err}); "
f"only GPU priority was updated",
file=sys.stderr,
)
return 1 if linux_failed else 0
if rest and not args.list:
target_nice, is_auto, is_desktop = resolve_target_spec(args)
if is_auto:
raise ValueError("--auto cannot be used when launching a new command")
if target_nice is None:
inherited = getpriority_fn(0)
target_nice = max(-20, min(19, inherited + 10)) # Match POSIX nice(1) default increment (+10)
self_pid = getpid_fn()
if args.gpu_only:
proc_arg = "desktop" if is_desktop else str(target_nice)
_proc_write(write_fn, args.proc_file, f"pid {self_pid} {proc_arg}")
else:
setpriority_fn(0, target_nice)
try:
proc_data = _proc_read(read_fn, args.proc_file)
except OSError:
# Non-fatal if procfs node isn't readable yet; still attempt registration.
proc_arg = "desktop" if is_desktop else "auto"
try:
_proc_write(write_fn, args.proc_file, f"pid {self_pid} {proc_arg}")
except OSError as exc:
print(
f"warning: only Linux nice ({target_nice}) was set; GPU priority unavailable ({exc})",
file=sys.stderr,
)
else:
if proc_data.get("unavailable"):
print(
f"warning: nvidia_rs gpu-prio is unavailable; only Linux nice ({target_nice}) was set",
file=sys.stderr,
)
elif is_desktop:
try:
_proc_write(write_fn, args.proc_file, f"pid {self_pid} desktop")
except OSError as exc:
print(
f"warning: only Linux nice ({target_nice}) was set; GPU desktop trust failed ({exc})",
file=sys.stderr,
)
elif proc_data.get("policy", {}).get("auto", 1) == 0:
try:
_proc_write(write_fn, args.proc_file, f"pid {self_pid} {target_nice}")
except OSError as exc:
print(
f"warning: automatic GPU-nice tracking is off (auto=0) and GPU override failed ({exc}); "
f"only Linux nice ({target_nice}) was set",
file=sys.stderr,
)
else:
try:
_proc_write(write_fn, args.proc_file, f"pid {self_pid} auto")
except OSError as exc:
print(
f"warning: only Linux nice ({target_nice}) was set; GPU priority registration failed ({exc})",
file=sys.stderr,
)
try:
exec_fn(rest[0], rest)
except OSError as exc:
raise LaunchError(f"failed to launch {rest[0]!r}: {exc}") from exc
return 0
data = _proc_read(read_fn, args.proc_file)
if args.json:
print(json.dumps(data, indent=2))
else:
print(format_table(data, use_color=sys.stdout.isatty()))
return 1 if data.get("unavailable") else 0
def main() -> int:
try:
return run(sys.argv[1:])
except ProcAccessError as exc:
print(f"nv-nice: {exc} (is nvidia_rs loaded with runtime_engines=1?)", file=sys.stderr)
return 1
except (ValueError, PermissionError, OSError) as exc:
print(f"nv-nice: {exc}", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())