okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
09cfbffed
main
1/** Live monitor: one state machine for phase, throughput, memory and thermals. */ 2import { variant as catalogVariant , footprint } from './catalog.mjs' ; 3import { detect , cachedHardware } from './hardware.mjs' ; 4import { readGpuTelemetry , gpuMemoryTotals } from './device-probes.mjs' ; 5import { createSystemSampler } from './system-telemetry.mjs' ; 6import { sensorPace , WATCH_MS } from './sensor-pace.mjs' ; 7import { readTemperatures , stopTemperatures } from './temperature-telemetry.mjs' ; 8import { addEnergy , energyWh , reportedPowerW } from './energy-meter.mjs' ; 9import { state as servingState } from './serving.mjs' ; 10import { originalDashboard } from './monitor-dashboard.mjs' ; 11import { get as getStore } from './store.mjs' ; 12import * as supervisor from './supervisor.mjs' ; 13import { clamp , round } from './util.mjs' ; 14 15const HISTORY = 60 ; 16 17const state = { 18phase :'idle' , 19phaseLabel :'Waiting for a request' , 20variantId :null , 21prompt :{ done :0 , total :0 , pct :0 }, 22generation :{ done :null , total :null }, 23queue :{ running :0 , waiting :0 }, 24context :{ usedTokens :0 , maxTokens :32768 , pct :0 }, 25expertCache :{ used :48 , total :64 }, 26hardware :{ 27gpus :[], 28gpuLoad :3 , 29vramUsedGb :2.1 , 30vramTotalGb :24 , 31ramUsedGb :14 , 32ramTotalGb :32 , 33gpuTempC :44 , 34tempLimitC :100 , 35}, 36history :[], 37totals :{ 38tokensIn :0 , 39tokensOut :0 , 40requests :0 , 41avgTps :0 , 42since :new Date (). toISOString (), 43/** Time to first token, averaged over the session. */ 44ttftMs :0 , 45/** Prompt-cache accounting. Everything the engine read is either reused 46* from the previous request's KV state or processed fresh. */ 47cachedTokens :0 , 48uncachedTokens :0 , 49usageRequests :0 , 50latencyRequests :0 , 51}, 52/** Where the context window actually went, so the breakdown can be shown. */ 53contextParts :{ system :0 , tools :0 , messages :0 }, 54target :{ gpuLoad :3 , outputTps :0 , promptTps :0 }, 55/** Which numbers come from the engine and which Strata has to estimate. */ 56telemetry :{ throughput :'estimated' , thermals :'estimated' , memory :'estimated' , ttftMs :null }, 57}; 58 59let hubRef = null ; 60let hwCache = null ; 61let ticker = null ; 62let memoryWarningShown = false ; 63let sensorsPending = false , sensorsAt = 0 ; 64/* The Monitor screen asks (GET /api/monitor) every few seconds while it is open; a model that is loaded counts as live (#4066). */ 65let watchedUntil = 0 , drivesUntil = 0 , liveProbe = () => false ; 66const hostStartedAt = Date . now (); 67/** The drive-temperature reader is not started in the first minute of the host: the app's own start-up traffic is not a person looking at the Monitor (#4661). */ 68export const DRIVES_AFTER_MS = 60000 ; 69/** Only the Monitor screen's own ask (GET /api/monitor?drives=1) wants drive temperatures; the start-up fetch and the Models page do not show them. */ 70export function watchDrives () { drivesUntil = Date . now () + WATCH_MS ; } 71export function watch () { 72const wasIdle = Date . now () >= watchedUntil ; 73watchedUntil = Date . now () + WATCH_MS ; 74if ( wasIdle ) sensorsAt = 0 ; // opening the Monitor after a quiet spell reads the card at once 75} 76export function setLiveProbe ( probe ) { liveProbe = typeof probe === 'function' ?probe :() => false ; } 77let systemReading = null ; 78/* CPU and SSD temperatures (null where this PC cannot give one) and the GPU energy used since the host started (#3628). */ 79let temperatures = { cpuTempC :null , ssdTempC :null }; 80const sampleSystem = createSystemSampler (); 81const finite = value => typeof value === 'number' && Number . isFinite ( value ); 82function aggregate ( readings , key , mode = 'sum' ) { 83const values = readings . map ( g => g [ key ]); 84if ( ! values . length || values . some ( v =>! finite ( v ))) return null ; 85return mode === 'max' ?Math . max ( ...values ) :values . reduce (( n , v ) => n + v , 0 ) / ( mode === 'mean' ?values . length :1 ); 86} 87 88function hardwareSnapshot () { 89const demo = process . env . STRATA_REAL_ENGINE !== '1' , hw = state . hardware ; 90const devices = cachedHardware ()?. gpus ?? hwCache ?. gpus ?? []; 91const memoryPools = Math . max ( 1 , devices . filter ( g =>! g . unified ). length + Number ( devices . some ( g => g . unified ))); 92const readings = demo ?devices . map (( gpu , i ) => ({ id :gpu . id ?? ` ${ gpu . vendor } : ${ gpu . index } ` , source :'demo' , sampledAt :new Date (). toISOString (), utilizationPct :Math . round ( clamp ( hw . gpuLoad + i * 2 , 0 , 100 )), temperatureC :Math . round ( hw . gpuTempC + i ), memoryUsedGb :round ( Math . min ( gpu . vramGb , hw . vramUsedGb / memoryPools ), 2 ), powerW :gpu . unified ?null :round ( 35 + hw . gpuLoad * 2 , 0 ), powerLimitW :gpu . unified ?null :300 , pcieGen :gpu . unified ?null :4 , pcieGenMax :gpu . unified ?null :4 , pcieWidth :gpu . unified ?null :16 , pcieRxMbs :gpu . unified ?null :round ( hw . gpuLoad * 1.2 , 1 ), fanPct :gpu . unified ?null :Math . round ( 30 + hw . gpuLoad * 0.5 ), clockMhz :gpu . unified ?null :Math . round ( 1400 + hw . gpuLoad * 14 )})) :hw . gpus . map ( g => ({ ...g })); 93const memory = gpuMemoryTotals ( devices , readings ); 94return { 95gpus :readings , cpus :systemReading ?. cpus ?? [], cpuLoad :systemReading ?. cpuLoad ?? null , 96gpuLoad :aggregate ( readings , 'utilizationPct' , 'mean' ), 97vramUsedGb :memory . used , 98vramTotalGb :memory . total , 99ramUsedGb :systemReading ?. ramUsedGb ?? null , ramTotalGb :systemReading ?. ramTotalGb ?? hw . ramTotalGb , 100gpuTempC :aggregate ( readings , 'temperatureC' , 'max' ), tempLimitC :hw . tempLimitC , 101powerW :aggregate ( readings , 'powerW' ), powerLimitW :aggregate ( readings , 'powerLimitW' ), 102pcieRxMbs :aggregate ( readings , 'pcieRxMbs' ), 103cpuTempC :demo ?54 :temperatures . cpuTempC , ssdTempC :demo ?41 :temperatures . ssdTempC , energyWh :round ( energyWh (), 3 ), 104diskReadGbs :systemReading ?. diskReadGbs ?? null , diskWriteMbs :systemReading ?. diskWriteMbs ?? null , 105}; 106} 107 108export function init ( hub , hardware ) { 109hubRef = hub ; 110hwCache = hardware ; 111supervisor . init ( hub ); 112const total = hardware . memory . totalGb ; 113state . hardware . ramTotalGb = Math . round ( total ); 114state . hardware . ramUsedGb = Math . round ( hardware . memory . usedGb ); 115state . hardware . vramTotalGb = Math . round ( hardware . accelerator . usableVramGb ); 116state . hardware . tempLimitC = hardware . accelerator . unified ?105 :90 ; 117state . expertCache = { used :0 , total :64 }; 118state . history = []; 119state . totals . since = new Date (). toISOString (); 120 121if ( ticker ) clearInterval ( ticker ); 122ticker = setInterval ( tick , 1000 ); 123ticker . unref ?.(); 124} 125 126function approach ( current , target , factor = 0.22 ) { 127return current + ( target - current ) * factor ; 128} 129 130function tick () { 131const pace = sensorPace ({ live :supervisor . status (). running ||!! liveProbe (), watchedUntil}); 132if ( ! sensorsPending && Date . now () - sensorsAt >= pace . intervalMs ){ 133sensorsPending = true ; sensorsAt = Date . now (); 134const hardware = cachedHardware () ?? hwCache ; 135void Promise . all ([ readGpuTelemetry ( hardware ?. gpus ?? [],{ transfer :pace . transfer }), sampleSystem ( hardware ?. processors ?? []),( process . env . STRATA_REAL_ENGINE === '1' && Date . now () < drivesUntil && Date . now () - hostStartedAt > DRIVES_AFTER_MS ?readTemperatures () :Promise . resolve ( temperatures )). catch (() => ({ cpuTempC :null , ssdTempC :null }))]) 136. then (([ readings , system , temps ]) => { state . hardware . gpus = readings ; systemReading = system ; temperatures = temps ;}) 137. catch (() => { state . hardware . gpus = []; systemReading = null ;}) 138. finally (() => { sensorsPending = false ;}); 139} 140/* #4661: the drive-temperature reader asks every physical drive for its temperature. Only while the Monitor is looked at, never from the first second of the app 141(on some PCs the storage queries stall the whole system); it ends a couple of minutes after the Monitor was last seen. */ 142if ( Date . now () > drivesUntil + 120000 ) stopTemperatures (); 143addEnergy ( reportedPowerW ( hardwareSnapshot (). gpus ), Date . now ()); 144const hw = state . hardware ; 145const busy = state . phase === 'generating' || state . phase === 'reading' || state . phase === 'thinking' ; 146 147// Real numbers whenever a real engine is running. 148const engine = supervisor . status (); 149const engineMetrics = engine . metrics ; 150if ( state . hardware . ramUsedGb > state . hardware . ramTotalGb && ! memoryWarningShown ){ 151console . warn ( 'Memory reading exceeded physical capacity; clamping the monitor snapshot.' ); 152memoryWarningShown = true ; 153} 154if ( state . hardware . ramUsedGb <= state . hardware . ramTotalGb ) memoryWarningShown = false ; 155if ( engine . running && engineMetrics . source === 'engine' ) { 156state . telemetry . throughput = 'engine' ; 157state . telemetry . memory = 'estimated' ; 158if ( state . phase === 'generating' && engineMetrics . outputTps > 0 ) state . target . outputTps = engineMetrics . outputTps ; 159if ( engineMetrics . promptTps > 0 ) state . target . promptTps = engineMetrics . promptTps ; 160if ( engineMetrics . kvUsage > 0 ) { 161state . context . usedTokens = Math . round ( engineMetrics . kvUsage * state . context . maxTokens ); 162} 163const v = engine . modelId ?catalogVariant ( engine . modelId ) :null ; 164if ( v ) { 165const kvUsed = ( state . context . usedTokens / 1024 ) * ( v . kvKbPerToken / 1024 ); 166const estimate = footprint ( v , state . context . usedTokens || 1024 ). weightsGb + kvUsed ; 167state . hardware . vramUsedGb = clamp ( estimate , 0.2 , state . hardware . vramTotalGb ); 168} 169state . queue . running = engineMetrics . requestsProcessing || ( busy ?1 :0 ); 170state . queue . waiting = engineMetrics . requestsDeferred || 0 ; 171} else { 172state . telemetry . throughput = process . env . STRATA_REAL_ENGINE !== '1' ?'demo' :'none' ; 173} 174 175state . target . gpuLoad = busy ?( state . phase === 'reading' ?88 :82 ) :state . phase === 'loading' ?64 :3 ; 176hw . gpuLoad = clamp ( approach ( hw . gpuLoad , state . target . gpuLoad ) + ( Math . random () - 0.5 ) * 3 , 1 , 100 ); 177 178const modelVram = state . variantId ?0 :0 ; 179const targetVram = busy 180 ?Math . min ( hw . vramTotalGb , hw . vramTotalGb * 0.86 ) 181 :state . phase === 'loading' 182 ?hw . vramTotalGb * 0.55 183 :2.4 + modelVram ; 184if ( process . env . STRATA_REAL_ENGINE !== '1' ) hw . vramUsedGb = clamp ( approach ( hw . vramUsedGb , targetVram , 0.14 ), 0.4 , hw . vramTotalGb ); 185 186const ramTarget = busy ?hw . ramTotalGb * 0.66 :hw . ramTotalGb * 0.44 ; 187if ( process . env . STRATA_REAL_ENGINE !== '1' ) hw . ramUsedGb = clamp ( approach ( hw . ramUsedGb , ramTarget , 0.08 ), 1 , hw . ramTotalGb ); 188 189const tempTarget = busy ?hw . tempLimitC - 18 :44 ; 190hw . gpuTempC = clamp ( approach ( hw . gpuTempC , tempTarget , 0.05 ) + ( Math . random () - 0.5 ), 32 , hw . tempLimitC ); 191 192const demo = process . env . STRATA_REAL_ENGINE !== '1' ; 193state . telemetry . thermals = demo ?'demo' :'none' ; 194state . telemetry . memory = demo ?'demo' :state . variantId ?'estimated' :'none' ; 195const outNow = state . phase === 'generating' ?state . target . outputTps :0 ; 196const promptNow = state . phase === 'reading' ?state . target . promptTps :0 ; 197const measuredHardware = hardwareSnapshot (); 198 199state . history = [ 200 ...state . history . slice ( - ( HISTORY - 1 )), 201{ 202t :Date . now (), 203outputTps :round ( outNow * ( demo ?0.9 + Math . random () * 0.2 :1 ), 1 ), 204promptTps :round ( promptNow * ( demo ?0.9 + Math . random () * 0.2 :1 ), 0 ), 205 ...measuredHardware , 206}, 207]; 208 209if ( ! engine . running ) state . queue . running = busy ?1 :0 ; 210state . context . pct = clamp (( state . context . usedTokens / Math . max ( state . context . maxTokens , 1 )) * 100 , 0 , 100 ); 211hubRef ?. send ( 'monitor' , snapshot ()); 212} 213 214export function snapshot () { 215const last = state . history . at ( - 1 ); 216const engine = supervisor . status (); 217const engineMetrics = engine . metrics ; 218if ( state . hardware . ramUsedGb > state . hardware . ramTotalGb && ! memoryWarningShown ){ 219console . warn ( 'Memory reading exceeded physical capacity; clamping the monitor snapshot.' ); 220memoryWarningShown = true ; 221} 222if ( state . hardware . ramUsedGb <= state . hardware . ramTotalGb ) memoryWarningShown = false ; 223const result = { 224phase :state . phase , 225phaseLabel :state . phaseLabel , 226variantId :state . variantId ?? getStore (). loaded , 227prompt :{ ...state . prompt }, 228generation :{ ...state . generation }, 229outputTps :state . phase === 'generating' ?round ( state . target . outputTps , 1 ) :( last ?. outputTps ?? 0 ), 230promptTps :[ 'reading' , 'thinking' , 'generating' ]. includes ( state . phase ) ?Math . round ( state . target . promptTps ) :( last ?. promptTps ?? 0 ), 231queue :{ ...state . queue }, 232context :{ ...state . context , parts :{ ...state . contextParts } }, 233expertCache :{ ...state . expertCache }, 234hardware :hardwareSnapshot (), 235requests :servingState (). requests , 236conversationCache :{ source :'unavailable' }, 237history :state . history , 238totals :{ ...state . totals }, 239telemetry :{ ...state . telemetry , system :systemReading ?'sensor' :'none' }, 240engine :{ 241status :engine . status , 242running :engine . running , 243pid :engine . pid , 244port :engine . port , 245modelId :engine . modelId , 246metricsSource :engineMetrics . source , 247command :engine . command , 248binary :engine . binary , 249startedAt :engine . startedAt , 250logCount :engine . logCount , 251}, 252}; 253return engine . running && engineMetrics . source === 'engine' && engineMetrics . dashboard ?originalDashboard ( engineMetrics . dashboard , cachedHardware () ?? hwCache , result ) :result ; 254} 255 256export function setContextMax ( max ) { 257state . context . maxTokens = max ; 258} 259 260export function setRecordedContext ({ tokensIn, tokensOut, usageSource, requestId, sessionId}) { 261const available = Number . isFinite ( tokensIn ) && Number . isFinite ( tokensOut ); 262state . context = { ...state . context , usedTokens :available ?tokensIn + tokensOut :0 , requestId, sessionId}; 263state . context . pct = available ?clamp ( state . context . usedTokens / Math . max ( 1 , state . context . maxTokens ) * 100 , 0 , 100 ) :0 ; 264state . contextParts = {}; 265state . telemetry . context = available ?usageSource :'unavailable' ; 266} 267 268/** 269* Records how full the context window is *now*. 270* 271* This used to **accumulate** — `usedTokens += tokensIn + tokensOut` — while the 272* per-part split beside it was computed as an absolute size. The two disagreed, 273* and the accumulating one is simply the wrong quantity: a context window is a 274* sliding space, so what matters is what has to fit in it at this moment, not 275* the sum of everything ever sent through it. 276* 277* The visible result was a meter that climbed past its own maximum within one 278* conversation — "40k / 32K tokens, 100%", clamped, with no way back down — on 279* the one indicator that tells a reader why a local model's answers are getting 280* worse. 281*/ 282export function setContext ( parts ) { 283state . contextParts = { 284system :parts . system ?? 0 , 285tools :parts . tools ?? 0 , 286messages :parts . messages ?? 0 , 287}; 288state . context . usedTokens = 289state . contextParts . system + state . contextParts . tools + state . contextParts . messages ; 290} 291 292export function resetContext () { 293state . context . usedTokens = 0 ; 294state . contextParts = { system :0 , tools :0 , messages :0 }; 295} 296 297export function setExpertCache ( used , total = 64 ) { 298state . expertCache = { used, total}; 299} 300 301export async function setModel ( id ) { 302state . variantId = id ; 303if ( ! id ) { 304state . phase = 'idle' ; 305state . phaseLabel = 'Waiting for a request' ; 306state . expertCache = { used :0 , total :64 }; 307return ; 308} 309const hw = hwCache ?? ( await detect ()); 310const v = getStore (); 311const total = 64 ; 312const demo = process . env . STRATA_REAL_ENGINE !== '1' ; 313const used = v . loaded && demo ?Math . round ( total * 0.75 ) :0 ; 314state . expertCache = { used, total, source :demo ?'demo' :'none' }; 315state . hardware . vramTotalGb = Math . round ( hw . accelerator . usableVramGb ); 316state . hardware . ramTotalGb = Math . round ( hw . memory . totalGb ); 317} 318 319export async function beginLoading ( id ) { 320state . variantId = id ; 321state . phase = 'loading' ; 322state . phaseLabel = 'Loading model into memory' ; 323state . prompt = { done :0 , total :0 , pct :0 }; 324state . queue . waiting = 0 ; 325hubRef ?. send ( 'monitor' , snapshot ()); 326} 327 328export function beginReading ( tokens , id ) { 329state . variantId = id ; 330state . phase = 'reading' ; 331state . phaseLabel = 'Reading prompt' ; 332state . prompt = { done :0 , total :tokens , pct :0 }; 333state . generation = { done :null , total :Number ( getStore (). expert ?.[ 'sample.maxTokens' ]) || null }; 334state . target . promptTps = process . env . STRATA_REAL_ENGINE !== '1' ?1400 + Math . random () * 500 :0 ; 335hubRef ?. send ( 'monitor' , snapshot ()); 336} 337 338export function progressReading ( done ) { 339state . prompt . done = Math . min ( done , state . prompt . total ); 340state . prompt . pct = state . prompt . total ?( state . prompt . done / state . prompt . total ) * 100 :100 ; 341if ( state . prompt . pct >= 100 && state . phase === 'reading' ) { 342state . phase = 'thinking' ; 343state . phaseLabel = 'Thinking' ; 344} 345hubRef ?. send ( 'monitor' , snapshot ()); 346} 347 348export function beginGenerating () { 349state . phase = 'generating' ; 350state . phaseLabel = 'Generating response' ; 351state . target . outputTps = process . env . STRATA_REAL_ENGINE !== '1' ?34 + Math . random () * 14 :0 ; 352hubRef ?. send ( 'monitor' , snapshot ()); 353} 354 355export function progressOutput ( tokens ) { 356if ( Number . isFinite ( tokens ) && tokens >= 0 ) state . generation . done = tokens ; 357} 358 359export function beginThinking () { 360state . phase = 'thinking' ; 361state . phaseLabel = 'Thinking' ; 362hubRef ?. send ( 'monitor' , snapshot ()); 363} 364 365export function idle ( label = 'Waiting for a request' ) { 366state . phase = 'idle' ; 367state . phaseLabel = label ; 368state . prompt = { done :0 , total :0 , pct :0 }; 369state . target . outputTps = 0 ; 370state . target . promptTps = 0 ; 371state . queue = { running :0 , waiting :state . queue . waiting }; 372hubRef ?. send ( 'monitor' , snapshot ()); 373} 374 375export function record ({ tokensIn, tokensOut, durationMs= 0 , ttftMs= null , cachedTokens= null , tps :answerTps = null }) { 376if ( Number . isFinite ( tokensIn )) state . totals . tokensIn += tokensIn ; 377if ( Number . isFinite ( tokensOut )) state . totals . tokensOut += tokensOut ; 378state . totals . requests += 1 ; 379// The average is of answer speeds (tokens over decode time). A request with no decode figure is left out: dividing by the whole request would 380// put the prompt reading into it and read lower than the engine and the chat do. 381if ( Number . isFinite ( answerTps ) && answerTps > 0 ) { 382const tps = answerTps ; 383const n = ++ state . totals . usageRequests ; 384state . totals . avgTps = round (( state . totals . avgTps * ( n - 1 ) + tps ) / n , 1 ); 385} 386 387// Time to first token, averaged the same way as throughput. 388if ( typeof ttftMs === 'number' && ttftMs >= 0 ) { 389const n = ++ state . totals . latencyRequests ; 390state . totals . ttftMs = Math . round ((( state . totals . ttftMs * ( n - 1 )) + ttftMs ) / n ); 391} 392 393// Include cache reuse only when the inference server reports it. 394if ( Number . isFinite ( cachedTokens ) && Number . isFinite ( tokensIn )) { 395const cached = Math . min ( cachedTokens , tokensIn ); 396state . totals . cachedTokens += cached ; 397state . totals . uncachedTokens += Math . max ( 0 , tokensIn - cached ); 398} 399} 400 401export function queueWaiting ( n ) { 402state . queue . waiting = n ; 403} 404 405export function currentOutputTps () { 406return state . target . outputTps ; 407}