Files
nvdriver/tools/perf_bench.py

304 lines
12 KiB
Python

#!/usr/bin/env python3
"""Head-to-head GPU performance benchmark suite (proprietary nvidia.ko vs nvdriver/nvdriver).
Measures:
1. HBM2 Device-to-Device bandwidth (cuMemcpyDtoD 512 MiB) & PyTorch STREAM Triad (GB/s)
2. PCIe Pinned H2D & D2H bandwidth (256 MiB, GB/s)
3. FP16 Tensor Core GEMM (8192^3) & FP32 GEMM (8192^3) throughput (TFLOPS)
4. Eager small-kernel launch latency & CUDA Graph replay latency (us)
5. Memory-bound LayerNorm+GELU block & FP16 Transformer fwd+bwd (ms/iter)
6. llama.cpp (sm_70) LLM prompt eval (pp512) & token generation (tg128) (tok/s)
Emits one JSON object on stdout with `"passed": true`.
"""
from __future__ import annotations
import ctypes
import json
import os
from pathlib import Path
import subprocess
import time
try:
import torch
except ImportError: # pragma: no cover - allows offline helper imports without torch
torch = None # type: ignore[assignment]
REPO_ROOT = Path(__file__).resolve().parents[1]
def _pick_path(env_var: str, rel_path: str) -> Path:
override = os.environ.get(env_var)
if override:
return Path(override).resolve()
local = REPO_ROOT / rel_path
if local.exists():
return local
vm_path = Path("/repo") / rel_path
if vm_path.exists():
return vm_path
return local
def resolve_llama_paths() -> tuple[Path, Path, str]:
bin_path = _pick_path("LLAMA_BENCH", "target/llama.cpp/build/bin/llama-bench")
model_path = _pick_path("LLAMA_MODEL", "target/models/smollm2-135m-instruct-q4_k_m.gguf")
cuda_lib = os.environ.get("CUDA_LIB_DIR", "/usr/local/cuda-12.9/lib64")
ld_parts = [str(bin_path.parent)]
if cuda_lib and Path(cuda_lib).is_dir():
ld_parts.append(cuda_lib)
elif cuda_lib:
ld_parts.append(cuda_lib)
return bin_path, model_path, ":".join(ld_parts)
def cuda_event_bench(fn, warmup: int = 5, iters: int = 20) -> float:
"""Returns average GPU time per iteration in seconds using CUDA events."""
for _ in range(warmup):
fn()
torch.cuda.synchronize()
start = torch.cuda.Event(enable_timing=True)
end = torch.cuda.Event(enable_timing=True)
start.record()
for _ in range(iters):
fn()
end.record()
torch.cuda.synchronize()
return max((start.elapsed_time(end) / 1000.0) / iters, 1e-12)
def _configure_libcuda(cuda: ctypes.CDLL) -> None:
c_devptr = ctypes.c_uint64
cuda.cuMemAlloc_v2.argtypes = [ctypes.POINTER(c_devptr), ctypes.c_size_t]
cuda.cuMemAlloc_v2.restype = ctypes.c_int
cuda.cuMemAllocHost_v2.argtypes = [ctypes.POINTER(ctypes.c_void_p), ctypes.c_size_t]
cuda.cuMemAllocHost_v2.restype = ctypes.c_int
cuda.cuMemsetD32_v2.argtypes = [c_devptr, ctypes.c_uint32, ctypes.c_size_t]
cuda.cuMemsetD32_v2.restype = ctypes.c_int
cuda.cuMemcpyDtoD_v2.argtypes = [c_devptr, c_devptr, ctypes.c_size_t]
cuda.cuMemcpyDtoD_v2.restype = ctypes.c_int
cuda.cuMemcpyHtoD_v2.argtypes = [c_devptr, ctypes.c_void_p, ctypes.c_size_t]
cuda.cuMemcpyHtoD_v2.restype = ctypes.c_int
cuda.cuMemcpyDtoH_v2.argtypes = [ctypes.c_void_p, c_devptr, ctypes.c_size_t]
cuda.cuMemcpyDtoH_v2.restype = ctypes.c_int
cuda.cuCtxSynchronize.argtypes = []
cuda.cuCtxSynchronize.restype = ctypes.c_int
cuda.cuMemFreeHost.argtypes = [ctypes.c_void_p]
cuda.cuMemFreeHost.restype = ctypes.c_int
cuda.cuMemFree_v2.argtypes = [c_devptr]
cuda.cuMemFree_v2.restype = ctypes.c_int
def bench_pcie_and_d2d() -> dict:
cuda = ctypes.CDLL("libcuda.so.1")
_configure_libcuda(cuda)
def chk(rc, msg):
if rc != 0:
raise RuntimeError(f"{msg} failed: {rc}")
# PyTorch already initialized primary context on device 0.
d2d_bytes = 512 * 1024 * 1024
pcie_bytes = 256 * 1024 * 1024
d_a = ctypes.c_uint64(0)
d_b = ctypes.c_uint64(0)
h_pinned = ctypes.c_void_p(0)
try:
chk(cuda.cuMemAlloc_v2(ctypes.byref(d_a), ctypes.c_size_t(d2d_bytes)), "alloc d_a")
chk(cuda.cuMemAlloc_v2(ctypes.byref(d_b), ctypes.c_size_t(d2d_bytes)), "alloc d_b")
chk(cuda.cuMemAllocHost_v2(ctypes.byref(h_pinned), ctypes.c_size_t(pcie_bytes)), "alloc host")
chk(cuda.cuMemsetD32_v2(d_a, ctypes.c_uint32(0x12345678), ctypes.c_size_t(d2d_bytes // 4)), "memset")
chk(cuda.cuCtxSynchronize(), "sync")
# D2D (read + write = 2 * d2d_bytes of HBM traffic)
for _ in range(3):
chk(cuda.cuMemcpyDtoD_v2(d_b, d_a, ctypes.c_size_t(d2d_bytes)), "d2d warmup")
chk(cuda.cuCtxSynchronize(), "sync")
iters_d2d = 20
t0 = time.perf_counter()
for _ in range(iters_d2d):
chk(cuda.cuMemcpyDtoD_v2(d_b, d_a, ctypes.c_size_t(d2d_bytes)), "d2d")
chk(cuda.cuCtxSynchronize(), "sync")
dt_d2d = max((time.perf_counter() - t0) / iters_d2d, 1e-12)
d2d_gbps = (2.0 * d2d_bytes) / dt_d2d / 1e9
# H2D
for _ in range(2):
chk(cuda.cuMemcpyHtoD_v2(d_a, h_pinned, ctypes.c_size_t(pcie_bytes)), "h2d warmup")
chk(cuda.cuCtxSynchronize(), "sync")
iters_pcie = 10
t0 = time.perf_counter()
for _ in range(iters_pcie):
chk(cuda.cuMemcpyHtoD_v2(d_a, h_pinned, ctypes.c_size_t(pcie_bytes)), "h2d")
chk(cuda.cuCtxSynchronize(), "sync")
dt_h2d = max((time.perf_counter() - t0) / iters_pcie, 1e-12)
h2d_gbps = pcie_bytes / dt_h2d / 1e9
# D2H
for _ in range(2):
chk(cuda.cuMemcpyDtoH_v2(h_pinned, d_a, ctypes.c_size_t(pcie_bytes)), "d2h warmup")
chk(cuda.cuCtxSynchronize(), "sync")
t0 = time.perf_counter()
for _ in range(iters_pcie):
chk(cuda.cuMemcpyDtoH_v2(h_pinned, d_a, ctypes.c_size_t(pcie_bytes)), "d2h")
chk(cuda.cuCtxSynchronize(), "sync")
dt_d2h = max((time.perf_counter() - t0) / iters_pcie, 1e-12)
d2h_gbps = pcie_bytes / dt_d2h / 1e9
finally:
if h_pinned.value:
cuda.cuMemFreeHost(h_pinned)
if d_b.value:
cuda.cuMemFree_v2(d_b)
if d_a.value:
cuda.cuMemFree_v2(d_a)
return {
"hbm_d2d_gbps": round(d2d_gbps, 2),
"pcie_h2d_gbps": round(h2d_gbps, 2),
"pcie_d2h_gbps": round(d2h_gbps, 2),
}
def bench_pytorch() -> dict:
dev = torch.device("cuda:0")
torch.manual_seed(42)
# 1. STREAM Triad: a = b + 2.0 * c (64M fp32 = 256 MB each -> 768 MB HBM traffic)
n_el = 64 * 1024 * 1024
b = torch.ones(n_el, dtype=torch.float32, device=dev)
c = torch.full((n_el,), 2.0, dtype=torch.float32, device=dev)
a = torch.empty_like(b)
dt_triad = cuda_event_bench(lambda: torch.add(b, c, alpha=2.0, out=a), warmup=10, iters=50)
triad_gbps = (3.0 * n_el * 4) / dt_triad / 1e9
del a, b, c
# 2. FP16 Tensor Core GEMM (8192 x 8192)
m = 8192
x16 = torch.randn((m, m), dtype=torch.float16, device=dev)
y16 = torch.randn((m, m), dtype=torch.float16, device=dev)
dt_fp16 = cuda_event_bench(lambda: torch.mm(x16, y16), warmup=10, iters=30)
fp16_tflops = (2.0 * m * m * m) / dt_fp16 / 1e12
del x16, y16
# 3. FP32 GEMM (8192 x 8192)
x32 = torch.randn((m, m), dtype=torch.float32, device=dev)
y32 = torch.randn((m, m), dtype=torch.float32, device=dev)
dt_fp32 = cuda_event_bench(lambda: torch.mm(x32, y32), warmup=5, iters=20)
fp32_tflops = (2.0 * m * m * m) / dt_fp32 / 1e12
del x32, y32
# 4. Eager small-kernel launch latency (2000 tiny ops)
tiny = torch.ones(1024, dtype=torch.float32, device=dev)
for _ in range(100):
tiny.add_(1.0)
torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(2000):
tiny.add_(1.0)
torch.cuda.synchronize()
launch_us = (time.perf_counter() - t0) / 2000.0 * 1e6
# 5. CUDA Graph replay latency (50 ops per graph)
g = torch.cuda.CUDAGraph()
torch.cuda.synchronize()
with torch.cuda.graph(g):
for _ in range(50):
tiny.add_(1.0)
for _ in range(10):
g.replay()
torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(200):
g.replay()
torch.cuda.synchronize()
graph_replay_us = (time.perf_counter() - t0) / 200.0 * 1e6
del tiny, g
# 6. Memory-bound LayerNorm + GELU + Residual ([64, 1024, 2048] fp16)
act = torch.randn((64, 1024, 2048), dtype=torch.float16, device=dev)
ln = torch.nn.LayerNorm(2048, device=dev, dtype=torch.float16)
dt_memop = cuda_event_bench(lambda: act + torch.nn.functional.gelu(ln(act)), warmup=10, iters=30)
del act, ln
# 7. Transformer Encoder Layer fwd + bwd (batch=16, seq=512, d=1024, heads=16, fp16)
enc = torch.nn.TransformerEncoderLayer(
d_model=1024, nhead=16, dim_feedforward=4096, dropout=0.0,
batch_first=True, device=dev, dtype=torch.float16,
)
inp = torch.randn((16, 512, 1024), dtype=torch.float16, device=dev, requires_grad=True)
def step():
enc.zero_grad(set_to_none=True)
if inp.grad is not None:
inp.grad = None
out = enc(inp)
out.sum().backward()
dt_tx = cuda_event_bench(step, warmup=5, iters=20)
del enc, inp
torch.cuda.empty_cache()
return {
"stream_triad_gbps": round(triad_gbps, 2),
"fp16_gemm_tflops": round(fp16_tflops, 2),
"fp32_gemm_tflops": round(fp32_tflops, 2),
"eager_launch_us": round(launch_us, 2),
"cuda_graph_50ops_us": round(graph_replay_us, 2),
"membound_ln_gelu_ms": round(dt_memop * 1000.0, 3),
"transformer_fwdbwd_ms": round(dt_tx * 1000.0, 3),
}
def bench_llama_cpp() -> dict:
bin_path, model_path, ld = resolve_llama_paths()
if not bin_path.is_file() or not model_path.is_file():
missing = str(bin_path) if not bin_path.is_file() else str(model_path)
if os.environ.get("LLAMA_REQUIRED", "").strip() in ("1", "true", "yes"):
raise FileNotFoundError(f"llama.cpp benchmark asset missing: {missing}")
return {"llama_skipped": f"missing {missing}"}
env = os.environ.copy()
env["LD_LIBRARY_PATH"] = ld + (":" + env["LD_LIBRARY_PATH"] if env.get("LD_LIBRARY_PATH") else "")
cmd = [str(bin_path), "-m", str(model_path), "-ngl", "99", "-p", "512", "-n", "128", "-r", "3", "-o", "json"]
proc = subprocess.run(cmd, env=env, capture_output=True, text=True, timeout=120)
if proc.returncode != 0:
raise RuntimeError(f"llama-bench failed rc={proc.returncode}: {proc.stderr[-500:]}")
rows = json.loads(proc.stdout)
workloads = {(512, 0): "llama_pp512_tps", (0, 128): "llama_tg128_tps"}
res = {}
for row in rows:
metric = workloads.get((row.get("n_prompt"), row.get("n_gen")))
if metric is not None:
res[metric] = round(float(row["avg_ts"]), 2)
missing_metrics = [metric for metric in workloads.values() if metric not in res]
if missing_metrics:
raise RuntimeError(f"llama-bench missing requested results: {', '.join(missing_metrics)}")
return res
def main() -> int:
if torch is None:
print(json.dumps({"passed": False, "error": "PyTorch is not installed"}))
return 1
if torch.cuda.device_count() < 1:
print(json.dumps({"passed": False, "error": "no CUDA GPUs detected"}))
return 1
name = torch.cuda.get_device_name(0)
# Force CUDA primary context creation before direct libcuda calls.
_init = torch.empty(1, device="cuda:0")
torch.cuda.synchronize()
del _init
res = {
"passed": True,
"device_name": name,
"torch_version": torch.__version__,
}
res.update(bench_pcie_and_d2d())
res.update(bench_pytorch())
res.update(bench_llama_cpp())
print(json.dumps(res))
return 0
if __name__ == "__main__":
raise SystemExit(main())