Files
Athena-Deck/strata_worker.py
T
Mikei386 c0bc5d3a1b Integrate Basalt telemetry and shared GPU speech runtimes
Publish the reviewed accumulated runtime, scheduler, profile, UI, native recipes and historical maintenance evidence. Includes Qwen GPU ASR correction and shared Anna/atelier ownership. Validated with 784 local tests, Python/JSON parsing and eight JavaScript syntax checks. Live GPU acceptance and full fresh-host restore limits remain documented.
2026-11-03 21:16:41 +01:00

163 lines
12 KiB
Python

"""Deck-owned loopback worker using the unmodified official Strata server."""
import http.client,json,os,secrets,signal,socket,subprocess,threading,time,urllib.request
from pathlib import Path
from image_test import probe
from inference import InferenceError,MemoryAdmissionError
from strata_runtime import RECIPE
import cpu_partition
def performance_tuning(quant,devices,parameters,cpu=None):
"""Apply measured tuning only to the qualified hardware and layer layout."""
tuning=RECIPE.get("performance",{}).get(quant,{})
if not tuning or parameters.get("strata_experts")!=tuning.get("experts","resident") or [g.get("name") for g in devices]!=tuning.get("gpu_names") or parameters["strata_layer_split"]!=tuning.get("layer_split") or parameters.get("context",8192)>tuning.get("max_context",131072):return {}
if cpu is None:
try:cpu=Path("/proc/cpuinfo").read_text()
except OSError:return {}
if not tuning.get("cpu_model") or tuning["cpu_model"] not in cpu:return {}
return tuning
class StrataWorker:
def __init__(self,root,catalog,runtime):
self.root=Path(root);self.catalog=catalog;self.runtime=runtime;self.lock=threading.RLock();self.process=None;self.profile=None;self.port=None;self.key=None;self.devices=[];self.state='stopped';self.error=None;self.phase='Gestoppt';self.memory_plan=None;self.cpu_layout=None
def blockers(self,p):
try:
if not self.runtime.status()['installed']:raise ValueError('Strata-Laufzeit fehlt. Unter Laufzeiten → Strata installieren.')
_,m=self.runtime.prepared(self.catalog.entry(p['model_id']))
if p['parameters'].get('vision_projector'):self.runtime.vision_config(p['parameters']['vision_projector'],self.runtime.storage/m['native'])
return []
except ValueError as e:return [str(e)]
def status(self):
with self.lock:
if self.process and self.process.poll() is not None:self.state='failed';self.error='Strata-Modellprozess beendet. Speicher und eigenes Worker-Protokoll prüfen.'
return dict(runtime='strata',state=self.state,profile_id=self.profile['id'] if self.profile else None,profile_name=self.profile['name'] if self.profile else None,port=self.port,error=self.error,gpus=self.devices,memory_plan=self.memory_plan,phase=self.phase,cpu_allowed=self.cpu_layout['strata'] if self.cpu_layout else None)
def plan(self,p,cancel=lambda:False):
errors=self.blockers(p)
if errors:raise InferenceError('; '.join(errors))
params=p['parameters'];gpus=probe();ids=params['gpu_devices']
if len(ids)!=2:raise InferenceError('Dieses Strata-Rezept benötigt zwei explizit ausgewählte GPUs. Erste GPU: Anfangslayer; zweite GPU: restliche Layer und MTP/Ausgabekopf.')
selected=[next((g for g in gpus if g['uuid']==i),None) for i in ids]
if any(g is None for g in selected):raise InferenceError('Eine ausgewählte Strata-GPU ist nicht verfügbar.')
q,_=self.runtime.prepared(self.catalog.entry(p['model_id']));tuning=performance_tuning(q,selected,params)
reserve=[params['gpu_reserve_mib'].get(i,768) if params['gpu_reserve_mode']=='manual' else 768 for i in ids]
if params['gpu_reserve_mode']=='auto' and tuning:reserve=[tuning['auto_reserve_mib']]*len(ids)
if any(g['free_mib']<g['total_mib']-r-1024 for g,r in zip(selected,reserve)):raise MemoryAdmissionError('Strata benötigt beide GPUs weitgehend frei. Fremde Prozesse werden nicht beendet; Deck kann seinen eigenen TTS-Worker entladen.')
self.memory_plan=dict(runtime='strata',context=params['context'],slots=params.get('slots',1),context_scope='per_slot',total_context_capacity=params['context']*params.get('slots',1),layer_split=params['strata_layer_split'],gpus=ids,reserve_mib=reserve,experts=params['strata_experts'],kv='int8',kv_resident=32768,tail_skip=int(tuning.get('environment',{}).get('STRATA_ROUTE_TAIL_SKIP','0')),performance=tuning)
return self.memory_plan
def ensure(self,p,cancel=lambda:False):
with self.lock:
layout=cpu_partition.load(self.root.parent)
if self.process and self.process.poll() is None and self.profile and (p['id'],p['revision'])==(self.profile['id'],self.profile['revision']) and layout==self.cpu_layout:return
self.stop();self.plan(p,cancel);self.state='loading';self.error=None;self.phase='Strata-Modell laden'
self.cpu_layout=layout
params=p['parameters'];entry=self.catalog.entry(p['model_id']);q,m=self.runtime.prepared(entry);python,source=self.runtime.paths();data=self.runtime.storage
self.root.mkdir(parents=True,exist_ok=True,mode=0o700)
with socket.socket() as s:s.bind(('127.0.0.1',0));self.port=s.getsockname()[1]
self.key=secrets.token_urlsafe(32);self.devices=params['gpu_devices']
args=['--pack',str(data/m['pack']),'--native',str(data/m['native']),'--ple-gguf',str(data/m['ple']),'--expert-profile',str(source/'data/expert-profile.bin'),'--expert-cache','auto','--prefill','auto','--spec','4','--spec-min-p','0.5','--mtp',str(data/'mtp/rt'),'--max-context',str(params['context']),'--kv','int8','--kv-resident','32768','--vram-reserve-mib',str(self.memory_plan['reserve_mib'][0]),'--vram-reserve-later-mib',str(self.memory_plan['reserve_mib'][1])]
args += self.context_arguments(params['context'])
args += self.parallel_arguments(params.get('slots',1),params.get('strata_batch_groups','1'),params.get('strata_batch_mtp',True))
tuning=self.memory_plan.get('performance',{})
for flag,value in tuning.get('arguments',{}).items():
if flag in args:
i=args.index(flag);del args[i:i+2]
args += [flag,str(value)]
if layout:args+=layout['strata_arguments']
if params['strata_experts']=='resident':args.append('--resident-experts')
else:args.append('--mmap-experts')
config=dict(exe=str(source/'engine/strata'),args=args,cwd=str(source),tokenizer=str(data/m['pack']/'tokenizer'),model_name=p['api_id'],host='127.0.0.1',port=self.port,api_key=self.key,gpu=[i for uuid in self.devices for i,g in enumerate(probe()) if g['uuid']==uuid],gpu_order='as_given',layer_split=str(params['strata_layer_split']),vram_elastic=False,open_browser=False,log=str(self.root/'engine.log'))
config['parallel']=params.get('slots',1)
config.update(self.reasoning_guard_config())
if params.get('vision_projector'):
config['vision']=self.runtime.vision_config(params['vision_projector'],data/m['native']);args.append('--vision')
path=self.root/'worker.json'
env=dict(os.environ,CUDA_VISIBLE_DEVICES=','.join(self.devices),STRATA_ROUTE_TAIL_SKIP='0',STRATA_RESIDENT_HEADROOM_GIB='6',PYTHONUNBUFFERED='1')
env.update(tuning.get('environment',{}));config['env']={k:env[k] for k in ('STRATA_ROUTE_TAIL_SKIP','STRATA_RESIDENT_HEADROOM_GIB')};config['env'].update(tuning.get('environment',{}));path.write_text(json.dumps(config));path.chmod(0o600)
# CUDA 13 libraries may be deployed beside the native runtime in the current
# container. Native installs use their configured toolkit, never a Docker API.
libs=self.runtime.root/'cuda/lib64'
if libs.is_dir() or (self.runtime.root/'cuda/lib').is_dir():env['LD_LIBRARY_PATH']=str(libs)+os.pathsep+str(self.runtime.root/'cuda/lib')+os.pathsep+env.get('LD_LIBRARY_PATH','')
self.profile=p
with (self.root/'server.log').open('w') as output:self.process=subprocess.Popen(cpu_partition.command(self.command(python,source,path,self.port),layout['strata'] if layout else None),cwd=source,env=env,stdout=output,stderr=subprocess.STDOUT,start_new_session=True)
try:
deadline=time.monotonic()+600
while time.monotonic()<deadline:
if cancel():raise InferenceError('Strata-Start abgebrochen.')
if self.process is None or self.process.poll() is not None:raise InferenceError('Strata-Start fehlgeschlagen. Eigenes Strata-Worker-Protokoll prüfen; OOM ist ohne Nachweis nicht bestätigt.')
try:
req=urllib.request.Request('http://127.0.0.1:'+str(self.port)+'/health',headers={'Authorization':'Bearer '+self.key})
with urllib.request.urlopen(req,timeout=3) as r:health=json.load(r)
if health.get('status')=='ok' and health.get('loaded',True):
if params.get('slots',1)>1:
req=urllib.request.Request('http://127.0.0.1:'+str(self.port)+'/v1/status',headers={'Authorization':'Bearer '+self.key})
with urllib.request.urlopen(req,timeout=3) as r:self.verify_capacity(json.load(r),params['slots'])
with self.lock:self.state='ready';self.phase='Strata bereit'
return
except InferenceError:raise
except (OSError,ValueError):pass
time.sleep(1)
raise InferenceError('Strata-Startzeitlimit überschritten.')
except Exception as e:
self.stop();self.state='failed';self.error=str(e);self.phase='Strata-Start fehlgeschlagen';raise
@staticmethod
def reasoning_guard_config():
mode=RECIPE.get('reasoning_loop_recovery',False)
if mode is not False and mode not in ('stop','recover'):raise ValueError('Ungültiger Strata-Schleifenschutz im Laufzeitrezept.')
return {'reasoning_loop_recovery':mode}
@staticmethod
def parallel_arguments(slots,batch_groups='1',batch_mtp=True):
# Missing fields preserve legacy behavior; solo MTP is independent.
return (['--batch-mtp'] if batch_mtp else [])+['--batch-groups',batch_groups] if slots==2 else []
@staticmethod
def verify_capacity(status,slots):
serving=(status.get('concurrency') or {}).get('serving')
if type(serving) is not int or serving<slots:raise InferenceError('Strata hat die angeforderten parallelen Slots nicht bestätigt. Dual-Slot-Profil nicht gestartet; Speicherbelegung prüfen.')
@staticmethod
def context_arguments(context):
# Native window stays unchanged; qualified extended window uses the tested YaRN factor.
return ['--rope-scaling','yarn','--rope-scale','2'] if context>262144 else []
@staticmethod
def command(python,source,config,port):return [str(python),str(source/'serve/server.py'),'--engine','strata','--config',str(config),'--host','127.0.0.1','--port',str(port),'--fit-max-tokens']
def connect(self):return http.client.HTTPConnection('127.0.0.1',self.port,timeout=120),self.key
def prepare_request(self,body):
body=dict(body);options=body.pop('chat_template_kwargs',{})
# Keep the official native helper-thread placement active while partitioned.
# A request's aux_cpus=0 would otherwise undo it (including checkpoint threads).
if self.cpu_layout:body['strata_tune']={**body.get('strata_tune',{}),'aux_cpus':1}
if options.get('enable_thinking') is False:body['reasoning_effort']='none'
elif 'reasoning_effort' not in body:body['reasoning_effort']='high'
if body.get('reasoning_effort')=='xhigh':body['reasoning_effort']='high'
body.pop('cache_prompt',None);return body
def stop(self):
with self.lock:
p=self.process
if p and p.poll() is None:
try:
os.killpg(p.pid,signal.SIGTERM)
try:p.wait(15)
except subprocess.TimeoutExpired:os.killpg(p.pid,signal.SIGKILL);p.wait(5)
except ProcessLookupError:pass
self.process=None;self.profile=None;self.port=None;self.key=None;self.devices=[];self.state='stopped';self.phase='Gestoppt';(self.root/'worker.json').unlink(missing_ok=True)
class ChatWorkerRouter:
"""Keep the scheduler and public API shared; embeddings always use llama.cpp."""
def __init__(self,llama,strata,basalt=None):self.llama=llama;self.strata=strata;self.basalt=basalt;self.active=llama;self.runtime=llama.runtime;self.catalog=llama.catalog;self.root=llama.root;self.lock=threading.RLock()
def __getattr__(self,name):return getattr(self.active,name)
def build(self):return self.llama.build()
def target(self,p):
mode=p['parameters'].get('chat_runtime','llama')
if mode=='basalt':
if self.basalt is None:raise InferenceError('Basalt-Worker ist nicht eingerichtet.')
return self.basalt
return self.strata if mode=='strata' else self.llama
def blockers(self,p):return self.target(p).blockers(p)
def plan(self,p,cancel=lambda:False):return self.target(p).plan(p,cancel)
def ensure(self,p,cancel=lambda:False):
with self.lock:
target=self.target(p)
if target is not self.active:self.active.stop();self.active=target
return target.ensure(p,cancel)
def prepare_request(self,body):return self.active.prepare_request(body) if self.active is self.strata or self.basalt is not None and self.active is self.basalt else body
def status(self):return {**self.active.status(),'runtime':'basalt' if self.basalt is not None and self.active is self.basalt else 'strata' if self.active is self.strata else 'llama'}
def stop(self):
with self.lock:
self.llama.stop();self.strata.stop()
if self.basalt is not None:self.basalt.stop()