Files
nvdriver/tools/dual_gpu_parity.py

186 lines
8.0 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
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())
ps = sh("ps -eo stat,comm | grep -E '^D.*(nv_open_q|nvidia)' || true").stdout.strip()
return taint, (ps == "")
def parse_last_json(stdout: str) -> dict:
for line in reversed(stdout.strip().splitlines()):
line = line.strip()
if line.startswith("{") and line.endswith("}"):
return json.loads(line)
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 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 = sh("sudo dmesg | awk 'END { if (match($0, /^\\[[ ]*([0-9]+\\.[0-9]+)\\]/, m)) print m[1]; else print 0 }'").stdout.strip()
if Path(f"/sys/bus/pci/devices/{RUST_BDF}/driver").exists():
sh(f"sudo python3 {ROOT}/tools/gpu_binding.py release {RUST_BDF}")
sh(f"sudo insmod {ROOT}/kernel-open/nvidia_rs.ko pci_target={RUST_BDF} runtime_engines=1")
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")
strace_out = OUT_DIR / "dual-gpu-parity.strace"
dmesg_out = OUT_DIR / "dual-gpu-parity.dmesg"
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)
# Unbind before rmmod
sh(f"echo {RUST_BDF} | sudo tee /sys/bus/pci/drivers/nvidia_rs/unbind >/dev/null")
sh(f"echo '' | sudo tee /sys/bus/pci/devices/{RUST_BDF}/driver_override >/dev/null")
sh("sudo rmmod nvidia_rs")
dmesg_text = sh(
f"sudo dmesg | awk -v ts='{dmesg_ts}' '{{ if (match($0, /^\\[[ ]*([0-9]+\\.[0-9]+)\\]/, m) && (m[1] + 0) > (ts + 0)) print }}' "
f"| grep -E 'nvidia_rs|{RUST_BDF}' || true"
).stdout
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.")
else:
if not clean_unload:
DIRTY_SENTINEL.write_text(current_boot_id() + "\n")
print("UNSAFE TO REBIND STOCK NVIDIA: clean GR unload (4752001a 00000000) NOT observed!")
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()
print(f"rust rc={rust_proc.returncode} ({rust_ms} ms)")
if rust_proc.stderr.strip():
print("RUST STDERR:", rust_proc.stderr.strip())
rust_json = parse_last_json(rust_proc.stdout) if "{" in rust_proc.stdout else {"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 healthy_after),
"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,
"taint_before": taint_before,
"taint_after": taint_after,
"healthy_after": healthy_after,
"post_run_baseline": post_base_out,
"stock_result": stock_json,
"rust_result": rust_json,
"diffs": diffs,
}
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())