Files
nexus/scripts/srv04-kern-test/block_cdg.py

202 lines
12 KiB
Python

#!/usr/bin/env python3
"""Kernprüfung Block C (Parallelität), D (Grenzen) und G (Prioritäten), #1263. Läuft auf dem Entwicklungsrechner.
Voraussetzung: remote.sh prepare, Tunnel `ssh -f -N -L 18100:127.0.0.1:18100 srv04`. Startet die Testinstanz selbst neu.
Aufruf: block_cdg.py ERGEBNIS.jsonl [c g d7 d6] Keine Antworttexte, kein Key in der Ausgabe.
"""
import collections, json, random, statistics, subprocess, sys, threading, time, urllib.request
import openai
BASE = "http://127.0.0.1:18100"
REMOTE = "bash /tmp/nexus-kern/remote.sh"
GRENZE = 12288 - 512
def ssh(cmd, timeout=120):
return subprocess.run(["ssh", "-o", "BatchMode=yes", "srv04", cmd], capture_output=True, text=True, timeout=timeout).stdout.strip()
KEY = ssh("cat /tmp/nexus-kern/key")
client = openai.OpenAI(base_url=BASE + "/v1", api_key=KEY, max_retries=0, timeout=400)
def status():
req = urllib.request.Request(BASE + "/gateway/v1/status", headers={"Authorization": "Bearer " + KEY})
return json.load(urllib.request.urlopen(req, timeout=30))["scheduler"]
def restart(*sched, vorher=""):
ssh(REMOTE + " stop")
# warten, bis das Gateway und seine Engines weg sind und die GPUs leer
ssh("for i in $(seq 1 90); do u=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | sort -n | tail -1); [ $u -lt 50 ] && ! curl -s -m1 " + BASE + "/gateway/v1/health >/dev/null && break; timeout 1 tail -f /dev/null; done")
if vorher: ssh(vorher)
ssh(REMOTE + " sched " + " ".join(f"'{x}'" for x in sched))
ssh(REMOTE + " start")
time.sleep(1)
class Monitor:
"""Beobachtet Buchungen (alle 2 s) und die echte GPU-Belegung."""
def __init__(self):
self.stop = threading.Event(); self.max_booked = [0, 0]; self.max_gpu = [0, 0]; self.verstoss = []; self.max_wartend = 0; self.n = 0
self.smi = subprocess.Popen(["ssh", "-o", "BatchMode=yes", "srv04", "timeout 1200 nvidia-smi --query-gpu=index,memory.used --format=csv,noheader,nounits -l 2"], stdout=subprocess.PIPE, text=True)
self.t = [threading.Thread(target=self.st, daemon=True), threading.Thread(target=self.gp, daemon=True)]
for t in self.t: t.start()
def st(self):
while not self.stop.wait(2):
try: s = status()
except Exception: continue
self.n += 1; self.max_wartend = max(self.max_wartend, len(s["waiting"]))
for g in (0, 1):
on = [i for i in s["instances"] if g in i["gpus"]]
booked = sum(i["booked_mb_per_gpu"] or 0 for i in on)
self.max_booked[g] = max(self.max_booked[g], booked)
if booked > GRENZE or (len(on) > 1 and any(i["booked_mb_per_gpu"] is None for i in on)):
self.verstoss.append(on)
names = [i["model"] for i in s["instances"]]
if len(names) != len(set(names)): self.verstoss.append(names)
def gp(self):
for line in self.smi.stdout:
try: g, m = [int(x) for x in line.split(",")]
except ValueError: continue
self.max_gpu[g] = max(self.max_gpu[g], m)
def end(self):
self.stop.set(); self.smi.terminate()
return {"proben": self.n, "max_gebucht_mb": self.max_booked, "max_gpu_mib": self.max_gpu, "max_wartend": self.max_wartend, "buchungsverstoesse": len(self.verstoss), "beispiel": self.verstoss[:2]}
def call(model, prio="normal", stream=False, max_tokens=150, timeout=400):
t = time.time(); r = {"model": model, "prio": prio, "stream": stream}
try:
c = client.with_options(timeout=timeout)
x = c.chat.completions.create(model=model, messages=[{"role": "user", "content": f"Erzähle kurz etwas über die Zahl {random.randint(1,999)}."}],
max_tokens=max_tokens, stream=stream, extra_headers={"X-Gateway-Priority": prio})
if stream:
ende = None
for p in x:
if "erstes" not in r: r["erstes"] = round(time.time() - t, 1)
if p.choices and p.choices[0].finish_reason: ende = p.choices[0].finish_reason
else:
ende = x.choices[0].finish_reason
r["ok"] = ende is not None
if not r["ok"]: r["code"] = "ohne_ende"
except openai.APIStatusError as e:
r.update(ok=False, code=e.code, status=e.status_code, retry_after=e.response.headers.get("retry-after"))
except Exception as e:
r.update(ok=False, code=type(e).__name__, text=str(e)[:150])
r["s"] = round(time.time() - t, 1)
return r
def summe(rs):
out = {}
for key in sorted({(r["model"], r["prio"]) for r in rs}):
g = [r for r in rs if (r["model"], r["prio"]) == key]; d = sorted(r["s"] for r in g)
out["/".join(key)] = {"n": len(g), "ok": sum(r["ok"] for r in g), "fehler": dict(collections.Counter(r.get("code") for r in g if not r["ok"])),
"median_s": statistics.median(d), "p95_s": d[int(len(d) * .95) - 1 if len(d) > 1 else 0], "max_s": d[-1]}
return out
def logzahlen():
prog = r'''import json,collections
c=collections.Counter(); w=collections.Counter()
for l in open("/tmp/nexus-kern/serve.log"):
try: d=json.loads(l)
except Exception: continue
e=d.get("ereignis")
if e and e!="zugeteilt": c[e+" "+str(d.get("model") or d.get("modell") or "")]+=1
if d.get("level")=="ERROR" or (d.get("level")=="WARN" and d.get("message")!="Anfrage beantwortet"): w[d.get("message","")[:120]]+=1
print(json.dumps({"ereignisse":dict(c),"warnungen":dict(w)}))'''
p = subprocess.run(["ssh", "-o", "BatchMode=yes", "srv04", "python3 -I -"], input=prog, capture_output=True, text=True, timeout=60)
return json.loads(p.stdout or "{}")
def ruhe():
time.sleep(5); s = status()
return {"wartend": len(s["waiting"]), "aktiv": sum(i["active"] for i in s["instances"]), "instanzen": [(i["model"], i["state"], i["booked_mb_per_gpu"]) for i in s["instances"]]}
def last(dauer, arbeiter):
ergebnisse, ende = [], time.time() + dauer
def lauf(fn):
while time.time() < ende: ergebnisse.append(fn())
ts = [threading.Thread(target=lauf, args=(f,)) for f in arbeiter]
for t in ts: t.start()
for t in ts: t.join()
return ergebnisse
def block_c(emit):
restart("idle_secs = 600", "maya_idle_secs = 600")
modelle = ["bonsai", "darkidol", "ollama-gemma3-4b", "erebus", "cydonia"]
emit({"fall": "c_aufwaermen", "rs": [call(m, "high", max_tokens=5) for m in modelle]})
with __import__("concurrent.futures").futures.ThreadPoolExecutor(8) as ex:
rs = list(ex.map(lambda i: call("qwen36", "high", stream=i % 2 == 0, max_tokens=40), range(8)))
emit({"fall": "c_gleiches_modell_kalt", "summe": summe(rs), "log": logzahlen()})
restart("idle_secs = 600", "maya_idle_secs = 600")
mon = Monitor()
rs = last(600, [lambda: call(random.choice(modelle), stream=random.random() < .5, max_tokens=random.randint(30, 300)) for _ in range(10)])
emit({"fall": "c_dauerlast", "anfragen": len(rs), "summe": summe(rs), "monitor": mon.end(), "ruhe": ruhe(), "log": logzahlen()})
def block_vergleich(emit, fristen=(60, 0)):
"""Dieselbe Mischlast je 600 s mit Schonfrist 60 (Standard) und 0, mit GPU-Auslastung."""
modelle = ["bonsai", "darkidol", "ollama-gemma3-4b", "erebus", "cydonia"]
for frist in fristen:
restart("idle_secs = 600", f"evict_min_idle_secs = {frist}")
smi = subprocess.Popen(["ssh", "-o", "BatchMode=yes", "srv04", "timeout 600 nvidia-smi --query-gpu=utilization.gpu --format=csv,noheader,nounits -l 2"], stdout=subprocess.PIPE, text=True)
werte = []
leser = threading.Thread(target=lambda: werte.extend(int(x) for x in smi.stdout if x.strip().isdigit())); leser.start()
random.seed(1263); start = time.time(); mon = Monitor()
rs = last(600, [lambda: call(random.choice(modelle), stream=random.random() < .5, max_tokens=random.randint(30, 300)) for _ in range(10)])
dauer = round(time.time() - start); leser.join(timeout=30)
d = sorted(r["s"] for r in rs)
emit({"fall": f"vergleich_schonfrist_{frist}", "anfragen": len(rs), "ok": sum(r["ok"] for r in rs), "dauer_s": dauer, "median_s": statistics.median(d), "max_s": d[-1],
"gpu_proben": len(werte), "anteil_proben_ohne_gpu_last": round(sum(w == 0 for w in werte) / max(len(werte), 1), 2),
"monitor": mon.end(), "ruhe": ruhe(), "log": logzahlen()})
def block_nachmessung(emit):
"""Nach #1269: gleiche Mischlast mit der neuen Standard-Schonfrist von 5 s."""
block_vergleich(emit, (5,))
def block_g(emit):
restart("idle_secs = 600", "maya_idle_secs = 600")
mon = Monitor()
def high():
time.sleep(45); return call("darkidol", "high", max_tokens=30)
rs = last(480, [lambda: call("erebus", "low", max_tokens=150)] * 4 + [lambda: call("cydonia", "normal", max_tokens=150)] * 4 + [high])
emit({"fall": "g_prioritaeten", "summe": summe(rs), "high_einzeln": [(r["ok"], r["s"]) for r in rs if r["prio"] == "high"], "monitor": mon.end(), "ruhe": ruhe(), "log": logzahlen()})
def block_d7(emit):
restart("idle_secs = 600", "max_waiting = 3", "max_wait_secs = 40")
call("erebus", "high", max_tokens=5)
lang = {}
def stream_lang():
lang.update(call("erebus", stream=True, max_tokens=3500))
t = threading.Thread(target=stream_lang); t.start(); time.sleep(3)
rs, ts = [], []
for _ in range(6):
x = threading.Thread(target=lambda: rs.append(call("cydonia", max_tokens=5))); x.start(); ts.append(x); time.sleep(.3)
time.sleep(3); waehrend = status()
for x in ts: x.join()
emit({"fall": "d7_voll_und_zeitlimit", "wartend_waehrend": len(waehrend["waiting"]), "rs": rs})
t.join(); emit({"fall": "d7_langer_stream", "r": lang, "ruhe": ruhe()})
# Abbruch eines wartenden und eines streamenden Clients
s = client.chat.completions.create(model="erebus", messages=[{"role": "user", "content": "Erzähle eine lange Geschichte."}], max_tokens=3500, stream=True)
next(iter(s))
a = call("cydonia", max_tokens=5, timeout=4); time.sleep(2); nach_a = status()
aktiv_vorher = sum(i["active"] for i in nach_a["instances"])
t0 = time.time(); s.close()
time.sleep(4); nach_b = status()
emit({"fall": "d7_abbruch", "wartender": a, "wartend_nach_abbruch": len(nach_a["waiting"]), "aktiv_mit_stream": aktiv_vorher,
"aktiv_nach_streamabbruch": sum(i["active"] for i in nach_b["instances"]), "folge": call("cydonia", "high", max_tokens=5), "ruhe": ruhe(), "log": logzahlen()})
def block_d6(emit):
n = "/tmp/nexus-kern/bin/nexus"; cfg = "--config /tmp/nexus-kern/config.toml"
restart("idle_secs = 600", vorher=f"{n} model add --name darkidol-klein --path /srv/models/gguf/DarkIdol-Llama-3.1-8B-Instruct-1.2-Uncensored-Q6_K.gguf --gpus 0 --context 32768 --vram-mb 1000 {cfg}")
mon = Monitor()
a = call("erebus", "high", max_tokens=5); b = call("darkidol-klein", "normal", max_tokens=5); nach = ruhe()
gpu = ssh("nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits").split()
c = call("erebus", max_tokens=5); d = call("darkidol-klein", max_tokens=5)
emit({"fall": "d6_zu_klein_angegeben", "erebus": a, "luege": b, "zustand": nach, "gpu_mib": gpu, "erebus_danach": c, "luege_wieder": d, "ruhe": ruhe(),
"gemessen": ssh(f"{n} model list {cfg} | grep -E 'darkidol-klein|erebus'"), "monitor": mon.end(), "log": logzahlen()})
def main():
out = sys.argv[1]
with open(out, "a") as f:
def emit(d):
f.write(json.dumps(d, ensure_ascii=False) + "\n"); f.flush(); print(d["fall"], flush=True)
for b in sys.argv[2:] or ["c", "g", "d7", "d6"]:
try: globals()["block_" + b](emit)
except Exception as e: emit({"fall": b + "_abbruch_des_skripts", "fehler": repr(e)[:500]})
main()