/** * Module code will be copied into worker. * * Messages between main <==> worker: * * From main thread to worker: * - Send direction: { verb, args, callbackId } * - Result direction: { callbackId, result } or { callbackId, err } * * Signal from worker to main: * - Unidirection: { verb, args } */ import { glueDeserialize, glueSerialize } from './glue/glue'; import type { GlueMsg } from './glue/messages'; import { canUseAsyncFileRead, createWorker, isSafariMobile, isString, } from './utils'; import { LLAMA_CPP_WORKER_CODE, WEBGPU_POLL_PATCH_CODE, RPC_TRANSPORT_WORKER_CODE, } from './workers-code/generated'; import { WllamaError, WllamaRuntimeError } from './wllama'; import { getOPFSPath } from './storage/opfs'; interface Logger { debug: typeof console.debug; log: typeof console.log; warn: typeof console.warn; error: typeof console.error; } const FILE_READ_REQ_EVENT = 'fs.read_req'; // wasm custom section with the emscripten JS glue, see scripts/pack_wasm.js const WASM_JS_SECTION_NAME = 'wllama_js'; export interface RpcInitOptions { env: Record; channels: { port: number; sab: SharedArrayBuffer; role: 'client' | 'server'; }[]; } interface TaskParam { verb: | 'module.init' | 'fs.alloc' | 'fs.write' | 'fs.read_res' | 'wllama.start' | 'wllama.action' | 'wllama.exit' | 'wllama.debug' | 'rpc.serve'; args: any[]; callbackId: number; } interface Task { resolve: any; reject: any; param: TaskParam; buffers?: ArrayBuffer[] | undefined; } const JSPI_STUB = ` if (!WebAssembly.Suspending) { // JSPI not available - stubs that keep the import/export tables valid. // Suspending wraps imports: identity is fine since async imports won't be called. WebAssembly.Suspending = function (fn) { // console.log(fn.toString()); return fn; }; // promising wraps exports: must return a Promise so ccall's ret.then() works. WebAssembly.promising = function (fn) { return function (...args) { try { return Promise.resolve(fn(...args)); } catch (e) { return Promise.reject(e); } }; }; } `; export interface WllamaWorkerResources { wasmPath: string; // if jsPath is not provided, use the JS code embedded inside the wasm file jsPath?: string | { code: string } | undefined; compat: boolean; // skip WebGPU device initialization entirely (e.g. when n_gpu_layers is 0) noWebGPU?: boolean; } export class ProxyToWorker { resources: WllamaWorkerResources; logger: Logger; suppressNativeLog: boolean; taskQueue: Task[] = []; taskId: number = 1; resultQueue: Task[] = []; busy = false; // is the work loop is running? private exited = false; private exitCtrl = new AbortController(); // cancel fetches of moduleInit on exit worker?: Worker | undefined; multiThread: boolean; nbThread: number; useAsyncFile: boolean; fileBlobs: Map = new Map(); // filename -> Blob for async reads constructor( resources: WllamaWorkerResources, nbThread: number, suppressNativeLog: boolean, logger: Logger ) { this.resources = resources; this.nbThread = nbThread; this.multiThread = nbThread > 0; this.logger = logger; this.suppressNativeLog = suppressNativeLog; this.useAsyncFile = canUseAsyncFileRead(resources.compat); } // the compiled module is sent to the worker, emscripten uses it via Module.instantiateWasm async compileWasm(): Promise { const url = this.resources.wasmPath; const fetchWasm = () => fetch(url, { credentials: 'same-origin', signal: this.exitCtrl.signal }); if (typeof WebAssembly.compileStreaming === 'function') { try { return await WebAssembly.compileStreaming(fetchWasm()); } catch (e) { this.throwIfExited(); // streaming requires the server to send "Content-Type: application/wasm" this.logger.warn( `wasm streaming compile failed: ${e}; falling back to ArrayBuffer instantiation` ); } } const response = await fetchWasm(); if (!response.ok) { throw new Error(`Failed to fetch wasm from ${url}`); } return await WebAssembly.compile(await response.arrayBuffer()); } async getModuleCode(wasmModule: WebAssembly.Module): Promise { let code: string; if (!this.resources.jsPath) { return this.getEmbeddedModuleCode(wasmModule); } else if ((this.resources.jsPath as { code: string }).code) { code = (this.resources.jsPath as { code: string }).code; } else if (isString(this.resources.jsPath)) { const response = await fetch(this.resources.jsPath as string, { signal: this.exitCtrl.signal, }); if (!response.ok) { throw new Error( `Failed to fetch worker code from ${this.resources.jsPath}` ); } code = await response.text(); } else { throw new Error('No JS code provided for worker'); } // new wllama.js is only a placeholder comment, see https://github.com/ngxson/wllama/pull/327 if (!code.includes('var Module')) { this.logger.warn( 'The worker JS has no emscripten code, using the JS embedded in the wasm file. The "worker" option of setCompat() is no longer needed.' ); return this.getEmbeddedModuleCode(wasmModule); } return code; } getEmbeddedModuleCode(wasmModule: WebAssembly.Module): string { const sections = WebAssembly.Module.customSections( wasmModule, WASM_JS_SECTION_NAME ); if (sections.length === 0) { throw new Error( `The wasm file "${this.resources.wasmPath}" does not contain the JS code ("${WASM_JS_SECTION_NAME}" section). ` + 'Make sure the wasm file comes from the same version of wllama.' ); } return new TextDecoder().decode(sections[0]); } private throwIfExited() { if (this.exited) { throw new WllamaError('The model was unloaded', 'model_not_loaded'); } } // rpc: channels are SharedArrayBuffer rings to the rpc workers, env is set before the wasm starts async moduleInit( ggufFiles: { name: string; blob: Blob }[], rpc?: RpcInitOptions ): Promise { let wasmModule: WebAssembly.Module; let moduleCode: string; try { wasmModule = await this.compileWasm(); moduleCode = JSPI_STUB + (await this.getModuleCode(wasmModule)); } catch (e) { this.throwIfExited(); // fetch was aborted by exit throw e; } this.throwIfExited(); // exit while compiling, do not create the worker if (this.resources.noWebGPU) { // make requestAdapter() resolve to null so ggml-webgpu skips device registration moduleCode = 'try{Object.defineProperty(WorkerNavigator.prototype,"gpu",{get:()=>({requestAdapter:async()=>null})});}catch(e){}' + moduleCode; } let mainModuleCode = moduleCode.replace('var Module', 'var ___Module'); const runOptions = { pathConfig: { 'wllama.wasm': this.resources.wasmPath, }, nbThread: this.nbThread, compat: this.resources.compat, }; const completeCode: string = [ `const RUN_OPTIONS = ${JSON.stringify(runOptions)};`, WEBGPU_POLL_PATCH_CODE, `function wModuleInit() { ${mainModuleCode}; return Module; }`, RPC_TRANSPORT_WORKER_CODE, LLAMA_CPP_WORKER_CODE, ].join(';\n\n'); this.worker = createWorker(completeCode); this.worker.onmessage = this.onRecvMsg.bind(this); this.worker.onerror = this.logger.error; const res = await this.pushTask({ verb: 'module.init', args: [ // pthread workers also need the rpc transport new Blob([RPC_TRANSPORT_WORKER_CODE, ';\n', moduleCode], { type: 'text/javascript', }), this.useAsyncFile, wasmModule, rpc, ], callbackId: this.taskId++, }); // allocate all files const nativeFiles: ({ id: number } & (typeof ggufFiles)[number])[] = []; for (const file of ggufFiles) { const needAllocBuffer = !this.useAsyncFile; // only alloc if mmap is used const id = await this.fileAlloc( file.name, file.blob.size, needAllocBuffer, this.useAsyncFile ? getOPFSPath(file.blob) : undefined ); nativeFiles.push({ id, ...file }); if (this.useAsyncFile) { this.fileBlobs.set(file.name, file.blob); } } // stream files (only used in non async - mmap mode) if (!this.useAsyncFile) { await Promise.all( nativeFiles.map((file) => { return this.fileWrite(file.id, file.blob); }) ); } return res; } async wllamaStart(): Promise { const result = await this.pushTask({ verb: 'wllama.start', args: [], callbackId: this.taskId++, }); const parsedResult = this.parseResult(result); return parsedResult; } async wllamaAction( name: string, body: GlueMsg ): Promise { // console.debug(`wllamaAction: ${name}`, body); const encodedMsg = glueSerialize(body); const result = await this.pushTask({ verb: 'wllama.action', args: [name, encodedMsg], callbackId: this.taskId++, }); const parsedResult = glueDeserialize(result); if (parsedResult._name === 'erro_evt') { throw new WllamaError(parsedResult.message, 'inference_error'); } return parsedResult as T; } async wllamaExit(): Promise { if (this.worker) { // we don't actually need to send exit // terminating the worker is faster and resources will be cleaned up by the browser // const result = await this.pushTask({ // verb: 'wllama.exit', // args: [], // callbackId: this.taskId++, // }); // this.parseResult(result); // only check for exceptions this.worker.terminate(); } // nothing answers anymore, so fail the actions that wait and the next ones this.exited = true; this.exitCtrl.abort(); this.rejectAll( new WllamaError('The model was unloaded', 'model_not_loaded') ); } // rpc worker: serves its CPU backend on this channel until it is terminated async rpcServe(port: number, nThreads: number): Promise { await this.pushTask({ verb: 'rpc.serve', args: [port, nThreads], callbackId: this.taskId++, }); } async wllamaDebug(): Promise { const result = await this.pushTask({ verb: 'wllama.debug', args: [], callbackId: this.taskId++, }); return JSON.parse(result); } /////////////////////////////////////// /** * Allocate a new file in heapfs * @returns fileId, to be used by fileWrite() */ private async fileAlloc( fileName: string, size: number, allocBuffer: boolean, opfsPath?: string[] ): Promise { const result = await this.pushTask({ verb: 'fs.alloc', args: [fileName, size, allocBuffer, opfsPath], callbackId: this.taskId++, }); return result.fileId; } /** * Write a Blob to heapfs */ private async fileWrite(fileId: number, blob: Blob): Promise { const reader = blob.stream().getReader(); let offset = 0; while (true) { const { done, value } = await reader.read(); if (done) break; const size = value.byteLength; await this.pushTask( { verb: 'fs.write', args: [fileId, value, offset], callbackId: this.taskId++, }, // @ts-ignore Type 'ArrayBufferLike' is not assignable to type 'ArrayBuffer' [value.buffer] ); offset += size; } } private async fileReadResponse( name: string, offset: number, size: number ): Promise { try { const blob = this.fileBlobs.get(name); if (!blob) { throw new Error(`blob not found for name="${name}"`); } const chunk = blob.slice(offset, offset + size); const buffer = await chunk.arrayBuffer(); this.worker!!.postMessage( { verb: 'fs.read_res', args: [buffer] }, { transfer: [buffer] } ); } catch (err) { this.logger.error('fileReadResponse failed, terminating worker:', err); this.worker?.terminate(); this.worker = undefined; this.abort(`File read failed: ${err}`, (err as Error).stack || ''); } } /** * Parse JSON result returned by cpp code. * Throw new Error if "__exception" is present in the response * * TODO: get rid of this function once everything is migrated to Glue */ private parseResult(result: any): any { const parsedResult = JSON.parse(result); if (parsedResult && parsedResult['error']) { throw new WllamaRuntimeError('Unknown error, please see console.log', ''); } return parsedResult; } /** * Push a new task to taskQueue */ private pushTask(param: TaskParam, buffers?: ArrayBuffer[]) { return new Promise((resolve, reject) => { if (this.exited) { reject(new WllamaError('The model was unloaded', 'model_not_loaded')); return; } this.taskQueue.push({ resolve, reject, param, buffers }); this.runTaskLoop(); }); } /** * Main loop for processing tasks */ private async runTaskLoop() { if (this.busy) { return; // another loop is already running } this.busy = true; while (true) { const task = this.taskQueue.shift(); if (!task) break; // no more tasks this.resultQueue.push(task); // TODO @ngxson : Safari mobile doesn't support transferable ArrayBuffer this.worker!!.postMessage( task.param, isSafariMobile() ? undefined : { transfer: task.buffers ?? [], } ); } this.busy = false; } /** * Handle messages from worker */ private onRecvMsg(e: MessageEvent) { if (!e.data) return; // ignore const { verb, args } = e.data; if (verb && verb.startsWith('console.')) { if (this.suppressNativeLog) { return; } if (verb.endsWith('debug')) this.logger.debug(...args); if (verb.endsWith('log')) this.logger.log(...args); if (verb.endsWith('warn')) this.logger.warn(...args); if (verb.endsWith('error')) this.logger.error(...args); return; } else if (verb === 'signal.abort') { const [signalType, message, rawStack, originalErr] = args as [ string, string, string, any, ]; if (originalErr) { this.logger.error(originalErr); } let stack = ''; let newMsg = String(message).replace( 'Build with -sASSERTIONS for more info.', '' ); if (signalType === 'abort') { newMsg = `(ABORT) ${newMsg}`; stack = rawStack.replace(/\|/g, '\n'); } else if (signalType === 'exception') { stack = rawStack; } this.logger.error(`Stack trace (${signalType}):\n` + stack); this.abort(newMsg, stack); return; } // handle fs.read_req signal from wasm (JSPI-suspended worker) if (verb === FILE_READ_REQ_EVENT) { const [name, offset, size] = args as [string, number, number]; this.fileReadResponse(name, offset, size).catch(() => {}); // errors handled inside return; } // handle task result const { callbackId, result, err } = e.data; if (callbackId) { const idx = this.resultQueue.findIndex( (t) => t.param.callbackId === callbackId ); if (idx !== -1) { const waitingTask = this.resultQueue.splice(idx, 1)[0]; if (err) waitingTask.reject(err); else waitingTask.resolve(result); } else { this.logger.error( `Cannot find waiting task with callbackId = ${callbackId}` ); } } } private abort(text: string, stack: string) { this.rejectAll( new WllamaRuntimeError(text.length == 0 ? '(unknown error)' : text, stack) ); } private rejectAll(error: Error) { while (this.resultQueue.length > 0) { const waitingTask = this.resultQueue.pop(); if (!waitingTask) break; waitingTask.reject(error); } while (this.taskQueue.length > 0) { const pendingTask = this.taskQueue.pop(); if (!pendingTask) break; pendingTask.reject(error); } } }