@tanstack-ai-browser/onnx 0.0.0-stage → 0.3.4

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.
@@ -0,0 +1,32 @@
1
+ /**
2
+ * The catalog: image models this adapter runs, by their Hugging Face
3
+ * repository. Each one's files are pinned to a commit, so a later change
4
+ * to the repository can't change what an app loads.
5
+ */
6
+ /**
7
+ * Tessera-small by Jagrat Patel (TheJagStudio): 16×16 pixel-art sprites
8
+ * from text, a 47.6M-parameter masked-diffusion transformer conditioned on
9
+ * OpenAI's CLIP ViT-B/32 text encoder. This is cfahlgren1's int8 ONNX build
10
+ * of both. CC BY-NC 4.0: no commercial use of the model or its images.
11
+ */
12
+ const TESSERA_SMALL = {
13
+ name: "cfahlgren1/tessera-small-onnx",
14
+ revision: "bef21be58afea4d16be21f5fbe85eaa0cae69290",
15
+ size: "16x16",
16
+ download: "115 MB",
17
+ license: "CC BY-NC 4.0",
18
+ files: {
19
+ denoiser: { path: "tessera_w8.onnx", bytes: 50834182 },
20
+ textEncoder: { path: "clip_text_w8.onnx", bytes: 64060515 },
21
+ tokenizer: { path: "tokenizer.json", bytes: 0 },
22
+ palette: { path: "palette.json", bytes: 0 }
23
+ }
24
+ };
25
+ /** The catalog's models, by their Hugging Face repository. */
26
+ export const ONNX_IMAGE_MODELS = [TESSERA_SMALL.name];
27
+ /** Each model's entry, by name. */
28
+ export const ONNX_MODEL_META = {
29
+ [TESSERA_SMALL.name]: TESSERA_SMALL
30
+ };
31
+ /** A file's URL at the model's pinned commit. */
32
+ export const fileUrl = (meta, file) => `https://huggingface.co/${meta.name}/resolve/${meta.revision}/${file.path}`;
package/dist/png.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ /**
2
+ * PNG encoding of RGBA pixels, with the platform's own deflate
3
+ * (`CompressionStream`), so it works in a page, a worker and Node alike.
4
+ */
5
+ /** A PNG of `width`×`height` RGBA pixels (8 bits a channel, rows top to bottom). */
6
+ export declare function encodePng(rgba: Uint8Array | Uint8ClampedArray, width: number, height: number): Promise<Uint8Array>;
7
+ /** Bytes as base64. */
8
+ export declare function toBase64(bytes: Uint8Array): string;
9
+ //# sourceMappingURL=png.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"png.d.ts","sourceRoot":"","sources":["../src/png.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAkCH,oFAAoF;AACpF,wBAAsB,SAAS,CAAC,IAAI,EAAE,UAAU,GAAG,iBAAiB,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CAwBxH;AAED,uBAAuB;AACvB,wBAAgB,QAAQ,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAIlD"}
package/dist/png.js ADDED
@@ -0,0 +1,70 @@
1
+ /**
2
+ * PNG encoding of RGBA pixels, with the platform's own deflate
3
+ * (`CompressionStream`), so it works in a page, a worker and Node alike.
4
+ */
5
+ const CRC_TABLE = (() => {
6
+ const table = new Uint32Array(256);
7
+ for (let n = 0; n < 256; n++) {
8
+ let c = n;
9
+ for (let k = 0; k < 8; k++)
10
+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
11
+ table[n] = c >>> 0;
12
+ }
13
+ return table;
14
+ })();
15
+ function crc32(bytes) {
16
+ let c = 0xffffffff;
17
+ for (const byte of bytes)
18
+ c = CRC_TABLE[(c ^ byte) & 0xff] ^ (c >>> 8);
19
+ return (c ^ 0xffffffff) >>> 0;
20
+ }
21
+ function chunk(type, data) {
22
+ const out = new Uint8Array(12 + data.length);
23
+ const view = new DataView(out.buffer);
24
+ view.setUint32(0, data.length);
25
+ for (let i = 0; i < 4; i++)
26
+ out[4 + i] = type.charCodeAt(i);
27
+ out.set(data, 8);
28
+ view.setUint32(8 + data.length, crc32(out.subarray(4, 8 + data.length)));
29
+ return out;
30
+ }
31
+ /** zlib-wrapped deflate, as PNG's image data is. */
32
+ async function deflate(bytes) {
33
+ const stream = new Blob([bytes]).stream().pipeThrough(new CompressionStream("deflate"));
34
+ return new Uint8Array(await new Response(stream).arrayBuffer());
35
+ }
36
+ /** A PNG of `width`×`height` RGBA pixels (8 bits a channel, rows top to bottom). */
37
+ export async function encodePng(rgba, width, height) {
38
+ if (rgba.length !== width * height * 4)
39
+ throw new Error(`Expected ${width * height * 4} RGBA bytes, got ${rgba.length}`);
40
+ // Each row starts with its filter type: 0, none.
41
+ const raw = new Uint8Array(height * (1 + width * 4));
42
+ for (let y = 0; y < height; y++)
43
+ raw.set(rgba.subarray(y * width * 4, (y + 1) * width * 4), y * (1 + width * 4) + 1);
44
+ const header = new Uint8Array(13);
45
+ const view = new DataView(header.buffer);
46
+ view.setUint32(0, width);
47
+ view.setUint32(4, height);
48
+ header[8] = 8; // bit depth
49
+ header[9] = 6; // color type: RGBA
50
+ const parts = [
51
+ new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
52
+ chunk("IHDR", header),
53
+ chunk("IDAT", await deflate(raw)),
54
+ chunk("IEND", new Uint8Array(0))
55
+ ];
56
+ const out = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
57
+ let offset = 0;
58
+ for (const part of parts) {
59
+ out.set(part, offset);
60
+ offset += part.length;
61
+ }
62
+ return out;
63
+ }
64
+ /** Bytes as base64. */
65
+ export function toBase64(bytes) {
66
+ let binary = "";
67
+ for (let i = 0; i < bytes.length; i += 0x8000)
68
+ binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
69
+ return btoa(binary);
70
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * ONNX Runtime Web, loaded on demand, and the page's one loaded model: its
3
+ * sessions run on WebGPU where the browser has a GPU adapter, else on the CPU
4
+ * (WebAssembly). ONNX Runtime's WebGL backend can't run these models (it has
5
+ * no int8 dequantization, among other ops), so it isn't tried.
6
+ */
7
+ import type { InferenceSession } from "onnxruntime-web";
8
+ /** The onnxruntime-web version this package installs; its WebAssembly files load from the CDN at this version by default. */
9
+ export declare const ORT_VERSION = "1.31.1";
10
+ /** Where ONNX Runtime's WebAssembly files load from, unless `wasmPaths` says otherwise. */
11
+ export declare const DEFAULT_WASM_PATHS = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/";
12
+ /** Where the model runs. */
13
+ export type OnnxBackend = "webgpu" | "wasm";
14
+ export type Ort = typeof import("onnxruntime-web");
15
+ /** ONNX Runtime Web with its WebGPU backend (WebAssembly included), once. */
16
+ export declare function loadOrt(wasmPaths: string): Promise<Ort>;
17
+ /** Whether the browser gives WebGPU an adapter. */
18
+ export declare function hasWebGpu(): Promise<boolean>;
19
+ /**
20
+ * Sessions for a model's files, on one backend, one at a time so the peak
21
+ * holds one model's copy, not both. Constant folding is off: it would turn
22
+ * every int8 weight into a float32 copy at load, about four times the memory,
23
+ * more than a phone gives a tab. The weights are dequantized as they're used.
24
+ */
25
+ export declare function createSessions<T extends string>(ort: Ort, files: Record<T, ArrayBuffer>, backend: OnnxBackend, overrides?: InferenceSession.SessionOptions, webgpuOptions?: Record<string, unknown>): Promise<Record<T, InferenceSession>>;
26
+ //# sourceMappingURL=runtime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../src/runtime.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAA;AAEvD,6HAA6H;AAC7H,eAAO,MAAM,WAAW,WAAW,CAAA;AAEnC,2FAA2F;AAC3F,eAAO,MAAM,kBAAkB,8DAAsE,CAAA;AAErG,4BAA4B;AAC5B,MAAM,MAAM,WAAW,GAAG,QAAQ,GAAG,MAAM,CAAA;AAE3C,MAAM,MAAM,GAAG,GAAG,cAAc,iBAAiB,CAAC,CAAA;AAGlD,6EAA6E;AAC7E,wBAAgB,OAAO,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,CAOvD;AAED,mDAAmD;AACnD,wBAAsB,SAAS,IAAI,OAAO,CAAC,OAAO,CAAC,CAQlD;AAED;;;;;GAKG;AACH,wBAAsB,cAAc,CAAC,CAAC,SAAS,MAAM,EACnD,GAAG,EAAE,GAAG,EACR,KAAK,EAAE,MAAM,CAAC,CAAC,EAAE,WAAW,CAAC,EAC7B,OAAO,EAAE,WAAW,EACpB,SAAS,GAAE,gBAAgB,CAAC,cAAmB,EAC/C,aAAa,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAM,GAC1C,OAAO,CAAC,MAAM,CAAC,CAAC,EAAE,gBAAgB,CAAC,CAAC,CAiBtC"}
@@ -0,0 +1,51 @@
1
+ /** The onnxruntime-web version this package installs; its WebAssembly files load from the CDN at this version by default. */
2
+ export const ORT_VERSION = "1.31.1";
3
+ /** Where ONNX Runtime's WebAssembly files load from, unless `wasmPaths` says otherwise. */
4
+ export const DEFAULT_WASM_PATHS = `https://cdn.jsdelivr.net/npm/onnxruntime-web@${ORT_VERSION}/dist/`;
5
+ let ortModule;
6
+ /** ONNX Runtime Web with its WebGPU backend (WebAssembly included), once. */
7
+ export function loadOrt(wasmPaths) {
8
+ ortModule ??= import("onnxruntime-web/webgpu").then((ort) => {
9
+ ort.env.wasm.wasmPaths = wasmPaths;
10
+ return ort;
11
+ });
12
+ ortModule.catch(() => (ortModule = undefined));
13
+ return ortModule;
14
+ }
15
+ /** Whether the browser gives WebGPU an adapter. */
16
+ export async function hasWebGpu() {
17
+ const gpu = globalThis.navigator?.gpu;
18
+ if (!gpu)
19
+ return false;
20
+ try {
21
+ return (await gpu.requestAdapter()) != null;
22
+ }
23
+ catch {
24
+ return false;
25
+ }
26
+ }
27
+ /**
28
+ * Sessions for a model's files, on one backend, one at a time so the peak
29
+ * holds one model's copy, not both. Constant folding is off: it would turn
30
+ * every int8 weight into a float32 copy at load, about four times the memory,
31
+ * more than a phone gives a tab. The weights are dequantized as they're used.
32
+ */
33
+ export async function createSessions(ort, files, backend, overrides = {}, webgpuOptions = {}) {
34
+ const options = {
35
+ graphOptimizationLevel: "all",
36
+ extra: { optimization: { disable_specified_optimizers: "ConstantFolding" } },
37
+ ...overrides,
38
+ executionProviders: [backend === "webgpu" ? { name: "webgpu", ...webgpuOptions } : backend]
39
+ };
40
+ const sessions = {};
41
+ try {
42
+ for (const [name, bytes] of Object.entries(files)) {
43
+ sessions[name] = await ort.InferenceSession.create(new Uint8Array(bytes), options);
44
+ }
45
+ }
46
+ catch (error) {
47
+ await Promise.all(Object.values(sessions).map((session) => session.release()));
48
+ throw error;
49
+ }
50
+ return sessions;
51
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Downloaded model files, kept in the page's Cache Storage under the URL
3
+ * they were downloaded from, which names the commit. A file is stored whole
4
+ * or not at all: a cache entry only appears once its body is written.
5
+ */
6
+ /** The parts of the page's Cache Storage and network the store uses (tests give their own). */
7
+ export type StorageEnvironment = {
8
+ caches: Pick<CacheStorage, "open">;
9
+ fetch: (input: string, init?: RequestInit) => Promise<Response>;
10
+ };
11
+ /** The cache's name in the page's Cache Storage. */
12
+ export declare const MODEL_CACHE = "tanstack-ai-browser-onnx";
13
+ /**
14
+ * Whether every one of these files is stored. Cache Storage this page can't
15
+ * open (a SecurityError in some private windows) counts as nothing stored,
16
+ * so loads go on to download without caching (fileBytes).
17
+ */
18
+ export declare function allStored(urls: ReadonlyArray<string>, env?: StorageEnvironment | undefined): Promise<boolean>;
19
+ /**
20
+ * A file's bytes: from the cache, else downloaded into it first, with the
21
+ * bytes downloaded so far reported as they arrive. Without Cache Storage
22
+ * (some private windows) the file downloads every time. An aborted or failed
23
+ * download stores nothing.
24
+ */
25
+ export declare function fileBytes(url: string, options?: {
26
+ onBytes?: (bytes: number) => void;
27
+ signal?: AbortSignal;
28
+ }, env?: StorageEnvironment | undefined): Promise<ArrayBuffer>;
29
+ /** Removes these files from the cache. Returns whether any was stored. */
30
+ export declare function removeFiles(urls: ReadonlyArray<string>, env?: StorageEnvironment | undefined): Promise<boolean>;
31
+ //# sourceMappingURL=storage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storage.d.ts","sourceRoot":"","sources":["../src/storage.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,+FAA+F;AAC/F,MAAM,MAAM,kBAAkB,GAAG;IAC/B,MAAM,EAAE,IAAI,CAAC,YAAY,EAAE,MAAM,CAAC,CAAA;IAClC,KAAK,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAA;CAChE,CAAA;AAED,oDAAoD;AACpD,eAAO,MAAM,WAAW,6BAA6B,CAAA;AAUrD;;;;GAIG;AACH,wBAAsB,SAAS,CAC7B,IAAI,EAAE,aAAa,CAAC,MAAM,CAAC,EAC3B,GAAG,iCAAgB,GAClB,OAAO,CAAC,OAAO,CAAC,CASlB;AAED;;;;;GAKG;AACH,wBAAsB,SAAS,CAC7B,GAAG,EAAE,MAAM,EACX,OAAO,GAAE;IAAE,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAAC,MAAM,CAAC,EAAE,WAAW,CAAA;CAAO,EACzE,GAAG,iCAAgB,GAClB,OAAO,CAAC,WAAW,CAAC,CA6CtB;AAED,0EAA0E;AAC1E,wBAAsB,WAAW,CAC/B,IAAI,EAAE,aAAa,CAAC,MAAM,CAAC,EAC3B,GAAG,iCAAgB,GAClB,OAAO,CAAC,OAAO,CAAC,CAOlB"}
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Downloaded model files, kept in the page's Cache Storage under the URL
3
+ * they were downloaded from, which names the commit. A file is stored whole
4
+ * or not at all: a cache entry only appears once its body is written.
5
+ */
6
+ /** The cache's name in the page's Cache Storage. */
7
+ export const MODEL_CACHE = "tanstack-ai-browser-onnx";
8
+ const environment = () => typeof caches === "undefined"
9
+ ? undefined
10
+ : { caches, fetch: (input, init) => fetch(input, init) };
11
+ const coded = (message, code, cause) => Object.assign(new Error(message, { cause }), { code });
12
+ /**
13
+ * Whether every one of these files is stored. Cache Storage this page can't
14
+ * open (a SecurityError in some private windows) counts as nothing stored,
15
+ * so loads go on to download without caching (fileBytes).
16
+ */
17
+ export async function allStored(urls, env = environment()) {
18
+ if (!env)
19
+ return false;
20
+ try {
21
+ const cache = await env.caches.open(MODEL_CACHE);
22
+ for (const url of urls)
23
+ if (!(await cache.match(url)))
24
+ return false;
25
+ return true;
26
+ }
27
+ catch {
28
+ return false;
29
+ }
30
+ }
31
+ /**
32
+ * A file's bytes: from the cache, else downloaded into it first, with the
33
+ * bytes downloaded so far reported as they arrive. Without Cache Storage
34
+ * (some private windows) the file downloads every time. An aborted or failed
35
+ * download stores nothing.
36
+ */
37
+ export async function fileBytes(url, options = {}, env = environment()) {
38
+ const cache = env
39
+ ? await env.caches.open(MODEL_CACHE).catch(() => undefined)
40
+ : undefined;
41
+ const hit = await cache?.match(url);
42
+ if (hit)
43
+ return hit.arrayBuffer();
44
+ const { onBytes, signal } = options;
45
+ const response = await (env?.fetch ?? fetch)(url, signal ? { signal } : undefined);
46
+ if (!response.ok || !response.body) {
47
+ throw coded(`${url} didn't download (HTTP ${response.status})`, "download-failed");
48
+ }
49
+ let loaded = 0;
50
+ const counted = response.body.pipeThrough(new TransformStream({
51
+ transform(chunk, controller) {
52
+ loaded += chunk.byteLength;
53
+ onBytes?.(loaded);
54
+ controller.enqueue(chunk);
55
+ }
56
+ }));
57
+ if (!cache)
58
+ return new Response(counted).arrayBuffer();
59
+ try {
60
+ await cache.put(url, new Response(counted));
61
+ }
62
+ catch (error) {
63
+ if (signal?.aborted)
64
+ throw signal.reason ?? error;
65
+ const full = error instanceof DOMException && error.name === "QuotaExceededError";
66
+ throw coded(full
67
+ ? "There's no room to store the model on this device"
68
+ : `${url} couldn't be stored (${error instanceof Error ? error.message : String(error)})`, full ? "storage-full" : "download-failed", error);
69
+ }
70
+ const stored = await cache.match(url);
71
+ if (!stored)
72
+ throw coded(`${url} wasn't stored`, "download-failed");
73
+ return stored.arrayBuffer();
74
+ }
75
+ /** Removes these files from the cache. Returns whether any was stored. */
76
+ export async function removeFiles(urls, env = environment()) {
77
+ if (!env)
78
+ return false;
79
+ const cache = await env.caches.open(MODEL_CACHE).catch(() => undefined);
80
+ if (!cache)
81
+ return false;
82
+ let removed = false;
83
+ for (const url of urls)
84
+ removed = (await cache.delete(url)) || removed;
85
+ return removed;
86
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Tessera's pipeline: the CLIP text encoder, then the masked-diffusion
3
+ * sampler, which starts from a blank canvas and commits pixels over a fixed
4
+ * number of steps, each step one pass of the denoiser over the whole canvas.
5
+ *
6
+ * The sampler follows Tessera's published one: classifier-free guidance
7
+ * (each image runs with and without the prompt), a cosine schedule of how
8
+ * many pixels stay blank, confidence-ordered commits with Gumbel noise that
9
+ * fades over the steps, a spatial non-maximum suppression that spreads each
10
+ * step's commits over the canvas, and self-conditioning (each step's
11
+ * distribution goes back into the next).
12
+ */
13
+ import type { InferenceSession, Tensor as OrtTensor } from "onnxruntime-web";
14
+ /** The canvas: GRID×GRID pixels, each one of K palette tokens. */
15
+ export declare const GRID = 16;
16
+ export declare const PIXELS: number;
17
+ export declare const PALETTE = 512;
18
+ /** The sampler's settings. */
19
+ export type SamplerSettings = {
20
+ /** Denoiser passes; each commits a share of the blank pixels. */
21
+ steps: number;
22
+ /** Classifier-free guidance: how far each pixel is pushed toward the prompt. */
23
+ guidanceScale: number;
24
+ /** The Gumbel noise on the commit order at the first step (it fades to none). */
25
+ choiceTemperature: number;
26
+ /** A pixel at least this certain is committed without competing with its neighbours. */
27
+ certainty: number;
28
+ /** The random source's seed: the same seed, prompt and settings draw the same images. */
29
+ seed: number;
30
+ };
31
+ export declare const DEFAULT_SAMPLER: Omit<SamplerSettings, "seed">;
32
+ /** What the pipeline runs on: ONNX Runtime's tensor class and the two sessions. */
33
+ export type TesseraSessions = {
34
+ Tensor: typeof OrtTensor;
35
+ denoiser: InferenceSession;
36
+ textEncoder: InferenceSession;
37
+ };
38
+ /** Mulberry32: a small seeded random source, uniform on [0, 1). */
39
+ export declare function seededRandom(seed: number): () => number;
40
+ /**
41
+ * The text encoder's input: the prompt's ids with its start and end tokens,
42
+ * padded with the end token to TEXT_LEN, or cut to it with the end token
43
+ * kept last.
44
+ */
45
+ export declare function fixedLengthIds(ids: ReadonlyArray<number>, endToken: number): Array<number>;
46
+ /** Blank pixels left after step `step` of `steps` (cosine schedule; none after the last). */
47
+ export declare function blankAfter(step: number, steps: number): number;
48
+ /**
49
+ * The order to commit this step's blank pixels in, best first. Pixels at
50
+ * least `certainty` sure go first; of the others, a pixel goes ahead only if
51
+ * it scores at least as well as every uncertain blank neighbour, so a step's
52
+ * commits spread out instead of clumping.
53
+ */
54
+ export declare function commitOrder(blank: Uint8Array, confidence: Float32Array, score: Float32Array, certainty: number): Array<number>;
55
+ /**
56
+ * Draws `count` sprites for one prompt (its fixed-length token ids). Returns
57
+ * each sprite's palette tokens, row by row. `signal` stops it between steps.
58
+ */
59
+ export declare function drawSprites(sessions: TesseraSessions, ids: ReadonlyArray<number>, count: number, settings: SamplerSettings, signal?: AbortSignal): Promise<Array<Int32Array>>;
60
+ /** A sprite's RGBA pixels, from its tokens and the palette (`palette_rgba`). */
61
+ export declare function spritePixels(tokens: Int32Array, palette: ReadonlyArray<ReadonlyArray<number>>): Uint8Array;
62
+ //# sourceMappingURL=tessera.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tessera.d.ts","sourceRoot":"","sources":["../src/tessera.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,IAAI,SAAS,EAAE,MAAM,iBAAiB,CAAA;AAE5E,kEAAkE;AAClE,eAAO,MAAM,IAAI,KAAK,CAAA;AACtB,eAAO,MAAM,MAAM,QAAc,CAAA;AACjC,eAAO,MAAM,OAAO,MAAM,CAAA;AAM1B,8BAA8B;AAC9B,MAAM,MAAM,eAAe,GAAG;IAC5B,iEAAiE;IACjE,KAAK,EAAE,MAAM,CAAA;IACb,gFAAgF;IAChF,aAAa,EAAE,MAAM,CAAA;IACrB,iFAAiF;IACjF,iBAAiB,EAAE,MAAM,CAAA;IACzB,wFAAwF;IACxF,SAAS,EAAE,MAAM,CAAA;IACjB,yFAAyF;IACzF,IAAI,EAAE,MAAM,CAAA;CACb,CAAA;AAED,eAAO,MAAM,eAAe,EAAE,IAAI,CAAC,eAAe,EAAE,MAAM,CAKzD,CAAA;AAED,mFAAmF;AACnF,MAAM,MAAM,eAAe,GAAG;IAC5B,MAAM,EAAE,OAAO,SAAS,CAAA;IACxB,QAAQ,EAAE,gBAAgB,CAAA;IAC1B,WAAW,EAAE,gBAAgB,CAAA;CAC9B,CAAA;AAED,mEAAmE;AACnE,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,gBASxC;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAC5B,GAAG,EAAE,aAAa,CAAC,MAAM,CAAC,EAC1B,QAAQ,EAAE,MAAM,GACf,KAAK,CAAC,MAAM,CAAC,CAKf;AAED,6FAA6F;AAC7F,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,UAIrD;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CACzB,KAAK,EAAE,UAAU,EACjB,UAAU,EAAE,YAAY,EACxB,KAAK,EAAE,YAAY,EACnB,SAAS,EAAE,MAAM,GAChB,KAAK,CAAC,MAAM,CAAC,CA8Bf;AAoBD;;;GAGG;AACH,wBAAsB,WAAW,CAC/B,QAAQ,EAAE,eAAe,EACzB,GAAG,EAAE,aAAa,CAAC,MAAM,CAAC,EAC1B,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,eAAe,EACzB,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CA+H5B;AAED,gFAAgF;AAChF,wBAAgB,YAAY,CAC1B,MAAM,EAAE,UAAU,EAClB,OAAO,EAAE,aAAa,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,GAC5C,UAAU,CAKZ"}
@@ -0,0 +1,206 @@
1
+ /** The canvas: GRID×GRID pixels, each one of K palette tokens. */
2
+ export const GRID = 16;
3
+ export const PIXELS = GRID * GRID;
4
+ export const PALETTE = 512;
5
+ /** The token of a pixel not painted yet. */
6
+ const MASK = PALETTE;
7
+ const TEXT_LEN = 24;
8
+ const TEXT_DIM = 512;
9
+ export const DEFAULT_SAMPLER = {
10
+ steps: 16,
11
+ guidanceScale: 3,
12
+ choiceTemperature: 2,
13
+ certainty: 0.9
14
+ };
15
+ /** Mulberry32: a small seeded random source, uniform on [0, 1). */
16
+ export function seededRandom(seed) {
17
+ let a = seed >>> 0;
18
+ return () => {
19
+ a = (a + 0x6d2b79f5) >>> 0;
20
+ let t = a;
21
+ t = Math.imul(t ^ (t >>> 15), t | 1);
22
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
23
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
24
+ };
25
+ }
26
+ /**
27
+ * The text encoder's input: the prompt's ids with its start and end tokens,
28
+ * padded with the end token to TEXT_LEN, or cut to it with the end token
29
+ * kept last.
30
+ */
31
+ export function fixedLengthIds(ids, endToken) {
32
+ const kept = ids.length > TEXT_LEN ? [...ids.slice(0, TEXT_LEN - 1), endToken] : [...ids];
33
+ while (kept.length < TEXT_LEN)
34
+ kept.push(endToken);
35
+ return kept;
36
+ }
37
+ /** Blank pixels left after step `step` of `steps` (cosine schedule; none after the last). */
38
+ export function blankAfter(step, steps) {
39
+ return step === steps - 1
40
+ ? 0
41
+ : Math.floor(PIXELS * Math.cos((Math.PI / 2) * ((step + 1) / steps)));
42
+ }
43
+ /**
44
+ * The order to commit this step's blank pixels in, best first. Pixels at
45
+ * least `certainty` sure go first; of the others, a pixel goes ahead only if
46
+ * it scores at least as well as every uncertain blank neighbour, so a step's
47
+ * commits spread out instead of clumping.
48
+ */
49
+ export function commitOrder(blank, confidence, score, certainty) {
50
+ const ranked = [];
51
+ for (let i = 0; i < PIXELS; i++) {
52
+ if (!blank[i])
53
+ continue;
54
+ let ahead = confidence[i] >= certainty;
55
+ if (!ahead) {
56
+ const row = Math.floor(i / GRID);
57
+ const col = i % GRID;
58
+ let best = -Infinity;
59
+ for (let r = Math.max(row - 1, 0); r <= Math.min(row + 1, GRID - 1); r++) {
60
+ for (let c = Math.max(col - 1, 0); c <= Math.min(col + 1, GRID - 1); c++) {
61
+ const j = r * GRID + c;
62
+ if (blank[j] && confidence[j] < certainty)
63
+ best = Math.max(best, score[j]);
64
+ }
65
+ }
66
+ ahead = score[i] >= best;
67
+ }
68
+ ranked.push([score[i] + (ahead ? 1e4 : 0), i]);
69
+ }
70
+ ranked.sort((a, b) => b[0] - a[0]);
71
+ return ranked.map(([, i]) => i);
72
+ }
73
+ /** The prompt's text states, for the denoiser. */
74
+ async function encodeText(sessions, ids) {
75
+ const { Tensor, textEncoder } = sessions;
76
+ const out = await textEncoder.run({
77
+ input_ids: new Tensor("int64", BigInt64Array.from(ids, BigInt), [
78
+ 1,
79
+ TEXT_LEN
80
+ ])
81
+ });
82
+ return {
83
+ states: out.last_hidden_state.data,
84
+ pooled: out.pooler_output.data
85
+ };
86
+ }
87
+ /**
88
+ * Draws `count` sprites for one prompt (its fixed-length token ids). Returns
89
+ * each sprite's palette tokens, row by row. `signal` stops it between steps.
90
+ */
91
+ export async function drawSprites(sessions, ids, count, settings, signal) {
92
+ const { Tensor, denoiser } = sessions;
93
+ const { steps, guidanceScale, choiceTemperature, certainty } = settings;
94
+ const random = seededRandom(settings.seed);
95
+ const { states, pooled } = await encodeText(sessions, ids);
96
+ // Rows [0, count) with the prompt, [count, 2·count) without it.
97
+ const rows = count * 2;
98
+ const textStates = new Float32Array(rows * TEXT_LEN * TEXT_DIM);
99
+ const textPooled = new Float32Array(rows * TEXT_DIM);
100
+ for (let r = 0; r < rows; r++) {
101
+ textStates.set(states, r * TEXT_LEN * TEXT_DIM);
102
+ textPooled.set(pooled, r * TEXT_DIM);
103
+ }
104
+ const fixed = {
105
+ text_states: new Tensor("float32", textStates, [rows, TEXT_LEN, TEXT_DIM]),
106
+ text_pooled: new Tensor("float32", textPooled, [rows, TEXT_DIM]),
107
+ drop_text: new Tensor("bool", Uint8Array.from({ length: rows }, (_, r) => (r >= count ? 1 : 0)), [rows])
108
+ };
109
+ const tokens = Array.from({ length: count }, () => new Int32Array(PIXELS).fill(MASK));
110
+ const blank = Array.from({ length: count }, () => new Uint8Array(PIXELS).fill(1));
111
+ const selfCond = new Float32Array(rows * PIXELS * PALETTE);
112
+ const probs = new Float32Array(PIXELS * PALETTE);
113
+ const picked = new Int32Array(PIXELS);
114
+ const confidence = new Float32Array(PIXELS);
115
+ const score = new Float32Array(PIXELS);
116
+ for (let step = 0; step < steps; step++) {
117
+ signal?.throwIfAborted();
118
+ const progress = (step + 1) / steps;
119
+ const x = new BigInt64Array(rows * PIXELS);
120
+ const maskRatio = new Float32Array(rows);
121
+ for (let b = 0; b < count; b++) {
122
+ let blanks = 0;
123
+ for (let i = 0; i < PIXELS; i++) {
124
+ const token = BigInt(tokens[b][i]);
125
+ x[b * PIXELS + i] = token;
126
+ x[(b + count) * PIXELS + i] = token;
127
+ blanks += blank[b][i];
128
+ }
129
+ maskRatio[b] = maskRatio[b + count] = blanks / PIXELS;
130
+ }
131
+ const out = await denoiser.run({
132
+ ...fixed,
133
+ x: new Tensor("int64", x, [rows, PIXELS]),
134
+ mask_ratio: new Tensor("float32", maskRatio, [rows]),
135
+ sc_probs: new Tensor("float32", selfCond, [rows, PIXELS, PALETTE])
136
+ });
137
+ const logits = out.logits.data;
138
+ signal?.throwIfAborted();
139
+ for (let b = 0; b < count; b++) {
140
+ const withText = b * PIXELS * PALETTE;
141
+ const withoutText = (b + count) * PIXELS * PALETTE;
142
+ // Guided distribution per pixel, and one token drawn from it.
143
+ for (let i = 0; i < PIXELS; i++) {
144
+ const row = i * PALETTE;
145
+ let max = -Infinity;
146
+ for (let k = 0; k < PALETTE; k++) {
147
+ const without = logits[withoutText + row + k];
148
+ const guided = without + guidanceScale * (logits[withText + row + k] - without);
149
+ if (!Number.isFinite(guided))
150
+ throw new Error("The model returned a non-finite value: this device's GPU may not run it correctly");
151
+ probs[row + k] = guided;
152
+ if (guided > max)
153
+ max = guided;
154
+ }
155
+ let sum = 0;
156
+ for (let k = 0; k < PALETTE; k++) {
157
+ const e = Math.exp(probs[row + k] - max);
158
+ probs[row + k] = e;
159
+ sum += e;
160
+ }
161
+ let u = random() * sum;
162
+ let pick = PALETTE - 1;
163
+ for (let k = 0; k < PALETTE; k++) {
164
+ u -= probs[row + k];
165
+ if (u <= 0) {
166
+ pick = k;
167
+ break;
168
+ }
169
+ }
170
+ for (let k = 0; k < PALETTE; k++)
171
+ probs[row + k] /= sum;
172
+ picked[i] = pick;
173
+ confidence[i] = probs[row + pick];
174
+ }
175
+ let blanks = 0;
176
+ for (let i = 0; i < PIXELS; i++)
177
+ blanks += blank[b][i];
178
+ const commits = Math.min(Math.max(blanks - blankAfter(step, steps), 1), blanks);
179
+ // Confidence with fading Gumbel noise.
180
+ for (let i = 0; i < PIXELS; i++) {
181
+ const u = Math.min(Math.max(random(), 1e-10), 1 - 1e-10);
182
+ score[i] =
183
+ Math.log(Math.max(confidence[i], 1e-12)) +
184
+ choiceTemperature * (1 - progress) * -Math.log(-Math.log(u));
185
+ }
186
+ for (const i of commitOrder(blank[b], confidence, score, certainty).slice(0, commits)) {
187
+ tokens[b][i] = picked[i];
188
+ blank[b][i] = 0;
189
+ }
190
+ // Self-conditioning: this step's distribution, for both rows of the image.
191
+ selfCond.set(probs, withText);
192
+ selfCond.set(probs, withoutText);
193
+ }
194
+ // Every pixel painted (the schedule can get there before the last step): no pass is left to run.
195
+ if (blank.every((sprite) => !sprite.includes(1)))
196
+ break;
197
+ }
198
+ return tokens;
199
+ }
200
+ /** A sprite's RGBA pixels, from its tokens and the palette (`palette_rgba`). */
201
+ export function spritePixels(tokens, palette) {
202
+ const rgba = new Uint8Array(PIXELS * 4);
203
+ for (let i = 0; i < PIXELS; i++)
204
+ rgba.set(palette[tokens[i]] ?? [0, 0, 0, 0], i * 4);
205
+ return rgba;
206
+ }
package/package.json CHANGED
@@ -1,6 +1,65 @@
1
1
  {
2
2
  "name": "@tanstack-ai-browser/onnx",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.4",
4
+ "description": "TanStack AI image adapter for ONNX models in the browser, on ONNX Runtime Web (WebGPU, or WebAssembly): Tessera-small pixel-art sprites",
5
+ "license": "MIT",
6
+ "author": "daveycodez",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/daveycodez/tanstack-ai-browser.git",
10
+ "directory": "packages/onnx"
11
+ },
12
+ "homepage": "https://github.com/daveycodez/tanstack-ai-browser/tree/main/packages/onnx#readme",
13
+ "bugs": "https://github.com/daveycodez/tanstack-ai-browser/issues",
14
+ "keywords": [
15
+ "tanstack-ai",
16
+ "tanstack",
17
+ "ai",
18
+ "image-generation",
19
+ "onnx",
20
+ "onnxruntime-web",
21
+ "webgpu",
22
+ "webassembly",
23
+ "browser",
24
+ "local-ai",
25
+ "pixel-art"
26
+ ],
27
+ "type": "module",
28
+ "sideEffects": false,
29
+ "main": "./dist/index.js",
30
+ "module": "./dist/index.js",
31
+ "types": "./dist/index.d.ts",
32
+ "exports": {
33
+ "./package.json": "./package.json",
34
+ ".": {
35
+ "@tanstack-ai-browser/source": "./src/index.ts",
36
+ "types": "./dist/index.d.ts",
37
+ "import": "./dist/index.js",
38
+ "default": "./dist/index.js"
39
+ }
40
+ },
41
+ "files": [
42
+ "src",
43
+ "dist",
44
+ "!**/*.tsbuildinfo"
45
+ ],
46
+ "publishConfig": {
47
+ "access": "public"
48
+ },
49
+ "nx": {
50
+ "name": "onnx"
51
+ },
52
+ "scripts": {
53
+ "test": "node --import @swc-node/register/esm-register --test \"src/**/*.test.ts\""
54
+ },
55
+ "peerDependencies": {
56
+ "@tanstack/ai": "^1.4.0"
57
+ },
58
+ "devDependencies": {
59
+ "@tanstack/ai": "1.4.0"
60
+ },
61
+ "dependencies": {
62
+ "@huggingface/tokenizers": "0.2.0",
63
+ "onnxruntime-web": "1.31.1"
64
+ }
65
+ }