fix: fremde GPU-Belegung vor dem Start messen (#1275)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-02 15:24:38 +01:00
parent 8a34ab835b
commit 2b434b914b
4 changed files with 109 additions and 33 deletions

View File

@ -4,15 +4,17 @@
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 collections, json, os, random, shlex, 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
# Falls der Name nicht auflöst: NEXUS_SSH_OPTS="-o HostName=ADRESSE -o HostKeyAlias=srv04"
SSH = ["ssh", "-o", "BatchMode=yes", *shlex.split(os.environ.get("NEXUS_SSH_OPTS", "")), "srv04"]
def ssh(cmd, timeout=120):
return subprocess.run(["ssh", "-o", "BatchMode=yes", "srv04", cmd], capture_output=True, text=True, timeout=timeout).stdout.strip()
return subprocess.run([*SSH, 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)
@ -34,7 +36,7 @@ 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.smi = subprocess.Popen([*SSH, "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):
@ -99,7 +101,7 @@ for l in open("/tmp/nexus-kern/serve.log"):
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)
p = subprocess.run([*SSH, "python3 -I -"], input=prog, capture_output=True, text=True, timeout=60)
return json.loads(p.stdout or "{}")
def ruhe():
@ -132,7 +134,7 @@ def block_vergleich(emit, fristen=(60, 0)):
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)
smi = subprocess.Popen([*SSH, "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()

View File

@ -5,7 +5,7 @@ Voraussetzung: remote.sh prepare, Tunnel wie in block_ab.py. Beendet nur Prozess
Testinstanz gehören. Aufruf: block_ef.py ERGEBNIS.jsonl [f_llama f_ollama f_strata f_maya f_neustart e_gpu e_ram e_fehlt]
"""
import json, subprocess, sys, threading, time
from block_cdg import BASE, REMOTE, call, client, ruhe, ssh, status, restart, logzahlen
from block_cdg import BASE, REMOTE, SSH, call, client, ruhe, ssh, status, restart, logzahlen
PROCS = r'''
import json,os,re,subprocess
@ -41,7 +41,7 @@ used=subprocess.run(["nvidia-smi","--query-gpu=memory.used","--format=csv,nohead
print(json.dumps({"root":root,"procs":res,"gpus":[int(x) for x in used]}))
'''
def procs():
p = subprocess.run(["ssh", "-o", "BatchMode=yes", "srv04", "python3 -I -"], input=PROCS, capture_output=True, text=True, timeout=60)
p = subprocess.run([*SSH, "python3 -I -"], input=PROCS, capture_output=True, text=True, timeout=60)
return json.loads(p.stdout)
def eigene(s): return [r for r in s["procs"] if r["tiefe"] is not None]
@ -72,7 +72,7 @@ def anfrage(model, stream, ereignis=None, ergebnis=None, max_tokens=2500, timeou
else: ende = x.choices[0].finish_reason
r.update(ok=ende is not None, ende=ende)
except Exception as e:
r.update(ok=False, fehler=type(e).__name__, code=getattr(e, "code", None), status=getattr(e, "status_code", None))
r.update(ok=False, fehler=type(e).__name__, code=getattr(e, "code", None), status=getattr(e, "status_code", None), text=str(getattr(e, "body", None) or e)[:260])
r["s"] = round(time.time() - t, 1)
if ereignis: ereignis.set()
if ergebnis is not None: ergebnis.update(r)
@ -149,7 +149,8 @@ def e_gpu(emit):
faelle[m] = {"r": r, "gpus_mib": p["gpus"], "eigene": kurz(eigene(p)), "ruhe": ruhe(), "gateway": ssh(f"curl -s -m3 {BASE}/gateway/v1/health || echo weg")}
if r["ok"]: # Instanz wieder loswerden, damit der naechste Fall frei beginnt
restart("idle_secs = 900"); aufraeumen()
emit({"fall": "e_fremde_gpu_belegung", "belegt_mib": belegt, "faelle": faelle, "log": logzahlen()})
gemessen = ssh("/tmp/nexus-kern/bin/nexus model list --config /tmp/nexus-kern/config.toml | grep ollama-gemma3")
emit({"fall": "e_fremde_gpu_belegung", "belegt_mib": belegt, "faelle": faelle, "gemessen_ollama": gemessen, "log": logzahlen()})
finally:
hog_ende()
emit({"fall": "e_nach_ende_der_belegung", "folge": {m: call(m, "high", max_tokens=5) for m in ("darkidol", "cydonia")}, "ruhe": ruhe()})
@ -158,13 +159,21 @@ def e_ram(emit):
"""Die Testinstanz laeuft in einem eigenen Speicherlimit; die Produktion bleibt davon unberuehrt."""
for modell, grenze in (("maya", "20G"), ("strata-q2_0", "12G")):
restart("idle_secs = 900"); aufraeumen(); ssh(REMOTE + " stop; timeout 30 tail -f /dev/null; true", 60)
ssh(f"export XDG_RUNTIME_DIR=/run/user/$(id -u); cd /tmp/nexus-kern; setsid nohup systemd-run --user --scope -q -p MemoryMax={grenze} -p MemorySwapMax=0 /tmp/nexus-kern/bin/nexus serve --config /tmp/nexus-kern/config.toml > serve.log 2>&1 < /dev/null & sleep 3; pgrep -u $(id -u) -f '^/tmp/nexus-kern/bin/nexus serve' | head -1 > /tmp/nexus-kern/nexus.pid")
ssh(f"export XDG_RUNTIME_DIR=/run/user/$(id -u); cd /tmp/nexus-kern; setsid nohup systemd-run --user --scope -q -p MemoryMax={grenze} -p MemorySwapMax=0 -p OOMPolicy=continue /tmp/nexus-kern/bin/nexus serve --config /tmp/nexus-kern/config.toml > serve.log 2>&1 < /dev/null & sleep 3; pgrep -u $(id -u) -f '^/tmp/nexus-kern/bin/nexus serve' | head -1 > /tmp/nexus-kern/nexus.pid")
r = anfrage(modell, False, max_tokens=20, timeout=420); time.sleep(10); p = procs()
d = {"fall": f"e_ram_{modell}_{grenze}", "r": r, "gateway": ssh(f"curl -s -m3 {BASE}/gateway/v1/health || echo weg"), "eigene": kurz(eigene(p)), "waisen": kurz(waisen(p)), "gpus_mib": p["gpus"]}
if d["gateway"] != "weg":
d["ruhe"] = ruhe(); d["kleines_modell_danach"] = call("bonsai", "high", max_tokens=5)
d["log"] = logzahlen(); emit(d)
def e_pruefung(emit):
"""#1277: RAM-Angabe groesser als frei verfuegbar: nichts starten, Grund nennen."""
n = "/tmp/nexus-kern/bin/nexus"; cfg = "--config /tmp/nexus-kern/config.toml"
restart("idle_secs = 900", vorher=f"{n} model set --name bonsai --ram-mb 500000 {cfg}")
r = anfrage("bonsai", False, max_tokens=5); p = procs()
ssh(f"{n} model set --name bonsai --ram-mb 0 {cfg}")
emit({"fall": "e_ram_angabe", "r": r, "eigene": kurz(eigene(p)), "ruhe": ruhe(), "danach": call("bonsai", max_tokens=5)})
def e_fehlt(emit):
n = "/tmp/nexus-kern/bin/nexus"; cfg = "--config /tmp/nexus-kern/config.toml"
restart("idle_secs = 900", vorher=f"ln -sf /srv/models/gguf/Bonsai-1.7B-Q1_0.gguf /tmp/nexus-kern/weg.gguf && {n} model add --name datei-weg --path /tmp/nexus-kern/weg.gguf --gpus 0 {cfg} && rm /tmp/nexus-kern/weg.gguf")