// onnxruntime glue. `ort` is injected: onnxruntime-web (WebGPU) in the browser, onnxruntime-node (CPU) in tests. import { toHalf, fromHalf } from "./utils.js"; /** * One ONNX graph as a session. Returns {run(feeds, fetches?) -> outputs}. * Browser: bytes come from `files` (Hub + Cache API) and external data is passed as `externalData`. * Node + LocalFiles: ORT reads the file and its `_data` sidecar from disk. */ export async function createSession(ort, files, path, { device, progress_callback, externalData = false, keepOutputsOnGpu = false } = {}) { const onProgress = progress_callback ? (e) => progress_callback({ status: "progress", ...e }) : undefined; progress_callback?.({ status: "initiate", file: path }); const opts = { executionProviders: [device === "webgpu" ? "webgpu" : "cpu"], graphOptimizationLevel: "all" }; if (device === "webgpu" && keepOutputsOnGpu) opts.preferredOutputLocation = "gpu-buffer"; let session; if (typeof files.path === "function" && device !== "webgpu") { session = await ort.InferenceSession.create(files.path(path), opts); onProgress?.({ file: path, loaded: 1, total: 1 }); } else { const model = await files.bytes(path, onProgress); if (externalData) { // true = one `_data` file; a number n = n chunks `_data`, `_data_1`, ... const name = path.split("/").pop() + "_data", n = externalData === true ? 1 : externalData; opts.externalData = []; for (let i = 0; i < n; i++) { const suffix = i ? `_${i}` : ""; opts.externalData.push({ path: name + suffix, data: await files.bytes(path + "_data" + suffix, onProgress) }); } } session = await ort.InferenceSession.create(model, opts); } progress_callback?.({ status: "done", file: path }); return { session, run: (feeds, fetches) => (fetches ? session.run(feeds, fetches) : session.run(feeds)), release: () => session.release() }; } /** fp16 tensor from fp16 bits (Uint16Array) or floats (converted). */ export function f16(ort, data, dims) { const bits = data instanceof Uint16Array ? data : toHalf(data instanceof Float32Array ? data : Float32Array.from(data)); return new ort.Tensor("float16", bits, dims); } export function f32(ort, data, dims) { return new ort.Tensor("float32", data instanceof Float32Array ? data : Float32Array.from(data), dims); } /** fp16 tensor (CPU) -> its raw fp16 bits as a Uint16Array (ORT may hand back Uint16Array or a native Float16Array). */ export function halfBits(t) { const d = t.data; if (d instanceof Uint16Array) return d; if (typeof Float16Array !== "undefined" && d instanceof Float16Array) return new Uint16Array(d.buffer, d.byteOffset, d.length); return toHalf(readFloat(t)); } /** Any float tensor (CPU) -> Float32Array. Handles Uint16Array fp16 bits and native Float16Array. */ export function readFloat(t) { const d = t.data; if (d instanceof Float32Array) return d; if (d instanceof Uint16Array) return fromHalf(d); return Float32Array.from(d); } let PERSIST_ON_GPU = true; /** Turn GPU-resident shared inputs on or off (for A/B timing in the browser). */ export function setPersistOnGpu(on) { PERSIST_ON_GPU = !!on; } /** * A tensor that many session.run calls read. On WebGPU it is uploaded once into a GPU buffer, so passing it to every * block does not copy it again; on CPU it is returned unchanged. Free it with `release`. */ export async function persistent(ort, device, t) { if (!PERSIST_ON_GPU || device !== "webgpu") return t; const gpu = await ort.env.webgpu.device; const bytes = new Uint8Array(t.data.buffer, t.data.byteOffset, t.data.byteLength); const size = Math.max(16, Math.ceil(bytes.byteLength / 16) * 16); // writeBuffer wants 4-byte multiples const buf = gpu.createBuffer({ size, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST }); if (bytes.byteLength % 4 === 0) gpu.queue.writeBuffer(buf, 0, bytes); else { const p = new Uint8Array(Math.ceil(bytes.byteLength / 4) * 4); p.set(bytes); gpu.queue.writeBuffer(buf, 0, p); } return ort.Tensor.fromGpuBuffer(buf, { dataType: t.type, dims: t.dims, dispose: () => buf.destroy() }); } /** Free GPU-resident outputs. CPU tensors need nothing. */ export function release(t) { if (t && t.location === "gpu-buffer") t.dispose(); }