@mlbottleneck/engine 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -95,6 +95,23 @@ export interface DeviceSummary {
95
95
  } | null;
96
96
  }
97
97
 
98
+ export interface MeasuredRun {
99
+ tokensPerSecond: number;
100
+ origin: 'community' | 'lab';
101
+ stack: 'stock' | 'lab-baseline' | 'tuned';
102
+ model: string;
103
+ hardware: string;
104
+ deviceCount: number;
105
+ runtime: string;
106
+ quantization: string;
107
+ depthTokens: number;
108
+ speculation: { method: string; tokens: number | null } | null;
109
+ /** Same runtime, quantization family, and device count as the request. */
110
+ sameSetup: boolean;
111
+ url: string | null;
112
+ note: string | null;
113
+ }
114
+
98
115
  export interface Prediction {
99
116
  fits: boolean;
100
117
  strategy: { key: Strategy; label: string; reasoning: string | null; auto: boolean };
@@ -118,6 +135,13 @@ export interface Prediction {
118
135
  verifiedPeers: number;
119
136
  } | null;
120
137
  memory: { modelSizeGB: number | null; residentWeightsGB: number | null; kvCacheGB: number | null; availableGB: number | null };
138
+ /** Measured runs on the same model and hardware template (null when none exist). */
139
+ measured: {
140
+ /** Closest stock measurement: a community gold run or a lab stock/baseline row. */
141
+ nearest: MeasuredRun | null;
142
+ /** Closest tuned neural.download lab result: what a tuned stack reached, never a stock reference. */
143
+ labTuned: MeasuredRun | null;
144
+ };
121
145
  bottleneck: string | null;
122
146
  power: { watts: number | null; tdpWatts: number | null; costPerDay: number | null; costPer1KTokens: number | null } | null;
123
147
  devices: DeviceSummary[];
@@ -142,7 +166,12 @@ export interface HardwareListing {
142
166
 
143
167
  export interface EvidenceSnapshot {
144
168
  generatedAt?: string;
169
+ /** Community gold rows: calibrate the engine (peer correction, optimized target). */
145
170
  goldCases: any[];
171
+ /** neural.download lab rows (stock / lab-baseline / tuned): measured references only, never calibration. */
172
+ labCases?: any[];
173
+ labSource?: string;
174
+ labUpdated?: string;
146
175
  }
147
176
 
148
177
  export interface Engine {
@@ -1,4 +1,4 @@
1
- /*! ML Bottleneck engine v0.4.1 | https://mlbottleneck.com | MIT */
1
+ /*! ML Bottleneck engine v0.5.0 | https://mlbottleneck.com | MIT */
2
2
  // Generated by scripts/build-sdk.mjs from engine.js and sdk/api.js. Do not edit.
3
3
 
4
4
  function createEngine(options = {}) {
@@ -23,13 +23,22 @@ function createEngine(options = {}) {
23
23
  }
24
24
  }
25
25
 
26
- // Benchmark evidence (Localmaxxing gold rows) used for peer calibration.
27
- const ENGINE_EVIDENCE = { goldCases: [] };
26
+ // Benchmark evidence. Localmaxxing gold rows calibrate the engine (peer
27
+ // correction, optimized target). Lab rows (data/lab-evidence.json, the
28
+ // author's neural.download Intel lab) never calibrate it: they are shown
29
+ // beside a plan as measured references — stock / lab-baseline rows can be
30
+ // the nearest measured run, tuned rows show what a tuned stack reached.
31
+ const ENGINE_EVIDENCE = { goldCases: [], labCases: [] };
28
32
  let goldValidationCache = null;
33
+ let labEvidenceCache = null;
34
+ let labValidationCache = null;
29
35
 
30
36
  function setEngineEvidence(snapshot) {
31
37
  ENGINE_EVIDENCE.goldCases = Array.isArray(snapshot?.goldCases) ? snapshot.goldCases : [];
38
+ ENGINE_EVIDENCE.labCases = Array.isArray(snapshot?.labCases) ? snapshot.labCases : [];
32
39
  goldValidationCache = null;
40
+ labEvidenceCache = null;
41
+ labValidationCache = null;
33
42
  }
34
43
 
35
44
  // Nominal storage bytes per weight for each quantization family. Real
@@ -7357,6 +7366,220 @@ function createEngine(options = {}) {
7357
7366
  }
7358
7367
 
7359
7368
 
7369
+ // ---- Lab evidence (neural.download) ------------------------------------
7370
+ const LAB_EVIDENCE_ORIGIN = 'neural.download';
7371
+ const TENSOR_CAPABLE_RUNTIMES = ['vllm', 'sglang', 'tensorrt_llm'];
7372
+
7373
+ // One measured lab point in the shape the gold helpers understand. Depth
7374
+ // sweeps and speculation ladders expand into one row per point so a plan
7375
+ // at 32K depth finds the 32K measurement, not the 128-token one.
7376
+ function normalizeLabEvidenceRow(row, overrides = {}) {
7377
+ const preset = MODEL_PRESETS[row.presetKey];
7378
+ const template = DEVICE_TEMPLATES[row.hardwareTemplate];
7379
+ if (!preset || !template) return null;
7380
+ const format = getQuantFormat(row.quantization);
7381
+ const quantKey = format ? format.family : String(row.quantization || 'q4').toLowerCase();
7382
+ const promptTokens = Number.isFinite(overrides.promptTokens) ? overrides.promptTokens : (Number.isFinite(row.promptTokens) ? row.promptTokens : 128);
7383
+ const outputTokens = Number.isFinite(row.outputTokens) && row.outputTokens > 0 ? row.outputTokens : 128;
7384
+ const speculation = overrides.speculation !== undefined ? overrides.speculation : (row.speculation || null);
7385
+ const observedTokS = Number.isFinite(overrides.observedTokS) ? overrides.observedTokS : row.observedTokS;
7386
+ if (!Number.isFinite(observedTokS) || observedTokS <= 0) return null;
7387
+ const deviceCount = Math.max(1, Number(row.deviceCount) || 1);
7388
+ const runtime = FRAMEWORK_PROFILES[row.runtimeKey];
7389
+ const strategy = row.strategy || (deviceCount > 1 ? (TENSOR_CAPABLE_RUNTIMES.includes(row.runtimeKey) ? 'tensor' : 'pipeline') : 'pipeline');
7390
+ return {
7391
+ id: overrides.id || row.id,
7392
+ origin: LAB_EVIDENCE_ORIGIN,
7393
+ isLab: true,
7394
+ stack: row.stack || 'stock',
7395
+ source: row.url || '',
7396
+ url: row.url || '',
7397
+ note: row.note || '',
7398
+ model: preset.label || row.presetKey,
7399
+ hfId: preset.hfId || '',
7400
+ presetKey: row.presetKey,
7401
+ hardware: template.name || row.hardwareTemplate,
7402
+ hardwareTemplate: row.hardwareTemplate,
7403
+ deviceCount,
7404
+ runtimeKey: row.runtimeKey,
7405
+ engine: runtime ? runtime.label : row.runtimeKey,
7406
+ quantization: row.quantization || quantKey,
7407
+ quantKey,
7408
+ strategy,
7409
+ speculation,
7410
+ promptTokens,
7411
+ outputTokens,
7412
+ contextLength: promptTokens + outputTokens,
7413
+ decodeContextTokens: promptTokens + outputTokens / 2,
7414
+ observedTokS,
7415
+ prefillTokS: Number.isFinite(overrides.prefillTokS) ? overrides.prefillTokS : (Number.isFinite(row.prefillTokS) ? row.prefillTokS : null),
7416
+ reproducibility: 1
7417
+ };
7418
+ }
7419
+
7420
+ function getLabEvidenceRows() {
7421
+ if (labEvidenceCache) return labEvidenceCache;
7422
+ const rows = [];
7423
+ for (const row of ENGINE_EVIDENCE.labCases || []) {
7424
+ if (!row || typeof row !== 'object' || !row.id) continue;
7425
+ const base = normalizeLabEvidenceRow(row);
7426
+ if (base) rows.push(base);
7427
+ for (const point of Array.isArray(row.depthSweep) ? row.depthSweep : []) {
7428
+ const swept = normalizeLabEvidenceRow(row, {
7429
+ id: `${row.id}@${point.promptTokens}`,
7430
+ promptTokens: point.promptTokens,
7431
+ observedTokS: point.decodeTokS,
7432
+ prefillTokS: point.prefillTokS
7433
+ });
7434
+ if (swept) rows.push(swept);
7435
+ }
7436
+ for (const rung of Array.isArray(row.speculationLadder) ? row.speculationLadder : []) {
7437
+ const stepped = normalizeLabEvidenceRow(row, {
7438
+ id: `${row.id}@${rung.method}${rung.tokens}`,
7439
+ speculation: { method: rung.method, tokens: rung.tokens },
7440
+ observedTokS: rung.observedTokS
7441
+ });
7442
+ if (stepped) rows.push(stepped);
7443
+ }
7444
+ }
7445
+ labEvidenceCache = rows;
7446
+ return rows;
7447
+ }
7448
+
7449
+ // Rows that can stand in as the plan's "nearest measured" run: community
7450
+ // gold runs plus the lab's stock / baseline rows without speculation. A
7451
+ // tuned stack is not a stock reference.
7452
+ function getMeasuredReferenceRows() {
7453
+ return getGoldValidationRows().concat(getLabEvidenceRows().filter(row => row.stack !== 'tuned' && !row.speculation));
7454
+ }
7455
+
7456
+ function describeSameSetup(target, row) {
7457
+ return row.runtimeKey === target.runtimeKey && row.quantKey === target.quantKey &&
7458
+ (row.deviceCount || 1) === (target.deviceCount || 1);
7459
+ }
7460
+
7461
+ function depthDistance(target, row) {
7462
+ const targetDepth = Math.max(64, Number.isFinite(target.decodeContextTokens) ? target.decodeContextTokens : (target.contextLength || 64));
7463
+ const rowDepth = Math.max(64, Number.isFinite(row.decodeContextTokens) ? row.decodeContextTokens : (row.contextLength || 64));
7464
+ return Math.abs(Math.log(targetDepth / rowDepth));
7465
+ }
7466
+
7467
+ // Closest measured run for the ladder: same preset and hardware template
7468
+ // are required; runtime, quantization, device count, and decode depth
7469
+ // refine the choice. Community runs and lab stock rows compete equally.
7470
+ function findNearestMeasuredRun(target) {
7471
+ if (!target?.presetKey || !target.hardwareTemplate) return null;
7472
+ const candidates = getMeasuredReferenceRows()
7473
+ .filter(row => row.presetKey === target.presetKey && row.hardwareTemplate === target.hardwareTemplate)
7474
+ .map(row => ({ row, score: getGoldSimilarity(target, row) }))
7475
+ .sort((a, b) => b.score - a.score ||
7476
+ depthDistance(target, a.row) - depthDistance(target, b.row) ||
7477
+ (b.row.reproducibility || 0) - (a.row.reproducibility || 0));
7478
+ const best = candidates[0];
7479
+ if (!best) return null;
7480
+ return { ...best.row, sameSetup: describeSameSetup(target, best.row), similarity: best.score };
7481
+ }
7482
+
7483
+ // The tuned lab result closest to this plan on the same machine (same
7484
+ // hardware template and device count — a different card count is a
7485
+ // different roofline); runtime, quantization, and depth refine the
7486
+ // choice and ties go to the faster run. Labeled as tuned, never used as
7487
+ // a stock reference.
7488
+ function findLabTunedRun(target) {
7489
+ if (!target?.presetKey || !target.hardwareTemplate) return null;
7490
+ const candidates = getLabEvidenceRows()
7491
+ .filter(row => row.stack === 'tuned' && row.presetKey === target.presetKey &&
7492
+ row.hardwareTemplate === target.hardwareTemplate && (row.deviceCount || 1) === (target.deviceCount || 1))
7493
+ .map(row => ({ row, score: getGoldSimilarity(target, row) }))
7494
+ .sort((a, b) => b.score - a.score ||
7495
+ depthDistance(target, a.row) - depthDistance(target, b.row) ||
7496
+ b.row.observedTokS - a.row.observedTokS);
7497
+ const best = candidates[0];
7498
+ if (!best) return null;
7499
+ return { ...best.row, sameSetup: describeSameSetup(target, best.row), similarity: best.score };
7500
+ }
7501
+
7502
+ function buildEvidenceTarget(modelConfig, devicesArray, metrics = null) {
7503
+ return {
7504
+ hfId: modelConfig.hfId,
7505
+ presetKey: modelConfig.modelPreset,
7506
+ hardwareTemplate: devicesArray[0]?.template || '',
7507
+ runtimeKey: getFrameworkProfile(modelConfig, devicesArray).key,
7508
+ quantKey: modelConfig.quantizationType,
7509
+ quantization: modelConfig.quantFormat || '',
7510
+ deviceCount: devicesArray.length,
7511
+ contextLength: modelConfig.seqLength,
7512
+ decodeContextTokens: getDecodeContextTokens(modelConfig),
7513
+ hasOverflow: Array.isArray(metrics) ? metrics.some(metric => metric.hasOverflow) : false,
7514
+ batchSize: modelConfig.batchSize || 1
7515
+ };
7516
+ }
7517
+
7518
+ // The engine's view of one lab row in the row's own setup (speculation
7519
+ // included when the row used it): stock projection, optimized target, and
7520
+ // physical roofline. Stock rows show how the engine tracks the lab's
7521
+ // hardware; tuned rows show how much of the optimized target a tuned
7522
+ // stack actually reached.
7523
+ function calculateLabCaseProjection(row) {
7524
+ const preset = MODEL_PRESETS[row.presetKey];
7525
+ const template = DEVICE_TEMPLATES[row.hardwareTemplate];
7526
+ if (!preset || !template || !DTYPE_SIZES[row.quantKey]) return null;
7527
+ const devices = Array.from({ length: row.deviceCount }, (_, index) => ({
7528
+ id: index + 1,
7529
+ template: row.hardwareTemplate,
7530
+ name: `${template.name || row.hardwareTemplate}${row.deviceCount > 1 ? ` #${index + 1}` : ''}`,
7531
+ ...JSON.parse(JSON.stringify(template))
7532
+ }));
7533
+ const strategy = row.strategy;
7534
+ const spec = row.speculation;
7535
+ const modelConfig = normalizeModelConfig({
7536
+ ...preset,
7537
+ modelPreset: row.presetKey,
7538
+ quantizationType: row.quantKey,
7539
+ quantFormat: getQuantFormat(row.quantization) ? row.quantization : '',
7540
+ runtimeFramework: row.runtimeKey,
7541
+ parallelismStrategy: strategy,
7542
+ optimizationMode: spec ? 'speculative' : 'none',
7543
+ specMethod: spec ? spec.method : 'mtp',
7544
+ specTokens: spec ? spec.tokens : null,
7545
+ specAcceptance: null,
7546
+ specDraftRatio: spec && Number.isFinite(spec.draftRatio) ? spec.draftRatio : null,
7547
+ kvCacheCompression: 'none',
7548
+ batchSize: 1,
7549
+ promptTokens: row.promptTokens,
7550
+ outputTokens: row.outputTokens,
7551
+ seqLength: row.promptTokens + row.outputTokens
7552
+ });
7553
+ const metrics = calculateMetricsForConfig(modelConfig, devices);
7554
+ const genericTokS = calculateSystemRateFromDeviceRates(metrics.map(metric => metric.decodeTokensPerSecond), strategy, 1, devices, getSystemRateOptions(modelConfig));
7555
+ const prefillProjectedTokS = getSystemPrefillRateForMetrics(modelConfig, metrics, devices, strategy);
7556
+ const calibration = calculateCurrentCalibration(modelConfig, metrics, genericTokS, strategy, devices);
7557
+ if (!calibration || !Number.isFinite(genericTokS) || genericTokS <= 0) return null;
7558
+ return {
7559
+ ...row,
7560
+ genericTokS,
7561
+ prefillProjectedTokS,
7562
+ expectedTokS: calibration.expectedTokS,
7563
+ optimizedTokS: calibration.optimizedTokS,
7564
+ physicalTokS: calibration.physicalTokS,
7565
+ latencyBoundTokS: calibration.latencyBoundTokS,
7566
+ calibrationPeers: calibration.peers,
7567
+ confidence: calibration.confidence,
7568
+ observedToGeneric: row.observedTokS / genericTokS,
7569
+ observedToExpected: row.observedTokS / calibration.expectedTokS,
7570
+ observedToOptimized: row.observedTokS / calibration.optimizedTokS,
7571
+ observedToPhysical: row.observedTokS / calibration.physicalTokS,
7572
+ hasOverflow: metrics.some(metric => metric.hasOverflow)
7573
+ };
7574
+ }
7575
+
7576
+ function getLabValidationRows() {
7577
+ if (labValidationCache) return labValidationCache;
7578
+ labValidationCache = getLabEvidenceRows().map(calculateLabCaseProjection).filter(Boolean);
7579
+ return labValidationCache;
7580
+ }
7581
+
7582
+
7360
7583
  function calculateCurrentCalibration(modelConfig, metrics, genericSystemRate, strategy, devicesArray = null) {
7361
7584
  const devices = devicesArray || defaultDevices();
7362
7585
  if (!metrics?.length || !Number.isFinite(genericSystemRate)) return null;
@@ -7669,6 +7892,7 @@ function createEngine(options = {}) {
7669
7892
  }
7670
7893
  const power = calculatePowerAndCost(devices, aggregateDecode, metrics, request.usage || {});
7671
7894
  const speculationActive = Boolean(primary?.speculation && primary.speculationMultiplier > 1);
7895
+ const evidenceTarget = buildEvidenceTarget(config, devices, metrics);
7672
7896
  return {
7673
7897
  fits,
7674
7898
  strategy: { key: strategy, label: strategy, reasoning: strategyInfo?.reasoning || null, auto: Boolean(strategyInfo) },
@@ -7702,6 +7926,10 @@ function createEngine(options = {}) {
7702
7926
  kvCacheGB: sdkRound(metrics.reduce((sum, metric) => sum + (metric.residentKvCacheGB || 0), 0), 2),
7703
7927
  availableGB: sdkRound(devices.reduce((sum, device) => sum + (parseFloat(device.memoryGB) || 0), 0), 1)
7704
7928
  },
7929
+ measured: {
7930
+ nearest: sdkSummarizeMeasuredRun(findNearestMeasuredRun(evidenceTarget)),
7931
+ labTuned: sdkSummarizeMeasuredRun(findLabTunedRun(evidenceTarget))
7932
+ },
7705
7933
  bottleneck: primary?.decodeTimeBreakdown?.dominant || null,
7706
7934
  power: power ? { watts: sdkRound(power.actualPowerWatts, 0), tdpWatts: sdkRound(power.totalTDP, 0), costPerDay: sdkRound(power.dailyCost, 3), costPer1KTokens: sdkRound(power.costPer1KTokens, 5) } : null,
7707
7935
  devices: metrics.map((metric, index) => sdkSummarizeDevice(metric, devices[index])),
@@ -7731,6 +7959,27 @@ function createEngine(options = {}) {
7731
7959
  };
7732
7960
  }
7733
7961
 
7962
+ // A measured reference run (community gold row or neural.download lab row)
7963
+ // in a stable shape; null when nothing on the same model + hardware exists.
7964
+ function sdkSummarizeMeasuredRun(row) {
7965
+ if (!row) return null;
7966
+ return {
7967
+ tokensPerSecond: sdkRound(row.observedTokS, 2),
7968
+ origin: row.isLab ? 'lab' : 'community',
7969
+ stack: row.isLab ? row.stack : 'stock',
7970
+ model: row.model,
7971
+ hardware: row.hardware,
7972
+ deviceCount: row.deviceCount || 1,
7973
+ runtime: row.runtimeKey,
7974
+ quantization: row.quantization || row.quantKey,
7975
+ depthTokens: Math.round(row.decodeContextTokens || row.contextLength || 0),
7976
+ speculation: row.speculation ? { method: row.speculation.method, tokens: row.speculation.tokens ?? null } : null,
7977
+ sameSetup: Boolean(row.sameSetup),
7978
+ url: row.source || row.url || null,
7979
+ note: row.note || null
7980
+ };
7981
+ }
7982
+
7734
7983
  function listModels() {
7735
7984
  return Object.entries(MODEL_PRESETS).map(([key, preset]) => ({
7736
7985
  key,
@@ -7792,11 +8041,11 @@ function createEngine(options = {}) {
7792
8041
 
7793
8042
  if (options.snapshot) setEngineEvidence(options.snapshot);
7794
8043
  const api = createApi();
7795
- api.version = "0.4.1";
8044
+ api.version = "0.5.0";
7796
8045
  api.evidenceGeneratedAt = options.snapshot?.generatedAt || null;
7797
8046
  return api;
7798
8047
  }
7799
8048
 
7800
- const version = "0.4.1";
8049
+ const version = "0.5.0";
7801
8050
  export { createEngine, version };
7802
8051
  export default createEngine;
@@ -1,4 +1,4 @@
1
- /*! ML Bottleneck engine v0.4.1 | https://mlbottleneck.com | MIT */
1
+ /*! ML Bottleneck engine v0.5.0 | https://mlbottleneck.com | MIT */
2
2
  // Generated by scripts/build-sdk.mjs from engine.js and sdk/api.js. Do not edit.
3
3
  (function (root, factory) {
4
4
  if (typeof define === 'function' && define.amd) {
@@ -32,13 +32,22 @@
32
32
  }
33
33
  }
34
34
 
35
- // Benchmark evidence (Localmaxxing gold rows) used for peer calibration.
36
- const ENGINE_EVIDENCE = { goldCases: [] };
35
+ // Benchmark evidence. Localmaxxing gold rows calibrate the engine (peer
36
+ // correction, optimized target). Lab rows (data/lab-evidence.json, the
37
+ // author's neural.download Intel lab) never calibrate it: they are shown
38
+ // beside a plan as measured references — stock / lab-baseline rows can be
39
+ // the nearest measured run, tuned rows show what a tuned stack reached.
40
+ const ENGINE_EVIDENCE = { goldCases: [], labCases: [] };
37
41
  let goldValidationCache = null;
42
+ let labEvidenceCache = null;
43
+ let labValidationCache = null;
38
44
 
39
45
  function setEngineEvidence(snapshot) {
40
46
  ENGINE_EVIDENCE.goldCases = Array.isArray(snapshot?.goldCases) ? snapshot.goldCases : [];
47
+ ENGINE_EVIDENCE.labCases = Array.isArray(snapshot?.labCases) ? snapshot.labCases : [];
41
48
  goldValidationCache = null;
49
+ labEvidenceCache = null;
50
+ labValidationCache = null;
42
51
  }
43
52
 
44
53
  // Nominal storage bytes per weight for each quantization family. Real
@@ -7366,6 +7375,220 @@
7366
7375
  }
7367
7376
 
7368
7377
 
7378
+ // ---- Lab evidence (neural.download) ------------------------------------
7379
+ const LAB_EVIDENCE_ORIGIN = 'neural.download';
7380
+ const TENSOR_CAPABLE_RUNTIMES = ['vllm', 'sglang', 'tensorrt_llm'];
7381
+
7382
+ // One measured lab point in the shape the gold helpers understand. Depth
7383
+ // sweeps and speculation ladders expand into one row per point so a plan
7384
+ // at 32K depth finds the 32K measurement, not the 128-token one.
7385
+ function normalizeLabEvidenceRow(row, overrides = {}) {
7386
+ const preset = MODEL_PRESETS[row.presetKey];
7387
+ const template = DEVICE_TEMPLATES[row.hardwareTemplate];
7388
+ if (!preset || !template) return null;
7389
+ const format = getQuantFormat(row.quantization);
7390
+ const quantKey = format ? format.family : String(row.quantization || 'q4').toLowerCase();
7391
+ const promptTokens = Number.isFinite(overrides.promptTokens) ? overrides.promptTokens : (Number.isFinite(row.promptTokens) ? row.promptTokens : 128);
7392
+ const outputTokens = Number.isFinite(row.outputTokens) && row.outputTokens > 0 ? row.outputTokens : 128;
7393
+ const speculation = overrides.speculation !== undefined ? overrides.speculation : (row.speculation || null);
7394
+ const observedTokS = Number.isFinite(overrides.observedTokS) ? overrides.observedTokS : row.observedTokS;
7395
+ if (!Number.isFinite(observedTokS) || observedTokS <= 0) return null;
7396
+ const deviceCount = Math.max(1, Number(row.deviceCount) || 1);
7397
+ const runtime = FRAMEWORK_PROFILES[row.runtimeKey];
7398
+ const strategy = row.strategy || (deviceCount > 1 ? (TENSOR_CAPABLE_RUNTIMES.includes(row.runtimeKey) ? 'tensor' : 'pipeline') : 'pipeline');
7399
+ return {
7400
+ id: overrides.id || row.id,
7401
+ origin: LAB_EVIDENCE_ORIGIN,
7402
+ isLab: true,
7403
+ stack: row.stack || 'stock',
7404
+ source: row.url || '',
7405
+ url: row.url || '',
7406
+ note: row.note || '',
7407
+ model: preset.label || row.presetKey,
7408
+ hfId: preset.hfId || '',
7409
+ presetKey: row.presetKey,
7410
+ hardware: template.name || row.hardwareTemplate,
7411
+ hardwareTemplate: row.hardwareTemplate,
7412
+ deviceCount,
7413
+ runtimeKey: row.runtimeKey,
7414
+ engine: runtime ? runtime.label : row.runtimeKey,
7415
+ quantization: row.quantization || quantKey,
7416
+ quantKey,
7417
+ strategy,
7418
+ speculation,
7419
+ promptTokens,
7420
+ outputTokens,
7421
+ contextLength: promptTokens + outputTokens,
7422
+ decodeContextTokens: promptTokens + outputTokens / 2,
7423
+ observedTokS,
7424
+ prefillTokS: Number.isFinite(overrides.prefillTokS) ? overrides.prefillTokS : (Number.isFinite(row.prefillTokS) ? row.prefillTokS : null),
7425
+ reproducibility: 1
7426
+ };
7427
+ }
7428
+
7429
+ function getLabEvidenceRows() {
7430
+ if (labEvidenceCache) return labEvidenceCache;
7431
+ const rows = [];
7432
+ for (const row of ENGINE_EVIDENCE.labCases || []) {
7433
+ if (!row || typeof row !== 'object' || !row.id) continue;
7434
+ const base = normalizeLabEvidenceRow(row);
7435
+ if (base) rows.push(base);
7436
+ for (const point of Array.isArray(row.depthSweep) ? row.depthSweep : []) {
7437
+ const swept = normalizeLabEvidenceRow(row, {
7438
+ id: `${row.id}@${point.promptTokens}`,
7439
+ promptTokens: point.promptTokens,
7440
+ observedTokS: point.decodeTokS,
7441
+ prefillTokS: point.prefillTokS
7442
+ });
7443
+ if (swept) rows.push(swept);
7444
+ }
7445
+ for (const rung of Array.isArray(row.speculationLadder) ? row.speculationLadder : []) {
7446
+ const stepped = normalizeLabEvidenceRow(row, {
7447
+ id: `${row.id}@${rung.method}${rung.tokens}`,
7448
+ speculation: { method: rung.method, tokens: rung.tokens },
7449
+ observedTokS: rung.observedTokS
7450
+ });
7451
+ if (stepped) rows.push(stepped);
7452
+ }
7453
+ }
7454
+ labEvidenceCache = rows;
7455
+ return rows;
7456
+ }
7457
+
7458
+ // Rows that can stand in as the plan's "nearest measured" run: community
7459
+ // gold runs plus the lab's stock / baseline rows without speculation. A
7460
+ // tuned stack is not a stock reference.
7461
+ function getMeasuredReferenceRows() {
7462
+ return getGoldValidationRows().concat(getLabEvidenceRows().filter(row => row.stack !== 'tuned' && !row.speculation));
7463
+ }
7464
+
7465
+ function describeSameSetup(target, row) {
7466
+ return row.runtimeKey === target.runtimeKey && row.quantKey === target.quantKey &&
7467
+ (row.deviceCount || 1) === (target.deviceCount || 1);
7468
+ }
7469
+
7470
+ function depthDistance(target, row) {
7471
+ const targetDepth = Math.max(64, Number.isFinite(target.decodeContextTokens) ? target.decodeContextTokens : (target.contextLength || 64));
7472
+ const rowDepth = Math.max(64, Number.isFinite(row.decodeContextTokens) ? row.decodeContextTokens : (row.contextLength || 64));
7473
+ return Math.abs(Math.log(targetDepth / rowDepth));
7474
+ }
7475
+
7476
+ // Closest measured run for the ladder: same preset and hardware template
7477
+ // are required; runtime, quantization, device count, and decode depth
7478
+ // refine the choice. Community runs and lab stock rows compete equally.
7479
+ function findNearestMeasuredRun(target) {
7480
+ if (!target?.presetKey || !target.hardwareTemplate) return null;
7481
+ const candidates = getMeasuredReferenceRows()
7482
+ .filter(row => row.presetKey === target.presetKey && row.hardwareTemplate === target.hardwareTemplate)
7483
+ .map(row => ({ row, score: getGoldSimilarity(target, row) }))
7484
+ .sort((a, b) => b.score - a.score ||
7485
+ depthDistance(target, a.row) - depthDistance(target, b.row) ||
7486
+ (b.row.reproducibility || 0) - (a.row.reproducibility || 0));
7487
+ const best = candidates[0];
7488
+ if (!best) return null;
7489
+ return { ...best.row, sameSetup: describeSameSetup(target, best.row), similarity: best.score };
7490
+ }
7491
+
7492
+ // The tuned lab result closest to this plan on the same machine (same
7493
+ // hardware template and device count — a different card count is a
7494
+ // different roofline); runtime, quantization, and depth refine the
7495
+ // choice and ties go to the faster run. Labeled as tuned, never used as
7496
+ // a stock reference.
7497
+ function findLabTunedRun(target) {
7498
+ if (!target?.presetKey || !target.hardwareTemplate) return null;
7499
+ const candidates = getLabEvidenceRows()
7500
+ .filter(row => row.stack === 'tuned' && row.presetKey === target.presetKey &&
7501
+ row.hardwareTemplate === target.hardwareTemplate && (row.deviceCount || 1) === (target.deviceCount || 1))
7502
+ .map(row => ({ row, score: getGoldSimilarity(target, row) }))
7503
+ .sort((a, b) => b.score - a.score ||
7504
+ depthDistance(target, a.row) - depthDistance(target, b.row) ||
7505
+ b.row.observedTokS - a.row.observedTokS);
7506
+ const best = candidates[0];
7507
+ if (!best) return null;
7508
+ return { ...best.row, sameSetup: describeSameSetup(target, best.row), similarity: best.score };
7509
+ }
7510
+
7511
+ function buildEvidenceTarget(modelConfig, devicesArray, metrics = null) {
7512
+ return {
7513
+ hfId: modelConfig.hfId,
7514
+ presetKey: modelConfig.modelPreset,
7515
+ hardwareTemplate: devicesArray[0]?.template || '',
7516
+ runtimeKey: getFrameworkProfile(modelConfig, devicesArray).key,
7517
+ quantKey: modelConfig.quantizationType,
7518
+ quantization: modelConfig.quantFormat || '',
7519
+ deviceCount: devicesArray.length,
7520
+ contextLength: modelConfig.seqLength,
7521
+ decodeContextTokens: getDecodeContextTokens(modelConfig),
7522
+ hasOverflow: Array.isArray(metrics) ? metrics.some(metric => metric.hasOverflow) : false,
7523
+ batchSize: modelConfig.batchSize || 1
7524
+ };
7525
+ }
7526
+
7527
+ // The engine's view of one lab row in the row's own setup (speculation
7528
+ // included when the row used it): stock projection, optimized target, and
7529
+ // physical roofline. Stock rows show how the engine tracks the lab's
7530
+ // hardware; tuned rows show how much of the optimized target a tuned
7531
+ // stack actually reached.
7532
+ function calculateLabCaseProjection(row) {
7533
+ const preset = MODEL_PRESETS[row.presetKey];
7534
+ const template = DEVICE_TEMPLATES[row.hardwareTemplate];
7535
+ if (!preset || !template || !DTYPE_SIZES[row.quantKey]) return null;
7536
+ const devices = Array.from({ length: row.deviceCount }, (_, index) => ({
7537
+ id: index + 1,
7538
+ template: row.hardwareTemplate,
7539
+ name: `${template.name || row.hardwareTemplate}${row.deviceCount > 1 ? ` #${index + 1}` : ''}`,
7540
+ ...JSON.parse(JSON.stringify(template))
7541
+ }));
7542
+ const strategy = row.strategy;
7543
+ const spec = row.speculation;
7544
+ const modelConfig = normalizeModelConfig({
7545
+ ...preset,
7546
+ modelPreset: row.presetKey,
7547
+ quantizationType: row.quantKey,
7548
+ quantFormat: getQuantFormat(row.quantization) ? row.quantization : '',
7549
+ runtimeFramework: row.runtimeKey,
7550
+ parallelismStrategy: strategy,
7551
+ optimizationMode: spec ? 'speculative' : 'none',
7552
+ specMethod: spec ? spec.method : 'mtp',
7553
+ specTokens: spec ? spec.tokens : null,
7554
+ specAcceptance: null,
7555
+ specDraftRatio: spec && Number.isFinite(spec.draftRatio) ? spec.draftRatio : null,
7556
+ kvCacheCompression: 'none',
7557
+ batchSize: 1,
7558
+ promptTokens: row.promptTokens,
7559
+ outputTokens: row.outputTokens,
7560
+ seqLength: row.promptTokens + row.outputTokens
7561
+ });
7562
+ const metrics = calculateMetricsForConfig(modelConfig, devices);
7563
+ const genericTokS = calculateSystemRateFromDeviceRates(metrics.map(metric => metric.decodeTokensPerSecond), strategy, 1, devices, getSystemRateOptions(modelConfig));
7564
+ const prefillProjectedTokS = getSystemPrefillRateForMetrics(modelConfig, metrics, devices, strategy);
7565
+ const calibration = calculateCurrentCalibration(modelConfig, metrics, genericTokS, strategy, devices);
7566
+ if (!calibration || !Number.isFinite(genericTokS) || genericTokS <= 0) return null;
7567
+ return {
7568
+ ...row,
7569
+ genericTokS,
7570
+ prefillProjectedTokS,
7571
+ expectedTokS: calibration.expectedTokS,
7572
+ optimizedTokS: calibration.optimizedTokS,
7573
+ physicalTokS: calibration.physicalTokS,
7574
+ latencyBoundTokS: calibration.latencyBoundTokS,
7575
+ calibrationPeers: calibration.peers,
7576
+ confidence: calibration.confidence,
7577
+ observedToGeneric: row.observedTokS / genericTokS,
7578
+ observedToExpected: row.observedTokS / calibration.expectedTokS,
7579
+ observedToOptimized: row.observedTokS / calibration.optimizedTokS,
7580
+ observedToPhysical: row.observedTokS / calibration.physicalTokS,
7581
+ hasOverflow: metrics.some(metric => metric.hasOverflow)
7582
+ };
7583
+ }
7584
+
7585
+ function getLabValidationRows() {
7586
+ if (labValidationCache) return labValidationCache;
7587
+ labValidationCache = getLabEvidenceRows().map(calculateLabCaseProjection).filter(Boolean);
7588
+ return labValidationCache;
7589
+ }
7590
+
7591
+
7369
7592
  function calculateCurrentCalibration(modelConfig, metrics, genericSystemRate, strategy, devicesArray = null) {
7370
7593
  const devices = devicesArray || defaultDevices();
7371
7594
  if (!metrics?.length || !Number.isFinite(genericSystemRate)) return null;
@@ -7678,6 +7901,7 @@
7678
7901
  }
7679
7902
  const power = calculatePowerAndCost(devices, aggregateDecode, metrics, request.usage || {});
7680
7903
  const speculationActive = Boolean(primary?.speculation && primary.speculationMultiplier > 1);
7904
+ const evidenceTarget = buildEvidenceTarget(config, devices, metrics);
7681
7905
  return {
7682
7906
  fits,
7683
7907
  strategy: { key: strategy, label: strategy, reasoning: strategyInfo?.reasoning || null, auto: Boolean(strategyInfo) },
@@ -7711,6 +7935,10 @@
7711
7935
  kvCacheGB: sdkRound(metrics.reduce((sum, metric) => sum + (metric.residentKvCacheGB || 0), 0), 2),
7712
7936
  availableGB: sdkRound(devices.reduce((sum, device) => sum + (parseFloat(device.memoryGB) || 0), 0), 1)
7713
7937
  },
7938
+ measured: {
7939
+ nearest: sdkSummarizeMeasuredRun(findNearestMeasuredRun(evidenceTarget)),
7940
+ labTuned: sdkSummarizeMeasuredRun(findLabTunedRun(evidenceTarget))
7941
+ },
7714
7942
  bottleneck: primary?.decodeTimeBreakdown?.dominant || null,
7715
7943
  power: power ? { watts: sdkRound(power.actualPowerWatts, 0), tdpWatts: sdkRound(power.totalTDP, 0), costPerDay: sdkRound(power.dailyCost, 3), costPer1KTokens: sdkRound(power.costPer1KTokens, 5) } : null,
7716
7944
  devices: metrics.map((metric, index) => sdkSummarizeDevice(metric, devices[index])),
@@ -7740,6 +7968,27 @@
7740
7968
  };
7741
7969
  }
7742
7970
 
7971
+ // A measured reference run (community gold row or neural.download lab row)
7972
+ // in a stable shape; null when nothing on the same model + hardware exists.
7973
+ function sdkSummarizeMeasuredRun(row) {
7974
+ if (!row) return null;
7975
+ return {
7976
+ tokensPerSecond: sdkRound(row.observedTokS, 2),
7977
+ origin: row.isLab ? 'lab' : 'community',
7978
+ stack: row.isLab ? row.stack : 'stock',
7979
+ model: row.model,
7980
+ hardware: row.hardware,
7981
+ deviceCount: row.deviceCount || 1,
7982
+ runtime: row.runtimeKey,
7983
+ quantization: row.quantization || row.quantKey,
7984
+ depthTokens: Math.round(row.decodeContextTokens || row.contextLength || 0),
7985
+ speculation: row.speculation ? { method: row.speculation.method, tokens: row.speculation.tokens ?? null } : null,
7986
+ sameSetup: Boolean(row.sameSetup),
7987
+ url: row.source || row.url || null,
7988
+ note: row.note || null
7989
+ };
7990
+ }
7991
+
7743
7992
  function listModels() {
7744
7993
  return Object.entries(MODEL_PRESETS).map(([key, preset]) => ({
7745
7994
  key,
@@ -7801,10 +8050,10 @@
7801
8050
 
7802
8051
  if (options.snapshot) setEngineEvidence(options.snapshot);
7803
8052
  const api = createApi();
7804
- api.version = "0.4.1";
8053
+ api.version = "0.5.0";
7805
8054
  api.evidenceGeneratedAt = options.snapshot?.generatedAt || null;
7806
8055
  return api;
7807
8056
  }
7808
8057
 
7809
- return { createEngine, version: "0.4.1" };
8058
+ return { createEngine, version: "0.5.0" };
7810
8059
  }));