transformers.js README

The project's README from github.com/huggingface/transformers.js. As one markdown file: README.md.


transformers.js javascript library logo

NPM NPM Downloads jsDelivr Hits License Documentation

State-of-the-art Machine Learning for the Web

Run 🤗 Transformers directly in your browser, with no need for a server!

Transformers.js is designed to be functionally equivalent to Hugging Face's transformers python library, meaning you can run the same pretrained models using a very similar API. These models support common tasks in different modalities, such as:

Transformers.js uses ONNX Runtime to run models in the browser. The best part about it, is that you can easily convert your pretrained PyTorch, TensorFlow, or JAX models to ONNX using 🤗 Optimum.

For more information, check out the full documentation.

Installation

To install via NPM, run:

npm i @huggingface/transformers

Alternatively, you can use it in vanilla JS, without any bundler, by using a CDN or static hosting. For example, using ES Modules, you can import the library with:

<script type="module">
    import { pipeline } from 'https://cdn.jsdelivr.net/npm/@huggingface/[email protected]';
</script>

Quick tour

It's super simple to translate from existing code! Just like the python library, we support the pipeline API. Pipelines group together a pretrained model with preprocessing of inputs and postprocessing of outputs, making it the easiest way to run models with the library.

Python (original) Javascript (ours)
from transformers import pipeline

# Allocate a pipeline for sentiment-analysis
pipe = pipeline('sentiment-analysis')

out = pipe('I love transformers!')
# [{'label': 'POSITIVE', 'score': 0.999806941}]
import { pipeline } from '@huggingface/transformers';

// Allocate a pipeline for sentiment-analysis
const pipe = await pipeline('sentiment-analysis');

const out = await pipe('I love transformers!');
// [{'label': 'POSITIVE', 'score': 0.999817686}]

You can also use a different model by specifying the model id or path as the second argument to the pipeline function. For example:

// Use a different model for sentiment-analysis
const pipe = await pipeline('sentiment-analysis', 'Xenova/bert-base-multilingual-uncased-sentiment');

By default, when running in the browser, the model will be run on your CPU (via WASM). If you would like to run the model on your GPU (via WebGPU), you can do this by setting device: 'webgpu', for example:

// Run the model on WebGPU
const pipe = await pipeline('sentiment-analysis', 'Xenova/distilbert-base-uncased-finetuned-sst-2-english', {
  device: 'webgpu',
});

For more information, check out the WebGPU guide.

[!WARNING] The WebGPU API is still experimental in many browsers, so if you run into any issues, please file a bug report.

In resource-constrained environments, such as web browsers, it is advisable to use a quantized version of the model to lower bandwidth and optimize performance. This can be achieved by adjusting the dtype option, which allows you to select the appropriate data type for your model. While the available options may vary depending on the specific model, typical choices include "fp32" (default for WebGPU), "fp16", "q8" (default for WASM), and "q4". For more information, check out the quantization guide.

// Run the model at 4-bit quantization
const pipe = await pipeline('sentiment-analysis', 'Xenova/distilbert-base-uncased-finetuned-sst-2-english', {
  dtype: 'q4',
});

Ready to dive in? Explore our wide variety of demo applications and templates here. You can also launch your own project instantly using the official Transformers.js template on Hugging Face!

Custom usage

By default, Transformers.js uses hosted pretrained models and precompiled WASM binaries, which should work out-of-the-box. You can customize this as follows:

Settings

import { env } from '@huggingface/transformers';

// Specify a custom location for models (defaults to '/models/').
env.localModelPath = '/path/to/models/';

// Disable the loading of remote models from the Hugging Face Hub:
env.allowRemoteModels = false;

// Set location of .wasm files. Defaults to use a CDN.
env.backends.onnx.wasm.wasmPaths = '/path/to/files/';

For a full list of available settings, check out the API Reference.

Convert your models to ONNX

We recommend using Optimum to convert your PyTorch models to ONNX in a single command. For the full list of supported architectures, check out the Optimum documentation.

Supported tasks/models

Here is the list of all tasks and architectures currently supported by Transformers.js. If you don't see your task/model listed here or it is not yet supported, feel free to open a feature request here.

To find compatible models on the Hub, select the "transformers.js" library tag in the filter menu (or visit this link). You can refine your search by selecting the task you're interested in (e.g., text-classification).

Tasks

Natural Language Processing

Task ID Description Supported?
Fill-Mask fill-mask Masking some of the words in a sentence and predicting which words should replace those masks. ✅ (docs)
(models)
Question Answering question-answering Retrieve the answer to a question from a given text. ✅ (docs)
(models)
Sentence Similarity sentence-similarity Determining how similar two texts are. ✅ (docs)
(models)
Summarization summarization Producing a shorter version of a document while preserving its important information. ✅ (docs)
(models)
Table Question Answering table-question-answering Answering a question about information from a given table. ❌
Text Classification text-classification or sentiment-analysis Assigning a label or class to a given text. ✅ (docs)
(models)
Text Generation text-generation Producing new text by predicting the next word in a sequence. ✅ (docs)
(models)
Text-to-text Generation text2text-generation Converting one text sequence into another text sequence. ✅ (docs)
(models)
Token Classification token-classification or ner Assigning a label to each token in a text. ✅ (docs)
(models)
Translation translation Converting text from one language to another. ✅ (docs)
(models)
Zero-Shot Classification zero-shot-classification Classifying text into classes that are unseen during training. ✅ (docs)
(models)
Feature Extraction feature-extraction Transforming raw data into numerical features that can be processed while preserving the information in the original dataset. ✅ (docs)
(models)

Vision

Task ID Description Supported?
Background Removal background-removal Isolating the main subject of an image by removing or making the background transparent. ✅ (docs)
(models)
Depth Estimation depth-estimation Predicting the depth of objects present in an image. ✅ (docs)
(models)
Image Classification image-classification Assigning a label or class to an entire image. ✅ (docs)
(models)
Image Segmentation image-segmentation Divides an image into segments where each pixel is mapped to an object. This task has multiple variants such as instance segmentation, panoptic segmentation and semantic segmentation. ✅ (docs)
(models)
Image-to-Image image-to-image Transforming a source image to match the characteristics of a target image or a target image domain. ✅ (docs)
(models)
Mask Generation mask-generation Generate masks for the objects in an image. ❌
Object Detection object-detection Identify objects of certain defined classes within an image. ✅ (docs)
(models)
Video Classification n/a Assigning a label or class to an entire video. ❌
Unconditional Image Generation n/a Generating images with no condition in any context (like a prompt text or another image). ❌
Image Feature Extraction image-feature-extraction Transforming raw data into numerical features that can be processed while preserving the information in the original image. ✅ (docs)
(models)

Audio

Task ID Description Supported?
Audio Classification audio-classification Assigning a label or class to a given audio. ✅ (docs)
(models)
Audio-to-Audio n/a Generating audio from an input audio source. ❌
Automatic Speech Recognition automatic-speech-recognition Transcribing a given audio into text. ✅ (docs)
(models)
Text-to-Speech text-to-speech or text-to-audio Generating natural-sounding speech given text input. ✅ (docs)
(models)

Tabular

Task ID Description Supported?
Tabular Classification n/a Classifying a target category (a group) based on set of attributes. ❌
Tabular Regression n/a Predicting a numerical value given a set of attributes. ❌

Multimodal

Task ID Description Supported?
Document Question Answering document-question-answering Answering questions on document images. ✅ (docs)
(models)
Image-to-Text image-to-text Output text from a given image. ✅ (docs)
(models)
Text-to-Image text-to-image Generates images from input text. ❌
Visual Question Answering visual-question-answering Answering open-ended questions based on an image. ❌
Zero-Shot Audio Classification `zero-shot-audio-classifi

transformers.js (huggingface/transformers.js)

Searching Database…

这是什么?Transformers.js 让你可以直接在网页浏览器中运行 Hugging Face 的最先进机器学习模型,无需服务器,它的 API 设计与 Python transformers 库保持一致。
这是我要导入的库,还是一个完整的应用?它是一个 JavaScript 库(可通过 npm 或 CDN 安装),而不是独立应用。它在功能上与 Hugging Face 的 Python transformers 库等效,因此同样的预训练模型可以用非常相似的 API 来运行。
我该怎样把它加入项目?可以用 npm 安装。如果是原生 JS 项目,完全不需要打包,直接以 ES Module 的方式从 CDN 或静态托管服务导入即可。
使用它需要 Python 或后端服务器吗?不需要。模型完全在客户端通过 ONNX Runtime 运行;默认情况下,库会自动获取托管的预训练模型和预编译的 WASM 二进制文件,因此无需任何服务器配置即可直接使用。
我能用上自己的 GPU 吗?效果一定稳定吗?可以通过设置 device: 'webgpu' 借助 WebGPU 使用 GPU 加速。但 README 提示,WebGPU API 在许多浏览器中仍处于实验阶段,可能会遇到问题;默认情况下,它会通过 WASM 回退到 CPU 运行。
如何使用我自己的 PyTorch 或 TensorFlow 模型,而不是 Hub 上的模型?用 Hugging Face 的 Optimum 库,一条命令即可将其转换为 ONNX 格式,然后像加载任何托管模型一样,用 Transformers.js 加载即可。
能让模型在浏览器中加载更快或占用更少带宽吗?可以。设置 dtype 选项(例如 fp16、q8、q4),即可使用模型的量化版本,以一定的精度换取更小的体积和更快的推理速度。
它实际能运行哪些类型的任务?它涵盖自然语言处理(分类、摘要、翻译、文本生成)、计算机视觉(图像分类、目标检测、图像分割、深度估计)、音频(语音识别、文本转语音),以及零样本分类和嵌入等多模态任务。
有没有不用从头写代码就能快速试用的方法?有。README 中链接了一系列演示应用和模板,还有托管在 Hugging Face 上的官方 Transformers.js 项目模板,可以立即启动。
Size
121.9 MB
Stars
16.4K
Age
3y
Commits · 90 Days