Download engine/tests/gpu_link_smoke.py from amogaddy/neuronal: direct link, hf CLI and curl.
- Browser
- Download file 8.43 kB
-
https://huggingface.co/spaces/amogaddy/neuronal/resolve/main/engine/tests/gpu_link_smoke.py
- Command line
-
hf download hf://spaces/amogaddy/neuronal/engine/tests/gpu_link_smoke.py
-
curl -L -o gpu_link_smoke.py https://huggingface.co/spaces/amogaddy/neuronal/resolve/main/engine/tests/gpu_link_smoke.py
8.43 kB
| """GPU in prestito: il motore gira solo sulla CPU, il modello gira in un altro processo sulla GPU | |
| (come nello Space ZeroGPU) e fa solo i calcoli. Qui il servizio GPU è finto: avvia neuronal-brain sul PC. | |
| Avvia il motore da sé su una cartella di stato temporanea: argomento 1 = cartella.""" | |
| import asyncio, json, os, shutil, struct, subprocess, sys, time, urllib.request | |
| import websockets | |
| sys.stdout.reconfigure(encoding="utf-8") | |
| ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
| sys.path.insert(0, os.path.join(ROOT, "huggingface", "zerogpu")) | |
| from ponte import ponte | |
| STATE = sys.argv[1] | |
| PORT = 7862 | |
| URL = f"ws://127.0.0.1:{PORT}/ws" | |
| RUNTIME = os.path.join(ROOT, "runtime", "llamacpp-b11200") | |
| ENV = dict(os.environ, PATH=RUNTIME + os.pathsep + os.environ["PATH"]) | |
| failures, sessioni, avviate = [], [], [0] | |
| rifiuta = False | |
| def check(cond, what): | |
| print((" ok " if cond else " FAIL ") + what) | |
| if not cond: | |
| failures.append(what) | |
| def wait_up(timeout=600): | |
| end = time.time() + timeout | |
| while time.time() < end: | |
| try: | |
| urllib.request.urlopen(f"http://127.0.0.1:{PORT}/health", timeout=2) | |
| return True | |
| except OSError: | |
| time.sleep(1) | |
| return False | |
| utenti = [] # la chiave del visitatore che il motore passa al servizio a ogni richiesta | |
| CHIAVE = "hf_" + "AbC123_-." * 4 # finta: serve solo a vedere che arrivi al servizio | |
| async def servizio_gpu(): | |
| """Il servizio finto: alla richiesta avvia il cervello sulla GPU del PC e lo collega al motore.""" | |
| async with websockets.connect(f"{URL}?role=gpu", max_size=None) as ws: | |
| async def sessione(biglietto): | |
| avviate[0] += 1 | |
| comando = [os.path.join(ROOT, "build", "neuronal-brain.exe"), os.path.join(ROOT, "neuronal.gguf"), RUNTIME, "", "8192"] | |
| t = await ponte(comando, f"{URL}?role=brain&ticket={biglietto}", 50, cwd=ROOT, env=ENV) | |
| sessioni.append(t) | |
| print(f" [GPU] sessione finita dopo {t:.1f} s") | |
| async for m in ws: | |
| if isinstance(m, str) and '"gpu_need"' in m: | |
| if rifiuta: | |
| await ws.send(json.dumps({"cmd": "gpu_status", "ok": False, "message": "prova di rifiuto", "retry": 600})) | |
| else: | |
| ev = json.loads(m) | |
| utenti.append(ev.get("user", "?")) | |
| asyncio.ensure_future(sessione(ev["ticket"])) | |
| async def chat(ws, text, timeout=240, **kw): | |
| await ws.send(json.dumps({"cmd": "chat", "text": text, **kw})) | |
| frames, t0, first = 0, time.time(), None | |
| while time.time() - t0 < timeout: | |
| m = await asyncio.wait_for(ws.recv(), timeout=timeout) | |
| if isinstance(m, bytes): | |
| if m[0] == ord("A"): | |
| frames += 1 | |
| nl, k = struct.unpack_from("<HH", m, 2) | |
| assert len(m) == 12 + nl * (4 + 6 * k), "frame dell'attività malformato" | |
| continue | |
| ev = json.loads(m) | |
| if ev["ev"] == "token" and first is None: | |
| first = time.time() - t0 | |
| if ev["ev"] == "done": | |
| return ev, frames, first, time.time() - t0 | |
| raise TimeoutError(text) | |
| async def until(ws, name, timeout=30): | |
| end = time.time() + timeout | |
| while time.time() < end: | |
| m = await asyncio.wait_for(ws.recv(), timeout=max(0.1, end - time.time())) | |
| if isinstance(m, str) and json.loads(m)["ev"] == name: | |
| return json.loads(m) | |
| raise TimeoutError(name) | |
| async def main(): | |
| global rifiuta | |
| check(wait_up(), "motore acceso (solo CPU)") | |
| gpu = asyncio.ensure_future(servizio_gpu()) | |
| await asyncio.sleep(1) | |
| async with websockets.connect(URL, max_size=None) as ws: | |
| await until(ws, "hello") | |
| print("0) login Hugging Face: la chiave del visitatore arriva al servizio, quella non valida no") | |
| await ws.send(json.dumps({"cmd": "hf_token", "token": "hf_" + "x" * 30 + "\"}"})) # caratteri non ammessi: ignorata | |
| await ws.send(json.dumps({"cmd": "hf_token", "token": CHIAVE})) | |
| print("1) una risposta calcolata sulla GPU in prestito") | |
| ev, frames, first, dt = await chat(ws, "Quanto fa 7 per 8? Rispondi solo con il numero.") | |
| print(f" -> {ev['answer']!r} ({ev['tokens']} token in {dt:.1f} s, prima parola dopo {first:.1f} s, {frames} frame dei neuroni)") | |
| check("56" in ev["answer"], "risposta corretta (56)") | |
| check(utenti and utenti[0] == CHIAVE, "il servizio riceve la chiave del visitatore (e non quella non valida)") | |
| check(frames >= 1, "l'attività dei neuroni arriva alla pagina a ogni parola") | |
| check(dt < 60, "tempi da GPU, non da CPU") | |
| print("2) la GPU si restituisce da sola quando resta ferma") | |
| await asyncio.sleep(8) | |
| check(len(sessioni) >= 1, f"sessione chiusa dopo l'ultima parola ({sessioni[0]:.1f} s)" if sessioni else "sessione chiusa") | |
| print("3) gli interventi sui neuroni arrivano al cervello remoto") | |
| await ws.send(json.dumps({"cmd": "hf_token", "token": ""})) # il visitatore esce: si torna ai minuti dello Space | |
| await ws.send(json.dumps({"cmd": "clear"})) | |
| await until(ws, "cleared") | |
| base, _, _, _ = await chat(ws, "Scrivi una frase sul mare.") | |
| for layer in range(20, 44): | |
| await ws.send(json.dumps({"cmd": "neurons", "layer": layer, "top": 4000, "factor": -2})) | |
| tot = (await until(ws, "interventions"))["total"] | |
| print(f" neuroni spenti: {tot}") | |
| await ws.send(json.dumps({"cmd": "clear"})) # senza cronologia: altrimenti ripeterebbe la risposta di prima | |
| await until(ws, "cleared") | |
| rotto, _, _, _ = await chat(ws, "Scrivi una frase sul mare.") | |
| print(f" prima: {base['answer'][:90]!r}\n dopo: {rotto['answer'][:90]!r}") | |
| check(base["answer"] != rotto["answer"], "con 96000 neuroni invertiti la risposta cambia") | |
| check(len(utenti) >= 2 and utenti[-1] == "", "dopo l'uscita il servizio non riceve più la chiave") | |
| await ws.send(json.dumps({"cmd": "reset"})) | |
| await until(ws, "interventions") | |
| print("4) ragionamento e più scambi di fila") | |
| await ws.send(json.dumps({"cmd": "clear"})) | |
| await until(ws, "cleared") | |
| ev, frames, first, dt = await chat(ws, "Quanto fa 12 più 30? Rispondi solo con il numero.", thinking=True, think_budget=64) | |
| print(f" -> {ev['answer']!r} ({dt:.1f} s)") | |
| check(ev["answer"].strip().rstrip(".") == "42", "risposta corretta (42)") | |
| print("5) senza GPU il motore continua sulla CPU") | |
| rifiuta = True # le prossime richieste di GPU vengono rifiutate | |
| fine = time.time() + 120 | |
| while len(sessioni) < avviate[0] and time.time() < fine: # aspetta che l'ultima sessione sia restituita | |
| await asyncio.sleep(0.5) | |
| chiuse = len(sessioni) | |
| ev, frames, first, dt = await chat(ws, "Di' solo: ciao.", timeout=600) | |
| print(f" -> {ev['answer']!r} ({dt:.1f} s sulla CPU)") | |
| check(len(ev["answer"]) > 0 and frames >= 1, "risposta arrivata lo stesso, con i neuroni") | |
| check(len(sessioni) == chiuse and avviate[0] == chiuse, "calcolata davvero sulla CPU (nessuna sessione di GPU)") | |
| gpu.cancel() | |
| os.makedirs(STATE, exist_ok=True) | |
| for name in ("atlas.json", "atlas.fingerprint", "atlas.bin", "integrity.txt"): | |
| if os.path.exists(os.path.join(ROOT, "state", name)): | |
| shutil.copy(os.path.join(ROOT, "state", name), os.path.join(STATE, name)) | |
| log = open(os.path.join(STATE, "motore.log"), "w", encoding="utf-8") | |
| engine = subprocess.Popen([os.path.join(ROOT, "build", "neuronald.exe"), "--port", str(PORT), "--state", STATE, "--local-only", | |
| "--workspace", os.path.join(STATE, "lavori"), "--ctx", "8192"], | |
| cwd=ROOT, env=dict(ENV, NEURONAL_GPU_LAYERS="0", NEURONAL_NO_BOOT_CHECK="1"), stdout=log, stderr=subprocess.STDOUT) | |
| try: | |
| asyncio.run(main()) | |
| finally: | |
| engine.kill() | |
| log.close() | |
| print("\nRISULTATO:", "OK" if not failures else f"{len(failures)} errori") | |
| sys.exit(1 if failures else 0) | |