From 2332a45a4be1af1ebd1c0b720f65f35da68e08a2 Mon Sep 17 00:00:00 2001 From: Mikei386 <44135113+Mikei386@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:40:54 +0200 Subject: [PATCH] Document Strata VRAM CPU and RAM tuning; persist 59 GiB budget --- docs/CURRENT_SYSTEM.md | 12 + .../README.md | 140 ++ .../benchmark.py | 195 +++ .../final-endpoint.json | 1 + .../final-production.json | 1 + .../launch-cpu12long.py | 110 ++ .../launch.py | 119 ++ .../phase1.json | 1517 +++++++++++++++++ .../phase2.json | 686 ++++++++ 9 files changed, 2781 insertions(+) create mode 100644 docs/experiments/strata-resource-tuning-2026-10-20/README.md create mode 100644 docs/experiments/strata-resource-tuning-2026-10-20/benchmark.py create mode 100644 docs/experiments/strata-resource-tuning-2026-10-20/final-endpoint.json create mode 100644 docs/experiments/strata-resource-tuning-2026-10-20/final-production.json create mode 100644 docs/experiments/strata-resource-tuning-2026-10-20/launch-cpu12long.py create mode 100644 docs/experiments/strata-resource-tuning-2026-10-20/launch.py create mode 100644 docs/experiments/strata-resource-tuning-2026-10-20/phase1.json create mode 100644 docs/experiments/strata-resource-tuning-2026-10-20/phase2.json diff --git a/docs/CURRENT_SYSTEM.md b/docs/CURRENT_SYSTEM.md index 3578f90..731548e 100644 --- a/docs/CURRENT_SYSTEM.md +++ b/docs/CURRENT_SYSTEM.md @@ -1,3 +1,15 @@ +## Strata resource tuning · 20 October 2026 (latest) + +Current Deck budget: **59 GiB memory and memory+swap, CPU quota8**. Updated live +and persisted in installation.json; no restart. GPU reserves remain1024 MiB each, +loop guard stop; prior single-slot profile restored, TTS/STT loaded. +512 MiB reserves fail MTP startup (178 MiB needed,70 free). 768/768 runs but5080 +has only26 MiB free; fresh64K pair92.55s vs94.31s is not worth that margin. +CPU12 fresh94.20s vs8 CPU94.31s gives no established gain; RAM59 did not improve +fresh throughput in the matched test. About3.7 GiB remains outside Deck's maximum. +[Measurements, limitations, reproduction and native/restore notes](experiments/strata-resource-tuning-2026-10-20/README.md). +Earlier58-GiB entries below are historical. + ## Strata dual-slot with 64 GB RAM · 20 October 2026 Repeat through the existing published dual profile on Strata0.1.45: fresh pair diff --git a/docs/experiments/strata-resource-tuning-2026-10-20/README.md b/docs/experiments/strata-resource-tuning-2026-10-20/README.md new file mode 100644 index 0000000..897c457 --- /dev/null +++ b/docs/experiments/strata-resource-tuning-2026-10-20/README.md @@ -0,0 +1,140 @@ +# Strata resource tuning · 20 October 2026 + +## Decision and final live state + +Deck now has a **59 GiB memory and memory+swap cap**, persisted in the host +installation manifest. Production remains **8 CPU-equivalent quota, 1024 MiB +reserve per GPU**, and the previous `flash-next-strata-iq3` single-slot profile. +Loop guard remains `stop`. Deck is healthy, TTS/STT are loaded. No Deck/container +restart occurred; isolated test containers were removed. The final endpoint +snapshot includes one active request; it is not a claim that production stayed idle. + +512 MiB per card cannot load this configuration: the MTP draft head needs +178 MiB but only70 MiB remains. 768/768 loads, but the RTX5080 reaches only +26 MiB free during a long case. Neither this risk nor extra CPU quota is justified +by the small measured fresh-prompt differences. RAM59 is the highest budget tested +here with host headroom, not a proven mathematical maximum or throughput improvement. + +## Conditions and method + +- Strata0.1.45, source commit `477ac13cbe8e582c20484871ce459d20d82df09d`, + existing IQ3_XXS weights, RTX3060/RTX5080 split16. Same existing Deck image + `athena-deck-standalone:22f6b89a6d119cb3`; no new image or model downloads. +- Two slots, context262144 each, int8 KV, resident KV32768, serial batch-MTP, + batch-groups1, full draft vocabulary. No smaller context/vocabulary workaround. +- Same saved synthetic64K fixtures, temperature0, seed42, top_p1, top_k0, + reasoning none. Short solo/pair and cached pair output512 tokens per request; + fresh64K pair outputs256 each. All successful cases reached their output counts. +- Each arm is a fresh isolated container with automatic expert allocation. + Production CPU TTS/STT remain warm outside the test cgroup. This differs from + the earlier production dual test with24.46 GiB resident experts; do not attribute + cross-test speed differences solely to RAM or GPU reserve. +- One ordered run per arm, no forced physical-cache flush, no output-quality or + output-identity scoring. Adaptive MTP/cache/order effects limit causal conclusions. + Fresh means uncached prompt KV, not cold SSD/file cache. Only64K prompts tested, + not128K or full262K workloads. +- Docker --cpus changes CPU quota. Ryzen5600 has6 physical cores/12 SMT threads; + native pool-workers defaults to physical cores. No worker-pool/affinity changes + tested. A12 quota is not a test of12 physical cores. + +## Results + +Times are wall seconds for the whole request or concurrent pair. + +| Arm | CPU quota | RAM GiB | Reserve3060/5080 MiB | Experts GiB | Solo | Short pair | Fresh64K pair | Cached pair | +| --- | ---: | ---: | --- | ---: | ---: | ---: | ---: | ---: | +| cpu6 | 6 | 58 | 1024/1024 | 30.45 | 8.155 | 12.824 | — | — | +| cpu8 | 8 | 58 | 1024/1024 | 30.45 | 8.018 | 12.636 | — | — | +| cpu12 | 12 | 58 | 1024/1024 | 30.45 | 8.023 | 13.050 | — | — | +| reference | 8 | 58 | 1024/1024 | 30.45 | 8.035 | 12.932 | 94.311 | 16.727 | +| reserve512 | 8 | 58 | 512/512 | — | Load failure | — | — | — | +| reserve768 | 8 | 58 | 768/768 | 30.04 | 8.024 | 12.748 | 92.551 | 15.743 | +| ram59 | 8 | 59 | 768/768 | 30.04 | 8.017 | 12.630 | 93.264 | 14.845 | +| cpu12-long | 12 | 58 | 1024/1024 | 30.45 | 8.127 | 12.860 | 94.204 | 14.911 | +| asym768-1024 | 8 | 58 | 768/1024 | 30.28 | 8.398 | 12.477 | 93.068 | 15.088 | + +Asymmetric reserve leaves minimum370/282 MiB free on3060/5080, versus370/26 +for768/768. The1.3% fresh-prompt improvement of the asymmetric arm is not a +replicated gain; leave production GPU settings unchanged. GPU-free instrumentation +was added after the initial CPU/reference runs and is absent from those records. +Fresh reference physical engine reads0.19 GiB vs0.09 for768/asymmetric; storage +is no longer the dominant bottleneck under these warm-cache test conditions. + +RAM59 vs58 at equal768/768 reserves did not improve fresh-prompt time or expert +allocation. It leaves about3.7 GiB outside Deck's maximum on62.7 GiB usable RAM; +this is headroom, not a guaranteed reservation. TTS/STT are already inside the +production Deck budget, so do not subtract them twice. Host MemAvailable stayed +at least9.00 GiB during ram59; successful long arms reached about8.64 GiB minimum. +There were no OOM kills or safety aborts. Host swap had a small background use +(roughly0.5–1 MiB); test containers had no extra swap allowance. + +## Safety and restoration + +The host launcher checks authenticated normal status twice for zero active +requests, then gracefully SIGTERMs only the uniquely identified Deck Strata HTTP +worker process group (exact server.py and worker.json arguments). No generic pkill, +force kill or container restart. The owning app reaps its child via normal status. +This mechanism is specific to today's deployment, not an administrator API bypass +or a portable official unload command. Recheck these assumptions before reuse. + +Each test container is --rm, network none, read-only root, UID65534, all capabilities +dropped, no-new-privileges. Model/state binds are read-only; only its experiment +output is writable. The test server uses a synthetic local token; the real API key +is passed to the host launcher through stdin and must never be stored in Git/logs. +Host monitoring stops only the owned test container if MemAvailable is below1.5 GiB +three consecutive samples, swap grows128 MiB, a new production request starts, +or the1000-second deadline expires. Finally removes owned test containers and +restores the previous profile through the normal one-token API request when idle. +Restoration returned HTTP200. Container StartedAt was unchanged. + +## Reproduce, maintain and restore + +Archived Python scripts use only the standard library, Linux proc/cgroup v2, +Docker and nvidia-smi. The benchmark additionally needs the existing pinned Strata +runtime and weights; it does not install them. Launch scripts are **host-specific +operational recipes**, not generic copy-and-run tooling. Review paths, image, +process ownership, request status and budgets first; never run during active work. + +On today's host the stage is `/opt/athena-deck-dev/strata-tune-20261020` and outputs +are `/data/experiments/strata-tune-20261020` and +`/data/experiments/strata-tune-cpu12long-20261020`. Stage contains benchmark.py, +sanitized base-template.json (real api_key removed) and fixture-65536-0/1.json. +Recover fixtures by decompressing the two .json.gz files from the sibling +[strata-dual-ram experiment](../strata-dual-ram-2026-10-20/README.md). +Their SHA256 values are: + +- fixture0: `1fad19b62481ed46c30fcd68fc8e8d3ac8a91c5aa982d9a9267b1bff5f55b09c` +- fixture1: `5220d85c7e12926323e603bf08269155e808d61ca59c239652c282a93bcc07fa` + +Use the earlier pinned runtime/model restore recipe; do not copy private configs +into this repository. `launch.py` does the CPU scan/reference/reserve/RAM arms; +`launch-cpu12long.py` verifies CPU12 and the asymmetric reserve. Both read a JSON +object containing key from stdin; obtain it through the configured secret store, +not a shell argument, source file or terminal echo. Do not rerun into existing +output directories: deliberately create a reviewed fresh stage/output/name set. + +Persistent production manifest is +`/opt/athena-deck-dev/runtime/installation.json`: +`memory_limit: "59g"`, `memory_swap_limit: "59g"`, `cpu_limit: 8`. +Applied live via Docker update and the existing installer manifest writer; the +installer already consumes these fields at recreation. Rollback to58g requires +checking current usage fits the lower cap, updating both live limits and both +manifest fields. CPU/GPU/profile rollback is unnecessary: they were restored. + +For a future native Debian deployment: install the documented compiler/CUDA/runtime +and pinned weights, Python3, NVIDIA driver/nvidia-smi, and a cgroup-v2-capable +systemd. Preserve encrypted Deck state, profiles, voices and API identities. +Translate budgets to MemoryMax59GiB, MemorySwapMax0 and CPUQuota800%, with an +explicit service user and state/runtime paths. The archived benchmark assumes +container cgroup namespace paths; adapt them to the actual native service cgroup +before measurement. Docker host launchers are optional current-deployment tooling, +not native restore prerequisites. No new application dependency or feature is +introduced. Fresh-host native end-to-end restoration remains unqualified; this +experiment does not establish it. + +## Evidence + +phase1.json / phase2.json contain sanitized cases and allocation metadata. +final-production.json records live limits, profile and GPU reserves; +final-endpoint.json records health-related endpoint state and loaded modalities. +No user chats, generated answer text, private audio or real credentials are archived. diff --git a/docs/experiments/strata-resource-tuning-2026-10-20/benchmark.py b/docs/experiments/strata-resource-tuning-2026-10-20/benchmark.py new file mode 100644 index 0000000..981b0ff --- /dev/null +++ b/docs/experiments/strata-resource-tuning-2026-10-20/benchmark.py @@ -0,0 +1,195 @@ +"""Isolated, synthetic serial-MTP versus pipelined dual-slot comparison.""" +import concurrent.futures, copy, json, os, pathlib, random, re, signal +import socket, subprocess, threading, time, urllib.request +P = pathlib.Path +ROOT = P('/experiment') +SOURCE = P('/var/lib/deck/strata-runtime/source') +MODEL = 'synthetic-batch-ab' +KEY = 'synthetic-isolated-batch-test' +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=900): + 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('/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(self.base,'/slots',timeout=3) as response: + r['processing_slots']=sum(bool(x.get('is_processing')) for x in json.load(response)) + if len(self.rows)%5==0: + raw=subprocess.check_output(['nvidia-smi','--query-gpu=index,utilization.gpu,memory.used,memory.free','--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): + with http(base,'/v1/messages/count_tokens',dict(model=MODEL,system=system,messages=[dict(role='user',content=text)]),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_processing_slots=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),min_free_mib=min(g[3] 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 run(): + baseline=json.loads(P('/test/base-template.json').read_text()) + baseline.pop('previous_model',None) + if os.environ.get('TEST_OPT')=='1': + baseline.setdefault('env',{}).update({k:'1' for k in ('STRATA_SLOT_COPY_DIRECT','STRATA_SLOT_COPY_BATCHSYNC','STRATA_CKPT_POOL','STRATA_CKPT_THREADS','STRATA_BATCH_SELF_COMMIT','STRATA_QSA_SLOTS')}) + for arm,group in [('serial_mtp','1'),('pipeline','auto')]: + if arm not in os.environ.get('TEST_ARMS','serial_mtp,pipeline').split(','):continue + cfg=copy.deepcopy(baseline); args=cfg['args'] + if os.environ.get('TEST_GPU_RESERVE'): + for index,flag in enumerate(('--vram-reserve-mib','--vram-reserve-later-mib')): + values=os.environ['TEST_GPU_RESERVE'].split(',') + args[args.index(flag)+1]=values[index] if len(values)==2 else values[0] + if '--batch-groups' in args: + i=args.index('--batch-groups');del args[i:i+2] + args+=['--batch-groups',group] + if os.environ.get('TEST_RESIDENT_GIB'): + if '--resident-budget-gib' in args: + i=args.index('--resident-budget-gib');del args[i:i+2] + args+=['--resident-budget-gib',os.environ['TEST_RESIDENT_GIB']] + with socket.socket() as s:s.bind(('127.0.0.1',0));port=s.getsockname()[1] + cfg.update(api_key=KEY,port=port,host='127.0.0.1',model_name=MODEL,open_browser=False,log=str(ROOT/f'engine-{arm}.log')) + path=ROOT/f'config-{arm}.json';path.write_text(json.dumps(cfg));path.chmod(0o600) + base=f'http://127.0.0.1:{port}'; proc=None + env=dict(os.environ,**cfg.get('env',{}),PYTHONUNBUFFERED='1',PYTHONDONTWRITEBYTECODE='1') + env['LD_LIBRARY_PATH']='/var/lib/deck/strata-runtime/cuda/lib64:/var/lib/deck/strata-runtime/cuda/lib:'+env.get('LD_LIBRARY_PATH','') + try: + save('loading',arm=arm) + with (ROOT/f'server-{arm}.log').open('w') as log: + proc=subprocess.Popen([str(SOURCE/'.venv/bin/python'),str(SOURCE/'serve/server.py'),'--engine','strata','--config',str(path),'--host','127.0.0.1','--port',str(port),'--fit-max-tokens'],cwd=SOURCE,env=env,stdout=log,stderr=subprocess.STDOUT,start_new_session=True) + end=time.monotonic()+600 + while time.monotonic()0.02: + raise RuntimeError('Controlled expert budget was clamped; do not compare unequal allocations') + text=(ROOT/f'engine-{arm}.log').read_text(errors='replace') + allocation=re.findall(r'resident RAM mode: ([0-9.]+) GiB of experts in RAM',text) + (ROOT/'allocation.json').write_text(json.dumps(dict(expert_gib=float(allocation[-1]) if allocation else None,memory_max=(P('/sys/fs/cgroup')/'memory.max').read_text().strip(),cpu_max=(P('/sys/fs/cgroup')/'cpu.max').read_text().strip()))) + for rep in range(int(os.environ.get('TEST_REPETITIONS','1'))): + msgs=[[dict(role='system',content=f'Kurzmessung {rep}, Gespräch {i}. Schreibe auf Deutsch.'),dict(role='user',content='Schreibe einen ausführlichen Fachtext mit mindestens 1200 Wörtern über '+('Home Assistant.' if i else 'Datensicherung.'))] for i in range(2)] + measure(base,arm,f'solo-short-{rep}',[msgs[0]]) + msgs[0][0]['content']+=' Parallele Messung.' + measure(base,arm,f'parallel-short-{rep}',msgs) + for target in (map(int,os.environ.get('TEST_TARGETS','65536,131072').split(',')) if os.environ.get('TEST_LONG','1')=='1' else []): + save('calibrating',arm=arm,target=target) + msgs=[json.loads(P(f'/test/fixture-{target}-{i}.json').read_text()) for i in range(2)] + first=measure(base,arm,f'parallel-cold-{target}',msgs,256) + follow=[m+[dict(role='assistant',content=r['_content']),dict(role='user',content='Führe den Fachtext mit mindestens 1200 weiteren Wörtern fort.')] for m,r in zip(msgs,first)] + measure(base,arm,f'parallel-cached-{target}',follow,512) + finally: + if proc and proc.poll() is None: + os.killpg(proc.pid,signal.SIGTERM) + try:proc.wait(30) + except subprocess.TimeoutExpired:os.killpg(proc.pid,signal.SIGKILL);proc.wait() + path.unlink(missing_ok=True) + save('complete') + +if __name__=='__main__': + try:run() + except BaseException as e:save('failed',error_type=type(e).__name__);raise diff --git a/docs/experiments/strata-resource-tuning-2026-10-20/final-endpoint.json b/docs/experiments/strata-resource-tuning-2026-10-20/final-endpoint.json new file mode 100644 index 0000000..e94c5d9 --- /dev/null +++ b/docs/experiments/strata-resource-tuning-2026-10-20/final-endpoint.json @@ -0,0 +1 @@ +{"state": "running", "port": 8120, "counts": {"llm": {"enabled": 12, "available": 12, "loaded": true, "supported": true}, "image": {"enabled": 1, "available": 1, "loaded": false, "supported": true}, "tts": {"enabled": 1, "available": 1, "loaded": true, "supported": true}, "stt": {"enabled": 1, "available": 1, "loaded": true, "supported": true}, "music": {"enabled": 2, "available": 2, "loaded": false, "supported": true}, "voice": {"enabled": 1, "available": 1, "loaded": false, "supported": true}}, "active_requests": 1} diff --git a/docs/experiments/strata-resource-tuning-2026-10-20/final-production.json b/docs/experiments/strata-resource-tuning-2026-10-20/final-production.json new file mode 100644 index 0000000..a315b2d --- /dev/null +++ b/docs/experiments/strata-resource-tuning-2026-10-20/final-production.json @@ -0,0 +1 @@ +{"memory_gib": 59.0, "memory_swap_gib": 59.0, "cpu": 8.0, "health": "healthy", "profile": "flash-next-strata-iq3", "parallel": 1, "loop_guard": "stop", "reserve": ["1024", "1024"], "manifest_memory": "59g", "manifest_swap": "59g"} diff --git a/docs/experiments/strata-resource-tuning-2026-10-20/launch-cpu12long.py b/docs/experiments/strata-resource-tuning-2026-10-20/launch-cpu12long.py new file mode 100644 index 0000000..31d6c51 --- /dev/null +++ b/docs/experiments/strata-resource-tuning-2026-10-20/launch-cpu12long.py @@ -0,0 +1,110 @@ +"""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-cpu12long-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()=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() + if not run('cpu12-long',12,58,1024,True):raise RuntimeError('Long CPU comparison failed') + if not run('asym768-1024',8,58,'768,1024',True):raise RuntimeError('Asymmetric reserve test failed') + status('measurements_complete') + 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 diff --git a/docs/experiments/strata-resource-tuning-2026-10-20/launch.py b/docs/experiments/strata-resource-tuning-2026-10-20/launch.py new file mode 100644 index 0000000..1bfb9e6 --- /dev/null +++ b/docs/experiments/strata-resource-tuning-2026-10-20/launch.py @@ -0,0 +1,119 @@ +"""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()=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]