Files
Athena-Deck/docs/experiments/strata-resource-tuning-2026-10-20/launch.py
T

120 lines
7.1 KiB
Python

"""Host-controlled isolated Strata tuning, no Deck restart or login bypass."""
import json,os,signal,subprocess,sys,time,urllib.request
from pathlib import Path as P
STAGE=P('/opt/athena-deck-dev/strata-tune-20261020')
OUT=P('/data/experiments/strata-tune-20261020')
KEY=json.load(sys.stdin)['key']
RECORD=[]
OWN=[]
def request(path,data=None):
req=urllib.request.Request('http://127.0.0.1:'+('8120' if path.startswith('/v1/') else '8108')+path,
data=json.dumps(data).encode() if data is not None else None,headers={'Authorization':'Bearer '+KEY,'Content-Type':'application/json'})
with urllib.request.urlopen(req,timeout=650) as r:return r.status,json.load(r)
def status(phase,**kw):
p=OUT/'status.tmp';p.write_text(json.dumps(dict(phase=phase,updated=time.time(),**kw)));p.replace(OUT/'status.json')
(OUT/'runs.json').write_text(json.dumps(RECORD,indent=2))
def memory():
d={k:int(v.split()[0]) for k,v in (line.split(':',1) for line in P('/proc/meminfo').read_text().splitlines())}
return dict(available_gib=d['MemAvailable']/1024**2,swap_used_mib=(d['SwapTotal']-d['SwapFree'])/1024)
def unload_idle():
for _ in range(2):
_,s=request('/api/v1/status')
if s['endpoint']['active_requests']:raise RuntimeError('Production requests active')
time.sleep(1)
# Only the exact Deck-owned Strata HTTP process group; no generic pkill.
found=[]
for p in P('/proc').glob('[0-9]*'):
try:
args=(p/'cmdline').read_bytes().split(b'\0')
if any(x.endswith(b'/serve/server.py') for x in args) and b'/var/lib/deck/strata-worker/worker.json' in args:
pid=int(p.name);group=os.getpgid(pid)
if group!=pid:raise RuntimeError('Unexpected worker process group')
found.append((pid,group))
except (OSError,ValueError):pass
if len(found)!=1:raise RuntimeError('Deck-owned Strata process not uniquely identified')
pid,group=found[0];os.killpg(group,signal.SIGTERM)
deadline=time.monotonic()+45
while time.monotonic()<deadline:
request('/api/v1/status') # Let the owning application reap its exited child.
if not P(f'/proc/{pid}').exists():break
time.sleep(1)
else:raise RuntimeError('Graceful Strata stop timed out; no force kill')
g=subprocess.check_output(['nvidia-smi','--query-compute-apps=pid','--format=csv,noheader,nounits'],text=True).strip()
if g and 'No running processes' not in g:raise RuntimeError('GPU still used; no isolated run')
status('production_model_unloaded')
def run(name,cpu,ram,reserve,long=False):
_,s=request('/api/v1/status')
if s['endpoint']['active_requests'] or s['endpoint']['counts']['llm']['loaded']:raise RuntimeError('New production activity')
root=OUT/name;root.mkdir();os.chown(root,65534,65534)
d=json.loads(subprocess.check_output(['docker','inspect','athena-deck-dev']))[0]
cname='athena-strata-tune-'+name+'-20261020'
args=['docker','run','--rm','--name',cname,'--gpus','all','--user','65534:65534','--read-only',
'--cap-drop','ALL','--security-opt','no-new-privileges:true','--memory',str(ram)+'g',
'--memory-swap',str(ram)+'g','--cpus',str(cpu),'--network','none',
'--tmpfs','/tmp:rw,nosuid,nodev,size=512m','-e','HOME=/experiment/home',
'-e','PYTHONDONTWRITEBYTECODE=1','-e','NVIDIA_DRIVER_CAPABILITIES=compute,utility',
'-e','TEST_ARMS=serial_mtp','-e','TEST_REPETITIONS=1','-e','TEST_TARGETS=65536',
'-e','TEST_LONG='+('1' if long else '0'),'-e','TEST_GPU_RESERVE='+str(reserve),'--entrypoint','python3']
for m in d['Mounts']:
if m['Type']=='bind' and (m['Destination']=='/var/lib/deck' or 'strata' in m['Destination']):
args+=['--mount',f"type=bind,src={m['Source']},dst={m['Destination']},readonly"]
args+=['--mount',f'type=bind,src={STAGE},dst=/test,readonly','--mount',f'type=bind,src={root},dst=/experiment',d['Config']['Image'],'/test/benchmark.py']
OWN.append(cname)
status('running',arm=name,cpu=cpu,ram=ram,reserve=reserve)
before=memory();watch=[];reason=None;low=0
with (root/'test.log').open('w') as log:
proc=subprocess.Popen(args,stdout=log,stderr=subprocess.STDOUT)
while proc.poll() is None:
m=memory();watch.append(dict(at=time.time(),**m))
low=low+1 if m['available_gib']<1.5 else 0
if low>=3 or m['swap_used_mib']>before['swap_used_mib']+128:reason='host_memory_guard'
if time.time()-watch[0]['at']>1000:reason='test_deadline'
_,s=request('/api/v1/status')
if s['endpoint']['active_requests']:reason='new_production_request'
if reason:
subprocess.run(['docker','stop','--time','25',cname],capture_output=True);break
time.sleep(3)
code=proc.wait()
(root/'host-memory.json').write_text(json.dumps(watch))
results=json.loads((root/'results.json').read_text()) if (root/'results.json').exists() else []
row=dict(name=name,cpu=cpu,ram_gib=ram,gpu_reserve_mib=reserve,long=long,exit_code=code,abort_reason=reason,
min_host_available_gib=min(x['available_gib'] for x in watch),max_host_swap_mib=max(x['swap_used_mib'] for x in watch))
if results:row['pair_seconds']=next((x['wall_seconds'] for x in results if x['case']=='parallel-short-0'),None)
RECORD.append(row);status('arm_complete',arm=name)
return code==0
def main():
prev=json.loads((STAGE/'previous-model.json').read_text())['model']
d=json.loads(subprocess.check_output(['docker','inspect','athena-deck-dev']))[0]
try:
unload_idle()
for cpu in (6,8,12):
if not run('cpu'+str(cpu),cpu,58,1024):raise RuntimeError('CPU comparison arm failed')
scores={r['cpu']:r['pair_seconds'] for r in RECORD}
chosen=12 if scores[12]<scores[8]*.95 else 8
status('cpu_selected',cpu=chosen,scores=scores)
if not run('reference',chosen,58,1024,True):raise RuntimeError('Matched long reference failed')
reserve=512
if not run('reserve512',chosen,58,reserve,True):
reserve=768
if not run('reserve768',chosen,58,reserve,True):raise RuntimeError('Reduced GPU reserve failed')
run('ram59',chosen,59,reserve,True)
status('measurements_complete',cpu=chosen,reserve=reserve)
finally:
# Stop only containers this invocation created, including on watcher errors.
for cname in OWN:
state=subprocess.run(['docker','inspect','--format','{{.State.Running}}',cname],capture_output=True,text=True)
if state.returncode==0 and state.stdout.strip()=='true':subprocess.run(['docker','stop','--time','25',cname],capture_output=True)
# A test-only container never owns production files or weights; all runs --rm.
_,s=request('/api/v1/status')
if s['endpoint']['active_requests'] or s['endpoint']['counts']['llm']['loaded']:
(OUT/'restore.json').write_text(json.dumps(dict(restored=False,reason='new_activity')))
else:
code,_=request('/v1/chat/completions',dict(model=prev,messages=[dict(role='user',content='OK')],max_tokens=1,reasoning_effort='none'))
(OUT/'restore.json').write_text(json.dumps(dict(restored=code==200,http_status=code,model=prev)))
after=json.loads(subprocess.check_output(['docker','inspect','athena-deck-dev']))[0]
(OUT/'production-unchanged.json').write_text(json.dumps(dict(restarted=d['State']['StartedAt']!=after['State']['StartedAt'],cpu=after['HostConfig']['NanoCpus']/1e9,memory_gib=after['HostConfig']['Memory']/2**30)))
status('finished')
if __name__=='__main__':
try:main()
except BaseException as e:status('failed',error_type=type(e).__name__);raise