Files
Athena-Deck/basalt_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

111 lines
8.3 KiB
Python

"""Deck-owned Basalt loopback worker; only selected GPU and own process group."""
import json
import os
from pathlib import Path
import secrets
import socket
import subprocess
import time
import urllib.request
from typing import Any
import cpu_partition
from basalt_runtime import validate_model,validate_projector
from image_test import probe
from inference import InferenceError,MemoryAdmissionError
from strata_worker import StrataWorker
def compute_capabilities():
result=subprocess.run(['nvidia-smi','--query-gpu=uuid,compute_cap','--format=csv,noheader'],capture_output=True,text=True,check=True,timeout=5)
return {uuid.strip():cap.strip() for uuid,cap in (line.split(',') for line in result.stdout.splitlines())}
class BasaltWorker(StrataWorker):
# Reuse only owned-process lifecycle/connect/stop and initialization, not Strata
# model planning, command-line generation or its model preparation recipe.
def blockers(self,p):
try:
if not self.runtime.status()['installed']:raise ValueError('Basalt-Laufzeit fehlt. Unter Laufzeiten → Basalt installieren.')
self.runtime.prepared(self.catalog.entry(p['model_id']))
if p['parameters'].get('vision_projector'):
validate_projector(self.catalog.entry(p['parameters']['vision_projector']))
if not self.runtime.status().get('vision'):raise ValueError('Basalt-Vision-Sidecar für SM86/SM120 fehlt.')
return []
except ValueError as exc:return [str(exc)]
def status(self):
with self.lock:
if self.process and self.process.poll() is not None:self.state='failed';self.error='Basalt-Prozess beendet. Eigenes Worker-Protokoll prüfen; OOM nicht ohne Nachweis behaupten.'
return dict(runtime='basalt',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'];ids=params['gpu_devices']
if len(ids)!=1:raise InferenceError('Basalt benötigt genau eine explizite SM120-GPU.')
devices=probe();selected:Any=next((g for g in devices if g['uuid']==ids[0]),None)
if not selected or compute_capabilities().get(ids[0])!='12.0':raise InferenceError('Ausgewählte GPU ist nicht als SM120 verfügbar. RTX 3060 wird nicht unterstützt.')
reserve=params['gpu_reserve_mib'].get(ids[0],700) if params['gpu_reserve_mode']=='manual' else 700
if type(selected.get('processes')) is not int:raise InferenceError('GPU-Prozessbelegung unbekannt; Basalt wird nicht gestartet.')
if selected['processes']>0 or selected['free_mib']<selected['total_mib']-reserve-512:raise MemoryAdmissionError('Basalt benötigt die ausgewählte GPU weitgehend frei. Fremde Prozesse werden nicht beendet.')
self.memory_plan:dict[str,Any]=dict(runtime='basalt',context=params['context'],slots=params.get('slots',1),context_scope='per_slot',total_context_capacity=params['context']*params.get('slots',1),gpus=ids,reserve_mib=[reserve],experts='resident',kv='int8',kv_elastic=True,mtp='model-pack-default')
if params.get('vision_projector'):
vision=params['vision_device'];card=next((i for i,g in enumerate(devices) if g['uuid']==vision),None)
if vision in ids or card is None or compute_capabilities().get(vision) not in ('8.6','12.0'):raise InferenceError('Basalt-Vision benötigt eine separate verfügbare SM86/SM120-GPU.')
gpu:Any=devices[card]
if type(gpu.get('processes')) is not int:raise InferenceError('Vision-GPU-Belegung unbekannt.')
if gpu['processes'] or gpu['free_mib']<4096:raise MemoryAdmissionError('Vision-GPU benötigt mindestens 4096 MiB frei und keine fremden Compute-Prozesse.')
self.memory_plan.update(vision_gpu=vision,vision_index=card)
return self.memory_plan
@staticmethod
def configuration(p,model,port,reserve,vision_index=None):
params=p['parameters']
if params.get('vision_projector') and type(vision_index) is not int:raise InferenceError('Vision-GPU-Index fehlt; kein stiller CPU-/GPU-Fallback.')
return dict(server=dict(model=str(model),alias=p['api_id'],host='127.0.0.1',port=port,gpu='0',parallel=params.get('slots',1),**{'slot-full-context':True,'vision':str(vision_index) if params.get('vision_projector') else 'off'}),engine={'max-context':params['context'],'kv':'int8','expert-cache':'auto','prefill':'auto','resident-experts':True,'vram-reserve-mib':reserve})
@staticmethod
def server_command(python,source,config,key):
# Upstream accepts API credentials only on CLI, never in a config file.
return [str(python),str(Path(__file__).with_name('basalt_serve.py')),'--deck-source',str(source),'--engine-bin',str(source/'bin/basalt'),'--config',str(config),'--api-key',key]
@staticmethod
def verify_properties(props,params):
if props.get('is_sleeping') is not False or props.get('total_slots')!=params.get('slots',1) or (props.get('default_generation_settings') or {}).get('n_ctx')!=params['context']:
raise InferenceError('Basalt hat geladenes Modell, parallele Slots und Kontext pro Slot nicht bestätigt.')
if params.get('vision_projector') and not (props.get('modalities') or {}).get('vision'):raise InferenceError('Basalt hat den Vision-Encoder nicht bestätigt.')
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.phase='Basalt-Modell laden';self.error=None;self.cpu_layout=layout
params=p['parameters'];entry=self.catalog.entry(p['model_id']);validate_model(entry);model=self.runtime.prepared(entry);python,source=self.runtime.paths()
self.root.mkdir(parents=True,exist_ok=True,mode=0o700)
with socket.socket() as sock:sock.bind(('127.0.0.1',0));self.port=sock.getsockname()[1]
self.key=secrets.token_urlsafe(32);self.devices=list(params['gpu_devices'])
path=self.root/'worker.json';path.write_text(json.dumps(self.configuration(p,model,self.port,self.memory_plan['reserve_mib'][0],self.memory_plan.get('vision_index'))));path.chmod(0o600)
for folder in ('home','tmp','cache','cache/cuda'):(self.root/folder).mkdir(parents=True,exist_ok=True,mode=0o700)
env=dict(os.environ,CUDA_VISIBLE_DEVICES=','.join(self.devices),HOME=str(self.root/'home'),TMPDIR=str(self.root/'tmp'),XDG_CACHE_HOME=str(self.root/'cache'),CUDA_CACHE_PATH=str(self.root/'cache/cuda'),PYTHONUNBUFFERED='1',OMP_NUM_THREADS='1',OPENBLAS_NUM_THREADS='1')
libs=self.runtime.root/'cuda';env['LD_LIBRARY_PATH']=str(libs/'lib64')+os.pathsep+str(libs/'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.server_command(python,source,path,self.key),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('Basalt-Start abgebrochen.')
if self.process is None or self.process.poll() is not None:raise InferenceError('Basalt-Start fehlgeschlagen. Eigenes Worker-Protokoll prüfen.')
try:
req=urllib.request.Request('http://127.0.0.1:'+str(self.port)+'/props',headers={'Authorization':'Bearer '+self.key})
with urllib.request.urlopen(req,timeout=3) as response:props=json.load(response)
if props.get('is_sleeping') is False:
self.verify_properties(props,params)
with self.lock:self.state='ready';self.phase='Basalt bereit'
return
except InferenceError:raise
except (OSError,ValueError):pass
time.sleep(1)
raise InferenceError('Basalt-Startzeitlimit überschritten.')
except Exception as exc:self.stop();self.state='failed';self.error=str(exc);self.phase='Basalt-Start fehlgeschlagen';raise
def prepare_request(self,body):
body=dict(body)
# Deck accepts stable profile aliases; upstream accepts only its launch alias.
# Apply this for both the public endpoint and Deck's own test chat.
if self.profile:body['model']=self.profile['api_id']
if 'repeat_penalty' in body:body['repetition_penalty']=body.pop('repeat_penalty')
body.pop('cache_prompt',None)
return body