Files
leleka/scripts/strata-dual-256-experiment.py

164 lines
6.0 KiB
Python

#!/usr/bin/env python3
"""Private Linux GPU experiment: two independent 256K Strata workers.
This offline controller reuses a local source configuration and its credential.
It never prints or persists the credential outside private tmpfs config files.
The normal Strata service on port 8080 is not touched.
"""
import json
import os
from pathlib import Path
import signal
import subprocess
import sys
import time
import urllib.request
SOURCE = Path('/home/para/inference/strata/strata-iq3_s.json')
ENGINE = Path('/home/para/.cache/leleka-api/engine-fork-f80a3e0/build/strata')
PYTHON = Path('/home/para/inference/strata/.venv/bin/python')
SERVER = Path('/home/para/inference/strata/serve/server.py')
ROOT = Path('/home/para/.cache/leleka-api/dual-256')
STATE = ROOT / 'state.json'
HOST = '192.168.1.196'
PORTS = (18081, 18082)
EXPERT_SLOTS = 2000
def config_path(port):
return Path(f'/dev/shm/leleka-api-dual-{port}.json')
def process_is_ours(pid, port):
try:
command = Path(f'/proc/{pid}/cmdline').read_bytes().replace(b'\0', b' ').decode()
except (OSError, ValueError):
return False
return str(SERVER) in command and str(config_path(port)) in command
def health(port):
try:
with urllib.request.urlopen(f'http://{HOST}:{port}/health', timeout=2) as response:
value = json.load(response)
return bool(value.get('loaded') and value.get('max_context') == 262144)
except (OSError, ValueError):
return False
def gpu_mib():
output = subprocess.check_output(
['nvidia-smi', '--query-gpu=memory.used', '--format=csv,noheader,nounits'], text=True)
return int(output.splitlines()[0].strip())
def read_state():
return json.loads(STATE.read_text()) if STATE.exists() else {'workers': []}
def status():
workers = read_state()['workers']
return {'workers': [{'port': w['port'], 'pid': w['pid'],
'alive': process_is_ours(w['pid'], w['port']),
'ready': health(w['port'])} for w in workers],
'gpu_used_mib': gpu_mib()}
def stop():
workers = read_state()['workers']
for w in workers:
port, pid = w['port'], w['pid']
cfg = config_path(port)
if process_is_ours(pid, port) and cfg.exists() and health(port):
key = json.loads(cfg.read_text())['api_key']
request = urllib.request.Request(
f'http://{HOST}:{port}/unload', data=b'{}', method='POST',
headers={'Authorization': 'Bearer ' + key, 'Content-Type': 'application/json'})
try:
urllib.request.urlopen(request, timeout=90).close()
except OSError:
pass
if process_is_ours(pid, port):
os.killpg(pid, signal.SIGTERM)
for _ in range(30):
if not any(process_is_ours(w['pid'], w['port']) for w in workers):
break
time.sleep(1)
for w in workers:
if process_is_ours(w['pid'], w['port']):
os.killpg(w['pid'], signal.SIGKILL)
config_path(w['port']).unlink(missing_ok=True)
STATE.unlink(missing_ok=True)
return status()
def start():
if STATE.exists():
raise RuntimeError('dual experiment already has state; inspect or stop it first')
if gpu_mib() > 1024:
raise RuntimeError('GPU is occupied; dual experiment requires an idle GPU')
if any(health(port) for port in PORTS):
raise RuntimeError('an experiment port already has a ready server')
for path in (SOURCE, ENGINE, PYTHON, SERVER):
if not path.is_file():
raise FileNotFoundError(path)
source = json.loads(SOURCE.read_text())
args = source['args']
if (args[args.index('--max-context') + 1] != '262144' or
args[args.index('--kv') + 1] != 'int8' or
args[args.index('--kv-resident') + 1] != '32768' or
args[args.index('--expert-cache') + 1] != 'auto'):
raise RuntimeError('source config differs from the measured 1x256K INT8 baseline')
ROOT.mkdir(mode=0o700, parents=True, exist_ok=True)
os.chmod(ROOT, 0o700)
workers = []
try:
for port in PORTS:
cfg = dict(source)
cfg['exe'] = str(ENGINE)
cfg['port'] = port
cfg['args'] = list(args)
cfg['args'][cfg['args'].index('--expert-cache') + 1] = str(EXPERT_SLOTS)
cfg['log'] = str(ROOT / f'engine-{port}.log')
path = config_path(port)
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, 'w') as file:
json.dump(cfg, file)
with (ROOT / f'server-{port}.log').open('ab') as output:
proc = subprocess.Popen(
[str(PYTHON), '-u', str(SERVER), '--engine', 'strata',
'--config', str(path), '--host', HOST, '--port', str(port)],
cwd=source['cwd'], stdout=output, stderr=subprocess.STDOUT,
start_new_session=True, close_fds=True)
workers.append({'port': port, 'pid': proc.pid})
STATE.write_text(json.dumps({'workers': workers}) + '\n')
os.chmod(STATE, 0o600)
deadline = time.monotonic() + 360
grace = time.monotonic() + 5
while time.monotonic() < deadline:
if health(port):
break
if time.monotonic() > grace and not process_is_ours(proc.pid, port):
raise RuntimeError(f'worker on {port} exited during startup')
time.sleep(3)
else:
raise TimeoutError(f'worker on {port} did not become ready')
return status()
except BaseException:
stop()
for port in PORTS:
config_path(port).unlink(missing_ok=True)
raise
def main():
if len(sys.argv) != 2 or sys.argv[1] not in ('start', 'status', 'stop'):
raise SystemExit('usage: strata-dual-256-experiment.py start|status|stop')
print(json.dumps({'start': start, 'status': status, 'stop': stop}[sys.argv[1]]()))
if __name__ == '__main__':
main()