llm-api-purity-check 0.0.0-stage → 1.3.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.
- package/LICENSE +27 -0
- package/README.md +161 -2
- package/README_CN.md +122 -0
- package/bin/cli.mjs +415 -0
- package/data/bank.generated.json +1 -0
- package/package.json +39 -4
- package/scripts/sync-bank.mjs +333 -0
- package/skills/aiapipk-check/SKILL.md +134 -0
- package/src/checks.mjs +1273 -0
- package/src/client.mjs +1240 -0
- package/src/fingerprint.mjs +665 -0
- package/src/links.mjs +135 -0
- package/src/modelIdNormalize.mjs +94 -0
|
@@ -0,0 +1,665 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 1-355 Numerical Distribution Model Fingerprinting Engine (38-model symmetric M2 engine)
|
|
3
|
+
*
|
|
4
|
+
* Statistical attribution (Hellinger + symmetric nuisance-projected Ordered-block + Jensen-Shannon similarity)
|
|
5
|
+
* built on MIT-licensed open-source methods from xqy2006/ModelTrace & kiss-kedaya/chanshui,
|
|
6
|
+
* packaged for standalone CLI use by AIAPIPK (https://www.aiapipk.com/detect/).
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import crypto from 'node:crypto';
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import { fileURLToPath } from 'node:url';
|
|
13
|
+
import { inferCanonicalBankFamily, normalizeModelSlug } from './modelIdNormalize.mjs';
|
|
14
|
+
|
|
15
|
+
export const FP_VALUE_MIN = 1;
|
|
16
|
+
export const FP_VALUE_MAX = 355;
|
|
17
|
+
export const FP_DIMENSION = FP_VALUE_MAX - FP_VALUE_MIN + 1;
|
|
18
|
+
const FP_ALPHA = 0.5;
|
|
19
|
+
const SYMMETRIC_OB_WEIGHT = 0.4;
|
|
20
|
+
const MERGED_BETA_BY_ROUNDS = { 1: 3.5, 2: 4.5, 3: 5.0 };
|
|
21
|
+
const STALE_BASELINE_DAYS = 90;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Empirically verified same-family sibling clusters whose 1-355 priors overlap closely.
|
|
25
|
+
* Landing within the same sibling cluster with combined probability >= 0.60 counts as matched.
|
|
26
|
+
*/
|
|
27
|
+
export const SIBLING_MODEL_GROUPS = [
|
|
28
|
+
['gpt-6.1-sol', 'gpt-6-astra'],
|
|
29
|
+
['deepseek-v4-flash', 'deepseek-v4.1-flash-0910', 'deepseek-v4.1-flash-1017'],
|
|
30
|
+
['gemini-4-argon', 'gemini-4-carbon'],
|
|
31
|
+
['kimi-k3', 'kimi-k3.1-pro'],
|
|
32
|
+
];
|
|
33
|
+
|
|
34
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
35
|
+
const DEFAULT_BANK_PATH = path.resolve(__dirname, '../data/bank.generated.json');
|
|
36
|
+
|
|
37
|
+
let cachedNumericBank = null;
|
|
38
|
+
|
|
39
|
+
export function clearFingerprintBankCache() {
|
|
40
|
+
cachedNumericBank = null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function loadFingerprintBank(bankPath = DEFAULT_BANK_PATH) {
|
|
44
|
+
if (cachedNumericBank && bankPath === DEFAULT_BANK_PATH) return cachedNumericBank;
|
|
45
|
+
const raw = JSON.parse(fs.readFileSync(bankPath, 'utf-8'));
|
|
46
|
+
const numeric = raw.numeric || raw;
|
|
47
|
+
if (!numeric || !Array.isArray(numeric.models) || !numeric.robust) {
|
|
48
|
+
throw new Error(`Invalid fingerprint bank schema in ${bankPath}`);
|
|
49
|
+
}
|
|
50
|
+
if (bankPath === DEFAULT_BANK_PATH) cachedNumericBank = numeric;
|
|
51
|
+
return numeric;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function dot(a, b) {
|
|
55
|
+
let s = 0;
|
|
56
|
+
for (let i = 0; i < a.length; i += 1) s += a[i] * b[i];
|
|
57
|
+
return s;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function unit(v) {
|
|
61
|
+
const n = Math.max(Math.sqrt(dot(v, v)), 1e-12);
|
|
62
|
+
return v.map((x) => x / n);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function standardizeScalar(values) {
|
|
66
|
+
const mean = values.reduce((a, b) => a + b, 0) / values.length;
|
|
67
|
+
const variance = values.reduce((a, b) => a + (b - mean) ** 2, 0) / values.length;
|
|
68
|
+
const scale = Math.max(Math.sqrt(variance), 1e-12);
|
|
69
|
+
return values.map((v) => (v - mean) / scale);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function standardizeWithStats(values, mean, scale) {
|
|
73
|
+
return values.map((v, i) => (v - mean[i]) / scale[i]);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function projectOut(values, basis) {
|
|
77
|
+
const out = values.slice();
|
|
78
|
+
for (const vec of basis || []) {
|
|
79
|
+
const proj = dot(out, vec);
|
|
80
|
+
for (let i = 0; i < out.length; i += 1) out[i] -= proj * vec[i];
|
|
81
|
+
}
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function parseModelTraceNumbers(text) {
|
|
86
|
+
const str = String(text || '');
|
|
87
|
+
const runs = [];
|
|
88
|
+
let current = [];
|
|
89
|
+
let prevEnd = 0;
|
|
90
|
+
for (const match of str.matchAll(/\d+/g)) {
|
|
91
|
+
const idx = match.index ?? 0;
|
|
92
|
+
const sep = str.slice(prevEnd, idx);
|
|
93
|
+
const val = Number(match[0]);
|
|
94
|
+
if (current.length > 0 && /\p{L}/u.test(sep)) {
|
|
95
|
+
runs.push(current);
|
|
96
|
+
current = [];
|
|
97
|
+
}
|
|
98
|
+
if (val >= FP_VALUE_MIN && val <= FP_VALUE_MAX) {
|
|
99
|
+
current.push(val);
|
|
100
|
+
}
|
|
101
|
+
prevEnd = idx + match[0].length;
|
|
102
|
+
}
|
|
103
|
+
if (current.length > 0) runs.push(current);
|
|
104
|
+
return runs.reduce((best, run) => (run.length > best.length ? run : best), []);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function countNumbers355(nums) {
|
|
108
|
+
const counts = new Array(FP_DIMENSION).fill(0);
|
|
109
|
+
for (const n of nums) {
|
|
110
|
+
if (n >= FP_VALUE_MIN && n <= FP_VALUE_MAX) counts[n - FP_VALUE_MIN] += 1;
|
|
111
|
+
}
|
|
112
|
+
return counts;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Inspect whether a parsed 1..355 sequence is degenerate (e.g., counting 1..300,
|
|
117
|
+
* constant/stuck repetitions, or collapsed tiny value vocabulary).
|
|
118
|
+
*/
|
|
119
|
+
export function inspectSequenceDegeneracy(nums) {
|
|
120
|
+
if (!Array.isArray(nums) || nums.length < 2) {
|
|
121
|
+
return {
|
|
122
|
+
degenerate: true,
|
|
123
|
+
reason: 'too_short',
|
|
124
|
+
stepOneRatio: 0,
|
|
125
|
+
adjacentRepeatRatio: 0,
|
|
126
|
+
uniqueCount: Array.isArray(nums) ? nums.length : 0,
|
|
127
|
+
minUnique: 2,
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
let stepOneCount = 0;
|
|
131
|
+
let adjacentRepeatCount = 0;
|
|
132
|
+
const unique = new Set();
|
|
133
|
+
unique.add(nums[0]);
|
|
134
|
+
for (let i = 1; i < nums.length; i += 1) {
|
|
135
|
+
unique.add(nums[i]);
|
|
136
|
+
if (nums[i] === nums[i - 1]) adjacentRepeatCount += 1;
|
|
137
|
+
else if (Math.abs(nums[i] - nums[i - 1]) === 1) stepOneCount += 1;
|
|
138
|
+
}
|
|
139
|
+
const transitions = nums.length - 1;
|
|
140
|
+
const stepOneRatio = Math.round((stepOneCount / transitions) * 10000) / 10000;
|
|
141
|
+
const adjacentRepeatRatio = Math.round((adjacentRepeatCount / transitions) * 10000) / 10000;
|
|
142
|
+
const uniqueCount = unique.size;
|
|
143
|
+
const minUnique = Math.min(30, nums.length * 0.15);
|
|
144
|
+
|
|
145
|
+
let reason = null;
|
|
146
|
+
if (stepOneRatio > 0.35) reason = 'monotonic_step_one';
|
|
147
|
+
else if (adjacentRepeatRatio > 0.35) reason = 'adjacent_repeat';
|
|
148
|
+
else if (uniqueCount < minUnique) reason = 'low_unique_diversity';
|
|
149
|
+
|
|
150
|
+
return {
|
|
151
|
+
degenerate: reason !== null,
|
|
152
|
+
reason,
|
|
153
|
+
stepOneRatio,
|
|
154
|
+
adjacentRepeatRatio,
|
|
155
|
+
uniqueCount,
|
|
156
|
+
minUnique,
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export function isDegenerateSequence(nums) {
|
|
161
|
+
return inspectSequenceDegeneracy(nums).degenerate;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function computePositionalOverlap(a, b) {
|
|
165
|
+
const maxLen = Math.max(a.length, b.length);
|
|
166
|
+
if (maxLen === 0) return 0;
|
|
167
|
+
const minLen = Math.min(a.length, b.length);
|
|
168
|
+
let same = 0;
|
|
169
|
+
for (let i = 0; i < minLen; i += 1) {
|
|
170
|
+
if (a[i] === b[i]) same += 1;
|
|
171
|
+
}
|
|
172
|
+
return same / maxLen;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function hellingerFeature(counts) {
|
|
176
|
+
const total = counts.reduce((a, b) => a + b, 0) + FP_ALPHA * FP_DIMENSION;
|
|
177
|
+
return counts.map((v) => Math.sqrt((v + FP_ALPHA) / total));
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function splitIntoFour(values) {
|
|
181
|
+
const base = Math.floor(values.length / 4);
|
|
182
|
+
const rem = values.length % 4;
|
|
183
|
+
const chunks = [];
|
|
184
|
+
let start = 0;
|
|
185
|
+
for (let i = 0; i < 4; i += 1) {
|
|
186
|
+
const size = base + (i < rem ? 1 : 0);
|
|
187
|
+
chunks.push(values.slice(start, start + size));
|
|
188
|
+
start += size;
|
|
189
|
+
}
|
|
190
|
+
return chunks;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function orderedBlockFeature(nums) {
|
|
194
|
+
const pieces = [];
|
|
195
|
+
for (const chunk of splitIntoFour(nums)) {
|
|
196
|
+
const bins = new Array(16).fill(0.5);
|
|
197
|
+
for (const val of chunk) {
|
|
198
|
+
const idx = Math.min(15, Math.floor(((val - 1) / FP_VALUE_MAX) * 16));
|
|
199
|
+
bins[idx] += 1;
|
|
200
|
+
}
|
|
201
|
+
const total = bins.reduce((a, b) => a + b, 0);
|
|
202
|
+
pieces.push(...bins.map((v) => Math.sqrt(v / total)));
|
|
203
|
+
}
|
|
204
|
+
const lastDigits = new Array(10).fill(0.5);
|
|
205
|
+
for (const val of nums) lastDigits[val % 10] += 1;
|
|
206
|
+
const lastTotal = lastDigits.reduce((a, b) => a + b, 0);
|
|
207
|
+
pieces.push(...lastDigits.map((v) => Math.sqrt(v / lastTotal)));
|
|
208
|
+
return pieces;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export function jsSimilarity355(queryCounts, refCounts) {
|
|
212
|
+
const leftTotal = queryCounts.reduce((a, b) => a + b, 0);
|
|
213
|
+
const rightTotal = refCounts.reduce((a, b) => a + b, 0) + FP_ALPHA * FP_DIMENSION;
|
|
214
|
+
if (leftTotal <= 0 || rightTotal <= 0) return 0;
|
|
215
|
+
let divP = 0;
|
|
216
|
+
let divQ = 0;
|
|
217
|
+
for (let i = 0; i < FP_DIMENSION; i += 1) {
|
|
218
|
+
const p = queryCounts[i] / leftTotal;
|
|
219
|
+
const q = (refCounts[i] + FP_ALPHA) / rightTotal;
|
|
220
|
+
const m = 0.5 * (p + q);
|
|
221
|
+
if (p > 0) divP += p * Math.log(p / m);
|
|
222
|
+
if (q > 0) divQ += q * Math.log(q / m);
|
|
223
|
+
}
|
|
224
|
+
const js = 0.5 * (divP + divQ);
|
|
225
|
+
return Math.max(0, Math.min(1, 1 - Math.sqrt(Math.max(0, js) / Math.log(2))));
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function softmax(beta, scores) {
|
|
229
|
+
const mx = Math.max(...scores);
|
|
230
|
+
const weights = scores.map((s) => Math.exp(beta * (s - mx)));
|
|
231
|
+
const sum = weights.reduce((a, b) => a + b, 0) || 1;
|
|
232
|
+
return weights.map((w) => w / sum);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Infer expected bank family for claimed model across the 7 covered families.
|
|
237
|
+
* Uncovered families (e.g. Grok, Llama, Mistral) return null so they do not trigger false family_mismatch.
|
|
238
|
+
*/
|
|
239
|
+
export function inferExpectedBankFamily(modelName) {
|
|
240
|
+
return inferCanonicalBankFamily(modelName);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export { normalizeModelSlug };
|
|
244
|
+
|
|
245
|
+
export function classifyBaselineProvenance(modelDef, nowMs = Date.now()) {
|
|
246
|
+
if (!modelDef) return { tier: 'unknown', stale: false, ageDays: null };
|
|
247
|
+
const src = String(modelDef.reference_source || '').toLowerCase();
|
|
248
|
+
let tier = 'official_direct';
|
|
249
|
+
if (!src || src === 'modeltrace_base' || src.includes('official') || src.includes('openai-direct') || src.includes('api.deepseek.com')) {
|
|
250
|
+
tier = 'official_direct';
|
|
251
|
+
} else if (src.includes('langbase.netease.com') || src.includes('aigw-int') || src.includes('verified_gateway')) {
|
|
252
|
+
tier = 'verified_gateway';
|
|
253
|
+
} else {
|
|
254
|
+
tier = 'third_party_relay';
|
|
255
|
+
}
|
|
256
|
+
let stale = false;
|
|
257
|
+
let ageDays = null;
|
|
258
|
+
if (modelDef.captured_at) {
|
|
259
|
+
const ts = Date.parse(modelDef.captured_at);
|
|
260
|
+
if (Number.isFinite(ts)) {
|
|
261
|
+
ageDays = Math.floor((nowMs - ts) / (24 * 3600 * 1000));
|
|
262
|
+
stale = ageDays > STALE_BASELINE_DAYS;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
return { tier, stale, ageDays };
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
export function generateFingerprintChallenges(count = 3) {
|
|
269
|
+
const openings = [
|
|
270
|
+
'Generate a fresh sequence of arbitrary integers',
|
|
271
|
+
'Output a sequence of independent integers',
|
|
272
|
+
'Produce a raw sequence of unpatterned integers',
|
|
273
|
+
];
|
|
274
|
+
const pool = Array.from({ length: 41 }, (_, i) => 292 + i);
|
|
275
|
+
const lengths = [];
|
|
276
|
+
while (lengths.length < count && pool.length > 0) {
|
|
277
|
+
const idx = crypto.randomInt(0, pool.length);
|
|
278
|
+
lengths.push(pool.splice(idx, 1)[0]);
|
|
279
|
+
}
|
|
280
|
+
return lengths.map((length, index) => ({
|
|
281
|
+
id: `fp-${index + 1}-${crypto.randomBytes(3).toString('hex')}`,
|
|
282
|
+
expectedCount: length,
|
|
283
|
+
prompt:
|
|
284
|
+
`${openings[index % openings.length]}: output exactly ${length} integers between 1 and 355 (inclusive). ` +
|
|
285
|
+
'Choose each number independently; do not count upward/downward, do not use arithmetic progressions, cycles, or repeating blocks. ' +
|
|
286
|
+
'Do NOT call any tools, code interpreter, Python, calculator, or external RNG—generate directly from the language model. ' +
|
|
287
|
+
'Output only the numbers separated by commas or spaces, starting immediately with the first integer and no commentary.',
|
|
288
|
+
}));
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function usesSymmetricNuisanceOB(bank) {
|
|
292
|
+
const ob = bank.robust?.ordered_blocks;
|
|
293
|
+
if (bank.merged_symmetric || bank.robust?.symmetric_nuisance_ob) return true;
|
|
294
|
+
if (bank.models.length > 18) return true;
|
|
295
|
+
if (!Array.isArray(ob?.environment_centroids) || ob.environment_centroids.length === 0) return true;
|
|
296
|
+
return false;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function robustScoreNumbers(nums, bank) {
|
|
300
|
+
const h = bank.robust.hellinger;
|
|
301
|
+
const ob = bank.robust.ordered_blocks;
|
|
302
|
+
const n = bank.models.length;
|
|
303
|
+
|
|
304
|
+
const hp = unit(
|
|
305
|
+
projectOut(
|
|
306
|
+
standardizeWithStats(hellingerFeature(countNumbers355(nums)), h.feature_mean, h.feature_scale),
|
|
307
|
+
h.nuisance_basis
|
|
308
|
+
)
|
|
309
|
+
);
|
|
310
|
+
const rawH = h.centroids.map((c) => dot(hp, c));
|
|
311
|
+
const hell = standardizeScalar(rawH);
|
|
312
|
+
|
|
313
|
+
if (!ob) {
|
|
314
|
+
return { scores: hell, rawH, rawOB: new Array(n).fill(0) };
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
const os = standardizeWithStats(orderedBlockFeature(nums), ob.feature_mean, ob.feature_scale);
|
|
318
|
+
const op = unit(projectOut(os, ob.nuisance_basis));
|
|
319
|
+
const rawOB = ob.centroids.map((c) => dot(op, c));
|
|
320
|
+
|
|
321
|
+
if (usesSymmetricNuisanceOB(bank)) {
|
|
322
|
+
const weight = SYMMETRIC_OB_WEIGHT;
|
|
323
|
+
const ordered = standardizeScalar(rawOB);
|
|
324
|
+
const scores = hell.map((hv, i) => (1 - weight) * hv + weight * ordered[i]);
|
|
325
|
+
return { scores, rawH, rawOB };
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
const weight = Number(ob.weight || 0);
|
|
329
|
+
if (weight === 0) return { scores: hell, rawH, rawOB };
|
|
330
|
+
|
|
331
|
+
const osUnit = unit(os);
|
|
332
|
+
const templateRaw = new Array(n);
|
|
333
|
+
for (let c = 0; c < n; c += 1) {
|
|
334
|
+
let best = -Infinity;
|
|
335
|
+
for (const env of ob.environment_centroids) {
|
|
336
|
+
const val = dot(osUnit, env[c]);
|
|
337
|
+
if (val > best) best = val;
|
|
338
|
+
}
|
|
339
|
+
templateRaw[c] = Number.isFinite(best) ? best : 0;
|
|
340
|
+
}
|
|
341
|
+
const template = standardizeScalar(templateRaw);
|
|
342
|
+
const nuisance = standardizeScalar(rawOB);
|
|
343
|
+
const ordered = standardizeScalar(template.map((t, i) => 0.5 * t + 0.5 * nuisance[i]));
|
|
344
|
+
const scores = hell.map((hv, i) => (1 - weight) * hv + weight * ordered[i]);
|
|
345
|
+
return { scores, rawH, rawOB };
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
function findClaimedModelInBank(claimedModel, bank) {
|
|
349
|
+
const req = normalizeModelSlug(claimedModel);
|
|
350
|
+
if (!req) return null;
|
|
351
|
+
for (const m of bank.models) {
|
|
352
|
+
if (normalizeModelSlug(m.id) === req || normalizeModelSlug(m.display_name) === req) return m;
|
|
353
|
+
for (const al of m.aliases || []) {
|
|
354
|
+
if (normalizeModelSlug(al) === req) return m;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
// Strict loose matching: only allow snapshot/version suffix tails (e.g. -20251001, -latest, -v1),
|
|
358
|
+
// never allow cross-tier prefix collisions like glm-5.3-flash matching glm-5.3 or gpt-5-mini matching gpt-5.
|
|
359
|
+
for (const m of bank.models) {
|
|
360
|
+
const normId = normalizeModelSlug(m.id);
|
|
361
|
+
if (normId.startsWith(req) || req.startsWith(normId)) {
|
|
362
|
+
const tail = req.length >= normId.length ? req.slice(normId.length) : normId.slice(req.length);
|
|
363
|
+
if (/^-(?:202\d{5}|latest|v\d+(?:-\d+)?)$/i.test(tail)) {
|
|
364
|
+
return m;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
return null;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
export function attributeFingerprint(outputs, claimedModel, bankPathOrOptions = DEFAULT_BANK_PATH) {
|
|
372
|
+
const opts =
|
|
373
|
+
typeof bankPathOrOptions === 'string'
|
|
374
|
+
? { bankPath: bankPathOrOptions }
|
|
375
|
+
: { bankPath: DEFAULT_BANK_PATH, ...(bankPathOrOptions || {}) };
|
|
376
|
+
const bank = opts.bank || loadFingerprintBank(opts.bankPath || DEFAULT_BANK_PATH);
|
|
377
|
+
const nowMs = typeof opts.nowMs === 'number' ? opts.nowMs : Date.now();
|
|
378
|
+
const minValid = bank.minimum_valid_numbers || 80;
|
|
379
|
+
const valid = [];
|
|
380
|
+
const diagnostics = [];
|
|
381
|
+
let degenerateRejectedCount = 0;
|
|
382
|
+
let duplicateRejectedCount = 0;
|
|
383
|
+
|
|
384
|
+
outputs.forEach((o, index) => {
|
|
385
|
+
const nums = parseModelTraceNumbers(o?.text);
|
|
386
|
+
const minimum = o?.expectedCount ? Math.max(minValid, Math.ceil(o.expectedCount * 0.55)) : minValid;
|
|
387
|
+
if (nums.length < minimum) {
|
|
388
|
+
diagnostics.push({
|
|
389
|
+
index,
|
|
390
|
+
parsedNumbers: nums.length,
|
|
391
|
+
minimumNumbers: minimum,
|
|
392
|
+
accepted: false,
|
|
393
|
+
rejectReason: 'too_short',
|
|
394
|
+
});
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
const deg = inspectSequenceDegeneracy(nums);
|
|
399
|
+
if (deg.degenerate) {
|
|
400
|
+
degenerateRejectedCount += 1;
|
|
401
|
+
diagnostics.push({
|
|
402
|
+
index,
|
|
403
|
+
parsedNumbers: nums.length,
|
|
404
|
+
minimumNumbers: minimum,
|
|
405
|
+
accepted: false,
|
|
406
|
+
rejectReason: `degenerate:${deg.reason}`,
|
|
407
|
+
});
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
const isDuplicate = valid.some((prev) => computePositionalOverlap(nums, prev.nums) > 0.9);
|
|
412
|
+
if (isDuplicate) {
|
|
413
|
+
duplicateRejectedCount += 1;
|
|
414
|
+
diagnostics.push({
|
|
415
|
+
index,
|
|
416
|
+
parsedNumbers: nums.length,
|
|
417
|
+
minimumNumbers: minimum,
|
|
418
|
+
accepted: false,
|
|
419
|
+
rejectReason: 'duplicate_round',
|
|
420
|
+
});
|
|
421
|
+
return;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
const scored = robustScoreNumbers(nums, bank);
|
|
425
|
+
diagnostics.push({
|
|
426
|
+
index,
|
|
427
|
+
parsedNumbers: nums.length,
|
|
428
|
+
minimumNumbers: minimum,
|
|
429
|
+
accepted: true,
|
|
430
|
+
rejectReason: null,
|
|
431
|
+
});
|
|
432
|
+
valid.push({
|
|
433
|
+
nums,
|
|
434
|
+
counts: countNumbers355(nums),
|
|
435
|
+
scores: scored.scores,
|
|
436
|
+
rawH: scored.rawH,
|
|
437
|
+
rawOB: scored.rawOB,
|
|
438
|
+
});
|
|
439
|
+
});
|
|
440
|
+
|
|
441
|
+
const claimedDef = findClaimedModelInBank(claimedModel, bank);
|
|
442
|
+
const claimedExpectedFamily = claimedDef?.family || inferExpectedBankFamily(claimedModel);
|
|
443
|
+
const verdictPath = [];
|
|
444
|
+
|
|
445
|
+
if (valid.length === 0) {
|
|
446
|
+
verdictPath.push(
|
|
447
|
+
`valid_rounds=0/${outputs.length}(deg=${degenerateRejectedCount},dup=${duplicateRejectedCount})`,
|
|
448
|
+
'status=insufficient'
|
|
449
|
+
);
|
|
450
|
+
return {
|
|
451
|
+
bankModelCount: bank.models.length,
|
|
452
|
+
usedOutputs: 0,
|
|
453
|
+
diagnostics,
|
|
454
|
+
prediction: null,
|
|
455
|
+
predictionName: null,
|
|
456
|
+
probability: 0,
|
|
457
|
+
lowConfidence: true,
|
|
458
|
+
familyPrediction: null,
|
|
459
|
+
familyPredictionName: null,
|
|
460
|
+
familyProbability: 0,
|
|
461
|
+
familyProbabilities: [],
|
|
462
|
+
topCandidates: [],
|
|
463
|
+
claimedInBank: Boolean(claimedDef),
|
|
464
|
+
claimedCanonicalId: claimedDef?.id || null,
|
|
465
|
+
claimedExpectedFamily,
|
|
466
|
+
claimedModelRank: null,
|
|
467
|
+
claimedModelProb: null,
|
|
468
|
+
claimedMatchStatus: 'insufficient',
|
|
469
|
+
cvAccuracy: null,
|
|
470
|
+
topRawH: null,
|
|
471
|
+
topRawOB: null,
|
|
472
|
+
topJsSimilarity: null,
|
|
473
|
+
degenerateRejectedCount,
|
|
474
|
+
duplicateRejectedCount,
|
|
475
|
+
siblingClusterMatched: false,
|
|
476
|
+
verdictPath,
|
|
477
|
+
baselineProvenanceWarning: null,
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
const n = bank.models.length;
|
|
482
|
+
const combinedScores = new Array(n).fill(0);
|
|
483
|
+
const combinedRawH = new Array(n).fill(0);
|
|
484
|
+
const combinedRawOB = new Array(n).fill(0);
|
|
485
|
+
for (const v of valid) {
|
|
486
|
+
for (let c = 0; c < n; c += 1) {
|
|
487
|
+
combinedScores[c] += v.scores[c];
|
|
488
|
+
combinedRawH[c] += v.rawH[c];
|
|
489
|
+
combinedRawOB[c] += v.rawOB[c];
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
for (let c = 0; c < n; c += 1) {
|
|
493
|
+
combinedScores[c] /= valid.length;
|
|
494
|
+
combinedRawH[c] /= valid.length;
|
|
495
|
+
combinedRawOB[c] /= valid.length;
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
const calibRound = Math.min(valid.length, 3);
|
|
499
|
+
const calibKey = String(calibRound);
|
|
500
|
+
const symmetricMode = usesSymmetricNuisanceOB(bank);
|
|
501
|
+
const defaultBeta = symmetricMode ? MERGED_BETA_BY_ROUNDS[calibRound] : 7.0;
|
|
502
|
+
const calib = bank.calibration?.[calibKey] || { beta: defaultBeta, cv_accuracy: null };
|
|
503
|
+
const beta = symmetricMode ? MERGED_BETA_BY_ROUNDS[calibRound] : calib.beta;
|
|
504
|
+
const probs = softmax(beta, combinedScores);
|
|
505
|
+
|
|
506
|
+
const pooledCounts = new Array(FP_DIMENSION).fill(0);
|
|
507
|
+
for (const v of valid) {
|
|
508
|
+
for (let i = 0; i < FP_DIMENSION; i += 1) pooledCounts[i] += v.counts[i];
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
const familyMap = new Map();
|
|
512
|
+
const allResults = bank.models.map((m, idx) => {
|
|
513
|
+
const p = probs[idx];
|
|
514
|
+
const fam = familyMap.get(m.family) || { displayName: m.family_name || m.family, probability: 0 };
|
|
515
|
+
fam.probability += p;
|
|
516
|
+
familyMap.set(m.family, fam);
|
|
517
|
+
return {
|
|
518
|
+
modelId: m.id,
|
|
519
|
+
displayName: m.display_name || m.id,
|
|
520
|
+
family: m.family,
|
|
521
|
+
familyName: m.family_name || m.family,
|
|
522
|
+
probability: Math.round(p * 10000) / 10000,
|
|
523
|
+
jsSimilarity: Math.round(jsSimilarity355(pooledCounts, m.counts) * 10000) / 10000,
|
|
524
|
+
rawH: Math.round(combinedRawH[idx] * 10000) / 10000,
|
|
525
|
+
rawOB: Math.round(combinedRawOB[idx] * 10000) / 10000,
|
|
526
|
+
score: Math.round(combinedScores[idx] * 1000) / 1000,
|
|
527
|
+
};
|
|
528
|
+
});
|
|
529
|
+
|
|
530
|
+
allResults.sort((a, b) => b.probability - a.probability || b.score - a.score);
|
|
531
|
+
const familyProbabilities = Array.from(familyMap.entries())
|
|
532
|
+
.map(([family, info]) => ({
|
|
533
|
+
family,
|
|
534
|
+
displayName: info.displayName,
|
|
535
|
+
probability: Math.round(info.probability * 10000) / 10000,
|
|
536
|
+
}))
|
|
537
|
+
.sort((a, b) => b.probability - a.probability);
|
|
538
|
+
|
|
539
|
+
const top = allResults[0];
|
|
540
|
+
const topModelDef = bank.models.find((m) => m.id === top.modelId) || null;
|
|
541
|
+
const winFam = familyProbabilities[0];
|
|
542
|
+
const lowConfidence = top.probability < 0.6;
|
|
543
|
+
const topRawH = top.rawH;
|
|
544
|
+
const topRawOB = top.rawOB;
|
|
545
|
+
const topJsSimilarity = top.jsSimilarity;
|
|
546
|
+
|
|
547
|
+
let claimedModelRank = null;
|
|
548
|
+
let claimedModelProb = null;
|
|
549
|
+
if (claimedDef) {
|
|
550
|
+
const idx = allResults.findIndex((r) => r.modelId === claimedDef.id);
|
|
551
|
+
if (idx >= 0) {
|
|
552
|
+
claimedModelRank = idx + 1;
|
|
553
|
+
claimedModelProb = allResults[idx].probability;
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
const siblingGroup = claimedDef ? SIBLING_MODEL_GROUPS.find((g) => g.includes(claimedDef.id)) : null;
|
|
558
|
+
const siblingMatched = (() => {
|
|
559
|
+
if (!claimedDef || !siblingGroup || !siblingGroup.includes(top.modelId)) return false;
|
|
560
|
+
const combinedSiblingProb = allResults
|
|
561
|
+
.filter((r) => siblingGroup.includes(r.modelId))
|
|
562
|
+
.reduce((sum, r) => sum + r.probability, 0);
|
|
563
|
+
return combinedSiblingProb >= 0.6;
|
|
564
|
+
})();
|
|
565
|
+
const siblingClusterMatched = Boolean(siblingMatched && (top.modelId !== claimedDef.id || lowConfidence));
|
|
566
|
+
|
|
567
|
+
verdictPath.push(
|
|
568
|
+
`valid_rounds=${valid.length}/${outputs.length}`,
|
|
569
|
+
`top=${top.modelId}(p=${top.probability},rawH=${topRawH},rawOB=${topRawOB},js=${topJsSimilarity})`
|
|
570
|
+
);
|
|
571
|
+
|
|
572
|
+
let claimedMatchStatus = 'not_in_bank';
|
|
573
|
+
if (!claimedDef) {
|
|
574
|
+
const passesOodFitGate =
|
|
575
|
+
Boolean(claimedExpectedFamily) &&
|
|
576
|
+
Boolean(winFam) &&
|
|
577
|
+
winFam.family !== claimedExpectedFamily &&
|
|
578
|
+
winFam.probability >= 0.85 &&
|
|
579
|
+
topRawH >= 0.3 &&
|
|
580
|
+
topRawOB >= 0.3 &&
|
|
581
|
+
topJsSimilarity >= 0.78;
|
|
582
|
+
if (passesOodFitGate) {
|
|
583
|
+
claimedMatchStatus = 'family_mismatch';
|
|
584
|
+
verdictPath.push(`ood_gate=passed(fam=${winFam.family}:${winFam.probability})`, 'status=family_mismatch');
|
|
585
|
+
} else {
|
|
586
|
+
claimedMatchStatus = 'not_in_bank';
|
|
587
|
+
verdictPath.push('ood_gate=conservative_reject', 'status=not_in_bank');
|
|
588
|
+
}
|
|
589
|
+
} else if (siblingMatched) {
|
|
590
|
+
claimedMatchStatus = 'matched';
|
|
591
|
+
verdictPath.push(siblingClusterMatched ? 'sibling_cluster=matched' : 'exact_top1=matched', 'status=matched');
|
|
592
|
+
} else if (lowConfidence) {
|
|
593
|
+
claimedMatchStatus = 'low_confidence';
|
|
594
|
+
verdictPath.push(`low_conf(p=${top.probability}<0.6)`, 'status=low_confidence');
|
|
595
|
+
} else if (claimedModelRank === 1 || (claimedModelProb !== null && claimedModelProb >= 0.25)) {
|
|
596
|
+
claimedMatchStatus = 'matched';
|
|
597
|
+
verdictPath.push(`claimed_rank=${claimedModelRank}(p=${claimedModelProb})`, 'status=matched');
|
|
598
|
+
} else if (top.probability >= 0.72 && (claimedModelProb ?? 0) < 0.15) {
|
|
599
|
+
claimedMatchStatus = 'mismatch';
|
|
600
|
+
verdictPath.push(`claimed_rank=${claimedModelRank}(p=${claimedModelProb})`, 'candidate=mismatch');
|
|
601
|
+
} else {
|
|
602
|
+
claimedMatchStatus = 'low_confidence';
|
|
603
|
+
verdictPath.push('ambiguous_margin', 'status=low_confidence');
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
let baselineProvenanceWarning = null;
|
|
607
|
+
const claimedProv = classifyBaselineProvenance(claimedDef, nowMs);
|
|
608
|
+
const topProv = classifyBaselineProvenance(topModelDef, nowMs);
|
|
609
|
+
const nonDirectOrStaleClaimed = claimedDef && (claimedProv.tier === 'third_party_relay' || claimedProv.stale);
|
|
610
|
+
const nonDirectOrStaleTop = topModelDef && (topProv.tier === 'third_party_relay' || topProv.stale);
|
|
611
|
+
|
|
612
|
+
if (claimedMatchStatus === 'mismatch') {
|
|
613
|
+
const sameFamily = claimedDef && top.family === claimedDef.family;
|
|
614
|
+
if ((sameFamily && nonDirectOrStaleClaimed) || nonDirectOrStaleTop) {
|
|
615
|
+
const reasons = [];
|
|
616
|
+
if (nonDirectOrStaleClaimed) {
|
|
617
|
+
reasons.push(
|
|
618
|
+
`claimed baseline "${claimedDef.id}" is ${claimedProv.tier}${claimedProv.stale ? ` (${claimedProv.ageDays}d stale)` : ''}`
|
|
619
|
+
);
|
|
620
|
+
}
|
|
621
|
+
if (nonDirectOrStaleTop) {
|
|
622
|
+
reasons.push(
|
|
623
|
+
`winning baseline "${top.modelId}" is ${topProv.tier}${topProv.stale ? ` (${topProv.ageDays}d stale)` : ''}`
|
|
624
|
+
);
|
|
625
|
+
}
|
|
626
|
+
baselineProvenanceWarning = `Downgraded mismatch to low_confidence: ${reasons.join('; ')}`;
|
|
627
|
+
claimedMatchStatus = 'low_confidence';
|
|
628
|
+
verdictPath.push('provenance_guard=downgraded_to_low_confidence');
|
|
629
|
+
} else {
|
|
630
|
+
verdictPath.push('status=mismatch');
|
|
631
|
+
}
|
|
632
|
+
} else if (nonDirectOrStaleClaimed) {
|
|
633
|
+
baselineProvenanceWarning = `Reference baseline "${claimedDef.id}" sourced from ${claimedProv.tier}${claimedProv.stale ? ` (${claimedProv.ageDays}d old)` : ''}`;
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
return {
|
|
637
|
+
bankModelCount: bank.models.length,
|
|
638
|
+
usedOutputs: valid.length,
|
|
639
|
+
diagnostics,
|
|
640
|
+
prediction: top.modelId,
|
|
641
|
+
predictionName: top.displayName,
|
|
642
|
+
probability: top.probability,
|
|
643
|
+
lowConfidence,
|
|
644
|
+
familyPrediction: winFam?.family || null,
|
|
645
|
+
familyPredictionName: winFam?.displayName || null,
|
|
646
|
+
familyProbability: winFam?.probability || 0,
|
|
647
|
+
familyProbabilities,
|
|
648
|
+
topCandidates: allResults.slice(0, 5),
|
|
649
|
+
claimedInBank: Boolean(claimedDef),
|
|
650
|
+
claimedCanonicalId: claimedDef?.id || null,
|
|
651
|
+
claimedExpectedFamily,
|
|
652
|
+
claimedModelRank,
|
|
653
|
+
claimedModelProb,
|
|
654
|
+
claimedMatchStatus,
|
|
655
|
+
cvAccuracy: calib.cv_accuracy ?? null,
|
|
656
|
+
topRawH,
|
|
657
|
+
topRawOB,
|
|
658
|
+
topJsSimilarity,
|
|
659
|
+
degenerateRejectedCount,
|
|
660
|
+
duplicateRejectedCount,
|
|
661
|
+
siblingClusterMatched,
|
|
662
|
+
verdictPath,
|
|
663
|
+
baselineProvenanceWarning,
|
|
664
|
+
};
|
|
665
|
+
}
|