Prepare isolated Speedy build and explicitly gated short benchmark

This commit is contained in:
Mikei386 committed 2026-11-05 21:58:12 +01:00
1 parent 6266bf33b8
commit e31356fdbb
8 files changed
+941

No files matched your search

+22
View File
@@ -5,6 +5,28 @@ curated project handoff, not imported chat history. Read applicable `AGENTS.md`,
then the current source and relevant linked documentation; verify live state
again before changing anything. Historical notes do not override current facts.
## Speedy built; model/Tok/s test explicitly awaiting Go · 5 November 2026
Michael requested a separate Speedy build and a short test preparation, explicitly
no test before his new Go. Release v0.3.1 / commit
`e307537e9e0d847da36960814ffec271f957a912` is built under
`/opt/athena-deck-dev/speedy-candidate-e307537e9e0d`, with CUDA 13.0 device code
for SM86 and SM120. Engine/server help, CPU-default fixture, library resolution
and device-code inspection pass; ten synthetic preparation tests pass. No model
load, GPU inference, production activation or Basalt update was performed.
Protected settings and the live Deck container identity remained unchanged.
Initial builder-only OOM and a missing binary inspector were corrected without
unloading Qwen. The prepared first test uses only the 5080 and existing Strata
IQ3_XXS assets read-only. Loopback test launcher and client require explicit Go
and verified maintenance; maximum total window 15 minutes with restoration
reserve. Basalt must be restored promptly through normal Deck management after
any later separately authorized test. An expired GUI login is not API authority.
Actual model compatibility, measured speed, native full restore and productive
integration are untested. Basalt currently verified 0.1.0 /
`9175e7a3211bda355c02e804c7c107b15b8ea89f`; discussion of 0.2.1 is research only.
See [build provenance, Go gates, test scope and native limits](maintenance/speedy-candidate-2026-11-05/README.md).
## Dreaming enabled for all 21 profiles · 4 November 2026
Michael explicitly requested installation/activation for all 21 existing bots.
@@ -0,0 +1,181 @@
# Speedy: isolierter Build und Go-gesperrter Kurztest
## Auftrag und Grenzen
Michael beauftragte den Build und die Vorbereitung eines kurzen Tok/s-Tests.
**Modellstart, Testrequests und vorübergehender Modellwechsel warten ausdrücklich
auf sein neues Go.** Keine produktive Integration, Profileinträge, Dienste,
Zeitpläne, Treiberänderungen oder Aktualisierung von Basalt beauftragt.
Der Kandidat wird unter
`/opt/athena-deck-dev/speedy-candidate-e307537e9e0d` auf Athena gehalten. Nur dieser
Bereich wird beschrieben. Produktions-CUDA und später Modellassets werden
explizit nur lesend geliehen. Keine neuen Gewichte heruntergeladen.
## Quellen und aktuelle Referenz
- Speedy: <https://github.com/DevDock-AI/Speedy>, Release **v0.3.1**,
Commit `e307537e9e0d847da36960814ffec271f957a912`.
Nicht der neuere experimentelle RTX-50-`main`-Stand.
- Der geerbte CMake-Projekt-/Engine-String ist **0.1.53**; dieser ist nicht die
Speedy-Releaseversion. Bei Berichten immer Release und Commit gemeinsam nennen.
- llama.cpp: `3cf03257f219afbe7334045ff7c6a06ac68c627d`, separat in `llama/`.
- CUDA: vorhandenes Toolkit **13.0**, ausschließlich lesend aus
`/opt/athena-deck-dev/runtime/state/strata-runtime/cuda`.
- Buildsystem: private CMake **3.31.6**, Ninja **1.11.1.4**; öffentliche
Runtime-Python-Abhängigkeiten aus der gepinnten Speedy-`requirements.txt`.
Tatsächlicher vollständiger Lock liegt im Kandidaten unter `python-lock.txt`.
- Explizit geliehenes vorhandenes Build-/Testimage:
`sha256:2198e221b71da1f00bc7d698e1a690d8d60dc7de97e9f1045180a225b48c5166`.
Kein Pull, kein neuer Tag und keine Änderung dieses Images.
- Aktiver Basalt-Stand bei Vorbereitung: **0.1.0**, Commit
`9175e7a3211bda355c02e804c7c107b15b8ea89f`, Binär-SHA-256
`1278458f0519a65fefec93224d5e3ff9cd1862a981f0fce2ae48a8e2614fb38a`.
Laufender nativer Basalt-Prozess und Marker/Binärdatei wurden verglichen.
Die spätere Recherche zu Basalt 0.2.1 ist kein Updateauftrag.
## Build und reale Abnahme
**Build abgeschlossen und ohne Modell/GPU-Nutzung geprüft.** Binärdatei
`build/strata`, 199599792 Bytes, SHA-256
`d593baa2596237cb57fbcb7f825a5643f1786dd137b86e4e250fd63747bec6d3`.
CPU-Defaults-Fixture, Engine-/Server-Hilfe, Bibliotheksauflösung und die
Gerätecode-Inspektion für SM86/SM120 sind bestanden. Zehn synthetische
Vorbereitungstests bestehen. Kein Modellstart, keine Tok/s-Messung.
Maßgeblich sind der abschließende `status.json` und `controller-check.json`,
nicht die erhaltenen alten Fehlerstatus oder verspätete Heartbeats.
`build.py` läuft ausschließlich im eigenen Builder. Bootstrap mit Netzwerk,
anschließende Konfiguration/Kompilation ohne Netzwerk, ohne GPU-Geräte und ohne
Modell-/Zugangs-/Docker-Socket-Mounts. Nur Kandidatenwurzel und ihr `tmp/` sind
beschreibbar. `/tmp` wird ebenfalls auf diesen eigenen Bereich gebunden.
`candidate.py` läuft auf dem Athena-Host. Der Builder läuft als UID/GID 65534,
mit einem CPU-Kern, niedrigen CPU-Anteilen und `nice 19`. Das ursprüngliche
1,5-GiB-Limit ohne Swap löste nachweislich ein **OOM nur im eigenen Builder** aus.
Erster Fehlerstatus und Isolation sind als `first-attempt-*.json` erhalten.
Fortsetzung inkrementell mit **2 GiB RAM und maximal 2 GiB zusätzlichem Swap**
für den Builder; OOM-Priorität 500. Keine Modelle wurden dafür entladen.
Host-RAM-Untergrenze und Zeitgrenze stoppen ausschließlich den eigenen Builder.
Gebaut wird mit CUDA für **SM86 und SM120**, nativen Experten und den vom
Projekt vorgesehenen Quantisierungskernels. Kein Wechsel auf andere Gewichte.
Erfolgreiche Abschlussprüfung: CPU-Defaults-Fixture, Engine-/Server-Hilfe ohne
Modellstart, Bibliotheksauflösung, `cuobjdump` der beiden Gerätearchitekturen und
Binärhash. Kein GPU-Paritätstest, kein Mikrobenchmark, keine Qualitätsinferenz.
Die Kompilierung war bereits erfolgreich, als die erste Abschlussprüfung am
fehlenden `cuobjdump` des kleinen geliehenen Toolkits scheiterte. Ohne Neubau
wurde ausschließlich im Kandidaten das NVIDIA-Redistributable **13.0.39**
ergänzt, Archiv-SHA-256
`2385804b0a628b98b3ed96a19c803143d5c2e2fcc5139f633450862cf7755d65`.
Quelle: `https://developer.download.nvidia.com/compute/cuda/redist/cuda_cuobjdump/linux-x86_64/cuda_cuobjdump-linux-x86_64-13.0.39-archive.tar.xz`.
Die erfolgreiche separate `check`-Fortsetzung ist erhalten; keine Änderung am
Produktivtoolkit. Der zuvor fehlgeschlagene Abschluss bleibt unter
`compile-complete-inspector-missing-*.json` nachvollziehbar.
Die zehn `test_preparation.py`-Fälle prüfen synthetisch Offline-Defaults,
Go-/Wartungssperren, feste Zieladresse/Modellalias, gültige und fehlerhafte
SSE-Verarbeitung sowie die Ablehnung von Ein-Token-Spitzen. Ihre Protokollwerte
sind ausdrücklich Fixtures, keine Modellmessungen.
## Bereitgelegter Modellpfad
Der erste Kandidat nutzt **nur die RTX 5080**
`GPU-8ad38c6c-5a01-9d8e-1dfa-ed662ad78fbe`; die 3060 und ihre Audioworker bleiben
außen vor. Beide Architekturen zu kompilieren ist kein Misch-GPU-Funktionstest.
Vorhandene Assets, ausschließlich lesend und ohne Kopie:
- GGUF-Teildateien IQ3_XXS und Pack-Index v3 mit `dense.bin`, `experts.bin`,
`native_experts.txt` und Tokenizer:
`/opt/athena-deck-dev/runtime/state/strata-ssd/{models/IQ3_XXS,packs/iq3_xxs}`.
- MTP: `/data/athena-deck-strata/mtp/rt`.
- Expertenprofil: öffentliche Datei des gepinnten Speedy-Checkouts.
Dateiexistenz, Header und vorhandener Strata-Preparemarker wurden gelesen;
keine neue vollständige Gewichte-Prüfsumme und keine erfolgreiche Ladung durch
Speedy behauptet. Tatsächliche Modell-/Pack-Kompatibilität bleibt Teil des
Go-Fensters. Das `.basalt`-Paket ist nicht das Speedy-Eingabeformat.
Vorbereitete Konfiguration: ein Slot, 262144 maximaler Kontext, INT8-KV,
32768 KV-Zellen resident, 1024 MiB VRAM-Reserve, 512 MiB Gesprächscache,
MTP-Spekulationstiefe 4 und Mindestwahrscheinlichkeit 0.5. Keine Vision.
Tatsächliche Eingabelängen werden später aus API-Usage berichtet, nicht mit dem
konfigurierten Maximum verwechselt. Speedys arithmetikändernde Defaults bleiben
als solche erkennbar; dies ist kein bitidentischer Stock-Strata-Vergleich.
## Kurzer Test nach neuem Go
Gesamtfenster **höchstens 15 Minuten**, einschließlich Laden und Rückkehr;
180 Sekunden Rückkehrreserve. Kein 1M-/Vollkontext-/Langzeit-/Qualitätstest.
Je Engine maximal 240 Sekunden mit einem ausgeschlossenen Warmup,
zwei kurzen Antworten, einem frischen kontrollierten Text und seiner echten
Fortsetzung mit übernommener Assistentenantwort. Maximal 256 Ausgabetokens je
Messantwort. Tatsächliche Verwendung des Caches ist zu messen, nicht anzunehmen.
Vor jedem Eingriff normale authentifizierte Deck-Wartung herstellen und aktive
**und wartende** Arbeit nachweislich drainieren. Fehlende Zähler reichen nicht.
Michael muss gegebenenfalls regulär anmelden; API-Schlüssel ersetzen keine
Managementanmeldung. Kein direkter Prozesskill und keine private Adminumgehung.
1. Neues menschliches Go und unveränderten Umfang bestätigen; ein CLI-Flag allein
ist keine Autorisierung. Absolute Gesamtfrist festlegen.
2. Basalt im nachgewiesen exklusiven Fenster mit demselben Client messen, falls
ein frischer Vergleich ausdrücklich Teil des Go ist. Baseline-Port 8120,
Alias `flash-next-basalt`. Client verlangt bereiten, inaktiven Basalt-Export.
Sonst historische Werte nur ausdrücklich als historischen Vergleich nutzen.
3. Über die normale Deck-Wartung ausschließlich den Chatworker für das Testfenster
freigeben; Audioworker nicht ungefragt stoppen. Kein Gateway-/Deck-Neustart.
4. `launch.py --go --maintenance-confirmed --deadline EPOCH` startet ausschließlich
den eigenen Kandidaten auf Loopback **18420**, nicht den öffentlichen Endpunkt.
Das Skript verweigert belegte GPU/RAM-Ressourcen, entlädt selbst keine Modelle
und begrenzt den Kandidaten auf 52 GiB ohne weiteren Swap. API-Schlüssel wird
erst jetzt privat erzeugt, nicht in Git oder Kommandoargumenten gespeichert.
5. Echte Bereitschaft inklusive geladenem Modell prüfen, nicht nur HTTP 200.
Nur wenn genügend verbleibendes Mess- und Rückkehrbudget vorhanden ist,
`bench.py --go --exclusive-window-confirmed --output ROOT/speedy-results.json`
mit dem eigenen temporären Schlüssel über stdin ausführen. Keine Schlüssel
ausgeben. Der Client akzeptiert ausschließlich 127.0.0.1:18420 mit dem festen
Kandidatenalias oder 127.0.0.1:8120 mit Basalts Alias.
6. Nur den eigenen Kandidaten beenden, danach **sofort** den ursprünglichen
Basalt-/Qwen-Betrieb über den regulären Deck-Pfad laden und seine tatsächliche
Bereitschaft prüfen. Der Launcher beendet nach Ablauf nur seinen Container,
stellt aber **nicht** eigenmächtig Produktion wieder her; das bleibt Pflicht
des durchführenden Operators, auch nach Fehlern. Keine zusätzlichen
Restaurations-Inferenzrequests ohne entsprechende Autorisierung.
Messwerte: reale Usage, erste sichtbare Antwort, gesamte Antwortdauer,
Ausgabetokens pro gesamter Sekunde (einschließlich Einlesen) und separat
Backend-Timings, soweit tatsächlich geliefert. Die zusätzlich ausgegebene
Stream-Decodierung ist wegen SSE-Chunking ausdrücklich nur eine Annäherung.
Kurze/fragmentierte Backend-Peaks nicht als vollständige Antwortrate vermarkten.
Originaler Basalt hat zwei Slots und ein anderes Laufzeitpack; diese Unterschiede
neben MTP-/Cache-/Kontextparametern offen berichten, nicht als reinen Engine-A/B
mit identischen Bedingungen bezeichnen.
## Reproduzierbarkeit, native Installation und Rückfall
Die drei Betriebsumgebungen klar trennen: Controller/Launcher auf Athena,
Buildworker im isolierten Builder, stdlib-Testclient auf Athena; lokale
synthetische Tests können auf dem NAS laufen. Keine Änderung an Hermes-Python.
Für ein frisches Debian sind Git, C/C++-Compiler, Python mit venv, CMake/Ninja,
passendes CUDA-Toolkit und kompatibler NVIDIA-Treiber explizite Voraussetzungen.
Diese Vorbereitung nutzt bewusst das dokumentierte vorhandene Image. Eine
vollständige native Installation ist damit **nicht** abgenommen; insbesondere
ist das Python-3.12-venv aus dem Ubuntu-Image kein ungeprüft portables Debian-venv.
Für nativen Betrieb ein privates venv mit dem Zielhost-Python aus demselben Lock
neu erstellen und ELF-/Bibliothekskompatibilität erneut prüfen. Kandidatenwurzel,
Dienstbenutzer, CUDA-Pfad und Assetpfade dann ausdrücklich konfigurieren.
Öffentliche Quellen/Versionen und Modellherkunft stehen im Rezept; keine Gewichte
oder Geheimnisse in Git. Private Testergebnisse bleiben in der Kandidatenwurzel.
Eine spätere Aufnahme in Vollrestore benötigt ihre explizite Registrierung und
verschlüsselte Sicherung. Kein Fresh-Host-/Vollrestore-Nachweis erbracht.
Rückfall ist hier primär: Kandidat niemals produktiv aktivieren, nach einem
separat genehmigten Test Basalt über Deck wiederherstellen. Keine produktiven
Dateien wurden überschrieben. Entfernung erst nach Besitzmarker-/Inodeprüfung,
Ausschluss laufender eigener Prozesse und Mounts; geliehene Toolchains, Images
und Modellassets bleiben erhalten. Kein allgemeines Docker-/Dateisystem-Pruning.
@@ -0,0 +1,69 @@
{
"status": {
"phase": "built; awaiting separate GO for model load and inference",
"updated": 1793912076.1689432,
"commit": "e307537e9e0d847da36960814ffec271f957a912",
"release": "v0.3.1",
"model_started": false,
"inference_performed": false,
"binary_sha256": "d593baa2596237cb57fbcb7f825a5643f1786dd137b86e4e250fd63747bec6d3",
"binary_bytes": 199599792,
"architectures": [
86,
120
],
"cpu_defaults_test_passed": true
},
"check": {
"exit_code": 0,
"seconds": 2.0367336629424244,
"builder_remaining": false,
"production_unchanged": true
},
"isolation": {
"verified": true,
"gpu_access": false,
"model_access": false,
"cpu_limit": 1,
"memory_mib": 2048,
"maximum_swap_mib": 2048,
"image": "sha256:2198e221b71da1f00bc7d698e1a690d8d60dc7de97e9f1045180a225b48c5166",
"mounts": [
[
"/opt/athena-deck-dev/speedy-candidate-e307537e9e0d",
"/opt/athena-deck-dev/speedy-candidate-e307537e9e0d",
true
],
[
"/opt/athena-deck-dev/speedy-candidate-e307537e9e0d/tmp",
"/tmp",
true
],
[
"/opt/athena-deck-dev/runtime/state/strata-runtime/cuda",
"/opt/athena-deck-dev/runtime/state/strata-runtime/cuda",
false
]
],
"network": "none"
},
"scripts": {
"build.py": "cf56c2a8a8b6dcad8b1945ef77a88cb52683c98422fbed0e5b70ee5a9e3da33d",
"candidate.py": "a6128442009e1ac714321defd117fc8bbd7f652d0348f43b4d5747fb82265175",
"bench.py": "bb54d7726bcaf7fa2dae9f1a62691497c57edf3e88f94e37d6e21f2b5206c478",
"launch.py": "2078d047b4232e7cce199a600b016143075d70dc29723d76a098413a33179fd0",
"test_preparation.py": "95c4b5e3ee41f7bcfd5654d113d18fa686d332a95c62c07c54ba960e440998bd"
},
"synthetic_preparation_tests_passed": 10,
"native_full_restore_tested": false,
"gpu_inference_tested": false,
"baseline": {
"version": "0.1.0",
"commit": "9175e7a3211bda355c02e804c7c107b15b8ea89f",
"binary_sha256": "1278458f0519a65fefec93224d5e3ff9cd1862a981f0fce2ae48a8e2614fb38a",
"original_worker_pids_observed_unchanged": [
141839,
141862
]
}
}
@@ -0,0 +1,167 @@
#!/usr/bin/env python3
"""Linux test-window client. Default is offline plan; POST requires explicit --go.
Run on Athena, not on a Mac. Never stops/starts a model or edits production.
The operator must first establish an authorized exclusive test window and restore
Basalt afterwards. API keys enter through stdin only, never command arguments.
"""
import argparse
import hashlib
import json
from pathlib import Path
import signal
import sys
import time
import urllib.parse
import urllib.request
def plan():
return dict(requests=['warmup-excluded', 'short-1', 'short-2', 'fresh-input', 'cached-followup'],
maximum_output_tokens=256, fresh_input_lines=500,
actual_input_tokens='taken from response usage, not estimated',
hard_deadline_seconds=240, inference_performed=False)
def target(url, model):
parsed = urllib.parse.urlsplit(url)
if (parsed.scheme != 'http' or parsed.hostname != '127.0.0.1'
or parsed.port not in (8120, 18420) or parsed.path not in ('', '/')
or parsed.username or parsed.password or parsed.query or parsed.fragment):
raise ValueError('Only the existing local Deck port or the owned candidate port is allowed')
expected = 'flash-next-basalt' if parsed.port == 8120 else 'flash-next-speedy-test'
if model != expected:
raise ValueError('Refusing unexpected model alias / implicit model switching')
return url.rstrip('/')
def stream(base, key, model, messages, max_tokens, opener=urllib.request.urlopen):
body = dict(model=model, messages=messages, max_tokens=max_tokens, temperature=0,
reasoning_effort='none', stream=True, stream_options={'include_usage': True})
headers = {'Content-Type': 'application/json'}
if key:
headers['Authorization'] = 'Bearer ' + key
request = urllib.request.Request(base + '/v1/chat/completions',
data=json.dumps(body).encode(), headers=headers)
start = time.monotonic()
first = None
text = ''
usage = None
timings = None
finished = False
with opener(request, timeout=60) as response:
for raw in response:
if len(raw) > 1024 * 1024:
raise ValueError('Oversized SSE record')
if not raw.startswith(b'data: '):
continue
payload = raw[6:].strip()
if payload == b'[DONE]':
finished = True
break
event = json.loads(payload)
if event.get('error'):
raise ValueError('Backend returned a streaming error')
usage = event.get('usage') or usage
timings = event.get('timings') or timings
for choice in event.get('choices') or []:
delta = choice.get('delta') or {}
content = delta.get('content') or ''
if content:
if first is None:
first = time.monotonic()
text += content
end = time.monotonic()
if not finished or not text or first is None or not usage or not isinstance(usage.get('completion_tokens'), int):
raise ValueError('Incomplete stream, no visible answer, or missing real token usage')
elapsed = end - start
count = usage['completion_tokens']
if count < 2:
raise ValueError('Too few generated tokens for a useful rate')
clean_timings = {k: v for k, v in (timings or {}).items()
if isinstance(v, (int, float)) and k in (
'cache_n', 'prompt_n', 'prompt_ms', 'prompt_per_second',
'predicted_n', 'predicted_ms', 'predicted_per_second',
'draft_n', 'draft_n_accepted')}
result = dict(usage=usage, elapsed_seconds=elapsed, first_visible_seconds=first - start,
output_tokens_per_total_second=count / elapsed,
# Includes first-chunk tokens and stream overhead: NOT exact engine decode.
approximate_stream_decode_tok_s=count / (end - first) if end > first else None,
engine_timings=clean_timings,
output_sha256=hashlib.sha256(text.encode()).hexdigest(), output_chars=len(text))
return result, text
def run(args):
if not args.go:
print(json.dumps(plan(), indent=2))
return
if not args.exclusive_window_confirmed:
raise ValueError('First verify authorized drain/maintenance; never benchmark behind production work')
base = target(args.url, args.model)
if args.output is None:
raise ValueError('Explicit private result path required')
key = sys.stdin.read().strip()
output = Path(args.output)
allowed = Path('/opt/athena-deck-dev/speedy-candidate-e307537e9e0d')
if output.parent != allowed or allowed.is_symlink() or allowed.resolve() != allowed or output.suffix != '.json':
raise ValueError('Results must stay inside the owned candidate root')
if output.exists() or output.is_symlink():
raise ValueError('Do not overwrite an earlier result')
records = []
started = time.monotonic()
def timed_out(signum, frame):
raise TimeoutError('Hard test deadline reached; no additional requests')
old_handler = signal.signal(signal.SIGALRM, timed_out)
signal.setitimer(signal.ITIMER_REAL, 240)
try:
headers = {'Authorization': 'Bearer ' + key} if key else {}
with urllib.request.urlopen(urllib.request.Request(base + '/health', headers=headers), timeout=5) as r:
health = json.load(r)
if health.get('status') != 'ok' or health.get('loaded') is False:
raise ValueError('Model is not ready; HTTP 200 alone is insufficient')
if args.model == 'flash-next-basalt':
with urllib.request.urlopen(urllib.request.Request(base + '/v1/telemetry/speed', headers=headers), timeout=5) as r:
sample = json.load(r)
if sample.get('backend') != 'basalt' or sample.get('phase') != 'idle' or sample.get('active_slots') != 0:
raise ValueError('Baseline worker not ready and idle; do not switch or interrupt')
corpus = '\n'.join(f'Record {i:04d}: alpha beta gamma delta epsilon; controlled synthetic input.' for i in range(500))
scenarios = [
('warmup-excluded', [{'role': 'user', 'content': 'Reply briefly with ready.'}], 32),
('short-1', [{'role': 'user', 'content': 'Write a detailed explanation of how a hash table works.'}], 256),
('short-2', [{'role': 'user', 'content': 'Explain in detail how merge sort works, including its steps.'}], 256),
('fresh-input', [{'role': 'user', 'content': corpus + '\nSummarize the structure of these records in detail.'}], 256),
]
last_answer = ''
for name, messages, limit in scenarios:
result, answer = stream(base, key, args.model, messages, limit)
last_answer = answer
result['name'] = name
records.append(result)
output.write_text(json.dumps(dict(model=args.model, complete=False, records=records), indent=2) + '\n')
print(json.dumps(result), flush=True)
followup = scenarios[-1][1] + [{'role': 'assistant', 'content': last_answer},
{'role': 'user', 'content': 'Now explain how these records could be validated efficiently.'}]
result, _ = stream(base, key, args.model, followup, 256)
result['name'] = 'cached-followup'
records.append(result)
output.write_text(json.dumps(dict(model=args.model, complete=True,
seconds=time.monotonic() - started, records=records), indent=2) + '\n')
print(json.dumps(result), flush=True)
except BaseException as error:
output.write_text(json.dumps(dict(model=args.model, complete=False, records=records,
error=type(error).__name__), indent=2) + '\n')
raise
finally:
signal.setitimer(signal.ITIMER_REAL, 0)
signal.signal(signal.SIGALRM, old_handler)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--go', action='store_true')
parser.add_argument('--exclusive-window-confirmed', action='store_true')
parser.add_argument('--url', default='http://127.0.0.1:18420')
parser.add_argument('--model', default='flash-next-speedy-test')
parser.add_argument('--output')
run(parser.parse_args())
@@ -0,0 +1,147 @@
#!/usr/bin/env python3
"""Owned GPU-less builder only; never launch the model/server or run GPU tests."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import subprocess
import tarfile
import time
import urllib.request
import venv
PIN = 'e307537e9e0d847da36960814ffec271f957a912'
LLAMA = '3cf03257f219afbe7334045ff7c6a06ac68c627d'
ROOT = Path('/opt/athena-deck-dev/speedy-candidate-e307537e9e0d')
CUDA = Path('/opt/athena-deck-dev/runtime/state/strata-runtime/cuda')
def status(phase, **extra):
data = dict(phase=phase, updated=time.time(), commit=PIN,
release='v0.3.1', model_started=False, inference_performed=False, **extra)
(ROOT / 'status.json').write_text(json.dumps(data, indent=2) + '\n')
print(json.dumps(data), flush=True)
def run(args, cwd=None, output=None):
with (ROOT / (output or 'build.log')).open('a') as log:
log.write('\n$ ' + ' '.join(map(str, args)) + '\n')
log.flush()
subprocess.run(list(map(str, args)), cwd=cwd, check=True,
stdout=log, stderr=subprocess.STDOUT)
def checkout(name, url, pin):
path = ROOT / name
run(['git', 'init', '-q', path])
run(['git', '-C', path, 'fetch', '--depth', '1', url, pin])
run(['git', '-C', path, 'sparse-checkout', 'init', '--no-cone'])
# Exclude forbidden names before materializing ANY source tree.
with (ROOT / 'sparse-policy.txt').open('w') as policy:
policy.write('/*\n!/**/vpn/\n!/vpn/\n!/**/vpn.auth\n!/vpn.auth\n!/**/OpenVPN-KIT/\n')
with (ROOT / 'sparse-policy.txt').open() as policy:
subprocess.run(['git', '-C', str(path), 'sparse-checkout', 'set',
'--no-cone', '--stdin'], stdin=policy, check=True)
run(['git', '-C', path, 'checkout', '-q', '--detach', 'FETCH_HEAD'])
assert subprocess.check_output(['git', '-C', str(path), 'rev-parse', 'HEAD'],
text=True).strip() == pin
def bootstrap():
status('fetching pinned Speedy and llama.cpp sources')
checkout('source', 'https://github.com/DevDock-AI/Speedy.git', PIN)
checkout('llama', 'https://github.com/ggml-org/llama.cpp.git', LLAMA)
status('installing private build and server dependencies; no setup.py')
venv.create(ROOT / 'venv', with_pip=True, symlinks=False)
python = ROOT / 'venv/bin/python'
run([python, '-m', 'pip', 'install', '--disable-pip-version-check', '--no-input',
'--index-url', 'https://pypi.org/simple', 'cmake==3.31.6', 'ninja==1.11.1.4',
'-r', ROOT / 'source/requirements.txt'])
run([python, '-m', 'pip', 'freeze', '--all'], output='python-lock.txt')
run([python, '-m', 'pip', 'check'], output='pip-check.txt')
tools()
status('bootstrap complete')
def tools():
"""Install only NVIDIA's pinned binary inspector into the owned tree."""
name = 'cuda_cuobjdump-linux-x86_64-13.0.39-archive.tar.xz'
url = 'https://developer.download.nvidia.com/compute/cuda/redist/cuda_cuobjdump/linux-x86_64/' + name
expected = '2385804b0a628b98b3ed96a19c803143d5c2e2fcc5139f633450862cf7755d65'
archive = ROOT / 'cache' / name
if not archive.exists():
with urllib.request.urlopen(url, timeout=30) as response:
archive.write_bytes(response.read(1024 * 1024))
assert hashlib.sha256(archive.read_bytes()).hexdigest() == expected
destination = ROOT / 'tools/cuobjdump'
assert not destination.is_symlink()
destination.mkdir(parents=True, exist_ok=True)
with tarfile.open(archive) as package:
for member in package:
parts = Path(member.name).parts
if (Path(member.name).is_absolute() or '..' in parts
or any(p in ('vpn', 'vpn.auth', 'OpenVPN-KIT') for p in parts)
or not (member.isfile() or member.isdir())):
raise ValueError('Refusing unsafe archive member')
if len(parts) < 2:
continue
member.name = str(Path(*parts[1:]))
package.extract(member, destination, filter='data')
(ROOT / 'cuobjdump-source.json').write_text(json.dumps(dict(
url=url, sha256=expected, version='13.0.39', installed_inside_candidate=True), indent=2) + '\n')
status('private cuobjdump installed; production toolkit untouched')
def environment():
os.environ['PATH'] = str(ROOT / 'venv/bin') + ':' + str(CUDA / 'bin') + ':' + os.environ['PATH']
os.environ['LD_LIBRARY_PATH'] = str(CUDA / 'lib64') + ':' + str(CUDA / 'lib')
def build():
environment()
status('configuring CUDA 13.0, SM86 and SM120; no GPU devices')
run(['cmake', '-S', ROOT / 'source', '-B', ROOT / 'build', '-G', 'Ninja',
'-DCMAKE_BUILD_TYPE=Release', '-DSTRATA_ENABLE_CUDA=ON',
'-DCMAKE_CUDA_COMPILER=' + str(CUDA / 'bin/nvcc'),
'-DCUDAToolkit_ROOT=' + str(CUDA), '-DCMAKE_CUDA_ARCHITECTURES=86;120',
'-DSTRATA_NATIVE_EXPERTS=ON', '-DSTRATA_MMQ_KQUANTS=ON',
'-DSTRATA_MMQ_TQ_OVERLAY=ON', '-DSTRATA_Q6K_EXPERTS=ON',
'-DSTRATA_BUILD_TESTS=ON', '-DSTRATA_GGML_DIR=' + str(ROOT / 'llama'),
'-DFETCHCONTENT_FULLY_DISCONNECTED=ON'])
status('compiling engine and selected CPU fixture; one build job')
run(['cmake', '--build', ROOT / 'build', '--parallel', '1',
'--target', 'strata', 'speedy_defaults_test'])
check()
def check():
environment()
run([ROOT / 'build/speedy_defaults_test'], output='cpu-defaults-test.txt')
run(['ldd', ROOT / 'build/strata'], output='ldd.txt')
assert 'not found' not in (ROOT / 'ldd.txt').read_text()
run([ROOT / 'build/strata', '--help'], output='engine-help.txt')
run([ROOT / 'venv/bin/python', ROOT / 'source/serve/server.py', '--help'],
cwd=ROOT / 'source', output='server-help.txt')
# Device-code inspection only: this does not initialize CUDA or load weights.
inspector = ROOT / 'tools/cuobjdump/bin/cuobjdump'
run([inspector, '--list-elf', ROOT / 'build/strata'], output='cuda-architectures.txt')
arch = (ROOT / 'cuda-architectures.txt').read_text()
assert 'sm_86' in arch and 'sm_120' in arch
binary = ROOT / 'build/strata'
with binary.open('rb') as stream:
digest = hashlib.file_digest(stream, 'sha256').hexdigest()
status('built; awaiting separate GO for model load and inference',
binary_sha256=digest, binary_bytes=binary.stat().st_size,
architectures=[86, 120], cpu_defaults_test_passed=True)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('phase', choices=['bootstrap', 'build', 'tools', 'check'])
args = parser.parse_args()
try:
globals()[args.phase]()
except BaseException as error:
status('failed', error=type(error).__name__ + ': ' + str(error))
raise
@@ -0,0 +1,142 @@
#!/usr/bin/env python3
"""Athena host controller: isolated build only, no inference/activation commands."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import subprocess
import time
ROOT = Path('/opt/athena-deck-dev/speedy-candidate-e307537e9e0d')
CUDA = Path('/opt/athena-deck-dev/runtime/state/strata-runtime/cuda')
NAME = 'athena-speedy-build-e307537e9e0d'
OWNER = 'athena-deck/speedy/e307537e9e0d847da36960814ffec271f957a912'
IMAGE = 'sha256:2198e221b71da1f00bc7d698e1a690d8d60dc7de97e9f1045180a225b48c5166'
def dump(name, value):
(ROOT / name).write_text(json.dumps(value, indent=2) + '\n')
def snapshot():
base = Path('/opt/athena-deck-dev/runtime/state')
hashes = {}
for name in ('profiles.json', 'endpoint.json', 'audio-policy.json',
'cpu-partition.json', 'reasoning-budget.json', 'basalt-runtime/ready.json'):
p = base / name
assert not p.is_symlink()
with p.open('rb') as stream:
hashes[name] = hashlib.file_digest(stream, 'sha256').hexdigest()
data = json.loads(subprocess.check_output(['docker', 'inspect', 'athena-deck-dev']))[0]
return dict(hashes=hashes, image=data['Image'], started=data['State']['StartedAt'],
pid=data['State']['Pid'], running=data['State']['Running'],
health=data['State'].get('Health', {}).get('Status'))
def prepare():
assert ROOT.is_dir() and not ROOT.is_symlink() and ROOT.resolve() == ROOT
assert {p.name for p in ROOT.iterdir()} == {'candidate.py', 'build.py'}
assert (CUDA / 'bin/nvcc').is_file()
before = snapshot()
assert before['running'] and before['image'] == IMAGE
dump('.owner.json', dict(owner=OWNER, device=ROOT.stat().st_dev, inode=ROOT.stat().st_ino))
dump('production-before.json', before)
for relative in ('home', 'tmp', 'cache/pip', 'cache/cuda', 'cache/hf'):
(ROOT / relative).mkdir(parents=True, exist_ok=True)
# Newly created owned tree only, never traverse links or another state root.
for parent, dirs, files in os.walk(ROOT, followlinks=False):
os.chown(parent, 65534, 65534)
for name in dirs + files:
p = Path(parent) / name
assert not p.is_symlink()
os.chown(p, 65534, 65534)
print(json.dumps(dict(prepared=True, root=str(ROOT), activated=False)))
def owned():
result = subprocess.run(['docker', 'inspect', NAME], capture_output=True, text=True)
if result.returncode:
return None
data = json.loads(result.stdout)[0]
assert data['Config']['Labels'].get('athena-deck.speedy-owner') == OWNER
assert data['Image'] == IMAGE
return data
def phase(name):
marker = json.loads((ROOT / '.owner.json').read_text())
assert marker == dict(owner=OWNER, device=ROOT.stat().st_dev, inode=ROOT.stat().st_ino)
assert snapshot() == json.loads((ROOT / 'production-before.json').read_text())
available = int(next(x.split()[1] for x in Path('/proc/meminfo').read_text().splitlines()
if x.startswith('MemAvailable:')))
assert available >= 3000 * 1024, 'Insufficient RAM headroom; production untouched'
assert owned() is None, 'Do not duplicate an existing builder'
env = dict(HOME=str(ROOT / 'home'), TMPDIR=str(ROOT / 'tmp'),
XDG_CACHE_HOME=str(ROOT / 'cache'), PIP_CACHE_DIR=str(ROOT / 'cache/pip'),
PIP_CONFIG_FILE='/dev/null', PYTHONDONTWRITEBYTECODE='1',
PYTHONNOUSERSITE='1', CUDA_VISIBLE_DEVICES='', NVIDIA_VISIBLE_DEVICES='void',
CUDA_CACHE_PATH=str(ROOT / 'cache/cuda'), HF_HOME=str(ROOT / 'cache/hf'),
OMP_NUM_THREADS='1', OPENBLAS_NUM_THREADS='1',
GIT_CONFIG_NOSYSTEM='1', GIT_CONFIG_GLOBAL='/dev/null', GIT_TERMINAL_PROMPT='0')
mounts = [(str(ROOT), str(ROOT), True), (str(ROOT / 'tmp'), '/tmp', True),
(str(CUDA), str(CUDA), False)]
command = ['docker', 'run', '--rm', '--pull=never', '--name', NAME,
'--label', 'athena-deck.speedy-owner=' + OWNER, '--runtime', 'runc',
'--network', 'bridge' if name in ('bootstrap', 'tools') else 'none', '--read-only',
'--cpus', '1', '--cpu-shares', '2', '--memory', '2g', '--memory-swap', '4g',
'--oom-score-adj', '500',
'--pids-limit', '512', '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges',
'--user', '65534:65534', '--entrypoint', 'nice']
for source, target, writable in mounts:
command += ['--mount', f'type=bind,src={source},dst={target}' + ('' if writable else ',readonly')]
for key, value in env.items():
command += ['-e', key + '=' + value]
command += [IMAGE, '-n', '19', 'python3', str(ROOT / 'build.py'), name]
start = time.monotonic()
process = subprocess.Popen(command)
inspected = False
try:
while process.poll() is None:
time.sleep(2)
info = owned()
if info and not inspected:
host = info['HostConfig']
assert not host.get('DeviceRequests') and not host.get('Devices')
assert host['Memory'] == 2 * 1024 ** 3 and host['MemorySwap'] == 4 * 1024 ** 3
assert host['NanoCpus'] == 1_000_000_000 and host['ReadonlyRootfs']
assert {(m['Source'], m['Destination'], m['RW']) for m in info['Mounts']} == set(mounts)
assert not any((info['NetworkSettings'].get('Ports') or {}).values())
dump('isolation-' + name + '.json', dict(verified=True, gpu_access=False,
model_access=False, cpu_limit=1, memory_mib=2048, maximum_swap_mib=2048,
image=IMAGE, mounts=mounts, network=host['NetworkMode']))
inspected = True
available = int(next(x.split()[1] for x in Path('/proc/meminfo').read_text().splitlines()
if x.startswith('MemAvailable:')))
if available < 900 * 1024 or time.monotonic() - start > 7200:
raise RuntimeError('Owned-builder RAM/time guard')
assert process.returncode == 0, f'Builder exited {process.returncode}'
finally:
info = owned()
if info and info['State']['Running']:
subprocess.run(['docker', 'stop', '--time', '5', NAME], check=True)
if process.poll() is None:
process.wait(timeout=20)
dump('controller-' + name + '.json', dict(exit_code=process.returncode,
seconds=time.monotonic() - start, builder_remaining=owned() is not None,
production_unchanged=snapshot() == json.loads((ROOT / 'production-before.json').read_text())))
assert owned() is None
assert snapshot() == json.loads((ROOT / 'production-before.json').read_text())
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('phase', choices=['prepare', 'bootstrap', 'build', 'tools', 'check', 'verify'])
args = parser.parse_args()
if args.phase == 'prepare':
prepare()
elif args.phase == 'verify':
print(json.dumps(dict(production_unchanged=snapshot() == json.loads(
(ROOT / 'production-before.json').read_text()), status=json.loads((ROOT / 'status.json').read_text()))))
else:
phase(args.phase)
@@ -0,0 +1,115 @@
#!/usr/bin/env python3
"""Athena host, only AFTER Michael's Go and a normal authenticated Deck drain.
This starts ONLY the owned candidate and never stops/restarts production. If the
5080 or RAM is occupied, it refuses. The fixed deadline stops only this candidate.
"""
import argparse
import json
import os
from pathlib import Path
import secrets
import subprocess
import time
ROOT = Path('/opt/athena-deck-dev/speedy-candidate-e307537e9e0d')
CUDA = Path('/opt/athena-deck-dev/runtime/state/strata-runtime/cuda')
SSD = Path('/opt/athena-deck-dev/runtime/state/strata-ssd')
MTP = Path('/data/athena-deck-strata/mtp/rt')
GPU = 'GPU-8ad38c6c-5a01-9d8e-1dfa-ed662ad78fbe'
IMAGE = 'sha256:2198e221b71da1f00bc7d698e1a690d8d60dc7de97e9f1045180a225b48c5166'
NAME = 'athena-speedy-test-e307537e9e0d'
OWNER = 'athena-deck/speedy/e307537e9e0d847da36960814ffec271f957a912'
def configuration():
native = SSD / 'models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf'
ple = native.with_name(native.name.replace('-00001-', '-00002-'))
pack = SSD / 'packs/iq3_xxs'
return dict(exe=str(ROOT / 'build/strata'), cwd=str(ROOT / 'source'),
args=['--pack', str(pack), '--native', str(native), '--ple-gguf', str(ple),
'--expert-profile', str(ROOT / 'source/data/expert-profile.bin'),
'--expert-cache', 'auto', '--prefill', 'auto', '--spec', '4',
'--spec-min-p', '0.5', '--mtp', str(MTP), '--max-context', '262144',
'--kv', 'int8', '--kv-resident', '32768', '--vram-reserve-mib', '1024',
'--resident-experts', '--conversation-cache-mib', '512',
'--adapt-async', '1', '--adapt-swaps', '80'],
tokenizer=str(pack / 'tokenizer'), model_name='flash-next-speedy-test',
host='127.0.0.1', port=18420, parallel=1, gpu=[1], gpu_order='as_given',
open_browser=False, vram_elastic=False, log=str(ROOT / 'test-engine.log'),
env={'CUDA_VISIBLE_DEVICES': GPU, 'CUDA_DEVICE_ORDER': 'PCI_BUS_ID',
'STRATA_REQUEST_LINES': ''})
def run(args):
config = configuration()
if not args.go:
print(json.dumps(dict(launch_performed=False, configuration=config), indent=2))
return
if not args.maintenance_confirmed or args.deadline is None:
raise ValueError('Explicit Go, verified maintenance and fixed deadline required')
remaining = args.deadline - time.time()
if not 240 < remaining <= 900:
raise ValueError('15-minute total window required, including 180-second restore reserve')
assert ROOT.resolve() == ROOT and not ROOT.is_symlink()
assert json.loads((ROOT / 'status.json').read_text())['phase'].startswith('built;')
free = int(subprocess.check_output(['nvidia-smi', '-i', GPU,
'--query-gpu=memory.free', '--format=csv,noheader,nounits'], text=True).strip())
available = int(next(x.split()[1] for x in Path('/proc/meminfo').read_text().splitlines()
if x.startswith('MemAvailable:')))
if free < 14000 or available < 48 * 1024 ** 2:
raise RuntimeError('Production still occupies resources; refusing to unload or interrupt it')
if subprocess.run(['docker', 'inspect', NAME], capture_output=True).returncode == 0:
raise RuntimeError('Owned test container already exists; inspect instead of duplicating')
for path in (config['exe'], config['tokenizer'], *[config['args'][config['args'].index(k) + 1]
for k in ('--pack', '--native', '--ple-gguf', '--mtp', '--expert-profile')]):
p = Path(path)
if 'vpn' in p.resolve().parts or p.name == 'vpn.auth' or not p.exists():
raise ValueError('Missing or forbidden test asset')
config['api_key'] = secrets.token_urlsafe(32)
config_path = ROOT / 'test-config.json'
fd = os.open(config_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, 'w') as stream:
json.dump(config, stream)
os.chown(config_path, 65534, 65534)
command = ['docker', 'run', '--rm', '--pull=never', '--name', NAME,
'--label', 'athena-deck.speedy-owner=' + OWNER, '--runtime', 'nvidia',
'--gpus', 'device=' + GPU, '--network', 'host', '--read-only',
'--memory', '52g', '--memory-swap', '52g', '--pids-limit', '1024',
'--oom-score-adj', '500', '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges',
'--ulimit', 'memlock=-1:-1', '--user', '65534:65534']
for source, target, writable in ((ROOT, ROOT, True), (ROOT / 'tmp', Path('/tmp'), True),
(CUDA, CUDA, False), (SSD, SSD, False), (MTP, MTP, False)):
command += ['--mount', f'type=bind,src={source},dst={target}' + ('' if writable else ',readonly')]
for key, value in dict(HOME=str(ROOT / 'home'), TMPDIR=str(ROOT / 'tmp'),
XDG_CACHE_HOME=str(ROOT / 'cache'), CUDA_VISIBLE_DEVICES=GPU,
CUDA_CACHE_PATH=str(ROOT / 'cache/cuda'), HF_HOME=str(ROOT / 'cache/hf'),
HF_HUB_OFFLINE='1', TRANSFORMERS_OFFLINE='1',
PYTHONDONTWRITEBYTECODE='1',
LD_LIBRARY_PATH=str(CUDA / 'lib64') + ':' + str(CUDA / 'lib')).items():
command += ['-e', key + '=' + value]
command += ['--entrypoint', str(ROOT / 'venv/bin/python'), IMAGE,
str(ROOT / 'source/serve/server.py'), '--engine', 'strata',
'--config', str(config_path), '--host', '127.0.0.1', '--port', '18420', '--fit-max-tokens']
with (ROOT / 'test-server.log').open('a') as log:
process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT)
try:
while process.poll() is None and time.time() < args.deadline - 180:
time.sleep(1)
finally:
info = subprocess.run(['docker', 'inspect', NAME], capture_output=True, text=True)
if info.returncode == 0:
record = json.loads(info.stdout)[0]
if record['Config']['Labels'].get('athena-deck.speedy-owner') != OWNER:
raise RuntimeError('Refusing to stop an unowned container')
subprocess.run(['docker', 'stop', '--time', '5', NAME], check=True)
process.wait(timeout=20)
print(json.dumps(dict(candidate_exited=process.returncode, restore_production_required=True)))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--go', action='store_true')
parser.add_argument('--maintenance-confirmed', action='store_true')
parser.add_argument('--deadline', type=float)
run(parser.parse_args())
@@ -0,0 +1,98 @@
#!/usr/bin/env python3
"""NAS or Athena: synthetic protocol/safety tests, never real model requests."""
import argparse
import contextlib
import importlib.util
import io
import json
from pathlib import Path
import unittest
from unittest.mock import patch
HERE = Path(__file__).resolve().parent
def module(name):
spec = importlib.util.spec_from_file_location(name, HERE / (name + '.py'))
assert spec and spec.loader
loaded = importlib.util.module_from_spec(spec)
spec.loader.exec_module(loaded)
return loaded
bench = module('bench')
launch = module('launch')
def fixture(records, done=True):
data = b''.join(b'data: ' + json.dumps(r).encode() + b'\n\n' for r in records)
return io.BytesIO(data + (b'data: [DONE]\n\n' if done else b''))
class SafetyTests(unittest.TestCase):
def test_default_bench_is_offline(self):
with patch.object(bench.urllib.request, 'urlopen', side_effect=AssertionError('network forbidden')):
with contextlib.redirect_stdout(io.StringIO()) as output:
bench.run(argparse.Namespace(go=False))
self.assertFalse(json.loads(output.getvalue())['inference_performed'])
def test_default_launch_has_no_side_effect(self):
with patch.object(launch.subprocess, 'Popen', side_effect=AssertionError('launch forbidden')):
with contextlib.redirect_stdout(io.StringIO()) as output:
launch.run(argparse.Namespace(go=False))
self.assertFalse(json.loads(output.getvalue())['launch_performed'])
def test_benchmark_requires_maintenance(self):
with self.assertRaises(ValueError):
bench.run(argparse.Namespace(go=True, exclusive_window_confirmed=False))
def test_launcher_requires_maintenance_and_deadline(self):
with self.assertRaises(ValueError):
launch.run(argparse.Namespace(go=True, maintenance_confirmed=False, deadline=None))
def test_candidate_pins_only_5080_and_existing_assets(self):
config = launch.configuration()
self.assertEqual(config['env']['CUDA_VISIBLE_DEVICES'], launch.GPU)
self.assertEqual(config['parallel'], 1)
self.assertNotIn('--layer-split', config['args'])
self.assertNotIn('api_key', config)
self.assertEqual(config['port'], 18420)
def test_refuses_remote_or_wrong_model(self):
for url, model in [('http://example.com:18420', 'flash-next-speedy-test'),
('http://127.0.0.1:8120', 'some-other-model'),
('http://127.0.0.1:18420/other', 'flash-next-speedy-test')]:
with self.assertRaises(ValueError):
bench.target(url, model)
def test_complete_synthetic_stream(self):
records = [{'choices': [{'delta': {'content': 'synthetic fixture'}}]},
{'choices': [], 'usage': {'prompt_tokens': 20, 'completion_tokens': 3},
'timings': {'predicted_per_second': 12.0, 'cache_n': 10, 'private': 'not copied'}}]
result, text = bench.stream('http://127.0.0.1:18420', '', 'flash-next-speedy-test', [], 256,
opener=lambda *a, **k: fixture(records))
self.assertEqual(text, 'synthetic fixture')
self.assertEqual(result['usage']['completion_tokens'], 3)
self.assertEqual(result['engine_timings']['cache_n'], 10)
self.assertNotIn('private', result['engine_timings'])
def test_rejects_incomplete_stream(self):
with self.assertRaises(ValueError):
bench.stream('http://127.0.0.1:18420', '', 'flash-next-speedy-test', [], 256,
opener=lambda *a, **k: fixture([], done=False))
def test_rejects_backend_error(self):
with self.assertRaises(ValueError):
bench.stream('http://127.0.0.1:18420', '', 'flash-next-speedy-test', [], 256,
opener=lambda *a, **k: fixture([{'error': {'message': 'synthetic error'}}]))
def test_rejects_single_token_peak(self):
with self.assertRaises(ValueError):
bench.stream('http://127.0.0.1:18420', '', 'flash-next-speedy-test', [], 1,
opener=lambda *a, **k: fixture([
{'choices': [{'delta': {'content': 'x'}}]},
{'usage': {'completion_tokens': 1}}]))
if __name__ == '__main__':
unittest.main()