Spaces:
Runtime error
Runtime error
Khunndev
Sisyphus
Run tile inference concurrently with memory-aware concurrency to cut counting wall-clock time.
0fdcb52 Download frontend/src/lib/inference.ts from npisb/pipecountapp-dev: direct link, hf CLI and curl.
- Browser
- Download file 13.2 kB
-
https://huggingface.co/spaces/npisb/pipecountapp-dev/resolve/main/frontend/src/lib/inference.ts
- Command line
-
hf download hf://spaces/npisb/pipecountapp-dev/frontend/src/lib/inference.ts
-
curl -L -o inference.ts https://huggingface.co/spaces/npisb/pipecountapp-dev/resolve/main/frontend/src/lib/inference.ts
13.2 kB
| import * as ort from 'onnxruntime-web' | |
| import { CONFIDENCE_THRESHOLD, IOU_THRESHOLD, MAX_DETECTIONS, MODEL_640_URL, MODEL_URL, TILE_OVERLAP } from './constants' | |
| import { | |
| enhanceImageElement, | |
| shouldAutoTile, | |
| suggestTileGrid, | |
| type EnhanceOptions, | |
| } from './imageEnhance' | |
| import { selectModelForImage } from './modelSelect' | |
| import { nonMaxSuppression, postProcessPipeline, reassignDetectionIds } from './postprocess' | |
| import { canvasToTensor, letterboxCanvas, mapBoxToOriginal } from './preprocess' | |
| import type { Detection, LetterboxMeta, PostProcessReport } from './types' | |
| ort.env.wasm.wasmPaths = 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.26.0/dist/' | |
| // --------------------------------------------------------------------------- | |
| // Backend capability detection (important for low-end Android devices) | |
| // --------------------------------------------------------------------------- | |
| // Multi-threaded WASM needs SharedArrayBuffer, which is only available when the | |
| // page is cross-origin isolated (COOP/COEP). Static hosts (e.g. HF Spaces) don't | |
| // set those headers, so we must run single-threaded — otherwise ORT may try to | |
| // spawn workers and crash on weak devices. | |
| function resolveThreadCount(): number { | |
| const hasSAB = typeof SharedArrayBuffer !== 'undefined' | |
| const isolated = typeof globalThis !== 'undefined' | |
| && Boolean((globalThis as { crossOriginIsolated?: boolean }).crossOriginIsolated) | |
| if (!hasSAB || !isolated) return 1 | |
| const cores = typeof navigator !== 'undefined' ? navigator.hardwareConcurrency || 2 : 2 | |
| return Math.max(1, Math.min(4, cores)) | |
| } | |
| ort.env.wasm.numThreads = resolveThreadCount() | |
| ort.env.wasm.simd = true | |
| // Device memory in GB (Chrome/Android only; capped at 8, undefined elsewhere). | |
| export function getDeviceMemoryGB(): number | undefined { | |
| const m = (navigator as unknown as { deviceMemory?: number }).deviceMemory | |
| return typeof m === 'number' && m > 0 ? m : undefined | |
| } | |
| // Heuristic for memory-constrained devices (typical low-price Android phones). | |
| export function isLowMemoryDevice(): boolean { | |
| const m = getDeviceMemoryGB() | |
| return m !== undefined && m <= 4 | |
| } | |
| // WebGPU often *creates* a session on cheap Android GPUs but then throws at | |
| // run() time. We pre-check for a usable adapter and additionally warm up each | |
| // session so a broken backend is rejected before we depend on it. | |
| let webgpuChecked = false | |
| let webgpuOk = false | |
| async function isWebgpuUsable(): Promise<boolean> { | |
| if (webgpuChecked) return webgpuOk | |
| webgpuChecked = true | |
| try { | |
| const gpu = (navigator as unknown as { gpu?: { requestAdapter(): Promise<unknown> } }).gpu | |
| if (!gpu) { webgpuOk = false; return false } | |
| const adapter = await gpu.requestAdapter() | |
| webgpuOk = Boolean(adapter) | |
| } catch { | |
| webgpuOk = false | |
| } | |
| return webgpuOk | |
| } | |
| // Map each model to the input size used to warm it up. | |
| const MODEL_WARMUP_SIZE: Record<string, number> = { | |
| [MODEL_URL]: 1024, | |
| [MODEL_640_URL]: 640, | |
| } | |
| let sessionCache = new Map<string, Promise<ort.InferenceSession>>() | |
| let activeBackend = 'loading' | |
| // Once a backend has proven it can actually run inference we don't warm up | |
| // subsequent (larger) models — a 1024 warmup is heavy and risks OOM on phones. | |
| let backendValidated = false | |
| async function warmUp(session: ort.InferenceSession, size: number): Promise<void> { | |
| const dummy = new ort.Tensor('float32', new Float32Array(3 * size * size), [1, 3, size, size]) | |
| await session.run({ images: dummy }) | |
| } | |
| async function createSession(modelUrl: string): Promise<ort.InferenceSession> { | |
| const warmSize = MODEL_WARMUP_SIZE[modelUrl] ?? 640 | |
| const backends: Array<{ name: string; providers: ort.InferenceSession.SessionOptions['executionProviders'] }> = [] | |
| if (await isWebgpuUsable()) { | |
| backends.push({ name: 'webgpu', providers: ['webgpu', 'wasm'] }) | |
| } | |
| backends.push({ name: 'wasm', providers: ['wasm'] }) | |
| let lastError: unknown = null | |
| for (const backend of backends) { | |
| let session: ort.InferenceSession | null = null | |
| try { | |
| session = await ort.InferenceSession.create(modelUrl, { | |
| executionProviders: backend.providers, | |
| graphOptimizationLevel: 'all', | |
| }) | |
| // Validate the backend can actually run (catches GPUs that init but fail | |
| // at run()) — but only once, to avoid a costly large-model warmup. | |
| if (!backendValidated) { | |
| await warmUp(session, warmSize) | |
| backendValidated = true | |
| } | |
| activeBackend = backend.name | |
| return session | |
| } catch (err) { | |
| lastError = err | |
| try { await session?.release() } catch { /* ignore */ } | |
| // try the next (more compatible) backend | |
| } | |
| } | |
| throw new Error( | |
| `Failed to initialize the detection model on this device. ${ | |
| lastError instanceof Error ? lastError.message : String(lastError ?? '') | |
| }`, | |
| ) | |
| } | |
| function getSession(modelUrl: string): Promise<ort.InferenceSession> { | |
| let cached = sessionCache.get(modelUrl) | |
| if (!cached) { | |
| cached = createSession(modelUrl).catch((err) => { | |
| // don't cache a failed load — allow a later retry | |
| sessionCache.delete(modelUrl) | |
| throw err | |
| }) | |
| sessionCache.set(modelUrl, cached) | |
| } | |
| return cached | |
| } | |
| export function getActiveBackend(): string { | |
| return activeBackend | |
| } | |
| // Warm only the small (640) model on startup. The large 1024 model is loaded | |
| // lazily when a big photo actually needs it — this keeps peak memory low so | |
| // low-RAM Android devices don't OOM during initial load. | |
| export async function loadModel(onProgress?: (msg: string) => void): Promise<void> { | |
| onProgress?.('Loading model...') | |
| await getSession(MODEL_640_URL) | |
| onProgress?.(`Model ready (${activeBackend})`) | |
| } | |
| function prepareSource( | |
| image: HTMLImageElement, | |
| enhance: boolean, | |
| enhanceOptions?: EnhanceOptions, | |
| ): HTMLCanvasElement | HTMLImageElement { | |
| if (!enhance) { | |
| return image | |
| } | |
| return enhanceImageElement(image, enhanceOptions) | |
| } | |
| async function inferCanvas( | |
| source: HTMLCanvasElement | HTMLImageElement, | |
| session: ort.InferenceSession, | |
| inferenceSize: number, | |
| offsetX: number, | |
| offsetY: number, | |
| regionW: number, | |
| regionH: number, | |
| ): Promise<Detection[]> { | |
| const { canvas, meta } = letterboxCanvas(source, inferenceSize) | |
| const tensor = canvasToTensor(canvas, inferenceSize) | |
| const input = new ort.Tensor('float32', tensor, [1, 3, inferenceSize, inferenceSize]) | |
| const results = await session.run({ images: input }) | |
| const output = results.output.data as Float32Array | |
| const dets = decodeOutput(output, meta, regionW, regionH) | |
| return dets.map((d) => ({ | |
| ...d, | |
| xmin: d.xmin + offsetX, | |
| ymin: d.ymin + offsetY, | |
| xmax: d.xmax + offsetX, | |
| ymax: d.ymax + offsetY, | |
| })) | |
| } | |
| export function decodeOutput( | |
| output: Float32Array, | |
| meta: LetterboxMeta, | |
| imageW: number, | |
| imageH: number, | |
| confThreshold = CONFIDENCE_THRESHOLD, | |
| ): Detection[] { | |
| const rows = output.length / 6 | |
| const raw = [] | |
| for (let i = 0; i < rows; i++) { | |
| const base = i * 6 | |
| const cx = output[base] | |
| const cy = output[base + 1] | |
| const w = output[base + 2] | |
| const h = output[base + 3] | |
| const obj = output[base + 4] | |
| const cls = output[base + 5] | |
| const confidence = obj * cls | |
| if (confidence < confThreshold) { | |
| continue | |
| } | |
| const box = mapBoxToOriginal(cx, cy, w, h, meta) | |
| box.xmin = Math.max(0, Math.min(imageW, box.xmin)) | |
| box.ymin = Math.max(0, Math.min(imageH, box.ymin)) | |
| box.xmax = Math.max(0, Math.min(imageW, box.xmax)) | |
| box.ymax = Math.max(0, Math.min(imageH, box.ymax)) | |
| if (box.xmax <= box.xmin || box.ymax <= box.ymin) { | |
| continue | |
| } | |
| raw.push({ ...box, confidence }) | |
| } | |
| const filtered = nonMaxSuppression(raw, IOU_THRESHOLD, MAX_DETECTIONS) | |
| return filtered.map((d, idx) => ({ | |
| ...d, | |
| id: `det-${idx}-${Date.now()}`, | |
| groupId: 0, | |
| confidence: d.confidence, | |
| })) | |
| } | |
| export async function runDetection( | |
| image: HTMLImageElement, | |
| options?: { | |
| useTiling?: boolean | |
| autoTile?: boolean | |
| enhanceImage?: boolean | |
| enhanceOptions?: EnhanceOptions | |
| filterOutliers?: boolean | |
| onProgress?: (msg: string) => void | |
| onReport?: (r: PostProcessReport) => void | |
| }, | |
| ): Promise<Detection[]> { | |
| await loadModel(options?.onProgress) | |
| const w = image.naturalWidth | |
| const h = image.naturalHeight | |
| const { modelUrl, inferenceSize } = selectModelForImage(w, h) | |
| // The large model may not be warmed yet (we lazy-load it to save memory). | |
| if (!sessionCache.has(modelUrl)) { | |
| options?.onProgress?.('Preparing high-resolution model...') | |
| } | |
| const session = await getSession(modelUrl) | |
| const start = performance.now() | |
| const enhance = options?.enhanceImage ?? true | |
| const useTiling = | |
| options?.useTiling ?? (options?.autoTile !== false && shouldAutoTile(w, h)) | |
| if (useTiling) { | |
| return runTiledDetection(image, session, inferenceSize, { | |
| ...options, | |
| enhanceImage: enhance, | |
| }) | |
| } | |
| options?.onProgress?.(enhance ? 'Enhancing image...' : 'Preparing image...') | |
| const source = prepareSource(image, enhance, options?.enhanceOptions) | |
| const dets = await inferCanvas(source, session, inferenceSize, 0, 0, w, h) | |
| const processed = postProcessPipeline(dets, { | |
| extraOutlierFilter: options?.filterOutliers ?? false, | |
| wasTiled: false, | |
| onReport: options?.onReport, | |
| }) | |
| options?.onProgress?.(`Detected ${processed.length} pipes in ${Math.round(performance.now() - start)}ms`) | |
| return reassignDetectionIds(processed, 'det').map((d) => ({ | |
| ...d, | |
| groupId: 0, | |
| confidence: d.confidence, | |
| })) | |
| } | |
| // How many tiles may be inferred in flight at once. Tile inference is the | |
| // dominant cost on dense bundles, and the old loop ran every tile strictly | |
| // sequentially. Overlapping tiles lets CPU tensor-prep of the next tile run | |
| // while the previous tile's session.run is in flight (and on WebGPU the GPU | |
| // pipelines the runs). Each in-flight 1024 tensor + output is ~25MB+, so we | |
| // stay sequential on low-RAM phones to avoid OOM. | |
| function tileConcurrency(): number { | |
| if (isLowMemoryDevice()) return 1 | |
| if (getActiveBackend() === 'webgpu') return 4 | |
| return 2 | |
| } | |
| async function runWithConcurrency<T, R>( | |
| items: readonly T[], | |
| worker: (item: T) => Promise<R>, | |
| concurrency: number, | |
| ): Promise<R[]> { | |
| const results: R[] = new Array(items.length) | |
| let cursor = 0 | |
| const runLane = async (): Promise<void> => { | |
| while (cursor < items.length) { | |
| const index = cursor | |
| cursor += 1 | |
| results[index] = await worker(items[index]) | |
| } | |
| } | |
| const lanes = Math.max(1, Math.min(concurrency, items.length)) | |
| await Promise.all(Array.from({ length: lanes }, runLane)) | |
| return results | |
| } | |
| async function runTiledDetection( | |
| image: HTMLImageElement, | |
| session: ort.InferenceSession, | |
| inferenceSize: number, | |
| options?: { | |
| enhanceImage?: boolean | |
| enhanceOptions?: EnhanceOptions | |
| filterOutliers?: boolean | |
| onProgress?: (msg: string) => void | |
| onReport?: (r: PostProcessReport) => void | |
| }, | |
| ): Promise<Detection[]> { | |
| const onProgress = options?.onProgress | |
| const w = image.naturalWidth | |
| const h = image.naturalHeight | |
| const grid = suggestTileGrid(w, h) | |
| const overlap = TILE_OVERLAP | |
| const tileW = w / grid | |
| const tileH = h / grid | |
| const all: Detection[] = [] | |
| onProgress?.(`Enhancing + tiling ${grid}x${grid}...`) | |
| const enhanced = (options?.enhanceImage ?? true) | |
| ? enhanceImageElement(image, options?.enhanceOptions) | |
| : image | |
| // Build tile rects (unchanged geometry), then infer with a memory-aware | |
| // concurrency limit instead of a strictly sequential loop. | |
| const rects: Array<{ x1: number; y1: number; cropW: number; cropH: number }> = [] | |
| for (let gy = 0; gy < grid; gy++) { | |
| for (let gx = 0; gx < grid; gx++) { | |
| const x1 = Math.max(0, gx * tileW - (tileW * overlap * (gx > 0 ? 1 : 0))) | |
| const y1 = Math.max(0, gy * tileH - (tileH * overlap * (gy > 0 ? 1 : 0))) | |
| const x2 = Math.min(w, (gx + 1) * tileW + (tileW * overlap * (gx < grid - 1 ? 1 : 0))) | |
| const y2 = Math.min(h, (gy + 1) * tileH + (tileH * overlap * (gy < grid - 1 ? 1 : 0))) | |
| rects.push({ x1, y1, cropW: x2 - x1, cropH: y2 - y1 }) | |
| } | |
| } | |
| const totalTiles = rects.length | |
| let done = 0 | |
| const tileBatches = await runWithConcurrency( | |
| rects, | |
| async (r) => { | |
| const tileCanvas = document.createElement('canvas') | |
| tileCanvas.width = r.cropW | |
| tileCanvas.height = r.cropH | |
| const ctx = tileCanvas.getContext('2d')! | |
| ctx.drawImage(enhanced, r.x1, r.y1, r.cropW, r.cropH, 0, 0, r.cropW, r.cropH) | |
| const dets = await inferCanvas( | |
| tileCanvas, | |
| session, | |
| inferenceSize, | |
| r.x1, | |
| r.y1, | |
| r.cropW, | |
| r.cropH, | |
| ) | |
| done += 1 | |
| onProgress?.(`Tile ${done}/${totalTiles}...`) | |
| return dets | |
| }, | |
| tileConcurrency(), | |
| ) | |
| for (const dets of tileBatches) all.push(...dets) | |
| const merged = reassignDetectionIds( | |
| postProcessPipeline(all, { | |
| extraOutlierFilter: options?.filterOutliers ?? false, | |
| wasTiled: true, | |
| onReport: options?.onReport, | |
| }), | |
| 'pipe', | |
| ).map((d) => ({ ...d, groupId: 0 })) | |
| onProgress?.(`Tiled detection: ${merged.length} pipes`) | |
| return merged | |
| } | |