@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.
package/src/tessera.ts ADDED
@@ -0,0 +1,295 @@
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
+
15
+ /** The canvas: GRID×GRID pixels, each one of K palette tokens. */
16
+ export const GRID = 16
17
+ export const PIXELS = GRID * GRID
18
+ export const PALETTE = 512
19
+ /** The token of a pixel not painted yet. */
20
+ const MASK = PALETTE
21
+ const TEXT_LEN = 24
22
+ const TEXT_DIM = 512
23
+
24
+ /** The sampler's settings. */
25
+ export type SamplerSettings = {
26
+ /** Denoiser passes; each commits a share of the blank pixels. */
27
+ steps: number
28
+ /** Classifier-free guidance: how far each pixel is pushed toward the prompt. */
29
+ guidanceScale: number
30
+ /** The Gumbel noise on the commit order at the first step (it fades to none). */
31
+ choiceTemperature: number
32
+ /** A pixel at least this certain is committed without competing with its neighbours. */
33
+ certainty: number
34
+ /** The random source's seed: the same seed, prompt and settings draw the same images. */
35
+ seed: number
36
+ }
37
+
38
+ export const DEFAULT_SAMPLER: Omit<SamplerSettings, "seed"> = {
39
+ steps: 16,
40
+ guidanceScale: 3,
41
+ choiceTemperature: 2,
42
+ certainty: 0.9
43
+ }
44
+
45
+ /** What the pipeline runs on: ONNX Runtime's tensor class and the two sessions. */
46
+ export type TesseraSessions = {
47
+ Tensor: typeof OrtTensor
48
+ denoiser: InferenceSession
49
+ textEncoder: InferenceSession
50
+ }
51
+
52
+ /** Mulberry32: a small seeded random source, uniform on [0, 1). */
53
+ export function seededRandom(seed: number) {
54
+ let a = seed >>> 0
55
+ return () => {
56
+ a = (a + 0x6d2b79f5) >>> 0
57
+ let t = a
58
+ t = Math.imul(t ^ (t >>> 15), t | 1)
59
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
60
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
61
+ }
62
+ }
63
+
64
+ /**
65
+ * The text encoder's input: the prompt's ids with its start and end tokens,
66
+ * padded with the end token to TEXT_LEN, or cut to it with the end token
67
+ * kept last.
68
+ */
69
+ export function fixedLengthIds(
70
+ ids: ReadonlyArray<number>,
71
+ endToken: number
72
+ ): Array<number> {
73
+ const kept =
74
+ ids.length > TEXT_LEN ? [...ids.slice(0, TEXT_LEN - 1), endToken] : [...ids]
75
+ while (kept.length < TEXT_LEN) kept.push(endToken)
76
+ return kept
77
+ }
78
+
79
+ /** Blank pixels left after step `step` of `steps` (cosine schedule; none after the last). */
80
+ export function blankAfter(step: number, steps: number) {
81
+ return step === steps - 1
82
+ ? 0
83
+ : Math.floor(PIXELS * Math.cos((Math.PI / 2) * ((step + 1) / steps)))
84
+ }
85
+
86
+ /**
87
+ * The order to commit this step's blank pixels in, best first. Pixels at
88
+ * least `certainty` sure go first; of the others, a pixel goes ahead only if
89
+ * it scores at least as well as every uncertain blank neighbour, so a step's
90
+ * commits spread out instead of clumping.
91
+ */
92
+ export function commitOrder(
93
+ blank: Uint8Array,
94
+ confidence: Float32Array,
95
+ score: Float32Array,
96
+ certainty: number
97
+ ): Array<number> {
98
+ const ranked: Array<[number, number]> = []
99
+ for (let i = 0; i < PIXELS; i++) {
100
+ if (!blank[i]) continue
101
+ let ahead = confidence[i] >= certainty
102
+ if (!ahead) {
103
+ const row = Math.floor(i / GRID)
104
+ const col = i % GRID
105
+ let best = -Infinity
106
+ for (
107
+ let r = Math.max(row - 1, 0);
108
+ r <= Math.min(row + 1, GRID - 1);
109
+ r++
110
+ ) {
111
+ for (
112
+ let c = Math.max(col - 1, 0);
113
+ c <= Math.min(col + 1, GRID - 1);
114
+ c++
115
+ ) {
116
+ const j = r * GRID + c
117
+ if (blank[j] && confidence[j] < certainty)
118
+ best = Math.max(best, score[j])
119
+ }
120
+ }
121
+ ahead = score[i] >= best
122
+ }
123
+ ranked.push([score[i] + (ahead ? 1e4 : 0), i])
124
+ }
125
+ ranked.sort((a, b) => b[0] - a[0])
126
+ return ranked.map(([, i]) => i)
127
+ }
128
+
129
+ /** The prompt's text states, for the denoiser. */
130
+ async function encodeText(
131
+ sessions: TesseraSessions,
132
+ ids: ReadonlyArray<number>
133
+ ) {
134
+ const { Tensor, textEncoder } = sessions
135
+ const out = await textEncoder.run({
136
+ input_ids: new Tensor("int64", BigInt64Array.from(ids, BigInt), [
137
+ 1,
138
+ TEXT_LEN
139
+ ])
140
+ })
141
+ return {
142
+ states: out.last_hidden_state.data as Float32Array,
143
+ pooled: out.pooler_output.data as Float32Array
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Draws `count` sprites for one prompt (its fixed-length token ids). Returns
149
+ * each sprite's palette tokens, row by row. `signal` stops it between steps.
150
+ */
151
+ export async function drawSprites(
152
+ sessions: TesseraSessions,
153
+ ids: ReadonlyArray<number>,
154
+ count: number,
155
+ settings: SamplerSettings,
156
+ signal?: AbortSignal
157
+ ): Promise<Array<Int32Array>> {
158
+ const { Tensor, denoiser } = sessions
159
+ const { steps, guidanceScale, choiceTemperature, certainty } = settings
160
+ const random = seededRandom(settings.seed)
161
+ const { states, pooled } = await encodeText(sessions, ids)
162
+ // Rows [0, count) with the prompt, [count, 2·count) without it.
163
+ const rows = count * 2
164
+ const textStates = new Float32Array(rows * TEXT_LEN * TEXT_DIM)
165
+ const textPooled = new Float32Array(rows * TEXT_DIM)
166
+ for (let r = 0; r < rows; r++) {
167
+ textStates.set(states, r * TEXT_LEN * TEXT_DIM)
168
+ textPooled.set(pooled, r * TEXT_DIM)
169
+ }
170
+ const fixed = {
171
+ text_states: new Tensor("float32", textStates, [rows, TEXT_LEN, TEXT_DIM]),
172
+ text_pooled: new Tensor("float32", textPooled, [rows, TEXT_DIM]),
173
+ drop_text: new Tensor(
174
+ "bool",
175
+ Uint8Array.from({ length: rows }, (_, r) => (r >= count ? 1 : 0)),
176
+ [rows]
177
+ )
178
+ }
179
+
180
+ const tokens = Array.from({ length: count }, () =>
181
+ new Int32Array(PIXELS).fill(MASK)
182
+ )
183
+ const blank = Array.from({ length: count }, () =>
184
+ new Uint8Array(PIXELS).fill(1)
185
+ )
186
+ const selfCond = new Float32Array(rows * PIXELS * PALETTE)
187
+ const probs = new Float32Array(PIXELS * PALETTE)
188
+ const picked = new Int32Array(PIXELS)
189
+ const confidence = new Float32Array(PIXELS)
190
+ const score = new Float32Array(PIXELS)
191
+
192
+ for (let step = 0; step < steps; step++) {
193
+ signal?.throwIfAborted()
194
+ const progress = (step + 1) / steps
195
+ const x = new BigInt64Array(rows * PIXELS)
196
+ const maskRatio = new Float32Array(rows)
197
+ for (let b = 0; b < count; b++) {
198
+ let blanks = 0
199
+ for (let i = 0; i < PIXELS; i++) {
200
+ const token = BigInt(tokens[b][i])
201
+ x[b * PIXELS + i] = token
202
+ x[(b + count) * PIXELS + i] = token
203
+ blanks += blank[b][i]
204
+ }
205
+ maskRatio[b] = maskRatio[b + count] = blanks / PIXELS
206
+ }
207
+ const out = await denoiser.run({
208
+ ...fixed,
209
+ x: new Tensor("int64", x, [rows, PIXELS]),
210
+ mask_ratio: new Tensor("float32", maskRatio, [rows]),
211
+ sc_probs: new Tensor("float32", selfCond, [rows, PIXELS, PALETTE])
212
+ })
213
+ const logits = out.logits.data as Float32Array
214
+ signal?.throwIfAborted()
215
+
216
+ for (let b = 0; b < count; b++) {
217
+ const withText = b * PIXELS * PALETTE
218
+ const withoutText = (b + count) * PIXELS * PALETTE
219
+ // Guided distribution per pixel, and one token drawn from it.
220
+ for (let i = 0; i < PIXELS; i++) {
221
+ const row = i * PALETTE
222
+ let max = -Infinity
223
+ for (let k = 0; k < PALETTE; k++) {
224
+ const without = logits[withoutText + row + k]
225
+ const guided =
226
+ without + guidanceScale * (logits[withText + row + k] - without)
227
+ if (!Number.isFinite(guided))
228
+ throw new Error(
229
+ "The model returned a non-finite value: this device's GPU may not run it correctly"
230
+ )
231
+ probs[row + k] = guided
232
+ if (guided > max) max = guided
233
+ }
234
+ let sum = 0
235
+ for (let k = 0; k < PALETTE; k++) {
236
+ const e = Math.exp(probs[row + k] - max)
237
+ probs[row + k] = e
238
+ sum += e
239
+ }
240
+ let u = random() * sum
241
+ let pick = PALETTE - 1
242
+ for (let k = 0; k < PALETTE; k++) {
243
+ u -= probs[row + k]
244
+ if (u <= 0) {
245
+ pick = k
246
+ break
247
+ }
248
+ }
249
+ for (let k = 0; k < PALETTE; k++) probs[row + k] /= sum
250
+ picked[i] = pick
251
+ confidence[i] = probs[row + pick]
252
+ }
253
+
254
+ let blanks = 0
255
+ for (let i = 0; i < PIXELS; i++) blanks += blank[b][i]
256
+ const commits = Math.min(
257
+ Math.max(blanks - blankAfter(step, steps), 1),
258
+ blanks
259
+ )
260
+
261
+ // Confidence with fading Gumbel noise.
262
+ for (let i = 0; i < PIXELS; i++) {
263
+ const u = Math.min(Math.max(random(), 1e-10), 1 - 1e-10)
264
+ score[i] =
265
+ Math.log(Math.max(confidence[i], 1e-12)) +
266
+ choiceTemperature * (1 - progress) * -Math.log(-Math.log(u))
267
+ }
268
+ for (const i of commitOrder(blank[b], confidence, score, certainty).slice(
269
+ 0,
270
+ commits
271
+ )) {
272
+ tokens[b][i] = picked[i]
273
+ blank[b][i] = 0
274
+ }
275
+
276
+ // Self-conditioning: this step's distribution, for both rows of the image.
277
+ selfCond.set(probs, withText)
278
+ selfCond.set(probs, withoutText)
279
+ }
280
+ // Every pixel painted (the schedule can get there before the last step): no pass is left to run.
281
+ if (blank.every((sprite) => !sprite.includes(1))) break
282
+ }
283
+ return tokens
284
+ }
285
+
286
+ /** A sprite's RGBA pixels, from its tokens and the palette (`palette_rgba`). */
287
+ export function spritePixels(
288
+ tokens: Int32Array,
289
+ palette: ReadonlyArray<ReadonlyArray<number>>
290
+ ): Uint8Array {
291
+ const rgba = new Uint8Array(PIXELS * 4)
292
+ for (let i = 0; i < PIXELS; i++)
293
+ rgba.set(palette[tokens[i]] ?? [0, 0, 0, 0], i * 4)
294
+ return rgba
295
+ }