#!/usr/bin/env python3
"""GPU bench: measures what a rented GPU really delivers and prints a report with its sha256 fingerprint.

Needs an NVIDIA GPU with nvidia-smi. PyTorch is used for the compute and memory tests when it is installed;
without it, only the card's facts and host tests run. Nothing is uploaded: the report is printed and saved.
"""
import hashlib, json, os, platform, shutil, subprocess, sys, tempfile, time, urllib.request

SPEC = {  # (fp16 dense tensor TFLOPS, memory GB/s) from vendor spec sheets
    "RTX 4090": (165.2, 1008), "RTX 3090": (71.0, 936), "RTX 4080": (97.5, 717), "RTX 3080": (59.5, 760),
    "A100 80GB PCIe": (312, 1935), "A100-SXM4-80GB": (312, 2039), "A100-SXM4-40GB": (312, 1555), "A100-PCIE-40GB": (312, 1555),
    "H100 PCIe": (756, 2000), "H100 80GB HBM3": (989, 3350), "H100 NVL": (835, 3900), "L40S": (362, 864), "L40": (181, 864),
    "RTX A6000": (154.8, 768), "A40": (149.7, 696), "RTX A5000": (111, 768), "RTX 6000 Ada": (364, 960), "L4": (121, 300), "Tesla T4": (65, 320),
    "Tesla V100": (125, 900), "RTX 5090": (209.5, 1792),
}

def sh(cmd):
    try: return subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=60).stdout.strip()
    except Exception: return ""

def spec_for(name):
    for k, v in SPEC.items():
        if k.lower().replace("-", " ") in name.lower().replace("-", " "): return k, v
    return None, (None, None)

def gpu_facts():
    q = sh("nvidia-smi --query-gpu=name,memory.total,driver_version,power.limit,temperature.gpu --format=csv,noheader,nounits")
    if not q: sys.exit("No NVIDIA GPU found (nvidia-smi did not answer).")
    name, mem, drv, pwr, temp = [x.strip() for x in q.splitlines()[0].split(",")]
    procs = sh("nvidia-smi --query-compute-apps=pid --format=csv,noheader")
    return {"name": name, "vram_gb": round(float(mem) / 1024, 1), "driver": drv, "power_limit_w": float(pwr) if pwr.replace(".", "").isdigit() else None,
            "idle_temp_c": int(temp) if temp.isdigit() else None, "other_processes": len([p for p in procs.splitlines() if p.strip()]), "gpu_count": len(q.splitlines())}

def torch_tests():
    try: import torch
    except Exception: return {"skipped": "PyTorch not installed: pip install torch, then run again for compute and memory tests"}
    if not torch.cuda.is_available(): return {"skipped": "PyTorch cannot see the GPU"}
    d = torch.device("cuda"); out = {}
    n = 8192; a = torch.randn(n, n, device=d, dtype=torch.float16); b = torch.randn(n, n, device=d, dtype=torch.float16)
    for _ in range(3): a @ b
    torch.cuda.synchronize(); t = time.time(); it = 20
    for _ in range(it): a @ b
    torch.cuda.synchronize(); out["fp16_tflops"] = round(2 * n ** 3 * it / (time.time() - t) / 1e12, 1)
    del a, b
    x = torch.empty(int(1024 ** 3 / 2), device=d, dtype=torch.float16); y = torch.empty_like(x)  # 1 GiB each
    for _ in range(3): y.copy_(x)
    torch.cuda.synchronize(); t = time.time(); it = 20
    for _ in range(it): y.copy_(x)
    torch.cuda.synchronize(); out["mem_gbps"] = round(2 * x.numel() * 2 * it / (time.time() - t) / 1e9)  # read + write
    del x, y; torch.cuda.empty_cache()
    free, total = torch.cuda.mem_get_info(); blocks = []; got = 0
    try:
        while True: blocks.append(torch.empty(256 * 1024 ** 2, dtype=torch.uint8, device=d)); got += 0.25
    except RuntimeError: pass
    out["usable_vram_gb"] = round(got, 2); del blocks; torch.cuda.empty_cache()
    peak = sh("nvidia-smi --query-gpu=temperature.gpu,clocks_throttle_reasons.active --format=csv,noheader")
    if peak: t_, thr = [s.strip() for s in peak.splitlines()[0].split(",")]; out["temp_after_c"] = int(t_) if t_.isdigit() else None; out["throttle_flags"] = thr
    return out

def host_tests():
    out = {}
    p = os.path.join(tempfile.gettempdir(), "gpubench.bin"); blk = os.urandom(1024 ** 2)
    t = time.time()
    with open(p, "wb") as f:
        for _ in range(512): f.write(blk)
        f.flush(); os.fsync(f.fileno())
    out["disk_write_mbps"] = round(512 / (time.time() - t))
    t = time.time()
    with open(p, "rb") as f:
        while f.read(8 * 1024 ** 2): pass
    out["disk_read_mbps"] = round(512 / (time.time() - t)); os.remove(p)
    try:
        t = time.time(); n = 0
        with urllib.request.urlopen("https://speed.cloudflare.com/__down?bytes=50000000", timeout=30) as r:
            while True:
                c = r.read(1 << 20)
                if not c: break
                n += len(c)
        out["download_mbps"] = round(n * 8 / (time.time() - t) / 1e6)
    except Exception as e: out["download_mbps"] = None
    out["cpu"] = platform.processor() or platform.machine(); out["cores"] = os.cpu_count()
    out["ram_gb"] = round(os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES") / 1024 ** 3, 1) if hasattr(os, "sysconf") else None
    return out

def score(g, t):
    _, (tf, bw) = spec_for(g["name"]); parts = []
    if tf and t.get("fp16_tflops"): parts.append(min(1, t["fp16_tflops"] / tf))
    if bw and t.get("mem_gbps"): parts.append(min(1, t["mem_gbps"] / bw))
    if t.get("usable_vram_gb"): parts.append(min(1, t["usable_vram_gb"] / max(1, g["vram_gb"] - 1)))
    return round(100 * sum(parts) / len(parts)) if parts else None

def main():
    print("detecting GPU…"); g = gpu_facts(); print(f"  {g['name']} · {g['vram_gb']} GB · driver {g['driver']}")
    print("compute and memory …"); t = torch_tests()
    if "skipped" in t: print("  " + t["skipped"])
    else:
        k, (tf, bw) = spec_for(g["name"])
        print(f"  fp16 matmul   {t['fp16_tflops']} TFLOPS" + (f"   (spec {tf})" if tf else ""))
        print(f"  bandwidth     {t['mem_gbps']} GB/s" + (f"   (spec {bw})" if bw else ""))
        print(f"  usable VRAM   {t['usable_vram_gb']} GB of {g['vram_gb']}")
    print("host …"); h = host_tests(); print(f"  disk read {h['disk_read_mbps']} MB/s · write {h['disk_write_mbps']} MB/s · download {h['download_mbps']} Mb/s")
    rep = {"v": 1, "at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "gpu": g, "tests": t, "host": h, "score": score(g, t)}
    blob = json.dumps(rep, sort_keys=True, separators=(",", ":")); fp = "0x" + hashlib.sha256(blob.encode()).hexdigest()
    with open("gpubench-report.json", "w") as f: f.write(json.dumps({**rep, "fingerprint": fp}, indent=2))
    print(f"score {rep['score']} / 100" if rep["score"] is not None else "score: needs PyTorch tests")
    print(f"report fingerprint {fp}\nsaved gpubench-report.json")

if __name__ == "__main__": main()
