okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
e5476b0e1
main
1/** Engine configuration: beginner goals, expert parameters, predictions, restart. */ 2import { CONTEXT_TOKENS , expertParams , footprint , variant } from './catalog.mjs' ; 3import { cachedHardware , detect } from './hardware.mjs' ; 4import { get as getStore , update } from './store.mjs' ; 5import * as supervisor from './supervisor.mjs' ; 6import { nowIso } from './util.mjs' ; 7 8const engineState = { 9running :false , 10startedAt :null , 11uptimeSec :0 , 12version :'strata-engine 0.1.0' , 13backend :'metal' , 14timer :null , 15}; 16 17let hubRef = null ; 18 19export function init ( hub ) { 20hubRef = hub ; 21supervisor . init ( hub ); 22if ( engineState . timer ) clearInterval ( engineState . timer ); 23engineState . timer = setInterval (() => { 24if ( ! engineState . running || ! engineState . startedAt ) return ; 25engineState . uptimeSec = Math . round (( Date . now () - new Date ( engineState . startedAt ). getTime ()) / 1000 ); 26}, 1000 ); 27} 28 29export function markRunning ( backend ) { 30engineState . running = true ; 31engineState . startedAt = nowIso (); 32engineState . uptimeSec = 0 ; 33if ( backend ) engineState . backend = backend ; 34} 35 36export function markStopped () { 37engineState . running = false ; 38engineState . startedAt = null ; 39engineState . uptimeSec = 0 ; 40} 41 42/** Merge stored overrides on top of the catalog defaults. */ 43export function params () { 44const overrides = getStore (). expert ?? {}; 45const catalog = expertParams ( cachedHardware ()?. cpu ?. cores ?? null ); 46const known = new Set ( catalog . map ( p => p . id )); 47const mapped = new Set ([ 'gpu.layers' , 'ctx.length' , 'ctx.kvMode' , 'mem.mmap' , 'mem.lock' , 'perf.batch' , 'perf.threads' , 'perf.flashAttn' , 'server.port' , 'server.parallel' ]); 48return [ ...catalog . map (( p ) => ({ 49 ...p , 50applies :p . id . startsWith ( 'sample.' ) ?'Next request' :mapped . has ( p . id ) ?'Next model load' :'Preserved only · adapter does not apply this value' , 51value :Object . hasOwn ( overrides , p . id ) ?overrides [ p . id ] :p . value , 52})), ...Object . entries ( overrides ). filter (([ id ]) => ! known . has ( id )). map (([ id , value ]) => ({ 53 id, value, recommended :value , group :'Additional settings' , label :id , 54effect :'Preserved; no verified engine mapping in this build.' , applies :'Preserved only' , 55type :typeof value === 'boolean' ?'toggle' :typeof value === 'number' ?'number' :'text' , 56}))]; 57} 58 59function loadArgs ( args ) { 60const sampling = new Set ([ '--temp' , '--top-p' , '--top-k' , '--repeat-penalty' , '--seed' ]); 61const result = []; 62for ( let i = 0 ; i < args . length ; i ++ ) { 63if ( sampling . has ( args [ i ])) { i ++ ; continue ; } 64result . push ( args [ i ]); 65} 66return result ; 67} 68 69export async function config () { 70const s = getStore (); 71const id = supervisor . status (). modelId ?? s . loaded ?? s . current ; 72const v = id ?variant ( id ) :null ; 73const hw = await detect (); 74const sup = supervisor . status (); 75const ctxLabel = String ( s . beginner . contextLength ). toUpperCase (); 76const ctxTokens = CONTEXT_TOKENS [ ctxLabel . toLowerCase ()] ?? 32768 ; 77 78const { pathFor} = await import ( './models.mjs' ); 79const previewArgs = v ?supervisor . buildArgs ({ 80modelPath :sup . running ?pathFor ( v ) :`<models>/ ${ v . id } / ${ v . source . file } ` , 81config :{ beginner :s . beginner , expert :params (), serving :s . serving , layerCount :v . layerCount }, 82hardware :hw , port :Number ( s . expert ?.[ 'server.port' ] ?? 8080 ), 83}) :[]; 84 85return { 86extra :s . configExtra ?? {}, 87variantId :v ?. id ?? null , 88beginner :s . beginner , 89expert :params (), 90predicted :predict ( s . beginner , hw , v ), 91footprint :v ?footprint ( v , ctxTokens ) :null , 92dirty :sup . running && JSON . stringify ( loadArgs ( previewArgs )) !== JSON . stringify ( loadArgs ( sup . args )), 93appliedAt :sup . startedAt ?? undefined , 94engine :{ 95running :sup . running , 96status :sup . status , 97pid :sup . pid ?? undefined , 98uptimeSec :sup . startedAt ?Math . round (( Date . now () - new Date ( sup . startedAt ). getTime ()) / 1000 ) :0 , 99version :sup . binary ?`llama.cpp · ${ sup . binary . source } ` :engineState . version , 100backend :hw . accelerator . backend , 101startedAt :sup . startedAt ?? undefined , 102port :sup . port , 103command :v ?[ sup . binary ?. path ?? 'llama-server' , ...previewArgs ]. join ( ' ' ) :'' , 104args :previewArgs , 105error :sup . error , 106}, 107}; 108} 109 110export function predict ( beginner , hw , v , expert = getStore (). expert ?? {}) { 111const notes = []; 112const ctx = CONTEXT_TOKENS [ beginner . contextLength ] ?? 32768 ; 113 114const speed = beginner . priority === 'speed' ?'Larger prompt batches' :beginner . priority === 'quality' ?'Lower randomness' :beginner . priority === 'coding' ?'Focused sampling' :'Balanced' ; 115let memory = 'Recommended' ; 116let restartNeeded = true ; 117 118if ( beginner . priority === 'speed' && ctx <= 16384 ) notes . push ( 'Short context keeps the KV cache small.' ); 119if ( beginner . priority === 'quality' ) notes . push ( 'Lower temperature makes responses less varied; it does not guarantee accuracy.' ); 120if ( beginner . priority === 'coding' ) notes . push ( 'Lower temperature favors repeatable responses.' ); 121if ( beginner . readImages ) { 122memory = 'Higher — vision layer adds ~1.8 GB' ; 123notes . push ( 'Vision needs the multimodal projector loaded alongside the model.' ); 124} 125if ( ctx >= 65536 ) { 126memory = 'Much higher — long context dominates memory' ; 127notes . push ( 'Longer context allocates a larger KV cache. Actual usage varies by architecture and cache format.' ); 128} 129if ( beginner . gpuIdle !== 'never' ) { 130notes . push ( `Freeing the GPU after ${ beginner . gpuIdle . replace ( 'm' , ' minutes' ). replace ( '1h' , 'an hour' )} means the next prompt reloads the model.` ); 131} else { 132notes . push ( 'Keeping the model loaded avoids a model reload between requests. Prompt reading still takes time.' ); 133} 134if ( v && hw ) { 135const headroom = hw . accelerator . unified ?hw . memory . totalGb * 0.72 :hw . accelerator . usableVramGb ; 136const fp = { ...footprint ( v , ctx ) }; 137const kvFactor = [ 'FP16' ]. includes ( expert [ 'ctx.kvMode' ]) ?2 :expert [ 'ctx.kvMode' ] === 'Q4_0' ?.5 :1 ; 138fp . kvGb *= kvFactor ; fp . totalGb = fp . weightsGb + fp . kvGb + fp . overheadGb ; 139if ( headroom ) { 140const verdict = fp . totalGb <= headroom * 0.85 ?'Comfortable' :fp . totalGb <= headroom ?'Tight' :'Above estimated memory budget' ; 141/* Non-breaking spaces inside the measurement: in the narrow effect 142panel this wrapped after "of", leaving an orphaned "12 GB" on a line 143of its own. The break now falls before the figure, so the second line 144is the whole measurement rather than its tail. */ 145const nb = '\u00a0' ; 146memory = ` ${ verdict } · about ${ nb } ${ fp . totalGb . toFixed ( 1 )} ${ nb } GB ${ nb } of ${ nb } ${ headroom . toFixed ( 0 )} ${ nb } GB` ; 147notes . push ( 148` ${ v . label } at ${( ctx / 1024 ). toFixed ( 0 )} K: ${ fp . weightsGb . toFixed ( 1 )} GB weights + ${ fp . kvGb . toFixed ( 2 )} GB KV cache + ${ fp . overheadGb . toFixed ( 1 )} GB runtime.` , 149); 150if ( fp . totalGb > headroom ) notes . push ( 'This estimate exceeds the selected memory budget. Use less context or a smaller variant.' ); 151} 152} 153if ( ctx > ( v ?. contextMax ?? 32768 )) { 154notes . push ( `Beyond the model's advertised context. Output reliability is not verified past ${(( v ?. contextMax ?? 32768 ) / 1024 ). toFixed ( 0 )} K.` ); 155} 156 157return { responseSpeed :speed , memory, restartNeeded, notes}; 158} 159 160export async function patch ( body ) { 161const s = getStore (); 162const next = { ...s }; 163 164if ( body . beginner ) { 165next . beginner = { ...s . beginner , ...body . beginner }; 166if ( body . beginner . contextLength ) next . expert = { ...( s . expert ?? {}), 'ctx.length' :body . beginner . contextLength === 'recommended' ?'128K' :body . beginner . contextLength . toUpperCase () }; 167} 168if ( Array . isArray ( body . expert )) { 169const overrides = body . replaceExpert ?{} :{ ...( next . expert ?? {}) }; 170for ( const item of body . expert ) { 171if ( ! item || typeof item . id !== 'string' ) continue ; 172overrides [ item . id ] = item . value ; 173} 174next . expert = overrides ; 175} 176if ( body . expertReset ) next . expert = {}; 177if ( body . extra && typeof body . extra === 'object' && ! Array . isArray ( body . extra )) next . configExtra = body . extra ; 178 179update ( next ); 180const cfg = await config (); 181hubRef ?. send ( 'engine' , cfg ); 182return cfg ; 183} 184 185export async function reset () { 186update ({ 187beginner :{ priority :'balanced' , contextLength :'recommended' , readImages :false , gpuIdle :'never' }, 188expert :{}, 189}); 190const cfg = await config (); 191hubRef ?. send ( 'engine' , cfg ); 192return cfg ; 193} 194 195export async function restart () { 196if ( process . env . STRATA_REAL_ENGINE !== '1' ) throw new Error ( 'Restart is unavailable with the example engine. Save settings for the next load.' ); 197const s = getStore (); 198const id = supervisor . status (). modelId ?? s . loaded ; 199const v = id ?variant ( id ) :null ; 200const hw = await detect (); 201 202if ( ! v ) { 203hubRef ?. send ( 'log' , { level :'warn' , message :'No model loaded — nothing to restart' , at :nowIso () }); 204const cfg = await config (); 205hubRef ?. send ( 'engine' , cfg ); 206return cfg ; 207} 208 209hubRef ?. send ( 'log' , { level :'info' , message :`Restarting engine with ${ v . label } ` , at :nowIso () }); 210try { 211const { pathFor} = await import ( './models.mjs' ); 212await supervisor . restart ({ 213modelId :v . id , 214modelPath :pathFor ( v ), 215port :Number ( s . expert ?.[ 'server.port' ] ?? 8080 ), 216config :{ beginner :s . beginner , expert :params (), serving :s . serving , layerCount :v . layerCount }, 217hardware :hw , 218}); 219markRunning ( hw . accelerator . backend ); 220} catch ( err ) { 221hubRef ?. send ( 'log' , { level :'error' , message :`Restart failed: ${ err . message } ` , at :nowIso () }); 222markStopped (); 223} 224 225const cfg = await config (); 226hubRef ?. send ( 'engine' , cfg ); 227return cfg ; 228} 229 230/** 231* @param draft optional beginner config to predict *instead of* the saved one. 232* Without it the screen can only show the consequence of settings that have 233* already been applied, which makes an "impact" line a restatement of the 234* status quo rather than a preview of the choice in front of you. 235*/ 236export async function validate ( draft = {}) { 237const hw = await detect (); 238const s = getStore (); 239const beginner = { ...s . beginner , ...( draft ?. beginner ?? {}) }; 240const v = variant ( draft ?. variantId ?? s . loaded ?? s . current ); 241const issues = []; 242const values = Object . fromEntries ( params (). map ( p => [ p . id , p . value ])); 243for ( const p of draft ?. expert ?? []) values [ p . id ] = p . value ; 244const addError = ( key , message ) => issues . push ({ level :'error' , key, message :` ${ key } : ${ message } ` }); 245const enums = { priority :[ 'speed' , 'balanced' , 'quality' , 'coding' ], contextLength :Object . keys ( CONTEXT_TOKENS ), gpuIdle :[ 'never' ] }; 246for ( const [ key , options ] of Object . entries ( enums )) if ( ! options . includes ( beginner [ key ])) addError ( key , 'choose a supported value.' ); 247if ( typeof beginner . readImages !== 'boolean' || beginner . readImages ) addError ( 'readImages' , 'image input is not supported by this host.' ); 248const limits = { 249'sample.temp' :[ 0 , 2 ], 'sample.topP' :[ 0 , 1 ], 'sample.topK' :[ 0 , 10000 ], 'sample.repeat' :[ 0.5 , 3 ], 250'sample.seed' :[ - 1 , 2147483647 ], 'sample.maxTokens' :[ 0 , 1048576 ], 'perf.threads' :[ 1 , 1024 ], 'perf.batch' :[ 1 , 65536 ], 251'perf.draftDepth' :[ 1 , 64 ], 'mem.expertCache' :[ 0 , 10000 ], 'server.port' :[ 1 , 65535 ], 252'server.parallel' :[ 1 , 64 ], 'server.queue' :[ 0 , 10000 ], 'server.timeout' :[ 1 , 86400 ], 253'adv.rope' :[ 0.01 , 100 ], 'adv.ropeBase' :[ 1 , 1000000000 ], 254}; 255const fractional = new Set ([ 'sample.temp' , 'sample.topP' , 'sample.repeat' , 'adv.rope' ]); 256for ( const p of expertParams ( hw . cpu . cores )) { 257const value = values [ p . id ]; 258if ( p . type === 'number' ) { 259const [ min , max ] = limits [ p . id ] ?? [ - Number . MAX_SAFE_INTEGER , Number . MAX_SAFE_INTEGER ]; 260if ( typeof value !== 'number' || ! Number . isFinite ( value ) || value < min || value > max || ( ! fractional . has ( p . id ) && ! Number . isInteger ( value ))) addError ( p . id , `enter ${ fractional . has ( p . id ) ? 'a number' : 'a whole number' } from ${ min } to ${ max } .` ); 261} else if ( p . type === 'toggle' && typeof value !== 'boolean' ) addError ( p . id , 'use true or false.' ); 262else if ( p . type === 'select' && ! p . options ?. includes ( value )) addError ( p . id , 'choose a supported value.' ); 263else if ( p . type === 'text' && typeof value !== 'string' ) addError ( p . id , 'enter text.' ); 264} 265if ( ! CONTEXT_TOKENS [ String ( values [ 'ctx.length' ]). toLowerCase ()] || String ( values [ 'ctx.length' ]). toLowerCase () === 'recommended' ) addError ( 'ctx.length' , 'enter a whole context size from 4K to 1024K.' ); 266const kv = values [ 'ctx.kvMode' ]; 267if ( draft ?. beginner && draft ?. expert ?. some ( p => p . id === 'ctx.length' )) { 268const effective = beginner . contextLength === 'recommended' ?'128K' :String ( beginner . contextLength ). toUpperCase (); 269if ( values [ 'ctx.length' ] !== effective ) addError ( 'ctx.length' , 'match beginner.contextLength (Recommended means 128K).' ); 270} 271const ctxLabel = beginner . contextLength ; 272const ctx = CONTEXT_TOKENS [ String ( ctxLabel ). toLowerCase ()] ?? 32768 ; 273const headroom = hw . accelerator . unified ?hw . memory . totalGb * 0.72 :hw . accelerator . usableVramGb ; 274 275if ( v && ctx > v . contextMax ) { 276issues . push ({ level :'warn' , message :` ${ ctx / 1024 } K exceeds ${ v . label } 's trained context — quality beyond that limit is not verified.` }); 277} 278if ( v && headroom ) { 279const fp = footprint ( v , ctx ); const factor = kv === 'FP16' ?2 :kv === 'Q4_0' ?.5 :1 ; 280const estimate = fp . weightsGb + fp . kvGb * factor + fp . overheadGb ; 281if ( estimate > hw . memory . totalGb ) issues . push ({ level :'warn' , message :`Estimated working memory ( ${ estimate . toFixed ( 1 )} GB) exceeds physical memory. Choose a smaller model or shorter context.` }); 282} 283if ( v && headroom && v . diskGb > headroom ) { 284issues . push ({ level :'warn' , message :` ${ v . label } needs ${ v . diskGb } GB; about ${ headroom . toFixed ( 0 )} GB is fast memory. Actual fit and offload behavior depend on the adapter.` }); 285} 286const threads = Number ( values [ 'perf.threads' ] ?? 0 ); 287if ( threads > hw . cpu . cores ) { 288issues . push ({ level :'warn' , message :`CPU threads ( ${ threads } ) exceed physical cores ( ${ hw . cpu . cores } ).` }); 289} 290const parallel = Number ( values [ 'server.parallel' ] ?? 1 ); 291if ( parallel > 1 ) { 292issues . push ({ level :'warn' , message :'Parallel requests multiply KV cache memory — keep it at 1 on unified memory.' }); 293} 294// The prediction for the config being asked about, not the one in force. 295return { 296ok :issues . every (( i ) => i . level !== 'error' ), 297 issues, 298predicted :predict ( beginner , hw , v , values ), 299}; 300} 301 302export async function exportConfig () { 303const s = getStore (); 304return { 305 ...( s . configExtra ?? {}), 306schema :'strata.engine/1' , 307exportedAt :nowIso (), 308model :s . loaded ?? s . current , 309beginner :s . beginner , 310expert :Object . fromEntries ( params (). map (( p ) => [ p . id , p . value ])), 311}; 312} 313 314export function engineInfo () { 315return { ...engineState , timer :undefined }; 316}