Transformers.js 文件

在 WebGPU 上執行模型

您正在檢視的是需要從原始碼安裝。如果您想進行常規 npm 安裝,請檢視最新的穩定版本 (v3.0.0)。
Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

在 WebGPU 上執行模型

WebGPU 是一種用於加速圖形和計算的新 Web 標準。API 使 Web 開發人員能夠直接在瀏覽器中使用底層系統的 GPU 進行高效能計算。WebGPU 是 WebGL 的後繼者,提供顯著更好的效能,因為它允許與現代 GPU 進行更直接的互動。最後,它支援通用 GPU 計算,這使其非常適合機器學習!


截至 2024 年 10 月,全球 WebGPU 支援率約為 70%(根據 caniuse.com),這意味著某些使用者可能無法使用該 API。

如果以下演示在您的瀏覽器中不起作用,您可能需要使用功能標誌啟用它

  • Firefox:使用 dom.webgpu.enabled 標誌(請參閱此處)。
  • Safari:使用 WebGPU 功能標誌(請參閱此處)。
  • 舊版 Chromium 瀏覽器(在 Windows、macOS、Linux 上):使用 enable-unsafe-webgpu 標誌(請參閱此處)。

Transformers.js v3 中的用法

感謝我們與 ONNX Runtime Web 的合作,啟用 WebGPU 加速就像在載入模型時設定 device: 'webgpu' 一樣簡單。讓我們看一些例子!

示例: 在 WebGPU 上計算文字嵌入 (演示)

import { pipeline } from "@huggingface/transformers";

// Create a feature-extraction pipeline
const extractor = await pipeline(
  "feature-extraction",
  "mixedbread-ai/mxbai-embed-xsmall-v1",
  { device: "webgpu" },
);

// Compute embeddings
const texts = ["Hello world!", "This is an example sentence."];
const embeddings = await extractor(texts, { pooling: "mean", normalize: true });
console.log(embeddings.tolist());
// [
//   [-0.016986183822155, 0.03228696808218956, -0.0013630966423079371, ... ],
//   [0.09050482511520386, 0.07207386940717697, 0.05762749910354614, ... ],
// ]

示例: 在 WebGPU 上使用 OpenAI Whisper 執行自動語音識別 (演示)

import { pipeline } from "@huggingface/transformers";

// Create automatic speech recognition pipeline
const transcriber = await pipeline(
  "automatic-speech-recognition",
  "onnx-community/whisper-tiny.en",
  { device: "webgpu" },
);

// Transcribe audio from a URL
const url = "https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav";
const output = await transcriber(url);
console.log(output);
// { text: ' And so my fellow Americans ask not what your country can do for you, ask what you can do for your country.' }

示例: 在 WebGPU 上使用 MobileNetV4 執行影像分類 (演示)

import { pipeline } from "@huggingface/transformers";

// Create image classification pipeline
const classifier = await pipeline(
  "image-classification",
  "onnx-community/mobilenetv4_conv_small.e2400_r224_in1k",
  { device: "webgpu" },
);

// Classify an image from a URL
const url = "https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg";
const output = await classifier(url);
console.log(output);
// [
//   { label: 'tiger, Panthera tigris', score: 0.6149784922599792 },
//   { label: 'tiger cat', score: 0.30281734466552734 },
//   { label: 'tabby, tabby cat', score: 0.0019135422771796584 },
//   { label: 'lynx, catamount', score: 0.0012161266058683395 },
//   { label: 'Egyptian cat', score: 0.0011465961579233408 }
// ]

報告錯誤並提供反饋

由於 WebGPU 的實驗性質,尤其是在非 Chromium 瀏覽器中,您在嘗試執行模型時可能會遇到問題(即使它可以在 WASM 中執行)。如果您遇到問題,請在 GitHub 上提交問題,我們將盡力解決。謝謝!

< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.