okami.mom/strata

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

Niko1221Merge f-0215-energy: monitor: Energy since start counts the GPUs that report power (#6012)09cfbffed

main
18.0 KiB407 linesraw
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 = {
18  phase: 'idle',
19  phaseLabel: 'Waiting for a request',
20  variantId: null,
21  prompt: { done: 0, total: 0, pct: 0 },
22  generation: { done:null,total:null },
23  queue: { running: 0, waiting: 0 },
24  context: { usedTokens: 0, maxTokens: 32768, pct: 0 },
25  expertCache: { used: 48, total: 64 },
26  hardware: {
27    gpus: [],
28    gpuLoad: 3,
29    vramUsedGb: 2.1,
30    vramTotalGb: 24,
31    ramUsedGb: 14,
32    ramTotalGb: 32,
33    gpuTempC: 44,
34    tempLimitC: 100,
35  },
36  history: [],
37  totals: {
38    tokensIn: 0,
39    tokensOut: 0,
40    requests: 0,
41    avgTps: 0,
42    since: new Date().toISOString(),
43    /** Time to first token, averaged over the session. */
44    ttftMs: 0,
45    /** Prompt-cache accounting. Everything the engine read is either reused
46     *  from the previous request's KV state or processed fresh. */
47    cachedTokens: 0,
48    uncachedTokens: 0,
49    usageRequests: 0,
50    latencyRequests: 0,
51  },
52  /** Where the context window actually went, so the breakdown can be shown. */
53  contextParts: { system: 0, tools: 0, messages: 0 },
54  target: { gpuLoad: 3, outputTps: 0, promptTps: 0 },
55  /** Which numbers come from the engine and which Strata has to estimate. */
56  telemetry: { 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() {
72  const wasIdle = Date.now() >= watchedUntil;
73  watchedUntil = Date.now() + WATCH_MS;
74  if (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') {
83  const values=readings.map(g=>g[key]);
84  if(!values.length||values.some(v=>!finite(v)))return null;
85  return mode==='max'?Math.max(...values):values.reduce((n,v)=>n+v,0)/(mode==='mean'?values.length:1);
86}
87
88function hardwareSnapshot() {
89  const demo=process.env.STRATA_REAL_ENGINE!=='1',hw=state.hardware;
90  const devices=cachedHardware()?.gpus??hwCache?.gpus??[];
91  const memoryPools=Math.max(1,devices.filter(g=>!g.unified).length+Number(devices.some(g=>g.unified)));
92  const 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}));
93  const memory = gpuMemoryTotals(devices,readings);
94  return {
95    gpus:readings,cpus:systemReading?.cpus??[],cpuLoad:systemReading?.cpuLoad??null,
96    gpuLoad:aggregate(readings,'utilizationPct','mean'),
97    vramUsedGb:memory.used,
98    vramTotalGb:memory.total,
99    ramUsedGb:systemReading?.ramUsedGb??null,ramTotalGb:systemReading?.ramTotalGb??hw.ramTotalGb,
100    gpuTempC:aggregate(readings,'temperatureC','max'),tempLimitC:hw.tempLimitC,
101    powerW:aggregate(readings,'powerW'),powerLimitW:aggregate(readings,'powerLimitW'),
102    pcieRxMbs:aggregate(readings,'pcieRxMbs'),
103    cpuTempC:demo?54:temperatures.cpuTempC,ssdTempC:demo?41:temperatures.ssdTempC,energyWh:round(energyWh(),3),
104    diskReadGbs:systemReading?.diskReadGbs??null,diskWriteMbs:systemReading?.diskWriteMbs??null,
105  };
106}
107
108export function init(hub, hardware) {
109  hubRef = hub;
110  hwCache = hardware;
111  supervisor.init(hub);
112  const total = hardware.memory.totalGb;
113  state.hardware.ramTotalGb = Math.round(total);
114  state.hardware.ramUsedGb = Math.round(hardware.memory.usedGb);
115  state.hardware.vramTotalGb = Math.round(hardware.accelerator.usableVramGb);
116  state.hardware.tempLimitC = hardware.accelerator.unified ? 105 : 90;
117  state.expertCache = { used: 0, total: 64 };
118  state.history = [];
119  state.totals.since = new Date().toISOString();
120
121  if (ticker) clearInterval(ticker);
122  ticker = setInterval(tick, 1000);
123  ticker.unref?.();
124}
125
126function approach(current, target, factor = 0.22) {
127  return current + (target - current) * factor;
128}
129
130function tick() {
131  const pace=sensorPace({live:supervisor.status().running||!!liveProbe(),watchedUntil});
132  if(!sensorsPending&&Date.now()-sensorsAt>=pace.intervalMs){
133    sensorsPending=true;sensorsAt=Date.now();
134    const hardware=cachedHardware()??hwCache;
135    void 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. */
142  if(Date.now()>drivesUntil+120000)stopTemperatures();
143  addEnergy(reportedPowerW(hardwareSnapshot().gpus),Date.now());
144  const hw = state.hardware;
145  const busy = state.phase === 'generating' || state.phase === 'reading' || state.phase === 'thinking';
146
147  // Real numbers whenever a real engine is running.
148  const engine = supervisor.status();
149  const engineMetrics = engine.metrics;
150  if(state.hardware.ramUsedGb > state.hardware.ramTotalGb && !memoryWarningShown){
151    console.warn('Memory reading exceeded physical capacity; clamping the monitor snapshot.');
152    memoryWarningShown = true;
153  }
154  if(state.hardware.ramUsedGb <= state.hardware.ramTotalGb) memoryWarningShown = false;
155  if (engine.running && engineMetrics.source === 'engine') {
156    state.telemetry.throughput = 'engine';
157    state.telemetry.memory = 'estimated';
158    if (state.phase === 'generating' && engineMetrics.outputTps > 0) state.target.outputTps = engineMetrics.outputTps;
159    if (engineMetrics.promptTps > 0) state.target.promptTps = engineMetrics.promptTps;
160    if (engineMetrics.kvUsage > 0) {
161      state.context.usedTokens = Math.round(engineMetrics.kvUsage * state.context.maxTokens);
162    }
163    const v = engine.modelId ? catalogVariant(engine.modelId) : null;
164    if (v) {
165      const kvUsed = (state.context.usedTokens / 1024) * (v.kvKbPerToken / 1024);
166      const estimate = footprint(v, state.context.usedTokens || 1024).weightsGb + kvUsed;
167      state.hardware.vramUsedGb = clamp(estimate, 0.2, state.hardware.vramTotalGb);
168    }
169    state.queue.running = engineMetrics.requestsProcessing || (busy ? 1 : 0);
170    state.queue.waiting = engineMetrics.requestsDeferred || 0;
171  } else {
172    state.telemetry.throughput = process.env.STRATA_REAL_ENGINE !== '1' ? 'demo' : 'none';
173  }
174
175  state.target.gpuLoad = busy ? (state.phase === 'reading' ? 88 : 82) : state.phase === 'loading' ? 64 : 3;
176  hw.gpuLoad = clamp(approach(hw.gpuLoad, state.target.gpuLoad) + (Math.random() - 0.5) * 3, 1, 100);
177
178  const modelVram = state.variantId ? 0 : 0;
179  const targetVram = busy
180    ? Math.min(hw.vramTotalGb, hw.vramTotalGb * 0.86)
181    : state.phase === 'loading'
182      ? hw.vramTotalGb * 0.55
183      : 2.4 + modelVram;
184  if (process.env.STRATA_REAL_ENGINE !== '1') hw.vramUsedGb = clamp(approach(hw.vramUsedGb, targetVram, 0.14), 0.4, hw.vramTotalGb);
185
186  const ramTarget = busy ? hw.ramTotalGb * 0.66 : hw.ramTotalGb * 0.44;
187  if (process.env.STRATA_REAL_ENGINE !== '1') hw.ramUsedGb = clamp(approach(hw.ramUsedGb, ramTarget, 0.08), 1, hw.ramTotalGb);
188
189  const tempTarget = busy ? hw.tempLimitC - 18 : 44;
190  hw.gpuTempC = clamp(approach(hw.gpuTempC, tempTarget, 0.05) + (Math.random() - 0.5), 32, hw.tempLimitC);
191
192  const demo = process.env.STRATA_REAL_ENGINE !== '1';
193  state.telemetry.thermals = demo ? 'demo' : 'none';
194  state.telemetry.memory = demo ? 'demo' : state.variantId ? 'estimated' : 'none';
195  const outNow = state.phase === 'generating' ? state.target.outputTps : 0;
196  const promptNow = state.phase === 'reading' ? state.target.promptTps : 0;
197  const measuredHardware=hardwareSnapshot();
198
199  state.history = [
200    ...state.history.slice(-(HISTORY - 1)),
201    {
202      t: Date.now(),
203      outputTps: round(outNow * (demo ? 0.9 + Math.random() * 0.2 : 1), 1),
204      promptTps: round(promptNow * (demo ? 0.9 + Math.random() * 0.2 : 1), 0),
205      ...measuredHardware,
206    },
207  ];
208
209  if (!engine.running) state.queue.running = busy ? 1 : 0;
210  state.context.pct = clamp((state.context.usedTokens / Math.max(state.context.maxTokens, 1)) * 100, 0, 100);
211  hubRef?.send('monitor', snapshot());
212}
213
214export function snapshot() {
215  const last = state.history.at(-1);
216  const engine = supervisor.status();
217  const engineMetrics = engine.metrics;
218  if(state.hardware.ramUsedGb > state.hardware.ramTotalGb && !memoryWarningShown){
219    console.warn('Memory reading exceeded physical capacity; clamping the monitor snapshot.');
220    memoryWarningShown = true;
221  }
222  if(state.hardware.ramUsedGb <= state.hardware.ramTotalGb) memoryWarningShown = false;
223  const result = {
224    phase: state.phase,
225    phaseLabel: state.phaseLabel,
226    variantId: state.variantId ?? getStore().loaded,
227    prompt: { ...state.prompt },
228    generation: { ...state.generation },
229    outputTps: state.phase === 'generating' ? round(state.target.outputTps, 1) : (last?.outputTps ?? 0),
230    promptTps: ['reading','thinking','generating'].includes(state.phase) ? Math.round(state.target.promptTps) : (last?.promptTps ?? 0),
231    queue: { ...state.queue },
232    context: { ...state.context, parts: { ...state.contextParts } },
233    expertCache: { ...state.expertCache },
234    hardware: hardwareSnapshot(),
235    requests: servingState().requests,
236    conversationCache: { source: 'unavailable' },
237    history: state.history,
238    totals: { ...state.totals },
239    telemetry: { ...state.telemetry, system:systemReading?'sensor':'none' },
240    engine: {
241      status: engine.status,
242      running: engine.running,
243      pid: engine.pid,
244      port: engine.port,
245      modelId: engine.modelId,
246      metricsSource: engineMetrics.source,
247      command: engine.command,
248      binary: engine.binary,
249      startedAt: engine.startedAt,
250      logCount: engine.logCount,
251    },
252  };
253  return engine.running&&engineMetrics.source==='engine'&&engineMetrics.dashboard?originalDashboard(engineMetrics.dashboard,cachedHardware()??hwCache,result):result;
254}
255
256export function setContextMax(max) {
257  state.context.maxTokens = max;
258}
259
260export function setRecordedContext({ tokensIn, tokensOut, usageSource, requestId, sessionId }) {
261  const available = Number.isFinite(tokensIn) && Number.isFinite(tokensOut);
262  state.context = { ...state.context, usedTokens: available ? tokensIn + tokensOut : 0, requestId, sessionId };
263  state.context.pct = available ? clamp(state.context.usedTokens / Math.max(1, state.context.maxTokens) * 100, 0, 100) : 0;
264  state.contextParts = {};
265  state.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) {
283  state.contextParts = {
284    system: parts.system ?? 0,
285    tools: parts.tools ?? 0,
286    messages: parts.messages ?? 0,
287  };
288  state.context.usedTokens =
289    state.contextParts.system + state.contextParts.tools + state.contextParts.messages;
290}
291
292export function resetContext() {
293  state.context.usedTokens = 0;
294  state.contextParts = { system: 0, tools: 0, messages: 0 };
295}
296
297export function setExpertCache(used, total = 64) {
298  state.expertCache = { used, total };
299}
300
301export async function setModel(id) {
302  state.variantId = id;
303  if (!id) {
304    state.phase = 'idle';
305    state.phaseLabel = 'Waiting for a request';
306    state.expertCache = { used: 0, total: 64 };
307    return;
308  }
309  const hw = hwCache ?? (await detect());
310  const v = getStore();
311  const total = 64;
312  const demo=process.env.STRATA_REAL_ENGINE!=='1';
313  const used = v.loaded&&demo ? Math.round(total * 0.75) : 0;
314  state.expertCache = { used, total, source:demo?'demo':'none' };
315  state.hardware.vramTotalGb = Math.round(hw.accelerator.usableVramGb);
316  state.hardware.ramTotalGb = Math.round(hw.memory.totalGb);
317}
318
319export async function beginLoading(id) {
320  state.variantId = id;
321  state.phase = 'loading';
322  state.phaseLabel = 'Loading model into memory';
323  state.prompt = { done: 0, total: 0, pct: 0 };
324  state.queue.waiting = 0;
325  hubRef?.send('monitor', snapshot());
326}
327
328export function beginReading(tokens, id) {
329  state.variantId = id;
330  state.phase = 'reading';
331  state.phaseLabel = 'Reading prompt';
332  state.prompt = { done: 0, total: tokens, pct: 0 };
333  state.generation={done:null,total:Number(getStore().expert?.['sample.maxTokens'])||null};
334  state.target.promptTps = process.env.STRATA_REAL_ENGINE !== '1' ? 1400 + Math.random() * 500 : 0;
335  hubRef?.send('monitor', snapshot());
336}
337
338export function progressReading(done) {
339  state.prompt.done = Math.min(done, state.prompt.total);
340  state.prompt.pct = state.prompt.total ? (state.prompt.done / state.prompt.total) * 100 : 100;
341  if (state.prompt.pct >= 100 && state.phase === 'reading') {
342    state.phase = 'thinking';
343    state.phaseLabel = 'Thinking';
344  }
345  hubRef?.send('monitor', snapshot());
346}
347
348export function beginGenerating() {
349  state.phase = 'generating';
350  state.phaseLabel = 'Generating response';
351  state.target.outputTps = process.env.STRATA_REAL_ENGINE !== '1' ? 34 + Math.random() * 14 : 0;
352  hubRef?.send('monitor', snapshot());
353}
354
355export function progressOutput(tokens) {
356  if(Number.isFinite(tokens)&&tokens>=0)state.generation.done=tokens;
357}
358
359export function beginThinking() {
360  state.phase = 'thinking';
361  state.phaseLabel = 'Thinking';
362  hubRef?.send('monitor', snapshot());
363}
364
365export function idle(label = 'Waiting for a request') {
366  state.phase = 'idle';
367  state.phaseLabel = label;
368  state.prompt = { done: 0, total: 0, pct: 0 };
369  state.target.outputTps = 0;
370  state.target.promptTps = 0;
371  state.queue = { running: 0, waiting: state.queue.waiting };
372  hubRef?.send('monitor', snapshot());
373}
374
375export function record({ tokensIn, tokensOut, durationMs = 0, ttftMs = null, cachedTokens = null, tps: answerTps = null }) {
376  if (Number.isFinite(tokensIn)) state.totals.tokensIn += tokensIn;
377  if (Number.isFinite(tokensOut)) state.totals.tokensOut += tokensOut;
378  state.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.
381  if (Number.isFinite(answerTps) && answerTps > 0) {
382    const tps = answerTps;
383    const n = ++state.totals.usageRequests;
384    state.totals.avgTps = round((state.totals.avgTps * (n - 1) + tps) / n, 1);
385  }
386
387  // Time to first token, averaged the same way as throughput.
388  if (typeof ttftMs === 'number' && ttftMs >= 0) {
389    const n = ++state.totals.latencyRequests;
390    state.totals.ttftMs = Math.round(((state.totals.ttftMs * (n - 1)) + ttftMs) / n);
391  }
392
393  // Include cache reuse only when the inference server reports it.
394  if (Number.isFinite(cachedTokens) && Number.isFinite(tokensIn)) {
395    const cached = Math.min(cachedTokens, tokensIn);
396    state.totals.cachedTokens += cached;
397    state.totals.uncachedTokens += Math.max(0, tokensIn - cached);
398  }
399}
400
401export function queueWaiting(n) {
402  state.queue.waiting = n;
403}
404
405export function currentOutputTps() {
406  return state.target.outputTps;
407}