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

Most upvoted comments

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:

@ChTiSh https://github.com/ChTiSh

I can confirm Web GPU is working for my little chrome extension app as well, but I’m having a problem disabling the warning.

You can numb it using a brittle monkey patch…

const originalConsole = self.console; self.console.error = () => {} const sessionwebGpu = await ONNX_WEBGPU.InferenceSession.create(buffer, { executionProviders: [“webgpu”],});console.log(“Loading embedding model using sessionwebGpu”, sessionwebGpu); self.console.error = originalConsole.error;

— Reply to this email directly, view it on GitHub https://github.com/microsoft/onnxruntime/issues/20876#issuecomment-2214167629, or unsubscribe https://github.com/notifications/unsubscribe-auth/AWQJC525QV2VY4WC2636BI3ZLKL3XAVCNFSM6AAAAABIRY45QKVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDEMJUGE3DONRSHE . You are receiving this because you were mentioned.Message ID: @.***>

@fs-eire I can verify that using 1.19.0-dev.20240621-69d522f4e9 loading a model using webgpu in a service worker works - even in a web extension. The necessary code is:

import * as ONNX_WEBGPU from "onnxruntime-web/webgpu";

// any Blob that contains a valid ORT model would work
// I'm using Xenova/multilingual-e5-small/onnx/model_quantized.with_runtime_opt.ort
const buffer = await mlModel.blob.arrayBuffer();  
  
const sessionwebGpu = await ONNX_WEBGPU.InferenceSession.create(buffer, {
  executionProviders: ["webgpu"],
});
console.log("Loading embedding model using sessionwebGpu", sessionwebGpu);

Results in a successful execution, yay! 💯 😃

Bildschirmfoto 2024-07-06 um 19 41 18

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 Blob or ArrayBuffer doesn’t mean you can’t get such data transferred into the Service Worker context. In fact, you can transfer Gigabytes instantly using MessageChannel and the concept of Transferable objects.

Passing down a Blob/ArrayBuffer from 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-2211770512

It’s even much simpler for non-Web-Extension use cases as you simply only use the self.onmessage API in a service worker to receive a MessageChannel object and via a port of it, receive the Blob or ArrayBuffer.

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…

  1. The Emscripten runtime code can be imported in userland code like this:
import ortWasmRuntime from "onnxruntime-web/dist/ort-wasm-simd-threaded"

As the node_modules show: Bildschirmfoto 2024-07-06 um 22 08 17

The runtime exports a default runtime function: Bildschirmfoto 2024-07-06 um 21 59 28

  1. You can easily override the default Emscripten WASM binary module loader by a custom Emscripten WASM module loader, that allows for an ArrayBuffer to be passed by reference:
Module['instantiateWasm'] = async(imports, onSuccess) => {
  let result;
  if (WebAssembly.instantiateStreaming) {
    result = WebAssembly.instantiateStreaming(Module["wasmModule"], imports);
  } else {
    result = await WebAssembly.instantiate(Module["wasmModule"], imports)
  }
  return onSuccess(result.instance, result.module)
};

Of course, we don’t want it that way, but I mention it as this is the “documented way”.

  1. But as you know, you can also set 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:
{
    numThreads,
    // just conditionally merge in:
    instantiateWasm: ONNX_WASM.env.wasm.instantiateWasm
}
  1. A proposal on how WASM could work as a PoC in service workers (and web extensions):
import * as ONNX_WASM from "onnxruntime-web/wasm";

// the difference is, that this will be bundled in by the user-land bundler, 
// while the conditional dynamic import that happens in the  ONNX runtime would not 
// as the trenary operator here: https://github.com/microsoft/onnxruntime/blob/83e0c6b96e77634dd648e890cead598b6e065cde/js/web/lib/wasm/wasm-utils-import.ts#L157 
// and all it's following code cannot be statically analyzed by bundlers; tree-shaking and inline cannot happen,
// so bundler will be forced to generate dynamic import() code
// this could also lead to downstream issues with the transformersjs package and other packages / bundler combinations,
// while this is explicit and inlined
import ortWasmRuntime from "onnxruntime-web/dist/ort-wasm-simd-threaded"

// could maybe be passed a Blob via https://emscripten.org/docs/api_reference/module.html#Module.mainScriptUrlOrBlob
ONNX_WASM.env.wasm.proxy = false;

// instead of always calling importWasmModule() in wasm-factory.ts, allow to pass down the callback of the Emscripten JS runtime
ONNX_WASM.env.wasm.wasmRuntime = ortWasmRuntime;

// allow to also set a custom Emscripten loader
ONNX_WASM.env.wasm.instantiateWasm = async(imports, onSuccess) => {
  let result;
  if (WebAssembly.instantiateStreaming) {
    // please note that wasmRuntimeBlob comes from user-land code. It may be passed via a MessageChannel
    result = WebAssembly.instantiateStreaming(await wasmRuntimeBlob.arrayBuffer(), imports);
  } else {
    // please note that wasmRuntimeBlob comes from user-land code. It may be passed via a MessageChannel
    result = await WebAssembly.instantiate(await wasmRuntimeBlob.arrayBuffer(), imports)
  }
  return onSuccess(result.instance, result.module)
}

// then continuing as usual
// please note that mlModel comes from user-land code. It may have been passed via a MessageChannel
const modelBuffer = await mlModel.blob.arrayBuffer();
const sessionWasm = await ONNX_WASM.InferenceSession.create(buffer, {
  executionProviders: ["wasm"],
});
console.log("Loading embedding model using sessionWasm", sessionWasm);

So with a 1 LoC change (using passed down runtime callback) here, and 1 LoC change here, (add the instantiateWasm callback 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:

import * as ONNX_WASM from "onnxruntime-web/wasm";

const sessionWasm = await ONNX_WASM.InferenceSession.create(buffer, {
  executionProviders: ["wasm"],
});
console.log("Loading embedding model using sessionWasm", sessionWasm);

Result: Bildschirmfoto 2024-07-06 um 19 57 46

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!

demo

1.19.0-dev.20240801-4b8f6dcbb6 includes the change.

I created #21534, which is a replacement of #21430:

  • exposing the instantiateWasm directly 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.
  • the import() is disallowed ... error is already fixed after version 1.19.0-dev.20240621-69d522f4e9. (only work for ESM. UMD will not work)
  • with this fix in ort-web, a few things are no longer need:
    • hacks on package.json and bundle
    • the top-level await is already taking care of by the build script of ort-web.

@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.js abstraction layer in between:

350204823-86f101f4-5213-4b5a-bc94-4c6bbcce047b

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-web dependencies using package overrides

@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 😃

Hey, I also need this. I am struggling with importing this version. So far I have been importing ONNX using import * as ort from "https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/esm/ort.webgpu.min.js". However, when I change to import * as ort from "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.19.0-dev.20240621-69d522f4e9/dist/esm/ort.webgpu.min.js" it seems not to have an .../esm/ folder. Do you know why that is and how to import it then?

just replace .../esm/ort.webgpu.min.js to .../ort.webgpu.min.mjs should work. If you are also using service worker, use ort.webgpu.bundle.min.mjs instead of ort.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.

Thanks for looking into it ! I think this is what I will end up doing but I am wondering if webpack could have used the correct loader if emscripten generated a slightly different code to locate the wasm file without the case that relies on URL.

That could maybe be solved by generating a worker compatible only JS file through emscripten using the flag ENVIRONMENT="worker" ? (I am building from source using the doc so I have control over the args passed to emscripten at that stage)

I will give it a try and let you know !

edit: I tried adding --emscripten_settings ENVIRONMENT="worker" to the build wasm command and faced new issues in the esbuild compilation afterwards regarding Unexpected number of matches for minified "PThread.pthreads[thread].ref()" - I’m stopping trying to do it this way in favor of the webpack config way.

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 backend error in chrome extension background script?

I have a follow-up issue that I struggle to understand: when using onnxruntime-web in a mv3 extension service-worker bundled with webpack.

The symptoms are that the service worker will crash right away with this error:

Uncaught ReferenceError: document is not defined

...

/******/ 	/* webpack/runtime/jsonp chunk loading */
/******/ 	(() => {
/******/ 		__webpack_require__.b = document.baseURI || self.location.href;

Here is a small reproduction sandbox: https://codesandbox.io/p/devbox/cocky-hamilton-5m398f

(Download the dist folder to try it out in a web browser where you can load unpacked extensions - I tested in Chrome & firefox)

There is a way to make it work using output.chunkLoading = false in the webpack configuration but this is not ideal. Could it be related to loading wasm with webpack: https://stackoverflow.com/a/71673305 ?

I am not sure if this requires a dedicated issue or if it’s okay to follow up in this one, let me know @fs-eire

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:

 module.exports = {
   mode: "development",
   devtool: false,
+  target: 'webworker',
   entry: {

Then I can see another error, which is expected (because the model is an invalid dummy file):

[Background] Error loading ONNX model or running inference: Can't create a session. ERROR_CODE: 7, ERROR_MESSAGE: Failed to load model because protobuf parsing failed

👋 Thank you @fs-eire ! I tried using 1.19.0-dev.20240801-4b8f6dcbb6 inside of a chrome mv3 extension and it worked right away with the webgpu backend, however I’m more interested in using the wasm backend for running a simple decision forest as it doesn’t include jsep and makes the overall bundle 10MB lighter. I wondered if there were any plans to support it too in a near future ?

Doesn’t it work if by just replacing import "onnxruntime-web/webgpu" to import "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:

Error:   Failed to scan for dependencies from entries:
  /Users/focus/Projects/---/webgpu-sam2/frontend/src/routes/+page.svelte

  ✘ [ERROR] Missing "./webgpu/index.js" specifier in "onnxruntime-web" package [plugin vite:dep-scan]

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

3:34:51 PM [vite] Error when evaluating SSR module /src/encoder.svelte: failed to import "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.20.0-dev.20240810-6ae7e02d34/dist/ort.webgpu.min.js"
|- Error [ERR_UNSUPPORTED_ESM_URL_SCHEME]: Only URLs with a scheme in: file, data, and node are supported by the default ESM loader. 

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:

Error: no available backend found. ERR: [webgpu] TypeError: Failed to fetch dynamically imported module: http://localhost:5173/src/ort-wasm-simd-threaded.jsep.mjs

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" package

Anyone 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.instantiateWasm addition?

I would like to try your workaround since I am stuck in a similar spot (.wasm needs to be imported in userland code)

@ChTiSh

I can confirm Web GPU is working for my little chrome extension app as well, but I’m having a problem disabling the warning.

You can numb it using a brittle monkey patch…

// store original reference
const originalConsole = self.console;

// override function reference with a new arrow function that does nothing
self.console.error = () => {}

// code will internally call the function that does nothing...
const sessionwebGpu = await ONNX_WEBGPU.InferenceSession.create(buffer, {
  executionProviders: ["webgpu"],
});

// still works, we did only replace the reference for the .error() function
console.log("Loading embedding model using sessionwebGpu", sessionwebGpu);

// restore the original function reference, so that console.error() works just as before
self.console.error = originalConsole.error;

But I agree… it should probably be a console.warning() call if it is intended to be a warning