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:
- π Natural Language Processing: text classification, named entity recognition, question answering, language modeling, summarization, translation, multiple choice, and text generation.
- πΌοΈ Computer Vision: image classification, object detection, and segmentation.
- π£οΈ Audio: automatic speech recognition and audio classification.
- π Multimodal: zero-shot image classification.
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.
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 '@xenova/transformers';
// Allocate a pipeline for sentiment-analysis
let pipe = await pipeline('sentiment-analysis');
let 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
let pipe = await pipeline('sentiment-analysis', 'nlptown/bert-base-multilingual-uncased-sentiment');
To install via NPM, run:
npm i @xenova/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/@xenova/[email protected]';
</script>
Want to jump straight in? Get started with one of our sample applications/templates:
Name | Description | Source code |
---|---|---|
Whisper Web | Speech recognition w/ Whisper | link |
Doodle Dash | Real-time sketch-recognition game (see blog) | link |
Code Playground | In-browser code completion website | link |
Semantic Image Search | Search for images with text (Next.js + Supabase) | link |
React | Multilingual translation website | link |
Browser extension | Text classification extension | link |
Electron | Text classification application | link |
Next.js (client-side) | Sentiment analysis (in-browser inference) | link |
Next.js (server-side) | Sentiment analysis (Node.js inference) | link |
Node.js | Sentiment analysis API | link |
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:
import { env } from '@xenova/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.
We recommend using our conversion script to convert your PyTorch, TensorFlow, or JAX models to ONNX in a single command. Behind the scenes, it uses π€ Optimum to perform conversion and quantization of your model.
python -m scripts.convert --quantize --model_id <model_name_or_path>
For example, convert and quantize bert-base-uncased using:
python -m scripts.convert --quantize --model_id bert-base-uncased
This will save the following files to ./models/
:
bert-base-uncased/
βββ config.json
βββ tokenizer.json
βββ tokenizer_config.json
βββ onnx/
βββ model.onnx
βββ model_quantized.onnx
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 up 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).
Task | ID | Description | Supported? |
---|---|---|---|
Conversational | conversational |
Generating conversational text that is relevant, coherent and knowledgable given a prompt. | β |
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) |
Task | ID | Description | Supported? |
---|---|---|---|
Depth Estimation | depth-estimation |
Predicting the depth of objects present in an image. | β |
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. | β |
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). | β |
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 | n/a | Generating natural-sounding speech given text input. | β |
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. | β |
Task | ID | Description | Supported? |
---|---|---|---|
Document Question Answering | document-question-answering |
Answering questions on document images. | β |
Feature Extraction | feature-extraction |
Transforming raw data into numerical features that can be processed while preserving the information in the original dataset. | β
(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 Image Classification | zero-shot-image-classification |
Classifying images into classes that are unseen during training. | β
(docs) (models) |
Task | ID | Description | Supported? |
---|---|---|---|
Reinforcement Learning | n/a | Learning from actions by interacting with an environment through trial and error and receiving rewards (negative or positive) as feedback. | β |
- ALBERT (from Google Research and the Toyota Technological Institute at Chicago) released with the paper ALBERT: A Lite BERT for Self-supervised Learning of Language Representations, by Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.
- BART (from Facebook) released with the paper BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, Translation, and Comprehension by Mike Lewis, Yinhan Liu, Naman Goyal, Marjan Ghazvininejad, Abdelrahman Mohamed, Omer Levy, Ves Stoyanov and Luke Zettlemoyer.
- BERT (from Google) released with the paper BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding by Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova.
- BLOOM (from BigScience workshop) released by the BigScience Workshop.
- CLIP (from OpenAI) released with the paper Learning Transferable Visual Models From Natural Language Supervision by Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel Goh, Sandhini Agarwal, Girish Sastry, Amanda Askell, Pamela Mishkin, Jack Clark, Gretchen Krueger, Ilya Sutskever.
- CodeGen (from Salesforce) released with the paper A Conversational Paradigm for Program Synthesis by Erik Nijkamp, Bo Pang, Hiroaki Hayashi, Lifu Tu, Huan Wang, Yingbo Zhou, Silvio Savarese, Caiming Xiong.
- DeBERTa (from Microsoft) released with the paper DeBERTa: Decoding-enhanced BERT with Disentangled Attention by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
- DeBERTa-v2 (from Microsoft) released with the paper DeBERTa: Decoding-enhanced BERT with Disentangled Attention by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
- DeiT (from Facebook) released with the paper Training data-efficient image transformers & distillation through attention by Hugo Touvron, Matthieu Cord, Matthijs Douze, Francisco Massa, Alexandre Sablayrolles, HervΓ© JΓ©gou.
- DETR (from Facebook) released with the paper End-to-End Object Detection with Transformers by Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, Sergey Zagoruyko.
- DistilBERT (from HuggingFace), released together with the paper DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter by Victor Sanh, Lysandre Debut and Thomas Wolf. The same method has been applied to compress GPT2 into DistilGPT2, RoBERTa into DistilRoBERTa, Multilingual BERT into DistilmBERT and a German version of DistilBERT.
- FLAN-T5 (from Google AI) released in the repository google-research/t5x by Hyung Won Chung, Le Hou, Shayne Longpre, Barret Zoph, Yi Tay, William Fedus, Eric Li, Xuezhi Wang, Mostafa Dehghani, Siddhartha Brahma, Albert Webson, Shixiang Shane Gu, Zhuyun Dai, Mirac Suzgun, Xinyun Chen, Aakanksha Chowdhery, Sharan Narang, Gaurav Mishra, Adams Yu, Vincent Zhao, Yanping Huang, Andrew Dai, Hongkun Yu, Slav Petrov, Ed H. Chi, Jeff Dean, Jacob Devlin, Adam Roberts, Denny Zhou, Quoc V. Le, and Jason Wei
- GPT Neo (from EleutherAI) released in the repository EleutherAI/gpt-neo by Sid Black, Stella Biderman, Leo Gao, Phil Wang and Connor Leahy.
- GPT-2 (from OpenAI) released with the paper Language Models are Unsupervised Multitask Learners by Alec Radford*, Jeffrey Wu*, Rewon Child, David Luan, Dario Amodei** and Ilya Sutskever**.
- GPTBigCode (from BigCode) released with the paper SantaCoder: don't reach for the stars! by Loubna Ben Allal, Raymond Li, Denis Kocetkov, Chenghao Mou, Christopher Akiki, Carlos Munoz Ferrandis, Niklas Muennighoff, Mayank Mishra, Alex Gu, Manan Dey, Logesh Kumar Umapathi, Carolyn Jane Anderson, Yangtian Zi, Joel Lamy Poirier, Hailey Schoelkopf, Sergey Troshin, Dmitry Abulkhanov, Manuel Romero, Michael Lappert, Francesco De Toni, Bernardo GarcΓa del RΓo, Qian Liu, Shamik Bose, Urvashi Bhattacharyya, Terry Yue Zhuo, Ian Yu, Paulo Villegas, Marco Zocca, Sourab Mangrulkar, David Lansky, Huu Nguyen, Danish Contractor, Luis Villa, Jia Li, Dzmitry Bahdanau, Yacine Jernite, Sean Hughes, Daniel Fried, Arjun Guha, Harm de Vries, Leandro von Werra.
- M2M100 (from Facebook) released with the paper Beyond English-Centric Multilingual Machine Translation by Angela Fan, Shruti Bhosale, Holger Schwenk, Zhiyi Ma, Ahmed El-Kishky, Siddharth Goyal, Mandeep Baines, Onur Celebi, Guillaume Wenzek, Vishrav Chaudhary, Naman Goyal, Tom Birch, Vitaliy Liptchinsky, Sergey Edunov, Edouard Grave, Michael Auli, Armand Joulin.
- MarianMT Machine translation models trained using OPUS data by JΓΆrg Tiedemann. The Marian Framework is being developed by the Microsoft Translator Team.
- MMS (from Facebook) released with the paper Scaling Speech Technology to 1,000+ Languages by Vineel Pratap, Andros Tjandra, Bowen Shi, Paden Tomasello, Arun Babu, Sayani Kundu, Ali Elkahky, Zhaoheng Ni, Apoorv Vyas, Maryam Fazel-Zarandi, Alexei Baevski, Yossi Adi, Xiaohui Zhang, Wei-Ning Hsu, Alexis Conneau, Michael Auli.
- MobileBERT (from CMU/Google Brain) released with the paper MobileBERT: a Compact Task-Agnostic BERT for Resource-Limited Devices by Zhiqing Sun, Hongkun Yu, Xiaodan Song, Renjie Liu, Yiming Yang, and Denny Zhou.
- MobileViT (from Apple) released with the paper MobileViT: Light-weight, General-purpose, and Mobile-friendly Vision Transformer by Sachin Mehta and Mohammad Rastegari.
- MPNet (from Microsoft Research) released with the paper MPNet: Masked and Permuted Pre-training for Language Understanding by Kaitao Song, Xu Tan, Tao Qin, Jianfeng Lu, Tie-Yan Liu.
- MPT (from MosaiML) released with the repository llm-foundry by the MosaicML NLP Team.
- MT5 (from Google AI) released with the paper mT5: A massively multilingual pre-trained text-to-text transformer by Linting Xue, Noah Constant, Adam Roberts, Mihir Kale, Rami Al-Rfou, Aditya Siddhant, Aditya Barua, Colin Raffel.
- NLLB (from Meta) released with the paper No Language Left Behind: Scaling Human-Centered Machine Translation by the NLLB team.
- RoBERTa (from Facebook), released together with the paper RoBERTa: A Robustly Optimized BERT Pretraining Approach by Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, Veselin Stoyanov.
- SqueezeBERT (from Berkeley) released with the paper SqueezeBERT: What can computer vision teach NLP about efficient neural networks? by Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, and Kurt W. Keutzer.
- Swin Transformer (from Microsoft) released with the paper Swin Transformer: Hierarchical Vision Transformer using Shifted Windows by Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo.
- T5 (from Google AI) released with the paper Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer by Colin Raffel and Noam Shazeer and Adam Roberts and Katherine Lee and Sharan Narang and Michael Matena and Yanqi Zhou and Wei Li and Peter J. Liu.
- T5v1.1 (from Google AI) released in the repository google-research/text-to-text-transfer-transformer by Colin Raffel and Noam Shazeer and Adam Roberts and Katherine Lee and Sharan Narang and Michael Matena and Yanqi Zhou and Wei Li and Peter J. Liu.
- Vision Transformer (ViT) (from Google AI) released with the paper An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale by Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, Neil Houlsby.
- Wav2Vec2 (from Facebook AI) released with the paper wav2vec 2.0: A Framework for Self-Supervised Learning of Speech Representations by Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli.
- Whisper (from OpenAI) released with the paper Robust Speech Recognition via Large-Scale Weak Supervision by Alec Radford, Jong Wook Kim, Tao Xu, Greg Brockman, Christine McLeavey, Ilya Sutskever.
- XLM-RoBERTa (from Facebook AI), released together with the paper Unsupervised Cross-lingual Representation Learning at Scale by Alexis Conneau*, Kartikay Khandelwal*, Naman Goyal, Vishrav Chaudhary, Guillaume Wenzek, Francisco GuzmΓ‘n, Edouard Grave, Myle Ott, Luke Zettlemoyer and Veselin Stoyanov.
- YOLOS (from Huazhong University of Science & Technology) released with the paper You Only Look at One Sequence: Rethinking Transformer in Vision through Object Detection by Yuxin Fang, Bencheng Liao, Xinggang Wang, Jiemin Fang, Jiyang Qi, Rui Wu, Jianwei Niu, Wenyu Liu.