Transformers: State-of-the-Art Natural Language Processing (2020)

Abstract: Recent progress in natural language processing has been driven by advances in both model architecture and model pretraining. Transformer architectures have facilitated building higher-capacity models and pretraining has made it possible to effectively utilize this capacity for a wide variety of tasks. Transformers is an open-source library with the goal of opening up these advances to the wider machine learning community. The library consists of carefully engineered state-of-the art Transformer architectures under a unified API. Backing this library is a curated collection of pretrained models made by and available for the community. Transformers is designed to be extensible by researchers, simple for practitioners, and fast and robust in industrial deployments. The library is available at https://github.com/huggingface/transformers .

## introduction the transformer @xcite has rapidly become the dominant architecture for natural language processing, surpassing alternative neural models such as convolutional and recurrent neural networks in performance for tasks in both natural language understanding and natural language generation. the architecture scales with training data and model size, facilitates efficient parallel training, and captures long-range sequence features. model pretraining @xcite @xcite allows models to be trained on generic corpora and subsequently be easily adapted to specific tasks with strong performance. the transformer architecture is particularly conducive to pretraining on large text corpora, leading to major gains in accuracy on downstream tasks including text classification @xcite , language understanding @xcite @xcite , machine translation @xcite , coreference resolution @xcite , commonsense inference @xcite , and summarization @xcite among others. this advance leads to a wide range of practical challenges that must be addressed in order for these models to be widely utilized. the ubiquitous use of the transformer calls for systems to train, analyze, scale, and augment the model on a variety of platforms. the architecture is used as a building block to design increasingly sophisticated extensions and precise experiments. the pervasive adoption of pretraining methods has led to the need to distribute, fine-tune, deploy, and compress the core pretrained models used by the community. transformers is a library dedicated to supporting transformer-based architectures and facilitating the distribution of pretrained models. at the core of the libary is an implementation of the transformer which is designed for both research and production. the philosophy is to support industrial-strength implementations of popular model variants that are easy to read, extend, and deploy. on this foundation, the library supports the distribution and usage of a wide-variety of pretrained models in a centralized model hub. this hub supports users to compare different models with the same minimal api and to experiment with shared models on a variety of different tasks. transformers is an ongoing effort maintained by the team of engineers and researchers at hugging face with support from a vibrant community of over 400 external contributors. the library is released under the apache 2.0 license and is available on github foot_0 . detailed documentation and tutorials are available on hugging face's website foot_1 . ## related work the nlp and ml communities have a strong culture of building open-source research tools. the structure of transformers is inspired by the pioneering tensor2tensor library @xcite and the original source code for bert @xcite , both from google research. the concept of providing easy caching for pretrained models stemmed from allennlp @xcite . the library is also closely related to neural translation and language modeling systems, such as fairseq @xcite , open-nmt @xcite , texar @xcite , megatron-lm @xcite , and marian nmt @xcite . building on these elements, transformers adds extra user-facing features to allow for easy downloading, caching, and fine-tuning of the models as well as seamless transition to production. transformers maintains some compatibility with these libraries, most directly including a tool for performing inference using models from marian nmt and google's bert. there is a long history of easy-to-use, userfacing libraries for general-purpose nlp. two core libraries are nltk @xcite and stanford corenlp @xcite , which collect a variety of different approaches to nlp in a single package. more recently, general-purpose, open-source libraries have focused primarily on machine learning for a variety of nlp tasks, these include spacy @xcite , al-lennlp @xcite , flair @xcite , and stanza @xcite . transformers provides similar functionality as these libraries. additionally, each of these libraries now uses the transformers library and model hub as a low-level framework. since transformers provides a hub for nlp models, it is also related to popular model hubs including torch hub and tensorflow hub which collect framework-specific model parameters for easy use. unlike these hubs, transformers is domain-specific which allows the system to provide automatic support for model analysis, usage, deployment, benchmarking, and easy replicability. ## library design transformers is designed to mirror the standard nlp machine learning model pipeline: process data, apply a model, and make predictions. although the library includes tools facilitating training and development, in this technical report we focus on the core modeling specifications. for complete details about the features of the library refer to the documentation available on https: //huggingface.co/transformers/. every model in the library is fully defined by three building blocks shown in the diagram in figure 2: (a) a tokenizer, which converts raw text to sparse index encodings, (b) a transformer, which transforms sparse indices to contextual embeddings, and (c) a head, which uses contextual embeddings to make a task-specific prediction. most user needs can be addressed with these three components. transformers central to the library are carefully tested implementations of transformer architecture variants which are widely used in nlp. the full list of currently implemented architectures is shown in figure 2 (left). while each of these architectures radford et al., 2019) trans-xl (dai et al., 2019) xlnet (yang et al., 2019) seq-to-seq [∼ x 1:n ⇒ x 1:n ] bart (lewis et al., 2019) t5 (raffel et al., 2019) marianmt (j.-dowmunt et al., 2018) specialty: multimodal mmbt (kiela et al., 2019) specialty: long-distance reformer (kitaev et al., 2020) longformer (beltagy et al., 2020) specialty: efficient albert (lan et al., 2019) electra (clark et al., 2020) distilbert (sanh et al., 2019) specialty: multilingual xlm/roberta (lample and conneau, 2019b) transformer tokenizer head head tokenizers name ex. uses character-level bpe nmt, gpt byte-level bpe gpt-2 wordpiece bert sentencepiece xlnet unigram lm character reformer custom bio-chem transformer to be used for different tasks. here we assume the input token sequence is x 1:n from a vocabulary v, and y represents different possible outputs, possibly from a class set c. example datasets represent a small subset of example code distributed with the library. practically, all models follow the same hierarchy of abstraction: a base class implements the model's computation graph from an encoding (projection on the embedding matrix) through the series of selfattention layers to the final encoder hidden states. the base class is specific to each model and closely follows the model's original implementation which gives users the flexibility to easily dissect the inner workings of each individual architecture. in most cases, each model is implemented in a single file to enable ease of extensibility. wherever possible, different architectures follow the same api allowing users to switch easily between different models. a set of auto classes provides a unified api that enables very fast switching between models and even between frameworks. these classes automatically instantiate with the configuration specified by the user-specified pretrained model. tokenizers a critical nlp-specific aspect of the library is the implementations of the tokenizers necessary to use each model. tokenizer classes (each inheriting from a common base class) can either be instantiated from a corresponding pretrained model or can be configured manually. these classes store the vocabulary token-to-index map for their corresponding model and handle the encoding and decoding of input sequences according to a model's specific tokenization process. the tokenizers implemented are shown in figure 2 (right). users can easily modify tokenizer with interfaces to add additional token mappings, special tokens (such as classification or separation tokens), or otherwise resize the vocabulary. tokenizers can also implement additional useful features for the users. these range from token type indices in the case of sequence classification to maximum length sequence truncating taking into account the added model-specific special tokens (most pretrained transformer models have a maximum sequence length). for training on very large datasets, python-based tokenization is often undesirably slow. in the most recent release, transformers switched its implementation to use a highly-optimized tokenization library by default. this low-level library, available at https://github.com/huggingface/ tokenizers , is written in rust to speed up the tokenization procedure both during training and deployment. heads each transformer can be paired with one out of several ready-implemented heads with outputs amenable to common types of tasks. these heads are implemented as additional wrapper classes on top of the base class, adding a specific output layer, and optional loss function, on top of the transformer's contextual embeddings. the full set of implemented heads are shown in figure 2 (top). these classes follow a similar naming pattern: xxxforsequenceclassification where xxx is the name of the model and can be used for adaptation (fine-tuning) or pretraining. some heads, such as conditional generation, support extra functionality like sampling and beam search. for pretrained models, we release the heads used to pretrain the model itself. for instance, for bert we release the language modeling and next sentence prediction heads which allows easy for adaptation using the pretraining objectives. we also make it easy for users to utilize the same core transformer parameters with a variety of other heads for finetuning. while each head can be used generally, the library also includes a collection of examples that show each head on real problems. these examples demonstrate how a pretrained model can be adapted with a given head to achieve state-of-theart results on a large variety of nlp tasks. ## community model hub transformers aims to facilitate easy use and distribution of pretrained models. inherently this is a community process; a single pretraining run facilitates fine-tuning on many specific tasks. the model hub makes it simple for any end-user to access a model for use with their own data. this hub now contains 2,097 user models, both pretrained and fine-tuned, from across the community. figure 1 shows the increase and distribution of popular transformers over time. while core models like bert and gpt-2 continue to be popular, other specialized models including distilbert @xcite , which was developed for the library, are now widely downloaded by the community. the user interface of the model hub is designed to be simple and open to the community. to upload a model, any user can sign up for an account and use a command-line interface to produce an archive consisting a tokenizer, transformer, and head. this bundle may be a model trained through the library or converted from a checkpoint of other popular training tools. these models are then stored and given a canonical name which a user can use to download, cache, and run the model either for finetuning or inference in two lines of code. to load flaubert @xcite , a bert model pretrained on a french training corpus, the command is: when a model is uploaded to the model hub, it is automatically given a landing page describing its core properties, architecture, and use cases. additional model-specific metadata can be provided via a model card @xcite that describes properties of its training, a citation to the work, datasets used during pretraining, and any caveats about known biases in the model and its predictions. an example model card is shown in figure 3 (left). since the model hub is specific to transformerbased models, we can target use cases that would be difficult for more general model collections. for example, because each uploaded model includes metadata concerning its structure, the model page can include live inference that allows users to experiment with output of models on a real data. figure 3 (right) shows an example of the model page with live inference. additionally, model pages include links to other model-specific tools like benchmarking and visualizations. for example, model pages can link to exbert @xcite , a transformer visualization library. ## deployment an increasingly important goal of transformers is to make it easy to efficiently deploy model to production. different users have different production needs, and deployment often requires solving significantly different challenges than training. the library thereforce allows for several different strategies for production deployment. one core propery of the libary is that models are available both in pytorch and tensorflow, and there is interoperability between both frameworks. a model trained in one of frameworks can be saved through standard serialization and be reloaded from the saved files in the other framework seamlessly. this makes it particularly easy to switch from one framework to the other one along the model lifetime (training, serving, etc.). each framework has deployment recommendations. for example, in pytorch, models are compatible with torchscript, an intermediate representation of a pytorch model that can then be run either in python in a more efficient way, or in a highperformance environment such as c++. fine-tuned models can thus be exported to production-friendly environment, and run through torchserving. ten-sorflow includes several serving options within its ecosystem, and these can be used directly. transformers can also export models to intermediate neural network formats for further compilation. it supports converting models to the open neural network exchange format (onnx) for deployment. not only does this allow the model to be run in a standardized interoperable format, but also leads to significant speed-ups. figure 4 shows experiments run in collaboration with the onnx team to optimize bert, roberta, and gpt-2 from the transformers library. using this intermediate format, onnx was able to achieve nearly a 4x speedup on this model. the team is also experimenting with other promising intermediate formats such as jax/xla @xcite and tvm @xcite . finally, as transformers become more widely used in all nlp applications, it is increasingly important to deploy to edge devices such as phones or home electronics. models can use adapters to convert models to coreml weights that are suitable to be embedded inside a ios application, to enable on-the-edge machine learning. code is also made available foot_2 . similar methods can be used for android devices. ## conclusion as transformer and pretraining play larger roles in nlp, it is important for these models to be accessible to researchers and end-users. transformers is an open-source library and community designed to facilitate users to access large-scale pretrained models, to build and experiment on top of them, and to deploy them in downstream tasks with stateof-the-art performance. transformers has gained significant organic traction since its release and is set up to continue to provide core infrastructure while helping to facilitate access to new models.