Transformers.js v3 發佈,加入 WebGPU 支援並將支援架構增至 120 種
Transformers.js v3: WebGPU Support, New Models & Tasks, and More…
Hugging Face 發佈 Transformers.js v3,新增 WebGPU 支援和量化格式選擇,支援架構總數增至 120 種。官方稱 WebGPU 最高可比 WASM 快 100 倍;此版本另提供 25 個示例專案與範本,以及超過 1200 個已轉換模型。
這次更新把 WebGPU、量化格式選擇及 120 種架構納入同一 JavaScript 庫,並兼容 Node.js、Deno、Bun,展示其瀏覽器與伺服器端部署路徑。
經過一年多的開發,我們很高興宣佈推出 🤗 Transformers.js v3!
重點包括:
- 支援 WebGPU(速度最高比 WASM 快 100 倍!)
- 新增量化格式(dtype)
- 支援架構總數達 120 種
- 新增 25 個範例項目和範本
- Hugging Face Hub 上有超過 1200 個預先轉換的模型
- 相容 Node.js(ESM + CJS)、Deno 和 Bun
- 在 GitHub 和 NPM 設立新家
安裝
你可以從 NPM 安裝 Transformers.js v3,立即開始使用:
npm i @huggingface/transformers
然後以下列方式匯入程式庫:
import { pipeline } from "@huggingface/transformers";
或透過 CDN 使用:
import { pipeline } from "https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.0.0";
詳情請參閲文件。
支援 WebGPU
WebGPU 是一項新的網頁標準,用於加速圖像處理和運算。這個 API 讓網頁開發者可以直接在瀏覽器中使用系統 GPU,執行高效能運算。WebGPU 是 WebGL 的後繼技術,因為能更直接地與現代 GPU 互動,效能顯著更佳。最後,它亦支援通用 GPU 運算,因此非常適合機器學習!
截至 2024 年十月,全球 WebGPU 支援率約為 70%(據 caniuse.com),代表部分用戶可能無法使用此 API。
如果以下示範無法在你的瀏覽器中運作,可能需要透過功能旗標啟用:
在 Transformers.js v3 中使用
多虧我們與 ONNX Runtime Web 合作,載入模型時只需設定 device: 'webgpu',即可啟用 WebGPU 加速。來看幾個例子!
範例:使用 WebGPU 計算文本 embedding(示範)
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, ... ],
// ]
範例:使用 OpenAI whisper 和 WebGPU 執行自動語音識別(示範)
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.' }
範例:使用 MobileNetV4 和 WebGPU 執行圖像分類(示範)
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 }
// ]
新增量化格式(dtype)
在 Transformers.js v3 之前,我們使用 quantized 選項指定使用量化(q8)或全精度(fp32)模型版本,分別將 quantized 設為 true 或 false。現在新增 dtype 參數,可以從更多格式中選擇。
可用的量化格式視乎模型而定,常見格式包括:全精度("fp32")、半精度("fp16")、8-bit("q8"、"int8"、"uint8")及 4-bit("q4"、"bnb4"、"q4f16")。
基本用法
範例:以 4-bit 量化執行 Qwen2.5-0.5B-Instruct(示範)
import { pipeline } from "@huggingface/transformers";
// Create a text generation pipeline
const generator = await pipeline(
"text-generation",
"onnx-community/Qwen2.5-0.5B-Instruct",
{ dtype: "q4", device: "webgpu" },
);
// Define the list of messages
const messages = [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "Tell me a funny joke." },
];
// Generate a response
const output = await generator(messages, { max_new_tokens: 128 });
console.log(output[0].generated_text.at(-1).content);
按模組指定 dtype
Whisper 或 Florence-2 等部分 encoder-decoder 模型對量化設定非常敏感,尤其是 encoder 的設定。因此,我們新增按模組選擇 dtype 的功能,只需提供模組名稱與 dtype 的對應表即可。
範例:在 WebGPU 上執行 Florence-2(示範)
import { Florence2ForConditionalGeneration } from "@huggingface/transformers";
const model = await Florence2ForConditionalGeneration.from_pretrained(
"onnx-community/Florence-2-base-ft",
{
dtype: {
embed_tokens: "fp16",
vision_encoder: "fp16",
encoder_model: "q4",
decoder_model_merged: "q4",
},
device: "webgpu",
},
);
查看完整程式碼範例
import {
Florence2ForConditionalGeneration,
AutoProcessor,
AutoTokenizer,
RawImage,
} from "@huggingface/transformers";
// Load model, processor, and tokenizer
const model_id = "onnx-community/Florence-2-base-ft";
const model = await Florence2ForConditionalGeneration.from_pretrained(
model_id,
{
dtype: {
embed_tokens: "fp16",
vision_encoder: "fp16",
encoder_model: "q4",
decoder_model_merged: "q4",
},
device: "webgpu",
},
);
const processor = await AutoProcessor.from_pretrained(model_id);
const tokenizer = await AutoTokenizer.from_pretrained(model_id);
// Load image and prepare vision inputs
const url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/car.jpg";
const image = await RawImage.fromURL(url);
const vision_inputs = await processor(image);
// Specify task and prepare text inputs
const task = "<MORE_DETAILED_CAPTION>";
const prompts = processor.construct_prompts(task);
const text_inputs = tokenizer(prompts);
// Generate text
const generated_ids = await model.generate({
...text_inputs,
...vision_inputs,
max_new_tokens: 100,
});
// Decode generated text
const generated_text = tokenizer.batch_decode(generated_ids, {
skip_special_tokens: false,
})[0];
// Post-process the generated text
const result = processor.post_process_generation(
generated_text,
task,
image.size,
);
console.log(result);
// { '<MORE_DETAILED_CAPTION>': 'A green car is parked in front of a tan building. The building has a brown door and two brown windows. The car is a two door and the door is closed. The green car has black tires.' }
支援 120 種架構
這次發布令支援架構總數增至 120 種(見完整清單),涵蓋多種輸入模態和任務。新加入的模型包括:Phi-3、Gemma 和 Gemma 2、LLaVa、Moondream、Florence-2、MusicGen、Sapiens、Depth Pro、PyAnnote 及 RT-DETR。
新增模型清單
- Cohere(來自 Cohere)隨論文 Command-R: Retrieval Augmented Generation at Production Scale 一同發布,作者為 Cohere。
- Decision Transformer(來自 Berkeley/Facebook/Google)隨論文 Decision Transformer: Reinforcement Learning via Sequence Modeling 一同發布,作者為 Lili Chen、Kevin Lu、Aravind Rajeswaran、Kimin Lee、Aditya Grover、Michael Laskin、Pieter Abbeel、Aravind Srinivas、Igor Mordatch。
- Depth Pro(來自 Apple)隨論文 Depth Pro: Sharp Monocular Metric Depth in Less Than a Second 一同發布,作者為 Aleksei Bochkovskii、Amaël Delaunoy、Hugo Germain、Marcel Santos、Yichao Zhou、Stephan R. Richter、Vladlen Koltun。
- Florence2(來自 Microsoft)隨論文 Florence-2: Advancing a Unified Representation for a Variety of Vision Tasks 一同發布,作者為 Bin Xiao、Haiping Wu、Weijian Xu、Xiyang Dai、Houdong Hu、Yumao Lu、Michael Zeng、Ce Liu、Lu Yuan。
- Gemma(來自 Google)隨論文 Gemma: Open Models Based on Gemini Technology and Research 一同發布,作者為 Gemma Google 團隊。
- Gemma2(來自 Google)隨論文 Gemma2: Open Models Based on Gemini Technology and Research 一同發布,作者為 Gemma Google 團隊。
- Granite(來自 IBM)隨論文 Power Scheduler: A Batch Size and Token Number Agnostic Learning Rate Scheduler 一同發布,作者為 Yikang Shen、Matthew Stallone、Mayank Mishra、Gaoyuan Zhang、Shawn Tan、Aditya Prasad、Adriana Meza Soria、David D. Cox、Rameswar Panda。
- GroupViT(來自 UCSD、NVIDIA)隨論文 GroupViT: Semantic Segmentation Emerges from Text Supervision 一同發布,作者為 Jiarui Xu、Shalini De Mello、Sifei Liu、Wonmin Byeon、Thomas Breuel、Jan Kautz、Xiaolong Wang。
- Hiera(來自 Meta)隨論文 Hiera: A Hierarchical Vision Transformer without the Bells-and-Whistles 一同發布,作者為 Chaitanya Ryali、Yuan-Ting Hu、Daniel Bolya、Chen Wei、Haoqi Fan、Po-Yao Huang、Vaibhav Aggarwal、Arkabandhu Chowdhury、Omid Poursaeed、Judy Hoffman、Jitendra Malik、Yanghao Li、Christoph Feichtenhofer。
- JAIS(來自 Core42)隨論文 Jais and Jais-chat: Arabic-Centric Foundation and Instruction-Tuned Open Generative Large Language Models 一同發布,作者為 Neha Sengupta、Sunil Kumar Sahu、Bokang Jia、Satheesh Katipomu、Haonan Li、Fajri Koto、William Marshall、Gurpreet Gosal、Cynthia Liu、Zhiming Chen、Osama Mohammed Afzal、Samta Kamboj、Onkar Pandit、Rahul Pal、Lalit Pradhan、Zain Muhammad Mujahid、Massa Baali、Xudong Han、Sondos Mahmoud Bsharat、Alham Fikri Aji、Zhiqiang Shen、Zhengzhong Liu、Natalia Vassilieva、Joel Hestness、Andy Hock、Andrew Feldman、Jonathan Lee、Andrew Jackson、Hector Xuguang Ren、Preslav Nakov、Timothy Baldwin、Eric Xing。
- LLaVa(來自 Microsoft Research 和 University of Wisconsin-Madison)隨論文 Visual Instruction Tuning 一同發布,作者為 Haotian Liu、Chunyuan Li、Yuheng Li 和 Yong Jae Lee。
- MaskFormer(來自 Meta 和 UIUC)隨論文 Per-Pixel Classification is Not All You Need for Semantic Segmentation 一同發布,作者為 Bowen Cheng、Alexander G. Schwing、Alexander Kirillov。
- MusicGen(來自 Meta)隨論文 Simple and Controllable Music Generation 一同發布,作者為 Jade Copet、Felix Kreuk、Itai Gat、Tal Remez、David Kant、Gabriel Synnaeve、Yossi Adi 和 Alexandre Défossez。
- MobileCLIP(來自 Apple)隨論文 MobileCLIP: Fast Image-Text Models through Multi-Modal Reinforced Training 一同發布,作者為 Pavan Kumar Anasosalu Vasu、Hadi Pouransari、Fartash Faghri、Raviteja Vemulapalli、Oncel Tuzel。
- MobileNetV1(來自 Google Inc.)隨論文 MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications 一同發布,作者為 Andrew G. Howard、Menglong Zhu、Bo Chen、Dmitry Kalenichenko、Weijun Wang、Tobias Weyand、Marco Andreetto、Hartwig Adam。
- MobileNetV2(來自 Google Inc.)隨論文 MobileNetV2: Inverted Residuals and Linear Bottlenecks 一同發布,作者為 Mark Sandler、Andrew Howard、Menglong Zhu、Andrey Zhmoginov、Liang-Chieh Chen。
- MobileNetV3(來自 Google Inc.)隨論文 Searching for MobileNetV3 一同發布,作者為 Andrew Howard、Mark Sandler、Grace Chu、Liang-Chieh Chen、Bo Chen、Mingxing Tan、Weijun Wang、Yukun Zhu、Ruoming Pang、Vijay Vasudevan、Quoc V. Le、Hartwig Adam。
- MobileNetV4(來自 Google Inc.)隨論文 MobileNetV4 - Universal Models for the Mobile Ecosystem 一同發布,作者為 Danfeng Qin、Chas Leichner、Manolis Delakis、Marco Fornoni、Shixin Luo、Fan Yang、Weijun Wang、Colby Banbury、Chengxi Ye、Berkin Akin、Vaibhav Aggarwal、Tenghui Zhu、Daniele Moro、Andrew Howard。
- Moondream1 由 vikhyat 在 moondream 儲存庫發布。
- OpenELM(來自 Apple)隨論文 OpenELM: An Efficient Language Model Family with Open-source Training and Inference Framework 一同發布,作者為 Sachin Mehta、Mohammad Hossein Sekhavat、Qingqing Cao、Maxwell Horton、Yanzi Jin、Chenfan Sun、Iman Mirzadeh、Mahyar Najibi、Dmitry Belenko、Peter Zatloukal、Mohammad Rastegari。
- Phi3(來自 Microsoft)隨論文 Phi-3 Technical Report: A Highly Capable Language Model Locally on Your Phone 一同發布,作者為 Marah Abdin、Sam Ade Jacobs、Ammar Ahmad Awan、Jyoti Aneja、Ahmed Awadallah、Hany Awadalla、Nguyen Bach、Amit Bahree、Arash Bakhtiari、Harkirat Behl、Alon Benhaim、Misha Bilenko、Johan Bjorck、Sébastien Bubeck、Martin Cai、Caio César Teodoro Mendes、Weizhu Chen、Vishrav Chaudhary、Parul Chopra、Allie Del Giorno、Gustavo de Rosa、Matthew Dixon、Ronen Eldan、Dan Iter、Amit Garg、Abhishek Goswami、Suriya Gunasekar、Emman Haider、Junheng Hao、Russell J. Hewett、Jamie Huynh、Mojan Javaheripi、Xin Jin、Piero Kauffmann、Nikos Karampatziakis、Dongwoo Kim、Mahoud Khademi、Lev Kurilenko、James R. Lee、Yin Tat Lee、Yuanzhi Li、Chen Liang、Weishung Liu、Eric Lin、Zeqi Lin、Piyush Madan、Arindam Mitra、Hardik Modi、Anh Nguyen、Brandon Norick、Barun Patra、Daniel Perez-Becker、Thomas Portet、Reid Pryzant、Heyang Qin、Marko Radmilac、Corby Rosset、Sambudha Roy、Olatunji Ruwase、Olli Saarikivi、Amin Saied、Adil Salim、Michael Santacroce、Shital Shah、Ning Shang、Hiteshi Sharma、Xia Song、Masahiro Tanaka、Xin Wang、Rachel Ward、Guanhua Wang、Philipp Witte、Michael Wyatt、Can Xu、Jiahang Xu、Sonali Yadav、Fan Yang、Ziyi Yang、Donghan Yu、Chengruidong Zhang、Cyril Zhang、Jianwen Zhang、Li Lyna Zhang、Yi Zhang、Yue Zhang、Yunan Zhang、Xiren Zhou。
- PVT(來自 Nanjing University、香港大學等)隨論文 Pyramid Vision Transformer: A Versatile Backbone for Dense Prediction without Convolutions 一同發布,作者為 Wenhai Wang、Enze Xie、Xiang Li、Deng-Ping Fan、Kaitao Song、Ding Liang、Tong Lu、Ping Luo、Ling Shao。
- PyAnnote 由 Hervé Bredin 在 pyannote/pyannote-audio 儲存庫發布。
- RT-DETR(來自 Baidu)隨論文 DETRs Beat YOLOs on Real-time Object Detection 一同發布,作者為 Yian Zhao、Wenyu Lv、Shangliang Xu、Jinman Wei、Guanzhong Wang、Qingqing Dang、Yi Liu、Jie Chen。
- Sapiens(來自 Meta AI)隨論文 Sapiens: Foundation for Human Vision Models 一同發布,作者為 Rawal Khirodkar、Timur Bagautdinov、Julieta Martinez、Su Zhaoen、Austin James、Peter Selednik、Stuart Anderson、Shunsuke Saito。
- ViTMAE(來自 Meta AI)隨論文 Masked Autoencoders Are Scalable Vision Learners 一同發布,作者為 Kaiming He、Xinlei Chen、Saining Xie、Yanghao Li、Piotr Dollár、Ross Girshick。
- ViTMSN(來自 Meta AI)隨論文 Masked Siamese Networks for Label-Efficient Learning 一同發布,作者為 Mahmoud Assran、Mathilde Caron、Ishan Misra、Piotr Bojanowski、Florian Bordes、Pascal Vincent、Armand Joulin、Michael Rabbat、Nicolas Ballas。
範例項目和範本
作為這次發布的一部分,我們推出了 25 個新範例項目和範本,主要展示 WebGPU 支援!以下包括 Phi-3.5 WebGPU 和 Whisper WebGPU 等示範。
我們正把所有範例項目和示範遷移至 https://github.com/huggingface/transformers.js-examples,請留意後續更新!
![]() |
![]() |
|---|
超過 1200 個預先轉換的模型
截至今天發布此版本,社羣已將超過 1200 個模型轉換成相容 Transformers.js 的格式!完整可用模型清單請見此處。
如要轉換自己的模型或微調版本,可按以下方式使用轉換指令碼:
python -m scripts.convert --quantize --model_id <model_name_or_path>
將生成的檔案上載到 Hugging Face Hub 後,記得加上 transformers.js 標籤,讓其他人容易找到並使用你的模型!
相容 Node.js(ESM + CJS)、Deno 和 Bun
Transformers.js v3 現已相容三種最受歡迎的伺服器端 JavaScript runtime:
| Runtime | 説明 | 範例 |
|---|---|---|
| Node.js | 廣泛使用的 JavaScript runtime,以 Chrome V8 為基礎。它擁有龐大生態系統,並支援各類程式庫和框架。 | ESM 範例 / CJS 範例 |
| Deno | 現代化的 JavaScript 和 TypeScript runtime,預設安全。它使用 ES modules,亦提供實驗性的 WebGPU 支援。 | Deno 範例 |
| Bun | 以效能為優先、速度快捷的 JavaScript runtime,內置 bundler、transpiler 和套件管理器。 | Bun 範例 |
在 NPM 和 GitHub 設立新家
最後,我們很高興宣佈 Transformers.js 現將以 Hugging Face 官方組織名義,在 NPM 發布為 @huggingface/transformers(取代 v1 和 v2 使用的 @xenova/transformers)。
我們亦已將儲存庫遷移至 Hugging Face 官方 GitHub 組織(https://github.com/huggingface/transformers.js),這將成為我們的新家,歡迎來打聲招呼!期待聽到你的意見、回覆你的 issue,並審閲你的 PR!
這是一個重要里程碑,我們非常感謝社羣協助實現這個長遠目標!若沒有大家,這一切都不可能成真……謝謝!🤗
來源:Hugging Face Blog · huggingface.co

