onnxruntime: [Web] WebGPU and WASM Backends Unavailable within Service Worker
Describe the issue
I’m running into issues trying to use the WebGPU or WASM backends inside of a ServiceWorker (on a chrome extension). More specifically, I’m attempting to use Phi-3 with transformers.js v3
Every time I attempt this, I get the following error:
Uncaught (in promise) Error: no available backend found. ERR: [webgpu]
TypeError: import() is disallowed on ServiceWorkerGlobalScope by the HTML specification.
See https://github.com/w3c/ServiceWorker/issues/1356.
This is originating in the InferenceSession class in js/common/lib/inference-session-impl.ts.
More specifically, it’s happening in this method:
const [backend, optionsWithValidatedEPs] = await resolveBackendAndExecutionProviders(options);
where the implementation is in js/common/lib/backend-impl.ts and the tryResolveAndInitializeBackend fails to initialize any of the execution providers.
WebGPU is now supported in ServiceWorkers though; it is a recent change and it should be feasible. Here were the chrome release notes.
Additionally, here is an example browser extension from the mlc-ai/web-llm framework that implements WebGPU usage in service workers successfully: https://github.com/mlc-ai/web-llm/tree/main/examples/chrome-extension-webgpu-service-worker
Here is some further discussion on this new support from Google itself: https://groups.google.com/a/chromium.org/g/chromium-extensions/c/ZEcSLsjCw84/m/WkQa5LAHAQAJ
So technically I think it should be possible for this to be supported now? Unless I’m doing something else glaringly wrong. Is it possible to add support for this?
To reproduce
Download and set up the transformers.js extension example and put this into the background.js file:
// background.js - Handles requests from the UI, runs the model, then sends back a response
import {
pipeline,
env,
AutoModelForCausalLM,
AutoTokenizer,
TextStreamer,
StoppingCriteria,
} from "@xenova/transformers";
// Skip initial check for local models, since we are not loading any local models.
env.allowLocalModels = false;
// Due to a bug in onnxruntime-web, we must disable multithreading for now.
// See https://github.com/microsoft/onnxruntime/issues/14445 for more information.
env.backends.onnx.wasm.numThreads = 1;
class CallbackTextStreamer extends TextStreamer {
constructor(tokenizer, cb) {
super(tokenizer, {
skip_prompt: true,
skip_special_tokens: true,
});
this.cb = cb;
}
on_finalized_text(text) {
this.cb(text);
}
}
class InterruptableStoppingCriteria extends StoppingCriteria {
constructor() {
super();
this.interrupted = false;
}
interrupt() {
this.interrupted = true;
}
reset() {
this.interrupted = false;
}
_call(input_ids, scores) {
return new Array(input_ids.length).fill(this.interrupted);
}
}
const stopping_criteria = new InterruptableStoppingCriteria();
async function hasFp16() {
try {
const adapter = await navigator.gpu.requestAdapter();
return adapter.features.has("shader-f16");
} catch (e) {
return false;
}
}
class PipelineSingleton {
static task = "feature-extraction";
static model_id = "Xenova/Phi-3-mini-4k-instruct_fp16";
static model = null;
static instance = null;
static async getInstance(progress_callback = null) {
this.model_id ??= (await hasFp16())
? "Xenova/Phi-3-mini-4k-instruct_fp16"
: "Xenova/Phi-3-mini-4k-instruct";
this.tokenizer ??= AutoTokenizer.from_pretrained(this.model_id, {
legacy: true,
progress_callback,
});
this.model ??= AutoModelForCausalLM.from_pretrained(this.model_id, {
dtype: "q4",
device: "webgpu",
use_external_data_format: true,
progress_callback,
});
return Promise.all([this.tokenizer, this.model]);
}
}
// Create generic classify function, which will be reused for the different types of events.
const classify = async (text) => {
// Get the pipeline instance. This will load and build the model when run for the first time.
const [tokenizer, model] = await PipelineSingleton.getInstance((data) => {
// You can track the progress of the pipeline creation here.
// e.g., you can send `data` back to the UI to indicate a progress bar
console.log("progress", data);
// data logs as this:
/**
*
* {
"status": "progress",
"name": "Xenova/Phi-3-mini-4k-instruct_fp16",
"file": "onnx/model_q4.onnx",
"progress": 99.80381792394503,
"loaded": 836435968,
"total": 838080131
}
when complete, last status will be 'done'
*/
});
/////////////
const inputs = tokenizer.apply_chat_template(text, {
add_generation_prompt: true,
return_dict: true,
});
let startTime;
let numTokens = 0;
const cb = (output) => {
startTime ??= performance.now();
let tps;
if (numTokens++ > 0) {
tps = (numTokens / (performance.now() - startTime)) * 1000;
}
self.postMessage({
status: "update",
output,
tps,
numTokens,
});
};
const streamer = new CallbackTextStreamer(tokenizer, cb);
// Tell the main thread we are starting
self.postMessage({ status: "start" });
const outputs = await model.generate({
...inputs,
max_new_tokens: 512,
streamer,
stopping_criteria,
});
const outputText = tokenizer.batch_decode(outputs, {
skip_special_tokens: false,
});
// Send the output back to the main thread
self.postMessage({
status: "complete",
output: outputText,
});
///////////////
// Actually run the model on the input text
// let result = await model(text);
// return result;
};
////////////////////// 1. Context Menus //////////////////////
//
// Add a listener to create the initial context menu items,
// context menu items only need to be created at runtime.onInstalled
chrome.runtime.onInstalled.addListener(function () {
// Register a context menu item that will only show up for selection text.
chrome.contextMenus.create({
id: "classify-selection",
title: 'Classify "%s"',
contexts: ["selection"],
});
});
// Perform inference when the user clicks a context menu
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
// Ignore context menu clicks that are not for classifications (or when there is no input)
if (info.menuItemId !== "classify-selection" || !info.selectionText) return;
// Perform classification on the selected text
let result = await classify(info.selectionText);
// Do something with the result
chrome.scripting.executeScript({
target: { tabId: tab.id }, // Run in the tab that the user clicked in
args: [result], // The arguments to pass to the function
function: (result) => {
// The function to run
// NOTE: This function is run in the context of the web page, meaning that `document` is available.
console.log("result", result);
console.log("document", document);
},
});
});
//////////////////////////////////////////////////////////////
////////////////////// 2. Message Events /////////////////////
//
// Listen for messages from the UI, process it, and send the result back.
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
console.log("sender", sender);
if (message.action !== "classify") return; // Ignore messages that are not meant for classification.
// Run model prediction asynchronously
(async function () {
// Perform classification
let result = await classify(message.text);
// Send response back to UI
sendResponse(result);
})();
// return true to indicate we will send a response asynchronously
// see https://stackoverflow.com/a/46628145 for more information
return true;
});
Urgency
this would help enable a new ecosystem to build up around locally intelligent browser extensions and tooling.
it’s urgent for me because it would be fun to build and I want to build it and it would be fun to be building it rather than not be building it.
ONNX Runtime Installation
Built from Source
ONNX Runtime Version or Commit ID
1.19.0-dev.20240509-69cfcba38a
Execution Provider
‘webgpu’ (WebGPU)
About this issue
- Original URL
- State: open
- Created 2 years ago
- Comments: 67 (24 by maintainers)
Commits related to this issue
- [js/web] allow build target for non dynamic import (#20898) ### Description <!-- Describe your changes. --> This PR allows to build ORT web to `ort{.all|.webgpu}.bundle.min.mjs`, which does not ... — committed to microsoft/onnxruntime by fs-eire 2 years ago
- feat: allow WASM modules to be imported via a user-land defined loader function #20876 — committed to kyr0/onnxruntime by kyr0 2 years ago
- [js/web] allow load WebAssembly binary from buffer (#21534) ### Description This PR adds a new option `ort.env.wasm.wasmBinary`, which allows user to set to a buffer containing preload .wasm file... — committed to microsoft/onnxruntime by fs-eire 2 years ago
Thank you so much!!! The whole time I was trying to change the ort log severity, now it’s fast and beautiful!!!
On Mon, Jul 8, 2024 at 7:03 AM Aron Homberg @.***> wrote:
@fs-eire I can verify that using
1.19.0-dev.20240621-69d522f4e9loading a model usingwebgpuin a service worker works - even in a web extension. The necessary code is:Results in a successful execution, yay! 💯 😃
I think we can ignore the warning, printed as an error, as the session loads.
WebAssembly would work in a Service Worker. Just because Service Workers are limited in their ability to load external resources such as WASM runtime files as
BloborArrayBufferdoesn’t mean you can’t get such data transferred into the Service Worker context. In fact, you can transfer Gigabytes instantly usingMessageChanneland the concept of Transferable objects.Passing down a
Blob/ArrayBufferfrom a content script to a background worker/service worker even works, standard-compliant, with Web Extensions, as I demonstrate here: https://github.com/w3c/webextensions/issues/293#issuecomment-2211770512It’s even much simpler for non-Web-Extension use cases as you simply only use the
self.onmessageAPI in a service worker to receive aMessageChannelobject and via aportof it, receive theBloborArrayBuffer.I’m aware that the current implementation hard-codes a few things. Like
importWasmModule()is trying to import the Emscripten runtime JS and by default, Emscripten is trying to import the WASM binary. But this isn’t something that needs to be engraved into stone…As the
node_modulesshow:The runtime exports a default runtime function:
ArrayBufferto be passed by reference:Of course, we don’t want it that way, but I mention it as this is the “documented way”.
Module["$option"]by passing these options as an object to the runtime factory function. In this case, the passed down runtime function, imported by userland code, exactly as you already do here:So with a 1 LoC change (using passed down runtime callback) here, and 1 LoC change here, (add the
instantiateWasmcallback reference), the WebAssembly backend should work as well in Service Workers, if I’m not mistaken in this 4D chess pseudo-code, reverse engineering game.Currently, when I call the WASM implementation:
Result:
Thank you for your help!
(Non-working Vite stuff is now in previous commits because I shipped this!)
If you want to play with it, SAM-2 working totally in WebGPU! Here’s a live demo link and here’s the source, thanks all for the help!
1.19.0-dev.20240801-4b8f6dcbb6 includes the change.
I created #21534, which is a replacement of #21430:
instantiateWasmdirectly may be not a good idea because this requires user to understand details of how WebAssembly works. I think this is unnecessary. To fulfill the requirement, allowing user to set an ArrayBuffer of the .wasm file should be good enough.import() is disallowed ...error is already fixed after version1.19.0-dev.20240621-69d522f4e9. (only work for ESM. UMD will not work)@asadm You’re welcome. No worries, we’ll get this to work just fine, also for you 😃 Here’s an impression from my background worker with the monkey patch applied. It’s working, even through the
@xenova/transformers.jsabstraction layer in between:Might take a while though, until downstream projects will adopt the new version. But once the maintainers here deploy a new version including my PR, we will be able to just override the
onnxruntime-webdependencies using packageoverrides@kyr0 that is amazing! I was also hacking around with unminified bundle (don’t want to rebuild from source etc).
Thank you so much for detailed solution, can’t wait to try this when I get home!
@kyr0 thank you a lot for your willing to help. I am currently in vacation but I will pick up this thread when I am back by end of this month.
@ChTiSh You’re welcome 🫶 Always happy to help 😃
just replace
.../esm/ort.webgpu.min.jsto.../ort.webgpu.min.mjsshould work. If you are also using service worker, useort.webgpu.bundle.min.mjsinstead ofort.webgpu.min.mjs.#20991 makes default ESM import to use non-dynamic-import and hope this change may fix this problem. PR is still in progress
Than you for reporting this issue. I will try to figure out how to fix this problem.
I tried to use Emscripten to build multiple targets (https://github.com/emscripten-core/emscripten/issues/21899), but it turns out difficult to do. Currently the onnxruntime-web build process has a few post-processing to make them working for Web, WebWorker and Node.
It may also be a problem for how to tell the runtime or bundler to import the correct file, giving the predefined “conditions” in the package.json “exports” property do not contain anything that distinguish between web and webworker.
Same problem here, how should I solve the
no available backenderror in chrome extension background script?It looks like that you are using jsonp for chunk loading in webpack. I don’t think this will work in a service worker.
I think the solution is to add
target: 'webworker',like this:Then I can see another error, which is expected (because the model is an invalid dummy file):
Doesn’t it work if by just replacing
import "onnxruntime-web/webgpu"toimport "onnxruntime-web"?Has anyone tried getting these imports working in Vite/other bundlers? When I try the classic:
import * as ONNX_WEBGPU from 'onnxruntime/webgpu(which works in create-react-app), Vite says:
Anyways, I tried importing from url, a la
import { InferenceSession, Tensor as ONNX_TENSOR } from 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.20.0-dev.20240810-6ae7e02d34/dist/ort.webgpu.min.js';which Vite also doesn’t like
I disabled SSR in Svelte but still seemingly no luck/change.
I tried manually downloading the files with CURL, where I got an error about the lack of source map, so, I also downloaded .min.js.map. When I run it now, this works, but I get back to the original error in the thread about unavailable backends:
I figured it might work to just import directly, so I also tried:
import * as ONNX_WEBGPU from 'onnxruntime-web/dist/ort.webgpu.min.mjs';but then I got
4:07:38 PM [vite] Internal server error: Missing "./dist/ort.webgpu.min.mjs" specifier in "onnxruntime-web" packageAnyone have ideas of how to handle? Happy to add more verbose error messages for any of the stuff above.
@kyr0 do you by any chance have a fork that I can try with the custom
env.wasm.instantiateWasmaddition?I would like to try your workaround since I am stuck in a similar spot (.wasm needs to be imported in userland code)
@ChTiSh
You can numb it using a brittle monkey patch…
But I agree… it should probably be a
console.warning()call if it is intended to be a warning