170 lines
10 KiB
Python
170 lines
10 KiB
Python
"""Saved synthetic fixtures measured through the normal Athena API."""
|
|
import concurrent.futures, copy, json, os, pathlib, random, re, signal
|
|
import socket, subprocess, threading, time, urllib.request
|
|
P = pathlib.Path
|
|
ROOT = P(os.environ.get('TEST_STAGE','/var/lib/deck/strata-half-context-20261020'))
|
|
SOURCE = P('/var/lib/deck/strata-runtime/source')
|
|
MODEL = 'flash-next-strata-iq3-dual'
|
|
import sys
|
|
KEY = json.load(sys.stdin)['key']
|
|
RESULTS = []
|
|
|
|
def save(phase, **extra):
|
|
ROOT.mkdir(exist_ok=True)
|
|
p = ROOT/'status.tmp'
|
|
p.write_text(json.dumps(dict(phase=phase, completed=len(RESULTS), updated=time.time(), **extra)))
|
|
p.replace(ROOT/'status.json')
|
|
(ROOT/'results.json').write_text(json.dumps(RESULTS, indent=2))
|
|
|
|
def http(base, route, data=None, timeout=2400):
|
|
req = urllib.request.Request(base+route, data=json.dumps(data).encode() if data is not None else None,
|
|
headers={'Authorization':'Bearer '+KEY, 'Content-Type':'application/json'})
|
|
return urllib.request.urlopen(req, timeout=timeout)
|
|
|
|
def numeric():
|
|
cg=P(os.environ.get('TEST_CGROUP_DIR','/sys/fs/cgroup'))
|
|
stat=dict((k,int(v)) for k,v in (x.split() for x in (cg/'memory.stat').read_text().splitlines()))
|
|
events=dict((k,int(v)) for k,v in (x.split() for x in (cg/'memory.events').read_text().splitlines()))
|
|
io=0; ticks=0
|
|
for p in P('/proc').glob('[0-9]*'):
|
|
try:
|
|
if (p/'comm').read_text().strip()!='strata': continue
|
|
st=(p/'stat').read_text().rsplit(')',1)[1].split()
|
|
ticks+=int(st[11])+int(st[12])
|
|
io+=int(dict(x.split(':') for x in (p/'io').read_text().splitlines())['read_bytes'])
|
|
except (OSError,ValueError): pass
|
|
pressure={x.split()[0]:int(re.search(r'total=(\d+)',x).group(1)) for x in (cg/'memory.pressure').read_text().splitlines()}
|
|
return dict(at=time.monotonic(), memory=int((cg/'memory.current').read_text()), read_bytes=io,
|
|
cpu_ticks=ticks, refault=stat.get('workingset_refault_file',0), major_fault=stat.get('pgmajfault',0),
|
|
max_events=events.get('max',0), oom=events.get('oom',0), oom_kill=events.get('oom_kill',0), pressure=pressure)
|
|
|
|
class Sampler:
|
|
def __init__(self,base): self.base=base; self.rows=[]; self.stop=threading.Event()
|
|
def run(self):
|
|
while not self.stop.is_set():
|
|
try:
|
|
r=numeric()
|
|
with http('http://127.0.0.1:8108','/api/v1/status',timeout=3) as response:
|
|
r['processing_slots']=json.load(response)['endpoint']['active_requests']
|
|
if len(self.rows)%5==0:
|
|
raw=subprocess.check_output(['nvidia-smi','--query-gpu=index,utilization.gpu,memory.used','--format=csv,noheader,nounits'],text=True,timeout=8)
|
|
r['gpus']=[[float(v.strip()) for v in line.split(',')] for line in raw.splitlines()]
|
|
self.rows.append(r)
|
|
except (OSError,ValueError): pass
|
|
self.stop.wait(1)
|
|
|
|
def generate(base,messages,limit=512):
|
|
body=dict(model=MODEL,messages=messages,max_tokens=limit,reasoning_effort='none',
|
|
temperature=0,top_p=1,top_k=0,seed=42,stream=True,stream_options={'include_usage':True})
|
|
start=time.monotonic(); first=None; content=''; usage={}; timings={}; finish=None; done=False
|
|
with http(base,'/v1/chat/completions',body) as response:
|
|
for line in response:
|
|
if not line.startswith(b'data:'): continue
|
|
raw=line[5:].strip()
|
|
if raw==b'[DONE]': done=True; break
|
|
v=json.loads(raw)
|
|
if 'error' in v: raise RuntimeError('Synthetic stream returned an error')
|
|
usage=v.get('usage') or usage
|
|
timings=v.get('timings') or v.get('backend_timings') or timings
|
|
for choice in v.get('choices',[]):
|
|
text=choice.get('delta',{}).get('content') or ''
|
|
if text and first is None: first=time.monotonic()
|
|
content+=text
|
|
finish=choice.get('finish_reason') or finish
|
|
if not done: raise RuntimeError('Synthetic stream ended without DONE')
|
|
return dict(wall_seconds=time.monotonic()-start,ttft_seconds=first-start if first else None,
|
|
usage=usage,backend_timings=timings,finish_reason=finish,_content=content)
|
|
|
|
def fixture(base,target,client):
|
|
path=ROOT/f'fixture-{target}-{client}.json'
|
|
if path.exists(): return json.loads(path.read_text())
|
|
system=f'Messung Kontext {target}, Gespräch {client}. Antworte auf Deutsch. Schreibe mindestens 1200 Wörter über '+('Home-Assistant-Automatisierungen.' if client else 'zuverlässige Datensicherung.')
|
|
def count(text):
|
|
# The public Deck router does not forward token counting. Use the already
|
|
# running local Strata worker's own tokenizer route; never save its key.
|
|
cfg=json.loads((ROOT.parent/'strata-worker/worker.json').read_text())
|
|
body=dict(model=MODEL,system=system,messages=[dict(role='user',content=text)])
|
|
req=urllib.request.Request('http://127.0.0.1:'+str(cfg['port'])+'/v1/messages/count_tokens',data=json.dumps(body).encode(),headers={'Authorization':'Bearer '+cfg['api_key'],'Content-Type':'application/json'})
|
|
with urllib.request.urlopen(req,timeout=120) as r:
|
|
return json.load(r)['input_tokens']
|
|
rng=random.Random(20261014+client)
|
|
rows=[f'Datensatz {i:06d}: Standort {rng.randrange(10000):04d}, Messwert {rng.randrange(100000000,999999999)}, Status archiviert.\n' for i in range(target//10+300)]
|
|
per=(count(''.join(rows[:100]))-count(''))/100
|
|
n=int((target-count(''))/per)
|
|
for _ in range(6):
|
|
text=''.join(rows[:n])+'\nFühre jetzt die ausführliche Schreibaufgabe aus.'
|
|
actual=count(text); delta=target-actual
|
|
if abs(delta)<64: break
|
|
n=max(1,n+int(delta/per))
|
|
if abs(actual-target)>128: raise RuntimeError('Tokenizer calibration failed')
|
|
value=[dict(role='system',content=system),dict(role='user',content=text)]
|
|
path.write_text(json.dumps(value)); return value
|
|
|
|
def measure(base,arm,case,messages,limit=512):
|
|
save('measuring',arm=arm,case=case)
|
|
before=numeric(); sampler=Sampler(base); thread=threading.Thread(target=sampler.run,daemon=True);thread.start()
|
|
start=time.monotonic()
|
|
try:
|
|
if len(messages)==1: rows=[generate(base,messages[0],limit)]
|
|
else:
|
|
barrier=threading.Barrier(len(messages))
|
|
def one(m): barrier.wait(); return generate(base,m,limit)
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=len(messages)) as pool: rows=list(pool.map(one,messages))
|
|
finally:
|
|
sampler.stop.set();thread.join(5)
|
|
elapsed=time.monotonic()-start; after=numeric(); peak=max([before['memory'],after['memory']]+[r['memory'] for r in sampler.rows])
|
|
res=dict(arm=arm,case=case,requests=len(messages),wall_seconds=elapsed,
|
|
aggregate_output_tok_s=sum(r['usage'].get('completion_tokens',0) for r in rows)/elapsed,
|
|
rows=[{k:v for k,v in r.items() if k!='_content'} for r in rows],
|
|
resources=dict(peak_memory_gib=peak/2**30,read_gib=(after['read_bytes']-before['read_bytes'])/2**30,
|
|
read_mib_s=(after['read_bytes']-before['read_bytes'])/elapsed/2**20,
|
|
refaults=after['refault']-before['refault'],major_faults=after['major_fault']-before['major_fault'],
|
|
limit_events=after['max_events']-before['max_events'],oom_kill_delta=after['oom_kill']-before['oom_kill'],
|
|
cpu_cores=(after['cpu_ticks']-before['cpu_ticks'])/os.sysconf('SC_CLK_TCK')/elapsed,
|
|
pressure_full_percent=(after['pressure']['full']-before['pressure']['full'])/elapsed/10000,
|
|
peak_admitted_requests=max([0]+[r.get('processing_slots',0) for r in sampler.rows])))
|
|
gpu_rows=[g for r in sampler.rows for g in r.get('gpus',[])]
|
|
res['resources']['gpu_samples']={str(int(i)):dict(mean_utilization=sum(g[1] for g in gpu_rows if g[0]==i)/sum(g[0]==i for g in gpu_rows),peak_memory_mib=max(g[2] for g in gpu_rows if g[0]==i)) for i in {g[0] for g in gpu_rows}}
|
|
RESULTS.append(res);save('measured',arm=arm,case=case)
|
|
return rows
|
|
|
|
|
|
def settings():
|
|
c=json.loads((ROOT.parent/'strata-worker/worker.json').read_text())
|
|
text=(ROOT.parent/'strata-worker/engine.log').read_text(errors='replace')
|
|
allocated=re.findall(r'resident RAM mode: ([0-9.]+) GiB of experts in RAM',text)
|
|
return dict(model=c['model_name'],parallel=c.get('parallel'),args=c['args'],environment=c.get('env',{}),resident_expert_gib=[float(x) for x in allocated[-1:]],memory_max=(P(os.environ.get('TEST_CGROUP_DIR','/sys/fs/cgroup'))/'memory.max').read_text().strip(),cpu_max=(P(os.environ.get('TEST_CGROUP_DIR','/sys/fs/cgroup'))/'cpu.max').read_text().strip())
|
|
|
|
def run():
|
|
global MODEL
|
|
base='http://127.0.0.1:8120'
|
|
ROOT.mkdir(exist_ok=True)
|
|
before=json.loads((ROOT.parent/'strata-worker/worker.json').read_text())
|
|
previous=before['model_name']
|
|
with http('http://127.0.0.1:8108','/api/v1/status') as r:s=json.load(r)
|
|
if s['endpoint']['active_requests']:raise RuntimeError('Production requests active')
|
|
(ROOT/'previous-model.json').write_text(json.dumps({'model':previous}))
|
|
try:
|
|
for model,target,clients in [('flash-next-strata-iq3-512k',262144,1),('flash-next-strata-iq3',131072,1),('flash-next-strata-iq3-dual',131072,2)]:
|
|
MODEL=model
|
|
with http('http://127.0.0.1:8108','/api/v1/status') as r:s=json.load(r)
|
|
if s['endpoint']['active_requests']:raise RuntimeError('New production activity')
|
|
save('loading',model=model)
|
|
with http(base,'/v1/chat/completions',dict(model=model,messages=[dict(role='user',content='OK')],max_tokens=1,reasoning_effort='none')) as r:json.load(r)
|
|
(ROOT/(model+'-settings.json')).write_text(json.dumps(settings(),indent=2))
|
|
save('calibrating',model=model,target=target)
|
|
msgs=[fixture(base,target,i) for i in range(clients)]
|
|
measure(base,model,'half-context-'+str(target),msgs,512)
|
|
save('complete')
|
|
finally:
|
|
with http('http://127.0.0.1:8108','/api/v1/status') as r:s=json.load(r)
|
|
if s['endpoint']['active_requests']:
|
|
(ROOT/'restore.json').write_text(json.dumps(dict(restored=False,reason='new_activity')))
|
|
else:
|
|
with http(base,'/v1/chat/completions',dict(model=previous,messages=[dict(role='user',content='OK')],max_tokens=1,reasoning_effort='none')) as r:
|
|
json.load(r);code=r.status
|
|
(ROOT/'restore.json').write_text(json.dumps(dict(http_status=code,model=previous,restored=code==200)))
|
|
if __name__=='__main__':
|
|
try:run()
|
|
except BaseException as e:save('failed',error_type=type(e).__name__);raise
|