Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/gpu-head-to-head/blob/main/q35-9b/tools/ordered-weights.mjs # gpu-head-to-head aien-dev/gpu-head-to-head Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `gpu-head-to-head / q35-9b / tools / ordered-weights.mjs` 149 lines ยท 9853 bytes Raw Blame History 1 // Verification-only byte/address glue. Numeric transforms call seeded Omega. 2 // Converter reference: llama.cpp `7aca0d2e` conversion/qwen.py, lines 404 and 463-655. 3 import fs from 'node:fs'; 4 import {spawnSync} from 'node:child_process'; 5 import {createHash} from 'node:crypto'; 6 import {pathToFileURL} from 'node:url'; 7 import {readAt,ggufCatalog,safetensorsCatalog} from './weight-files.mjs'; 8 const sha=p=>createHash('sha256').update(fs.readFileSync(p)).digest('hex'); 9 10 export function mapping(name,c) { 11 if(name==='lm_head.weight')return {name:'output.weight'}; 12 if(name.startsWith('mtp.')||name.startsWith('model.visual.'))return null; 13 const prefix='model.language_model.'; 14 if(!name.startsWith(prefix))throw Error('unknown HF namespace: '+name); 15 name=name.slice(prefix.length); 16 if(name==='embed_tokens.weight')return {name:'token_embd.weight'}; 17 if(name==='norm.weight')return {name:'output_norm.weight',numeric:'plus1'}; 18 const m=/^layers\.(\d+)\.(.+)$/.exec(name);if(!m||Number(m[1])>=c.num_hidden_layers)throw Error('unknown text tensor'); 19 const base='blk.'+m[1]+'.',tail=m[2]; 20 const simple={'mlp.down_proj.weight':'ffn_down.weight','mlp.up_proj.weight':'ffn_up.weight', 21 'mlp.gate_proj.weight':'ffn_gate.weight','self_attn.q_proj.weight':'attn_q.weight', 22 'self_attn.k_proj.weight':'attn_k.weight','self_attn.v_proj.weight':'attn_v.weight', 23 'self_attn.o_proj.weight':'attn_output.weight','linear_attn.norm.weight':'ssm_norm.weight'}; 24 if(simple[tail])return {name:base+simple[tail]}; 25 const norms={'input_layernorm.weight':'attn_norm.weight','post_attention_layernorm.weight':'post_attention_norm.weight', 26 'self_attn.q_norm.weight':'attn_q_norm.weight','self_attn.k_norm.weight':'attn_k_norm.weight'}; 27 if(norms[tail])return {name:base+norms[tail],numeric:'plus1'}; 28 const qk=2*c.linear_num_key_heads*c.linear_key_head_dim; 29 const linear={ 30 'in_proj_qkv.weight':{target:'attn_qkv.weight',axis:0,prefix:qk,hd:c.linear_value_head_dim}, 31 'in_proj_z.weight':{target:'attn_gate.weight',axis:0,hd:c.linear_value_head_dim}, 32 'in_proj_a.weight':{target:'ssm_alpha.weight',axis:0,hd:1}, 33 'in_proj_b.weight':{target:'ssm_beta.weight',axis:0,hd:1}, 34 'out_proj.weight':{target:'ssm_out.weight',axis:1,hd:c.linear_value_head_dim}, 35 'conv1d.weight':{target:'ssm_conv1d.weight',axis:0,prefix:qk,hd:c.linear_value_head_dim,squeeze:true}, 36 'dt_bias':{target:'ssm_dt.bias',axis:0,hd:1}, 37 'A_log':{target:'ssm_a',axis:0,hd:1,numeric:'negexp'} 38 }; 39 const v=tail.startsWith('linear_attn.')?linear[tail.slice('linear_attn.'.length)]:null; 40 if(!v)throw Error('unmapped text tensor: '+name); 41 return {...v,name:base+v.target}; 42 } 43 export function reorder(data,shape,bytes,c,plan) { 44 if(plan.axis===undefined)return Buffer.from(data); 45 const nk=c.linear_num_key_heads,nv=c.linear_num_value_heads,per=nv/nk,hd=plan.hd,prefix=plan.prefix||0; 46 if(!Number.isInteger(per)||per<=0||!Number.isInteger(hd)||hd<=0)throw Error('invalid head mapping'); 47 if(shape[plan.axis]!==prefix+nv*hd)throw Error('head axis does not match tensor'); 48 const out=Buffer.alloc(data.length); 49 if(plan.axis===0){ 50 const stride=shape.slice(1).reduce((a,b)=>a*b,1)*bytes; 51 data.copy(out,0,0,prefix*stride); 52 for(let v=0;vx.startsWith('--only='))?.slice(7); 89 const expHelper=options.find(x=>x.startsWith('--negexp-helper='))?.slice('--negexp-helper='.length); 90 if(options.some(x=>x!=='--mutant-order'&&!x.startsWith('--only=')&&!x.startsWith('--negexp-helper=')))throw Error('unknown option'); 91 const configFile=hfDir+'/config.json',c=JSON.parse(fs.readFileSync(configFile)).text_config; 92 for(const k of ['num_hidden_layers','linear_num_key_heads','linear_num_value_heads','linear_key_head_dim','linear_value_head_dim']) 93 if(!Number.isSafeInteger(c[k])||c[k]<=0)throw Error('invalid model config'); 94 const hf=safetensorsCatalog(hfDir),g=ggufCatalog(ggufFile); 95 try { 96 const plans=[],covered=new Set(),excludedHF=[]; 97 for(const t of hf.tensors.values()){ 98 const p=mapping(t.name,c);if(!p){excludedHF.push(t.name);continue;} 99 const target=g.tensors.get(p.name);if(!target||covered.has(p.name))throw Error('missing/duplicate named GGUF tensor: '+p.name); 100 const shape=p.squeeze?t.shape.filter(x=>x!==1):t.shape; 101 if(JSON.stringify(shape)!==JSON.stringify(target.shape))throw Error('shape mismatch: '+p.name); 102 covered.add(p.name);plans.push({h:t,g:target,plan:p,shape}); 103 } 104 const excludedGGUF=[]; 105 for(const name of g.tensors.keys())if(!covered.has(name)){ 106 const m=/^blk\.(\d+)\./.exec(name); 107 if(name.startsWith('nextn.')||(m&&Number(m[1])===c.num_hidden_layers))excludedGGUF.push(name); 108 else throw Error('unaccounted GGUF tensor: '+name); 109 } 110 const report={kind:'ordered_weight_verification',source:'llama.cpp7aca0d2e conversion/qwen.py', 111 numeric:expHelper?'seeded Omega plus-one; pinned ATen CPU exp oracle':'seeded Omega bin/sexp units via I/O-only glue', 112 numericBinarySha256:sha(numeric),expHelper:expHelper?{path:expHelper,sha256:sha(expHelper)}:null, 113 configSha256:sha(configFile),mutantOrder:mutant,only:only||null, 114 catalogue:{hf:hf.tensors.size,gguf:g.tensors.size,textPlans:plans.length,excludedHF,excludedGGUF},rows:[],expEvidence:[]}; 115 const selected=only?plans.filter(p=>p.g.name===only):plans;if(!selected.length)throw Error('empty tensor selection'); 116 for(const {h,g,plan,shape}of selected){ 117 let mismatch; 118 if(plan.axis===undefined&&!plan.numeric&&h.dtype===g.dtype)mismatch=compareDirect(h,g); 119 else{ 120 let data=readAt(h.fd,h.offset,h.bytes); 121 if(h.dtype!==g.dtype){if(h.dtype!=='BF16'||g.dtype!=='F32')throw Error('unhandled numeric format');data=widenBf16(data);} 122 const input=reorder(data,shape,g.dtype==='BF16'?2:4,c,mutant?{...plan,axis:undefined}:plan); 123 let expected=input; 124 if(plan.numeric){ 125 if(g.dtype!=='F32')throw Error('numeric transform requires F32'); 126 const helper=plan.numeric==='negexp'&&expHelper?expHelper:numeric; 127 const result=spawnSync(helper,[plan.numeric],{input,timeout:60000,maxBuffer:`1048576`}); 128 if(result.status!==0||result.stdout.length!==input.length)throw Error('numeric transform failed: '+result.status); 129 expected=result.stdout; 130 } 131 const actual=readAt(g.fd,g.offset,g.bytes);mismatch=difference(expected,actual); 132 if(plan.numeric==='negexp')report.expEvidence.push({tensor:g.name, 133 inputBits:Array.from({length:input.length/4},(_,i)=>input.readUInt32LE(i*4)), 134 referenceBackend:expHelper?'pinned ATen CPU':'seeded Omega sexp', 135 expectedBits:Array.from({length:expected.length/4},(_,i)=>expected.readUInt32LE(i*4)), 136 actualBits:Array.from({length:actual.length/4},(_,i)=>actual.readUInt32LE(i*4))}); 137 } 138 report.rows.push({hf:h.name,gguf:g.name,shape,hfType:h.dtype,ggufType:g.dtype, 139 permutationAxis:plan.axis??null,numeric:plan.numeric||null,status:mismatch?'MISMATCH':'EXACT',mismatch}); 140 } 141 report.status=report.rows.some(r=>r.status!=='EXACT')?'MISMATCH':only?'PARTIAL_SELECTION_EXACT':'ALL_NAMED_TEXT_TENSORS_EXACT'; 142 fs.writeFileSync(out,JSON.stringify(report,null,2)+'\n',{flag:'wx'}); 143 console.log(JSON.stringify({status:report.status,checked:report.rows.length, 144 mismatches:report.rows.filter(r=>r.status!=='EXACT').map(r=>({name:r.gguf,transform:r.numeric,axis:r.permutationAxis,mismatch:r.mismatch}))})); 145 if(report.status==='MISMATCH')process.exitCode=1; 146 }finally{hf.close();g.close();} 147 } 148 if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href) 149 try{main();}catch(e){console.error(e.message);process.exitCode=1;}