Files
Athena-Deck/docs/experiments/deepseek-026-64k-2026-10-26/run_context.py
T

287 lines
13 KiB
Python

#!/usr/bin/env python3
"""One authorized pilot; owned workers only, production priority, finally restore."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import secrets
import signal
import subprocess
import sys
import time
import urllib.request
import threading
import random
BASE = Path(os.environ.get('DECK_TEST_BASE', '/data/athena-deck-strata/experiments/deepseek-026-64k-20261026'))
STATE = Path(os.environ.get('DECK_TEST_STATE', '/opt/athena-deck-dev/runtime/state'))
SOURCE = STATE / 'strata-runtime/source'
ASSETS = Path('/data/athena-deck-strata/experiments/deepseek-iq2-20261024')
PYTHON = ASSETS / 'venv/bin/python'
SETTINGS = ('profiles.json', 'endpoint.json', 'audio-policy.json', 'cpu-partition.json', 'reasoning-budget.json')
def hashes():
return {n: hashlib.sha256((STATE / n).read_bytes()).hexdigest() for n in SETTINGS}
def translate(obj):
if isinstance(obj, str):
return obj.replace('/var/lib/deck/', str(STATE) + '/')
if isinstance(obj, list):
return [translate(v) for v in obj]
if isinstance(obj, dict):
return {k: translate(v) for k, v in obj.items()}
return obj
def main(key, run):
run.mkdir(parents=True, exist_ok=False)
result = dict(started_at=time.time(), previous_profile=None, arms={}, restored=False)
(BASE / 'active-context-run.txt').write_text(str(run) + '\n')
deadline = time.monotonic() + 1800
owned = None
measurement = None
original_stopped = False
def save(phase):
result['phase'] = phase
result['updated_at'] = time.time()
temp = run / 'result.tmp'
temp.write_text(json.dumps(result, indent=2) + '\n')
temp.replace(run / 'result.json')
print(phase, flush=True)
def api(path, body=None, timeout=15):
req = urllib.request.Request('http://127.0.0.1:' + ('8120' if path.startswith('/v1/') else '8108') + path,
data=json.dumps(body).encode() if body is not None else None,
headers={'Authorization': 'Bearer ' + key, 'Content-Type': 'application/json'})
with urllib.request.urlopen(req, timeout=timeout) as response:
return json.load(response)
def idle():
stop = time.monotonic() + 1800
clean = 0
while time.monotonic() < stop:
if api('/api/v1/status')['endpoint']['active_requests'] == 0:
clean += 1
if clean >= 3:
return
else:
clean = 0
time.sleep(1)
raise RuntimeError('No idle window; productive requests left untouched')
def abort_check():
if (run / 'stop.request').exists() or time.monotonic() > deadline:
raise RuntimeError('Own test stop requested or overall time limit')
def stop_owned():
nonlocal owned, measurement
if measurement and measurement.poll() is None:
measurement.terminate()
try:
measurement.wait(timeout=8)
except subprocess.TimeoutExpired:
measurement.kill()
measurement.wait()
measurement = None
if owned and owned.poll() is None:
os.killpg(owned.pid, signal.SIGTERM)
try:
owned.wait(timeout=30)
except subprocess.TimeoutExpired:
os.killpg(owned.pid, signal.SIGKILL)
owned.wait()
owned = None
def production_priority_check():
if api('/api/v1/status')['endpoint']['active_requests']:
time.sleep(.5)
if api('/api/v1/status')['endpoint']['active_requests']:
raise RuntimeError('Productive request arrived; only owned synthetic worker is stopped')
def worker_get(port, token, path):
req = urllib.request.Request('http://127.0.0.1:' + str(port) + path,
headers={'Authorization': 'Bearer ' + token})
with urllib.request.urlopen(req, timeout=3) as response:
return json.load(response)
def on_signal(signum, frame):
raise InterruptedError('Own comparison interrupted')
signal.signal(signal.SIGTERM, on_signal)
signal.signal(signal.SIGINT, on_signal)
try:
import socket
with socket.socket() as sock: sock.bind(('127.0.0.1',19084))
version=subprocess.check_output([str(SOURCE/'engine/strata-dsv41'),'--version'],text=True,env=dict(os.environ,LD_LIBRARY_PATH=str(SOURCE.parent/'cuda/lib')+':'+str(SOURCE.parent/'cuda/lib64'))).strip()
assert '0.1.51' in version
result['engine_version']=version
save('waiting_for_idle')
idle()
current = json.loads((STATE / 'strata-worker/worker.json').read_text())
assert 'IQ3_XXS' in current['args'][current['args'].index('--native') + 1], 'Expected existing XXS production worker'
result['previous_profile'] = current['model_name']
result['settings_before'] = hashes()
result['endpoint_before'] = api('/api/v1/status')['endpoint']
clean = {k: v for k, v in current.items() if k not in ('api_key', 'key')}
(run / 'qwen-template.json').write_text(json.dumps(clean, indent=2) + '\n')
candidates = []
accepted_paths = {b'/var/lib/deck/strata-worker/worker.json', str(STATE / 'strata-worker/worker.json').encode()}
for p in Path('/proc').iterdir():
if not p.name.isdigit():
continue
try:
args = (p / 'cmdline').read_bytes().split(b'\0')
if accepted_paths.intersection(args) and any(a.endswith(b'/serve/server.py') for a in args):
candidates.append(int(p.name))
except OSError:
pass
if len(candidates) != 1:
raise RuntimeError('Original worker identity is not unique')
pid = candidates[0]
if os.getpgid(pid) != pid:
raise RuntimeError('Original worker has unexpected process-group ownership')
# The exact server PID supplies its network namespace for either a
# native service or today's container transport; no Docker dependency.
check = "import json,sys,urllib.request;x=json.load(sys.stdin);r=urllib.request.Request('http://127.0.0.1:'+str(x['port'])+'/v1/status',headers={'Authorization':'Bearer '+x['api_key']});d=json.load(urllib.request.urlopen(r,timeout=5));print(json.dumps(d.get('activity',{}).get('in_flight')))"
for _ in range(600):
idle()
active = json.loads(subprocess.check_output(['nsenter', '-t', str(pid), '-n', 'python3', '-c', check], input=json.dumps(current), text=True))
if active == 0:
break
time.sleep(2)
else:
raise RuntimeError('Original worker is not idle')
idle()
save('unloading_idle_qwen')
os.killpg(pid, signal.SIGTERM)
original_stopped = True
for _ in range(60):
# Normal status polling lets Deck reap its completed Popen child.
api('/api/v1/status')
if not Path('/proc/' + str(pid)).exists():
break
time.sleep(1)
else:
raise RuntimeError('Original worker did not stop; no forced production kill')
cpus = json.loads((STATE / 'cpu-partition.json').read_text())['strata']
result['cpu_affinity'] = cpus
result['protocol'] = dict(contexts=[65536], experts=6, target_input='context minus 1024', output_limit=128,
temperature=0, top_p=1, seed=42, thinking=False, repetitions=1,
synthetic='unique Python source lines with three retrieval markers', reserve_min_available_mib=1536)
for context in (65536,):
arm = str(context)
abort_check()
idle()
cfg = json.loads((ASSETS / 'test-config.json').read_text())
cfg['args'][cfg['args'].index('--max-context') + 1] = str(context)
assert '--experts' not in cfg['args']
cfg['args'] += ['--experts','6']
cfg['exe']=str(SOURCE/'engine/strata-dsv41')
cfg['cwd']=str(SOURCE)
cfg['lib_dirs']=[str(SOURCE/'engine'),str(SOURCE.parent/'cuda/lib'),str(SOURCE.parent/'cuda/lib64')]
cfg.update(host='127.0.0.1', port=19084, api_key='local-synthetic-context',
open_browser=False, log=str(run / (arm + '-engine.log')))
cfg_path = run / (arm + '-config.json')
cfg_path.write_text(json.dumps(cfg, indent=2) + '\n')
source = SOURCE
env = dict(os.environ, **cfg.get('env', {}), CUDA_VISIBLE_DEVICES='0,1', PYTHONUNBUFFERED='1')
env['LD_LIBRARY_PATH'] = ':'.join(cfg.get('lib_dirs', []) + [env.get('LD_LIBRARY_PATH', '')])
cmd = ['taskset', '-c', ','.join(map(str, cpus)), str(PYTHON), str(source / 'serve/server.py'),
'--engine', 'strata', '--config', str(cfg_path), '--host', '127.0.0.1', '--port', '19084', '--fit-max-tokens']
row = dict(context=context)
result['arms'][arm] = row
save('loading_' + arm)
started = time.monotonic()
with (run / (arm + '-server.log')).open('w') as log:
owned = subprocess.Popen(cmd, env=env, cwd=source, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
ready_deadline = time.monotonic() + 600
while time.monotonic() < ready_deadline:
abort_check()
production_priority_check()
mem={l.split(':')[0]:int(l.split()[1]) for l in Path('/proc/meminfo').read_text().splitlines()}
if mem['MemAvailable']<1536*1024:raise MemoryError('Host reserve below 1536MiB while loading')
if owned.poll() is not None:
row['error']='worker exited during loading'
break
try:
health = worker_get(19084, cfg['api_key'], '/health')
if health.get('status') == 'ok' and health.get('loaded', True):
row.update(load_seconds=time.monotonic()-started, health=health, worker_status=worker_get(19084, cfg['api_key'], '/v1/status'))
break
except OSError:
pass
time.sleep(2)
else:
row['error']='loading timeout'
if row.get('error'):
stop_owned()
save('unavailable_' + arm)
continue
save('measuring_' + arm)
args = [str(PYTHON), str(BASE / 'context_measure.py'), '--context', arm,
'--pid', str(owned.pid), '--output', str(run / (arm + '-measurement.json')), '--run']
with (run / (arm + '-measure.log')).open('w') as log:
measurement = subprocess.Popen(args, env=env, cwd=BASE, stdout=log, stderr=subprocess.STDOUT)
while measurement.poll() is None:
abort_check()
production_priority_check()
if owned.poll() is not None:
raise RuntimeError('worker failed during context measurement')
time.sleep(1)
out = run / (arm + '-measurement.json')
if out.exists():
row['measurement']=json.loads(out.read_text())
if measurement.returncode:
row['error']='measurement harness failed; inspect synthetic log'
stop_owned()
save('finished_' + arm)
except BaseException as exc:
result['error'] = type(exc).__name__ + ': ' + str(exc)
print(result['error'], flush=True)
finally:
stop_owned()
if original_stopped:
save('restoring_qwen')
try:
idle()
body = dict(model=result['previous_profile'], messages=[dict(role='user', content='Antworte mit OK.')],
max_tokens=1, temperature=0, reasoning_effort='none')
answer = api('/v1/chat/completions', body, timeout=900)
restored = json.loads((STATE / 'strata-worker/worker.json').read_text())
result['restored'] = bool(answer.get('choices')) and restored['model_name'] == result['previous_profile']
result['restored_profile'] = restored['model_name']
result['endpoint_after'] = api('/api/v1/status')['endpoint']
except Exception as exc:
result['restore_error'] = type(exc).__name__ + ': ' + str(exc)
result['settings_after'] = hashes()
result['settings_unchanged'] = result.get('settings_before') == result['settings_after']
result['finished_at'] = time.time()
save('complete' if result['restored'] and 'error' not in result and not any(a.get('error') for a in result['arms'].values()) else 'finished_with_error')
if __name__ == '__main__':
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument('--detach', action='store_true')
a = ap.parse_args()
key = json.load(sys.stdin)['key']
run = BASE / 'context-runs' / (time.strftime('%Y%m%dT%H%M%SZ', time.gmtime()) + '-' + secrets.token_hex(3))
if a.detach:
pid = os.fork()
if pid:
print(json.dumps(dict(pid=pid, directory=str(run))))
sys.exit(0)
os.setsid()
fd = os.open(str(BASE / 'context-controller.log'), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
os.dup2(fd, 1)
os.dup2(fd, 2)
os.close(fd)
fd = os.open('/dev/null', os.O_RDONLY)
os.dup2(fd, 0)
os.close(fd)
main(key, run)