gpu-head-to-head
aien-dev/gpu-head-to-head
Brought by drakestapleton
gpu-head-to-head / q35-9b / tools / weight-files.mjs
| 1 | // Verification-only, read-only binary catalogues. Layouts from llama.cpp 7aca0d2e |
| 2 | // gguf-py/gguf/{constants,gguf_reader}.py and safetensors' JSON header. |
| 3 | import fs from 'node:fs'; |
| 4 | import path from 'node:path'; |
| 5 | export function readAt(fd,pos,size) { |
| 6 | if(!Number.isSafeInteger(pos)||!Number.isSafeInteger(size)||pos<0||size<0) throw Error('invalid byte range'); |
| 7 | const data=Buffer.alloc(size);let used=0; |
| 8 | while(used<size) {const n=fs.readSync(fd,data,used,size-used,pos+used);if(!n)throw Error('truncated file');used+=n;} |
| 9 | return data; |
| 10 | } |
| 11 | class Reader { |
| 12 | constructor(file){this.fd=fs.openSync(file,'r');this.size=fs.fstatSync(this.fd).size;this.pos=0;this.cache=Buffer.alloc(0);this.base=0;} |
| 13 | skip(n){if(!Number.isSafeInteger(n)||n<0||this.pos+n>this.size)throw Error('invalid skip');this.pos+=n;} |
| 14 | bytes(n){ |
| 15 | if(!Number.isSafeInteger(n)||n<0||n>65536||this.pos+n>this.size)throw Error('invalid header size'); |
| 16 | if(this.pos<this.base||this.pos+n>this.base+this.cache.length){this.base=this.pos;this.cache=readAt(this.fd,this.pos,Math.min(1048576,this.size-this.pos));} |
| 17 | const b=this.cache.subarray(this.pos-this.base,this.pos-this.base+n);this.pos+=n;return b; |
| 18 | } |
| 19 | u32(){return this.bytes(4).readUInt32LE();} |
| 20 | u64(){const n=this.bytes(8).readBigUInt64LE();if(n>BigInt(Number.MAX_SAFE_INTEGER))throw Error('oversize integer');return Number(n);} |
| 21 | string(keep=true){const n=this.u64();if(!keep){this.skip(n);return null;}return this.bytes(n).toString('utf8');} |
| 22 | value(type,keep=false){ |
| 23 | const widths={0:1,1:1,2:2,3:2,4:4,5:4,6:4,7:1,10:8,11:8,12:8}; |
| 24 | if(type===8)return this.string(keep); |
| 25 | if(type===9){const sub=this.u32(),n=this.u64();if(widths[sub]){this.skip(n*widths[sub]);return null;} |
| 26 | if(sub!==8)throw Error('unsupported metadata array');for(let i=0;i<n;i++)this.string(false);return null;} |
| 27 | if(!widths[type])throw Error('unknown metadata type'); |
| 28 | const b=this.bytes(widths[type]);if(!keep)return null; |
| 29 | if(type!==4)throw Error('alignment must be uint32');return b.readUInt32LE(); |
| 30 | } |
| 31 | } |
| 32 | export function ggufCatalog(file){ |
| 33 | const r=new Reader(file); |
| 34 | try { |
| 35 | if(r.bytes(4).toString()!=='GGUF'||r.u32()!==3)throw Error('expected little-endian GGUF v3'); |
| 36 | const count=r.u64(),kv=r.u64();let alignment=32; |
| 37 | for(let i=0;i<kv;i++){const key=r.string(),type=r.u32();const v=r.value(type,key==='general.alignment');if(key==='general.alignment')alignment=v;} |
| 38 | if(!Number.isSafeInteger(alignment)||alignment<=0||(alignment&(alignment-1)))throw Error('bad alignment'); |
| 39 | const tensors=new Map(); |
| 40 | for(let i=0;i<count;i++){ |
| 41 | const name=r.string(),rank=r.u32();if(!rank||rank>4||tensors.has(name))throw Error('bad tensor descriptor'); |
| 42 | const dims=Array.from({length:rank},()=>r.u64()),type=r.u32(),relative=r.u64(); |
| 43 | if(dims.some(x=>x<=0)||![0,30].includes(type)||relative%alignment)throw Error('unsupported tensor shape/type/offset'); |
| 44 | const bytes=dims.reduce((a,b)=>a*b,1)*(type===30?2:4); |
| 45 | if(!Number.isSafeInteger(bytes))throw Error('tensor too large'); |
| 46 | tensors.set(name,{name,fd:r.fd,file,shape:dims.reverse(),dtype:type===30?'BF16':'F32',bytes,relative}); |
| 47 | } |
| 48 | const padding=r.pos%alignment;const base=padding?r.pos+alignment-padding:r.pos; |
| 49 | let end=base; |
| 50 | for(const t of [...tensors.values()].sort((a,b)=>a.relative-b.relative)){ |
| 51 | t.offset=base+t.relative;if(t.offset<end||t.offset+t.bytes>r.size)throw Error('overlap or truncated tensor');end=t.offset+t.bytes; |
| 52 | } |
| 53 | return {tensors,alignment,dataOffset:base,close:()=>fs.closeSync(r.fd)}; |
| 54 | }catch(e){fs.closeSync(r.fd);throw e;} |
| 55 | } |
| 56 | export function safetensorsCatalog(directory){ |
| 57 | const tensors=new Map(),fds=[]; |
| 58 | try { |
| 59 | for(const file of fs.readdirSync(directory).filter(f=>f.endsWith('.safetensors')).sort()){ |
| 60 | const full=path.join(directory,file),fd=fs.openSync(full,'r');fds.push(fd); |
| 61 | const size=fs.fstatSync(fd).size,nBig=readAt(fd,0,8).readBigUInt64LE(); |
| 62 | if(nBig>16777216n||nBig>BigInt(size-8))throw Error('invalid safetensors header'); |
| 63 | const n=Number(nBig),header=JSON.parse(readAt(fd,8,n).toString('utf8'));let end=8+n; |
| 64 | const entries=[]; |
| 65 | for(const [name,v]of Object.entries(header)){ |
| 66 | if(name==='__metadata__')continue; |
| 67 | if(tensors.has(name)||!['BF16','F32'].includes(v.dtype)||!Array.isArray(v.shape)||v.shape.some(d=>!Number.isSafeInteger(d)||d<=0))throw Error('bad safetensors descriptor'); |
| 68 | if(!Array.isArray(v.data_offsets)||v.data_offsets.length!==2||v.data_offsets.some(d=>!Number.isSafeInteger(d)||d<0))throw Error('bad data offsets'); |
| 69 | const bytes=v.shape.reduce((a,b)=>a*b,1)*(v.dtype==='BF16'?2:4); |
| 70 | const [a,b]=v.data_offsets;if(!Number.isSafeInteger(bytes)||b-a!==bytes||8+n+b>size)throw Error('bad tensor byte length'); |
| 71 | const t={name,fd,file:full,shape:v.shape,dtype:v.dtype,bytes,offset:8+n+a};entries.push(t);tensors.set(name,t); |
| 72 | } |
| 73 | for(const t of entries.sort((a,b)=>a.offset-b.offset)){if(t.offset!==end)throw Error('overlapping or non-contiguous safetensors data');end=t.offset+t.bytes;} |
| 74 | if(end!==size)throw Error('unaccounted safetensors bytes'); |
| 75 | } |
| 76 | if(!tensors.size)throw Error('no safetensors');return {tensors,close:()=>fds.forEach(fd=>fs.closeSync(fd))}; |
| 77 | }catch(e){fds.forEach(fd=>fs.closeSync(fd));throw e;} |
| 78 | } |