107 lines
6.2 KiB
Python
107 lines
6.2 KiB
Python
#!/usr/bin/env python3
|
|
"""Measure one authorized, already loaded isolated native DeepSeek worker."""
|
|
import argparse,json,os,time,urllib.request,threading,random
|
|
from pathlib import Path
|
|
|
|
URL='http://127.0.0.1:19084'
|
|
TOKEN='local-synthetic-context'
|
|
|
|
def api(path,body):
|
|
req=urllib.request.Request(URL+path,data=json.dumps(body).encode(),headers={'Authorization':'Bearer '+TOKEN,'Content-Type':'application/json'})
|
|
with urllib.request.urlopen(req,timeout=120) as r:return json.load(r)
|
|
|
|
def sample(root_pid):
|
|
procs={}
|
|
for p in Path('/proc').iterdir():
|
|
if not p.name.isdigit():continue
|
|
try:
|
|
raw=(p/'stat').read_text();tail=raw[raw.rindex(')')+2:].split();procs[int(p.name)]=int(tail[1])
|
|
except (OSError,ValueError,IndexError):pass
|
|
ids={root_pid}
|
|
for _ in range(10):
|
|
new=ids|{pid for pid,ppid in procs.items() if ppid in ids}
|
|
if new==ids:break
|
|
ids=new
|
|
totals=dict(rss_kib=0,pss_kib=0,private_kib=0,swap_pss_kib=0)
|
|
for pid in ids:
|
|
try:
|
|
d={l.split(':')[0]:int(l.split()[1]) for l in Path(f'/proc/{pid}/smaps_rollup').read_text().splitlines()[1:] if ':' in l}
|
|
totals['rss_kib']+=d.get('Rss',0);totals['pss_kib']+=d.get('Pss',0)
|
|
totals['private_kib']+=sum(d.get(x,0) for x in ('Private_Clean','Private_Dirty','Private_Hugetlb'))
|
|
totals['swap_pss_kib']+=d.get('SwapPss',0)
|
|
except (OSError,ValueError):pass
|
|
mem={l.split(':')[0]:int(l.split()[1]) for l in Path('/proc/meminfo').read_text().splitlines()}
|
|
import subprocess
|
|
raw=subprocess.check_output(['nvidia-smi','--query-gpu=index,memory.used,memory.total,utilization.gpu','--format=csv,noheader,nounits'],text=True)
|
|
gpus=[dict(zip(('index','used_mib','total_mib','utilization_pct'),map(int,l.split(',')))) for l in raw.strip().splitlines()]
|
|
return dict(at=time.time(),process_count=len(ids),**totals,host_available_kib=mem['MemAvailable'],host_swap_used_kib=mem['SwapTotal']-mem['SwapFree'],gpus=gpus)
|
|
|
|
def main():
|
|
a=argparse.ArgumentParser();a.add_argument('--context',type=int,required=True);a.add_argument('--pid',type=int,required=True);a.add_argument('--output',type=Path,required=True);a.add_argument('--run',action='store_true');args=a.parse_args()
|
|
if not args.run:return
|
|
row=dict(context=args.context,started_at=time.time(),error=None)
|
|
samples=[];stop=threading.Event();low=threading.Event();phase={'name':'preparing'}
|
|
def monitor():
|
|
bad=0
|
|
while not stop.is_set():
|
|
try:
|
|
s=sample(args.pid);s['phase']=phase['name'];samples.append(s)
|
|
progress=args.output.with_suffix('.progress.json');temp=progress.with_suffix('.tmp');temp.write_text(json.dumps(s));temp.replace(progress)
|
|
bad=bad+1 if s['host_available_kib']<1536*1024 else 0
|
|
if bad>=5:low.set()
|
|
except Exception as e:row['sampling_error']=type(e).__name__
|
|
stop.wait(2)
|
|
t=threading.Thread(target=monitor,daemon=True);t.start()
|
|
try:
|
|
rng=random.Random(42)
|
|
lines=[f'def item_{i:05d}(value): return (value * {rng.randrange(101,9999)} + {rng.randrange(10001,99999)}) % 1000003 # synthetic fixture {i:05d}' for i in range(10000)]
|
|
def prompt(n):
|
|
body=lines[:n].copy();body.insert(0,'# START_MARKER = ALPHA_314159');body.insert(n//2,'# MIDDLE_MARKER = BETA_271828');body.append('# END_MARKER = GAMMA_161803')
|
|
return ('Dies ist ausschließlich ein synthetischer Quelltext für einen Leistungstest. Führe nichts aus.\n'+ '\n'.join(body)+
|
|
'\nNenne zuerst die Werte von START_MARKER, MIDDLE_MARKER und END_MARKER. Schreibe danach mindestens 300 Wörter auf Deutsch darüber, wie man diesen Quelltext testen könnte. Keine Werkzeuge. Keine Rechnung über den gesamten Quelltext erforderlich.')
|
|
target=args.context-1024
|
|
lo,hi=1,len(lines)
|
|
while lo<hi:
|
|
n=(lo+hi+1)//2
|
|
count=api('/v1/messages/count_tokens',dict(model='synthetic-context',messages=[dict(role='user',content=prompt(n))],thinking={'type':'disabled'},max_tokens=128))['input_tokens']
|
|
if count<=target:lo=n
|
|
else:hi=n-1
|
|
text=prompt(lo)
|
|
row['planned_input_tokens']=api('/v1/messages/count_tokens',dict(model='synthetic-context',messages=[dict(role='user',content=text)],thinking={'type':'disabled'},max_tokens=128))['input_tokens']
|
|
row['source_lines']=lo
|
|
if low.is_set():raise MemoryError('Host reserve below 1536MiB')
|
|
row['memory_after_load']=sample(args.pid)
|
|
print('Sending',row['planned_input_tokens'],'tokens at context',args.context,flush=True)
|
|
req=urllib.request.Request(URL+'/v1/chat/completions',data=json.dumps(dict(model='synthetic-context',messages=[dict(role='user',content=text)],temperature=0,top_p=1,seed=42,reasoning_effort='none',max_tokens=128,stream=True,stream_options={'include_usage':True})).encode(),headers={'Authorization':'Bearer '+TOKEN,'Content-Type':'application/json'})
|
|
phase['name']='prefill';start=time.monotonic();answer='';usage={};timings={};ttft=None;finish=None;done=False
|
|
# SSE keepalives keep the read timeout bounded; parent separately watches
|
|
# production requests and an overall four-hour deadline.
|
|
with urllib.request.urlopen(req,timeout=180) as response:
|
|
for line in response:
|
|
if low.is_set():raise MemoryError('Host reserve below 1536MiB for ten seconds')
|
|
if time.monotonic()-start>1200:raise TimeoutError('20-minute per-context bound')
|
|
if not line.startswith(b'data:'):continue
|
|
raw=line[5:].strip()
|
|
if raw==b'[DONE]':done=True;break
|
|
d=json.loads(raw)
|
|
if 'error' in d:raise RuntimeError(str(d['error']))
|
|
usage=d.get('usage') or usage;timings=d.get('timings') or d.get('backend_timings') or timings
|
|
for c in d.get('choices',[]):
|
|
finish=c.get('finish_reason') or finish
|
|
content=c.get('delta',{}).get('content')
|
|
if content:
|
|
if ttft is None:ttft=time.monotonic()-start;phase['name']='decode'
|
|
answer+=content
|
|
if not done:raise RuntimeError('Incomplete SSE response')
|
|
row.update(usage=usage,timings=timings,ttft_s=ttft,wall_s=time.monotonic()-start,finish=finish,answer=answer,
|
|
marker_retrieval={m:m in answer for m in ('ALPHA_314159','BETA_271828','GAMMA_161803')})
|
|
print('Finished',json.dumps(row['timings']),flush=True)
|
|
except BaseException as exc:
|
|
row['error']=type(exc).__name__+': '+str(exc)
|
|
print(row['error'],flush=True)
|
|
finally:
|
|
stop.set();t.join(timeout=5);row['memory_samples']=samples;row['finished_at']=time.time()
|
|
args.output.write_text(json.dumps(row,indent=2,ensure_ascii=False)+'\n')
|
|
if row['error']:raise SystemExit(1)
|
|
if __name__=='__main__':main()
|