interplane.Get Omega
Read in your language

gpu-head-to-head

aien-dev/gpu-head-to-head

Brought by drakestapleton

branch main Branches Tags History

gpu-head-to-head / q35-9b / tools / token-audit.mjs

96 lines · 6325 bytes Raw Blame History
1// Verification-only: pinned CPU llama-tokenize against the recorded HF oracle.
2// Counts/positions are retained; rates and statistics are calculated in Wolfram.
3import fs from 'node:fs';
4import {spawnSync} from 'node:child_process';
5import {createHash} from 'node:crypto';
6import {pathToFileURL} from 'node:url';
7const hash=p=>createHash('sha256').update(fs.readFileSync(p)).digest('hex');
8const jsonl=p=>fs.readFileSync(p,'utf8').split('\n').filter(x=>x.trim()).map(JSON.parse);
9
10export function compareTokens(a,b) {
11 for(const ids of [a,b])
12 if(!Array.isArray(ids)||ids.some(x=>!Number.isInteger(x)||x<0)) throw new Error('invalid token IDs');
13 let prefix=0;
14 while(prefix<a.length && prefix<b.length && a[prefix]===b[prefix]) prefix++;
15 const identical=prefix===a.length && prefix===b.length;
16 return {length_a:a.length,length_b:b.length,common_prefix:prefix,identical,
17 first_div:identical?null:prefix,token_a:a[prefix]??null,token_b:b[prefix]??null};
18}
19export function uniqueRows(rows) {
20 const map=new Map();
21 for(const row of rows) {
22 if(typeof row.prompt_id!=='string'||map.has(row.prompt_id)) throw new Error('missing or duplicate prompt ID');
23 map.set(row.prompt_id,row);
24 }
25 return map;
26}
27export function findObservation(records,prompt,comparison) {
28 if(comparison.identical || comparison.token_a===null || comparison.token_b===null) return null;
29 return records.find(r=>r.prompt_id===prompt && r.first_div===comparison.first_div &&
30 r.oracle_tok===comparison.token_a && r.arm_tok===comparison.token_b &&
31 r.oracle_len===comparison.length_a && Number.isFinite(r.logit_gap)) || null;
32}
33function main() {
34 const [tokenizer,gguf,out,oraclePath,tiesCSV,...armArgs]=process.argv.slice(2);
35 if(!tokenizer||!gguf||!out||!oraclePath||!tiesCSV||!armArgs.length) throw new Error('missing arguments');
36 if(fs.existsSync(out)) throw new Error('output already exists');
37 const prompts=jsonl(new URL('../../prompts/decode.jsonl',import.meta.url));
38 const oracle=uniqueRows(jsonl(oraclePath));
39 if(prompts.length!==oracle.size || prompts.some(p=>!oracle.has(p.id))) throw new Error('oracle prompt coverage mismatch');
40 const log=fs.openSync(out+'.tokenizer.log','wx');
41 const tokens=text=>{
42 if(typeof text!=='string') throw new Error('missing output text');
43 const run=spawnSync(tokenizer,['-m',gguf,'--stdin','--ids','--no-bos','--no-parse-special','--no-escape'],
44 {input:text,encoding:'utf8',maxBuffer:16777216,timeout:60000});
45 fs.writeSync(log,run.stderr||'');
46 if(run.status!==0) throw new Error('tokenizer failed: '+run.status);
47 const ids=JSON.parse(run.stdout);
48 compareTokens(ids,ids); // Validate IDs even when no comparison follows.
49 return ids;
50 };
51 try {
52 const report={kind:'token_audit_not_final_model_qualification',
53 tokenizer:{path:tokenizer,sha256:hash(tokenizer),source:'7aca0d2ea8d92b56911233b822db01f9fbb1ae50',backend:'CPU-only'},
54 oracle:{path:oraclePath,sha256:hash(oraclePath)},tieSources:[],oracleRoundtrip:[],arms:{},pairs:{}};
55 const observations=[];
56 for(const path of tiesCSV.split(',')) {
57 report.tieSources.push({path,sha256:hash(path)});observations.push(...jsonl(path));
58 }
59 for(const [id,row] of oracle) report.oracleRoundtrip.push({prompt_id:id,...compareTokens(row.ids,tokens(row.text))});
60 report.tokenizerValidatedAgainstRecordedHF=report.oracleRoundtrip.every(r=>r.identical);
61 const allTokens={};
62 for(const arg of armArgs) {
63 const equal=arg.indexOf('=');if(equal<1) throw new Error('invalid arm argument');
64 const arm=arg.slice(0,equal),path=arg.slice(equal+1);
65 if(allTokens[arm]) throw new Error('duplicate arm');
66 const input=uniqueRows(jsonl(path));
67 if(input.size!==oracle.size || [...oracle.keys()].some(id=>!input.has(id))) throw new Error('arm prompt coverage mismatch');
68 allTokens[arm]={};
69 report.arms[arm]={path,sha256:hash(path),rows:[]};
70 for(const [id,reference] of oracle) {
71 const row=input.get(id);
72 if(row.error!==null || row.http_status!==200 || row.warmup || row.metric!=='agree') throw new Error('invalid correctness row');
73 const ids=tokens(row.text);allTokens[arm][id]=ids;
74 const comparison=compareTokens(reference.ids,ids);
75 const observation=report.tokenizerValidatedAgainstRecordedHF?findObservation(observations,id,comparison):null;
76 report.arms[arm].rows.push({prompt_id:id,...comparison,
77 recordedUsage:row.usage?.completion_tokens??null,
78 priorObservation:observation,
79 observationStatus:comparison.identical?'IDENTICAL':observation?'EXACT_PRIOR_TUPLE':'NEEDS_ORACLE_OBSERVATION'});
80 }
81 }
82 const names=Object.keys(allTokens);
83 for(let a=0;a<names.length;a++) for(let b=a+1;b<names.length;b++)
84 report.pairs[names[a]+'-'+names[b]]=[...oracle.keys()].map(id=>({prompt_id:id,
85 ...compareTokens(allTokens[names[a]][id],allTokens[names[b]][id])}));
86 report.notes=['Recorded prior logit observations are reused only for exact prompt/position/token tuples against the same frozen HF oracle.',
87 'Matching prior scores are observations, not proof of all-model numerical equivalence.',
88 'Uncovered divergences remain unverified. No speed or model qualification verdict follows from request success alone.'];
89 fs.writeFileSync(out,JSON.stringify(report,null,2)+'\n',{flag:'wx'});
90 console.log(JSON.stringify({tokenizerValidatedAgainstRecordedHF:report.tokenizerValidatedAgainstRecordedHF,
91 arms:Object.fromEntries(Object.entries(report.arms).map(([a,v])=>[a,v.rows.map(r=>({id:r.prompt_id,status:r.observationStatus,first:r.first_div,gap:r.priorObservation?.logit_gap??null}))]))}));
92 if(!report.tokenizerValidatedAgainstRecordedHF) process.exitCode=1;
93 } finally { fs.closeSync(log); }
94}
95if(process.argv[1] && import.meta.url===pathToFileURL(process.argv[1]).href)
96 try { main(); } catch(error) {console.error(error.message);process.exitCode=1;}