@hackbuild/imagegen 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Moheeb Zara
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,131 @@
1
- # Temporary Holding Version
1
+ # @hackbuild/imagegen
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Text to image in a tab with SD-Turbo on onnxruntime-web: CLIP ids into the
4
+ text encoder, a seeded Euler loop over the UNet on trailing timesteps, and
5
+ the VAE decoder to RGBA. Code MIT; this README CC-BY-4.0 with the code
6
+ samples also MIT. No weights ship here. The default ONNX export,
7
+ `schmuell/sd-turbo-ort-web`, carries the Stability AI Non-Commercial
8
+ Research Community License, so it allows no commercial use. Upstream
9
+ `stabilityai/sd-turbo` moved to the Stability AI Community License in July
10
+ 2024; to use that licence, point the record at an export made from the
11
+ current upstream weights and check its licence before use.
12
+
13
+ # not on npm yet: the @hackbuild scope is unpublished; build from this repository
14
+ npm install @hackbuild/imagegen
15
+
16
+ ## Use
17
+
18
+ import { generate, IMAGEGEN_RECORDS } from "@hackbuild/imagegen";
19
+
20
+ // sessions from your own bytes (the weights store), webgpu execution provider
21
+ const sessions = {
22
+ textEncoder: await ort.InferenceSession.create(te, { executionProviders: ["webgpu"] }),
23
+ unet: await ort.InferenceSession.create(unet, { executionProviders: ["webgpu"] }),
24
+ vaeDecoder: await ort.InferenceSession.create(vae, { executionProviders: ["webgpu"] }),
25
+ };
26
+ const clip = await AutoTokenizer.from_pretrained("Xenova/clip-vit-base-patch16"); // CLIP tokenizer, MIT
27
+ const tokenize = async (p) => (await clip(p, { padding: "max_length", max_length: 77, truncation: true })).input_ids.data;
28
+
29
+ const img = await generate(ort, sessions, tokenize, {
30
+ prompt: "a ceramic mug on a wooden shelf",
31
+ steps: 1,
32
+ seed: 42,
33
+ run: (fn) => hub.exclusive("gpu", fn), // share the gpu with a chat or vision model
34
+ });
35
+ ctx2d.putImageData(new ImageData(img.rgba, img.width, img.height), 0, 0);
36
+
37
+ ## Through the models hub
38
+
39
+ import { ortProvider, loadOrt } from "@hackbuild/devices";
40
+ import { attachImagegen, loadImagegen, loadLabel, IMAGEGEN_RECORDS } from "@hackbuild/imagegen";
41
+
42
+ hub.provide("ort", ortProvider({ runtime: () => loadOrt(), store }).factory); // once per page
43
+ attachImagegen(hub);
44
+ const rec = IMAGEGEN_RECORDS[1]; // sd-1.5
45
+ button.textContent = loadLabel(rec); // "load stable diffusion 1.5, about 2.0 gb (inferred)"
46
+ const gen = await loadImagegen(hub, { id: rec.id });
47
+ const img = await gen.generate(tokenize, { prompt, negative, seed, signal });
48
+
49
+ The three graphs come through the shared weight store, once, and are
50
+ keyed by their folder (`text_encoder`, `unet`, `vae_decoder`), since all
51
+ three files are named `model.onnx`. Every graph call runs under
52
+ `hub.run`, so the gpu lock and frame budget apply. In stub mode, register
53
+ `stubFactory({ imagegen: () => stubImagegenModel() })` for a grey image
54
+ with no weights.
55
+
56
+ Each record carries a `form`, the fields a model select reshapes the
57
+ form to, after an earlier image generation bench's model table:
58
+
59
+ | record | steps (min, max, default) | guidance | negative prompt | sizes | spacing | size |
60
+ |---|---|---|---|---|---|---|
61
+ | `sd-turbo` | 1, 4, 2 | none | no | 512 | trailing | 2.6 GB (inferred) |
62
+ | `sd-1.5` | 5, 40, 22 | 1 to 12, 7.5 | yes | 512 | leading, offset 1 | 2.0 GB (inferred) |
63
+
64
+ `applyForm` fills the defaults, clamps steps and guidance, drops fields
65
+ the model does not take, and refuses a size its graphs do not accept with
66
+ a `FormError` whose message is the copy. `loadLabel(record)` names the
67
+ size and its source for the load button. SD 1.5 weights carry CreativeML
68
+ OpenRAIL-M, with use restrictions in its attachment A.
69
+
70
+ ## Behaviour
71
+
72
+ - Scheduler, written from the published diffusers description: 1000
73
+ scaled linear betas from 0.00085 to 0.012, sigma = sqrt((1 - alphaBar)
74
+ / alphaBar), trailing spacing (1 step is 999; 4 steps are 999, 749,
75
+ 499, 249), UNet input divided by sqrt(sigma^2 + 1), Euler step on the
76
+ predicted noise. sigma at 999 is 14.6146 (computed).
77
+ - Guidance: above 1 the UNet runs twice a step, on the prompt and on the
78
+ negative (the empty prompt when absent), one sample per call so exports
79
+ fixed at batch 1 still run, and the noise is uncond + scale * (cond -
80
+ uncond). Leading spacing (SD 1.5) is 1000 // steps apart plus 1, and
81
+ its first noise is scaled by sqrt(sigma^2 + 1), as diffusers does.
82
+ - Noise: mulberry32 seeded, Box-Muller to a normal; pass `rng` to
83
+ replace it. The same seed gives the same initial latent bit for bit.
84
+ - Graph names: `input_ids` to `last_hidden_state`; `sample`, `timestep`
85
+ (int64) and `encoder_hidden_states` to `out_sample`; `latent_sample` to
86
+ `sample`, as in an earlier build. Output sides are multiples of 8;
87
+ the default is 512.
88
+ - Every graph call goes through `run`, so the models hub's gpu lock and
89
+ frame budget apply.
90
+
91
+ The family plan lists a Rust half for this package; the scheduler is a
92
+ few thousand multiply adds per step, so it stays in TypeScript and no
93
+ crate was written.
94
+
95
+ ## What is verified, and what is not
96
+
97
+ ### Verified on this machine
98
+
99
+ - 2026-11-22: `npx vitest run packages/imagegen` passes, 10 tests, in
100
+ Node 22.18.0: sigmas, trailing timesteps, seeded noise statistics, an
101
+ Euler step that removes exactly predicted noise, id padding, RGBA
102
+ conversion, the graph call order and shapes against fake sessions,
103
+ seed reproducibility and abort.
104
+
105
+ - 2026-11-24: `test/hub.test.ts`, 8 tests: both forms, the load label,
106
+ applyForm clamps and refusals, leading timesteps, the guidance mix
107
+ against a hand computed latent, a load of sd-1.5 through the devices
108
+ ort provider and a memory weight store with fake sessions (three
109
+ fetches, graphs keyed by folder, 13 hub runs for 5 steps), the stub
110
+ mode, and a refusal when the graphs are missing.
111
+
112
+ ### Not verified by anything
113
+
114
+ - SD-Turbo on real onnxruntime-web webgpu: graph names, image quality,
115
+ speed and memory.
116
+ - The repo file paths in both records (inferred), and whether
117
+ `microsoft/stable-diffusion-v1.5-webnn` exists with those paths, takes
118
+ float32 inputs and runs on onnxruntime-web webgpu. SD 1.5 image quality
119
+ with this sampler.
120
+ - A wasm path; an earlier build had none.
121
+
122
+ ## Size budget
123
+
124
+ | file | gzip (measured) | ceiling |
125
+ |---|---|---|
126
+ | `dist/index.js` (main entry, imports external) | 5,631 bytes | 5,912 bytes |
127
+ | `dist/single/index.iife.js` (single file build) | 5,276 bytes | 5,539 bytes |
128
+
129
+ Measured 2026-11-24 by `node tools/lint-packages.mjs` (gzip level 9) from the packed
130
+ tarball. Generated from `tools/size-budget.json`; CI fails when a file moves more than
131
+ 5 percent from its row.
package/dist/hub.d.ts ADDED
@@ -0,0 +1,53 @@
1
+ /**
2
+ * The hub loader: image models load through the models hub and the weight
3
+ * store like any other ort model, so the tool never builds sessions by
4
+ * hand. Register an ort provider once (`ortProvider` from
5
+ * @hackbuild/devices), call attachImagegen, then loadImagegen. Each graph
6
+ * call of a generate runs under hub.run, so the gpu lock and frame budget
7
+ * apply. In stub mode, `stubImagegenModel` serves a flat grey image with
8
+ * no weights.
9
+ */
10
+ import type { Capability, Hub, Loaded, ModelRecord, RunOptions, UseOptions } from "@hackbuild/models";
11
+ import { type ClipTokenize, type Generated, type GenerateOptions, type OrtLike, type SessionLike, type Sessions } from "./pipeline.js";
12
+ import { type ImageForm } from "./records.js";
13
+ /** What the ort provider loads, structurally: the module and sessions by graph name. */
14
+ export interface ImagegenModel {
15
+ ort: OrtLike;
16
+ sessions: Record<string, SessionLike>;
17
+ }
18
+ export type FormOptions = Omit<GenerateOptions, "run" | "spacing"> & {
19
+ runOptions?: RunOptions;
20
+ };
21
+ export interface ImageGenerator {
22
+ readonly loaded: Loaded<ImagegenModel>;
23
+ readonly record: ModelRecord;
24
+ readonly form: ImageForm;
25
+ readonly sessions: Sessions;
26
+ /** Generate with the form's defaults filled in; fields the model does not take are dropped. */
27
+ generate(tokenize: ClipTokenize, o: FormOptions): Promise<Generated>;
28
+ release(): void;
29
+ }
30
+ /** Thrown when a request does not fit the model's form; the message is the copy to show. */
31
+ export declare class FormError extends Error {
32
+ readonly name = "FormError";
33
+ }
34
+ /** Add the image records to the hub's registry. */
35
+ export declare function attachImagegen(hub: Hub): void;
36
+ /** The three sessions of a loaded model, by the form's graph names. */
37
+ export declare function sessionsOf(m: ImagegenModel, form: ImageForm): Sessions;
38
+ /** Clamp a request to what the form allows, with the form's defaults. */
39
+ export declare function applyForm(form: ImageForm, o: Omit<GenerateOptions, "run">): Omit<GenerateOptions, "run">;
40
+ /**
41
+ * Load an image model through the hub: a record id (`{ id: "sd-1.5" }`)
42
+ * or the capability ("imagegen", which the hub routes, or sends to the
43
+ * stub in stub mode). A record without a form (the stub) gets SD-Turbo's.
44
+ */
45
+ export declare function loadImagegen(hub: Hub, what?: Capability | {
46
+ id: string;
47
+ }, o?: UseOptions): Promise<ImageGenerator>;
48
+ /**
49
+ * A weightless model for stub pages and tests: the text encoder returns
50
+ * zeros, the UNet predicts zero noise, and the VAE returns a flat grey, so
51
+ * the whole flow (stages, timing cells, history) runs with no download.
52
+ */
53
+ export declare function stubImagegenModel(): ImagegenModel;
package/dist/hub.js ADDED
@@ -0,0 +1,106 @@
1
+ /**
2
+ * The hub loader: image models load through the models hub and the weight
3
+ * store like any other ort model, so the tool never builds sessions by
4
+ * hand. Register an ort provider once (`ortProvider` from
5
+ * @hackbuild/devices), call attachImagegen, then loadImagegen. Each graph
6
+ * call of a generate runs under hub.run, so the gpu lock and frame budget
7
+ * apply. In stub mode, `stubImagegenModel` serves a flat grey image with
8
+ * no weights.
9
+ */
10
+ import { generate } from "./pipeline.js";
11
+ import { formOf, IMAGEGEN_RECORDS } from "./records.js";
12
+ /** Thrown when a request does not fit the model's form; the message is the copy to show. */
13
+ export class FormError extends Error {
14
+ name = "FormError";
15
+ }
16
+ /** Add the image records to the hub's registry. */
17
+ export function attachImagegen(hub) {
18
+ hub.registry.add(...IMAGEGEN_RECORDS);
19
+ }
20
+ /** The three sessions of a loaded model, by the form's graph names. */
21
+ export function sessionsOf(m, form) {
22
+ const pick = (k) => {
23
+ const s = m.sessions[k];
24
+ if (!s)
25
+ throw new Error(`the loaded model has no ${k} graph; it has ${Object.keys(m.sessions).join(", ") || "none"}`);
26
+ return s;
27
+ };
28
+ return { textEncoder: pick(form.graphs.textEncoder), unet: pick(form.graphs.unet), vaeDecoder: pick(form.graphs.vaeDecoder) };
29
+ }
30
+ /** Clamp a request to what the form allows, with the form's defaults. */
31
+ export function applyForm(form, o) {
32
+ const size = o.size ?? form.sizes[0];
33
+ if (!form.sizes.includes(size))
34
+ throw new FormError(`this model makes ${form.sizes.join(" or ")} pixel images, not ${size}.`);
35
+ const steps = Math.round(Math.min(form.steps.max, Math.max(form.steps.min, o.steps ?? form.steps.default)));
36
+ const out = { ...o, size, steps, spacing: form.spacing };
37
+ if (form.guidance)
38
+ out.guidance = Math.min(form.guidance.max, Math.max(form.guidance.min, o.guidance ?? form.guidance.default));
39
+ else
40
+ delete out.guidance;
41
+ if (!form.negative)
42
+ delete out.negative;
43
+ return out;
44
+ }
45
+ /**
46
+ * Load an image model through the hub: a record id (`{ id: "sd-1.5" }`)
47
+ * or the capability ("imagegen", which the hub routes, or sends to the
48
+ * stub in stub mode). A record without a form (the stub) gets SD-Turbo's.
49
+ */
50
+ export async function loadImagegen(hub, what = "imagegen", o = {}) {
51
+ const loaded = await hub.use(what, o);
52
+ const form = formOf(loaded.record) ?? IMAGEGEN_RECORDS[0].form;
53
+ let sessions;
54
+ try {
55
+ sessions = sessionsOf(loaded.value, form);
56
+ }
57
+ catch (e) {
58
+ hub.release(loaded);
59
+ throw e;
60
+ }
61
+ return {
62
+ loaded,
63
+ record: loaded.record,
64
+ form,
65
+ sessions,
66
+ generate(tokenize, req) {
67
+ const { runOptions, ...rest } = req;
68
+ const run = (fn) => hub.run(loaded, () => fn(), { ...(runOptions ?? {}), ...(rest.signal ? { signal: rest.signal } : {}) });
69
+ return generate(loaded.value.ort, sessions, tokenize, { ...applyForm(form, rest), run });
70
+ },
71
+ release() {
72
+ hub.release(loaded);
73
+ },
74
+ };
75
+ }
76
+ /**
77
+ * A weightless model for stub pages and tests: the text encoder returns
78
+ * zeros, the UNet predicts zero noise, and the VAE returns a flat grey, so
79
+ * the whole flow (stages, timing cells, history) runs with no download.
80
+ */
81
+ export function stubImagegenModel() {
82
+ class Tensor {
83
+ type;
84
+ data;
85
+ dims;
86
+ constructor(type, data, dims) {
87
+ this.type = type;
88
+ this.data = data;
89
+ this.dims = dims;
90
+ }
91
+ }
92
+ const dims = (t) => t.dims;
93
+ return {
94
+ ort: { Tensor },
95
+ sessions: {
96
+ text_encoder: { run: async () => ({ last_hidden_state: { data: new Float32Array(77 * 8), dims: [1, 77, 8] } }) },
97
+ unet: { run: async (f) => ({ out_sample: { data: new Float32Array(f.sample.data.length) } }) },
98
+ vae_decoder: {
99
+ run: async (f) => {
100
+ const [, , h, w] = dims(f.latent_sample);
101
+ return { sample: { data: new Float32Array(3 * h * 8 * w * 8) } };
102
+ },
103
+ },
104
+ },
105
+ };
106
+ }
@@ -0,0 +1,4 @@
1
+ export { sigmas, trailingTimesteps, leadingTimesteps, mulberry32, gaussian, eulerPlan, euler, type Rng, type EulerPlan, type Spacing } from "./schedule.js";
2
+ export { generate, toRgba, padIds, VAE_SCALE, type OrtLike, type SessionLike, type Sessions, type ClipTokenize, type GenerateOptions, type Generated } from "./pipeline.js";
3
+ export { IMAGEGEN_RECORDS, formOf, loadLabel, type ImageForm, type ImagegenRecord } from "./records.js";
4
+ export { attachImagegen, loadImagegen, sessionsOf, applyForm, stubImagegenModel, FormError, type ImagegenModel, type ImageGenerator, type FormOptions } from "./hub.js";
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { sigmas, trailingTimesteps, leadingTimesteps, mulberry32, gaussian, eulerPlan, euler } from "./schedule.js";
2
+ export { generate, toRgba, padIds, VAE_SCALE } from "./pipeline.js";
3
+ export { IMAGEGEN_RECORDS, formOf, loadLabel } from "./records.js";
4
+ export { attachImagegen, loadImagegen, sessionsOf, applyForm, stubImagegenModel, FormError } from "./hub.js";
@@ -0,0 +1,72 @@
1
+ /**
2
+ * SD-Turbo text to image on onnxruntime-web: CLIP token ids into the text
3
+ * encoder, the Euler loop over the UNet, the latent divided by 0.18215
4
+ * into the VAE decoder, and the [-1, 1] NCHW output to RGBA. The caller
5
+ * brings the ort module, the three sessions (weights through
6
+ * @hackbuild/weights) and a tokenizer; the hub's run() wraps each graph
7
+ * call so the gpu lock and frame budget apply.
8
+ */
9
+ import { type Rng, type Spacing } from "./schedule.js";
10
+ export interface OrtLike {
11
+ Tensor: new (type: string, data: Float32Array | Int32Array | BigInt64Array, dims: number[]) => unknown;
12
+ }
13
+ export interface SessionLike {
14
+ run(feeds: Record<string, unknown>): Promise<Record<string, {
15
+ data: ArrayLike<number>;
16
+ dims?: readonly number[];
17
+ }>>;
18
+ }
19
+ export interface Sessions {
20
+ textEncoder: SessionLike;
21
+ unet: SessionLike;
22
+ vaeDecoder: SessionLike;
23
+ }
24
+ /** Prompt to CLIP ids, padded or cut to 77 (transformers.js AutoTokenizer for Xenova/clip-vit-base-patch16 fits). */
25
+ export type ClipTokenize = (prompt: string) => Promise<ArrayLike<number>> | ArrayLike<number>;
26
+ export interface GenerateOptions {
27
+ prompt: string;
28
+ /** Used only when guidance is above 1; the empty prompt when absent. */
29
+ negative?: string;
30
+ /**
31
+ * Classifier free guidance scale. Above 1 the UNet runs twice a step,
32
+ * on the negative and on the prompt, and the noise is
33
+ * uncond + guidance * (cond - uncond). SD-Turbo takes none (default 1).
34
+ */
35
+ guidance?: number;
36
+ /** Timestep spacing: "trailing" for SD-Turbo (default), "leading" for SD 1.5. */
37
+ spacing?: Spacing;
38
+ /** SD-Turbo is distilled for 1 to 4 steps. Default 1, at most 50. */
39
+ steps?: number;
40
+ seed?: number;
41
+ /** Replaces the seeded noise source. */
42
+ rng?: Rng;
43
+ /** Output side in pixels, a multiple of 8. Default 512. */
44
+ size?: number;
45
+ signal?: AbortSignal;
46
+ /** Wraps each graph call, e.g. (fn) => hub.run(loaded, () => fn(), { frameBudgetMs: 12 }). */
47
+ run?: <T>(fn: () => Promise<T>) => Promise<T>;
48
+ onStep?: (p: {
49
+ stage: "text" | "denoise" | "decode";
50
+ step: number;
51
+ steps: number;
52
+ ms: number;
53
+ }) => void;
54
+ now?: () => number;
55
+ }
56
+ export interface Generated {
57
+ width: number;
58
+ height: number;
59
+ /** RGBA, ready for new ImageData(rgba, width, height). */
60
+ rgba: Uint8ClampedArray;
61
+ seed: number;
62
+ ms: {
63
+ text: number;
64
+ unet: number;
65
+ vae: number;
66
+ };
67
+ }
68
+ export declare const VAE_SCALE = 0.18215;
69
+ /** NCHW floats in [-1, 1] to RGBA bytes. */
70
+ export declare function toRgba(nchw: ArrayLike<number>, w: number, h: number): Uint8ClampedArray;
71
+ export declare function padIds(ids: ArrayLike<number>, n?: number, pad?: number): Int32Array;
72
+ export declare function generate(ort: OrtLike, s: Sessions, tokenize: ClipTokenize, o: GenerateOptions): Promise<Generated>;
@@ -0,0 +1,95 @@
1
+ /**
2
+ * SD-Turbo text to image on onnxruntime-web: CLIP token ids into the text
3
+ * encoder, the Euler loop over the UNet, the latent divided by 0.18215
4
+ * into the VAE decoder, and the [-1, 1] NCHW output to RGBA. The caller
5
+ * brings the ort module, the three sessions (weights through
6
+ * @hackbuild/weights) and a tokenizer; the hub's run() wraps each graph
7
+ * call so the gpu lock and frame budget apply.
8
+ */
9
+ import { euler, eulerPlan, gaussian, mulberry32 } from "./schedule.js";
10
+ export const VAE_SCALE = 0.18215;
11
+ /** NCHW floats in [-1, 1] to RGBA bytes. */
12
+ export function toRgba(nchw, w, h) {
13
+ const out = new Uint8ClampedArray(w * h * 4);
14
+ const plane = w * h;
15
+ for (let i = 0; i < plane; i++) {
16
+ for (let c = 0; c < 3; c++)
17
+ out[i * 4 + c] = Math.round(((nchw[c * plane + i] + 1) / 2) * 255);
18
+ out[i * 4 + 3] = 255;
19
+ }
20
+ return out;
21
+ }
22
+ export function padIds(ids, n = 77, pad) {
23
+ const out = new Int32Array(n);
24
+ const last = ids.length ? ids[ids.length - 1] : 0;
25
+ out.fill(pad ?? last);
26
+ for (let i = 0; i < Math.min(n, ids.length); i++)
27
+ out[i] = ids[i];
28
+ return out;
29
+ }
30
+ export async function generate(ort, s, tokenize, o) {
31
+ const now = o.now ?? (() => (globalThis.performance ? performance.now() : Date.now()));
32
+ const run = o.run ?? ((fn) => fn());
33
+ const steps = Math.max(1, Math.min(50, o.steps ?? 1));
34
+ const guidance = o.guidance ?? 1;
35
+ const cfg = guidance > 1;
36
+ const seed = (o.seed ?? 0) >>> 0;
37
+ const size = o.size ?? 512;
38
+ if (size % 8)
39
+ throw new Error("size must be a multiple of 8");
40
+ const lw = size / 8;
41
+ const n = 4 * lw * lw;
42
+ const ms = { text: 0, unet: 0, vae: 0 };
43
+ let t = now();
44
+ const encode = async (text) => {
45
+ const ids = padIds(await tokenize(text.length ? text : " "));
46
+ const te = await run(() => s.textEncoder.run({ input_ids: new ort.Tensor("int32", ids, [1, 77]) }));
47
+ const hidden = te.last_hidden_state ?? Object.values(te)[0];
48
+ return new ort.Tensor("float32", Float32Array.from(hidden.data), [...(hidden.dims ?? [1, 77, hidden.data.length / 77])]);
49
+ };
50
+ const hiddenTensor = await encode(o.prompt);
51
+ const uncondTensor = cfg ? await encode(o.negative ?? "") : null;
52
+ ms.text = now() - t;
53
+ o.onStep?.({ stage: "text", step: 0, steps, ms: ms.text });
54
+ const plan = eulerPlan(steps, o.spacing);
55
+ const randn = gaussian(o.rng ?? mulberry32(seed));
56
+ const latent = new Float32Array(n);
57
+ // diffusers scales the first noise by sigma for trailing spacing and by sqrt(sigma^2 + 1) for leading
58
+ const s0 = plan.sigmas[0];
59
+ const init = o.spacing === "leading" ? Math.sqrt(s0 * s0 + 1) : s0;
60
+ for (let i = 0; i < n; i++)
61
+ latent[i] = randn() * init;
62
+ const final = await euler(latent, plan, async (scaled, timestep, step) => {
63
+ const t0 = now();
64
+ const unet = async (h) => {
65
+ const u = await run(() => s.unet.run({
66
+ sample: new ort.Tensor("float32", scaled, [1, 4, lw, lw]),
67
+ timestep: new ort.Tensor("int64", BigInt64Array.from([BigInt(timestep)]), [1]),
68
+ encoder_hidden_states: h,
69
+ }));
70
+ return (u.out_sample ?? Object.values(u)[0]).data;
71
+ };
72
+ const c = await unet(hiddenTensor);
73
+ let e = c;
74
+ if (uncondTensor) {
75
+ // one sample per call, so exports fixed at batch 1 still run
76
+ const u = await unet(uncondTensor);
77
+ const g = new Float32Array(c.length);
78
+ for (let i = 0; i < g.length; i++)
79
+ g[i] = u[i] + guidance * (c[i] - u[i]);
80
+ e = g;
81
+ }
82
+ const d = now() - t0;
83
+ ms.unet += d;
84
+ o.onStep?.({ stage: "denoise", step: step + 1, steps, ms: d });
85
+ return e;
86
+ }, o.signal);
87
+ t = now();
88
+ const vin = new Float32Array(n);
89
+ for (let i = 0; i < n; i++)
90
+ vin[i] = final[i] / VAE_SCALE;
91
+ const v = await run(() => s.vaeDecoder.run({ latent_sample: new ort.Tensor("float32", vin, [1, 4, lw, lw]) }));
92
+ ms.vae = now() - t;
93
+ o.onStep?.({ stage: "decode", step: steps, steps, ms: ms.vae });
94
+ return { width: size, height: size, rgba: toRgba((v.sample ?? Object.values(v)[0]).data, size, size), seed, ms };
95
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Image generation records. Licences are the model cards' as of
3
+ * 2026-11-22; check them before shipping a product. Sizes inferred.
4
+ *
5
+ * Each record carries a `form`: what the generate form shows for it, so a
6
+ * model select can reshape the form (steps range and default, guidance and
7
+ * a negative prompt only where the model takes them, the sizes its graphs
8
+ * accept) and the load button can name the size. The field set follows an
9
+ * earlier image generation bench's model table.
10
+ */
11
+ import type { ModelRecord } from "@hackbuild/models";
12
+ import type { Spacing } from "./schedule.js";
13
+ export interface ImageForm {
14
+ steps: {
15
+ min: number;
16
+ max: number;
17
+ default: number;
18
+ };
19
+ /** Classifier free guidance; null when the model takes none and the field is hidden. */
20
+ guidance: {
21
+ min: number;
22
+ max: number;
23
+ default: number;
24
+ step: number;
25
+ } | null;
26
+ /** Show a negative prompt field. Only models run with guidance use one. */
27
+ negative: boolean;
28
+ /** Output sides in pixels the graphs accept, the default first. */
29
+ sizes: number[];
30
+ spacing: Spacing;
31
+ /** One line under the select saying what the model is. */
32
+ note: string;
33
+ /** CLIP tokenizer the caller loads, transformers.js model id. */
34
+ tokenizer: string;
35
+ /** Session keys of the three graphs in the loaded ort model. */
36
+ graphs: {
37
+ textEncoder: string;
38
+ unet: string;
39
+ vaeDecoder: string;
40
+ };
41
+ }
42
+ export type ImagegenRecord = ModelRecord & {
43
+ form: ImageForm;
44
+ };
45
+ export declare const IMAGEGEN_RECORDS: ImagegenRecord[];
46
+ /** The form for a record, or null for a record without one (a stub). */
47
+ export declare function formOf(rec: ModelRecord | undefined): ImageForm | null;
48
+ /** The load button label: names the model and its download size with the size's source. */
49
+ export declare function loadLabel(rec: ModelRecord): string;
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Image generation records. Licences are the model cards' as of
3
+ * 2026-11-22; check them before shipping a product. Sizes inferred.
4
+ *
5
+ * Each record carries a `form`: what the generate form shows for it, so a
6
+ * model select can reshape the form (steps range and default, guidance and
7
+ * a negative prompt only where the model takes them, the sizes its graphs
8
+ * accept) and the load button can name the size. The field set follows an
9
+ * earlier image generation bench's model table.
10
+ */
11
+ const graphs = { textEncoder: "text_encoder", unet: "unet", vaeDecoder: "vae_decoder" };
12
+ const files = [{ path: "text_encoder/model.onnx" }, { path: "unet/model.onnx" }, { path: "vae_decoder/model.onnx" }];
13
+ // fixed free dimensions for a 512 pixel image at batch 1, as an earlier build set them; ort ignores names a graph lacks
14
+ const free512 = {
15
+ freeDimensionOverrides: { batch_size: 1, num_channels: 4, height: 64, width: 64, sequence_length: 77, num_channels_latent: 4, height_latent: 64, width_latent: 64 },
16
+ };
17
+ export const IMAGEGEN_RECORDS = [
18
+ {
19
+ id: "sd-turbo",
20
+ label: "sd-turbo 512",
21
+ provides: ["imagegen"],
22
+ provider: "ort",
23
+ source: { repo: "schmuell/sd-turbo-ort-web", files },
24
+ sizeMB: 2600,
25
+ sizeSource: "inferred",
26
+ ladder: [{ device: "webgpu", ort: { executionProviders: ["webgpu"] }, options: free512 }],
27
+ licence: "Stability AI Non-Commercial Research Community License (the LICENSE in schmuell/sd-turbo-ort-web; upstream stabilityai/sd-turbo moved to the Community License in July 2024, this export did not)",
28
+ commercial: false,
29
+ place: "gpu",
30
+ runtime: "onnxruntime-web@1.27.0",
31
+ notes: [
32
+ "webgpu only in an earlier build, no wasm floor",
33
+ "tokenizer: Xenova/clip-vit-base-patch16 through transformers.js (CLIP weights MIT)",
34
+ "graph file paths inferred from an earlier build, not checked against the repo",
35
+ ],
36
+ form: {
37
+ steps: { min: 1, max: 4, default: 2 },
38
+ guidance: null,
39
+ negative: false,
40
+ sizes: [512],
41
+ spacing: "trailing",
42
+ note: "distilled from sd 2.1. 1 to 4 steps, no negative prompt. the fastest path.",
43
+ tokenizer: "Xenova/clip-vit-base-patch16",
44
+ graphs,
45
+ },
46
+ },
47
+ {
48
+ id: "sd-1.5",
49
+ label: "stable diffusion 1.5",
50
+ provides: ["imagegen"],
51
+ provider: "ort",
52
+ source: { repo: "microsoft/stable-diffusion-v1.5-webnn", files },
53
+ sizeMB: 2000,
54
+ sizeSource: "inferred",
55
+ ladder: [{ device: "webgpu", ort: { executionProviders: ["webgpu"] }, options: free512 }],
56
+ licence: "CreativeML OpenRAIL-M (use restrictions in its attachment A)",
57
+ commercial: true,
58
+ place: "gpu",
59
+ runtime: "onnxruntime-web@1.27.0",
60
+ notes: [
61
+ "about 2 GB by an earlier bench's label (vendor); the repo, its file paths and its input dtypes are inferred and not checked",
62
+ "runs the unet twice a step for guidance, so a step costs about twice an sd-turbo step (inferred)",
63
+ "tokenizer: Xenova/clip-vit-base-patch16 through transformers.js (CLIP weights MIT)",
64
+ ],
65
+ form: {
66
+ steps: { min: 5, max: 40, default: 22 },
67
+ guidance: { min: 1, max: 12, default: 7.5, step: 0.5 },
68
+ negative: true,
69
+ sizes: [512],
70
+ spacing: "leading",
71
+ note: "classic sd, openrail-m licence. 20 to 30 steps with guidance, takes a negative prompt. slower per image.",
72
+ tokenizer: "Xenova/clip-vit-base-patch16",
73
+ graphs,
74
+ },
75
+ },
76
+ ];
77
+ /** The form for a record, or null for a record without one (a stub). */
78
+ export function formOf(rec) {
79
+ const f = rec?.form;
80
+ return f ?? null;
81
+ }
82
+ /** The load button label: names the model and its download size with the size's source. */
83
+ export function loadLabel(rec) {
84
+ const name = rec.label ?? rec.id;
85
+ if (rec.sizeMB === null)
86
+ return `load ${name}, size unknown`;
87
+ if (rec.sizeMB === 0)
88
+ return `load ${name}, no download`;
89
+ const size = rec.sizeMB >= 1000 ? `${(rec.sizeMB / 1000).toFixed(1)} gb` : `${rec.sizeMB} mb`;
90
+ return `load ${name}, about ${size} (${rec.sizeSource})`;
91
+ }