"""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']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 serving262144 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 capabilities(self,p): target=self.target(p);method=getattr(type(target),'capabilities',None) return method(target,p) if callable(method) else {} def answer_now(self,request): with self.lock:target=self.active if target is not self.basalt: from chat_control import ControlError raise ControlError('Der ursprüngliche Basalt-Worker ist nicht mehr aktiv.',409,'worker_changed') return target.answer_now(request) 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()