Files
nvdriver/tools/perf_bench.py

232 lines
8.4 KiB
Python

#!/usr/bin/env python3
"""Head-to-head GPU performance benchmark suite (proprietary nvidia.ko vs QuixiAI/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
import subprocess
import time
import torch
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 (start.elapsed_time(end) / 1000.0) / iters
def bench_pcie_and_d2d() -> dict:
cuda = ctypes.CDLL("libcuda.so.1")
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)
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 = (time.perf_counter() - t0) / iters_d2d
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 = (time.perf_counter() - t0) / iters_pcie
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 = (time.perf_counter() - t0) / iters_pcie
d2h_gbps = pcie_bytes / dt_d2h / 1e9
cuda.cuMemFreeHost(h_pinned)
cuda.cuMemFree_v2(d_b)
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 = "/repo/target/llama.cpp/build/bin/llama-bench"
model_path = "/repo/target/models/smollm2-135m-instruct-q4_k_m.gguf"
env = os.environ.copy()
ld = "/repo/target/llama.cpp/build/bin:/usr/local/cuda-12.9/lib64"
env["LD_LIBRARY_PATH"] = ld + (":" + env["LD_LIBRARY_PATH"] if env.get("LD_LIBRARY_PATH") else "")
cmd = [bin_path, "-m", 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)
res = {}
for row in rows:
if row.get("n_prompt", 0) > 0 and row.get("n_gen", 0) == 0:
res["llama_pp512_tps"] = round(float(row["avg_ts"]), 2)
elif row.get("n_gen", 0) > 0 and row.get("n_prompt", 0) == 0:
res["llama_tg128_tps"] = round(float(row["avg_ts"]), 2)
return res
def main() -> int:
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())