/** * Tiled ONNX inference for the base plane -- the SCUNet path. * * This is the only file that may import `onnxruntime-node`, and it imports it * lazily: nothing here requires a model to exist until a denoiser is actually * asked to run. The classical stand-ins (`guided`, `nlm`) occupy the same slot * and need no model at all, so the model selector is safe to show even before a * run ever selects SCUNet. * * The model contract is fixed and small: * * input 1 x 3 x TILE x TILE float32, RGB in 0..1 * output 1 x 3 x TILE x TILE float32, same * * `runTiled` is separated from the session so the tiling, padding, feathering * and normalisation can be reasoned about independently of ORT. */ import type { BaseDenoiser, BaseImage } from './standin.ts'; /** Runs one `tile x tile`, 3-channel tile. Input and output are interleaved RGB. */ export type RgbTileRunner = (input: Float32Array, tile: number) => Promise; export interface TileProgress { done: number; total: number; } export interface OnnxBaseOptions { modelPath: string; /** Fixed square size the graph was exported at. Must match the graph. */ tile?: number; /** Overlap in pixels between neighbouring tiles. */ overlap?: number; /** Defaults to physical cores. Keep it below the host's raw decode pool. */ intraOpThreads?: number; /** Called after each tile lands, so a long run can report where it is. */ onProgress?: (progress: TileProgress) => void; } /** * Raised-cosine feather along one axis, floored so no pixel is weighted zero. * * The floor matters: at the image border a tile is the only contributor, and a * zero weight there would divide 0 by 0. */ export function featherWeights(tile: number, overlap: number): Float32Array { const weights = new Float32Array(tile).fill(1); const edge = Math.min(Math.max(0, overlap), Math.floor(tile / 2)); for (let i = 0; i < edge; i++) { const t = (i + 0.5) / edge; weights[i] = Math.max(0.5 - 0.5 * Math.cos(Math.PI * t), 1e-3); weights[tile - 1 - i] = weights[i]; } return weights; } /** Tiled inference with overlap-add and feathering. */ export async function runTiled( runTile: RgbTileRunner, image: BaseImage, tile: number, overlap: number, onProgress?: (progress: TileProgress) => void, ): Promise { const { width, height } = image; if (!Number.isInteger(tile) || tile < 8) throw new Error(`tile must be an integer >= 8, got ${tile}`); if (overlap < 0 || overlap >= tile) throw new Error(`overlap must be in [0, tile), got ${overlap}`); const expected = 3 * tile * tile; const step = tile - overlap; const weights = featherWeights(tile, overlap); const acc = new Float32Array(3 * width * height); const weight = new Float32Array(width * height); const patch = new Float32Array(expected); // Tiles start every `step` pixels, so the last one may hang off the edge. const total = Math.ceil(width / step) * Math.ceil(height / step); let done = 0; for (let ty = 0; ty < height; ty += step) { for (let tx = 0; tx < width; tx += step) { // Gather with clamp-to-edge padding; the convolution needs a full tile // even when the tile hangs off the right or bottom edge. for (let y = 0; y < tile; y++) { const sy = ty + y; const cy = sy < 0 ? 0 : sy >= height ? height - 1 : sy; for (let x = 0; x < tile; x++) { const sx = tx + x; const cx = sx < 0 ? 0 : sx >= width ? width - 1 : sx; const src = (cy * width + cx) * 3; const dst = (y * tile + x) * 3; patch[dst] = image.rgb[src]; patch[dst + 1] = image.rgb[src + 1]; patch[dst + 2] = image.rgb[src + 2]; } } const out = await runTile(patch, tile); if (out.length !== expected) { throw new Error(`tile runner returned ${out.length} values, expected ${expected}`); } for (let y = 0; y < tile; y++) { const sy = ty + y; if (sy < 0 || sy >= height) continue; for (let x = 0; x < tile; x++) { const sx = tx + x; if (sx < 0 || sx >= width) continue; const w = weights[y] * weights[x]; const dst = (sy * width + sx) * 3; const src = (y * tile + x) * 3; acc[dst] += out[src] * w; acc[dst + 1] += out[src + 1] * w; acc[dst + 2] += out[src + 2] * w; weight[sy * width + sx] += w; } } done += 1; onProgress?.({ done, total }); } } const rgb = new Float32Array(3 * width * height); for (let i = 0, p = 0; i < width * height; i++, p += 3) { const w = weight[i] || 1; for (let k = 0; k < 3; k++) { const v = acc[p + k] / w; rgb[p + k] = v < 0 ? 0 : v > 255 ? 255 : v; } } return { rgb, width, height }; } interface Session { run(feeds: Record): Promise>; inputNames: readonly string[]; outputNames: readonly string[]; } /** * Build a `BaseDenoiser` backed by an ONNX model. * * The session is created on first use and memoised, so constructing this is * free and a missing model surfaces as a clear error at run time rather than at * import time. */ export function createOnnxBaseDenoiser(options: OnnxBaseOptions): BaseDenoiser { const tile = options.tile ?? 256; const overlap = options.overlap ?? 32; let sessionPromise: Promise | null = null; const session = (): Promise => { if (!sessionPromise) { sessionPromise = (async () => { const ort = await import('onnxruntime-node'); const created = await ort.InferenceSession.create(options.modelPath, { executionProviders: ['cpu'], graphOptimizationLevel: 'all', intraOpNumThreads: options.intraOpThreads ?? 0, }); return created as unknown as Session; })(); } return sessionPromise; }; return async (image: BaseImage): Promise => { const active = await session(); const ort = await import('onnxruntime-node'); const inputName = active.inputNames[0]; const outputName = active.outputNames[0]; if (!inputName || !outputName) throw new Error('model has no input/output'); // The model expects 0..1; everything above works in 0..255. // // But the two sides disagree about layout: `runTiled` is interleaved (HWC), // while every published denoiser is NCHW (`1x3xTILExTILE`). Handing HWC bytes // to a `[1,3,T,T]` tensor does not throw -- it silently feeds a scrambled // image, so channel 0 holds a third of every row rather than red. The output // needs the mirror transpose for the same reason. const plane = tile * tile; const runTile: RgbTileRunner = async (input, size) => { const normalised = new Float32Array(3 * plane); for (let p = 0, i = 0; p < plane; p++, i += 3) { normalised[p] = input[i] / 255; normalised[plane + p] = input[i + 1] / 255; normalised[2 * plane + p] = input[i + 2] / 255; } const tensor = new ort.Tensor('float32', normalised, [1, 3, size, size]); const result = await active.run({ [inputName]: tensor }); const output = result[outputName]?.data; if (!output) throw new Error(`model produced no output named ${outputName}`); const scaled = new Float32Array(output.length); for (let p = 0, i = 0; p < plane; p++, i += 3) { scaled[i] = output[p] * 255; scaled[i + 1] = output[plane + p] * 255; scaled[i + 2] = output[2 * plane + p] * 255; } return scaled; }; return runTiled(runTile, image, tile, overlap, options.onProgress); }; }