ONNX Runtime Web 入門
目錄
安裝
在 shell 中使用以下命令安裝 ONNX Runtime Web
# install latest release version
npm install onnxruntime-web
# install nightly build dev version
npm install onnxruntime-web@dev
匯入
使用以下 JavaScript 程式碼匯入 ONNX Runtime Web
// use ES6 style import syntax (recommended)
import * as ort from 'onnxruntime-web';
// or use CommonJS style import syntax
const ort = require('onnxruntime-web');
如果您想使用支援 WebGPU 的 ONNX Runtime Web(實驗性功能),您需要按如下方式匯入
// use ES6 style import syntax (recommended)
import * as ort from 'onnxruntime-web/webgpu';
// or use CommonJS style import syntax
const ort = require('onnxruntime-web/webgpu');
如果您想使用支援 WebNN 的 ONNX Runtime Web(實驗性功能),您需要按如下方式匯入
// use ES6 style import syntax (recommended)
import * as ort from 'onnxruntime-web/experimental';
// or use CommonJS style import syntax
const ort = require('onnxruntime-web/experimental');
有關完整的匯入表格,請參閱 條件匯入。
文件
請參閱 ONNX Runtime JavaScript API 獲取 API 參考。另請檢視以下連結獲取 API 使用示例
- Tensor - 基本 Tensor 使用示例。
- Tensor <–> 影像轉換 - 從影像元素到 Tensor 以及從 Tensor 到影像元素的轉換示例。
- InferenceSession - InferenceSession 的基本使用示例。
- SessionOptions - 如何配置 InferenceSession 例項建立的示例。
-
ort.env 標誌 - 如何配置一組全域性標誌的示例。
- 另請參閱:Inference Session、Tensor 和 環境標誌 的 TypeScript 宣告作為參考。
請參閱 教程:Web 獲取教程。
請參閱 Web 訓練演示 以使用 onnxruntime-web 進行訓練。
示例
以下示例描述瞭如何在 Web 應用程式中使用 ONNX Runtime Web 進行模型推理
以下是在 Web 應用程式中使用 ONNX Runtime Web 的端到端示例
- 使用 ONNX Runtime Web 分類影像 - 一個使用 Next.js 進行影像分類的簡單 Web 應用程式。
- ONNX Runtime Web 演示 用於影像識別、手寫分析、即時情感檢測、目標檢測等。
- OpenAI Whisper - 演示如何在瀏覽器中使用 onnxruntime-web 和瀏覽器的音訊介面執行 whisper tiny.en。
- Facebook Segment-Anything - 演示如何在瀏覽器中使用 onnxruntime-web 和 webgpu 執行 segment-anything。
以下是在 Web 應用程式中使用 ONNX Runtime Web 的影片教程
支援的版本
| EPs/瀏覽器 | Chrome/Edge (Windows) | Chrome/Edge (Android) | Chrome/Edge (macOS) | Chrome/Edge (iOS) | Safari (macOS) | Safari (iOS) | Firefox (Windows) | Node.js |
|---|---|---|---|---|---|---|---|---|
| WebAssembly (CPU) | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️[1] |
| WebGPU | ✔️[2] | ✔️[3] | ✔️ | ❌ | ❌ | ❌ | ❌ | ❌ |
| WebGL | ✔️[4] | ✔️[4] | ✔️[4] | ✔️[4] | ✔️[4] | ✔️[4] | ✔️[4] | ❌ |
| WebNN | ✔️[5] | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
- [1]: Node.js 僅支援單執行緒
wasmEP。 - [2]: WebGPU 需要 Windows 上的 Chromium v113 或更高版本。Float16 支援需要 Chrome v121 或更高版本,以及 Edge v122 或更高版本。
- [3]: WebGPU 需要 Windows 上的 Chromium v121 或更高版本。
- [4]: WebGL 支援處於維護模式。建議使用 WebGPU 以獲得更好的效能。
- [5]: 需要使用命令列標誌
--enable-features=WebMachineLearningNeuralNetwork啟動瀏覽器。