okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221apps/host: the owner's UI and the Node App Host0b3299a01

main
12.2 KiB151 linesraw
1/** Independent model identities for the design host. Native engines remain capability gated. */
2import { randomUUID } from 'node:crypto';
3import { RequestQueue } from './request-queue.mjs';
4const deviceId = gpu => gpu.id ?? `${gpu.vendor}:${gpu.index}`;
5const active = r => ['queued','generating'].includes(r.state);
6
7export function modelReservation(model, config, hardware, gpuIds, checkCapacity=true) {
8  const expert = Object.fromEntries((config.expert ?? []).map(p => [p.id,p.value]));
9  const label = config.beginner?.contextLength === 'recommended' ? '128k' : config.beginner?.contextLength;
10  const context = Number.parseInt(label ?? '128k') * 1024;
11  if (!Number.isFinite(context) || context < 4096 || checkCapacity && context > model.contextMax) throw new Error('Choose a supported conversation context.');
12  const chosen = hardware.gpus.filter(g => gpuIds.includes(deviceId(g)));
13  const reserve = config.extra?.headroom === 'full' ? Math.max(2,hardware.memory.totalGb*.125) : Math.max(4,hardware.memory.totalGb*.25);
14  const cache = (model.kvKbPerToken ?? 24) * context / 1024**2 * (expert['ctx.kvMode']==='FP16'?2:expert['ctx.kvMode']==='Q4_0'?.5:1) * Math.max(1,Number(expert['server.parallel'] ?? 1));
15  const fixed = cache + (model.experts>0?2.5:1.2);
16  const weights = model.diskGb;
17  // Equal placement is a planning assumption, never a claim about engine allocation.
18  const dedicated = chosen.filter(g=>!g.unified);
19  const gpuBudget = dedicated.reduce((n,g)=>n+Math.max(0,g.vramGb-1),0);
20  const gpu = Math.min(weights+fixed,gpuBudget);
21  const ramBudget = Math.max(0,hardware.memory.totalGb-reserve);
22  const ram = Math.min(ramBudget,Math.max(0,weights+fixed-gpu));
23  const spill = Math.max(0,weights+fixed-gpu-ram);
24  if (checkCapacity && (spill>weights || (expert['mem.mmap']===false || expert['mem.lock']===true) && spill>0)) throw new Error('This setup cannot fit its context and runtime in available memory. Reduce context or use a smaller version.');
25  return { minimumRamGb:Math.max(0,fixed-gpu), pageable:expert['mem.mmap']!==false && expert['mem.lock']!==true, context, ramGb:ram, gpuGb:gpu, spillGb:spill, reserveGb:reserve, totalGb:weights+fixed, devices:dedicated.map(g=>({id:deviceId(g),gb:gpu/dedicated.length})) };
26}
27
28/** RAM is one host pool. Dedicated VRAM is checked separately on each selected GPU. */
29export function rebalanceReservations(instances, hardware) {
30  const rows=structuredClone(instances);
31  const reserve=Math.min(hardware.memory.totalGb,Math.max(0,...rows.map(i=>i.memory.reserveGb)));
32  const budget=Math.max(0,hardware.memory.totalGb-reserve);
33  let excess=Math.max(0,rows.reduce((n,i)=>n+i.memory.ramGb,0)-budget);
34  const flexible=rows.filter(i=>i.memory.pageable);
35  const spare=flexible.reduce((n,i)=>n+Math.max(0,i.memory.ramGb-i.memory.minimumRamGb),0);
36  if(excess>spare+.01)return null;
37  for(const row of flexible){const reduction=spare?excess*Math.max(0,row.memory.ramGb-row.memory.minimumRamGb)/spare:0;row.memory.ramGb-=reduction;row.memory.spillGb+=reduction;}
38  return rows;
39}
40
41export function reservationBudget(instances, hardware) {
42  const reserveGb = Math.min(hardware.memory.totalGb,Math.max(0,...instances.map(i=>i.memory.reserveGb)));
43  const ramGb = instances.reduce((n,i)=>n+i.memory.ramGb,0);
44  const devices = hardware.gpus.filter(g=>!g.unified).map(g=>({id:deviceId(g),name:g.name,usedGb:instances.reduce((n,i)=>n+(i.memory.devices.find(d=>d.id===deviceId(g))?.gb??0),0),budgetGb:Math.max(0,g.vramGb-1)}));
45  return { ramGb, budgetGb:Math.max(0,hardware.memory.totalGb-reserveGb), reserveGb, totalGb:hardware.memory.totalGb, devices, fits:ramGb<=hardware.memory.totalGb-reserveGb+.01 && devices.every(d=>d.usedGb<=d.budgetGb+.01) };
46}
47
48export function createRuntimeModels({hardware, library, requests=()=>[], changed=()=>{}, real=false}) {
49  const records = new Map(), queues = new Map();
50  let defaultId = null, revision = 0;
51  const publish = () => { revision++; changed(state()); };
52  function devices(ids) {
53    if (!Array.isArray(ids) || new Set(ids).size!==ids.length || ids.some(id=>!hardware().gpus.some(g=>deviceId(g)===id))) throw new Error('Choose detected GPUs, or CPU only.');
54    return hardware().gpus.filter(g=>ids.includes(deviceId(g))).map(deviceId);
55  }
56  function prepare(body) {
57    const model = library().variants.find(v=>v.id===body.variantId);
58    if (!model) throw new Error('This model version is unavailable.');
59    const gpuIds = devices(body.gpuIds);
60    const config = structuredClone(body.config);
61    if (!config?.beginner || !Array.isArray(config.expert)) throw new Error('A validated engine configuration is required.');
62    if (gpuIds.length===0) {
63      const layers=config.expert.find(p=>p.id==='gpu.layers');
64      if(layers)layers.value='CPU only'; else config.expert.push({id:'gpu.layers',value:'CPU only'});
65    } else if(config.expert.find(p=>p.id==='gpu.layers')?.value==='CPU only') throw new Error('Choose CPU only as the execution device, or enable GPU layers.');
66    if(!real && gpuIds.length && !['Automatic','All layers',undefined].includes(config.expert.find(p=>p.id==='gpu.layers')?.value))throw new Error('Partial GPU layer placement needs a verified allocation plan. Choose Automatic, All layers, or CPU only.');
67    const memory = modelReservation(model,config,hardware(),gpuIds,!real);
68    return {variantId:model.id,family:model.family,name:model.name,quant:model.quant,gpuIds,config,memory};
69  }
70  function state() {
71    const entries=[...records.values()].map(i=>{
72      const log=requests().filter(r=>r.instanceId===i.id);
73      return {...structuredClone(i),active:log.filter(r=>r.state==='generating').length,queued:log.filter(r=>r.state==='queued').length};
74    });
75    return {revision,mode:real?'real':'simulated',capabilities:{multipleModels:!real,deviceAssignment:!real},defaultId,instances:entries,memory:reservationBudget(entries,hardware())};
76  }
77  function add(prepared, apiModelId) {
78    const id=randomUUID();
79    const instance={...prepared,id,apiModelId,loadedAt:new Date().toISOString(),status:'ready',phase:'idle',prompt:{done:0,total:0,pct:0},outputTps:0,promptTps:0,context:{usedTokens:0,maxTokens:prepared.memory.context,pct:0}};
80    records.set(id,instance);
81    queues.set(id,new RequestQueue(()=>publish()));
82    if(!defaultId)defaultId=id;
83    return instance;
84  }
85  function adopt(variantId,config) {
86    if (!variantId) { if(real){records.clear();queues.clear();defaultId=null;} return; }
87    const existing=[...records.values()].find(i=>i.variantId===variantId);
88    if(real) { for(const i of records.values())if(i.variantId!==variantId){records.delete(i.id);queues.delete(i.id);} }
89    if(existing){if(real)try{const prepared=prepare({variantId,config,gpuIds:config.expert?.find(p=>p.id==='gpu.layers')?.value==='CPU only'?[]:hardware().gpus.map(deviceId)});Object.assign(existing,prepared,{context:{...existing.context,maxTokens:prepared.memory.context}});}catch{}defaultId=existing.id;return;}
90    const model=library().variants.find(v=>v.id===variantId);if(!model)return;
91    const ids=real&&config.expert?.find(p=>p.id==='gpu.layers')?.value==='CPU only'?[]:hardware().gpus.map(deviceId);
92    try { const prepared=prepare({variantId,config,gpuIds:ids});const row=add(prepared,variantId);defaultId=row.id; }
93    catch { /* A legacy configuration may be invalid; never fabricate a ready instance. */ }
94  }
95  function executionMode(body) {
96    const mode=body.executionMode??'single';
97    if(!['single','multiple'].includes(mode))throw new Error('Choose single or multiple model execution.');
98    return mode;
99  }
100  function samePlacement(prepared) {
101    return [...records.values()].find(i=>i.variantId===prepared.variantId && JSON.stringify(i.gpuIds)===JSON.stringify(prepared.gpuIds));
102  }
103  function plan(body) {
104    const mode=executionMode(body),prepared=prepare(body),matching=samePlacement(prepared);
105    const identical=matching && JSON.stringify(matching.config)===JSON.stringify(prepared.config);
106    const siblings=mode==='multiple'?[...records.values()].filter(i=>i.id!==matching?.id):[];
107    const planned=rebalanceReservations([...siblings,prepared],hardware());
108    const budget=reservationBudget(planned??[...siblings,prepared],hardware());
109    const candidate=planned?.at(-1)??prepared;
110    return {memory:candidate.memory,budget,allowed:!!planned&&budget.fits,alreadyLoaded:!!identical,reloads:!!matching,executionMode:mode};
111  }
112  function load(body) {
113    if(real)throw new Error('Multiple native engines and GPU assignment are not supported by this host yet.');
114    const mode=executionMode(body),prepared=prepare(body),matching=samePlacement(prepared);
115    const model=library().variants.find(v=>v.id===prepared.variantId);
116    if(!model.installedAt && !['loaded','installed'].includes(model.state))throw new Error('Download this model version before loading.');
117    const identical=matching && JSON.stringify(matching.config)===JSON.stringify(prepared.config);
118    if(identical && (mode==='multiple'||records.size===1))return {state:state(),instance:structuredClone(matching)};
119    const affected=mode==='single'?[...records.values()]:matching?[matching]:[];
120    if(affected.some(i=>requests().some(r=>r.instanceId===i.id&&active(r))))throw new Error(mode==='single'?'Finish or cancel model requests before switching models.':'Finish or cancel this model’s requests before reloading it.');
121    if(mode==='multiple'&&!matching&&records.size>=8)throw new Error('Unload a model before adding another. This preview supports eight instances.');
122    const siblings=mode==='multiple'?[...records.values()].filter(i=>i.id!==matching?.id):[];
123    const planned=rebalanceReservations([...siblings,prepared],hardware());
124    if(!planned || !reservationBudget(planned,hardware()).fits)throw new Error(mode==='single'?'This model cannot fit its context and runtime in available memory. Reduce context or use a smaller version.':'Other loaded models have reserved this memory. Unload one, choose another GPU, or reduce context.');
125    // Validation and all request/memory checks precede the switch. Failed loads keep the current model.
126    if(mode==='single')for(const row of records.values())if(row.id!==matching?.id){records.delete(row.id);queues.delete(row.id);}
127    let suffix=1,apiModelId=matching?.apiModelId??prepared.variantId;
128    while(!matching&&[...records.values()].some(i=>i.apiModelId===apiModelId))apiModelId=`${prepared.variantId}--${++suffix}`;
129    for(const row of planned.slice(0,-1))records.get(row.id).memory=row.memory;
130    prepared.memory=planned.at(-1).memory;
131    const instance=matching?Object.assign(matching,prepared,{loadedAt:new Date().toISOString(),phase:'idle',prompt:{done:0,total:0,pct:0},outputTps:0,promptTps:0,context:{usedTokens:0,maxTokens:prepared.memory.context,pct:0}}):add(prepared,apiModelId);
132    if(mode==='single')defaultId=instance.id;
133    publish();return {state:state(),instance:structuredClone(instance)};
134  }
135  function resolve(modelId,{chatDefault=false}={}) {
136    if(modelId!==undefined && typeof modelId!=='string')throw new Error('Use a model ID from /v1/models.');
137    if(modelId){const row=[...records.values()].find(i=>i.apiModelId===modelId);if(!row)throw new Error('That model ID is not loaded. Choose one from /v1/models.');return row;}
138    if(!records.size)throw new Error('No model is loaded.');
139    if(!chatDefault && records.size>1)throw new Error('Choose a model ID in your request when multiple models are loaded.');
140    return records.get(defaultId);
141  }
142  function unload(id) {
143    if(!records.has(id))throw new Error('This model is no longer loaded.');
144    if(requests().some(r=>r.instanceId===id && active(r)))throw new Error('Finish or cancel this model’s requests before unloading it.');
145    records.delete(id);queues.delete(id);if(defaultId===id)defaultId=records.keys().next().value??null;publish();return state();
146  }
147  function setDefault(id) {if(!records.has(id))throw new Error('This model is no longer loaded.');defaultId=id;publish();return state();}
148  function update(id,patch) {const row=records.get(id);if(row){Object.assign(row,patch);publish();}}
149  function libraryState(value) {const ids=new Set([...records.values()].map(i=>i.variantId));return {...value,loaded:records.get(defaultId)?.variantId??value.loaded,variants:value.variants.map(v=>ids.has(v.id)?{...v,state:'loaded'}:v)};}
150  return {state,prepare,plan,adopt,load,resolve,unload,setDefault,update,libraryState,queue:id=>queues.get(id),hasVariant:id=>[...records.values()].some(i=>i.variantId===id)};
151}