gpu-engine 0.0.0-stage → 0.0.1
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 +21 -0
- package/README.md +96 -2
- package/SPEC.md +988 -0
- package/THIRD_PARTY_NOTICES.md +29 -0
- package/dist/cli.d.mts +1 -0
- package/dist/cli.mjs +4 -0
- package/dist/harness.d.mts +132 -0
- package/dist/harness.mjs +1 -0
- package/dist/index.d.mts +98 -0
- package/dist/index.mjs +1 -0
- package/dist/load-o_thEAKC.mjs +258 -0
- package/dist/scaffold-CY5xhy-V.mjs +106 -0
- package/dist/types-BwigqFwr.d.mts +868 -0
- package/docs/apps.md +108 -0
- package/docs/cli.md +126 -0
- package/docs/data.md +101 -0
- package/docs/diagnostics.md +509 -0
- package/docs/harness.md +191 -0
- package/docs/layers.md +249 -0
- package/docs/measurements/auto-threshold.json +335 -0
- package/docs/measurements/auto-threshold.md +56 -0
- package/docs/measurements/real-gpu-2026-11-22.json +4718 -0
- package/docs/measurements/real-gpu-2026-11-22.md +75 -0
- package/docs/runtime.md +112 -0
- package/docs/sealed-test-set.md +107 -0
- package/docs/weights-format.md +138 -0
- package/llms.txt +24 -0
- package/package.json +73 -3
- package/skills/gpu-engine/SKILL.md +117 -0
- package/templates/common/AGENTS.md +27 -0
- package/templates/common/github/workflows/ci.yml +35 -0
- package/templates/common/gitignore +3 -0
- package/templates/common/package.template.json +27 -0
- package/templates/common/tsconfig.template.json +17 -0
- package/templates/pooled/NEW_MODEL_NAME.eval.ts +93 -0
- package/templates/pooled/NEW_MODEL_NAME.model.ts +11 -0
- package/templates/pooled/SPEC.md +31 -0
- package/templates/pooled/src/decode.ts +10 -0
- package/templates/pooled/src/index.ts +44 -0
- package/templates/pooled/src/weights.ts +4 -0
- package/templates/retrieve/NEW_MODEL_NAME.eval.ts +149 -0
- package/templates/retrieve/NEW_MODEL_NAME.model.ts +12 -0
- package/templates/retrieve/SPEC.md +33 -0
- package/templates/retrieve/data/table.jsonl +16 -0
- package/templates/retrieve/src/decode.ts +9 -0
- package/templates/retrieve/src/index.ts +45 -0
- package/templates/retrieve/src/table.ts +21 -0
- package/templates/retrieve/src/weights.ts +4 -0
- package/templates/tag/NEW_MODEL_NAME.eval.ts +114 -0
- package/templates/tag/NEW_MODEL_NAME.model.ts +11 -0
- package/templates/tag/SPEC.md +31 -0
- package/templates/tag/src/decode.ts +25 -0
- package/templates/tag/src/index.ts +44 -0
- package/templates/tag/src/weights.ts +4 -0
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
const e={DEFINE_NET_ORDER:{why:"`net` must start with exactly one `embed` layer, and `embed` may not appear anywhere else.",fix:"Put one `layers.embed({ size })` first in `net` and remove any other `embed` layer."},DEFINE_LAYER_SHAPE:{why:`A layer has a size, tap count or activation it cannot run with.`,fix:"Use positive integer sizes, an odd `taps` of at least 1, and an activation from `relu`, `tanh` or `none`."},DEFINE_FEATURE_ROW:{why:"The token input cannot be featurized: it is not `features.tokens(...)`, `max` or `buckets` is not a positive integer, `k` is outside 1 to `buckets`, `rows` is empty or has an unknown kind, a flag name is empty, or a shape row or a flag name repeats.",fix:"Give `features.tokens` a positive integer `max` and at least one row, keep `k` between 1 and `buckets`, use one `features.shape()` and distinct non-empty flag names."},DEFINE_HEAD_LABELS:{why:"The head cannot be built from its labels: fewer than two labels, a duplicate label, or both or neither of `labels` and `outputs`.",fix:"Give the head two or more distinct `labels`, or for a pooled values head only `outputs`."},DEFINE_BUDGET_EXCEEDED:{why:`The layers already exceed a budget before any training: multiply-adds per token, or a packed int6 size that cannot fit the Brotli budget.`,fix:"Shrink a layer (embed size, scan size, dense size, hash buckets) or raise the budget in `budgets`."},DEFINE_QUANT_INVALID:{why:"`quant` is not int6 quantization with `qatFrom` a finite share of the run from 0 to 1.",fix:"Write `quant: int6({ qatFrom })` with `qatFrom` from 0 to 1, such as 0.7, or leave `quant` out for float32 weights."},DEFINE_BUDGET_INVALID:{why:`A budget is not a positive integer, so no size or multiply-add count can be compared against it.`,fix:"Give `budgets.brotliBytes` and `budgets.macsPerToken` positive integers, such as `{ brotliBytes: 5_000, macsPerToken: 3_200 }`."},DEFINE_NAME_INVALID:{why:"The model name names the weights file, `weights/<name>.bin`, and the package, so it must be a lowercase name that cannot leave the `weights/` folder.",fix:"Use lowercase letters, digits and `-`, starting with a letter, at most 64 characters, such as `unit-phrases`."},DEFINE_DATA_INVALID:{why:"`data` cannot generate or check the sets: `seed` is not a safe integer, a `minSize` count is not a positive integer, or a `generate` entry is not a function.",fix:"Write `defineDataset({ seed: 1, minSize: { train, dev, test } })` with positive integer counts, and give `generate` only functions `(random) => examples`."},DEFINE_TRAIN_INVALID:{why:"`train` cannot run: `seeds` is empty, repeats a seed or holds a non-integer, `epochs` or `batch` is not a positive integer, `learningRate` or `budgetSeconds` is not a finite number above 0, `warmup` is outside 0 up to 1, or `negatives` is not a positive integer (a retrieve head needs it).",fix:"Write every option out, such as `{ seeds: [1, 2, 3], epochs: 20, batch: 32, learningRate: 0.01, warmup: 0.1, budgetSeconds: 40 }`, and add `negatives: 8` for a retrieve head."},DEFINE_GATE_INVALID:{why:"`gate` cannot compare scores: `floors` is not `promoted`, or `noise` is not a finite number of at least 0.",fix:"Write `gate: { floors: 'promoted', noise }` with `noise` at or above the measured seed spread, such as 0.05."},DEFINE_PARITY_INVALID:{why:"`parity` is not an object, or its `tolerance` is not a finite number of at least 0, so no logit difference can be compared with it.",fix:"Write `parity: { tolerance: 1e-3 }`, and raise it only with a measured reason."},DEFINE_SHIP_INVALID:{why:"`ship` is present, and `brotliBytes` is not a positive integer or `files` is not a non-empty list of paths.",fix:"Write `ship: { brotliBytes: 40_000, files: ['dist/index.mjs'] }`, or leave `ship` out."},DEFINE_EVAL_INVALID:{why:"The eval cannot score: `metric` is not a function, `decode` is not a function, or `baselines` is not an object of functions.",fix:"Give `metric: (pred, gold) => number`, an optional `decode: (raw, input) => result`, and `baselines` as named functions `(input) => result` (`{}` for none)."},DEFINE_SET_FOLDER:{why:"Each set must live in its own folder: train in `data/train/`, dev in `data/dev/`, test in `data/test/`, each path written plainly, without `.` or `..` segments. The retrieve table lives inside the package, outside those folders.",fix:"Move the files and point `sets` at `data/train/*.jsonl`, `data/dev/*.jsonl` and `sealed('data/test/*.jsonl')`."},DEFINE_EVAL_MODEL:{why:"`defineEval` takes the model definition first, so it can type the decode, the baselines and the metric from the head, and the eval definition second.",fix:"Import the model file's default export in the eval file and write `export default defineEval(model, { ... })`."},WEIGHTS_FORMAT_INVALID:{why:`The bytes are not a gpu-engine weights file: the magic, a length or a tensor record is wrong.`,fix:"Load the `weights/<name>.bin` file written by `gpu-engine promote`, or re-export it with the byte layout in SPEC.md section 5."},WEIGHTS_VERSION_UNSUPPORTED:{why:`The weights file uses a format version this runtime does not read.`,fix:`Upgrade gpu-engine, or re-export the weights with the format version this runtime reads.`},WEIGHTS_DEFINITION_MISMATCH:{why:`The definition hash or a tensor shape in the file does not match the definition the file carries.`,fix:"Load weights trained from this definition. In a model package a changed model file is expected while tuning: run `gpu-engine loop` to train a candidate from it, and promote once when the tuning is done, not after every try."},RUN_BACKEND_UNAVAILABLE:{why:`The requested backend cannot run here: WebGPU is missing or no adapter was found.`,fix:"Use `backend: 'auto'` or `'cpu'`, or pass a WebGPU entry point as `gpu` (in Node, the `webgpu` package)."},RUN_GPU_FAILED:{why:`The GPU device was lost or reported a validation error while running the model.`,fix:"Retry with `backend: 'cpu'`, and run `gpu-engine parity` to check the WGSL output."},RUN_INPUT_INVALID:{why:"The input is not a string or a `{ text, flags }` object, or a flag list does not have one entry per token.",fix:"Pass a string, or `{ text, flags }` where each flag array has one boolean per token of `text`."},RUN_OUTPUT_NONFINITE:{why:"The model produced a logit or a score that is not a finite number, so decoding it would give a label chosen by accident or `Infinity`.",fix:"Check the weights file with `gpu-engine parity`; weights this large overflow float32, so retrain with a lower `train.learningRate`."},RUN_FAILED:{why:`The model loaded, but running it failed for a reason no other run code covers, such as an op that throws.`,fix:'Run `gpu-engine inspect "<text>"` on the same input to see which step fails, and report it with the weights file.'},RUN_MODEL_DESTROYED:{why:"The model was destroyed with `model.destroy()`, which freed its GPU buffers and device, so it cannot run again.",fix:"Call `destroy()` only when the model is no longer needed, or load the weights again with `loadModel`."},RUN_TABLE_MISSING:{why:`A retrieve model needs a table of rows to score the input against.`,fix:"Pass `table` to `loadModel`: the `{ id, text }` rows the model ranks."},DATA_ROW_INVALID:{why:"A data row is not valid JSON or does not have the `{ input, gold }` shape the head needs.",fix:"Write one JSON object per line with `input` (text or `{ text, flags }`) and `gold` in the shape of the head."},DATA_LABEL_UNKNOWN:{why:`A gold label is not one of the head labels.`,fix:"Fix the label in the data, or add it to the head `labels` in the model file."}},t=[`WEIGHTS_FORMAT_INVALID`,`WEIGHTS_VERSION_UNSUPPORTED`,`WEIGHTS_DEFINITION_MISMATCH`,`RUN_BACKEND_UNAVAILABLE`,`RUN_GPU_FAILED`,`RUN_INPUT_INVALID`,`RUN_OUTPUT_NONFINITE`,`RUN_FAILED`,`RUN_MODEL_DESTROYED`,`RUN_TABLE_MISSING`];function n(e){return t.some(t=>t===e)}function r(t,n,r={}){let{why:i,fix:a}=e[t];return{code:t,message:n,why:i,fix:a,...r}}var i=class extends Error{diagnostic;constructor(e){super(`${e.code}: ${e.message}`),this.name=`GpuEngineError`,this.diagnostic=e}get code(){return this.diagnostic.code}};function a(e,t,n){return new i(r(e,t,n))}new TextEncoder;function o(e){return 2166136261+Math.imul(e,2654435769)>>>0}function s(e,t){let n=t>>>0;for(let t of e)n=Math.imul(n^t,16777619);return n>>>0}function c(e){let t=t=>s(e,o(t)).toString(16).padStart(8,`0`);return t(0)+t(1)}const l=/^\p{L}$/u,u=/^\p{Nd}$/u,d=/^\p{M}$/u,f=/^\p{White_Space}$/u;function p(e){return l.test(e)?`letter`:u.test(e)?`digit`:d.test(e)?`mark`:f.test(e)?`space`:`other`}function m(e){let t=[],n,r=0,i=0,a=()=>{n!==void 0&&t.push({text:e.slice(r,i),start:r,end:i}),n=void 0};for(let t of e){let e=p(t);(n===void 0||e!==`mark`&&(e!==n||e===`other`))&&(a(),e!==`space`&&(n=e===`mark`?`letter`:e,r=i)),i+=t.length}return a(),t}const h={lower:0,upper:1,title:2,mixed:3,caseless:4,digits:5,punctuation:6,other:7},g=/^[\p{L}\p{M}]$/u,_=/^\p{Nd}$/u,v=/^\p{P}$/u,y=/^[\p{Lu}\p{Lt}]$/u,b=/^\p{Ll}$/u,x=new TextEncoder,S=/* @__PURE__ */ new WeakMap;function ee(e){return typeof e==`number`&&Number.isInteger(e)&&e>0}function C(e){return a(`DEFINE_FEATURE_ROW`,e)}function te(e,t){let n=e.kind;switch(e.kind){case`shape`:return{rows:13,slots:2};case`hash`:if(!ee(e.buckets))throw C(`rows[${t}].buckets is not a positive integer`);if(!Number.isInteger(e.k)||e.k<1||e.k>e.buckets)throw C(`rows[${t}].k is ${e.k}, expected an integer from 1 to ${e.buckets}`);return{rows:e.buckets,slots:e.k};case`flag`:if(typeof e.name!=`string`||e.name===``)throw C(`rows[${t}] has an empty flag name`);return{rows:1,slots:1};default:throw C(`rows[${t}] has the unknown kind '${n}'`)}}function ne(e){let t=typeof e==`object`&&e?e.kind:void 0;if(t!==`tokens`)throw C(`input.kind is '${String(t)}', expected 'tokens'`);if(!Array.isArray(e.rows))throw C(`rows is not an array`);if(!ee(e.max))throw C(`max is ${String(e.max)}, expected a positive integer`);if(e.rows.length===0)throw C(`rows is empty`);let n=/* @__PURE__ */ new Set,r=0,i=0,a=0,o=e.rows.map((e,t)=>{let o=te(e,t);if(e.kind===`shape`&&++r>1)throw C(`rows has more than one shape row`);if(e.kind===`flag`){if(n.has(e.name))throw C(`rows has the flag '${e.name}' twice`);n.add(e.name)}let s={feature:e,row:i,rows:o.rows,slot:a,slots:o.slots};return i+=o.rows,a+=o.slots,s});return{slots:a,rows:i,blocks:o}}function w(e){let t=S.get(e);return t===void 0&&(t=ne(e),S.set(e,t)),t}function re(e){let t=Array.from(e),n=t[0]??``;if(_.test(n))return h.digits;if(!g.test(n))return v.test(n)?h.punctuation:h.other;let r=0,i=0,a=!1;for(let e of t){let t=y.test(e);(t||b.test(e))&&(r===0&&i===0&&(a=t),t?r++:i++)}return r===0&&i===0?h.caseless:r===0?h.lower:i===0?h.upper:a&&r===1?h.title:h.mixed}function ie(e){let t=Array.from(e).length;return t<=2?Math.max(t-1,0):t<=4?2:t<=7?3:4}function T(e){return a(`RUN_INPUT_INVALID`,e)}function ae(e){if(typeof e==`string`)return{text:e,flags:{}};if(typeof e!=`object`||!e||typeof e.text!=`string`)throw T(`the input is not a string or a { text, flags } object`);let{flags:t}=e;if(t===void 0)return{text:e.text,flags:{}};if(typeof t!=`object`||!t||Array.isArray(t))throw T(`flags is not an object of boolean lists`);return{text:e.text,flags:t}}function oe(e){return m(ae(e).text).length}function se(e,t,n){let r=new Set(t.blocks.flatMap(({feature:e})=>e.kind===`flag`?[e.name]:[]));for(let[t,i]of Object.entries(e)){if(!r.has(t))throw T(`flags has '${t}', which the definition does not declare`);if(!Array.isArray(i)||i.length!==n||i.some(e=>typeof e!=`boolean`))throw T(`flag '${t}' has ${Array.isArray(i)?`${i.length} entries`:`no list`}, expected ${n} booleans, one per token`)}}function ce(e,t,n,r,i){for(let a=0;a<n.slots;a++){let c=s(r,o(a))%i;for(;e.subarray(t,t+a).includes(n.row+c);)c=(c+1)%i;e[t+a]=n.row+c}}function le(e,t,n,r,i,a){let o;for(let s of n.blocks){let n=t+s.slot,{feature:c}=s;c.kind===`shape`?(e[n]=s.row+re(r.text),e[n+1]=s.row+8+ie(r.text)):c.kind===`hash`?(o??=x.encode(r.text.toLowerCase().normalize(`NFC`)),ce(e,n,s,o,c.buckets)):Object.hasOwn(i,c.name)&&i[c.name]?.[a]===!0&&(e[n]=s.row)}}function E(e,t){let n=w(e),{text:r,flags:i}=ae(t),a=m(r);se(i,n,a.length);let o=Math.min(a.length,e.max),{slots:s}=n,c=new Int32Array(o*s).fill(-1);for(let[e,t]of a.slice(0,o).entries())le(c,e*s,n,t,i,e);return{count:o,slots:s,rows:c}}const ue=new TextEncoder,de=[`relu`,`tanh`,`none`],fe=/^[a-z][a-z0-9-]{0,63}$/u;function pe(e){if(!(typeof e==`string`&&fe.test(e)))throw a(`DEFINE_NAME_INVALID`,`name is ${typeof e==`string`?`'${e}'`:String(e)}, expected lowercase letters, digits and '-', starting with a letter, at most 64 characters`)}function me(e){let{name:t,input:n,net:r,head:i,quant:a}=e;return a===void 0?{name:t,input:n,net:r,head:i}:{name:t,input:n,net:r,head:i,quant:a}}function D(e){return Array.isArray(e)?e.map(D):typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>[e,D(t)]))}function he(e){return JSON.stringify(D(me(e)))}function O(e){return c(ue.encode(he(e)))}function k(e,t){return typeof e==`object`&&e?Object.entries(e).find(([e])=>e===t)?.[1]:void 0}function A(e){return String(k(e,`kind`))}function j(e){return typeof e==`number`&&Number.isInteger(e)&&e>0}function ge(e,t){let n=`net[${t}]`;switch(e.kind){case`embed`:case`biScan`:if(!j(e.size))throw a(`DEFINE_LAYER_SHAPE`,`${n} ${e.kind} has size ${String(e.size)}`);return;case`dense`:if(!j(e.size))throw a(`DEFINE_LAYER_SHAPE`,`${n} dense has size ${String(e.size)}`);if(!de.includes(e.activation))throw a(`DEFINE_LAYER_SHAPE`,`${n} dense has activation '${e.activation}'`);return;case`conv`:if(!j(e.taps)||e.taps%2==0)throw a(`DEFINE_LAYER_SHAPE`,`${n} conv has taps ${String(e.taps)}`);return;default:throw a(`DEFINE_LAYER_SHAPE`,`${n} has kind '${A(e)}'`)}}function _e(e){if(!Array.isArray(e)||e.length<2)throw a(`DEFINE_HEAD_LABELS`,`head.labels has ${Array.isArray(e)?e.length:0} labels`);let t=/* @__PURE__ */ new Set;for(let[n,r]of e.entries()){if(typeof r!=`string`||r===``)throw a(`DEFINE_HEAD_LABELS`,`head.labels[${n}] is not a non-empty string`);if(t.has(r))throw a(`DEFINE_HEAD_LABELS`,`head.labels[${n}] repeats an earlier label`);t.add(r)}}function ve(e){let t=k(e,`labels`),n=k(e,`outputs`);switch(e.kind){case`tag`:if(n!==void 0)throw a(`DEFINE_HEAD_LABELS`,"a tag head has `outputs`");_e(t);return;case`pooled`:if(t===void 0==(n===void 0))throw a(`DEFINE_HEAD_LABELS`,"a pooled head needs exactly one of `labels` and `outputs`");if(t!==void 0)_e(t);else if(!j(n))throw a(`DEFINE_HEAD_LABELS`,`head.outputs is ${String(n)}`);return;case`retrieve`:if(!j(e.size))throw a(`DEFINE_LAYER_SHAPE`,`the retrieve head has size ${String(e.size)}`);return;default:throw a(`DEFINE_HEAD_LABELS`,`head.kind is '${A(e)}'`)}}function ye(e){if(!Object.hasOwn(e,`quant`)||e.quant===void 0)return;let t=e.quant;if(typeof t!=`object`||!t)throw a(`DEFINE_QUANT_INVALID`,`quant is ${String(t)}`);let n=k(t,`kind`);if(n!==`int6`)throw a(`DEFINE_QUANT_INVALID`,`quant.kind is '${String(n)}', expected 'int6'`);let r=k(t,`qatFrom`);if(typeof r!=`number`||!Number.isFinite(r)||r<0||r>1)throw a(`DEFINE_QUANT_INVALID`,`quant.qatFrom is ${String(r)}, expected a number from 0 to 1`)}function be(e){pe(e.name),ye(e);let{net:t,head:n}=e;if(!Array.isArray(t)||t.length===0)throw a(`DEFINE_NET_ORDER`,"`net` is empty");for(let[e,n]of t.entries()){if(e===0&&n.kind!==`embed`)throw a(`DEFINE_NET_ORDER`,`net[0] is '${n.kind}', expected 'embed'`);if(e>0&&n.kind===`embed`)throw a(`DEFINE_NET_ORDER`,`net[${e}] is a second 'embed'`);ge(n,e)}if(typeof n!=`object`||!n)throw a(`DEFINE_HEAD_LABELS`,"`head` is missing");ve(n)}function xe(e,t){return[{name:`weight`,shape:[e,t]},{name:`bias`,shape:[e]}]}function Se(e,t,n){switch(e.kind){case`embed`:return{outWidth:e.size,tensors:[{name:`table`,shape:[n.rows,e.size]},{name:`bias`,shape:[e.size]}],macs:n.slots*e.size};case`conv`:return{outWidth:t,tensors:[{name:`kernel`,shape:[e.taps,t]},{name:`bias`,shape:[t]}],macs:e.taps*t};case`biScan`:return{outWidth:2*e.size,tensors:[`forward`,`backward`].flatMap(n=>[{name:`${n}.gateWeight`,shape:[e.size,t]},{name:`${n}.gateBias`,shape:[e.size]},{name:`${n}.candidateWeight`,shape:[e.size,t]},{name:`${n}.candidateBias`,shape:[e.size]}]),macs:4*e.size*t+2*e.size};case`dense`:return{outWidth:e.size,tensors:xe(e.size,t),macs:e.size*t};case`tag`:return{outWidth:e.labels.length,tensors:xe(e.labels.length,t),macs:t*e.labels.length};case`pooled`:case`retrieve`:{let n=e.kind===`retrieve`?e.size:`labels`in e?e.labels.length:e.outputs;return{outWidth:n,tensors:xe(n,2*t),macs:2*t+2*t*n}}default:throw Error(`no shape for op kind '${A(e)}'`)}}function Ce(e,t,n,r,i){let a=Se(e,t,n),o=i,s=a.tensors.map(t=>{let n=t.shape.reduce((e,t)=>e*t,1),i={name:`${r}.${e.kind}.${t.name}`,shape:t.shape,offset:o,length:n};return o+=n,i});return{op:{index:r,spec:e,inWidth:t,outWidth:a.outWidth,tensors:s,macs:a.macs},end:o}}function M(e){be(e);let t=me(e),n=w(t.input),r=[...t.net,t.head],i=n.slots,a=0,o=0;return{definition:t,layout:n,ops:r.map((e,t)=>{let{op:r,end:s}=Ce(e,i,n,t,a);return i=r.outWidth,a=s,o+=r.macs,r}),size:a,macsPerToken:o,slots:n.slots,rows:n.rows,maxTokens:t.input.max,outWidth:i,hash:O(t)}}function N(e){return e.ops.flatMap(e=>e.tensors)}function we(e){return N(e).filter(e=>!e.name.endsWith(`.embed.table`)).reduce((e,t)=>e+Math.ceil(t.length*6/8),0)}function Te(e,t){for(let e of[`brotliBytes`,`macsPerToken`]){let n=k(t,e);if(!j(n))throw a(`DEFINE_BUDGET_INVALID`,`budgets.${e} is ${typeof n==`string`?`'${n}'`:String(n)}, expected a positive integer`)}if(e.macsPerToken>t.macsPerToken)throw a(`DEFINE_BUDGET_EXCEEDED`,`the layers need ${e.macsPerToken} multiply-adds per token, budgets.macsPerToken is ${t.macsPerToken}`);let n=we(e);if(n>2*t.brotliBytes)throw a(`DEFINE_BUDGET_EXCEEDED`,`the tensors after the embedding table pack to ${n} int6 bytes, more than 2 times budgets.brotliBytes (${t.brotliBytes}), and Brotli shrinks packed int6 to no less than about 0.57 of its size`)}function Ee(e){return Te(M(e),e.budgets),e}function De(e){let t=[];for(let n of e.split(`/`))n!==``&&n!==`.`&&(n===`..`&&t.length>0&&t.at(-1)!==`..`?t.pop():t.push(n));return t.join(`/`)}function P(e){return typeof e==`string`?`'${e}'`:Array.isArray(e)?`[${e.map(P).join(`, `)}]`:typeof e==`object`&&e?`an object`:String(e)}function F(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function I(e,t){throw a(e,t)}const L=e=>typeof e==`number`&&Number.isInteger(e)&&e>0,Oe=e=>typeof e==`number`&&Number.isFinite(e)&&e>0,R=e=>typeof e==`number`&&Number.isFinite(e)&&e>=0;function ke(e,t=!1){if(!F(e))return I(`DEFINE_TRAIN_INVALID`,`train is ${P(e)}, expected the training options`);let{seeds:n,epochs:r,batch:i,learningRate:a,warmup:o,budgetSeconds:s,negatives:c}=e;Array.isArray(n)&&n.length!==0||I(`DEFINE_TRAIN_INVALID`,`train.seeds is ${P(n)}, expected at least one seed`);let l=Array.isArray(n)?n:[];for(let[e,t]of l.entries())Number.isSafeInteger(t)||I(`DEFINE_TRAIN_INVALID`,`train.seeds[${e}] is ${P(t)}, expected an integer`),l.indexOf(t)!==e&&I(`DEFINE_TRAIN_INVALID`,`train.seeds[${e}] repeats seed ${P(t)}`);L(r)||I(`DEFINE_TRAIN_INVALID`,`train.epochs is ${P(r)}, expected a positive integer`),L(i)||I(`DEFINE_TRAIN_INVALID`,`train.batch is ${P(i)}, expected a positive integer`),Oe(a)||I(`DEFINE_TRAIN_INVALID`,`train.learningRate is ${P(a)}, expected a finite number above 0`),(!R(o)||o>=1)&&I(`DEFINE_TRAIN_INVALID`,`train.warmup is ${P(o)}, expected a number from 0 up to, not including, 1`),Oe(s)||I(`DEFINE_TRAIN_INVALID`,`train.budgetSeconds is ${P(s)}, expected a finite number above 0`),(c===void 0?t:!L(c))&&I(`DEFINE_TRAIN_INVALID`,`train.negatives is ${P(c)}, expected a positive integer${t?` (a retrieve head needs it)`:``}`)}function Ae(e){if(!F(e))return I(`DEFINE_DATA_INVALID`,`data is ${P(e)}, expected defineDataset({ seed, minSize })`);Number.isSafeInteger(e.seed)||I(`DEFINE_DATA_INVALID`,`data.seed is ${P(e.seed)}, expected an integer`);let{minSize:t,generate:n}=e;for(let e of[`train`,`dev`,`test`]){let n=F(t)?t[e]:void 0;L(n)||I(`DEFINE_DATA_INVALID`,`data.minSize.${e} is ${P(n)}, expected a positive integer`)}if(n!==void 0){if(!F(n))return I(`DEFINE_DATA_INVALID`,`data.generate is ${P(n)}, expected an object of generators`);for(let[e,t]of Object.entries(n))[`train`,`dev`,`test`].includes(e)||I(`DEFINE_DATA_INVALID`,`data.generate.${e} is not a set name`),t!==void 0&&typeof t!=`function`&&I(`DEFINE_DATA_INVALID`,`data.generate.${e} is ${P(t)}, expected a function`)}}function je(e){if(!F(e)||e.floors!==`promoted`)throw a(`DEFINE_GATE_INVALID`,`gate.floors is ${P(F(e)?e.floors:e)}, expected 'promoted'`);if(!R(e.noise))throw a(`DEFINE_GATE_INVALID`,`gate.noise is ${P(e.noise)}, expected a finite number of at least 0`)}function Me(e){if(!F(e))throw a(`DEFINE_PARITY_INVALID`,`parity is ${P(e)}, expected { tolerance }`);let{tolerance:t}=e;if(!R(t))throw a(`DEFINE_PARITY_INVALID`,`parity.tolerance is ${P(t)}, expected a finite number of at least 0`)}function Ne(e){if(e===void 0)return;if(!F(e)||!L(e.brotliBytes))throw a(`DEFINE_SHIP_INVALID`,`ship.brotliBytes is ${P(F(e)?e.brotliBytes:e)}, expected a positive integer`);let{files:t}=e;if(!Array.isArray(t)||t.length===0||!t.every(e=>typeof e==`string`&&e!==``))throw a(`DEFINE_SHIP_INVALID`,`ship.files is ${P(t)}, expected a non-empty list of paths`)}function Pe(e,t,n){if(typeof e!=`function`)throw a(`DEFINE_EVAL_INVALID`,`metric is ${P(e)}, expected a function`);if(t!==void 0&&typeof t!=`function`)throw a(`DEFINE_EVAL_INVALID`,`decode is ${P(t)}, expected a function`);if(!F(n))throw a(`DEFINE_EVAL_INVALID`,`baselines is ${P(n)}, expected an object of functions`);for(let[e,t]of Object.entries(n))if(typeof t!=`function`)throw a(`DEFINE_EVAL_INVALID`,`baselines.${e} is ${P(t)}, expected a function`)}function Fe(e,t){return Ie(e,t),t}function Ie(e,t){if(typeof e!=`object`||!e||!(`head`in e)||!(`input`in e))throw a(`DEFINE_EVAL_MODEL`,`the first argument of defineEval is not a model definition`);if(typeof t!=`object`||!t)throw a(`DEFINE_EVAL_MODEL`,`defineEval has no eval definition after the model`);let{sets:n}=t,r=[[`train`,n.train,`data/train/`],[`dev`,n.dev,`data/dev/`],[`test`,n.test.path,`data/test/`]];for(let[e,t,n]of r)if(typeof t!=`string`||!t.startsWith(n)||De(t)!==t)throw a(`DEFINE_SET_FOLDER`,`sets.${e} is '${t}', expected a path inside '${n}' without '.', '..' or empty segments`);let{table:i}=t;if(i!==void 0){let e=De(i);if(i.startsWith(`/`)||e===`..`||e.startsWith(`../`)||r.some(([,,t])=>`${e}/`.startsWith(t)))throw a(`DEFINE_SET_FOLDER`,`table is '${i}', expected a relative path inside the package and outside the set folders`)}let o=t;Ae(o.data),ke(o.train,e.head.kind===`retrieve`),je(o.gate),Me(o.parity),Ne(o.ship),Pe(o.metric,o.decode,o.baselines)}function Le(e){return e}const Re={tokens(e){return{kind:`tokens`,max:e.max,rows:e.rows}},shape(){return{kind:`shape`}},hash(e){return{kind:`hash`,buckets:e.buckets,k:e.k}},flag(e){return{kind:`flag`,name:e.name}}},ze={embed(e){return{kind:`embed`,size:e.size}},conv(e){return{kind:`conv`,taps:e.taps}},biScan(e){return{kind:`biScan`,size:e.size}},dense(e){return{kind:`dense`,size:e.size,activation:e.activation}}};function Be(e){let{labels:t,outputs:n}=e;return{kind:`pooled`,...t===void 0?{}:{labels:t},...n===void 0?{}:{outputs:n}}}const Ve={tag(e){return{kind:`tag`,labels:e.labels}},pooled:Be,retrieve(e){return{kind:`retrieve`,size:e.size}}};function He(e){return{kind:`int6`,qatFrom:e.qatFrom}}function Ue(e){return{kind:`sealed`,path:e}}function z(e){let[t,n]=e.tensors;if(!t||!n)throw Error(`${e.spec.kind} op ${e.index} has ${e.tensors.length} tensors, expected 2`);return{weight:t.offset,bias:n.offset}}function We(e,t,n){let r=new Float32Array(2*n),i=new Int32Array(n).fill(-1);if(t===0)return{pooled:r,argmax:i};for(let a=0;a<n;a++){let o=0,s=0,c=-1/0;for(let r=0;r<t;r++){let t=e[r*n+a]??0;o+=t,t>c&&(c=t,s=r)}r[a]=o/t,r[n+a]=c,i[a]=s}return{pooled:r,argmax:i}}function Ge(e,t,n,r,i){let{inWidth:a,outWidth:o}=e,s=2*a,{weight:c,bias:l}=z(e),{pooled:u,argmax:d}=We(n,r,a),f=new Float32Array(o);for(let e=0;e<o;e++){let n=c+e*s,r=t[l+e]??0;for(let e=0;e<s;e++)r+=(t[n+e]??0)*(u[e]??0);f[e]=r}return i&&(i.set(`pooled`,u),i.set(`argmax`,d)),f}function Ke(e,t){let{inWidth:n,outWidth:r}=e,{weight:i,bias:a}=z(e),o=`
|
|
2
|
+
const IN_WIDTH: u32 = ${n}u;
|
|
3
|
+
const OUT: u32 = ${r}u;
|
|
4
|
+
const WEIGHT: u32 = ${i}u;
|
|
5
|
+
const BIAS: u32 = ${a}u;
|
|
6
|
+
|
|
7
|
+
struct Params { n: u32 }
|
|
8
|
+
`,s={label:`${e.spec.kind} ${e.index} linear`,code:`${o}
|
|
9
|
+
@group(0) @binding(0) var<storage, read> weights: array<f32>;
|
|
10
|
+
@group(0) @binding(3) var<storage, read_write> output: array<f32>;
|
|
11
|
+
@group(0) @binding(4) var<storage, read_write> temp: array<f32>;
|
|
12
|
+
|
|
13
|
+
@compute @workgroup_size(64)
|
|
14
|
+
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
|
|
15
|
+
let o = id.x;
|
|
16
|
+
if (o >= OUT) {
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
var z = weights[BIAS + o];
|
|
20
|
+
for (var j = 0u; j < 2u * IN_WIDTH; j++) {
|
|
21
|
+
z += weights[WEIGHT + o * 2u * IN_WIDTH + j] * temp[j];
|
|
22
|
+
}
|
|
23
|
+
output[o] = z;
|
|
24
|
+
}
|
|
25
|
+
`,dispatch:()=>[Math.ceil(r/64),1,1]};return t.maxTokens*t.maxWidth<2*n?[{label:`${e.spec.kind} ${e.index} one token`,code:`${o}
|
|
26
|
+
@group(0) @binding(0) var<storage, read> weights: array<f32>;
|
|
27
|
+
@group(0) @binding(1) var<uniform> params: Params;
|
|
28
|
+
@group(0) @binding(2) var<storage, read> input: array<f32>;
|
|
29
|
+
@group(0) @binding(3) var<storage, read_write> output: array<f32>;
|
|
30
|
+
|
|
31
|
+
@compute @workgroup_size(64)
|
|
32
|
+
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
|
|
33
|
+
let o = id.x;
|
|
34
|
+
if (o >= OUT) {
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
var z = weights[BIAS + o];
|
|
38
|
+
if (params.n > 0u) {
|
|
39
|
+
for (var j = 0u; j < 2u * IN_WIDTH; j++) {
|
|
40
|
+
z += weights[WEIGHT + o * 2u * IN_WIDTH + j] * input[j % IN_WIDTH];
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
output[o] = z;
|
|
44
|
+
}
|
|
45
|
+
`,dispatch:()=>[Math.ceil(r/64),1,1]}]:[{label:`${e.spec.kind} ${e.index} pool`,code:`${o}
|
|
46
|
+
@group(0) @binding(1) var<uniform> params: Params;
|
|
47
|
+
@group(0) @binding(2) var<storage, read> input: array<f32>;
|
|
48
|
+
@group(0) @binding(4) var<storage, read_write> temp: array<f32>;
|
|
49
|
+
|
|
50
|
+
@compute @workgroup_size(64)
|
|
51
|
+
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
|
|
52
|
+
let i = id.x;
|
|
53
|
+
if (i >= IN_WIDTH) {
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
let n = params.n;
|
|
57
|
+
if (n == 0u) {
|
|
58
|
+
temp[i] = 0.0;
|
|
59
|
+
temp[IN_WIDTH + i] = 0.0;
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
var sum = 0.0;
|
|
63
|
+
var best = input[i];
|
|
64
|
+
for (var t = 0u; t < n; t++) {
|
|
65
|
+
let value = input[t * IN_WIDTH + i];
|
|
66
|
+
sum += value;
|
|
67
|
+
best = max(best, value);
|
|
68
|
+
}
|
|
69
|
+
temp[i] = sum / f32(n);
|
|
70
|
+
temp[IN_WIDTH + i] = best;
|
|
71
|
+
}
|
|
72
|
+
`,dispatch:()=>[Math.ceil(n/64),1,1]},s]}const qe={forward:Ge,wgsl:Ke,decode(e,t){if(`outputs`in e){if(t.length<e.outputs)throw RangeError(`expected ${e.outputs} logits, got ${t.length}`);return Array.from(t.subarray(0,e.outputs))}let n=e.labels.length;if(t.length<n)throw RangeError(`expected ${n} logits, got ${t.length}`);let r=0;for(let e=1;e<n;e++)(t[e]??0)>(t[r]??0)&&(r=e);return e.labels[r]??``}};function B(e){if(e===void 0||e.length===0)throw a(`RUN_TABLE_MISSING`,`a retrieve head has no table rows to score the input against`);return e}function Je(e,t,n,r){if(e.length<r)throw RangeError(`expected a query of ${r} values, got ${e.length}`);if(t.length<n*r)throw RangeError(`expected ${n*r} table values, got ${t.length}`);let i=new Float32Array(n);for(let a=0;a<n;a++){let n=0,o=a*r;for(let i=0;i<r;i++)n+=(e[i]??0)*(t[o+i]??0);i[a]=n}return i}function Ye(e,t,n){return[{label:`retrieve score`,code:`
|
|
73
|
+
const SIZE: u32 = ${e}u;
|
|
74
|
+
const ROWS: u32 = ${t}u;
|
|
75
|
+
const TABLE: u32 = ${n}u;
|
|
76
|
+
|
|
77
|
+
@group(0) @binding(0) var<storage, read> weights: array<f32>;
|
|
78
|
+
@group(0) @binding(2) var<storage, read> input: array<f32>;
|
|
79
|
+
@group(0) @binding(3) var<storage, read_write> output: array<f32>;
|
|
80
|
+
|
|
81
|
+
@compute @workgroup_size(64)
|
|
82
|
+
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
|
|
83
|
+
let r = id.x;
|
|
84
|
+
if (r >= ROWS) {
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
var sum = 0.0;
|
|
88
|
+
for (var i = 0u; i < SIZE; i++) {
|
|
89
|
+
sum += input[i] * weights[TABLE + r * SIZE + i];
|
|
90
|
+
}
|
|
91
|
+
output[r] = sum;
|
|
92
|
+
}
|
|
93
|
+
`,dispatch:()=>[Math.ceil(t/64),1,1]}]}function Xe(e,t){if(t.length!==e.length)throw RangeError(`expected ${e.length} scores, got ${t.length}`);return e.map((e,n)=>({id:e,score:t[n]??0,index:n})).toSorted((e,t)=>t.score-e.score||e.index-t.index).map(({id:e,score:t})=>({id:e,score:t}))}function Ze(e,t){if(typeof e==`string`||e.length===0)throw a(`DATA_ROW_INVALID`,"a retrieve head needs `gold` as an array of at least one table row id");let n=e,r=[];for(let[e,i]of n.entries()){if(typeof i!=`string`)throw a(`DATA_ROW_INVALID`,`gold[${e}] is not a table row id`);let n=t.indexOf(i);if(n<0)throw a(`DATA_LABEL_UNKNOWN`,`gold[${e}] names none of the ${t.length} table rows`);if(r.includes(n))throw a(`DATA_ROW_INVALID`,`gold[${e}] repeats an earlier id`);r.push(n)}return r}function Qe(e,t){let n=Ze(e,B(t)),r=n.map(e=>({id:t[e]??``,score:1})),i=[];for(let[e,r]of t.entries())n.includes(e)||i.push({id:r,score:0});return[...r,...i]}const $e={forward:Ge,wgsl:Ke,decode(e,t,n,r){return Xe(B(r),t)}};function V(e){let[t,n]=e.tensors;if(!t||!n)throw Error(`tag op ${e.index} has ${e.tensors.length} tensors, expected 2`);return{weight:t.offset,bias:n.offset}}const H={tag:{forward(e,t,n,r,i){let{inWidth:a,outWidth:o}=e,{weight:s,bias:c}=V(e),l=new Float32Array(r*o);for(let e=0;e<r;e++){let r=e*a;for(let i=0;i<o;i++){let u=s+i*a,d=t[c+i]??0;for(let e=0;e<a;e++)d+=(t[u+e]??0)*(n[r+e]??0);l[e*o+i]=d}}return i&&i.set(`x`,n),l},wgsl(e){let{inWidth:t,outWidth:n}=e,{weight:r,bias:i}=V(e),a=`
|
|
94
|
+
const IN_WIDTH: u32 = ${t}u;
|
|
95
|
+
const LABELS: u32 = ${n}u;
|
|
96
|
+
const WEIGHT: u32 = ${r}u;
|
|
97
|
+
const BIAS: u32 = ${i}u;
|
|
98
|
+
|
|
99
|
+
struct Params { n: u32 }
|
|
100
|
+
|
|
101
|
+
@group(0) @binding(0) var<storage, read> weights: array<f32>;
|
|
102
|
+
@group(0) @binding(1) var<uniform> params: Params;
|
|
103
|
+
@group(0) @binding(2) var<storage, read> input: array<f32>;
|
|
104
|
+
@group(0) @binding(3) var<storage, read_write> output: array<f32>;
|
|
105
|
+
|
|
106
|
+
@compute @workgroup_size(64)
|
|
107
|
+
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
|
|
108
|
+
let index = id.x;
|
|
109
|
+
if (index >= params.n * LABELS) {
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
let t = index / LABELS;
|
|
113
|
+
let l = index % LABELS;
|
|
114
|
+
var z = weights[BIAS + l];
|
|
115
|
+
for (var i = 0u; i < IN_WIDTH; i++) {
|
|
116
|
+
z += weights[WEIGHT + l * IN_WIDTH + i] * input[t * IN_WIDTH + i];
|
|
117
|
+
}
|
|
118
|
+
output[index] = z;
|
|
119
|
+
}
|
|
120
|
+
`;return[{label:`tag ${e.index}`,code:a,dispatch:e=>[Math.ceil(e*n/64),1,1]}]},decode(e,t,n){let r=e.labels,i=r.length;if(t.length<n*i)throw RangeError(`expected ${n*i} logits, got ${t.length}`);let a=[];for(let e=0;e<n;e++){let n=0;for(let r=1;r<i;r++)(t[e*i+r]??0)>(t[e*i+n]??0)&&(n=r);a.push(r[n]??``)}return a}},pooled:qe,retrieve:$e};function et(e,t,n){let r=0;for(let i=t;i<t+n;i++){let t=e[i]??0;if(!Number.isFinite(t))throw RangeError(`weight ${i} is ${t}, not a finite number`);r=Math.max(r,Math.abs(t))}return Math.fround(r/31)}function tt(e,t){if(t===0)return 0;let n=Math.max(-31,Math.min(31,Math.round(e/t)));return n===0?0:n}function nt(e,t,n){if(t.length!==e.size||n.length!==e.size)throw RangeError(`expected ${e.size} weights, got ${t.length} and ${n.length}`);for(let{offset:r,length:i}of N(e)){let e=et(t,r,i);for(let a=r;a<r+i;a++)n[a]=tt(t[a]??0,e)*e}}const rt=[71,80,69,87],it=new TextEncoder;function U(e){return e+3&-4}function W(e,t){return e===6?Math.ceil(t*6/8):t*4}function G(e){return e.reduce((e,t)=>e*t,1)}function at(e,t){if(t.length!==e.size)throw RangeError(`expected ${e.size} weights, got ${t.length}`);let n=e.definition.quant!==void 0,r=N(e).map(({name:e,shape:r,offset:i,length:a})=>{if(!n)return{name:e,shape:r,bitWidth:32,scale:1,values:t.slice(i,i+a)};let o=et(t,i,a),s=new Int8Array(a);for(let e=0;e<a;e++)s[e]=tt(t[i+e]??0,o);return{name:e,shape:r,bitWidth:6,scale:o,values:s}});return{version:1,hash:e.hash,definition:e.definition,tensors:r}}function ot(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function st(e,t){if(e.hash!==t.hash)throw a(`WEIGHTS_DEFINITION_MISMATCH`,`the file hash is ${e.hash}, the definition hashes to ${t.hash}`);let n=N(t);if(e.tensors.length!==n.length)throw a(`WEIGHTS_DEFINITION_MISMATCH`,`the file has ${e.tensors.length} tensors, the definition plans ${n.length}`);let r=t.definition.quant===void 0?32:6;for(let[t,i]of n.entries()){let n=e.tensors[t];if(n!==void 0&&(n.name!==i.name||!ot(n.shape,i.shape)||n.bitWidth!==r))throw a(`WEIGHTS_DEFINITION_MISMATCH`,`tensor ${t} is '${n.name}' [${n.shape.join(`, `)}] at ${n.bitWidth} bits, the definition plans '${i.name}' [${i.shape.join(`, `)}] at ${r} bits`)}}function ct(e,t){st(e,t);let n=new Float32Array(t.size);for(let[r,{offset:i}]of N(t).entries()){let t=e.tensors[r];if(t!==void 0){if(t.bitWidth===32)n.set(t.values,i);else for(let[e,r]of t.values.entries())n[i+e]=r*t.scale}}return n}function lt(e,t){let n=Object.is(t,-0)?`-0`:String(t);if(!Number.isFinite(t)||t<0||Object.is(t,-0))return`has scale ${n}`;if(e===32&&t!==1)return`is a float32 tensor with scale ${n}, expected 1`}function ut(e){if(e.values.length!==G(e.shape))throw RangeError(`tensor '${e.name}' has ${e.values.length} values for shape [${e.shape.join(`, `)}]`);let t=lt(e.bitWidth,e.scale);if(t!==void 0)throw RangeError(`tensor '${e.name}' ${t}`);let n=e.bitWidth===6?e=>Number.isInteger(e)&&Math.abs(e)<=31:e=>Number.isFinite(e);if(!e.values.every(n))throw RangeError(`tensor '${e.name}' holds a value its bit width cannot store`)}function dt(e){if(!/^[0-9a-f]{16}$/.test(e.hash))throw RangeError(`hash '${e.hash}' is not 16 hex characters`);let t=it.encode(he(e.definition)),n=e.tensors.map(e=>it.encode(e.name)),r=24+U(t.length);for(let[t,i]of e.tensors.entries())ut(i),r+=U(2+(n[t]?.length??0))+4+4*i.shape.length+8;for(let t of e.tensors)r+=U(W(t.bitWidth,t.values.length));let i=new Uint8Array(r),a=new DataView(i.buffer);i.set(rt,0),a.setUint16(4,e.version,!0),a.setUint16(6,0,!0),a.setUint32(8,Number.parseInt(e.hash.slice(0,8),16),!0),a.setUint32(12,Number.parseInt(e.hash.slice(8),16),!0),a.setUint32(16,t.length,!0),a.setUint32(20,e.tensors.length,!0),i.set(t,24);let o=24+U(t.length);for(let[t,r]of e.tensors.entries()){let e=n[t]??/* @__PURE__ */ new Uint8Array;a.setUint16(o,e.length,!0),i.set(e,o+2),o+=U(2+e.length),a.setUint8(o,r.bitWidth),a.setUint8(o+1,r.shape.length),a.setUint16(o+2,0,!0),o+=4;for(let e of r.shape)a.setUint32(o,e,!0),o+=4;a.setFloat32(o,r.scale,!0),a.setUint32(o+4,W(r.bitWidth,r.values.length),!0),o+=8}for(let t of e.tensors){if(t.bitWidth===32)for(let[e,n]of t.values.entries())a.setFloat32(o+4*e,n,!0);else for(let[e,n]of t.values.entries()){let t=n+32;for(let n=0;n<6;n++)if(t>>n&1){let t=e*6+n;i[o+(t>>3)]=(i[o+(t>>3)]??0)|1<<(t&7)}}o+=U(W(t.bitWidth,t.values.length))}return i}function K(e){return a(`WEIGHTS_FORMAT_INVALID`,e)}var ft=class{at=0;view;bytes;constructor(e){this.bytes=e,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}need(e,t){let n=this.at;if(n+e>this.bytes.length)throw K(`the file ends at byte ${this.bytes.length}, ${t} needs bytes ${n} to ${n+e}`);return this.at+=e,n}u8(e){return this.view.getUint8(this.need(1,e))}u16(e){return this.view.getUint16(this.need(2,e),!0)}u32(e){return this.view.getUint32(this.need(4,e),!0)}f32(e){return this.view.getFloat32(this.need(4,e),!0)}slice(e,t){let n=this.need(e,t);return this.bytes.subarray(n,n+e)}zeros(e,t){if(this.slice(e,t).some(e=>e!==0))throw K(`${t} at byte ${this.at-e} is not zero`)}padTo4(e){this.zeros(U(this.at)-this.at,e)}};const pt=new TextDecoder(`utf-8`,{fatal:!0});function mt(e,t){try{return pt.decode(e)}catch{throw K(`${t} is not valid UTF-8`)}}function q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ht(e){return q(e)&&typeof e.name==`string`&&q(e.input)&&Array.isArray(e.net)&&q(e.head)}function gt(e){let t;try{t=JSON.parse(e)}catch{throw K(`the definition is not valid JSON`)}if(!ht(t))throw K("the definition JSON is not an object with `name`, `input`, `net` and `head`");if(he(t)!==e)throw K(`the definition JSON is not in canonical form`);return t}function _t(e){try{return M(e)}catch(e){throw K(`the definition cannot be planned: ${e instanceof i?e.message:String(e)}`)}}function vt(e,t){let n=`tensor record ${t}`,r=mt(e.slice(e.u16(n),n),`${n} name`);e.padTo4(`${n} name padding`);let i=e.u8(n);if(i!==6&&i!==32)throw K(`${n} has bit width ${i}, expected 6 or 32`);let a=e.u8(n);e.zeros(2,`${n} reserved field`);let o=Array.from({length:a},()=>e.u32(n)),s=e.f32(n),c=lt(i,s);if(c!==void 0)throw K(`${n} ${c}`);let l=e.u32(n),u=W(i,G(o));if(l!==u)throw K(`${n} declares ${l} payload bytes, its shape needs ${u}`);return{tensor:{name:r,shape:o,bitWidth:i,scale:s},bytes:l}}function yt(e,t,n){let r=`payload of '${t.name}'`,i=e.slice(n,r),a=G(t.shape);if(t.bitWidth===32){let n=new DataView(i.buffer,i.byteOffset,i.byteLength),o=new Float32Array(a);for(let e=0;e<a;e++){let t=n.getFloat32(e*4,!0);if(!Number.isFinite(t))throw K(`${r} holds ${t} at value ${e}`);o[e]=t}return e.padTo4(`${r} padding`),{...t,values:o}}let o=new Int8Array(a);for(let e=0;e<a;e++){let t=0;for(let n=0;n<6;n++){let r=e*6+n;t|=((i[r>>3]??0)>>(r&7)&1)<<n}if(t===0)throw K(`${r} holds code 0 at value ${e}; codes run from 1 to 63`);o[e]=t-32}let s=a*6;if(s%8!=0&&(i[n-1]??0)>>s%8)throw K(`${r} has bits set after its last value`);return e.padTo4(`${r} padding`),{...t,values:o}}function bt(e){let t=new ft(e),n=t.slice(4,`the magic`);if(!rt.every((e,t)=>n[t]===e))throw K(`the file does not start with "GPEW"`);let r=t.u16(`the version`);if(r!==1)throw a(`WEIGHTS_VERSION_UNSUPPORTED`,`the file has format version ${r}, this runtime reads 1`);t.zeros(2,`the flags`);let i=[t.u32(`the hash`),t.u32(`the hash`)].map(e=>e.toString(16).padStart(8,`0`)).join(``),o=t.u32(`the definition length`),s=t.u32(`the tensor count`),c=gt(mt(t.slice(o,`the definition`),`the definition`));if(t.padTo4(`the definition padding`),s*16>e.length-t.at)throw K(`the file declares ${s} tensors, more than its ${e.length} bytes can hold`);let l=Array.from({length:s},(e,n)=>vt(t,n)).map(({tensor:e,bytes:n})=>yt(t,e,n));if(t.at!==e.length)throw K(`${e.length-t.at} bytes follow the last payload`);let u={version:r,hash:i,definition:c,tensors:l};return st(u,_t(c)),u}const J=51314688;function Y(e,t,n){let r=e*t,i=`${e} multiply-adds per token * ${t} tokens = ${r}`;return r<n?{backend:`cpu`,reason:`auto chose cpu by the rule "below the WebGPU threshold": ${i} < AUTO_WEBGPU_MIN_MACS = ${n}`}:{backend:`webgpu`,reason:`auto chose webgpu by the rule "at or above the WebGPU threshold": ${i} >= AUTO_WEBGPU_MIN_MACS = ${n}`}}function X(e){if(e.tensors.length!==8)throw Error(`biScan op ${e.index} has ${e.tensors.length} tensors, expected 8`);let t=t=>{let[n,r,i,a]=e.tensors.slice(t,t+4).map(e=>e.offset);return{gateWeight:n??0,gateBias:r??0,candidateWeight:i??0,candidateBias:a??0}};return[t(0),t(4)]}function xt(e,t,n){return e===0?t:n-1-t}const St=e=>1/(1+Math.exp(-e)),Ct=e=>`array<u32, 4>(${e.gateWeight}u, ${e.gateBias}u, ${e.candidateWeight}u, ${e.candidateBias}u)`,wt={forward(e,t,n,r,i){let{inWidth:a,outWidth:o}=e,s=e.spec.size,c=X(e),l=new Float32Array(r*o),u=new Float32Array(r*o),d=new Float32Array(r*o);for(let[e,i]of c.entries()){let c=e*s;for(let f=0;f<s;f++){let s=i.gateWeight+f*a,p=i.candidateWeight+f*a,m=0;for(let h=0;h<r;h++){let g=xt(e,h,r),_=g*a,v=t[i.gateBias+f]??0,y=t[i.candidateBias+f]??0;for(let e=0;e<a;e++){let r=n[_+e]??0;v+=(t[s+e]??0)*r,y+=(t[p+e]??0)*r}let b=g*o+c+f;l[b]=St(v),u[b]=Math.tanh(y);let x=l[b]??0;d[b]=x*m+(1-x)*(u[b]??0),m=d[b]??0}}}return i&&(i.set(`x`,n),i.set(`gate`,l),i.set(`tanh`,u),i.set(`y`,d)),d},wgsl(e){let{inWidth:t,outWidth:n}=e,r=e.spec.size,[i,a]=X(e),o=`
|
|
121
|
+
const IN_WIDTH: u32 = ${t}u;
|
|
122
|
+
const OUT_WIDTH: u32 = ${n}u;
|
|
123
|
+
const SIZE: u32 = ${r}u;
|
|
124
|
+
// Per direction: gate weight, gate bias, candidate weight, candidate bias.
|
|
125
|
+
const FORWARD: array<u32, 4> = ${Ct(i)};
|
|
126
|
+
const BACKWARD: array<u32, 4> = ${Ct(a)};
|
|
127
|
+
|
|
128
|
+
struct Params { n: u32 }
|
|
129
|
+
|
|
130
|
+
@group(0) @binding(0) var<storage, read> weights: array<f32>;
|
|
131
|
+
@group(0) @binding(1) var<uniform> params: Params;
|
|
132
|
+
@group(0) @binding(2) var<storage, read> input: array<f32>;
|
|
133
|
+
@group(0) @binding(3) var<storage, read_write> output: array<f32>;
|
|
134
|
+
|
|
135
|
+
@compute @workgroup_size(64)
|
|
136
|
+
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
|
|
137
|
+
let index = id.x;
|
|
138
|
+
if (index >= 2u * SIZE) {
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
let direction = index / SIZE;
|
|
142
|
+
let d = index % SIZE;
|
|
143
|
+
var tensors = FORWARD;
|
|
144
|
+
if (direction == 1u) {
|
|
145
|
+
tensors = BACKWARD;
|
|
146
|
+
}
|
|
147
|
+
let gateRow = tensors[0] + d * IN_WIDTH;
|
|
148
|
+
let candidateRow = tensors[2] + d * IN_WIDTH;
|
|
149
|
+
let n = params.n;
|
|
150
|
+
var state = 0.0;
|
|
151
|
+
for (var step = 0u; step < n; step++) {
|
|
152
|
+
var t = step;
|
|
153
|
+
if (direction == 1u) {
|
|
154
|
+
t = n - 1u - step;
|
|
155
|
+
}
|
|
156
|
+
var zGate = weights[tensors[1] + d];
|
|
157
|
+
var zCandidate = weights[tensors[3] + d];
|
|
158
|
+
for (var i = 0u; i < IN_WIDTH; i++) {
|
|
159
|
+
let value = input[t * IN_WIDTH + i];
|
|
160
|
+
zGate += weights[gateRow + i] * value;
|
|
161
|
+
zCandidate += weights[candidateRow + i] * value;
|
|
162
|
+
}
|
|
163
|
+
let gate = 1.0 / (1.0 + exp(-clamp(zGate, -30.0, 30.0)));
|
|
164
|
+
let squashed = tanh(clamp(zCandidate, -15.0, 15.0));
|
|
165
|
+
state = gate * state + (1.0 - gate) * squashed;
|
|
166
|
+
output[t * OUT_WIDTH + direction * SIZE + d] = state;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
`;return[{label:`biScan ${e.index}`,code:o,dispatch:()=>[Math.ceil(2*r/64),1,1]}]}};function Tt(e){let[t,n]=e.tensors;if(!t||!n)throw Error(`conv op ${e.index} has ${e.tensors.length} tensors, expected 2`);return{kernel:t.offset,bias:n.offset}}const Et={forward(e,t,n,r,i){let a=e.inWidth,{taps:o}=e.spec,s=(o-1)/2,{kernel:c,bias:l}=Tt(e),u=new Float32Array(r*a);for(let e=0;e<r;e++)for(let i=0;i<a;i++){let d=t[l+i]??0;for(let l=0;l<o;l++){let o=e+l-s;o>=0&&o<r&&(d+=(t[c+l*a+i]??0)*(n[o*a+i]??0))}u[e*a+i]=Math.tanh(d)}return i&&(i.set(`x`,n),i.set(`y`,u)),u},wgsl(e){let t=e.inWidth,{taps:n}=e.spec,{kernel:r,bias:i}=Tt(e),a=`
|
|
170
|
+
const WIDTH: u32 = ${t}u;
|
|
171
|
+
const TAPS: u32 = ${n}u;
|
|
172
|
+
const HALF: i32 = ${(n-1)/2};
|
|
173
|
+
const KERNEL: u32 = ${r}u;
|
|
174
|
+
const BIAS: u32 = ${i}u;
|
|
175
|
+
|
|
176
|
+
struct Params { n: u32 }
|
|
177
|
+
|
|
178
|
+
@group(0) @binding(0) var<storage, read> weights: array<f32>;
|
|
179
|
+
@group(0) @binding(1) var<uniform> params: Params;
|
|
180
|
+
@group(0) @binding(2) var<storage, read> input: array<f32>;
|
|
181
|
+
@group(0) @binding(3) var<storage, read_write> output: array<f32>;
|
|
182
|
+
|
|
183
|
+
@compute @workgroup_size(64)
|
|
184
|
+
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
|
|
185
|
+
let index = id.x;
|
|
186
|
+
if (index >= params.n * WIDTH) {
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
let t = i32(index / WIDTH);
|
|
190
|
+
let i = index % WIDTH;
|
|
191
|
+
var z = weights[BIAS + i];
|
|
192
|
+
for (var j = 0u; j < TAPS; j++) {
|
|
193
|
+
let source = t + i32(j) - HALF;
|
|
194
|
+
if (source >= 0 && source < i32(params.n)) {
|
|
195
|
+
z += weights[KERNEL + j * WIDTH + i] * input[u32(source) * WIDTH + i];
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
output[index] = tanh(clamp(z, -15.0, 15.0));
|
|
199
|
+
}
|
|
200
|
+
`;return[{label:`conv ${e.index}`,code:a,dispatch:e=>[Math.ceil(e*t/64),1,1]}]}};function Dt(e,t){return e===`relu`?t>0?t:0:e===`tanh`?Math.tanh(t):t}const Ot={relu:`max(z, 0.0)`,tanh:`tanh(clamp(z, -15.0, 15.0))`,none:`z`};function kt(e){let[t,n]=e.tensors;if(!t||!n)throw Error(`dense op ${e.index} has ${e.tensors.length} tensors, expected 2`);return{weight:t.offset,bias:n.offset}}const At={forward(e,t,n,r,i){let{inWidth:a,outWidth:o}=e,{activation:s}=e.spec,{weight:c,bias:l}=kt(e),u=new Float32Array(r*o);for(let e=0;e<r;e++){let r=e*a;for(let i=0;i<o;i++){let d=c+i*a,f=t[l+i]??0;for(let e=0;e<a;e++)f+=(t[d+e]??0)*(n[r+e]??0);u[e*o+i]=Dt(s,f)}}return i&&(i.set(`x`,n),i.set(`y`,u)),u},wgsl(e){let{inWidth:t,outWidth:n}=e,{weight:r,bias:i}=kt(e),a=`
|
|
201
|
+
const IN_WIDTH: u32 = ${t}u;
|
|
202
|
+
const OUT_WIDTH: u32 = ${n}u;
|
|
203
|
+
const WEIGHT: u32 = ${r}u;
|
|
204
|
+
const BIAS: u32 = ${i}u;
|
|
205
|
+
|
|
206
|
+
struct Params { n: u32 }
|
|
207
|
+
|
|
208
|
+
@group(0) @binding(0) var<storage, read> weights: array<f32>;
|
|
209
|
+
@group(0) @binding(1) var<uniform> params: Params;
|
|
210
|
+
@group(0) @binding(2) var<storage, read> input: array<f32>;
|
|
211
|
+
@group(0) @binding(3) var<storage, read_write> output: array<f32>;
|
|
212
|
+
|
|
213
|
+
@compute @workgroup_size(64)
|
|
214
|
+
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
|
|
215
|
+
let index = id.x;
|
|
216
|
+
if (index >= params.n * OUT_WIDTH) {
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
let t = index / OUT_WIDTH;
|
|
220
|
+
let o = index % OUT_WIDTH;
|
|
221
|
+
var z = weights[BIAS + o];
|
|
222
|
+
for (var i = 0u; i < IN_WIDTH; i++) {
|
|
223
|
+
z += weights[WEIGHT + o * IN_WIDTH + i] * input[t * IN_WIDTH + i];
|
|
224
|
+
}
|
|
225
|
+
output[index] = ${Ot[e.spec.activation]};
|
|
226
|
+
}
|
|
227
|
+
`;return[{label:`dense ${e.index}`,code:a,dispatch:e=>[Math.ceil(e*n/64),1,1]}]}};function jt(e){let[t,n]=e.tensors;if(!t||!n)throw Error(`embed op ${e.index} has ${e.tensors.length} tensors, expected 2`);return{table:t.offset,bias:n.offset,rows:t.shape[0]??0}}const Mt={layers:{embed:{forward(e,t,n,r,i){let{inWidth:a,outWidth:o}=e,{table:s,bias:c,rows:l}=jt(e),u=new Float32Array(r*o),d=new Float64Array(o);for(let e=0;e<r;e++){for(let e=0;e<o;e++)d[e]=t[c+e]??0;for(let r=0;r<a;r++){let i=n[e*a+r]??-1;if(i<0||i>=l)continue;let c=s+i*o;for(let e=0;e<o;e++)d[e]=(d[e]??0)+(t[c+e]??0)}u.set(d,e*o)}return i&&i.set(`rows`,n),u},wgsl(e){let{inWidth:t,outWidth:n}=e,{table:r,bias:i,rows:a}=jt(e),o=`
|
|
228
|
+
const SLOTS: u32 = ${t}u;
|
|
229
|
+
const SIZE: u32 = ${n}u;
|
|
230
|
+
const ROWS: i32 = ${a};
|
|
231
|
+
const TABLE: u32 = ${r}u;
|
|
232
|
+
const BIAS: u32 = ${i}u;
|
|
233
|
+
|
|
234
|
+
struct Params { n: u32 }
|
|
235
|
+
|
|
236
|
+
@group(0) @binding(0) var<storage, read> weights: array<f32>;
|
|
237
|
+
@group(0) @binding(1) var<uniform> params: Params;
|
|
238
|
+
@group(0) @binding(2) var<storage, read> input: array<i32>;
|
|
239
|
+
@group(0) @binding(3) var<storage, read_write> output: array<f32>;
|
|
240
|
+
|
|
241
|
+
@compute @workgroup_size(64)
|
|
242
|
+
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
|
|
243
|
+
let index = id.x;
|
|
244
|
+
if (index >= params.n * SIZE) {
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
let t = index / SIZE;
|
|
248
|
+
let o = index % SIZE;
|
|
249
|
+
var z = weights[BIAS + o];
|
|
250
|
+
for (var s = 0u; s < SLOTS; s++) {
|
|
251
|
+
let row = input[t * SLOTS + s];
|
|
252
|
+
if (row >= 0 && row < ROWS) {
|
|
253
|
+
z += weights[TABLE + u32(row) * SIZE + o];
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
output[index] = z;
|
|
257
|
+
}
|
|
258
|
+
`;return[{label:`embed ${e.index}`,code:o,dispatch:e=>[Math.ceil(e*n/64),1,1]}]}},conv:Et,biScan:wt,dense:At},heads:H};function Nt(e,t){switch(t.kind){case`embed`:return e.layers.embed;case`conv`:return e.layers.conv;case`biScan`:return e.layers.biScan;case`dense`:return e.layers.dense;case`tag`:return e.heads.tag;case`pooled`:return e.heads.pooled;case`retrieve`:return e.heads.retrieve;default:throw Error(`no forward op for kind '${A(t)}'`)}}function Pt(e,t,n,r,i,a=Mt){if(t.length!==e.size)throw RangeError(`expected ${e.size} weights, got ${t.length}`);if(!Number.isInteger(r)||r<0||r>e.maxTokens)throw RangeError(`n is ${r}, expected an integer from 0 to ${e.maxTokens}`);if(n.length<r*e.slots)throw RangeError(`expected ${r*e.slots} feature rows for ${r} tokens, got ${n.length}`);let o=n,s=/* @__PURE__ */ new Float32Array;for(let n of e.ops){let e=i===void 0?void 0:i[n.index]=/* @__PURE__ */ new Map;s=Nt(a,n.spec).forward(n,t,o,r,e);let c=n.spec.kind===`pooled`||n.spec.kind===`retrieve`?n.outWidth:r*n.outWidth;if(s.length!==c)throw RangeError(`op ${n.index} (${n.spec.kind}) returned ${s.length} values, expected ${c}`);o=s}return s}function Ft(e,t,n){return Pt(e,t,n.rows,n.count)}function It(e){if(!Array.isArray(e)||e.length===0)throw a(`RUN_TABLE_MISSING`,"a retrieve model needs `table`, a non-empty array of { id, text } rows");let t=e,n=/* @__PURE__ */ new Set,r=[];for(let[e,i]of t.entries()){let t=typeof i==`object`&&i&&`id`in i?i.id:void 0,o=typeof i==`object`&&i&&`text`in i?i.text:void 0;if(typeof t!=`string`||t===``||typeof o!=`string`)throw a(`RUN_TABLE_MISSING`,`table[${e}] is not a { id, text } row with a non-empty string id`);if(n.has(t))throw a(`RUN_TABLE_MISSING`,`table[${e}] repeats the id of an earlier row`);n.add(t),r.push({id:t,text:o})}return r}function Lt(e,t,n){let r=e.outWidth,i=new Float32Array(n.length*r);for(let[a,o]of n.entries()){let{rows:n,count:s}=E(e.definition.input,o.text);i.set(Pt(e,t,n,s),a*r)}return{ids:n.map(e=>e.id),rows:n.length,size:r,vectors:i}}function Rt(e){return Math.max(16,Math.ceil(e*4/16)*16)}async function zt(e,t,n){e.pushErrorScope(`validation`);let r=e.createShaderModule({label:n.label,code:n.code}),i=(await r.getCompilationInfo()).messages.filter(e=>e.type===`error`);if(i.length>0){await e.popErrorScope();let t=i.map(e=>`${e.lineNum}:${e.linePos} ${e.message}`).join(`; `);throw Error(`WGSL compile failed in '${n.label}': ${t}`)}let a=e.createComputePipeline({label:n.label,layout:t,compute:{module:r,entryPoint:`main`}}),o=await e.popErrorScope();if(o)throw Error(`pipeline '${n.label}' failed validation: ${o.message}`);return a}async function Bt(e,t){let{weights:n,ops:r,inputLength:i,scratchLength:a}=t;if(r.length===0)throw Error(`a program needs at least one op`);let o=e.createBindGroupLayout({label:`gpu-engine bindings`,entries:[`read-only-storage`,`uniform`,`read-only-storage`,`storage`,`storage`].map((e,t)=>({binding:t,visibility:4,buffer:{type:e}}))}),s=e.createPipelineLayout({bindGroupLayouts:[o]}),c=(t,n,r)=>e.createBuffer({label:t,size:Rt(n),usage:r}),l=c(`weights`,n.length,136),u=c(`params`,4,72),d=c(`input`,i,136),f=c(`scratch a`,a,132),p=c(`scratch b`,a,132),m=c(`temp`,a,128),h=[l,u,d,f,p,m],g=()=>{for(let e of h)e.destroy()};n.length>0&&e.queue.writeBuffer(l,0,n.buffer,n.byteOffset,n.byteLength);let _=e=>e%2==0?f:p,v=[];try{for(let[t,n]of r.entries()){let r=e.createBindGroup({label:`op ${t}`,layout:o,entries:[l,u,t===0?d:_(t-1),_(t),m].map((e,t)=>({binding:t,resource:{buffer:e}}))});for(let t of n)v.push({pass:t,pipeline:await zt(e,s,t),bindGroup:r})}}catch(e){throw g(),e}let y=_(r.length-1);async function b(t,n,r){if(t.length>i)throw Error(`input has ${t.length} elements, the buffer holds ${i}`);if(r>a)throw Error(`output of ${r} floats exceeds the scratch buffer of ${a}`);e.pushErrorScope(`validation`),e.queue.writeBuffer(u,0,new Uint32Array([n])),t.length>0&&e.queue.writeBuffer(d,0,t.buffer,t.byteOffset,t.byteLength);let o=c(`readback`,r,9);try{let t=e.createCommandEncoder(),i=t.beginComputePass();for(let e of v){let[t,r,a]=e.pass.dispatch(n);t*r*a!==0&&(i.setPipeline(e.pipeline),i.setBindGroup(0,e.bindGroup),i.dispatchWorkgroups(t,r,a))}i.end(),r>0&&t.copyBufferToBuffer(y,0,o,0,r*4),e.queue.submit([t.finish()]);let a=await e.popErrorScope();if(a)throw Error(`run failed validation: ${a.message}`);await o.mapAsync(1);let s=new Float32Array(o.getMappedRange().slice(0,r*4));return o.unmap(),s}finally{o.destroy()}}let x=Promise.resolve(),S;return{run(e,t,n){if(S!==void 0)return Promise.reject(/* @__PURE__ */ Error(`the program was destroyed`));let r=x.then(()=>b(e,t,n));return x=r.catch(()=>void 0),r},destroy(){return S??=x.then(()=>g()),S}}}function Vt(e){return e instanceof Error?e.message:String(e)}function Ht(e){return[r(`RUN_GPU_FAILED`,e),void 0]}function Ut(e,t){let n=new Map([...Object.entries(e.layers),...Object.entries(e.heads)]).get(t.kind);if(n===void 0)throw Error(`no forward op for kind '${A(t)}'`);return n}function Wt(e,t,n){if(n!==void 0)return n.outputs;let{kind:r}=e.definition.head;return r===`pooled`||r===`retrieve`?e.outWidth:t*e.outWidth}function Gt(e){let t=e.info;return t==null?`unnamed adapter`:[t.vendor,t.architecture,t.description].filter(Boolean).join(` `)||`unnamed adapter`}async function Kt(e,t,n,r,i){let a=Math.max(...t.ops.flatMap(e=>[e.inWidth,e.outWidth])),o={maxTokens:t.maxTokens,maxWidth:a},s=t.ops.map(e=>Ut(r,e.spec).wgsl(e,o)),c=n;i!==void 0&&(s.push(i.passes),c=new Float32Array(n.length+i.weights.length),c.set(n),c.set(i.weights,n.length)),e.pushErrorScope(`out-of-memory`),e.pushErrorScope(`validation`);let l,u;try{l=await Bt(e,{weights:c,ops:s,inputLength:t.maxTokens*t.slots,scratchLength:Math.max(t.maxTokens*a,i?.outputs??0)})}catch(e){u=e}let d=await e.popErrorScope(),f=await e.popErrorScope(),p=d??f;if(u!==void 0)throw u;if(l===void 0||p)throw await l?.destroy(),Error(`the model pipeline failed validation: ${p?.message??`no program`}`);return l}async function qt(e,t,n,i=Mt,a){let o;try{o=await e.requestAdapter()}catch(e){return[r(`RUN_BACKEND_UNAVAILABLE`,`requestAdapter failed: ${Vt(e)}`),void 0]}if(!o)return[r(`RUN_BACKEND_UNAVAILABLE`,`the WebGPU entry point found no adapter`),void 0];let s;try{let c=Gt(o);s=await o.requestDevice();let l,u=s.lost;(async()=>{let e=await u;l=r(`RUN_GPU_FAILED`,`the device on ${c} was lost (${e.reason}): ${e.message}`)})();let d=await Kt(s,t,n,i,a),f=s,p;return[void 0,{adapter:c,gpu:e,async run(e){if(l)return[l,void 0];try{return[void 0,await d.run(e.rows,e.count,Wt(t,e.count,a))]}catch(e){return[l??r(`RUN_GPU_FAILED`,`on ${c}: ${Vt(e)}`),void 0]}},destroy(){return p??=d.destroy().then(()=>f.destroy()),p}}]}catch(e){return s?.destroy(),Ht(`WebGPU setup failed: ${Vt(e)}`)}}const Jt=/* @__PURE__ */ new WeakMap,Yt=/* @__PURE__ */ new WeakSet,Xt=()=>r(`RUN_MODEL_DESTROYED`,"`destroy()` was called on this model; load the weights again to run it");function Z(e){return e===null?`null`:Array.isArray(e)?`an array`:typeof e==`string`?`'${e}'`:typeof e}function Q(e){if(e instanceof i){let{code:t,message:i}=e.diagnostic;return n(t)?{...e.diagnostic,code:t}:t.startsWith(`DEFINE_`)?r(`WEIGHTS_FORMAT_INVALID`,`the definition in the file fails a check: ${t}: ${i}`):r(`RUN_FAILED`,`${t}: ${i}`)}return r(`RUN_FAILED`,e instanceof Error?e.message:String(e))}function Zt(e){return typeof e.requestAdapter==`function`}function Qt(e){return e===void 0?typeof navigator>`u`?void 0:navigator.gpu:Zt(e)?e:void 0}const $t="no `gpu` option with a `requestAdapter` method was passed and `navigator.gpu` is undefined";function $(e,t){return{backend:`cpu`,reason:`auto chose cpu by the rule "${e}": ${t}`}}function en(e){return e===`cpu`||e===`webgpu`||e===`auto`?[void 0,e]:[r(`RUN_BACKEND_UNAVAILABLE`,`backend is ${Z(e)}, expected 'auto', 'webgpu' or 'cpu'`),void 0]}async function tn(e,t,n,i,a){if(e===`cpu`)return[void 0,{chosen:{backend:`cpu`,reason:`backend 'cpu' was requested`}}];let o=Qt(t);if(e===`webgpu`){if(o===void 0)return[r(`RUN_BACKEND_UNAVAILABLE`,`backend 'webgpu' was requested, and there is no WebGPU entry point: ${$t}`),void 0];let[e,t]=await qt(o,n,i,void 0,a);return e?[{...e,message:`backend 'webgpu' was requested: ${e.message}`},void 0]:[void 0,{gpu:t,chosen:{backend:`webgpu`,reason:`backend 'webgpu' was requested, running on ${t.adapter}`}}]}if(o===void 0)return[void 0,{chosen:$(`no WebGPU entry point`,$t)}];let s=Y(n.macsPerToken,n.maxTokens,J);if(s.backend===`cpu`)return[void 0,{chosen:{...s,reason:`${s.reason}, at input.max, the most tokens a run can have`}}];let[c,l]=await qt(o,n,i,void 0,a);return c?[void 0,{chosen:$(c.code===`RUN_BACKEND_UNAVAILABLE`?`no WebGPU adapter`:`WebGPU failed to start`,`${c.code}: ${c.message}`)}]:[void 0,{gpu:l,auto:!0,chosen:{backend:`webgpu`,reason:`auto opened WebGPU on ${l.adapter} and picks per run: webgpu when ${n.macsPerToken} multiply-adds per token * tokens >= AUTO_WEBGPU_MIN_MACS = ${J}, else cpu; no run yet`}}]}async function nn(e,t){let n=Qt(t);if(n===void 0)return $(`no WebGPU entry point`,$t);let r;try{if(typeof e!=`object`||!e)throw a(`RUN_FAILED`,`definition is ${Z(e)}, expected a model definition`);r=M(e)}catch(e){let{code:t,message:n}=Q(e);return{backend:`cpu`,reason:`auto cannot choose for this definition, so it answers cpu: ${t}: ${n}`}}let i=Y(r.macsPerToken,r.maxTokens,J);if(i.backend===`cpu`)return{...i,reason:`${i.reason}, at input.max, the most tokens a run can have`};let o;try{o=await n.requestAdapter()}catch(e){return $(`no WebGPU adapter`,`requestAdapter failed: ${e instanceof Error?e.message:String(e)}`)}return o?{backend:`webgpu`,reason:`auto chose webgpu by the rule "WebGPU adapter found": the model opens WebGPU and picks per run, webgpu from ${Math.ceil(J/r.macsPerToken)} tokens (${r.macsPerToken} multiply-adds per token * tokens >= AUTO_WEBGPU_MIN_MACS = ${J}), cpu below`}:$(`no WebGPU adapter`,`the WebGPU entry point found no adapter`)}function rn(e){return ArrayBuffer.isView(e)&&Object.prototype.toString.call(e)===`[object Uint8Array]`}function an(e){return Object.prototype.toString.call(e)===`[object ArrayBuffer]`}function on(e){if(rn(e))return e;if(an(e))return new Uint8Array(e);throw a(`WEIGHTS_FORMAT_INVALID`,`weights is ${Z(e)}, expected a Uint8Array or an ArrayBuffer`)}function sn(e,t){if(e===void 0)return;if(typeof e!=`object`||!e)throw a(`WEIGHTS_DEFINITION_MISMATCH`,`definition is ${Z(e)}, expected a model definition`);let n;try{n=O(e)}catch{throw a(`WEIGHTS_DEFINITION_MISMATCH`,`the definition passed to loadModel cannot be hashed`)}if(n!==t)throw a(`WEIGHTS_DEFINITION_MISMATCH`,`the file hash is ${t}, the definition passed to loadModel hashes to ${n}`)}async function cn(e,t){let n=t??{},[r,i]=en(n.backend),a=0,o=0,s=e=>({ok:!1,error:e,inspection:{backend:i===`webgpu`?`webgpu`:`cpu`,reason:`the model did not load: ${e.code}: ${e.message}`,bytes:a,macs:o}});try{let t=on(e);a=t.byteLength;let c=bt(t);sn(n.definition,c.hash);let l=M(c.definition);o=l.macsPerToken;let u=ct(c,l);if(r)return s(r);let d=l.definition.head.kind===`retrieve`?Lt(l,u,It(n.table)):void 0,f=d===void 0?void 0:{weights:d.vectors,passes:Ye(d.size,d.rows,u.length),outputs:d.rows},[p,m]=await tn(i,n.gpu,l,u,f);return p?s(p):{ok:!0,plan:l,weights:u,bytes:a,runner:m,...d===void 0?{}:{table:d}}}catch(e){return s(Q(e))}}function ln(e){return e.ok?{...e.runner.chosen,bytes:e.bytes,macs:e.plan.macsPerToken,inputMax:e.plan.definition.input.max,head:e.plan.definition.head.kind}:e.inspection}async function un(e,t){if(!e.ok)return[e.error,void 0];try{let n=E(e.plan.definition.input,t),{runner:r}=e,i=r.gpu!==void 0&&r.auto===!0?Y(e.plan.macsPerToken,n.count,J):r.chosen;if(r.chosen=i,r.gpu===void 0||i.backend===`cpu`){let{table:t}=e,r=Ft(e.plan,e.weights,n);return[void 0,{logits:t===void 0?r:Je(r,t.vectors,t.rows,t.size),count:n.count}]}let[a,o]=await r.gpu.run(n);return a?[a,void 0]:[void 0,{logits:o,count:n.count}]}catch(e){return[Q(e),void 0]}}function dn(e,t,n,r){switch(e.kind){case`tag`:return H.tag.decode(e,t,n);case`pooled`:return H.pooled.decode(e,t,n);case`retrieve`:return H.retrieve.decode(e,t,n,r);default:throw Error(`no decode for head kind '${A(e)}'`)}}function fn(e,t){let n=`labels`in t?t.labels:void 0;return t.kind===`tag`?Array.isArray(e)&&e.every(e=>n?.includes(e)===!0):t.kind===`retrieve`?Array.isArray(e)&&e.every(e=>typeof e==`object`&&!!e&&`id`in e&&typeof e.id==`string`&&`score`in e&&typeof e.score==`number`):n===void 0?Array.isArray(e)&&e.every(e=>typeof e==`number`):n.includes(e)}async function pn(e,t){let n=await cn(e,t),i=e=>n.ok&&fn(e,n.plan.definition.head),a={async run(e){if(Yt.has(a))return[Xt(),void 0];if(!n.ok)return[n.error,void 0];let[t,o]=await un(n,e);if(t)return[t,void 0];let{head:s}=n.plan.definition,c=o.logits.findIndex(e=>!Number.isFinite(e));if(c!==-1)return[r(`RUN_OUTPUT_NONFINITE`,`${s.kind===`retrieve`?`score`:`logit`} ${c} of ${o.logits.length} is ${o.logits[c]}, so the ${s.kind} head did not decode it`),void 0];try{let e=dn(s,o.logits,o.count,n.table?.ids);return i(e)?[void 0,e]:[r(`RUN_FAILED`,`the ${s.kind} head decoded to a value outside its labels`),void 0]}catch(e){return[Q(e),void 0]}},inspect:()=>ln(n),async destroy(){Yt.add(a),n.ok&&await n.runner.gpu?.destroy()}};return Jt.set(a,n),a}async function mn(e){let t=e??{};try{return await nn(t.definition,t.gpu)}catch{return nn(t.definition,void 0)}}async function hn(e,t){let n=Jt.get(e);return n===void 0?[r(`RUN_FAILED`,`runLogits was given an object that loadModel did not return`),void 0]:Yt.has(e)?[Xt(),void 0]:un(n,t)}export{Ve as A,oe as B,z as C,Fe as D,Le as E,O as F,i as H,A as I,M as L,ze as M,Ue as N,Ee as O,fe as P,E as R,B as S,ke as T,e as U,m as V,H as _,Lt as a,Ze as b,kt as c,xt as d,bt as f,nt as g,at as h,Gt as i,He as j,Re as k,Tt as l,dt as m,pn as n,Pt as o,ct as p,hn as r,jt as s,mn as t,X as u,V as v,Ie as w,Je as x,Qe as y,w as z};
|