okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0b3299a01
main
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 ) { 8const expert = Object . fromEntries (( config . expert ?? []). map ( p => [ p . id , p . value ])); 9const label = config . beginner ?. contextLength === 'recommended' ?'128k' :config . beginner ?. contextLength ; 10const context = Number . parseInt ( label ?? '128k' ) * 1024 ; 11if ( ! Number . isFinite ( context ) || context < 4096 || checkCapacity && context > model . contextMax ) throw new Error ( 'Choose a supported conversation context.' ); 12const chosen = hardware . gpus . filter ( g => gpuIds . includes ( deviceId ( g ))); 13const reserve = config . extra ?. headroom === 'full' ?Math . max ( 2 , hardware . memory . totalGb * .125 ) :Math . max ( 4 , hardware . memory . totalGb * .25 ); 14const 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 )); 15const fixed = cache + ( model . experts > 0 ?2.5 :1.2 ); 16const weights = model . diskGb ; 17// Equal placement is a planning assumption, never a claim about engine allocation. 18const dedicated = chosen . filter ( g =>! g . unified ); 19const gpuBudget = dedicated . reduce (( n , g ) => n + Math . max ( 0 , g . vramGb - 1 ), 0 ); 20const gpu = Math . min ( weights + fixed , gpuBudget ); 21const ramBudget = Math . max ( 0 , hardware . memory . totalGb - reserve ); 22const ram = Math . min ( ramBudget , Math . max ( 0 , weights + fixed - gpu )); 23const spill = Math . max ( 0 , weights + fixed - gpu - ram ); 24if ( 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.' ); 25return { 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 ) { 30const rows = structuredClone ( instances ); 31const reserve = Math . min ( hardware . memory . totalGb , Math . max ( 0 , ...rows . map ( i => i . memory . reserveGb ))); 32const budget = Math . max ( 0 , hardware . memory . totalGb - reserve ); 33let excess = Math . max ( 0 , rows . reduce (( n , i ) => n + i . memory . ramGb , 0 ) - budget ); 34const flexible = rows . filter ( i => i . memory . pageable ); 35const spare = flexible . reduce (( n , i ) => n + Math . max ( 0 , i . memory . ramGb - i . memory . minimumRamGb ), 0 ); 36if ( excess > spare + .01 ) return null ; 37for ( 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 ;} 38return rows ; 39} 40 41export function reservationBudget ( instances , hardware ) { 42const reserveGb = Math . min ( hardware . memory . totalGb , Math . max ( 0 , ...instances . map ( i => i . memory . reserveGb ))); 43const ramGb = instances . reduce (( n , i ) => n + i . memory . ramGb , 0 ); 44const 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 )})); 45return { 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 }) { 49const records = new Map (), queues = new Map (); 50let defaultId = null , revision = 0 ; 51const publish = () => { revision ++ ; changed ( state ()); }; 52function devices ( ids ) { 53if ( ! 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.' ); 54return hardware (). gpus . filter ( g => ids . includes ( deviceId ( g ))). map ( deviceId ); 55} 56function prepare ( body ) { 57const model = library (). variants . find ( v => v . id === body . variantId ); 58if ( ! model ) throw new Error ( 'This model version is unavailable.' ); 59const gpuIds = devices ( body . gpuIds ); 60const config = structuredClone ( body . config ); 61if ( ! config ?. beginner || ! Array . isArray ( config . expert )) throw new Error ( 'A validated engine configuration is required.' ); 62if ( gpuIds . length === 0 ) { 63const layers = config . expert . find ( p => p . id === 'gpu.layers' ); 64if ( 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.' ); 66if ( ! 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.' ); 67const memory = modelReservation ( model , config , hardware (), gpuIds , ! real ); 68return { variantId :model . id , family :model . family , name :model . name , quant :model . quant , gpuIds, config, memory}; 69} 70function state () { 71const entries = [ ...records . values ()]. map ( i => { 72const log = requests (). filter ( r => r . instanceId === i . id ); 73return { ...structuredClone ( i ), active :log . filter ( r => r . state === 'generating' ). length , queued :log . filter ( r => r . state === 'queued' ). length }; 74}); 75return { revision, mode :real ?'real' :'simulated' , capabilities :{ multipleModels :! real , deviceAssignment :! real }, defaultId, instances :entries , memory :reservationBudget ( entries , hardware ())}; 76} 77function add ( prepared , apiModelId ) { 78const id = randomUUID (); 79const 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 }}; 80records . set ( id , instance ); 81queues . set ( id , new RequestQueue (() => publish ())); 82if ( ! defaultId ) defaultId = id ; 83return instance ; 84} 85function adopt ( variantId , config ) { 86if ( ! variantId ) { if ( real ){ records . clear (); queues . clear (); defaultId = null ;} return ; } 87const existing = [ ...records . values ()]. find ( i => i . variantId === variantId ); 88if ( real ) { for ( const i of records . values ()) if ( i . variantId !== variantId ){ records . delete ( i . id ); queues . delete ( i . id );} } 89if ( 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 ;} 90const model = library (). variants . find ( v => v . id === variantId ); if ( ! model ) return ; 91const ids = real && config . expert ?. find ( p => p . id === 'gpu.layers' )?. value === 'CPU only' ?[] :hardware (). gpus . map ( deviceId ); 92try { const prepared = prepare ({ variantId, config, gpuIds :ids }); const row = add ( prepared , variantId ); defaultId = row . id ; } 93catch { /* A legacy configuration may be invalid; never fabricate a ready instance. */ } 94} 95function executionMode ( body ) { 96const mode = body . executionMode ?? 'single' ; 97if ( ! [ 'single' , 'multiple' ]. includes ( mode )) throw new Error ( 'Choose single or multiple model execution.' ); 98return mode ; 99} 100function samePlacement ( prepared ) { 101return [ ...records . values ()]. find ( i => i . variantId === prepared . variantId && JSON . stringify ( i . gpuIds ) === JSON . stringify ( prepared . gpuIds )); 102} 103function plan ( body ) { 104const mode = executionMode ( body ), prepared = prepare ( body ), matching = samePlacement ( prepared ); 105const identical = matching && JSON . stringify ( matching . config ) === JSON . stringify ( prepared . config ); 106const siblings = mode === 'multiple' ?[ ...records . values ()]. filter ( i => i . id !== matching ?. id ) :[]; 107const planned = rebalanceReservations ([ ...siblings , prepared ], hardware ()); 108const budget = reservationBudget ( planned ?? [ ...siblings , prepared ], hardware ()); 109const candidate = planned ?. at ( - 1 ) ?? prepared ; 110return { memory :candidate . memory , budget, allowed :!! planned && budget . fits , alreadyLoaded :!! identical , reloads :!! matching , executionMode :mode }; 111} 112function load ( body ) { 113if ( real ) throw new Error ( 'Multiple native engines and GPU assignment are not supported by this host yet.' ); 114const mode = executionMode ( body ), prepared = prepare ( body ), matching = samePlacement ( prepared ); 115const model = library (). variants . find ( v => v . id === prepared . variantId ); 116if ( ! model . installedAt && ! [ 'loaded' , 'installed' ]. includes ( model . state )) throw new Error ( 'Download this model version before loading.' ); 117const identical = matching && JSON . stringify ( matching . config ) === JSON . stringify ( prepared . config ); 118if ( identical && ( mode === 'multiple' || records . size === 1 )) return { state :state (), instance :structuredClone ( matching )}; 119const affected = mode === 'single' ?[ ...records . values ()] :matching ?[ matching ] :[]; 120if ( 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.' ); 121if ( mode === 'multiple' &&! matching && records . size >= 8 ) throw new Error ( 'Unload a model before adding another. This preview supports eight instances.' ); 122const siblings = mode === 'multiple' ?[ ...records . values ()]. filter ( i => i . id !== matching ?. id ) :[]; 123const planned = rebalanceReservations ([ ...siblings , prepared ], hardware ()); 124if ( ! 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. 126if ( mode === 'single' ) for ( const row of records . values ()) if ( row . id !== matching ?. id ){ records . delete ( row . id ); queues . delete ( row . id );} 127let suffix = 1 , apiModelId = matching ?. apiModelId ?? prepared . variantId ; 128while ( ! matching && [ ...records . values ()]. some ( i => i . apiModelId === apiModelId )) apiModelId = ` ${ prepared . variantId } -- ${ ++ suffix } ` ; 129for ( const row of planned . slice ( 0 , - 1 )) records . get ( row . id ). memory = row . memory ; 130prepared . memory = planned . at ( - 1 ). memory ; 131const 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 ); 132if ( mode === 'single' ) defaultId = instance . id ; 133publish (); return { state :state (), instance :structuredClone ( instance )}; 134} 135function resolve ( modelId ,{ chatDefault= false } = {}) { 136if ( modelId !== undefined && typeof modelId !== 'string' ) throw new Error ( 'Use a model ID from /v1/models.' ); 137if ( 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 ;} 138if ( ! records . size ) throw new Error ( 'No model is loaded.' ); 139if ( ! chatDefault && records . size > 1 ) throw new Error ( 'Choose a model ID in your request when multiple models are loaded.' ); 140return records . get ( defaultId ); 141} 142function unload ( id ) { 143if ( ! records . has ( id )) throw new Error ( 'This model is no longer loaded.' ); 144if ( requests (). some ( r => r . instanceId === id && active ( r ))) throw new Error ( 'Finish or cancel this model’s requests before unloading it.' ); 145records . delete ( id ); queues . delete ( id ); if ( defaultId === id ) defaultId = records . keys (). next (). value ?? null ; publish (); return state (); 146} 147function setDefault ( id ) { if ( ! records . has ( id )) throw new Error ( 'This model is no longer loaded.' ); defaultId = id ; publish (); return state ();} 148function update ( id , patch ) { const row = records . get ( id ); if ( row ){ Object . assign ( row , patch ); publish ();}} 149function 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 )};} 150return { 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}