190 lines
6.6 KiB
Python
190 lines
6.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Start one private Strata A/B agent profile on the Linux GPU host.
|
|
|
|
This is an offline experiment controller. It keeps its config in tmpfs, never
|
|
prints credentials, and does not modify the ordinary Strata service on port 8080.
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import signal
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import urllib.request
|
|
|
|
|
|
ROOT = Path('/home/para/.cache/strata-next/agent-profiles')
|
|
STATE = ROOT / 'state.json'
|
|
CONFIG = Path('/dev/shm/strata-next-agent-profile.json')
|
|
SOURCE = Path('/home/para/inference/strata/strata-iq3_s.json')
|
|
SERVER = Path('/home/para/inference/strata/serve/server.py')
|
|
PYTHON = Path('/home/para/inference/strata/.venv/bin/python')
|
|
ARCHIVE = Path('/mnt/microcrm-flash-preflight/microcrm-flash-next-experiment/strata-next/qwen-iq3-s-l2-v4.kar')
|
|
EXES = {
|
|
'strata-next-baseline': Path('/home/para/.cache/strata-next/engine-fork-f80a3e0/build/strata'),
|
|
'strata-next-kar-ple': Path('/home/para/.cache/strata-next/engine-kar-ple-build/strata'),
|
|
}
|
|
HOST = '192.168.1.196'
|
|
PORT = 18081
|
|
URL = f'http://{HOST}:{PORT}'
|
|
|
|
|
|
def pid_alive(pid):
|
|
try:
|
|
os.kill(pid, 0)
|
|
return True
|
|
except (ProcessLookupError, PermissionError):
|
|
return False
|
|
|
|
|
|
def state():
|
|
if not STATE.exists():
|
|
return None
|
|
value = json.loads(STATE.read_text())
|
|
if not pid_alive(value['pid']):
|
|
return None
|
|
return value
|
|
|
|
|
|
def health():
|
|
try:
|
|
with urllib.request.urlopen(URL + '/health', timeout=3) as response:
|
|
value = json.load(response)
|
|
return {'ready': bool(value.get('loaded') and value.get('max_context') == 262144),
|
|
'context': value.get('max_context')}
|
|
except (OSError, ValueError):
|
|
return {'ready': False}
|
|
|
|
|
|
def status():
|
|
current = state()
|
|
observed = health() if current else {'ready': False}
|
|
return {'profile': current['profile'] if current else None,
|
|
'pid': current['pid'] if current else None, **observed}
|
|
|
|
|
|
def unload(current):
|
|
if health()['ready']:
|
|
key = json.loads(CONFIG.read_text())['api_key']
|
|
request = urllib.request.Request(URL + '/unload', data=b'{}', method='POST',
|
|
headers={'Authorization': 'Bearer ' + key,
|
|
'Content-Type': 'application/json'})
|
|
with urllib.request.urlopen(request, timeout=180) as response:
|
|
if response.status != 200:
|
|
raise RuntimeError('model unload failed')
|
|
try:
|
|
os.killpg(current['pid'], signal.SIGTERM)
|
|
except ProcessLookupError:
|
|
pass
|
|
for _ in range(30):
|
|
if not pid_alive(current['pid']):
|
|
break
|
|
time.sleep(1)
|
|
if pid_alive(current['pid']):
|
|
os.killpg(current['pid'], signal.SIGKILL)
|
|
STATE.unlink(missing_ok=True)
|
|
CONFIG.unlink(missing_ok=True)
|
|
|
|
|
|
def ensure_idle():
|
|
current = state()
|
|
if not current:
|
|
return
|
|
config = json.loads(CONFIG.read_text())
|
|
key = config['api_key']
|
|
request = urllib.request.Request(URL + '/slots',
|
|
headers={'Authorization': 'Bearer ' + key})
|
|
try:
|
|
with urllib.request.urlopen(request, timeout=5) as response:
|
|
slots = json.load(response)
|
|
except (OSError, ValueError):
|
|
raise RuntimeError('experimental server is loading or its state is unknown')
|
|
if not slots or any(slot.get('is_processing', True) for slot in slots):
|
|
raise RuntimeError('experimental server is processing a request')
|
|
|
|
|
|
def start(profile):
|
|
if profile not in EXES:
|
|
raise ValueError('unknown experiment profile')
|
|
current = state()
|
|
if current and current['profile'] == profile:
|
|
return {'started': False, **status()}
|
|
if current:
|
|
ensure_idle()
|
|
unload(current)
|
|
elif STATE.exists():
|
|
STATE.unlink()
|
|
CONFIG.unlink(missing_ok=True)
|
|
if health()['ready']:
|
|
raise RuntimeError('port is already occupied by an untracked server')
|
|
used = subprocess.check_output(
|
|
['nvidia-smi', '--query-gpu=memory.used', '--format=csv,noheader,nounits'],
|
|
text=True).strip()
|
|
if int(used.splitlines()[0]) > 1024:
|
|
raise RuntimeError('GPU is already occupied by another workload')
|
|
for path in (SOURCE, SERVER, PYTHON, EXES[profile]):
|
|
if not path.is_file():
|
|
raise FileNotFoundError(path)
|
|
if profile == 'strata-next-kar-ple' and not ARCHIVE.is_file():
|
|
raise FileNotFoundError(ARCHIVE)
|
|
raw = json.loads(SOURCE.read_text())
|
|
args = raw['args']
|
|
if (args[args.index('--max-context') + 1] != '262144' or
|
|
args[args.index('--kv') + 1] != 'int8' or
|
|
args[args.index('--kv-resident') + 1] != '32768'):
|
|
raise RuntimeError('expected 1x256K with INT8 K+V and 32768 resident cells')
|
|
if '--ple-kar' in args or '--control-vector-scaled' in args:
|
|
raise RuntimeError('source config contains another experiment')
|
|
cfg = dict(raw)
|
|
cfg['exe'] = str(EXES[profile])
|
|
cfg['args'] = list(args)
|
|
if profile == 'strata-next-kar-ple':
|
|
cfg['args'] += ['--ple-kar', str(ARCHIVE), '--ple-kar-level', '2']
|
|
ROOT.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
os.chmod(ROOT, 0o700)
|
|
cfg['log'] = str(ROOT / f'{profile}-engine.log')
|
|
fd = os.open(CONFIG, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
try:
|
|
with os.fdopen(fd, 'w') as file:
|
|
json.dump(cfg, file)
|
|
log = ROOT / f'{profile}-server.log'
|
|
with log.open('ab') as output:
|
|
proc = subprocess.Popen([str(PYTHON), '-u', str(SERVER), '--engine', 'strata',
|
|
'--config', str(CONFIG), '--host', HOST, '--port', str(PORT)],
|
|
cwd=raw['cwd'], stdout=output, stderr=subprocess.STDOUT,
|
|
start_new_session=True, close_fds=True)
|
|
STATE.write_text(json.dumps({'pid': proc.pid, 'profile': profile}) + '\n')
|
|
os.chmod(STATE, 0o600)
|
|
except BaseException:
|
|
CONFIG.unlink(missing_ok=True)
|
|
raise
|
|
return {'started': True, **status()}
|
|
|
|
|
|
def main():
|
|
action = sys.argv[1]
|
|
payload = json.load(sys.stdin)
|
|
if action == 'status':
|
|
result = status()
|
|
elif action == 'start':
|
|
result = start(payload['profile'])
|
|
elif action == 'stop':
|
|
current = state()
|
|
if current:
|
|
ensure_idle()
|
|
unload(current)
|
|
result = {'stopped': bool(current)}
|
|
else:
|
|
raise ValueError('unknown action')
|
|
print(json.dumps(result))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
try:
|
|
main()
|
|
except Exception as exc:
|
|
print(type(exc).__name__ + ': ' + str(exc), file=sys.stderr)
|
|
sys.exit(1)
|