bitgpu 0.3.0 → 0.4.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/dist/index.d.ts +7 -0
- package/dist/index.js +204 -68
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -24,6 +24,13 @@ interface EngineOptions {
|
|
|
24
24
|
fetchJson?: (url: string) => Promise<unknown>;
|
|
25
25
|
/** Fetch binary (data/aux). Override to add caching (e.g. OPFS) for the ~290MB data file. Default: `fetch(url).arrayBuffer()`. */
|
|
26
26
|
fetchArrayBuffer?: (url: string) => Promise<ArrayBuffer>;
|
|
27
|
+
/** Stream the big weights DATA file: chunks flow straight into GPU buffers, so the whole
|
|
28
|
+
* ~290MB file never sits in memory at once (critical on phones, where the buffered peak gets
|
|
29
|
+
* the tab killed). Used for the data file only (manifest/aux stay on fetchJson/fetchArrayBuffer);
|
|
30
|
+
* when set it takes precedence over fetchArrayBuffer for that file. Point it at a cache stream,
|
|
31
|
+
* e.g. an OPFS file's `stream()`. Default: the data file streams from `fetch(url).body`
|
|
32
|
+
* (or through `fetchArrayBuffer` when that override is provided, for back compatibility). */
|
|
33
|
+
fetchStream?: (url: string) => Promise<ReadableStream<Uint8Array>>;
|
|
27
34
|
/** GPU power preference. Default `'high-performance'` (picks the discrete GPU on multi-GPU machines).
|
|
28
35
|
* (Spelled out rather than `GPUPowerPreference` so the published d.ts resolves without @webgpu/types.) */
|
|
29
36
|
powerPreference?: 'low-power' | 'high-performance';
|
package/dist/index.js
CHANGED
|
@@ -211,17 +211,6 @@ const eqBytes = (a, b) => {
|
|
|
211
211
|
for (let i = 0; i < b.length; i++) if (a[i] !== b[i]) return false;
|
|
212
212
|
return true;
|
|
213
213
|
};
|
|
214
|
-
function concat(Cls, arrs) {
|
|
215
|
-
let n = 0;
|
|
216
|
-
for (const a of arrs) n += a.length;
|
|
217
|
-
const o = new Cls(n);
|
|
218
|
-
let p = 0;
|
|
219
|
-
for (const a of arrs) {
|
|
220
|
-
o.set(a, p);
|
|
221
|
-
p += a.length;
|
|
222
|
-
}
|
|
223
|
-
return o;
|
|
224
|
-
}
|
|
225
214
|
/** Load a 1-bit model and return an {@link Engine}. Pass a model URL string for defaults. */
|
|
226
215
|
async function createEngine(options) {
|
|
227
216
|
const opts = typeof options === "string" ? { modelUrl: options } : options;
|
|
@@ -266,8 +255,7 @@ async function createEngine(options) {
|
|
|
266
255
|
const manifest = await fetchJson(opts.manifestUrl ?? `${modelDir}/manifest.json`);
|
|
267
256
|
opts.onProgress?.({ phase: "weights" });
|
|
268
257
|
const dataUrl = opts.dataUrl ?? `${modelDir}/${manifest.data_file}`;
|
|
269
|
-
|
|
270
|
-
let [data, aux] = await Promise.all([fetchBytes(dataUrl), fetchBytes(auxUrl)]);
|
|
258
|
+
let aux = await fetchBytes(opts.auxUrl ?? `${modelDir}/${manifest.aux_file}`);
|
|
271
259
|
const A = manifest.arch;
|
|
272
260
|
const T = manifest.tensors;
|
|
273
261
|
const FINAL_NORM = `layers.${A.layers}.final_norm_layernorm`;
|
|
@@ -276,16 +264,15 @@ async function createEngine(options) {
|
|
|
276
264
|
if (!T[FINAL_NORM]) throw new Error(`bitgpu: manifest is missing the final norm tensor '${FINAL_NORM}'`);
|
|
277
265
|
for (const [name, t] of Object.entries(T)) if (t.block !== void 0 && t.block !== 128) throw new Error(`bitgpu: tensor ${name} has block ${t.block} (kernels assume 128)`);
|
|
278
266
|
const readRef = (ref) => {
|
|
279
|
-
|
|
280
|
-
if (ref.off + ref.len >
|
|
267
|
+
if (ref.src !== "aux") throw new Error("bitgpu: internal - readRef reads aux-file refs; data-file tensors stream through routes");
|
|
268
|
+
if (ref.off + ref.len > aux.byteLength) throw new Error(`bitgpu: tensor range ${ref.off}+${ref.len} exceeds the aux file (${aux.byteLength} bytes); the download is truncated or the manifest does not match it`);
|
|
281
269
|
const V = VIEW[ref.dtype];
|
|
282
|
-
if (V === Uint8Array) return new Uint8Array(
|
|
270
|
+
if (V === Uint8Array) return new Uint8Array(aux, ref.off, ref.len);
|
|
283
271
|
const bpe = V.BYTES_PER_ELEMENT;
|
|
284
|
-
if (ref.off % bpe === 0) return new V(
|
|
285
|
-
return new V(
|
|
272
|
+
if (ref.off % bpe === 0) return new V(aux, ref.off, ref.len / bpe);
|
|
273
|
+
return new V(aux.slice(ref.off, ref.off + ref.len));
|
|
286
274
|
};
|
|
287
275
|
const readU8 = (ref) => readRef(ref);
|
|
288
|
-
const readF32 = (ref) => readRef(ref);
|
|
289
276
|
const adapter = await navigator.gpu.requestAdapter({ powerPreference });
|
|
290
277
|
if (!adapter) throw new WebGPUUnavailableError("No suitable WebGPU adapter was found.");
|
|
291
278
|
const hasSG = adapter.features.has("subgroups");
|
|
@@ -449,94 +436,243 @@ async function createEngine(options) {
|
|
|
449
436
|
const resetCache = () => {
|
|
450
437
|
fullHistory = [];
|
|
451
438
|
};
|
|
439
|
+
if (manifest.luts.tgt2.src !== "aux") throw new Error("bitgpu: luts.tgt2 must live in the aux file (the streaming loader needs it before the weights arrive)");
|
|
452
440
|
const tgt2 = readU8(manifest.luts.tgt2);
|
|
453
|
-
let tgt4 = readU8(manifest.luts.tgt4);
|
|
454
441
|
const signTable = /* @__PURE__ */ new Uint8Array(256);
|
|
455
442
|
for (let b = 0; b < 256; b++) {
|
|
456
443
|
let bits = 0;
|
|
457
444
|
for (let j = 0; j < 8; j++) bits |= ((tgt2[2 * b + (j >> 2)] >> 2 * (j & 3) & 3) >> 1 & 1) << j;
|
|
458
445
|
signTable[b] = bits;
|
|
459
446
|
}
|
|
460
|
-
const
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
447
|
+
const routes = [];
|
|
448
|
+
const gbuf = (len) => device.createBuffer({
|
|
449
|
+
size: len + 3 & -4,
|
|
450
|
+
usage: S_ | CD
|
|
451
|
+
});
|
|
452
|
+
const gpuSink = (buf, base) => {
|
|
453
|
+
let written = 0;
|
|
454
|
+
let carry = /* @__PURE__ */ new Uint8Array(0);
|
|
465
455
|
return {
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
456
|
+
push(bytes) {
|
|
457
|
+
let all = bytes;
|
|
458
|
+
if (carry.length) {
|
|
459
|
+
all = new Uint8Array(carry.length + bytes.length);
|
|
460
|
+
all.set(carry);
|
|
461
|
+
all.set(bytes, carry.length);
|
|
462
|
+
}
|
|
463
|
+
const n = all.length & -4;
|
|
464
|
+
if (n) device.queue.writeBuffer(buf, base + written, all, 0, n);
|
|
465
|
+
carry = all.subarray(n).slice();
|
|
466
|
+
written += n;
|
|
467
|
+
},
|
|
468
|
+
finish() {
|
|
469
|
+
if (!carry.length) return;
|
|
470
|
+
const pad = /* @__PURE__ */ new Uint8Array(4);
|
|
471
|
+
pad.set(carry);
|
|
472
|
+
device.queue.writeBuffer(buf, base + written, pad);
|
|
473
|
+
written += 4;
|
|
474
|
+
carry = /* @__PURE__ */ new Uint8Array(0);
|
|
475
|
+
}
|
|
476
|
+
};
|
|
477
|
+
};
|
|
478
|
+
const wire = (ref, push, finish) => {
|
|
479
|
+
if (ref.src === "aux") {
|
|
480
|
+
push(new Uint8Array(readRef(ref).buffer, ref.off, ref.len));
|
|
481
|
+
finish();
|
|
482
|
+
} else routes.push({
|
|
483
|
+
off: ref.off,
|
|
484
|
+
len: ref.len,
|
|
485
|
+
push,
|
|
486
|
+
finish
|
|
487
|
+
});
|
|
488
|
+
};
|
|
489
|
+
const wireRaw = (ref, buf, base = 0) => {
|
|
490
|
+
const s = gpuSink(buf, base);
|
|
491
|
+
wire(ref, s.push, s.finish);
|
|
492
|
+
};
|
|
493
|
+
const wireSign = (ref, buf, base = 0) => {
|
|
494
|
+
const s = gpuSink(buf, base);
|
|
495
|
+
wire(ref, (b) => {
|
|
496
|
+
const o = new Uint8Array(b.length);
|
|
497
|
+
for (let i = 0; i < b.length; i++) o[i] = signTable[b[i]];
|
|
498
|
+
s.push(o);
|
|
499
|
+
}, s.finish);
|
|
500
|
+
};
|
|
501
|
+
const wireQ2 = (ref, buf) => {
|
|
502
|
+
const s = gpuSink(buf, 0);
|
|
503
|
+
wire(ref, (b) => {
|
|
504
|
+
const o = new Uint8Array(b.length * 2);
|
|
505
|
+
for (let i = 0; i < b.length; i++) {
|
|
506
|
+
o[2 * i] = tgt2[2 * b[i]];
|
|
507
|
+
o[2 * i + 1] = tgt2[2 * b[i] + 1];
|
|
508
|
+
}
|
|
509
|
+
s.push(o);
|
|
510
|
+
}, s.finish);
|
|
511
|
+
};
|
|
512
|
+
const wireCpu = (ref) => {
|
|
513
|
+
const dst = new Uint8Array(ref.len);
|
|
514
|
+
let w = 0;
|
|
515
|
+
wire(ref, (b) => {
|
|
516
|
+
dst.set(b, w);
|
|
517
|
+
w += b.length;
|
|
518
|
+
}, () => void 0);
|
|
519
|
+
return dst;
|
|
520
|
+
};
|
|
521
|
+
const wireCpuGpu = (ref) => {
|
|
522
|
+
const buf = gbuf(ref.len);
|
|
523
|
+
const s = gpuSink(buf, 0);
|
|
524
|
+
const dst = new Uint8Array(ref.len);
|
|
525
|
+
let w = 0;
|
|
526
|
+
wire(ref, (b) => {
|
|
527
|
+
dst.set(b, w);
|
|
528
|
+
w += b.length;
|
|
529
|
+
s.push(b);
|
|
530
|
+
}, s.finish);
|
|
531
|
+
return {
|
|
532
|
+
cpu: dst,
|
|
533
|
+
buf
|
|
471
534
|
};
|
|
472
535
|
};
|
|
473
536
|
device.pushErrorScope("out-of-memory");
|
|
474
537
|
const W = {};
|
|
475
538
|
for (const [name, t] of Object.entries(T)) if (t.kind === "q2") {
|
|
476
|
-
const
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
}
|
|
539
|
+
const codes = gbuf(t.weight.len * 2);
|
|
540
|
+
wireQ2(t.weight, codes);
|
|
541
|
+
const scales = gbuf(t.scales.len);
|
|
542
|
+
wireRaw(t.scales, scales);
|
|
481
543
|
W[name] = {
|
|
482
544
|
N: t.N,
|
|
483
545
|
K: t.K,
|
|
484
546
|
nb: t.K / 128,
|
|
485
547
|
zp: 2,
|
|
486
|
-
codes
|
|
487
|
-
scales
|
|
548
|
+
codes,
|
|
549
|
+
scales
|
|
550
|
+
};
|
|
551
|
+
} else if (t.kind === "f32" && t.weight) {
|
|
552
|
+
const buf = gbuf(t.weight.len);
|
|
553
|
+
wireRaw(t.weight, buf);
|
|
554
|
+
W[name] = { buf };
|
|
555
|
+
}
|
|
556
|
+
const fuse = (parts) => {
|
|
557
|
+
const sign = gbuf(parts.reduce((n, p) => n + p.weight.len, 0));
|
|
558
|
+
const scales = gbuf(parts.reduce((n, p) => n + p.scales.len, 0));
|
|
559
|
+
let so = 0;
|
|
560
|
+
let co = 0;
|
|
561
|
+
for (const p of parts) {
|
|
562
|
+
wireSign(p.weight, sign, so);
|
|
563
|
+
so += p.weight.len;
|
|
564
|
+
wireRaw(p.scales, scales, co);
|
|
565
|
+
co += p.scales.len;
|
|
566
|
+
}
|
|
567
|
+
return {
|
|
568
|
+
sign,
|
|
569
|
+
scales
|
|
488
570
|
};
|
|
489
|
-
}
|
|
571
|
+
};
|
|
490
572
|
for (let li = 0; li < A.layers; li++) {
|
|
491
|
-
const q =
|
|
573
|
+
const q = T[`layers.${li}.attn.q_proj`], k = T[`layers.${li}.attn.k_proj`], v = T[`layers.${li}.attn.v_proj`];
|
|
492
574
|
W[`layers.${li}.attn.qkv`] = {
|
|
493
575
|
K: q.K,
|
|
494
|
-
nb: q.
|
|
576
|
+
nb: q.K / 128,
|
|
495
577
|
N0: q.N,
|
|
496
578
|
N1: k.N,
|
|
497
579
|
N2: v.N,
|
|
498
|
-
|
|
499
|
-
q
|
|
500
|
-
k
|
|
501
|
-
v
|
|
502
|
-
])
|
|
503
|
-
scales: upload(concat(Float32Array, [
|
|
504
|
-
q.scales,
|
|
505
|
-
k.scales,
|
|
506
|
-
v.scales
|
|
507
|
-
]))
|
|
580
|
+
...fuse([
|
|
581
|
+
q,
|
|
582
|
+
k,
|
|
583
|
+
v
|
|
584
|
+
])
|
|
508
585
|
};
|
|
509
|
-
const g =
|
|
586
|
+
const g = T[`layers.${li}.mlp.gate_proj`], u = T[`layers.${li}.mlp.up_proj`];
|
|
510
587
|
W[`layers.${li}.mlp.gateup`] = {
|
|
511
588
|
K: g.K,
|
|
512
|
-
nb: g.
|
|
589
|
+
nb: g.K / 128,
|
|
513
590
|
N0: g.N,
|
|
514
591
|
N1: u.N,
|
|
515
592
|
N2: 0,
|
|
516
|
-
|
|
517
|
-
scales: upload(concat(Float32Array, [g.scales, u.scales]))
|
|
593
|
+
...fuse([g, u])
|
|
518
594
|
};
|
|
519
595
|
for (const nm of [`layers.${li}.attn.o_proj`, `layers.${li}.mlp.down_proj`]) {
|
|
520
|
-
const r =
|
|
596
|
+
const r = T[nm];
|
|
521
597
|
W[nm] = {
|
|
522
598
|
N: r.N,
|
|
523
599
|
K: r.K,
|
|
524
|
-
nb: r.
|
|
525
|
-
|
|
526
|
-
scales: upload(r.scales)
|
|
600
|
+
nb: r.K / 128,
|
|
601
|
+
...fuse([r])
|
|
527
602
|
};
|
|
528
603
|
}
|
|
529
604
|
}
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
const
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
605
|
+
const embW = wireCpuGpu(T.embed_tokens.weight);
|
|
606
|
+
const embS = wireCpuGpu(T.embed_tokens.scales);
|
|
607
|
+
const embZ = wireCpuGpu(T.embed_tokens.zp);
|
|
608
|
+
const tgt4W = wireCpuGpu(manifest.luts.tgt4);
|
|
609
|
+
const cosBytes = wireCpu(T.cos_cache);
|
|
610
|
+
const sinBytes = wireCpu(T.sin_cache);
|
|
611
|
+
const embWq = embW.cpu;
|
|
612
|
+
const embScales = new Float32Array(embS.cpu.buffer);
|
|
613
|
+
const embZp = embZ.cpu;
|
|
614
|
+
const tgt4 = tgt4W.cpu;
|
|
615
|
+
const cosCache = new Float32Array(cosBytes.buffer);
|
|
616
|
+
const sinCache = new Float32Array(sinBytes.buffer);
|
|
617
|
+
const embWqG = embW.buf, tgt4G = tgt4W.buf, embScalesG = embS.buf, embZpG = embZ.buf;
|
|
618
|
+
routes.sort((a, b) => a.off - b.off || a.len - b.len);
|
|
619
|
+
const merged = [];
|
|
620
|
+
for (const r of routes) {
|
|
621
|
+
const last = merged[merged.length - 1];
|
|
622
|
+
if (last && last.off === r.off && last.len === r.len) {
|
|
623
|
+
const lp = last.push, lf = last.finish;
|
|
624
|
+
last.push = (b) => {
|
|
625
|
+
lp(b);
|
|
626
|
+
r.push(b);
|
|
627
|
+
};
|
|
628
|
+
last.finish = () => {
|
|
629
|
+
lf();
|
|
630
|
+
r.finish();
|
|
631
|
+
};
|
|
632
|
+
} else if (last && r.off < last.off + last.len) throw new Error("bitgpu: partially overlapping data-file tensor ranges (unsupported by the streaming loader)");
|
|
633
|
+
else merged.push(r);
|
|
634
|
+
}
|
|
635
|
+
const needed = merged.length ? merged[merged.length - 1].off + merged[merged.length - 1].len : 0;
|
|
636
|
+
const reader = (opts.fetchStream ? await opts.fetchStream(dataUrl) : opts.fetchArrayBuffer ? new Response(await opts.fetchArrayBuffer(dataUrl)).body : await (async () => {
|
|
637
|
+
const res = await fetch(dataUrl);
|
|
638
|
+
if (!res.ok) throw new Error(`bitgpu: fetch ${dataUrl} failed: HTTP ${res.status}`);
|
|
639
|
+
return res.body ?? new Response(await res.arrayBuffer()).body;
|
|
640
|
+
})()).getReader();
|
|
641
|
+
let cursor = 0;
|
|
642
|
+
let ri = 0;
|
|
643
|
+
for (;;) {
|
|
644
|
+
const { done, value } = await reader.read();
|
|
645
|
+
if (done) break;
|
|
646
|
+
let bo = 0;
|
|
647
|
+
while (bo < value.byteLength && ri < merged.length) {
|
|
648
|
+
const r = merged[ri];
|
|
649
|
+
if (cursor >= r.off + r.len) {
|
|
650
|
+
ri++;
|
|
651
|
+
continue;
|
|
652
|
+
}
|
|
653
|
+
if (cursor < r.off) {
|
|
654
|
+
const skip = Math.min(r.off - cursor, value.byteLength - bo);
|
|
655
|
+
cursor += skip;
|
|
656
|
+
bo += skip;
|
|
657
|
+
continue;
|
|
658
|
+
}
|
|
659
|
+
const n = Math.min(r.off + r.len - cursor, value.byteLength - bo);
|
|
660
|
+
r.push(value.subarray(bo, bo + n));
|
|
661
|
+
cursor += n;
|
|
662
|
+
bo += n;
|
|
663
|
+
if (cursor === r.off + r.len) {
|
|
664
|
+
r.finish();
|
|
665
|
+
ri++;
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
cursor += value.byteLength - bo;
|
|
669
|
+
opts.onProgress?.({
|
|
670
|
+
phase: "weights",
|
|
671
|
+
loaded: Math.min(cursor, needed),
|
|
672
|
+
total: needed
|
|
673
|
+
});
|
|
674
|
+
}
|
|
675
|
+
if (cursor < needed) throw new Error(`bitgpu: the data file ended at ${cursor} bytes but tensors extend to ${needed}; the download is truncated or the manifest does not match it`);
|
|
540
676
|
aux = null;
|
|
541
677
|
function embedDequant(ids) {
|
|
542
678
|
const Hh = A.hidden, out = new Float32Array(ids.length * Hh);
|