# cont 6-A: which sustained load takes the card to NVML P0, and when. Logs pstate/clocks every 250 ms per load.
import time, torch, pynvml
pynvml.nvmlInit(); h = pynvml.nvmlDeviceGetHandleByIndex(0)
def rd(): return (pynvml.nvmlDeviceGetPerformanceState(h), pynvml.nvmlDeviceGetClockInfo(h, 1), pynvml.nvmlDeviceGetClockInfo(h, 2))
d = "cuda:0"
rbuf = torch.empty(64 << 20, dtype=torch.float32, device=d)
a = torch.randn(4096, 4096, device=d, dtype=torch.float16); b = torch.randn_like(a)
loads = {
  "idle": lambda: time.sleep(0.01),
  "read_sum": lambda: rbuf.sum(),
  "add_inplace": lambda: rbuf.add_(1.0),
  "hgemm": lambda: a @ b,
}
t00 = time.monotonic()
for name in ["idle", "read_sum", "add_inplace", "hgemm", "idle", "add_inplace"]:
    t0 = time.monotonic(); last = -1; seen = []
    while time.monotonic() - t0 < 15:
        for _ in range(8): loads[name]()
        torch.cuda.synchronize()
        if time.monotonic() - last >= 0.25:
            last = time.monotonic(); seen.append((round(last - t0, 2), *rd()))
    first0 = next((s[0] for s in seen if s[1] == 0), None)
    from collections import Counter
    print(f"{name:12s} t={t0-t00:5.1f} first_P0_at={first0} states={dict(Counter(s[1] for s in seen))} last={seen[-1]}", flush=True)
