Files
nvdriver/tools/dual_gpu_parity.py

280 lines
11 KiB
Python
Executable File

#!/usr/bin/env python3
"""Side-by-side Dual-GPU Parity Harness:
Runs the exact same CUDA Driver API parity suite on:
- Stock NVIDIA 580.178.04 driver (0000:1a:00.0, untouched)
- Rust clean-room nvidia_rs.ko (0000:b3:00.0, private mount namespace)
and diffs EVERY output field, attribute, memory transfer, kernel digest, and status!
Enforces all AGENTS.md safety rules:
- Health check (tainted + NO_D_STATE) before starting
- Only 0000:b3:00.0 is ever unbound/bound to nvidia_rs
- Fail-closed clean-unload gate (requires 4752001a 00000000 before rebinding stock nvidia)
- Optional --no-rebind mode keeps 0000:b3:00.0 dedicated to nvidia_rs across iterations
so stock nvidia.ko never re-opens 0000:b3:00.0 (avoiding nv_open_q rebind crashes)
"""
from __future__ import annotations
import argparse
import json
import os
import re
import subprocess
import sys
import time
from pathlib import Path
if __package__:
from .gpu_binding import blocked_nvidia_task
else:
from gpu_binding import blocked_nvidia_task
ROOT = Path(__file__).resolve().parents[1]
SUITE_SRC = ROOT / "tools/cuda_parity_suite.c"
SUITE_BIN = ROOT / "target/hardware-hello/cuda-parity-suite"
CUBIN = ROOT / "target/hardware-hello/native_hello.sm70.cubin"
STOCK_BDF = "0000:1a:00.0"
RUST_BDF = "0000:b3:00.0"
REPORT_OUT = ROOT / "reports/dual-gpu-parity.json"
OUT_DIR = ROOT / "target/stage8b"
DIRTY_SENTINEL = OUT_DIR / "b3_dirty_boot_id"
def current_boot_id() -> str:
return Path("/proc/sys/kernel/random/boot_id").read_text().strip()
def sh(cmd: str, check: bool = True, timeout: int = 45) -> subprocess.CompletedProcess:
return subprocess.run(cmd, shell=True, text=True, capture_output=True, check=check, timeout=timeout)
def check_health() -> tuple[int, bool]:
taint = int(Path("/proc/sys/kernel/tainted").read_text().strip())
return taint, blocked_nvidia_task() is None
DMESG_TS_RE = re.compile(r"^\[\s*([0-9]+\.[0-9]+)\]")
TAINT_DIE_BIT = 1 << 7
def last_dmesg_timestamp(dmesg_text: str) -> float:
for line in reversed(dmesg_text.splitlines()):
m = DMESG_TS_RE.match(line)
if m:
return float(m.group(1))
return 0.0
def filter_dmesg_since(dmesg_text: str, since_ts: float, bdf: str) -> str:
kept = []
for line in dmesg_text.splitlines():
m = DMESG_TS_RE.match(line)
if m and float(m.group(1)) > since_ts and ("nvidia_rs" in line or bdf in line):
kept.append(line)
return ("\n".join(kept) + "\n") if kept else ""
def has_new_oops_taint(taint_before: int, taint_after: int) -> bool:
return bool((taint_after & ~taint_before) & TAINT_DIE_BIT)
def parse_last_json(stdout: str) -> dict:
for line in reversed(stdout.strip().splitlines()):
line = line.strip()
if line.startswith("{") and line.endswith("}"):
try:
parsed = json.loads(line)
except json.JSONDecodeError:
continue
if isinstance(parsed, dict):
return parsed
raise ValueError(f"No JSON line in stdout:\n{stdout}")
def diff_dicts(a: dict, b: dict, prefix: str = "") -> list[dict]:
diffs = []
keys = sorted(set(a.keys()) | set(b.keys()))
for k in keys:
path = f"{prefix}.{k}" if prefix else k
if k not in a:
diffs.append({"field": path, "stock": None, "rust": b[k]})
elif k not in b:
diffs.append({"field": path, "stock": a[k], "rust": None})
elif isinstance(a[k], dict) and isinstance(b[k], dict):
diffs.extend(diff_dicts(a[k], b[k], path))
elif a[k] != b[k]:
diffs.append({"field": path, "stock": a[k], "rust": b[k]})
return diffs
def teardown_nvidia_rs(
bdf: str,
insmod_done: bool,
run_cmd=sh,
path_exists=lambda p: Path(p).exists(),
) -> list[str]:
"""Attempt every nvidia_rs teardown step and return any failure descriptions."""
errors: list[str] = []
def _run_step(label: str, cmd: str) -> bool:
try:
proc = run_cmd(cmd, check=False)
except (subprocess.SubprocessError, OSError) as exc:
errors.append(f"{label} raised {type(exc).__name__}: {exc}")
return False
if proc.returncode != 0:
errors.append(f"{label} failed (rc={proc.returncode})")
return False
return True
driver_link = f"/sys/bus/pci/drivers/nvidia_rs/{bdf}"
if path_exists(driver_link):
if _run_step(f"unbind {bdf}", f"echo {bdf} | sudo tee /sys/bus/pci/drivers/nvidia_rs/unbind >/dev/null") and path_exists(driver_link):
errors.append(f"unbind {bdf} left {driver_link} present")
override_path = f"/sys/bus/pci/devices/{bdf}/driver_override"
if path_exists(override_path):
_run_step(f"clearing {override_path}", f"echo '' | sudo tee {override_path} >/dev/null")
if insmod_done and path_exists("/sys/module/nvidia_rs"):
if _run_step("rmmod nvidia_rs", "sudo rmmod nvidia_rs") and path_exists("/sys/module/nvidia_rs"):
errors.append("rmmod nvidia_rs left /sys/module/nvidia_rs loaded")
return errors
def main() -> int:
ap = argparse.ArgumentParser(description="Dual-GPU parity harness (stock 1a:00.0 vs Rust b3:00.0)")
ap.add_argument(
"--no-rebind",
action="store_true",
help="Keep 0000:b3:00.0 unbound from stock nvidia after unloading nvidia_rs (zero-reboot dev mode).",
)
args = ap.parse_args()
OUT_DIR.mkdir(parents=True, exist_ok=True)
if not SUITE_BIN.exists() or SUITE_SRC.stat().st_mtime > SUITE_BIN.stat().st_mtime:
print("Compiling cuda-parity-suite...")
sh(f"cc -O2 -Wall -Wextra -Werror {SUITE_SRC} -ldl -o {SUITE_BIN}")
taint_before, healthy = check_health()
if not healthy:
print("ABORT: D-state nvidia/nv_open_q task detected!")
return 1
if not args.no_rebind and DIRTY_SENTINEL.exists() and DIRTY_SENTINEL.read_text().strip() == current_boot_id():
print(f"ABORT: {RUST_BDF} had an unclean GR unload in this boot ({DIRTY_SENTINEL}); reboot before rebinding stock nvidia!")
return 2
# 1. Run on stock NVIDIA driver (0000:1a:00.0)
print(f"=== Running parity suite on STOCK nvidia ({STOCK_BDF}) ===")
t0 = time.monotonic()
stock_proc = sh(f"timeout 45 {SUITE_BIN} {CUBIN} {STOCK_BDF}", check=False, timeout=60)
stock_ms = round((time.monotonic() - t0) * 1000.0, 1)
print(f"stock rc={stock_proc.returncode} ({stock_ms} ms): {stock_proc.stdout.strip()}")
if stock_proc.returncode != 0:
print("STDERR:", stock_proc.stderr)
return 1
stock_json = parse_last_json(stock_proc.stdout)
# 2. Bind 0000:b3:00.0 to nvidia_rs and run the EXACT same binary in private mount namespace
print(f"=== Running parity suite on RUST nvidia_rs ({RUST_BDF}) ===")
dmesg_ts = last_dmesg_timestamp(sh("sudo dmesg").stdout)
if Path(f"/sys/bus/pci/devices/{RUST_BDF}/driver").exists():
sh(f"sudo python3 {ROOT}/tools/gpu_binding.py release {RUST_BDF}")
strace_out = OUT_DIR / "dual-gpu-parity.strace"
dmesg_out = OUT_DIR / "dual-gpu-parity.dmesg"
insmod_done = False
rust_proc = None
rust_ms = 0.0
cleanup_errors: list[str] = []
try:
sh(f"sudo insmod {ROOT}/kernel-open/nvidia_rs.ko pci_target={RUST_BDF} runtime_engines=1")
insmod_done = True
if not Path(f"/sys/bus/pci/devices/{RUST_BDF}/driver").exists():
sh(f"echo nvidia_rs | sudo tee /sys/bus/pci/devices/{RUST_BDF}/driver_override >/dev/null")
sh(f"echo {RUST_BDF} | sudo tee /sys/bus/pci/drivers/nvidia_rs/bind >/dev/null")
t1 = time.monotonic()
rust_proc = sh(
f"sudo timeout -k 5 45 python3 {ROOT}/tools/rmapi_namespace_launcher.py "
f"--gpu-node 0=/dev/nvidia-rs-rmapi-gpu0 --bdf 0={RUST_BDF} "
f"--strace-out {strace_out} -- {SUITE_BIN} {CUBIN} {RUST_BDF}",
check=False,
timeout=60,
)
rust_ms = round((time.monotonic() - t1) * 1000.0, 1)
finally:
# Always attempt every cleanup step even if bind or the workload raised,
# record any failures, and persist DIRTY_SENTINEL before any setup error propagates.
cleanup_errors = teardown_nvidia_rs(RUST_BDF, insmod_done)
if cleanup_errors:
DIRTY_SENTINEL.parent.mkdir(parents=True, exist_ok=True)
DIRTY_SENTINEL.write_text(current_boot_id() + "\n")
cleanup_ok = len(cleanup_errors) == 0
dmesg_text = filter_dmesg_since(sh("sudo dmesg").stdout, dmesg_ts, RUST_BDF)
dmesg_out.write_text(dmesg_text)
clean_unload = "4752001a 00000000" in dmesg_text
post_base_out = "skipped (--no-rebind)"
if args.no_rebind:
if not clean_unload:
DIRTY_SENTINEL.write_text(current_boot_id() + "\n")
print(f"NOTE: clean GR unload marker not seen (marked {DIRTY_SENTINEL}); keeping {RUST_BDF} unbound from stock nvidia.")
if not cleanup_ok:
print(f"ERROR: nvidia_rs teardown failed: {'; '.join(cleanup_errors)}")
else:
if not clean_unload or not cleanup_ok:
DIRTY_SENTINEL.write_text(current_boot_id() + "\n")
if not clean_unload:
print("UNSAFE TO REBIND STOCK NVIDIA: clean GR unload (4752001a 00000000) NOT observed!")
if not cleanup_ok:
print(f"UNSAFE TO REBIND STOCK NVIDIA: teardown failed: {'; '.join(cleanup_errors)}")
print(f"Marked {DIRTY_SENTINEL}; reboot before rebinding stock nvidia. See {dmesg_out}")
return 2
sh(f"sudo python3 {ROOT}/tools/gpu_binding.py restore {RUST_BDF}")
post_base_out = sh(f"timeout 20 {ROOT}/target/hardware-hello/native-hello {CUBIN} {RUST_BDF} 317866785").stdout.strip()
taint_after, healthy_after = check_health()
no_new_oops = not has_new_oops_taint(taint_before, taint_after)
print(f"rust rc={rust_proc.returncode} ({rust_ms} ms)")
if rust_proc.stderr.strip():
print("RUST STDERR:", rust_proc.stderr.strip())
try:
rust_json = parse_last_json(rust_proc.stdout)
except ValueError:
rust_json = {"passed": False, "raw": rust_proc.stdout[-500:]}
diffs = diff_dicts(stock_json, rust_json)
report = {
"passed": (
stock_proc.returncode == 0
and rust_proc.returncode == 0
and len(diffs) == 0
and clean_unload
and cleanup_ok
and healthy_after
and no_new_oops
),
"stock_bdf": STOCK_BDF,
"rust_bdf": RUST_BDF,
"no_rebind": args.no_rebind,
"stock_ms": stock_ms,
"rust_ms": rust_ms,
"clean_unload": clean_unload,
"cleanup_ok": cleanup_ok,
"cleanup_errors": cleanup_errors,
"taint_before": taint_before,
"taint_after": taint_after,
"no_new_oops": no_new_oops,
"healthy_after": healthy_after,
"post_run_baseline": post_base_out,
"stock_result": stock_json,
"rust_result": rust_json,
"diffs": diffs,
}
REPORT_OUT.parent.mkdir(parents=True, exist_ok=True)
REPORT_OUT.write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps({"passed": report["passed"], "stock_ms": stock_ms, "rust_ms": rust_ms, "diff_count": len(diffs), "diffs": diffs}, indent=2))
return 0 if report["passed"] else 1
if __name__ == "__main__":
raise SystemExit(main())