LocalWebAgent / js /lazy-weights.js
ereniko's picture
v0.7.0: Qwen3.5 2B/4B, SmolLM3 3B, Llama 3.2 3B, Jan-nano 4B; drop Qwen3 4B
6b1f716 unverified
Raw History Blame Contribute Delete
4.9 kB
// Low-memory loading of the model's external weights (model_<dtype>.onnx_data, ~1.4 GB).
//
// By default transformers.js reads the whole file into one Uint8Array and hands it to
// onnxruntime, which then copies it tensor by tensor into GPU buffers. Until that finishes
// the weights exist twice: once in JS memory and once on the GPU. On phones and other
// devices with shared CPU/GPU memory that peak is what gets the tab's GPU process killed.
//
// Instead we keep the file in Cache Storage (streamed there, never fully in memory) and
// give onnxruntime a Blob-backed stand-in. onnxruntime only ever calls .byteLength and
// .subarray(begin, end) on mounted external data, so each tensor is read from disk with
// FileReaderSync right before it is uploaded. Peak extra memory becomes one tensor.
//
// Worker-only (FileReaderSync). Callers fall back to the default path if this throws.
const CACHE_NAME = "transformers-cache"; // the cache transformers.js uses; setup.js checks it too
/** Fetches a small text file from the model repo, cache-first, so it also works offline. */
export async function cachedRepoText(modelId, file) {
const url = `https://huggingface.co/${modelId}/resolve/main/${file}`;
const cache = await caches.open(CACHE_NAME);
let res = await cache.match(url);
if (!res) {
const net = await fetch(url);
if (!net.ok) throw new Error(`Download failed (${net.status}) for ${file}`);
await cache.put(url, net.clone());
res = net;
}
return res.text();
}
/** A Uint8Array (so transformers.js passes it through untouched) whose bytes live in a Blob. */
class BlobBytes extends Uint8Array {
#blob;
constructor(blob) {
super(0);
this.#blob = blob;
}
get byteLength() { return this.#blob.size; }
get length() { return this.#blob.size; }
subarray(begin = 0, end = this.#blob.size) {
return new Uint8Array(new FileReaderSync().readAsArrayBuffer(this.#blob.slice(begin, end)));
}
}
/** Streams url into Cache Storage, reporting progress like transformers.js does. */
async function download(cache, url, file, progress) {
const res = await fetch(url);
if (!res.ok || !res.body) throw new Error(`Download failed (${res.status}) for ${file}`);
const total = Number(res.headers.get("Content-Length")) || 0;
let loaded = 0;
let last = 0;
progress?.({ status: "initiate", file, loaded: 0, total });
const counted = res.body.pipeThrough(new TransformStream({
transform(chunk, ctl) {
loaded += chunk.byteLength;
const now = performance.now();
if (now - last > 200) { last = now; progress?.({ status: "progress", file, loaded, total }); }
ctl.enqueue(chunk);
},
}));
const headers = new Headers(res.headers);
await cache.put(url, new Response(counted, { status: 200, headers }));
if (total && loaded !== total) {
await cache.delete(url);
throw new Error(`Incomplete download of ${file} (${loaded} of ${total} bytes)`);
}
progress?.({ status: "done", file, loaded, total: total || loaded });
}
/** Gets one external-data file as a disk-backed BlobBytes, downloading it first if needed. */
async function lazyFile(cache, modelId, name, progress) {
const file = `onnx/${name}`;
const url = `https://huggingface.co/${modelId}/resolve/main/${file}`;
let res = await cache.match(url);
if (!res) {
await download(cache, url, file, progress);
res = await cache.match(url);
if (!res) throw new Error("weights were not stored in Cache Storage");
} else {
const size = Number(res.headers.get("Content-Length")) || 0;
progress?.({ status: "done", file, loaded: size, total: size });
}
const blob = await res.blob(); // disk-backed in Chromium; not read into memory
if (!blob.size) throw new Error(`cached ${name} is empty`);
return new BlobBytes(blob);
}
/**
* Returns from_pretrained options that make onnxruntime read the external weights
* (<file>_<dtype>.onnx_data, _data_1, ...) lazily from Cache Storage, downloading them
* first if needed.
*/
export async function lazyWeightsOptions(modelId, dtype, graphs, progress) {
if (typeof FileReaderSync === "undefined" || !self.caches) throw new Error("lazy weights unsupported here");
const cache = await caches.open(CACHE_NAME);
const externalData = [];
for (const { file, chunks } of graphs) {
for (let i = 0; i < chunks; i++) {
const name = `${file}_${dtype}.onnx_data${i === 0 ? "" : "_" + i}`;
externalData.push({ path: name, data: await lazyFile(cache, modelId, name, progress) });
}
}
return {
// Stop transformers.js from fetching the .onnx_data files itself...
use_external_data_format: false,
// ...and mount ours under the names the ONNX graphs refer to. Every session gets the
// whole list; each graph only reads the files it references, and nothing is read
// until it does.
session_options: { externalData },
};
}