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

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,39 @@
1
+ /**
2
+ * One queue for everything that touches the page's ONNX sessions: loading,
3
+ * switching to another model or backend, drawing, unloading. Each task runs
4
+ * after the one before has ended, so no task releases sessions another is
5
+ * still using.
6
+ */
7
+
8
+ let tail: Promise<unknown> = Promise.resolve()
9
+
10
+ /** The reason an aborted signal gives, as an error. */
11
+ const abortReason = (signal: AbortSignal) =>
12
+ signal.reason instanceof Error
13
+ ? signal.reason
14
+ : new DOMException("The operation was aborted.", "AbortError")
15
+
16
+ /**
17
+ * Runs `task` after every task queued before it. A caller whose `signal` is
18
+ * aborted while it waits rejects at once, and its task, when its turn
19
+ * comes, rejects without running.
20
+ */
21
+ export function serial<T>(
22
+ task: () => Promise<T>,
23
+ signal?: AbortSignal
24
+ ): Promise<T> {
25
+ const run = tail.then(() => {
26
+ signal?.throwIfAborted()
27
+ return task()
28
+ })
29
+ tail = run.catch(() => undefined)
30
+ if (!signal) return run
31
+ if (signal.aborted) return Promise.reject(abortReason(signal))
32
+ return new Promise<T>((resolve, reject) => {
33
+ const onAbort = () => reject(abortReason(signal))
34
+ signal.addEventListener("abort", onAbort, { once: true })
35
+ run
36
+ .then(resolve, reject)
37
+ .finally(() => signal.removeEventListener("abort", onAbort))
38
+ })
39
+ }
@@ -0,0 +1,70 @@
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
+ /** A model file: its path in the repository and its size in bytes. */
8
+ export type OnnxModelFile = { path: string; bytes: number }
9
+
10
+ /** What a model is and where its files are. */
11
+ export type OnnxImageModelMeta = {
12
+ /** The model's Hugging Face repository, its name for `onnxImage`. */
13
+ name: string
14
+ /** The commit its files are read at. */
15
+ revision: string
16
+ /** The one size it draws, as TanStack AI's `size` (WIDTHxHEIGHT). */
17
+ size: string
18
+ /** The download, all files together. */
19
+ download: string
20
+ /** The weights' license. */
21
+ license: string
22
+ files: {
23
+ /** The denoiser: one pass over the whole canvas per step. */
24
+ denoiser: OnnxModelFile
25
+ /** The text encoder the denoiser is conditioned on. */
26
+ textEncoder: OnnxModelFile
27
+ /** The text encoder's tokenizer (Hugging Face `tokenizer.json`). */
28
+ tokenizer: OnnxModelFile
29
+ /** The colors a pixel token stands for (`palette_rgba`, one RGBA per token). */
30
+ palette: OnnxModelFile
31
+ }
32
+ }
33
+
34
+ /**
35
+ * Tessera-small by Jagrat Patel (TheJagStudio): 16×16 pixel-art sprites
36
+ * from text, a 47.6M-parameter masked-diffusion transformer conditioned on
37
+ * OpenAI's CLIP ViT-B/32 text encoder. This is cfahlgren1's int8 ONNX build
38
+ * of both. CC BY-NC 4.0: no commercial use of the model or its images.
39
+ */
40
+ const TESSERA_SMALL = {
41
+ name: "cfahlgren1/tessera-small-onnx",
42
+ revision: "bef21be58afea4d16be21f5fbe85eaa0cae69290",
43
+ size: "16x16",
44
+ download: "115 MB",
45
+ license: "CC BY-NC 4.0",
46
+ files: {
47
+ denoiser: { path: "tessera_w8.onnx", bytes: 50834182 },
48
+ textEncoder: { path: "clip_text_w8.onnx", bytes: 64060515 },
49
+ tokenizer: { path: "tokenizer.json", bytes: 0 },
50
+ palette: { path: "palette.json", bytes: 0 }
51
+ }
52
+ } as const satisfies OnnxImageModelMeta
53
+
54
+ /** The catalog's models, by their Hugging Face repository. */
55
+ export const ONNX_IMAGE_MODELS = [TESSERA_SMALL.name] as const
56
+
57
+ /** A model of the catalog. */
58
+ export type OnnxImageModel = (typeof ONNX_IMAGE_MODELS)[number]
59
+
60
+ /** Each model's entry, by name. */
61
+ export const ONNX_MODEL_META = {
62
+ [TESSERA_SMALL.name]: TESSERA_SMALL
63
+ } as const satisfies Record<OnnxImageModel, OnnxImageModelMeta>
64
+
65
+ /** The size each model draws, for TanStack AI's `size` option. */
66
+ export type OnnxImageModelSizeByName = { [K in OnnxImageModel]: (typeof ONNX_MODEL_META)[K]["size"] }
67
+
68
+ /** A file's URL at the model's pinned commit. */
69
+ export const fileUrl = (meta: OnnxImageModelMeta, file: OnnxModelFile) =>
70
+ `https://huggingface.co/${meta.name}/resolve/${meta.revision}/${file.path}`
@@ -0,0 +1,55 @@
1
+ import assert from "node:assert/strict"
2
+ import { test } from "node:test"
3
+ import { inflateSync } from "node:zlib"
4
+
5
+ import { encodePng, toBase64 } from "./png.js"
6
+
7
+ /** The chunks of a PNG, by type, with each one's CRC checked. */
8
+ function chunks(png: Uint8Array) {
9
+ const buffer = Buffer.from(png)
10
+ assert.deepEqual(
11
+ [...buffer.subarray(0, 8)],
12
+ [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
13
+ )
14
+ const found: Array<{ type: string; data: Buffer }> = []
15
+ for (let offset = 8; offset < buffer.length;) {
16
+ const length = buffer.readUInt32BE(offset)
17
+ found.push({
18
+ type: buffer.toString("ascii", offset + 4, offset + 8),
19
+ data: buffer.subarray(offset + 8, offset + 8 + length)
20
+ })
21
+ offset += 12 + length
22
+ }
23
+ return found
24
+ }
25
+
26
+ test("a PNG holds the pixels it was given, row by row", async () => {
27
+ const rgba = new Uint8Array(3 * 2 * 4).map((_, i) => i * 7)
28
+ const parsed = chunks(await encodePng(rgba, 3, 2))
29
+ assert.deepEqual(
30
+ parsed.map((c) => c.type),
31
+ ["IHDR", "IDAT", "IEND"]
32
+ )
33
+ const header = parsed[0].data
34
+ assert.equal(header.readUInt32BE(0), 3)
35
+ assert.equal(header.readUInt32BE(4), 2)
36
+ assert.equal(header[8], 8)
37
+ assert.equal(header[9], 6)
38
+ const raw = inflateSync(parsed[1].data)
39
+ assert.equal(raw.length, 2 * (1 + 12))
40
+ assert.equal(raw[0], 0)
41
+ assert.deepEqual([...raw.subarray(1, 13)], [...rgba.subarray(0, 12)])
42
+ assert.deepEqual([...raw.subarray(14, 26)], [...rgba.subarray(12, 24)])
43
+ })
44
+
45
+ test("the wrong number of bytes for the size is refused", async () => {
46
+ await assert.rejects(
47
+ encodePng(new Uint8Array(10), 16, 16),
48
+ /Expected 1024 RGBA bytes/
49
+ )
50
+ })
51
+
52
+ test("base64 matches Node's", () => {
53
+ const bytes = new Uint8Array(70000).map((_, i) => (i * 31) % 256)
54
+ assert.equal(toBase64(bytes), Buffer.from(bytes).toString("base64"))
55
+ })
package/src/png.ts 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
+
6
+ const CRC_TABLE = (() => {
7
+ const table = new Uint32Array(256)
8
+ for (let n = 0; n < 256; n++) {
9
+ let c = n
10
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
11
+ table[n] = c >>> 0
12
+ }
13
+ return table
14
+ })()
15
+
16
+ function crc32(bytes: Uint8Array) {
17
+ let c = 0xffffffff
18
+ for (const byte of bytes) c = CRC_TABLE[(c ^ byte) & 0xff] ^ (c >>> 8)
19
+ return (c ^ 0xffffffff) >>> 0
20
+ }
21
+
22
+ function chunk(type: string, data: Uint8Array) {
23
+ const out = new Uint8Array(12 + data.length)
24
+ const view = new DataView(out.buffer)
25
+ view.setUint32(0, data.length)
26
+ for (let i = 0; i < 4; i++) 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
+
32
+ /** zlib-wrapped deflate, as PNG's image data is. */
33
+ async function deflate(bytes: Uint8Array) {
34
+ const stream = new Blob([bytes as BlobPart]).stream().pipeThrough(new CompressionStream("deflate"))
35
+ return new Uint8Array(await new Response(stream).arrayBuffer())
36
+ }
37
+
38
+ /** A PNG of `width`×`height` RGBA pixels (8 bits a channel, rows top to bottom). */
39
+ export async function encodePng(rgba: Uint8Array | Uint8ClampedArray, width: number, height: number): Promise<Uint8Array> {
40
+ if (rgba.length !== width * height * 4) throw new Error(`Expected ${width * height * 4} RGBA bytes, got ${rgba.length}`)
41
+ // Each row starts with its filter type: 0, none.
42
+ const raw = new Uint8Array(height * (1 + width * 4))
43
+ for (let y = 0; y < height; y++) 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
+
65
+ /** Bytes as base64. */
66
+ export function toBase64(bytes: Uint8Array): string {
67
+ let binary = ""
68
+ for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000))
69
+ return btoa(binary)
70
+ }
package/src/runtime.ts ADDED
@@ -0,0 +1,71 @@
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
+
9
+ /** The onnxruntime-web version this package installs; its WebAssembly files load from the CDN at this version by default. */
10
+ export const ORT_VERSION = "1.31.1"
11
+
12
+ /** Where ONNX Runtime's WebAssembly files load from, unless `wasmPaths` says otherwise. */
13
+ export const DEFAULT_WASM_PATHS = `https://cdn.jsdelivr.net/npm/onnxruntime-web@${ORT_VERSION}/dist/`
14
+
15
+ /** Where the model runs. */
16
+ export type OnnxBackend = "webgpu" | "wasm"
17
+
18
+ export type Ort = typeof import("onnxruntime-web")
19
+
20
+ let ortModule: Promise<Ort> | undefined
21
+ /** ONNX Runtime Web with its WebGPU backend (WebAssembly included), once. */
22
+ export function loadOrt(wasmPaths: string): Promise<Ort> {
23
+ ortModule ??= import("onnxruntime-web/webgpu").then((ort) => {
24
+ ort.env.wasm.wasmPaths = wasmPaths
25
+ return ort as unknown as Ort
26
+ })
27
+ ortModule.catch(() => (ortModule = undefined))
28
+ return ortModule
29
+ }
30
+
31
+ /** Whether the browser gives WebGPU an adapter. */
32
+ export async function hasWebGpu(): Promise<boolean> {
33
+ const gpu = (globalThis.navigator as { gpu?: { requestAdapter(): Promise<unknown> } } | undefined)?.gpu
34
+ if (!gpu) return false
35
+ try {
36
+ return (await gpu.requestAdapter()) != null
37
+ } catch {
38
+ return false
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Sessions for a model's files, on one backend, one at a time so the peak
44
+ * holds one model's copy, not both. Constant folding is off: it would turn
45
+ * every int8 weight into a float32 copy at load, about four times the memory,
46
+ * more than a phone gives a tab. The weights are dequantized as they're used.
47
+ */
48
+ export async function createSessions<T extends string>(
49
+ ort: Ort,
50
+ files: Record<T, ArrayBuffer>,
51
+ backend: OnnxBackend,
52
+ overrides: InferenceSession.SessionOptions = {},
53
+ webgpuOptions: Record<string, unknown> = {}
54
+ ): Promise<Record<T, InferenceSession>> {
55
+ const options: InferenceSession.SessionOptions = {
56
+ graphOptimizationLevel: "all",
57
+ extra: { optimization: { disable_specified_optimizers: "ConstantFolding" } },
58
+ ...overrides,
59
+ executionProviders: [backend === "webgpu" ? ({ name: "webgpu", ...webgpuOptions } as InferenceSession.ExecutionProviderConfig) : backend]
60
+ }
61
+ const sessions = {} as Record<T, InferenceSession>
62
+ try {
63
+ for (const [name, bytes] of Object.entries(files) as Array<[T, ArrayBuffer]>) {
64
+ sessions[name] = await ort.InferenceSession.create(new Uint8Array(bytes), options)
65
+ }
66
+ } catch (error) {
67
+ await Promise.all(Object.values<InferenceSession>(sessions).map((session) => session.release()))
68
+ throw error
69
+ }
70
+ return sessions
71
+ }
@@ -0,0 +1,32 @@
1
+ import assert from "node:assert/strict"
2
+ import { test } from "node:test"
3
+
4
+ import { allStored, fileBytes, removeFiles } from "./storage.js"
5
+ import type { StorageEnvironment } from "./storage.js"
6
+
7
+ /** Cache Storage the page can't open, as in some private windows. */
8
+ const noCache: StorageEnvironment = {
9
+ caches: {
10
+ open: () =>
11
+ Promise.reject(
12
+ new DOMException("The operation is insecure.", "SecurityError")
13
+ )
14
+ },
15
+ fetch: () => Promise.resolve(new Response(new Uint8Array([1, 2, 3])))
16
+ }
17
+
18
+ test("Cache Storage that can't be opened counts as nothing stored", async () => {
19
+ assert.equal(await allStored(["https://example.com/a"], noCache), false)
20
+ assert.equal(await removeFiles(["https://example.com/a"], noCache), false)
21
+ })
22
+
23
+ test("without Cache Storage a file still downloads, uncached", async () => {
24
+ const seen: Array<number> = []
25
+ const bytes = await fileBytes(
26
+ "https://example.com/a",
27
+ { onBytes: (n) => seen.push(n) },
28
+ noCache
29
+ )
30
+ assert.deepEqual([...new Uint8Array(bytes)], [1, 2, 3])
31
+ assert.deepEqual(seen, [3])
32
+ })
package/src/storage.ts ADDED
@@ -0,0 +1,111 @@
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
+
7
+ /** The parts of the page's Cache Storage and network the store uses (tests give their own). */
8
+ export type StorageEnvironment = {
9
+ caches: Pick<CacheStorage, "open">
10
+ fetch: (input: string, init?: RequestInit) => Promise<Response>
11
+ }
12
+
13
+ /** The cache's name in the page's Cache Storage. */
14
+ export const MODEL_CACHE = "tanstack-ai-browser-onnx"
15
+
16
+ const environment = (): StorageEnvironment | undefined =>
17
+ typeof caches === "undefined"
18
+ ? undefined
19
+ : { caches, fetch: (input, init) => fetch(input, init) }
20
+
21
+ const coded = (message: string, code: string, cause?: unknown) =>
22
+ Object.assign(new Error(message, { cause }), { code })
23
+
24
+ /**
25
+ * Whether every one of these files is stored. Cache Storage this page can't
26
+ * open (a SecurityError in some private windows) counts as nothing stored,
27
+ * so loads go on to download without caching (fileBytes).
28
+ */
29
+ export async function allStored(
30
+ urls: ReadonlyArray<string>,
31
+ env = environment()
32
+ ): Promise<boolean> {
33
+ if (!env) return false
34
+ try {
35
+ const cache = await env.caches.open(MODEL_CACHE)
36
+ for (const url of urls) if (!(await cache.match(url))) return false
37
+ return true
38
+ } catch {
39
+ return false
40
+ }
41
+ }
42
+
43
+ /**
44
+ * A file's bytes: from the cache, else downloaded into it first, with the
45
+ * bytes downloaded so far reported as they arrive. Without Cache Storage
46
+ * (some private windows) the file downloads every time. An aborted or failed
47
+ * download stores nothing.
48
+ */
49
+ export async function fileBytes(
50
+ url: string,
51
+ options: { onBytes?: (bytes: number) => void; signal?: AbortSignal } = {},
52
+ env = environment()
53
+ ): Promise<ArrayBuffer> {
54
+ const cache = env
55
+ ? await env.caches.open(MODEL_CACHE).catch(() => undefined)
56
+ : undefined
57
+ const hit = await cache?.match(url)
58
+ if (hit) return hit.arrayBuffer()
59
+ const { onBytes, signal } = options
60
+ const response = await (env?.fetch ?? fetch)(
61
+ url,
62
+ signal ? { signal } : undefined
63
+ )
64
+ if (!response.ok || !response.body) {
65
+ throw coded(
66
+ `${url} didn't download (HTTP ${response.status})`,
67
+ "download-failed"
68
+ )
69
+ }
70
+ let loaded = 0
71
+ const counted = response.body.pipeThrough(
72
+ new TransformStream<Uint8Array, Uint8Array>({
73
+ transform(chunk, controller) {
74
+ loaded += chunk.byteLength
75
+ onBytes?.(loaded)
76
+ controller.enqueue(chunk)
77
+ }
78
+ })
79
+ )
80
+ if (!cache) return new Response(counted).arrayBuffer()
81
+ try {
82
+ await cache.put(url, new Response(counted))
83
+ } catch (error) {
84
+ if (signal?.aborted) throw signal.reason ?? error
85
+ const full =
86
+ error instanceof DOMException && error.name === "QuotaExceededError"
87
+ throw coded(
88
+ full
89
+ ? "There's no room to store the model on this device"
90
+ : `${url} couldn't be stored (${error instanceof Error ? error.message : String(error)})`,
91
+ full ? "storage-full" : "download-failed",
92
+ error
93
+ )
94
+ }
95
+ const stored = await cache.match(url)
96
+ if (!stored) throw coded(`${url} wasn't stored`, "download-failed")
97
+ return stored.arrayBuffer()
98
+ }
99
+
100
+ /** Removes these files from the cache. Returns whether any was stored. */
101
+ export async function removeFiles(
102
+ urls: ReadonlyArray<string>,
103
+ env = environment()
104
+ ): Promise<boolean> {
105
+ if (!env) return false
106
+ const cache = await env.caches.open(MODEL_CACHE).catch(() => undefined)
107
+ if (!cache) return false
108
+ let removed = false
109
+ for (const url of urls) removed = (await cache.delete(url)) || removed
110
+ return removed
111
+ }
@@ -0,0 +1,138 @@
1
+ import assert from "node:assert/strict"
2
+ import { test } from "node:test"
3
+
4
+ import {
5
+ blankAfter,
6
+ commitOrder,
7
+ DEFAULT_SAMPLER,
8
+ drawSprites,
9
+ fixedLengthIds,
10
+ GRID,
11
+ PALETTE,
12
+ PIXELS,
13
+ seededRandom,
14
+ spritePixels
15
+ } from "./tessera.js"
16
+ import type { TesseraSessions } from "./tessera.js"
17
+
18
+ test("the text encoder's ids are padded with the end token to 24", () => {
19
+ // "a red apple", as Tessera's own self-test encodes it.
20
+ assert.deepEqual(fixedLengthIds([49406, 320, 736, 3055, 49407], 49407), [
21
+ 49406,
22
+ 320,
23
+ 736,
24
+ 3055,
25
+ ...Array<number>(20).fill(49407)
26
+ ])
27
+ })
28
+
29
+ test("a prompt over 24 tokens is cut with the end token kept last", () => {
30
+ const ids = fixedLengthIds(
31
+ [49406, ...Array<number>(30).fill(7), 49407],
32
+ 49407
33
+ )
34
+ assert.equal(ids.length, 24)
35
+ assert.equal(ids[0], 49406)
36
+ assert.equal(ids[22], 7)
37
+ assert.equal(ids[23], 49407)
38
+ })
39
+
40
+ test("the cosine schedule leaves fewer blank pixels each step, and none after the last", () => {
41
+ const blanks = Array.from({ length: 16 }, (_, step) => blankAfter(step, 16))
42
+ for (let i = 1; i < blanks.length; i++) assert.ok(blanks[i] <= blanks[i - 1])
43
+ assert.ok(blanks[0] < PIXELS)
44
+ assert.equal(blanks[15], 0)
45
+ })
46
+
47
+ test("the seeded random source repeats for a seed and stays in [0, 1)", () => {
48
+ const a = seededRandom(42)
49
+ const b = seededRandom(42)
50
+ for (let i = 0; i < 100; i++) {
51
+ const x = a()
52
+ assert.equal(x, b())
53
+ assert.ok(x >= 0 && x < 1)
54
+ }
55
+ assert.notEqual(seededRandom(1)(), seededRandom(2)())
56
+ })
57
+
58
+ test("a blank pixel goes ahead if it's certain or beats its uncertain blank neighbours, then by score", () => {
59
+ const blank = new Uint8Array(PIXELS).fill(1)
60
+ const confidence = new Float32Array(PIXELS).fill(0.1)
61
+ const score = new Float32Array(PIXELS).fill(-5)
62
+ // Two uncertain neighbours: only the better one goes ahead.
63
+ score[0] = -1
64
+ score[1] = -2
65
+ // A certain pixel goes ahead even beside a better neighbour.
66
+ confidence[200] = 0.95
67
+ score[200] = -4
68
+ score[201] = -3
69
+ const order = commitOrder(blank, confidence, score, 0.9)
70
+ assert.equal(order.length, PIXELS)
71
+ assert.deepEqual(order.slice(0, 3), [0, 201, 200])
72
+ // Pixel 1 loses to its neighbour 0, so a pixel that ties all its neighbours comes before it.
73
+ assert.ok(order.indexOf(1) > order.indexOf(GRID * 8 + 8))
74
+ })
75
+
76
+ test("committed pixels are left out of the order", () => {
77
+ const blank = new Uint8Array(PIXELS)
78
+ blank[5] = 1
79
+ blank[77] = 1
80
+ const order = commitOrder(
81
+ blank,
82
+ new Float32Array(PIXELS),
83
+ new Float32Array(PIXELS),
84
+ 0.9
85
+ )
86
+ assert.deepEqual(
87
+ [...order].sort((a, b) => a - b),
88
+ [5, 77]
89
+ )
90
+ })
91
+
92
+ test("a sprite's pixels are its tokens' palette colors", () => {
93
+ const tokens = new Int32Array(PIXELS)
94
+ tokens[1] = 2
95
+ const rgba = spritePixels(tokens, [
96
+ [0, 0, 0, 0],
97
+ [1, 1, 1, 255],
98
+ [10, 20, 30, 255]
99
+ ])
100
+ assert.deepEqual([...rgba.subarray(0, 8)], [0, 0, 0, 0, 10, 20, 30, 255])
101
+ })
102
+
103
+ test("the sampler stops once every pixel is painted, however many steps it was given", async () => {
104
+ let passes = 0
105
+ class Tensor {
106
+ constructor(
107
+ readonly type: string,
108
+ readonly data: unknown,
109
+ readonly dims: ReadonlyArray<number>
110
+ ) {}
111
+ }
112
+ const sessions = {
113
+ Tensor,
114
+ textEncoder: {
115
+ run: () =>
116
+ Promise.resolve({
117
+ last_hidden_state: { data: new Float32Array(24 * 512) },
118
+ pooler_output: { data: new Float32Array(512) }
119
+ })
120
+ },
121
+ denoiser: {
122
+ run: (feeds: { x: Tensor }) => {
123
+ passes++
124
+ // Flat logits: every pixel is as uncertain as it can be, so each step paints only what the schedule asks.
125
+ return Promise.resolve({
126
+ logits: { data: new Float32Array(feeds.x.dims[0] * PIXELS * PALETTE) }
127
+ })
128
+ }
129
+ }
130
+ } as unknown as TesseraSessions
131
+ const [sprite] = await drawSprites(sessions, new Array(24).fill(0), 1, {
132
+ ...DEFAULT_SAMPLER,
133
+ steps: 1000,
134
+ seed: 1
135
+ })
136
+ assert.ok(passes <= PIXELS, `${passes} passes`)
137
+ assert.ok(sprite.every((token) => token < PALETTE))
138
+ })