diff --git a/messung/gpu/kern/dienst/dienst.py b/messung/gpu/kern/dienst/dienst.py index 53aa12f2..6a2e92c5 100644 --- a/messung/gpu/kern/dienst/dienst.py +++ b/messung/gpu/kern/dienst/dienst.py @@ -4,6 +4,8 @@ [--vorab baeume.json] [--nur-vorab] Schreibt nach dem Start eine JSON-Zeile {"bereit": true, "port": ...} nach stdout und laeuft, bis stdin schliesst oder SIGTERM kommt. +Abgekoppelt (Spielrechner, ohne Konsole): `--halt-datei ` laeuft ohne stdin, bis die Datei existiert (geprueft alle 0,5 s), +und loescht sie danach; `--pid-datei ` schreibt die PID (atomar) und loescht sie beim Ende. Start auf Windows: windows/dienst_start.ps1. Aufbau: ein Faden nimmt Verbindungen an, je Verbindung ein Faden liest Rahmen; EIN Arbeitsfaden besitzt das Geraet (ein CUDA-Kontext gehoert einem Faden). Der Arbeitsfaden rechnet in Runden (eine Runde = `pruefe_alle` Iterationen fuer alle laufenden Lagen eines @@ -812,6 +814,8 @@ def main(): ap.add_argument("--turn-plaetze", type=int, default=48, help="Plaetze je Turn-Baum (ein Turn-Teilspiel braucht 66-820 MB)") ap.add_argument("--vorab", help="JSON-Datei mit Baeumen, deren Kernel beim Start uebersetzt werden") ap.add_argument("--nur-vorab", action="store_true", help="Baeume, die nicht vorab uebersetzt sind, mit Fehler 9 ablehnen") + ap.add_argument("--halt-datei", help="ohne stdin laufen, bis diese Datei existiert (abgekoppelter Betrieb)") + ap.add_argument("--pid-datei", help="PID hierhin schreiben (atomar), beim Ende loeschen") ap.add_argument("--daten-plaetze", type=int, default=64, help="Plaetze des Daten-Stroms (Baum als Daten, art 13)") ap.add_argument("--daten-kapazitaet", type=int, nargs=3, default=(256, 768, 512), help="Knoten, Kanten, Blaetter je Lage im Daten-Strom") a = ap.parse_args() @@ -826,12 +830,24 @@ def main(): print(json.dumps(dict(bereit=True, port=port, geraet=a.geraet, plaetze=a.plaetze, turn_plaetze=a.turn_plaetze, pid=os.getpid(), start_s=round(time.perf_counter() - t0, 3), vorab_ms=[round(x[3] * 1e3, 1) for x in d.vorab_s])), flush=True) signal.signal(signal.SIGTERM, lambda *_: d.ende.set()) + if a.pid_datei: + tmp = a.pid_datei + ".tmp" + with open(tmp, "w") as f: + f.write(f"{os.getpid()} {port}\n") + os.replace(tmp, a.pid_datei) try: - while not d.ende.is_set() and sys.stdin.readline(): # laeuft, bis der Starter stdin schliesst - pass + if a.halt_datei: + while not d.ende.is_set() and not os.path.exists(a.halt_datei): + time.sleep(0.5) + else: + while not d.ende.is_set() and sys.stdin.readline(): # laeuft, bis der Starter stdin schliesst + pass except KeyboardInterrupt: pass d.stoppe() + for pfad in (a.halt_datei, a.pid_datei): + if pfad and os.path.exists(pfad): + os.remove(pfad) print(json.dumps(dict(beendet=True, **d.zaehler)), flush=True) diff --git a/messung/gpu/kern/windows/dienst_halt.ps1 b/messung/gpu/kern/windows/dienst_halt.ps1 new file mode 100644 index 00000000..85fc5c07 --- /dev/null +++ b/messung/gpu/kern/windows/dienst_halt.ps1 @@ -0,0 +1,8 @@ +# Haelt den GPU-Dienst an (legt die Halt-Datei an und wartet bis zu 15 s auf das Ende). Beendet nichts mit Gewalt. +$ordner = 'D:\Projects\pf-gpu-kern\dienst' +New-Item -ItemType File -Force -Path (Join-Path $ordner 'HALT') | Out-Null +for ($i = 0; $i -lt 30; $i++) { + if (-not (Test-Path (Join-Path $ordner 'DIENST.pid'))) { "beendet"; exit 0 } + Start-Sleep -Milliseconds 500 +} +"Dienst laeuft noch nach 15 s (PID in DIENST.pid)"; exit 1 diff --git a/messung/gpu/kern/windows/dienst_messung.py b/messung/gpu/kern/windows/dienst_messung.py new file mode 100644 index 00000000..55106fca --- /dev/null +++ b/messung/gpu/kern/windows/dienst_messung.py @@ -0,0 +1,121 @@ +"""Misst den laufenden GPU-Dienst auf dem Spielrechner: RAM, VRAM, CPU-Anteil im Leerlauf und unter River-Anfragen, Zeit je Anfrage. + + pokerbench-gpu-kern.exe dienst_messung.py --anfragen [--n 60] [--leer-s 10] [--port 47311] + +Der Dienst muss laufen (dienst_start.ps1; PID in D:\\Projects\\pf-gpu-kern\\dienst\\DIENST.pid). Prozessdaten ueber ctypes (GetProcessTimes, +K32GetProcessMemoryInfo), VRAM ueber einen nvidia-smi-Aufruf ohne Fenster. Haengt eine Zeile an windows/dienst_messung.jsonl an. +""" +import argparse +import ctypes +import json +import os +import subprocess +import sys +import time +from ctypes import wintypes + +import numpy as np + +HIER = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.dirname(HIER)) +sys.path.insert(0, os.path.join(os.path.dirname(HIER), "dienst")) +from kunde import Kunde # noqa: E402 + +OHNE_FENSTER = 0x08000000 | 0x4000 +k32 = ctypes.WinDLL("kernel32", use_last_error=True) + + +class _Speicher(ctypes.Structure): + _fields_ = [("cb", wintypes.DWORD), ("PageFaultCount", wintypes.DWORD), ("PeakWorkingSetSize", ctypes.c_size_t), + ("WorkingSetSize", ctypes.c_size_t), ("QuotaPeakPagedPoolUsage", ctypes.c_size_t), ("QuotaPagedPoolUsage", ctypes.c_size_t), + ("QuotaPeakNonPagedPoolUsage", ctypes.c_size_t), ("QuotaNonPagedPoolUsage", ctypes.c_size_t), ("PagefileUsage", ctypes.c_size_t), + ("PeakPagefileUsage", ctypes.c_size_t)] + + +def _griff(pid): + h = k32.OpenProcess(0x1000 | 0x0400 | 0x0010, False, pid) + if not h: + raise OSError(f"Prozess {pid} nicht offen: {ctypes.get_last_error()}") + return h + + +def cpu_s(h): + a, b, c, d = (wintypes.FILETIME() for _ in range(4)) + if not k32.GetProcessTimes(h, ctypes.byref(a), ctypes.byref(b), ctypes.byref(c), ctypes.byref(d)): + raise OSError("GetProcessTimes") + zu = lambda ft: ((ft.dwHighDateTime << 32) | ft.dwLowDateTime) / 1e7 + return zu(c) + zu(d) + + +def ram_gb(h): + m = _Speicher() + m.cb = ctypes.sizeof(m) + if not k32.K32GetProcessMemoryInfo(h, ctypes.byref(m), m.cb): + raise OSError("K32GetProcessMemoryInfo") + return m.WorkingSetSize / 1e9, m.PagefileUsage / 1e9 + + +def vram_gb(pid): + r = subprocess.run(["nvidia-smi", "--query-compute-apps=pid,used_memory", "--format=csv,noheader,nounits"], capture_output=True, text=True, + timeout=20, creationflags=OHNE_FENSTER) + for z in r.stdout.splitlines(): + teile = [x.strip() for x in z.split(",")] + if len(teile) == 2 and teile[0] == str(pid): + return int(teile[1]) / 1e3 + return None + + +def karte_prozent(): + r = subprocess.run(["nvidia-smi", "--query-gpu=utilization.gpu,memory.used", "--format=csv,noheader,nounits"], capture_output=True, text=True, + timeout=20, creationflags=OHNE_FENSTER) + u, m = (int(x) for x in r.stdout.strip().splitlines()[0].split(",")) + return u, m / 1e3 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--anfragen", required=True) + ap.add_argument("--n", type=int, default=60) + ap.add_argument("--leer-s", type=float, default=10.0) + ap.add_argument("--port", type=int, default=47311) + ap.add_argument("--pid-datei", default=r"D:\Projects\pf-gpu-kern\dienst\DIENST.pid") + a = ap.parse_args() + pid = int(open(a.pid_datei).read().split()[0]) + h = _griff(pid) + karte0 = karte_prozent() + c0, t0 = cpu_s(h), time.perf_counter() + time.sleep(a.leer_s) + leer_cpu = (cpu_s(h) - c0) / (time.perf_counter() - t0) + ram_leer = ram_gb(h) + vram_leer = vram_gb(pid) + anfragen = [] + with open(a.anfragen) as f: + for z in f: + if z.strip(): + anfragen.append(json.loads(z)) + if len(anfragen) >= a.n: + break + k = Kunde("127.0.0.1", a.port) + k.loese_baum(np.array([anfragen[0]["brett"]], np.uint8), np.array([anfragen[0]["reichweiten"]], np.float32), [anfragen[0]["spielbaum"]], max_iter=200) + ms, its = [], [] + c0, t0 = cpu_s(h), time.perf_counter() + for x in anfragen: + s0 = time.perf_counter() + antw = k.loese_baum(np.array([x["brett"]], np.uint8), np.array([x["reichweiten"]], np.float32), [x["spielbaum"]], + ziel_prozent=x.get("ziel_prozent", 0.5), max_iter=x.get("max_iter", 200)) + ms.append(1e3 * (time.perf_counter() - s0)) + its.append(antw.kopf["iterationen"][0]) + dauer = time.perf_counter() - t0 + last_cpu = (cpu_s(h) - c0) / dauer + zeile = dict(zeit=time.strftime("%Y-%m-%d %H:%M:%S"), pid=pid, karte_davor_prozent=karte0[0], karte_davor_gb=karte0[1], + leer_cpu_kerne=round(leer_cpu, 4), ram_gb=round(ram_leer[0], 3), privat_gb=round(ram_leer[1], 3), vram_gb=vram_leer, + last_cpu_kerne=round(last_cpu, 3), vram_nach_last_gb=vram_gb(pid), ram_nach_last_gb=round(ram_gb(h)[0], 3), n=len(ms), + ms_median=round(float(np.median(ms)), 1), ms_p90=round(float(np.percentile(ms, 90)), 1), ms_max=round(max(ms), 1), + iterationen_median=float(np.median(its)), gpu_anteil_unter_last=round(sum(ms) / 1e3 / dauer, 3)) + print(json.dumps(zeile)) + with open(os.path.join(HIER, "dienst_messung.jsonl"), "a") as f: + f.write(json.dumps(zeile) + "\n") + + +if __name__ == "__main__": + main() diff --git a/messung/gpu/kern/windows/dienst_start.ps1 b/messung/gpu/kern/windows/dienst_start.ps1 new file mode 100644 index 00000000..e061b242 --- /dev/null +++ b/messung/gpu/kern/windows/dienst_start.ps1 @@ -0,0 +1,24 @@ +# Startet den GPU-Dienst auf dem Spielrechner abgekoppelt: ohne Fenster, Prioritaet BelowNormal, Prozessname pokerbench-gpu-dienst.exe, +# 127.0.0.1:. Halt: Datei D:\Projects\pf-gpu-kern\dienst\HALT anlegen (dienst_halt.ps1); PID und Port in dienst\DIENST.pid, +# Ausgabe in dienst\dienst.log (nur anhaengen). Startet nicht, wenn schon ein Dienst laeuft. +# powershell -NoProfile -ExecutionPolicy Bypass -File dienst_start.ps1 [-Port 47311] [-Plaetze 64] +param([int]$Port = 47311, [int]$Plaetze = 64) +$wurzel = 'D:\Projects\pf-gpu-kern' +$ordner = Join-Path $wurzel 'dienst' +New-Item -ItemType Directory -Force -Path $ordner | Out-Null +$pid_datei = Join-Path $ordner 'DIENST.pid' +$halt = Join-Path $ordner 'HALT' +if (Test-Path $pid_datei) { + $alt = (Get-Content $pid_datei).Split(' ')[0] + if (Get-Process -Id $alt -ErrorAction SilentlyContinue) { "laeuft schon: PID $alt"; exit 1 } +} +if (Test-Path $halt) { Remove-Item $halt } +$exe = 'D:\Projects\venv-gpu\Scripts\pokerbench-gpu-dienst.exe' +if (-not (Test-Path $exe)) { Copy-Item 'D:\Projects\venv-gpu\Scripts\python.exe' $exe } +$log = Join-Path $ordner 'dienst.log' +$skript = Join-Path $wurzel 'messung\gpu\kern\dienst\dienst.py' +$kommando = "cmd /c `"`"$exe`" -u `"$skript`" --geraet cuda --port $Port --pruefe-alle 20 --pruefe-ab 20 --plaetze 64 --daten-plaetze $Plaetze --halt-datei `"$halt`" --pid-datei `"$pid_datei`" >> `"$log`" 2>&1`"" +# 0x08000000 CREATE_NO_WINDOW; Prioritaet ueber Win32_ProcessStartup (PriorityClass 16384 = BelowNormal), ShowWindow 0 +$start = New-CimInstance -ClassName Win32_ProcessStartup -ClientOnly -Property @{ ShowWindow = [uint16]0; PriorityClass = [uint32]16384; CreateFlags = [uint32]0x08000000 } +$r = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{ CommandLine = $kommando; CurrentDirectory = $wurzel; ProcessStartupInformation = $start } +"Rueckgabe $($r.ReturnValue), cmd-PID $($r.ProcessId); Dienst-PID steht nach dem Start in $pid_datei"