101 lines
7.9 KiB
Python
101 lines
7.9 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
|
|
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
|
|
def blockers(self,p):
|
|
try:
|
|
if not self.runtime.status()['installed']:raise ValueError('Strata-Laufzeit fehlt. Unter Laufzeiten → Strata installieren.')
|
|
self.runtime.prepared(self.catalog.entry(p['model_id']));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)
|
|
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.')
|
|
reserve=[params['gpu_reserve_mib'].get(i,768) if params['gpu_reserve_mode']=='manual' else 768 for i in 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'],layer_split=params['strata_layer_split'],gpus=ids,reserve_mib=reserve,experts=params['strata_experts'],kv='int8',kv_resident=32768,tail_skip=0)
|
|
return self.memory_plan
|
|
def ensure(self,p,cancel=lambda:False):
|
|
with self.lock:
|
|
if self.process and self.process.poll() is None and self.profile and (p['id'],p['revision'])==(self.profile['id'],self.profile['revision']):return
|
|
self.stop();self.plan(p,cancel);self.state='loading';self.error=None;self.phase='Strata-Modell laden'
|
|
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])]
|
|
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'))
|
|
path=self.root/'worker.json';path.write_text(json.dumps(config));path.chmod(0o600)
|
|
env=dict(os.environ,CUDA_VISIBLE_DEVICES=','.join(self.devices),STRATA_ROUTE_TAIL_SKIP='0',STRATA_RESIDENT_HEADROOM_GIB='6',PYTHONUNBUFFERED='1')
|
|
# 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(self.command(python,source,path,self.port),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):
|
|
with self.lock:self.state='ready';self.phase='Strata bereit'
|
|
return
|
|
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 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)]
|
|
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',{})
|
|
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):self.llama=llama;self.strata=strata;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):return self.strata if p['parameters'].get('chat_runtime','llama')=='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 else body
|
|
def status(self):return {**self.active.status(),'runtime':'strata' if self.active is self.strata else 'llama'}
|
|
def stop(self):
|
|
with self.lock:self.llama.stop();self.strata.stop()
|