"""Bounded Athena thread comparison; only CPU policy and idle Qwen are changed.""" import json, os, signal, subprocess, sys, time, urllib.request from pathlib import Path stage = Path(__file__).resolve().parent plan_path = Path('/opt/athena-deck-dev/runtime/state/cpu-partition.json') key = json.load(sys.stdin)['key'] headers = {'Authorization': 'Bearer ' + key} def endpoint(): req = urllib.request.Request('http://127.0.0.1:8108/api/v1/status', headers=headers) with urllib.request.urlopen(req, timeout=10) as response: return json.load(response)['endpoint'] def workers(): root = json.loads(subprocess.check_output(['docker', 'inspect', 'athena-deck-dev']))[0]['State']['Pid'] pending, seen, result = [root], set(), {} while pending: pid = pending.pop() if pid in seen: continue seen.add(pid) try: for children in Path(f'/proc/{pid}/task').glob('*/children'): try: pending.extend(map(int, children.read_text().split())) except OSError: pass cmd = Path(f'/proc/{pid}/cmdline').read_bytes().split(b'\0') if b'/app/qwen_native_worker.py' in cmd: result['qwen'] = (pid, cmd) elif cmd[0].endswith(b'/engine/strata'): result['strata'] = (pid, cmd) except (OSError, ValueError): pass return result def idle(): for _ in range(2): if endpoint()['active_requests']: raise RuntimeError('Live request active; thread change deferred') time.sleep(1) def save_plan(value): sys.path.insert(0, '/opt/athena-deck-dev/source') import cpu_partition cpu_partition.placement(value, cpu_partition.topology()) temp = plan_path.with_suffix('.threads.tmp') temp.write_text(json.dumps(value, indent=2) + '\n') temp.chmod(0o600) os.chown(temp, 65534, 65534) temp.replace(plan_path) def select(generation): assert generation in (2, 3, 4) idle() value = json.loads(plan_path.read_text()) assert value['qwen_codec_threads'] == 2 assert value['qwen_tts'] == [2, 3, 4, 5, 8, 9, 10, 11] assert value['shared_cpus'] == [2, 3, 8, 9] assert value['qwen_cpu_flash_attention'] is False policy = json.loads(plan_path.with_name('audio-policy.json').read_text()) assert policy['tts']['mode'] in ('auto', 'warm') found = workers() assert set(found) == {'qwen', 'strata'} and endpoint()['counts']['tts']['loaded'] old_pid, cmd = found['qwen'] strata_pid = found['strata'][0] backup = stage / 'thread-baseline.json' if not backup.exists(): assert value['qwen_generation_threads'] == 2 backup.write_text(json.dumps(value, indent=2) + '\n') backup.chmod(0o600) value['qwen_generation_threads'] = generation if int(cmd[-3]) != generation: idle() save_plan(value) # Only the identified, idle Qwen worker is terminated. Deck's existing # automatic residency loop loads the same profile with the new policy. os.kill(old_pid, signal.SIGTERM) until = time.monotonic() + 110 while time.monotonic() < until: now = workers() if now.get('strata', (None,))[0] != strata_pid: raise RuntimeError('Strata process changed unexpectedly') qwen = now.get('qwen') if qwen and int(qwen[1][-3]) == generation and endpoint()['counts']['tts']['loaded']: # Process registration precedes native loading; allow readiness. time.sleep(3) if workers().get('qwen', (None,))[0] != qwen[0]: continue result = dict(generation_threads=generation, codec_threads=2, qwen_pid=qwen[0], strata_pid=strata_pid, allowed_cpus=sorted(os.sched_getaffinity(qwen[0])), active_requests=endpoint()['active_requests']) print(json.dumps(result), flush=True) return time.sleep(1) raise RuntimeError('TTS did not reload within the bounded wait') if sys.argv[1] == 'select': select(int(sys.argv[2])) elif sys.argv[1] == 'status': found = workers() print(json.dumps(dict(endpoint=endpoint(), plan=json.loads(plan_path.read_text()), pids={k:v[0] for k,v in found.items()}, threads={k:[s.decode() for s in v[1][-3:-1]] for k,v in found.items() if k=='qwen'})), flush=True) elif sys.argv[1] == 'warm': idle() data = dict(model='qwen-06b-q4-anna-cpu', voice='default', response_format='pcm', input='Die Sprachausgabe ist bereit.') req = urllib.request.Request('http://127.0.0.1:8120/v1/audio/speech', data=json.dumps(data).encode(), headers=dict(headers, **{'Content-Type':'application/json'})) size = 0 with urllib.request.urlopen(req, timeout=60) as response: while True: block = response.read(16384) if not block: break size += len(block) assert 0 < size < 4*1024**2 and size%2 == 0 print(json.dumps(dict(warmup_audio_seconds=size/48000)), flush=True) elif sys.argv[1] == 'warm-llm': idle() data = dict(model='flash-next-strata-iq3-dual', messages=[dict(role='user', content='Antworte nur mit OK.')], max_tokens=1, reasoning_effort='none', temperature=0) req = urllib.request.Request('http://127.0.0.1:8120/v1/chat/completions', data=json.dumps(data).encode(), headers=dict(headers, **{'Content-Type':'application/json'})) start = time.monotonic() with urllib.request.urlopen(req, timeout=180) as response: result = json.load(response) print(json.dumps(dict(warmup_llm_seconds=time.monotonic()-start, completion_tokens=result.get('usage',{}).get('completion_tokens'))), flush=True) else: raise ValueError('Unknown action')