bitgpu 0.12.0 → 0.13.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/README.md CHANGED
@@ -34,7 +34,7 @@ weights stream straight from the Hugging Face Hub. This runs as-is:
34
34
  import { createEngine } from 'bitgpu'
35
35
  import { createChat } from 'bitgpu/chat'
36
36
 
37
- const REPO = 'https://cdn.jsdelivr.net/gh/stfurkan/bitgpu@v0.12.0/models/bonsai-1.7b-gguf'
37
+ const REPO = 'https://cdn.jsdelivr.net/gh/stfurkan/bitgpu@v0.13.0/models/bonsai-1.7b-gguf'
38
38
  const TOK = 'https://huggingface.co/onnx-community/Bonsai-1.7B-ONNX/resolve/main'
39
39
  const engine = await createEngine({
40
40
  manifestUrl: `${REPO}/manifest.json`,
@@ -318,9 +318,32 @@ GPU gate proves the reuse paths bit-exact on real hardware. Prefer your own toke
318
318
 
319
319
  ## Bring your own model
320
320
 
321
- bitgpu loads its own small format instead of parsing ONNX or GGUF at runtime: a
321
+ ### Any 1-bit GGUF, zero steps: `bitgpu/gguf`
322
+
323
+ For GGUF models there is no conversion step at all - `fromGguf` fetches ONLY the header
324
+ (HTTP ranges, a few MB, never the weights), builds the manifest in memory, and derives the
325
+ lookup tables, so one URL is the whole setup:
326
+
327
+ ```ts
328
+ import { createEngine } from 'bitgpu'
329
+ import { fromGguf } from 'bitgpu/gguf'
330
+
331
+ const engine = await createEngine({
332
+ ...(await fromGguf('https://huggingface.co/prism-ml/Bonsai-1.7B-gguf/resolve/main/Bonsai-1.7B-Q1_0.gguf')),
333
+ kvCache: 'q8',
334
+ })
335
+ ```
336
+
337
+ The in-browser parse is gated: it must deep-equal the offline converter's manifest AND an
338
+ engine built from it must reproduce the known-good greedy ids bit-exactly on GPU. Prefer the
339
+ committed [`models/`](models/) manifests when one exists (a `manifest.json` is smaller than a
340
+ GGUF header and caches better); `fromGguf` is for models nobody has converted yet.
341
+
342
+ ### Offline converters
343
+
344
+ bitgpu loads its own small format instead of parsing ONNX (or re-parsing GGUF) at runtime: a
322
345
  `manifest.json` (the architecture contract + every tensor mapped to a byte range) and a small
323
- aux file, both produced ONCE, offline, from a standard export - while the big weights file is
346
+ aux file, both produced ONCE from a standard export - while the big weights file is
324
347
  used byte-for-byte unchanged, so it can keep streaming from wherever it already lives (e.g.
325
348
  the Hugging Face Hub). Same one-time-conversion model as llama.cpp or MLX. Two converters:
326
349
 
package/dist/chat.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { c as KvSnapshot, n as Engine, o as GenerateOptions, u as TokenLogprobs } from "./types-Bl0FS_nX.js";
1
+ import { c as KvSnapshot, m as TokenLogprobs, n as Engine, o as GenerateOptions } from "./types-ByYx15Yw.js";
2
2
 
3
3
  //#region src/chat/tokenizer.d.ts
4
4
  interface ChatMessage {
package/dist/gguf.d.ts ADDED
@@ -0,0 +1,33 @@
1
+ import { u as Manifest } from "./types-ByYx15Yw.js";
2
+
3
+ //#region src/gguf.d.ts
4
+ interface GgufModel {
5
+ manifest: Manifest;
6
+ aux: Uint8Array;
7
+ /** The GGUF URL itself - the weights stream from it byte-for-byte unchanged. */
8
+ dataUrl: string;
9
+ }
10
+ interface FromGgufOptions {
11
+ /** Fetch `len` bytes at `off`. Override for caching or non-HTTP sources. Default: `fetch`
12
+ * with a `Range` header (and a stream-and-cancel fallback for servers that ignore ranges). */
13
+ fetchRange?: (url: string, off: number, len: number) => Promise<ArrayBuffer>;
14
+ /** Parse abort cap: headers larger than this fail loudly. Default 64 MiB. */
15
+ maxHeaderBytes?: number;
16
+ }
17
+ /** The two expansion tables the kernels use, generated from their defining property:
18
+ * LSB-first sign bits -> per-weight codes around the recipe midpoints (2-bit: {1,3},
19
+ * 4-bit: {7,9}). Byte-identical to the tables the ONNX exports carry. */
20
+ declare function ggufLuts(): Uint8Array;
21
+ /** Parse a GGUF header already in memory (e.g. from a File). Grows nothing - the buffer must
22
+ * contain the full header (weights past it are not needed). */
23
+ declare function fromGgufBytes(buf: ArrayBuffer, dataFile: string): {
24
+ manifest: Manifest;
25
+ aux: Uint8Array;
26
+ };
27
+ /** Fetch and parse a GGUF header; returns `{ manifest, aux, dataUrl }` for createEngine.
28
+ * Only the header is transferred, progressively: 1 MiB first, then EXTENSION ranges (2x
29
+ * growth) appended to the kept prefix - total transfer stays under 2x the header size. */
30
+ declare function fromGguf(url: string, options?: FromGgufOptions): Promise<GgufModel>;
31
+ //#endregion
32
+ export { FromGgufOptions, GgufModel, fromGguf, fromGgufBytes, ggufLuts };
33
+ //# sourceMappingURL=gguf.d.ts.map
package/dist/gguf.js ADDED
@@ -0,0 +1,394 @@
1
+ //#region src/gguf.ts
2
+ const F32 = 0;
3
+ const Q1_0 = 41;
4
+ const BLK = 18;
5
+ const FIRST_FETCH = 1 << 20;
6
+ const LINEAR = {
7
+ attn_q: "attn.q_proj",
8
+ attn_k: "attn.k_proj",
9
+ attn_v: "attn.v_proj",
10
+ attn_output: "attn.o_proj",
11
+ ffn_gate: "mlp.gate_proj",
12
+ ffn_up: "mlp.up_proj",
13
+ ffn_down: "mlp.down_proj"
14
+ };
15
+ const NORM = {
16
+ attn_norm: "input_layernorm",
17
+ ffn_norm: "post_attention_layernorm",
18
+ attn_q_norm: "attn.q_norm",
19
+ attn_k_norm: "attn.k_norm"
20
+ };
21
+ /** Sentinel: the parse ran past the fetched prefix - fetch a bigger one and retry. */
22
+ var OutOfData = class extends Error {};
23
+ function u64ToNumber(v, what) {
24
+ if (v > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error(`bitgpu/gguf: ${what} ${v} exceeds safe integer range`);
25
+ return Number(v);
26
+ }
27
+ /** Parse a GGUF v3 header from a fetched prefix; throws OutOfData if the prefix is too short. */
28
+ function parseHeader(buf) {
29
+ const dv = new DataView(buf);
30
+ const u8 = new Uint8Array(buf);
31
+ const td = new TextDecoder();
32
+ let pos = 0;
33
+ const need = (n) => {
34
+ if (pos + n > buf.byteLength) throw new OutOfData();
35
+ };
36
+ const u32 = () => {
37
+ need(4);
38
+ const v = dv.getUint32(pos, true);
39
+ pos += 4;
40
+ return v;
41
+ };
42
+ const u64 = (what) => {
43
+ need(8);
44
+ const v = dv.getBigUint64(pos, true);
45
+ pos += 8;
46
+ return u64ToNumber(v, what);
47
+ };
48
+ const gstr = () => {
49
+ const n = u64("string length");
50
+ need(n);
51
+ const s = td.decode(u8.subarray(pos, pos + n));
52
+ pos += n;
53
+ return s;
54
+ };
55
+ const value = (t) => {
56
+ switch (t) {
57
+ case 0:
58
+ need(1);
59
+ return u8[pos++];
60
+ case 1:
61
+ need(1);
62
+ return dv.getInt8(pos++);
63
+ case 2:
64
+ need(2);
65
+ {
66
+ const v = dv.getUint16(pos, true);
67
+ pos += 2;
68
+ return v;
69
+ }
70
+ case 3:
71
+ need(2);
72
+ {
73
+ const v = dv.getInt16(pos, true);
74
+ pos += 2;
75
+ return v;
76
+ }
77
+ case 4: return u32();
78
+ case 5:
79
+ need(4);
80
+ {
81
+ const v = dv.getInt32(pos, true);
82
+ pos += 4;
83
+ return v;
84
+ }
85
+ case 6:
86
+ need(4);
87
+ {
88
+ const v = dv.getFloat32(pos, true);
89
+ pos += 4;
90
+ return v;
91
+ }
92
+ case 7:
93
+ need(1);
94
+ return u8[pos++] !== 0;
95
+ case 8: return gstr();
96
+ case 9: {
97
+ const et = u32();
98
+ const n = u64("array length");
99
+ const out = new Array(n);
100
+ for (let i = 0; i < n; i++) out[i] = value(et);
101
+ return out;
102
+ }
103
+ case 10: return u64("u64 value");
104
+ case 11:
105
+ need(8);
106
+ {
107
+ const v = dv.getBigInt64(pos, true);
108
+ pos += 8;
109
+ if (v > BigInt(Number.MAX_SAFE_INTEGER) || v < -BigInt(Number.MAX_SAFE_INTEGER)) throw new Error(`bitgpu/gguf: i64 value ${v} exceeds safe integer range`);
110
+ return Number(v);
111
+ }
112
+ case 12:
113
+ need(8);
114
+ {
115
+ const v = dv.getFloat64(pos, true);
116
+ pos += 8;
117
+ return v;
118
+ }
119
+ default: throw new Error(`bitgpu/gguf: unknown GGUF value type ${t}`);
120
+ }
121
+ };
122
+ need(4);
123
+ if (td.decode(u8.subarray(0, 4)) !== "GGUF") throw new Error("bitgpu/gguf: not a GGUF file (bad magic)");
124
+ pos = 4;
125
+ const version = u32();
126
+ if (version !== 3) throw new Error(`bitgpu/gguf: unsupported GGUF version ${version} (this parser implements v3)`);
127
+ const nTensors = u64("tensor count");
128
+ const nKv = u64("kv count");
129
+ const meta = {};
130
+ for (let i = 0; i < nKv; i++) {
131
+ const k = gstr();
132
+ meta[k] = value(u32());
133
+ }
134
+ const tensors = {};
135
+ for (let i = 0; i < nTensors; i++) {
136
+ const name = gstr();
137
+ const nd = u32();
138
+ const dims = [];
139
+ for (let d = 0; d < nd; d++) dims.push(u64("tensor dim"));
140
+ tensors[name] = {
141
+ dims,
142
+ type: u32(),
143
+ off: u64("tensor offset")
144
+ };
145
+ }
146
+ const align = Number(meta["general.alignment"] ?? 32);
147
+ return {
148
+ meta,
149
+ tensors,
150
+ dataStart: Math.ceil(pos / align) * align
151
+ };
152
+ }
153
+ /** Default ranged fetch. Servers that ignore `Range` (HTTP 200) are handled by reading the
154
+ * stream only up to the needed length and cancelling - the weights are never downloaded. */
155
+ async function fetchRangeHttp(url, off, len) {
156
+ const res = await fetch(url, { headers: { Range: `bytes=${off}-${off + len - 1}` } });
157
+ if (!res.ok) throw new Error(`bitgpu/gguf: fetch ${url} failed: HTTP ${res.status}`);
158
+ if (res.status === 206) return res.arrayBuffer();
159
+ if (!res.body) throw new Error(`bitgpu/gguf: ${url} has no readable body`);
160
+ const reader = res.body.getReader();
161
+ const out = new Uint8Array(len);
162
+ let seen = 0;
163
+ let filled = 0;
164
+ for (;;) {
165
+ const { done, value } = await reader.read();
166
+ if (done) break;
167
+ const start = Math.max(off - seen, 0);
168
+ if (value.byteLength > start) {
169
+ const take = Math.min(value.byteLength - start, len - filled);
170
+ out.set(value.subarray(start, start + take), filled);
171
+ filled += take;
172
+ }
173
+ seen += value.byteLength;
174
+ if (filled >= len) {
175
+ reader.cancel().catch(() => {});
176
+ break;
177
+ }
178
+ }
179
+ return out.buffer.slice(0, filled);
180
+ }
181
+ /** The two expansion tables the kernels use, generated from their defining property:
182
+ * LSB-first sign bits -> per-weight codes around the recipe midpoints (2-bit: {1,3},
183
+ * 4-bit: {7,9}). Byte-identical to the tables the ONNX exports carry. */
184
+ function ggufLuts() {
185
+ const aux = /* @__PURE__ */ new Uint8Array(1536);
186
+ for (let b = 0; b < 256; b++) for (let j = 0; j < 8; j++) {
187
+ const bit = b >> j & 1;
188
+ aux[b * 2 + (j >> 2)] |= (bit ? 3 : 1) << 2 * (j % 4);
189
+ aux[512 + b * 4 + (j >> 1)] |= (bit ? 9 : 7) << 4 * (j % 2);
190
+ }
191
+ return aux;
192
+ }
193
+ function basename(url) {
194
+ const path = url.split(/[?#]/)[0];
195
+ return decodeURIComponent(path.slice(path.lastIndexOf("/") + 1)) || "model.gguf";
196
+ }
197
+ /** Build the manifest from a parsed header - the exact mapping tools/convert-gguf.py performs. */
198
+ function buildManifest(h, dataFile) {
199
+ const { meta, tensors: gg, dataStart } = h;
200
+ const archName = meta["general.architecture"];
201
+ if (archName !== "qwen3") throw new Error(`bitgpu/gguf: unsupported architecture '${archName}' (bitgpu kernels implement the qwen3 topology)`);
202
+ const P = (k) => {
203
+ const v = meta[`${archName}.${k}`];
204
+ if (v === void 0) throw new Error(`bitgpu/gguf: header is missing ${archName}.${k}`);
205
+ return v;
206
+ };
207
+ const headDim = Number(P("attention.key_length"));
208
+ if (headDim !== Number(P("attention.value_length"))) throw new Error("bitgpu/gguf: key_length != value_length (kernels assume one head_dim)");
209
+ const layers = Number(P("block_count"));
210
+ const embd = gg["token_embd.weight"];
211
+ if (!embd) throw new Error("bitgpu/gguf: header has no token_embd.weight tensor");
212
+ const vocab = embd.dims[1];
213
+ const tied = !("output.weight" in gg);
214
+ const scalingType = meta[`${archName}.rope.scaling.type`];
215
+ const rope = { rope_theta: Number(P("rope.freq_base")) };
216
+ if (scalingType === "yarn") {
217
+ rope.rope_type = "yarn";
218
+ rope.factor = Number(P("rope.scaling.factor"));
219
+ rope.original_max_position_embeddings = Number(P("rope.scaling.original_context_length"));
220
+ } else if (scalingType !== void 0 && scalingType !== "none") throw new Error(`bitgpu/gguf: unsupported rope scaling '${scalingType}'`);
221
+ /** The interleaved Q1_0 byte range of a tensor inside the GGUF (used unchanged). */
222
+ const region = (gname, N, K) => {
223
+ const t = gg[gname];
224
+ if (!t) throw new Error(`bitgpu/gguf: header has no ${gname} tensor`);
225
+ if (t.type !== Q1_0) throw new Error(`bitgpu/gguf: ${gname}: expected ggml type 41 (Q1_0), got ${t.type}`);
226
+ if (K % 128 !== 0) throw new Error(`bitgpu/gguf: ${gname}: K=${K} not a multiple of the 128-wide blocks`);
227
+ const [gk, gn] = t.dims.length === 2 ? [t.dims[0], t.dims[1]] : [t.dims[0], 1];
228
+ if (gk !== K || gn !== N) throw new Error(`bitgpu/gguf: ${gname}: dims [${t.dims}] do not match expected [${K}, ${N}]`);
229
+ return {
230
+ dtype: "UINT8",
231
+ shape: [N, K / 128 * BLK],
232
+ src: "data",
233
+ off: dataStart + t.off,
234
+ len: N * (K / 128) * BLK
235
+ };
236
+ };
237
+ const normRef = (gname, n) => {
238
+ const t = gg[gname];
239
+ if (!t) throw new Error(`bitgpu/gguf: header has no ${gname} tensor`);
240
+ if (t.type !== F32) throw new Error(`bitgpu/gguf: ${gname}: expected F32 norm, got ggml type ${t.type}`);
241
+ if (t.dims.length !== 1 || t.dims[0] !== n) throw new Error(`bitgpu/gguf: ${gname}: dims [${t.dims}] != [${n}]`);
242
+ return {
243
+ dtype: "FLOAT",
244
+ shape: [n],
245
+ src: "data",
246
+ off: dataStart + t.off,
247
+ len: n * 4
248
+ };
249
+ };
250
+ const hidden = Number(P("embedding_length"));
251
+ const inter = Number(P("feed_forward_length"));
252
+ const heads = Number(P("attention.head_count"));
253
+ const kvHeads = Number(P("attention.head_count_kv"));
254
+ const SHAPES = {
255
+ attn_q: [heads * headDim, hidden],
256
+ attn_k: [kvHeads * headDim, hidden],
257
+ attn_v: [kvHeads * headDim, hidden],
258
+ attn_output: [hidden, heads * headDim],
259
+ ffn_gate: [inter, hidden],
260
+ ffn_up: [inter, hidden],
261
+ ffn_down: [hidden, inter]
262
+ };
263
+ const tensors = {};
264
+ for (let li = 0; li < layers; li++) {
265
+ for (const [gk, lk] of Object.entries(LINEAR)) {
266
+ const [N, K] = SHAPES[gk];
267
+ tensors[`layers.${li}.${lk}`] = {
268
+ kind: "binary",
269
+ N,
270
+ K,
271
+ block: 128,
272
+ bits: 2,
273
+ lut: "tgt2",
274
+ container: "q1_0",
275
+ weight: region(`blk.${li}.${gk}.weight`, N, K)
276
+ };
277
+ }
278
+ for (const [gk, lk] of Object.entries(NORM)) {
279
+ const n = gk.includes("q_norm") || gk.includes("k_norm") ? headDim : hidden;
280
+ tensors[`layers.${li}.${lk}`] = {
281
+ kind: "f32",
282
+ weight: normRef(`blk.${li}.${gk}.weight`, n)
283
+ };
284
+ }
285
+ }
286
+ tensors[`layers.${layers}.final_norm_layernorm`] = {
287
+ kind: "f32",
288
+ weight: normRef("output_norm.weight", hidden)
289
+ };
290
+ tensors["embed_tokens"] = {
291
+ kind: "q4",
292
+ rows: vocab,
293
+ cols: hidden,
294
+ block: 128,
295
+ bits: 4,
296
+ lut: "tgt4",
297
+ container: "q1_0",
298
+ weight: region("token_embd.weight", vocab, hidden)
299
+ };
300
+ tensors["lm_head"] = {
301
+ kind: "q2",
302
+ N: vocab,
303
+ K: hidden,
304
+ block: 128,
305
+ bits: 2,
306
+ lut: "tgt2",
307
+ container: "q1_0",
308
+ weight: region(tied ? "token_embd.weight" : "output.weight", vocab, hidden)
309
+ };
310
+ const eos = meta["tokenizer.ggml.eos_token_id"];
311
+ if (eos === void 0) throw new Error("bitgpu/gguf: header is missing tokenizer.ggml.eos_token_id");
312
+ return {
313
+ version: 2,
314
+ data_file: dataFile,
315
+ aux_file: `${dataFile.replace(/\.gguf$/i, "")}.aux.bin`,
316
+ arch: {
317
+ model_type: archName,
318
+ layers,
319
+ hidden,
320
+ intermediate: inter,
321
+ heads,
322
+ kv_heads: kvHeads,
323
+ head_dim: headDim,
324
+ rms_eps: Number(P("attention.layer_norm_rms_epsilon")),
325
+ rope,
326
+ max_positions: Number(P("context_length")),
327
+ vocab,
328
+ eos: Number(eos),
329
+ tie_word_embeddings: tied,
330
+ act: "silu"
331
+ },
332
+ luts: {
333
+ tgt2: {
334
+ dtype: "UINT8",
335
+ shape: [256, 2],
336
+ src: "aux",
337
+ off: 0,
338
+ len: 512
339
+ },
340
+ tgt4: {
341
+ dtype: "UINT8",
342
+ shape: [256, 4],
343
+ src: "aux",
344
+ off: 512,
345
+ len: 1024
346
+ }
347
+ },
348
+ tensors
349
+ };
350
+ }
351
+ /** Parse a GGUF header already in memory (e.g. from a File). Grows nothing - the buffer must
352
+ * contain the full header (weights past it are not needed). */
353
+ function fromGgufBytes(buf, dataFile) {
354
+ try {
355
+ return {
356
+ manifest: buildManifest(parseHeader(buf), dataFile),
357
+ aux: ggufLuts()
358
+ };
359
+ } catch (e) {
360
+ if (e instanceof OutOfData) throw new Error("bitgpu/gguf: buffer ends inside the GGUF header (pass more bytes)");
361
+ throw e;
362
+ }
363
+ }
364
+ /** Fetch and parse a GGUF header; returns `{ manifest, aux, dataUrl }` for createEngine.
365
+ * Only the header is transferred, progressively: 1 MiB first, then EXTENSION ranges (2x
366
+ * growth) appended to the kept prefix - total transfer stays under 2x the header size. */
367
+ async function fromGguf(url, options = {}) {
368
+ const fetchRange = options.fetchRange ?? fetchRangeHttp;
369
+ const cap = options.maxHeaderBytes ?? 64 << 20;
370
+ let size = FIRST_FETCH;
371
+ let have = new Uint8Array(await fetchRange(url, 0, size));
372
+ for (;;) try {
373
+ return {
374
+ manifest: buildManifest(parseHeader(have.buffer), basename(url)),
375
+ aux: ggufLuts(),
376
+ dataUrl: url
377
+ };
378
+ } catch (e) {
379
+ if (!(e instanceof OutOfData)) throw e;
380
+ if (have.byteLength < size) throw new Error(`bitgpu/gguf: ${url} ends inside its own header (truncated file?)`);
381
+ if (size >= cap) throw new Error(`bitgpu/gguf: header exceeds maxHeaderBytes (${cap}); raise the cap if this is a real model`);
382
+ const next = Math.min(size * 2, cap);
383
+ const ext = new Uint8Array(await fetchRange(url, have.byteLength, next - have.byteLength));
384
+ const grown = new Uint8Array(have.byteLength + ext.byteLength);
385
+ grown.set(have, 0);
386
+ grown.set(ext, have.byteLength);
387
+ have = grown;
388
+ size = next;
389
+ }
390
+ }
391
+ //#endregion
392
+ export { fromGguf, fromGgufBytes, ggufLuts };
393
+
394
+ //# sourceMappingURL=gguf.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gguf.js","names":[],"sources":["../src/gguf.ts"],"sourcesContent":["// bitgpu/gguf - point the engine at any 1-bit Q1_0 GGUF URL with NO offline step.\n//\n// `fromGguf(url)` fetches ONLY the GGUF header (HTTP ranges, a few MB - never the weights),\n// parses it, and returns `{ manifest, aux, dataUrl }` ready to spread into createEngine:\n//\n// import { createEngine } from 'bitgpu'\n// import { fromGguf } from 'bitgpu/gguf'\n// const engine = await createEngine({ ...(await fromGguf(GGUF_URL)), kvCache: 'q8' })\n//\n// This is tools/convert-gguf.py running in the browser: the same header walk, the same\n// tensor mapping, the same validations, producing a manifest deep-equal to the converter's\n// output (verified by scripts/verify-gguf.ts against the committed models/ manifests). The\n// aux LUTs are derived, not stored (generated from their defining property, byte-identical\n// to the tables the ONNX exports carry), so a GGUF model needs zero side files.\n//\n// Compatibility envelope (identical to the converter): architecture `qwen3`, every linear +\n// embedding + lm_head in Q1_0 (ggml tensor type 41), F32 norms, plain or YaRN rope - the\n// PrismML Bonsai 1-bit releases. Anything else fails loudly here, not as garbage output.\nimport type { Manifest, ManifestRef, ManifestTensor } from './types'\n\nexport interface GgufModel {\n manifest: Manifest\n aux: Uint8Array\n /** The GGUF URL itself - the weights stream from it byte-for-byte unchanged. */\n dataUrl: string\n}\n\nexport interface FromGgufOptions {\n /** Fetch `len` bytes at `off`. Override for caching or non-HTTP sources. Default: `fetch`\n * with a `Range` header (and a stream-and-cancel fallback for servers that ignore ranges). */\n fetchRange?: (url: string, off: number, len: number) => Promise<ArrayBuffer>\n /** Parse abort cap: headers larger than this fail loudly. Default 64 MiB. */\n maxHeaderBytes?: number\n}\n\nconst F32 = 0\nconst Q1_0 = 41 // ggml tensor types\nconst BLK = 18 // Q1_0: 2-byte f16 scale + 16 sign bytes per 128 weights\nconst FIRST_FETCH = 1 << 20 // 1 MiB - covers small headers in one round trip\n\nconst LINEAR: Record<string, string> = {\n attn_q: 'attn.q_proj',\n attn_k: 'attn.k_proj',\n attn_v: 'attn.v_proj',\n attn_output: 'attn.o_proj',\n ffn_gate: 'mlp.gate_proj',\n ffn_up: 'mlp.up_proj',\n ffn_down: 'mlp.down_proj',\n}\nconst NORM: Record<string, string> = {\n attn_norm: 'input_layernorm',\n ffn_norm: 'post_attention_layernorm',\n attn_q_norm: 'attn.q_norm',\n attn_k_norm: 'attn.k_norm',\n}\n\n/** Sentinel: the parse ran past the fetched prefix - fetch a bigger one and retry. */\nclass OutOfData extends Error {}\n\ninterface GTensor {\n dims: number[]\n type: number\n off: number\n}\ninterface Header {\n meta: Record<string, unknown>\n tensors: Record<string, GTensor>\n dataStart: number\n}\n\nfunction u64ToNumber(v: bigint, what: string): number {\n if (v > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error(`bitgpu/gguf: ${what} ${v} exceeds safe integer range`)\n return Number(v)\n}\n\n/** Parse a GGUF v3 header from a fetched prefix; throws OutOfData if the prefix is too short. */\nfunction parseHeader(buf: ArrayBuffer): Header {\n const dv = new DataView(buf)\n const u8 = new Uint8Array(buf)\n const td = new TextDecoder()\n let pos = 0\n const need = (n: number) => {\n if (pos + n > buf.byteLength) throw new OutOfData()\n }\n const u32 = () => {\n need(4)\n const v = dv.getUint32(pos, true)\n pos += 4\n return v\n }\n const u64 = (what: string) => {\n need(8)\n const v = dv.getBigUint64(pos, true)\n pos += 8\n return u64ToNumber(v, what)\n }\n const gstr = () => {\n const n = u64('string length')\n need(n)\n const s = td.decode(u8.subarray(pos, pos + n))\n pos += n\n return s\n }\n const value = (t: number): unknown => {\n switch (t) {\n case 0: need(1); return u8[pos++]\n case 1: need(1); return dv.getInt8(pos++)\n case 2: need(2); { const v = dv.getUint16(pos, true); pos += 2; return v }\n case 3: need(2); { const v = dv.getInt16(pos, true); pos += 2; return v }\n case 4: return u32()\n case 5: need(4); { const v = dv.getInt32(pos, true); pos += 4; return v }\n case 6: need(4); { const v = dv.getFloat32(pos, true); pos += 4; return v }\n case 7: need(1); return u8[pos++] !== 0\n case 8: return gstr()\n case 9: {\n const et = u32()\n const n = u64('array length')\n const out = new Array(n)\n for (let i = 0; i < n; i++) out[i] = value(et)\n return out\n }\n case 10: return u64('u64 value')\n case 11: need(8); { const v = dv.getBigInt64(pos, true); pos += 8; if (v > BigInt(Number.MAX_SAFE_INTEGER) || v < -BigInt(Number.MAX_SAFE_INTEGER)) throw new Error(`bitgpu/gguf: i64 value ${v} exceeds safe integer range`); return Number(v) }\n case 12: need(8); { const v = dv.getFloat64(pos, true); pos += 8; return v }\n default: throw new Error(`bitgpu/gguf: unknown GGUF value type ${t}`)\n }\n }\n\n need(4)\n if (td.decode(u8.subarray(0, 4)) !== 'GGUF') throw new Error('bitgpu/gguf: not a GGUF file (bad magic)')\n pos = 4\n const version = u32()\n if (version !== 3) throw new Error(`bitgpu/gguf: unsupported GGUF version ${version} (this parser implements v3)`)\n const nTensors = u64('tensor count')\n const nKv = u64('kv count')\n const meta: Record<string, unknown> = {}\n for (let i = 0; i < nKv; i++) {\n const k = gstr()\n const t = u32()\n meta[k] = value(t)\n }\n const tensors: Record<string, GTensor> = {}\n for (let i = 0; i < nTensors; i++) {\n const name = gstr()\n const nd = u32()\n const dims: number[] = []\n for (let d = 0; d < nd; d++) dims.push(u64('tensor dim'))\n const type = u32()\n const off = u64('tensor offset')\n tensors[name] = { dims, type, off }\n }\n const align = Number(meta['general.alignment'] ?? 32)\n const dataStart = Math.ceil(pos / align) * align\n return { meta, tensors, dataStart }\n}\n\n/** Default ranged fetch. Servers that ignore `Range` (HTTP 200) are handled by reading the\n * stream only up to the needed length and cancelling - the weights are never downloaded. */\nasync function fetchRangeHttp(url: string, off: number, len: number): Promise<ArrayBuffer> {\n const res = await fetch(url, { headers: { Range: `bytes=${off}-${off + len - 1}` } })\n if (!res.ok) throw new Error(`bitgpu/gguf: fetch ${url} failed: HTTP ${res.status}`)\n if (res.status === 206) return res.arrayBuffer()\n // Range ignored: take the first off+len bytes off the stream, then cancel the rest.\n if (!res.body) throw new Error(`bitgpu/gguf: ${url} has no readable body`)\n const reader = res.body.getReader()\n const out = new Uint8Array(len)\n let seen = 0 // bytes of the FILE consumed so far\n let filled = 0 // bytes of `out` filled so far\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n const start = Math.max(off - seen, 0)\n if (value.byteLength > start) {\n const take = Math.min(value.byteLength - start, len - filled)\n out.set(value.subarray(start, start + take), filled)\n filled += take\n }\n seen += value.byteLength\n if (filled >= len) {\n reader.cancel().catch(() => {})\n break\n }\n }\n return out.buffer.slice(0, filled) as ArrayBuffer\n}\n\n/** The two expansion tables the kernels use, generated from their defining property:\n * LSB-first sign bits -> per-weight codes around the recipe midpoints (2-bit: {1,3},\n * 4-bit: {7,9}). Byte-identical to the tables the ONNX exports carry. */\nexport function ggufLuts(): Uint8Array {\n const aux = new Uint8Array(512 + 1024) // tgt2 [256,2] then tgt4 [256,4]\n for (let b = 0; b < 256; b++) {\n for (let j = 0; j < 8; j++) {\n const bit = (b >> j) & 1\n aux[b * 2 + (j >> 2)] |= (bit ? 3 : 1) << (2 * (j % 4))\n aux[512 + b * 4 + (j >> 1)] |= (bit ? 9 : 7) << (4 * (j % 2))\n }\n }\n return aux\n}\n\nfunction basename(url: string): string {\n const path = url.split(/[?#]/)[0]\n return decodeURIComponent(path.slice(path.lastIndexOf('/') + 1)) || 'model.gguf'\n}\n\n/** Build the manifest from a parsed header - the exact mapping tools/convert-gguf.py performs. */\nfunction buildManifest(h: Header, dataFile: string): Manifest {\n const { meta, tensors: gg, dataStart } = h\n const archName = meta['general.architecture'] as string\n if (archName !== 'qwen3')\n throw new Error(`bitgpu/gguf: unsupported architecture '${archName}' (bitgpu kernels implement the qwen3 topology)`)\n const P = (k: string): unknown => {\n const v = meta[`${archName}.${k}`]\n if (v === undefined) throw new Error(`bitgpu/gguf: header is missing ${archName}.${k}`)\n return v\n }\n\n const headDim = Number(P('attention.key_length'))\n if (headDim !== Number(P('attention.value_length')))\n throw new Error('bitgpu/gguf: key_length != value_length (kernels assume one head_dim)')\n const layers = Number(P('block_count'))\n const embd = gg['token_embd.weight']\n if (!embd) throw new Error('bitgpu/gguf: header has no token_embd.weight tensor')\n const vocab = embd.dims[1]\n const tied = !('output.weight' in gg)\n const scalingType = meta[`${archName}.rope.scaling.type`]\n const rope: NonNullable<Manifest['arch']['rope']> = { rope_theta: Number(P('rope.freq_base')) }\n if (scalingType === 'yarn') {\n rope.rope_type = 'yarn'\n rope.factor = Number(P('rope.scaling.factor'))\n rope.original_max_position_embeddings = Number(P('rope.scaling.original_context_length'))\n } else if (scalingType !== undefined && scalingType !== 'none') {\n throw new Error(`bitgpu/gguf: unsupported rope scaling '${scalingType}'`)\n }\n\n /** The interleaved Q1_0 byte range of a tensor inside the GGUF (used unchanged). */\n const region = (gname: string, N: number, K: number): ManifestRef => {\n const t = gg[gname]\n if (!t) throw new Error(`bitgpu/gguf: header has no ${gname} tensor`)\n if (t.type !== Q1_0) throw new Error(`bitgpu/gguf: ${gname}: expected ggml type 41 (Q1_0), got ${t.type}`)\n if (K % 128 !== 0) throw new Error(`bitgpu/gguf: ${gname}: K=${K} not a multiple of the 128-wide blocks`)\n const [gk, gn] = t.dims.length === 2 ? [t.dims[0], t.dims[1]] : [t.dims[0], 1]\n if (gk !== K || gn !== N) throw new Error(`bitgpu/gguf: ${gname}: dims [${t.dims}] do not match expected [${K}, ${N}]`)\n return { dtype: 'UINT8', shape: [N, (K / 128) * BLK], src: 'data', off: dataStart + t.off, len: N * (K / 128) * BLK }\n }\n const normRef = (gname: string, n: number): ManifestRef => {\n const t = gg[gname]\n if (!t) throw new Error(`bitgpu/gguf: header has no ${gname} tensor`)\n if (t.type !== F32) throw new Error(`bitgpu/gguf: ${gname}: expected F32 norm, got ggml type ${t.type}`)\n if (t.dims.length !== 1 || t.dims[0] !== n) throw new Error(`bitgpu/gguf: ${gname}: dims [${t.dims}] != [${n}]`)\n return { dtype: 'FLOAT', shape: [n], src: 'data', off: dataStart + t.off, len: n * 4 }\n }\n\n const hidden = Number(P('embedding_length'))\n const inter = Number(P('feed_forward_length'))\n const heads = Number(P('attention.head_count'))\n const kvHeads = Number(P('attention.head_count_kv'))\n const SHAPES: Record<string, [number, number]> = {\n attn_q: [heads * headDim, hidden],\n attn_k: [kvHeads * headDim, hidden],\n attn_v: [kvHeads * headDim, hidden],\n attn_output: [hidden, heads * headDim],\n ffn_gate: [inter, hidden],\n ffn_up: [inter, hidden],\n ffn_down: [hidden, inter],\n }\n const tensors: Record<string, ManifestTensor> = {}\n for (let li = 0; li < layers; li++) {\n for (const [gk, lk] of Object.entries(LINEAR)) {\n const [N, K] = SHAPES[gk]\n tensors[`layers.${li}.${lk}`] = {\n kind: 'binary', N, K, block: 128, bits: 2, lut: 'tgt2',\n container: 'q1_0', weight: region(`blk.${li}.${gk}.weight`, N, K),\n }\n }\n for (const [gk, lk] of Object.entries(NORM)) {\n const n = gk.includes('q_norm') || gk.includes('k_norm') ? headDim : hidden\n tensors[`layers.${li}.${lk}`] = { kind: 'f32', weight: normRef(`blk.${li}.${gk}.weight`, n) }\n }\n }\n tensors[`layers.${layers}.final_norm_layernorm`] = { kind: 'f32', weight: normRef('output_norm.weight', hidden) }\n tensors['embed_tokens'] = {\n kind: 'q4', rows: vocab, cols: hidden, block: 128, bits: 4, lut: 'tgt4',\n container: 'q1_0', weight: region('token_embd.weight', vocab, hidden),\n }\n tensors['lm_head'] = {\n kind: 'q2', N: vocab, K: hidden, block: 128, bits: 2, lut: 'tgt2',\n container: 'q1_0', weight: region(tied ? 'token_embd.weight' : 'output.weight', vocab, hidden),\n }\n\n const eos = meta['tokenizer.ggml.eos_token_id']\n if (eos === undefined) throw new Error('bitgpu/gguf: header is missing tokenizer.ggml.eos_token_id')\n const stem = dataFile.replace(/\\.gguf$/i, '')\n return {\n version: 2,\n data_file: dataFile,\n aux_file: `${stem}.aux.bin`,\n arch: {\n model_type: archName, layers, hidden, intermediate: inter,\n heads, kv_heads: kvHeads, head_dim: headDim,\n rms_eps: Number(P('attention.layer_norm_rms_epsilon')),\n rope, max_positions: Number(P('context_length')),\n vocab, eos: Number(eos),\n tie_word_embeddings: tied, act: 'silu',\n },\n luts: {\n tgt2: { dtype: 'UINT8', shape: [256, 2], src: 'aux', off: 0, len: 512 },\n tgt4: { dtype: 'UINT8', shape: [256, 4], src: 'aux', off: 512, len: 1024 },\n },\n tensors,\n }\n}\n\n/** Parse a GGUF header already in memory (e.g. from a File). Grows nothing - the buffer must\n * contain the full header (weights past it are not needed). */\nexport function fromGgufBytes(buf: ArrayBuffer, dataFile: string): { manifest: Manifest; aux: Uint8Array } {\n try {\n return { manifest: buildManifest(parseHeader(buf), dataFile), aux: ggufLuts() }\n } catch (e) {\n if (e instanceof OutOfData) throw new Error('bitgpu/gguf: buffer ends inside the GGUF header (pass more bytes)')\n throw e\n }\n}\n\n/** Fetch and parse a GGUF header; returns `{ manifest, aux, dataUrl }` for createEngine.\n * Only the header is transferred, progressively: 1 MiB first, then EXTENSION ranges (2x\n * growth) appended to the kept prefix - total transfer stays under 2x the header size. */\nexport async function fromGguf(url: string, options: FromGgufOptions = {}): Promise<GgufModel> {\n const fetchRange = options.fetchRange ?? fetchRangeHttp\n const cap = options.maxHeaderBytes ?? 64 << 20\n let size = FIRST_FETCH\n let have = new Uint8Array(await fetchRange(url, 0, size))\n for (;;) {\n try {\n // `have` always owns its exactly-sized buffer (fresh Uint8Array per round)\n const manifest = buildManifest(parseHeader(have.buffer as ArrayBuffer), basename(url))\n return { manifest, aux: ggufLuts(), dataUrl: url }\n } catch (e) {\n if (!(e instanceof OutOfData)) throw e\n if (have.byteLength < size) throw new Error(`bitgpu/gguf: ${url} ends inside its own header (truncated file?)`)\n if (size >= cap) throw new Error(`bitgpu/gguf: header exceeds maxHeaderBytes (${cap}); raise the cap if this is a real model`)\n const next = Math.min(size * 2, cap)\n const ext = new Uint8Array(await fetchRange(url, have.byteLength, next - have.byteLength))\n const grown = new Uint8Array(have.byteLength + ext.byteLength)\n grown.set(have, 0)\n grown.set(ext, have.byteLength)\n have = grown\n size = next\n }\n }\n}\n"],"mappings":";AAmCA,MAAM,MAAM;AACZ,MAAM,OAAO;AACb,MAAM,MAAM;AACZ,MAAM,cAAc,KAAK;AAEzB,MAAM,SAAiC;CACrC,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,aAAa;CACb,UAAU;CACV,QAAQ;CACR,UAAU;AACZ;AACA,MAAM,OAA+B;CACnC,WAAW;CACX,UAAU;CACV,aAAa;CACb,aAAa;AACf;;AAGA,IAAM,YAAN,cAAwB,MAAM,CAAC;AAa/B,SAAS,YAAY,GAAW,MAAsB;CACpD,IAAI,IAAI,OAAO,OAAO,gBAAgB,GAAG,MAAM,IAAI,MAAM,gBAAgB,KAAK,GAAG,EAAE,4BAA4B;CAC/G,OAAO,OAAO,CAAC;AACjB;;AAGA,SAAS,YAAY,KAA0B;CAC7C,MAAM,KAAK,IAAI,SAAS,GAAG;CAC3B,MAAM,KAAK,IAAI,WAAW,GAAG;CAC7B,MAAM,KAAK,IAAI,YAAY;CAC3B,IAAI,MAAM;CACV,MAAM,QAAQ,MAAc;EAC1B,IAAI,MAAM,IAAI,IAAI,YAAY,MAAM,IAAI,UAAU;CACpD;CACA,MAAM,YAAY;EAChB,KAAK,CAAC;EACN,MAAM,IAAI,GAAG,UAAU,KAAK,IAAI;EAChC,OAAO;EACP,OAAO;CACT;CAC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;EAAI;CACnD,SAAS,GAAG;EACV,IAAI,EAAE,aAAa,YAAY,MAAM;EACrC,IAAI,KAAK,aAAa,MAAM,MAAM,IAAI,MAAM,gBAAgB,IAAI,8CAA8C;EAC9G,IAAI,QAAQ,KAAK,MAAM,IAAI,MAAM,+CAA+C,IAAI,yCAAyC;EAC7H,MAAM,OAAO,KAAK,IAAI,OAAO,GAAG,GAAG;EACnC,MAAM,MAAM,IAAI,WAAW,MAAM,WAAW,KAAK,KAAK,YAAY,OAAO,KAAK,UAAU,CAAC;EACzF,MAAM,QAAQ,IAAI,WAAW,KAAK,aAAa,IAAI,UAAU;EAC7D,MAAM,IAAI,MAAM,CAAC;EACjB,MAAM,IAAI,KAAK,KAAK,UAAU;EAC9B,OAAO;EACP,OAAO;CACT;AAEJ"}
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as ForwardResult, c as KvSnapshot, i as EngineOptions, l as LoadProgress, n as Engine, o as GenerateOptions, r as EngineCapabilities, s as GenerateResult, t as DeviceLostInfo, u as TokenLogprobs } from "./types-Bl0FS_nX.js";
1
+ import { a as ForwardResult, c as KvSnapshot, d as ManifestArch, f as ManifestRef, i as EngineOptions, l as LoadProgress, m as TokenLogprobs, n as Engine, o as GenerateOptions, p as ManifestTensor, r as EngineCapabilities, s as GenerateResult, t as DeviceLostInfo, u as Manifest } from "./types-ByYx15Yw.js";
2
2
 
3
3
  //#region src/engine.d.ts
4
4
  /** Load a 1-bit model and return an {@link Engine}. Pass a model URL string for defaults. */
@@ -20,5 +20,5 @@ declare class GpuOutOfMemoryError extends Error {
20
20
  constructor(message: string);
21
21
  }
22
22
  //#endregion
23
- export { type DeviceLostInfo, type Engine, type EngineCapabilities, type EngineOptions, type ForwardResult, type GenerateOptions, type GenerateResult, GpuOutOfMemoryError, type KvSnapshot, type LoadProgress, type TokenLogprobs, WebGPUUnavailableError, createEngine };
23
+ export { type DeviceLostInfo, type Engine, type EngineCapabilities, type EngineOptions, type ForwardResult, type GenerateOptions, type GenerateResult, GpuOutOfMemoryError, type KvSnapshot, type LoadProgress, type Manifest, type ManifestArch, type ManifestRef, type ManifestTensor, type TokenLogprobs, WebGPUUnavailableError, createEngine };
24
24
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -279,7 +279,8 @@ async function createEngine(options) {
279
279
  async function createEngineInner(options, holder) {
280
280
  const opts = typeof options === "string" ? { modelUrl: options } : options;
281
281
  const modelDir = opts.modelUrl ? opts.modelUrl.replace(/\/$/, "") : null;
282
- if (!modelDir && !opts.manifestUrl) throw new Error("createEngine: provide modelUrl or manifestUrl");
282
+ if (!modelDir && !opts.manifestUrl && !opts.manifest) throw new Error("createEngine: provide modelUrl, manifestUrl, or an in-memory manifest");
283
+ if (opts.manifest && !modelDir && !opts.dataUrl) throw new Error("createEngine: an in-memory manifest needs dataUrl (or modelUrl) for the weights file");
283
284
  const powerPreference = opts.powerPreference ?? "high-performance";
284
285
  const fetchJson = opts.fetchJson ?? (async (url) => {
285
286
  const res = await fetch(url);
@@ -316,10 +317,12 @@ async function createEngineInner(options, holder) {
316
317
  });
317
318
  if (typeof navigator === "undefined" || !navigator.gpu) throw new WebGPUUnavailableError("WebGPU is not available (no navigator.gpu). Use a WebGPU-capable browser over a secure context.");
318
319
  opts.onProgress?.({ phase: "manifest" });
319
- const manifest = await fetchJson(opts.manifestUrl ?? `${modelDir}/manifest.json`);
320
+ const manifest = opts.manifest ?? await fetchJson(opts.manifestUrl ?? `${modelDir}/manifest.json`);
320
321
  opts.onProgress?.({ phase: "weights" });
321
322
  const dataUrl = opts.dataUrl ?? `${modelDir}/${manifest.data_file}`;
322
- let aux = await fetchBytes(opts.auxUrl ?? `${modelDir}/${manifest.aux_file}`);
323
+ let aux;
324
+ if (opts.aux) aux = opts.aux instanceof Uint8Array ? new Uint8Array(opts.aux).buffer : opts.aux;
325
+ else aux = await fetchBytes(opts.auxUrl ?? `${modelDir}/${manifest.aux_file}`);
323
326
  const A = manifest.arch;
324
327
  const T = manifest.tensors;
325
328
  const FINAL_NORM = `layers.${A.layers}.final_norm_layernorm`;