Spaces:
Running
Running
File size: 12,801 Bytes
31c7d49 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 | import type { OnnxModelManifest } from './modelManifest'
import { copyModelManifest, resolveModelManifest } from './modelManifest'
import type { TensorPayloadMap } from './tensors'
import { assertTensorPayloadMap, tensorPayloadTransferables } from './tensors'
export type OrtExecutionProvider = 'webgpu' | 'wasm'
export interface OrtRuntimeConfiguration {
/** Absolute prefix or explicit files for the ONNX Runtime WASM artifacts. */
wasmPaths?: string | { mjs?: string; wasm?: string }
wasmThreads?: number
wasmSimd?: boolean | 'fixed' | 'relaxed'
}
export interface OrtWebGpuSessionOptions {
preferredLayout?: 'NCHW' | 'NHWC'
forceCpuNodeNames?: readonly string[]
validationMode?: 'disabled' | 'wgpuOnly' | 'basic' | 'full'
}
export interface OrtSessionLoadOptions {
/** If WebGPU session creation fails, retry the whole graph with WASM. Defaults to false. */
allowWasmFallback?: boolean
graphOptimizationLevel?: 'disabled' | 'basic' | 'extended' | 'layout' | 'all'
freeDimensionOverrides?: Readonly<Record<string, number>>
enableGraphCapture?: boolean
logSeverityLevel?: 0 | 1 | 2 | 3 | 4
webgpu?: OrtWebGpuSessionOptions
}
export interface OrtLoadSessionRequest {
sessionId: string
manifest: OnnxModelManifest
options?: OrtSessionLoadOptions
}
export interface OrtRunSessionRequest {
sessionId: string
inputs: TensorPayloadMap
/** Omit to fetch all graph outputs. */
outputs?: readonly string[]
tag?: string
}
export interface OrtRunClientOptions {
/**
* Move input buffers into the worker instead of cloning them. Defaults to
* true. The caller's typed arrays are detached after posting when enabled.
*/
transferInputs?: boolean
}
export interface OrtValueMetadata {
name: string
isTensor: boolean
type?: string
shape?: Array<number | string>
}
export interface OrtConfigureRuntimeResult {
wasmThreads: number
wasmSimd: boolean | 'fixed' | 'relaxed'
wasmPaths: string | { mjs?: string; wasm?: string }
}
export interface OrtLoadSessionResult {
sessionId: string
executionProvider: OrtExecutionProvider
inputNames: string[]
outputNames: string[]
inputMetadata: OrtValueMetadata[]
outputMetadata: OrtValueMetadata[]
loadMs: number
}
export interface OrtRunTimings {
/** Time spent inside `InferenceSession.run`. */
inferenceMs: number
/** Time spent materializing and copying outputs to transferable CPU buffers. */
readbackMs: number
totalMs: number
}
export interface OrtRunSessionResult {
sessionId: string
outputs: TensorPayloadMap
timings: OrtRunTimings
}
export interface OrtDisposeSessionResult {
sessionId: string
disposed: boolean
}
export interface OrtDisposeAllResult {
disposedSessionIds: string[]
}
export interface OrtWorkerRequestPayloadMap {
'configure-runtime': OrtRuntimeConfiguration
'load-session': OrtLoadSessionRequest
'run-session': OrtRunSessionRequest
'dispose-session': { sessionId: string }
'dispose-all': Record<string, never>
}
export interface OrtWorkerResultMap {
'configure-runtime': OrtConfigureRuntimeResult
'load-session': OrtLoadSessionResult
'run-session': OrtRunSessionResult
'dispose-session': OrtDisposeSessionResult
'dispose-all': OrtDisposeAllResult
}
export type OrtWorkerOperation = keyof OrtWorkerRequestPayloadMap
export type OrtWorkerRequest = {
[Operation in OrtWorkerOperation]: {
type: Operation
requestId: string
payload: OrtWorkerRequestPayloadMap[Operation]
}
}[OrtWorkerOperation]
export interface SerializedWorkerError {
name: string
message: string
stack?: string
}
export type OrtWorkerReply = {
[Operation in OrtWorkerOperation]:
| {
type: 'reply'
operation: Operation
requestId: string
ok: true
result: OrtWorkerResultMap[Operation]
}
| {
type: 'reply'
operation: Operation
requestId: string
ok: false
error: SerializedWorkerError
}
}[OrtWorkerOperation]
export type OrtWorkerStage =
| 'runtime-configuring'
| 'runtime-ready'
| 'session-loading'
| 'session-fallback'
| 'session-ready'
| 'inference-queued'
| 'inference-running'
| 'outputs-reading'
| 'inference-complete'
| 'session-disposing'
| 'session-disposed'
| 'worker-disposing'
| 'worker-disposed'
export interface OrtWorkerStatus {
type: 'status'
stage: OrtWorkerStage
message: string
timestampMs: number
requestId?: string
sessionId?: string
executionProvider?: OrtExecutionProvider
/** Normalized progress within this stage, when meaningful. */
progress?: number
}
export type OrtWorkerMessage = OrtWorkerReply | OrtWorkerStatus
export interface OrtWorkerClientOptions {
onStatus?: (status: OrtWorkerStatus) => void
/** Configure ORT before the first model is loaded. Worker defaults are used when omitted. */
runtime?: OrtRuntimeConfiguration
/** Base used to resolve relative graph and external-data URLs before posting. */
baseUrl?: string | URL
/** Test/embed hook. The default creates the generic module worker. */
workerFactory?: () => Worker
}
interface PendingRequest {
operation: OrtWorkerOperation
resolve: (value: unknown) => void
reject: (error: Error) => void
}
function requestId(): string {
return typeof crypto !== 'undefined' && 'randomUUID' in crypto
? crypto.randomUUID()
: `${Date.now()}-${Math.random().toString(16).slice(2)}`
}
function defaultBaseUrl(): string {
if (typeof document !== 'undefined' && document.baseURI) {
return document.baseURI
}
if (typeof location !== 'undefined') {
return location.href
}
throw new Error('OrtWorkerClient needs an explicit baseUrl outside a browser document.')
}
function assertSessionId(sessionId: unknown): asserts sessionId is string {
if (typeof sessionId !== 'string' || sessionId.trim().length === 0 || sessionId.includes('\0')) {
throw new TypeError('sessionId must be a non-empty string without null characters.')
}
}
function deserializeError(error: SerializedWorkerError): Error {
const result = new Error(error.message)
result.name = error.name
if (error.stack) {
result.stack = error.stack
}
return result
}
function isWorkerMessage(value: unknown): value is OrtWorkerMessage {
if (typeof value !== 'object' || value === null || !('type' in value)) {
return false
}
const type = (value as { type?: unknown }).type
return type === 'status' || type === 'reply'
}
/** Correlated, typed facade over the generic multi-session ONNX worker. */
export class OrtWorkerClient {
private readonly worker: Worker
private readonly baseUrl: string
private readonly pending = new Map<string, PendingRequest>()
private onStatus?: (status: OrtWorkerStatus) => void
private ready: Promise<unknown> = Promise.resolve()
private fatalError?: Error
private disposePromise?: Promise<void>
constructor(options: OrtWorkerClientOptions = {}) {
this.baseUrl = new URL(options.baseUrl ?? defaultBaseUrl()).href
this.onStatus = options.onStatus
this.worker = options.workerFactory?.() ?? new Worker(new URL('../workers/onnxWorker.ts', import.meta.url), {
type: 'module',
name: 'onnx-runtime-webgpu',
})
this.worker.onmessage = (event: MessageEvent<unknown>) => {
this.handleMessage(event.data)
}
this.worker.onerror = (event: ErrorEvent) => {
const cause = event.error instanceof Error ? event.error.message : undefined
const location = event.filename
? `${event.filename}${event.lineno ? `:${event.lineno}${event.colno ? `:${event.colno}` : ''}` : ''}`
: undefined
const details = [event.message, cause, location].filter((value): value is string => Boolean(value))
this.fail(new Error(details.length > 0 ? `ONNX worker error: ${details.join(' · ')}` : 'ONNX worker error.'))
}
this.worker.onmessageerror = () => {
this.fail(new Error('Could not deserialize a message from the ONNX worker.'))
}
if (options.runtime) {
this.ready = this.sendRequest('configure-runtime', options.runtime)
// Avoid an unhandled-rejection report before the first public call awaits readiness.
void this.ready.catch(() => undefined)
}
}
setStatusHandler(handler?: (status: OrtWorkerStatus) => void): void {
this.onStatus = handler
}
async configureRuntime(configuration: OrtRuntimeConfiguration): Promise<OrtConfigureRuntimeResult> {
await this.ready
const configuring = this.sendRequest('configure-runtime', configuration)
this.ready = configuring
return configuring
}
async loadSession(request: OrtLoadSessionRequest): Promise<OrtLoadSessionResult> {
assertSessionId(request.sessionId)
const manifest = resolveModelManifest(copyModelManifest(request.manifest), this.baseUrl)
await this.ready
return this.sendRequest('load-session', {
sessionId: request.sessionId,
manifest,
options: request.options,
})
}
async runSession(
request: OrtRunSessionRequest,
options: OrtRunClientOptions = {},
): Promise<OrtRunSessionResult> {
assertSessionId(request.sessionId)
assertTensorPayloadMap(request.inputs, 'request.inputs')
if (request.outputs !== undefined) {
const seen = new Set<string>()
for (const output of request.outputs) {
if (typeof output !== 'string' || output.trim().length === 0 || seen.has(output)) {
throw new TypeError('Requested output names must be unique, non-empty strings.')
}
seen.add(output)
}
}
await this.ready
const transfer = options.transferInputs === false ? [] : tensorPayloadTransferables(request.inputs)
return this.sendRequest('run-session', request, transfer)
}
async disposeSession(sessionId: string): Promise<OrtDisposeSessionResult> {
assertSessionId(sessionId)
await this.ready
return this.sendRequest('dispose-session', { sessionId })
}
async disposeAllSessions(): Promise<OrtDisposeAllResult> {
await this.ready
return this.sendRequest('dispose-all', {})
}
/** Release every ORT session, acknowledge disposal, and then terminate the worker. */
dispose(): Promise<void> {
if (this.disposePromise) {
return this.disposePromise
}
this.disposePromise = (async () => {
try {
await this.ready
if (!this.fatalError) {
await this.sendRequest('dispose-all', {}, [], true)
}
} finally {
this.worker.terminate()
this.rejectAll(new Error('ONNX worker client disposed.'))
}
})()
return this.disposePromise
}
private sendRequest<Operation extends OrtWorkerOperation>(
operation: Operation,
payload: OrtWorkerRequestPayloadMap[Operation],
transfer: Transferable[] = [],
allowDuringDispose = false,
): Promise<OrtWorkerResultMap[Operation]> {
if (this.fatalError) {
return Promise.reject(this.fatalError)
}
if (this.disposePromise && !allowDuringDispose) {
return Promise.reject(new Error('ONNX worker client is disposing or disposed.'))
}
const id = requestId()
const promise = new Promise<OrtWorkerResultMap[Operation]>((resolve, reject) => {
this.pending.set(id, {
operation,
resolve: resolve as (value: unknown) => void,
reject,
})
})
const message: OrtWorkerRequest = { type: operation, requestId: id, payload } as OrtWorkerRequest
try {
this.worker.postMessage(message, transfer)
} catch (error) {
this.pending.delete(id)
const typedError = error instanceof Error ? error : new Error(String(error))
return Promise.reject(typedError)
}
return promise
}
private handleMessage(value: unknown): void {
if (!isWorkerMessage(value)) {
this.fail(new Error('Received a malformed message from the ONNX worker.'))
return
}
if (value.type === 'status') {
this.onStatus?.(value)
return
}
const pending = this.pending.get(value.requestId)
if (!pending) {
return
}
this.pending.delete(value.requestId)
if (pending.operation !== value.operation) {
pending.reject(
new Error(`ONNX worker replied to '${pending.operation}' with mismatched operation '${value.operation}'.`),
)
return
}
if (value.ok) {
pending.resolve(value.result)
} else {
pending.reject(deserializeError(value.error))
}
}
private fail(error: Error): void {
if (this.fatalError) {
return
}
this.fatalError = error
this.worker.terminate()
this.rejectAll(error)
}
private rejectAll(error: Error): void {
for (const pending of this.pending.values()) {
pending.reject(error)
}
this.pending.clear()
}
}
|