text
stringlengths
2
11.8k
from transformers import TapasTokenizer, TFTapasForQuestionAnswering import pandas as pd model_name = "google/tapas-base-finetuned-wtq" model = TFTapasForQuestionAnswering.from_pretrained(model_name) tokenizer = TapasTokenizer.from_pretrained(model_name) data = {"Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"], "Number of movies": ["87", "53", "69"]} queries = [ "What is the name of the first actor?", "How many movies has George Clooney played in?", "What is the total number of movies?", ] table = pd.DataFrame.from_dict(data) inputs = tokenizer(table=table, queries=queries, padding="max_length", return_tensors="tf") outputs = model(**inputs) predicted_answer_coordinates, predicted_aggregation_indices = tokenizer.convert_logits_to_predictions( inputs, outputs.logits, outputs.logits_aggregation ) let's print out the results: id2aggregation = {0: "NONE", 1: "SUM", 2: "AVERAGE", 3: "COUNT"} aggregation_predictions_string = [id2aggregation[x] for x in predicted_aggregation_indices] answers = [] for coordinates in predicted_answer_coordinates: if len(coordinates) == 1: # only a single cell: answers.append(table.iat[coordinates[0]]) else: # multiple cells cell_values = [] for coordinate in coordinates: cell_values.append(table.iat[coordinate]) answers.append(", ".join(cell_values)) display(table) print("") for query, answer, predicted_agg in zip(queries, answers, aggregation_predictions_string): print(query) if predicted_agg == "NONE": print("Predicted answer: " + answer) else: print("Predicted answer: " + predicted_agg + " > " + answer) What is the name of the first actor? Predicted answer: Brad Pitt How many movies has George Clooney played in? Predicted answer: COUNT > 69 What is the total number of movies? Predicted answer: SUM > 87, 53, 69
In case of a conversational set-up, then each table-question pair must be provided sequentially to the model, such that the prev_labels token types can be overwritten by the predicted labels of the previous table-question pair. Again, more info can be found in this notebook (for PyTorch) and this notebook (for TensorFlow). Resources Text classification task guide Masked language modeling task guide
Text classification task guide Masked language modeling task guide TAPAS specific outputs [[autodoc]] models.tapas.modeling_tapas.TableQuestionAnsweringOutput TapasConfig [[autodoc]] TapasConfig TapasTokenizer [[autodoc]] TapasTokenizer - call - convert_logits_to_predictions - save_vocabulary
TapasModel [[autodoc]] TapasModel - forward TapasForMaskedLM [[autodoc]] TapasForMaskedLM - forward TapasForSequenceClassification [[autodoc]] TapasForSequenceClassification - forward TapasForQuestionAnswering [[autodoc]] TapasForQuestionAnswering - forward
TFTapasModel [[autodoc]] TFTapasModel - call TFTapasForMaskedLM [[autodoc]] TFTapasForMaskedLM - call TFTapasForSequenceClassification [[autodoc]] TFTapasForSequenceClassification - call TFTapasForQuestionAnswering [[autodoc]] TFTapasForQuestionAnswering - call
LXMERT Overview The LXMERT model was proposed in LXMERT: Learning Cross-Modality Encoder Representations from Transformers by Hao Tan & Mohit Bansal. It is a series of bidirectional transformer encoders (one for the vision modality, one for the language modality, and then one to fuse both modalities) pretrained using a combination of masked language modeling, visual-language text alignment, ROI-feature regression, masked visual-attribute modeling, masked visual-object modeling, and visual-question answering objectives. The pretraining consists of multiple multi-modal datasets: MSCOCO, Visual-Genome + Visual-Genome Question Answering, VQA 2.0, and GQA. The abstract from the paper is the following: Vision-and-language reasoning requires an understanding of visual concepts, language semantics, and, most importantly, the alignment and relationships between these two modalities. We thus propose the LXMERT (Learning Cross-Modality Encoder Representations from Transformers) framework to learn these vision-and-language connections. In LXMERT, we build a large-scale Transformer model that consists of three encoders: an object relationship encoder, a language encoder, and a cross-modality encoder. Next, to endow our model with the capability of connecting vision and language semantics, we pre-train the model with large amounts of image-and-sentence pairs, via five diverse representative pretraining tasks: masked language modeling, masked object prediction (feature regression and label classification), cross-modality matching, and image question answering. These tasks help in learning both intra-modality and cross-modality relationships. After fine-tuning from our pretrained parameters, our model achieves the state-of-the-art results on two visual question answering datasets (i.e., VQA and GQA). We also show the generalizability of our pretrained cross-modality model by adapting it to a challenging visual-reasoning task, NLVR, and improve the previous best result by 22% absolute (54% to 76%). Lastly, we demonstrate detailed ablation studies to prove that both our novel model components and pretraining strategies significantly contribute to our strong results; and also present several attention visualizations for the different encoders This model was contributed by eltoto1219. The original code can be found here. Usage tips
Bounding boxes are not necessary to be used in the visual feature embeddings, any kind of visual-spacial features will work. Both the language hidden states and the visual hidden states that LXMERT outputs are passed through the cross-modality layer, so they contain information from both modalities. To access a modality that only attends to itself, select the vision/language hidden states from the first input in the tuple. The bidirectional cross-modality encoder attention only returns attention values when the language modality is used as the input and the vision modality is used as the context vector. Further, while the cross-modality encoder contains self-attention for each respective modality and cross-attention, only the cross attention is returned and both self attention outputs are disregarded.
Resources Question answering task guide
LxmertConfig [[autodoc]] LxmertConfig LxmertTokenizer [[autodoc]] LxmertTokenizer LxmertTokenizerFast [[autodoc]] LxmertTokenizerFast Lxmert specific outputs [[autodoc]] models.lxmert.modeling_lxmert.LxmertModelOutput [[autodoc]] models.lxmert.modeling_lxmert.LxmertForPreTrainingOutput [[autodoc]] models.lxmert.modeling_lxmert.LxmertForQuestionAnsweringOutput [[autodoc]] models.lxmert.modeling_tf_lxmert.TFLxmertModelOutput [[autodoc]] models.lxmert.modeling_tf_lxmert.TFLxmertForPreTrainingOutput
LxmertModel [[autodoc]] LxmertModel - forward LxmertForPreTraining [[autodoc]] LxmertForPreTraining - forward LxmertForQuestionAnswering [[autodoc]] LxmertForQuestionAnswering - forward TFLxmertModel [[autodoc]] TFLxmertModel - call TFLxmertForPreTraining [[autodoc]] TFLxmertForPreTraining - call
DPT Overview The DPT model was proposed in Vision Transformers for Dense Prediction by René Ranftl, Alexey Bochkovskiy, Vladlen Koltun. DPT is a model that leverages the Vision Transformer (ViT) as backbone for dense prediction tasks like semantic segmentation and depth estimation. The abstract from the paper is the following: We introduce dense vision transformers, an architecture that leverages vision transformers in place of convolutional networks as a backbone for dense prediction tasks. We assemble tokens from various stages of the vision transformer into image-like representations at various resolutions and progressively combine them into full-resolution predictions using a convolutional decoder. The transformer backbone processes representations at a constant and relatively high resolution and has a global receptive field at every stage. These properties allow the dense vision transformer to provide finer-grained and more globally coherent predictions when compared to fully-convolutional networks. Our experiments show that this architecture yields substantial improvements on dense prediction tasks, especially when a large amount of training data is available. For monocular depth estimation, we observe an improvement of up to 28% in relative performance when compared to a state-of-the-art fully-convolutional network. When applied to semantic segmentation, dense vision transformers set a new state of the art on ADE20K with 49.02% mIoU. We further show that the architecture can be fine-tuned on smaller datasets such as NYUv2, KITTI, and Pascal Context where it also sets the new state of the art.
DPT architecture. Taken from the original paper. This model was contributed by nielsr. The original code can be found here. Usage tips DPT is compatible with the [AutoBackbone] class. This allows to use the DPT framework with various computer vision backbones available in the library, such as [VitDetBackbone] or [Dinov2Backbone]. One can create it as follows: thon from transformers import Dinov2Config, DPTConfig, DPTForDepthEstimation initialize with a Transformer-based backbone such as DINOv2 in that case, we also specify reshape_hidden_states=False to get feature maps of shape (batch_size, num_channels, height, width) backbone_config = Dinov2Config.from_pretrained("facebook/dinov2-base", out_features=["stage1", "stage2", "stage3", "stage4"], reshape_hidden_states=False) config = DPTConfig(backbone_config=backbone_config) model = DPTForDepthEstimation(config=config)
Resources A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with DPT. Demo notebooks for [DPTForDepthEstimation] can be found here. Semantic segmentation task guide Monocular depth estimation task guide
If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. DPTConfig [[autodoc]] DPTConfig DPTFeatureExtractor [[autodoc]] DPTFeatureExtractor - call - post_process_semantic_segmentation DPTImageProcessor [[autodoc]] DPTImageProcessor - preprocess - post_process_semantic_segmentation DPTModel [[autodoc]] DPTModel - forward DPTForDepthEstimation [[autodoc]] DPTForDepthEstimation - forward DPTForSemanticSegmentation [[autodoc]] DPTForSemanticSegmentation - forward
CANINE Overview The CANINE model was proposed in CANINE: Pre-training an Efficient Tokenization-Free Encoder for Language Representation by Jonathan H. Clark, Dan Garrette, Iulia Turc, John Wieting. It's among the first papers that trains a Transformer without using an explicit tokenization step (such as Byte Pair Encoding (BPE), WordPiece or SentencePiece). Instead, the model is trained directly at a Unicode character-level. Training at a character-level inevitably comes with a longer sequence length, which CANINE solves with an efficient downsampling strategy, before applying a deep Transformer encoder. The abstract from the paper is the following: Pipelined NLP systems have largely been superseded by end-to-end neural modeling, yet nearly all commonly-used models still require an explicit tokenization step. While recent tokenization approaches based on data-derived subword lexicons are less brittle than manually engineered tokenizers, these techniques are not equally suited to all languages, and the use of any fixed vocabulary may limit a model's ability to adapt. In this paper, we present CANINE, a neural encoder that operates directly on character sequences, without explicit tokenization or vocabulary, and a pre-training strategy that operates either directly on characters or optionally uses subwords as a soft inductive bias. To use its finer-grained input effectively and efficiently, CANINE combines downsampling, which reduces the input sequence length, with a deep transformer stack, which encodes context. CANINE outperforms a comparable mBERT model by 2.8 F1 on TyDi QA, a challenging multilingual benchmark, despite having 28% fewer model parameters. This model was contributed by nielsr. The original code can be found here. Usage tips
CANINE uses no less than 3 Transformer encoders internally: 2 "shallow" encoders (which only consist of a single layer) and 1 "deep" encoder (which is a regular BERT encoder). First, a "shallow" encoder is used to contextualize the character embeddings, using local attention. Next, after downsampling, a "deep" encoder is applied. Finally, after upsampling, a "shallow" encoder is used to create the final character embeddings. Details regarding up- and downsampling can be found in the paper. CANINE uses a max sequence length of 2048 characters by default. One can use [CanineTokenizer] to prepare text for the model. Classification can be done by placing a linear layer on top of the final hidden state of the special [CLS] token (which has a predefined Unicode code point). For token classification tasks however, the downsampled sequence of tokens needs to be upsampled again to match the length of the original character sequence (which is 2048). The details for this can be found in the paper.
Model checkpoints: google/canine-c: Pre-trained with autoregressive character loss, 12-layer, 768-hidden, 12-heads, 121M parameters (size ~500 MB). google/canine-s: Pre-trained with subword loss, 12-layer, 768-hidden, 12-heads, 121M parameters (size ~500 MB). Usage example CANINE works on raw characters, so it can be used without a tokenizer: thon
from transformers import CanineModel import torch model = CanineModel.from_pretrained("google/canine-c") # model pre-trained with autoregressive character loss text = "hello world" use Python's built-in ord() function to turn each character into its unicode code point id input_ids = torch.tensor([[ord(char) for char in text]]) outputs = model(input_ids) # forward pass pooled_output = outputs.pooler_output sequence_output = outputs.last_hidden_state
For batched inference and training, it is however recommended to make use of the tokenizer (to pad/truncate all sequences to the same length): thon
from transformers import CanineTokenizer, CanineModel model = CanineModel.from_pretrained("google/canine-c") tokenizer = CanineTokenizer.from_pretrained("google/canine-c") inputs = ["Life is like a box of chocolates.", "You never know what you gonna get."] encoding = tokenizer(inputs, padding="longest", truncation=True, return_tensors="pt") outputs = model(**encoding) # forward pass pooled_output = outputs.pooler_output sequence_output = outputs.last_hidden_state Resources
Resources Text classification task guide Token classification task guide Question answering task guide Multiple choice task guide
CanineConfig [[autodoc]] CanineConfig CanineTokenizer [[autodoc]] CanineTokenizer - build_inputs_with_special_tokens - get_special_tokens_mask - create_token_type_ids_from_sequences CANINE specific outputs [[autodoc]] models.canine.modeling_canine.CanineModelOutputWithPooling CanineModel [[autodoc]] CanineModel - forward CanineForSequenceClassification [[autodoc]] CanineForSequenceClassification - forward CanineForMultipleChoice [[autodoc]] CanineForMultipleChoice - forward CanineForTokenClassification [[autodoc]] CanineForTokenClassification - forward CanineForQuestionAnswering [[autodoc]] CanineForQuestionAnswering - forward
VipLlava Overview The VipLlava model was proposed in Making Large Multimodal Models Understand Arbitrary Visual Prompts by Mu Cai, Haotian Liu, Siva Karthik Mustikovela, Gregory P. Meyer, Yuning Chai, Dennis Park, Yong Jae Lee. VipLlava enhances the training protocol of Llava by marking images and interact with the model using natural cues like a "red bounding box" or "pointed arrow" during training. The abstract from the paper is the following: While existing large vision-language multimodal models focus on whole image understanding, there is a prominent gap in achieving region-specific comprehension. Current approaches that use textual coordinates or spatial encodings often fail to provide a user-friendly interface for visual prompting. To address this challenge, we introduce a novel multimodal model capable of decoding arbitrary visual prompts. This allows users to intuitively mark images and interact with the model using natural cues like a "red bounding box" or "pointed arrow". Our simple design directly overlays visual markers onto the RGB image, eliminating the need for complex region encodings, yet achieves state-of-the-art performance on region-understanding tasks like Visual7W, PointQA, and Visual Commonsense Reasoning benchmark. Furthermore, we present ViP-Bench, a comprehensive benchmark to assess the capability of models in understanding visual prompts across multiple dimensions, enabling future research in this domain. Code, data, and model are publicly available. Tips:
The architecture is similar than llava architecture except that the multi-modal projector takes a set of concatenated vision hidden states and has an additional layernorm layer on that module. We advise users to use padding_side="left" when computing batched generation as it leads to more accurate results. Simply make sure to call processor.tokenizer.padding_side = "left" before generating.
Note the model has not been explicitly trained to process multiple images in the same prompt, although this is technically possible, you may experience inaccurate results. For better results, we recommend users to prompt the model with the correct prompt format: A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.###Human: <image>\n<prompt>###Assistant: For multiple turns conversation:
A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.###Human: <image>\n<prompt1>###Assistant: <answer1>###Human: <prompt2>###Assistant: The original code can be found here. This model was contributed by Younes Belkada VipLlavaConfig [[autodoc]] VipLlavaConfig VipLlavaForConditionalGeneration [[autodoc]] VipLlavaForConditionalGeneration - forward
NLLB Updated tokenizer behavior DISCLAIMER: The default behaviour for the tokenizer was fixed and thus changed in April 2023. The previous version adds [self.eos_token_id, self.cur_lang_code] at the end of the token sequence for both target and source tokenization. This is wrong as the NLLB paper mentions (page 48, 6.1.1. Model Architecture) : Note that we prefix the source sequence with the source language, as opposed to the target language as previously done in several works (Arivazhagan et al., 2019; Johnson et al., 2017). This is primarily because we prioritize optimizing zero-shot performance of our model on any pair of 200 languages at a minor cost to supervised performance. Previous behaviour: thon
from transformers import NllbTokenizer tokenizer = NllbTokenizer.from_pretrained("facebook/nllb-200-distilled-600M") tokenizer("How was your day?").input_ids [13374, 1398, 4260, 4039, 248130, 2, 256047] 2: '' 256047 : 'eng_Latn' New behaviour thon from transformers import NllbTokenizer tokenizer = NllbTokenizer.from_pretrained("facebook/nllb-200-distilled-600M") tokenizer("How was your day?").input_ids [256047, 13374, 1398, 4260, 4039, 248130, 2]
Enabling the old behaviour can be done as follows: thon from transformers import NllbTokenizer tokenizer = NllbTokenizer.from_pretrained("facebook/nllb-200-distilled-600M", legacy_behaviour=True)
For more details, feel free to check the linked PR and Issue. Overview The NLLB model was presented in No Language Left Behind: Scaling Human-Centered Machine Translation by Marta R. Costa-jussà, James Cross, Onur Çelebi, Maha Elbayad, Kenneth Heafield, Kevin Heffernan, Elahe Kalbassi, Janice Lam, Daniel Licht, Jean Maillard, Anna Sun, Skyler Wang, Guillaume Wenzek, Al Youngblood, Bapi Akula, Loic Barrault, Gabriel Mejia Gonzalez, Prangthip Hansanti, John Hoffman, Semarley Jarrett, Kaushik Ram Sadagopan, Dirk Rowe, Shannon Spruit, Chau Tran, Pierre Andrews, Necip Fazil Ayan, Shruti Bhosale, Sergey Edunov, Angela Fan, Cynthia Gao, Vedanuj Goswami, Francisco Guzmán, Philipp Koehn, Alexandre Mourachko, Christophe Ropers, Safiyyah Saleem, Holger Schwenk, and Jeff Wang. The abstract of the paper is the following: Driven by the goal of eradicating language barriers on a global scale, machine translation has solidified itself as a key focus of artificial intelligence research today. However, such efforts have coalesced around a small subset of languages, leaving behind the vast majority of mostly low-resource languages. What does it take to break the 200 language barrier while ensuring safe, high quality results, all while keeping ethical considerations in mind? In No Language Left Behind, we took on this challenge by first contextualizing the need for low-resource language translation support through exploratory interviews with native speakers. Then, we created datasets and models aimed at narrowing the performance gap between low and high-resource languages. More specifically, we developed a conditional compute model based on Sparsely Gated Mixture of Experts that is trained on data obtained with novel and effective data mining techniques tailored for low-resource languages. We propose multiple architectural and training improvements to counteract overfitting while training on thousands of tasks. Critically, we evaluated the performance of over 40,000 different translation directions using a human-translated benchmark, Flores-200, and combined human evaluation with a novel toxicity benchmark covering all languages in Flores-200 to assess translation safety. Our model achieves an improvement of 44% BLEU relative to the previous state-of-the-art, laying important groundwork towards realizing a universal translation system. This implementation contains the dense models available on release. The sparse model NLLB-MoE (Mixture of Expert) is now available! More details here This model was contributed by Lysandre. The authors' code can be found here. Generating with NLLB While generating the target text set the forced_bos_token_id to the target language id. The following example shows how to translate English to French using the facebook/nllb-200-distilled-600M model. Note that we're using the BCP-47 code for French fra_Latn. See here for the list of all BCP-47 in the Flores 200 dataset. thon
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer tokenizer = AutoTokenizer.from_pretrained("facebook/nllb-200-distilled-600M") model = AutoModelForSeq2SeqLM.from_pretrained("facebook/nllb-200-distilled-600M") article = "UN Chief says there is no military solution in Syria" inputs = tokenizer(article, return_tensors="pt") translated_tokens = model.generate( **inputs, forced_bos_token_id=tokenizer.lang_code_to_id["fra_Latn"], max_length=30 ) tokenizer.batch_decode(translated_tokens, skip_special_tokens=True)[0] Le chef de l'ONU dit qu'il n'y a pas de solution militaire en Syrie
Generating from any other language than English English (eng_Latn) is set as the default language from which to translate. In order to specify that you'd like to translate from a different language, you should specify the BCP-47 code in the src_lang keyword argument of the tokenizer initialization. See example below for a translation from romanian to german:
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer tokenizer = AutoTokenizer.from_pretrained( "facebook/nllb-200-distilled-600M", token=True, src_lang="ron_Latn" ) model = AutoModelForSeq2SeqLM.from_pretrained("facebook/nllb-200-distilled-600M", token=True) article = "Şeful ONU spune că nu există o soluţie militară în Siria" inputs = tokenizer(article, return_tensors="pt") translated_tokens = model.generate( **inputs, forced_bos_token_id=tokenizer.lang_code_to_id["deu_Latn"], max_length=30 ) tokenizer.batch_decode(translated_tokens, skip_special_tokens=True)[0] UN-Chef sagt, es gibt keine militärische Lösung in Syrien
Resources Translation task guide Summarization task guide NllbTokenizer [[autodoc]] NllbTokenizer - build_inputs_with_special_tokens NllbTokenizerFast [[autodoc]] NllbTokenizerFast
DeiT Overview The DeiT model was proposed in Training data-efficient image transformers & distillation through attention by Hugo Touvron, Matthieu Cord, Matthijs Douze, Francisco Massa, Alexandre Sablayrolles, Hervé Jégou. The Vision Transformer (ViT) introduced in Dosovitskiy et al., 2020 has shown that one can match or even outperform existing convolutional neural networks using a Transformer encoder (BERT-like). However, the ViT models introduced in that paper required training on expensive infrastructure for multiple weeks, using external data. DeiT (data-efficient image transformers) are more efficiently trained transformers for image classification, requiring far less data and far less computing resources compared to the original ViT models. The abstract from the paper is the following: Recently, neural networks purely based on attention were shown to address image understanding tasks such as image classification. However, these visual transformers are pre-trained with hundreds of millions of images using an expensive infrastructure, thereby limiting their adoption. In this work, we produce a competitive convolution-free transformer by training on Imagenet only. We train them on a single computer in less than 3 days. Our reference vision transformer (86M parameters) achieves top-1 accuracy of 83.1% (single-crop evaluation) on ImageNet with no external data. More importantly, we introduce a teacher-student strategy specific to transformers. It relies on a distillation token ensuring that the student learns from the teacher through attention. We show the interest of this token-based distillation, especially when using a convnet as a teacher. This leads us to report results competitive with convnets for both Imagenet (where we obtain up to 85.2% accuracy) and when transferring to other tasks. We share our code and models. This model was contributed by nielsr. The TensorFlow version of this model was added by amyeroberts. Usage tips
Compared to ViT, DeiT models use a so-called distillation token to effectively learn from a teacher (which, in the DeiT paper, is a ResNet like-model). The distillation token is learned through backpropagation, by interacting with the class ([CLS]) and patch tokens through the self-attention layers. There are 2 ways to fine-tune distilled models, either (1) in a classic way, by only placing a prediction head on top of the final hidden state of the class token and not using the distillation signal, or (2) by placing both a prediction head on top of the class token and on top of the distillation token. In that case, the [CLS] prediction head is trained using regular cross-entropy between the prediction of the head and the ground-truth label, while the distillation prediction head is trained using hard distillation (cross-entropy between the prediction of the distillation head and the label predicted by the teacher). At inference time, one takes the average prediction between both heads as final prediction. (2) is also called "fine-tuning with distillation", because one relies on a teacher that has already been fine-tuned on the downstream dataset. In terms of models, (1) corresponds to [DeiTForImageClassification] and (2) corresponds to [DeiTForImageClassificationWithTeacher]. Note that the authors also did try soft distillation for (2) (in which case the distillation prediction head is trained using KL divergence to match the softmax output of the teacher), but hard distillation gave the best results. All released checkpoints were pre-trained and fine-tuned on ImageNet-1k only. No external data was used. This is in contrast with the original ViT model, which used external data like the JFT-300M dataset/Imagenet-21k for pre-training. The authors of DeiT also released more efficiently trained ViT models, which you can directly plug into [ViTModel] or [ViTForImageClassification]. Techniques like data augmentation, optimization, and regularization were used in order to simulate training on a much larger dataset (while only using ImageNet-1k for pre-training). There are 4 variants available (in 3 different sizes): facebook/deit-tiny-patch16-224, facebook/deit-small-patch16-224, facebook/deit-base-patch16-224 and facebook/deit-base-patch16-384. Note that one should use [DeiTImageProcessor] in order to prepare images for the model.
Resources A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with DeiT. [DeiTForImageClassification] is supported by this example script and notebook. See also: Image classification task guide Besides that: [DeiTForMaskedImageModeling] is supported by this example script.
Besides that: [DeiTForMaskedImageModeling] is supported by this example script. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. DeiTConfig [[autodoc]] DeiTConfig DeiTFeatureExtractor [[autodoc]] DeiTFeatureExtractor - call DeiTImageProcessor [[autodoc]] DeiTImageProcessor - preprocess
DeiTModel [[autodoc]] DeiTModel - forward DeiTForMaskedImageModeling [[autodoc]] DeiTForMaskedImageModeling - forward DeiTForImageClassification [[autodoc]] DeiTForImageClassification - forward DeiTForImageClassificationWithTeacher [[autodoc]] DeiTForImageClassificationWithTeacher - forward
TFDeiTModel [[autodoc]] TFDeiTModel - call TFDeiTForMaskedImageModeling [[autodoc]] TFDeiTForMaskedImageModeling - call TFDeiTForImageClassification [[autodoc]] TFDeiTForImageClassification - call TFDeiTForImageClassificationWithTeacher [[autodoc]] TFDeiTForImageClassificationWithTeacher - call
PEGASUS-X Overview The PEGASUS-X model was proposed in Investigating Efficiently Extending Transformers for Long Input Summarization by Jason Phang, Yao Zhao and Peter J. Liu. PEGASUS-X (PEGASUS eXtended) extends the PEGASUS models for long input summarization through additional long input pretraining and using staggered block-local attention with global tokens in the encoder. The abstract from the paper is the following: While large pretrained Transformer models have proven highly capable at tackling natural language tasks, handling long sequence inputs continues to be a significant challenge. One such task is long input summarization, where inputs are longer than the maximum input context of most pretrained models. Through an extensive set of experiments, we investigate what model architectural changes and pretraining paradigms can most efficiently adapt a pretrained Transformer for long input summarization. We find that a staggered, block-local Transformer with global encoder tokens strikes a good balance of performance and efficiency, and that an additional pretraining phase on long sequences meaningfully improves downstream summarization performance. Based on our findings, we introduce PEGASUS-X, an extension of the PEGASUS model with additional long input pretraining to handle inputs of up to 16K tokens. PEGASUS-X achieves strong performance on long input summarization tasks comparable with much larger models while adding few additional parameters and not requiring model parallelism to train. This model was contributed by zphang. The original code can be found here. Documentation resources
Translation task guide Summarization task guide PEGASUS-X uses the same tokenizer as PEGASUS. PegasusXConfig [[autodoc]] PegasusXConfig PegasusXModel [[autodoc]] PegasusXModel - forward PegasusXForConditionalGeneration [[autodoc]] PegasusXForConditionalGeneration - forward
Wav2Vec2-BERT Overview The Wav2Vec2-BERT model was proposed in Seamless: Multilingual Expressive and Streaming Speech Translation by the Seamless Communication team from Meta AI. This model was pre-trained on 4.5M hours of unlabeled audio data covering more than 143 languages. It requires finetuning to be used for downstream tasks such as Automatic Speech Recognition (ASR), or Audio Classification. The official results of the model can be found in Section 3.2.1 of the paper. The abstract from the paper is the following: Recent advancements in automatic speech translation have dramatically expanded language coverage, improved multimodal capabilities, and enabled a wide range of tasks and functionalities. That said, large-scale automatic speech translation systems today lack key features that help machine-mediated communication feel seamless when compared to human-to-human dialogue. In this work, we introduce a family of models that enable end-to-end expressive and multilingual translations in a streaming fashion. First, we contribute an improved version of the massively multilingual and multimodal SeamlessM4T model—SeamlessM4T v2. This newer model, incorporating an updated UnitY2 framework, was trained on more low-resource language data. The expanded version of SeamlessAlign adds 114,800 hours of automatically aligned data for a total of 76 languages. SeamlessM4T v2 provides the foundation on which our two newest models, SeamlessExpressive and SeamlessStreaming, are initiated. SeamlessExpressive enables translation that preserves vocal styles and prosody. Compared to previous efforts in expressive speech research, our work addresses certain underexplored aspects of prosody, such as speech rate and pauses, while also preserving the style of one’s voice. As for SeamlessStreaming, our model leverages the Efficient Monotonic Multihead Attention (EMMA) mechanism to generate low-latency target translations without waiting for complete source utterances. As the first of its kind, SeamlessStreaming enables simultaneous speech-to-speech/text translation for multiple source and target languages. To understand the performance of these models, we combined novel and modified versions of existing automatic metrics to evaluate prosody, latency, and robustness. For human evaluations, we adapted existing protocols tailored for measuring the most relevant attributes in the preservation of meaning, naturalness, and expressivity. To ensure that our models can be used safely and responsibly, we implemented the first known red-teaming effort for multimodal machine translation, a system for the detection and mitigation of added toxicity, a systematic evaluation of gender bias, and an inaudible localized watermarking mechanism designed to dampen the impact of deepfakes. Consequently, we bring major components from SeamlessExpressive and SeamlessStreaming together to form Seamless, the first publicly available system that unlocks expressive cross-lingual communication in real-time. In sum, Seamless gives us a pivotal look at the technical foundation needed to turn the Universal Speech Translator from a science fiction concept into a real-world technology. Finally, contributions in this work—including models, code, and a watermark detector—are publicly released and accessible at the link below. This model was contributed by ylacombe. The original code can be found here. Usage tips
Wav2Vec2-BERT follows the same architecture as Wav2Vec2-Conformer, but employs a causal depthwise convolutional layer and uses as input a mel-spectrogram representation of the audio instead of the raw waveform. Wav2Vec2-BERT can use either no relative position embeddings, Shaw-like position embeddings, Transformer-XL-like position embeddings, or rotary position embeddings by setting the correct config.position_embeddings_type. Wav2Vec2-BERT also introduces a Conformer-based adapter network instead of a simple convolutional network.
Resources [Wav2Vec2BertForCTC] is supported by this example script. You can also adapt these notebooks on how to finetune a speech recognition model in English, and how to finetune a speech recognition model in any language. [Wav2Vec2BertForSequenceClassification] can be used by adapting this example script. See also: Audio classification task guide
Wav2Vec2BertConfig [[autodoc]] Wav2Vec2BertConfig Wav2Vec2BertProcessor [[autodoc]] Wav2Vec2BertProcessor - call - pad - from_pretrained - save_pretrained - batch_decode - decode Wav2Vec2BertModel [[autodoc]] Wav2Vec2BertModel - forward Wav2Vec2BertForCTC [[autodoc]] Wav2Vec2BertForCTC - forward Wav2Vec2BertForSequenceClassification [[autodoc]] Wav2Vec2BertForSequenceClassification - forward Wav2Vec2BertForAudioFrameClassification [[autodoc]] Wav2Vec2BertForAudioFrameClassification - forward Wav2Vec2BertForXVector [[autodoc]] Wav2Vec2BertForXVector - forward
RoFormer Overview The RoFormer model was proposed in RoFormer: Enhanced Transformer with Rotary Position Embedding by Jianlin Su and Yu Lu and Shengfeng Pan and Bo Wen and Yunfeng Liu. The abstract from the paper is the following: Position encoding in transformer architecture provides supervision for dependency modeling between elements at different positions in the sequence. We investigate various methods to encode positional information in transformer-based language models and propose a novel implementation named Rotary Position Embedding(RoPE). The proposed RoPE encodes absolute positional information with rotation matrix and naturally incorporates explicit relative position dependency in self-attention formulation. Notably, RoPE comes with valuable properties such as flexibility of being expand to any sequence lengths, decaying inter-token dependency with increasing relative distances, and capability of equipping the linear self-attention with relative position encoding. As a result, the enhanced transformer with rotary position embedding, or RoFormer, achieves superior performance in tasks with long texts. We release the theoretical analysis along with some preliminary experiment results on Chinese data. The undergoing experiment for English benchmark will soon be updated. This model was contributed by junnyu. The original code can be found here. Usage tips RoFormer is a BERT-like autoencoding model with rotary position embeddings. Rotary position embeddings have shown improved performance on classification tasks with long texts. Resources
Text classification task guide Token classification task guide Question answering task guide Causal language modeling task guide Masked language modeling task guide Multiple choice task guide
RoFormerConfig [[autodoc]] RoFormerConfig RoFormerTokenizer [[autodoc]] RoFormerTokenizer - build_inputs_with_special_tokens - get_special_tokens_mask - create_token_type_ids_from_sequences - save_vocabulary RoFormerTokenizerFast [[autodoc]] RoFormerTokenizerFast - build_inputs_with_special_tokens
RoFormerModel [[autodoc]] RoFormerModel - forward RoFormerForCausalLM [[autodoc]] RoFormerForCausalLM - forward RoFormerForMaskedLM [[autodoc]] RoFormerForMaskedLM - forward RoFormerForSequenceClassification [[autodoc]] RoFormerForSequenceClassification - forward RoFormerForMultipleChoice [[autodoc]] RoFormerForMultipleChoice - forward RoFormerForTokenClassification [[autodoc]] RoFormerForTokenClassification - forward RoFormerForQuestionAnswering [[autodoc]] RoFormerForQuestionAnswering - forward
TFRoFormerModel [[autodoc]] TFRoFormerModel - call TFRoFormerForMaskedLM [[autodoc]] TFRoFormerForMaskedLM - call TFRoFormerForCausalLM [[autodoc]] TFRoFormerForCausalLM - call TFRoFormerForSequenceClassification [[autodoc]] TFRoFormerForSequenceClassification - call TFRoFormerForMultipleChoice [[autodoc]] TFRoFormerForMultipleChoice - call TFRoFormerForTokenClassification [[autodoc]] TFRoFormerForTokenClassification - call TFRoFormerForQuestionAnswering [[autodoc]] TFRoFormerForQuestionAnswering - call
FlaxRoFormerModel [[autodoc]] FlaxRoFormerModel - call FlaxRoFormerForMaskedLM [[autodoc]] FlaxRoFormerForMaskedLM - call FlaxRoFormerForSequenceClassification [[autodoc]] FlaxRoFormerForSequenceClassification - call FlaxRoFormerForMultipleChoice [[autodoc]] FlaxRoFormerForMultipleChoice - call FlaxRoFormerForTokenClassification [[autodoc]] FlaxRoFormerForTokenClassification - call FlaxRoFormerForQuestionAnswering [[autodoc]] FlaxRoFormerForQuestionAnswering - call
OWL-ViT Overview The OWL-ViT (short for Vision Transformer for Open-World Localization) was proposed in Simple Open-Vocabulary Object Detection with Vision Transformers by Matthias Minderer, Alexey Gritsenko, Austin Stone, Maxim Neumann, Dirk Weissenborn, Alexey Dosovitskiy, Aravindh Mahendran, Anurag Arnab, Mostafa Dehghani, Zhuoran Shen, Xiao Wang, Xiaohua Zhai, Thomas Kipf, and Neil Houlsby. OWL-ViT is an open-vocabulary object detection network trained on a variety of (image, text) pairs. It can be used to query an image with one or multiple text queries to search for and detect target objects described in text. The abstract from the paper is the following: Combining simple architectures with large-scale pre-training has led to massive improvements in image classification. For object detection, pre-training and scaling approaches are less well established, especially in the long-tailed and open-vocabulary setting, where training data is relatively scarce. In this paper, we propose a strong recipe for transferring image-text models to open-vocabulary object detection. We use a standard Vision Transformer architecture with minimal modifications, contrastive image-text pre-training, and end-to-end detection fine-tuning. Our analysis of the scaling properties of this setup shows that increasing image-level pre-training and model size yield consistent improvements on the downstream detection task. We provide the adaptation strategies and regularizations needed to attain very strong performance on zero-shot text-conditioned and one-shot image-conditioned object detection. Code and models are available on GitHub.
OWL-ViT architecture. Taken from the original paper. This model was contributed by adirik. The original code can be found here. Usage tips OWL-ViT is a zero-shot text-conditioned object detection model. OWL-ViT uses CLIP as its multi-modal backbone, with a ViT-like Transformer to get visual features and a causal language model to get the text features. To use CLIP for detection, OWL-ViT removes the final token pooling layer of the vision model and attaches a lightweight classification and box head to each transformer output token. Open-vocabulary classification is enabled by replacing the fixed classification layer weights with the class-name embeddings obtained from the text model. The authors first train CLIP from scratch and fine-tune it end-to-end with the classification and box heads on standard detection datasets using a bipartite matching loss. One or multiple text queries per image can be used to perform zero-shot text-conditioned object detection. [OwlViTImageProcessor] can be used to resize (or rescale) and normalize images for the model and [CLIPTokenizer] is used to encode the text. [OwlViTProcessor] wraps [OwlViTImageProcessor] and [CLIPTokenizer] into a single instance to both encode the text and prepare the images. The following example shows how to perform object detection using [OwlViTProcessor] and [OwlViTForObjectDetection]. thon
import requests from PIL import Image import torch from transformers import OwlViTProcessor, OwlViTForObjectDetection processor = OwlViTProcessor.from_pretrained("google/owlvit-base-patch32") model = OwlViTForObjectDetection.from_pretrained("google/owlvit-base-patch32") url = "http://images.cocodataset.org/val2017/000000039769.jpg" image = Image.open(requests.get(url, stream=True).raw) texts = [["a photo of a cat", "a photo of a dog"]] inputs = processor(text=texts, images=image, return_tensors="pt") outputs = model(**inputs) Target image sizes (height, width) to rescale box predictions [batch_size, 2] target_sizes = torch.Tensor([image.size[::-1]]) Convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax) results = processor.post_process_object_detection(outputs=outputs, target_sizes=target_sizes, threshold=0.1) i = 0 # Retrieve predictions for the first image for the corresponding text queries text = texts[i] boxes, scores, labels = results[i]["boxes"], results[i]["scores"], results[i]["labels"] for box, score, label in zip(boxes, scores, labels): box = [round(i, 2) for i in box.tolist()] print(f"Detected {text[label]} with confidence {round(score.item(), 3)} at location {box}") Detected a photo of a cat with confidence 0.707 at location [324.97, 20.44, 640.58, 373.29] Detected a photo of a cat with confidence 0.717 at location [1.46, 55.26, 315.55, 472.17]
Resources A demo notebook on using OWL-ViT for zero- and one-shot (image-guided) object detection can be found here. OwlViTConfig [[autodoc]] OwlViTConfig - from_text_vision_configs OwlViTTextConfig [[autodoc]] OwlViTTextConfig OwlViTVisionConfig [[autodoc]] OwlViTVisionConfig OwlViTImageProcessor [[autodoc]] OwlViTImageProcessor - preprocess - post_process_object_detection - post_process_image_guided_detection OwlViTFeatureExtractor [[autodoc]] OwlViTFeatureExtractor - call - post_process - post_process_image_guided_detection OwlViTProcessor [[autodoc]] OwlViTProcessor OwlViTModel [[autodoc]] OwlViTModel - forward - get_text_features - get_image_features OwlViTTextModel [[autodoc]] OwlViTTextModel - forward OwlViTVisionModel [[autodoc]] OwlViTVisionModel - forward OwlViTForObjectDetection [[autodoc]] OwlViTForObjectDetection - forward - image_guided_detection
RWKV Overview The RWKV model was proposed in this repo It suggests a tweak in the traditional Transformer attention to make it linear. This way, the model can be used as recurrent network: passing inputs for timestamp 0 and timestamp 1 together is the same as passing inputs at timestamp 0, then inputs at timestamp 1 along with the state of timestamp 0 (see example below). This can be more efficient than a regular Transformer and can deal with sentence of any length (even if the model uses a fixed context length for training). This model was contributed by sgugger. The original code can be found here. Usage example
import torch from transformers import AutoTokenizer, RwkvConfig, RwkvModel model = RwkvModel.from_pretrained("sgugger/rwkv-430M-pile") tokenizer = AutoTokenizer.from_pretrained("sgugger/rwkv-430M-pile") inputs = tokenizer("This is an example.", return_tensors="pt") Feed everything to the model outputs = model(inputs["input_ids"]) output_whole = outputs.last_hidden_state outputs = model(inputs["input_ids"][:, :2]) output_one = outputs.last_hidden_state Using the state computed on the first inputs, we will get the same output outputs = model(inputs["input_ids"][:, 2:], state=outputs.state) output_two = outputs.last_hidden_state torch.allclose(torch.cat([output_one, output_two], dim=1), output_whole, atol=1e-5)
If you want to make sure the model stops generating when '\n\n' is detected, we recommend using the following stopping criteria: thon from transformers import StoppingCriteria class RwkvStoppingCriteria(StoppingCriteria): def init(self, eos_sequence = [187,187], eos_token_id = 537): self.eos_sequence = eos_sequence self.eos_token_id = eos_token_id def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool: last_2_ids = input_ids[:,-2:].tolist() return self.eos_sequence in last_2_ids
output = model.generate(inputs["input_ids"], max_new_tokens=64, stopping_criteria = [RwkvStoppingCriteria()])
RwkvConfig [[autodoc]] RwkvConfig RwkvModel [[autodoc]] RwkvModel - forward RwkvLMHeadModel [[autodoc]] RwkvForCausalLM - forward Rwkv attention and the recurrent formulas In a traditional auto-regressive Transformer, attention is written as $$O = \hbox{softmax}(QK^{T} / \sqrt{d}) V$$ with \(Q\), \(K\) and \(V\) are matrices of shape seq_len x hidden_size named query, key and value (they are actually bigger matrices with a batch dimension and an attention head dimension but we're only interested in the last two, which is where the matrix product is taken, so for the sake of simplicity we only consider those two). The product \(QK^{T}\) then has shape seq_len x seq_len and we can take the matrix product with \(V\) to get the output \(O\) of the same shape as the others. Replacing the softmax by its value gives: $$O_{i} = \frac{\sum_{j=1}^{i} e^{Q_{i} K_{j}^{T} / \sqrt{d}} V_{j}}{\sum_{j=1}^{i} e^{Q_{i} K_{j}^{T} / \sqrt{d}}}$$ Note that the entries in \(QK^{T}\) corresponding to \(j > i\) are masked (the sum stops at j) because the attention is not allowed to look at future tokens (only past ones). In comparison, the RWKV attention is given by $$O_{i} = \sigma(R_{i}) \frac{\sum_{j=1}^{i} e^{W_{i-j} + K_{j}} V_{j}}{\sum_{j=1}^{i} e^{W_{i-j} + K_{j}}}$$ where \(R\) is a new matrix called receptance by the author, \(K\) and \(V\) are still the key and value (\(\sigma\) here is the sigmoid function). \(W\) is a new vector that represents the position of the token and is given by $$W_{0} = u \hbox{ and } W_{k} = (k-1)w \hbox{ for } k \geq 1$$ with \(u\) and \(w\) learnable parameters called in the code time_first and time_decay respectively. The numerator and denominator can both be expressed recursively. Naming them \(N_{i}\) and \(D_{i}\) we have: $$N_{i} = e^{u + K_{i}} V_{i} + \hat{N}{i} \hbox{ where } \hat{N}{i} = e^{K_{i-1}} V_{i-1} + e^{w + K_{i-2}} V_{i-2} \cdots + e^{(i-2)w + K_{1}} V_{1}$$ so \(\hat{N}_{i}\) (called numerator_state in the code) satisfies $$\hat{N}{0} = 0 \hbox{ and } \hat{N}{j+1} = e^{K_{j}} V_{j} + e^{w} \hat{N}_{j}$$ and $$D_{i} = e^{u + K_{i}} + \hat{D}{i} \hbox{ where } \hat{D}{i} = e^{K_{i-1}} + e^{w + K_{i-2}} \cdots + e^{(i-2)w + K_{1}}$$ so \(\hat{D}_{i}\) (called denominator_state in the code) satisfies $$\hat{D}{0} = 0 \hbox{ and } \hat{D}{j+1} = e^{K_{j}} + e^{w} \hat{D}_{j}$$ The actual recurrent formula used are a tiny bit more complex, as for numerical stability we don't want to compute exponentials of big numbers. Usually the softmax is not computed as is, but the exponential of the maximum term is divided of the numerator and denominator: $$\frac{e^{x_{i}}}{\sum_{j=1}^{n} e^{x_{j}}} = \frac{e^{x_{i} - M}}{\sum_{j=1}^{n} e^{x_{j} - M}}$$ with \(M\) the maximum of all \(x_{j}\). So here on top of saving the numerator state (\(\hat{N}\)) and the denominator state (\(\hat{D}\)) we also keep track of the maximum of all terms encountered in the exponentials. So we actually use $$\tilde{N}{i} = e^{-M{i}} \hat{N}{i} \hbox{ and } \tilde{D}{i} = e^{-M_{i}} \hat{D}_{i}$$ defined by the following recurrent formulas: $$\tilde{N}{0} = 0 \hbox{ and } \tilde{N}{j+1} = e^{K_{j} - q} V_{j} + e^{w + M_{j} - q} \tilde{N}{j} \hbox{ where } q = \max(K{j}, w + M_{j})$$ and $$\tilde{D}{0} = 0 \hbox{ and } \tilde{D}{j+1} = e^{K_{j} - q} + e^{w + M_{j} - q} \tilde{D}{j} \hbox{ where } q = \max(K{j}, w + M_{j})$$ and \(M_{j+1} = q\). With those, we can then compute $$N_{i} = e^{u + K_{i} - q} V_{i} + e^{M_{i}} \tilde{N}{i} \hbox{ where } q = \max(u + K{i}, M_{i})$$ and $$D_{i} = e^{u + K_{i} - q} + e^{M_{i}} \tilde{D}{i} \hbox{ where } q = \max(u + K{i}, M_{i})$$ which finally gives us $$O_{i} = \sigma(R_{i}) \frac{N_{i}}{D_{i}}$$
ByT5 Overview The ByT5 model was presented in ByT5: Towards a token-free future with pre-trained byte-to-byte models by Linting Xue, Aditya Barua, Noah Constant, Rami Al-Rfou, Sharan Narang, Mihir Kale, Adam Roberts, Colin Raffel. The abstract from the paper is the following: Most widely-used pre-trained language models operate on sequences of tokens corresponding to word or subword units. Encoding text as a sequence of tokens requires a tokenizer, which is typically created as an independent artifact from the model. Token-free models that instead operate directly on raw text (bytes or characters) have many benefits: they can process text in any language out of the box, they are more robust to noise, and they minimize technical debt by removing complex and error-prone text preprocessing pipelines. Since byte or character sequences are longer than token sequences, past work on token-free models has often introduced new model architectures designed to amortize the cost of operating directly on raw text. In this paper, we show that a standard Transformer architecture can be used with minimal modifications to process byte sequences. We carefully characterize the trade-offs in terms of parameter count, training FLOPs, and inference speed, and show that byte-level models are competitive with their token-level counterparts. We also demonstrate that byte-level models are significantly more robust to noise and perform better on tasks that are sensitive to spelling and pronunciation. As part of our contribution, we release a new set of pre-trained byte-level Transformer models based on the T5 architecture, as well as all code and data used in our experiments. This model was contributed by patrickvonplaten. The original code can be found here.
ByT5's architecture is based on the T5v1.1 model, refer to T5v1.1's documentation page for the API reference. They only differ in how inputs should be prepared for the model, see the code examples below. Since ByT5 was pre-trained unsupervisedly, there's no real advantage to using a task prefix during single-task fine-tuning. If you are doing multi-task fine-tuning, you should use a prefix. Usage example ByT5 works on raw UTF-8 bytes, so it can be used without a tokenizer: thon
from transformers import T5ForConditionalGeneration import torch model = T5ForConditionalGeneration.from_pretrained("google/byt5-small") num_special_tokens = 3 Model has 3 special tokens which take up the input ids 0,1,2 of ByT5. => Need to shift utf-8 character encodings by 3 before passing ids to model. input_ids = torch.tensor([list("Life is like a box of chocolates.".encode("utf-8"))]) + num_special_tokens labels = torch.tensor([list("La vie est comme une boîte de chocolat.".encode("utf-8"))]) + num_special_tokens loss = model(input_ids, labels=labels).loss loss.item() 2.66
For batched inference and training it is however recommended to make use of the tokenizer: thon
from transformers import T5ForConditionalGeneration, AutoTokenizer model = T5ForConditionalGeneration.from_pretrained("google/byt5-small") tokenizer = AutoTokenizer.from_pretrained("google/byt5-small") model_inputs = tokenizer( ["Life is like a box of chocolates.", "Today is Monday."], padding="longest", return_tensors="pt" ) labels_dict = tokenizer( ["La vie est comme une boîte de chocolat.", "Aujourd'hui c'est lundi."], padding="longest", return_tensors="pt" ) labels = labels_dict.input_ids loss = model(**model_inputs, labels=labels).loss loss.item() 17.9
Similar to T5, ByT5 was trained on the span-mask denoising task. However, since the model works directly on characters, the pretraining task is a bit different. Let's corrupt some characters of the input sentence "The dog chases a ball in the park." and ask ByT5 to predict them for us. thon
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM import torch tokenizer = AutoTokenizer.from_pretrained("google/byt5-base") model = AutoModelForSeq2SeqLM.from_pretrained("google/byt5-base") input_ids_prompt = "The dog chases a ball in the park." input_ids = tokenizer(input_ids_prompt).input_ids Note that we cannot add "{extra_id_}" to the string directly as the Byte tokenizer would incorrectly merge the tokens For ByT5, we need to work directly on the character level Contrary to T5, ByT5 does not use sentinel tokens for masking, but instead uses final utf character ids. UTF-8 is represented by 8 bits and ByT5 has 3 special tokens. => There are 2**8+2 = 259 input ids and mask tokens count down from index 258. => mask to "The dog [258]a ball [257]park." input_ids = torch.tensor([input_ids[:8] + [258] + input_ids[14:21] + [257] + input_ids[28:]]) input_ids tensor([[ 87, 107, 104, 35, 103, 114, 106, 35, 258, 35, 100, 35, 101, 100, 111, 111, 257, 35, 115, 100, 117, 110, 49, 1]]) ByT5 produces only one char at a time so we need to produce many more output characters here -> set max_length=100. output_ids = model.generate(input_ids, max_length=100)[0].tolist() output_ids [0, 258, 108, 118, 35, 119, 107, 104, 35, 114, 113, 104, 35, 122, 107, 114, 35, 103, 114, 104, 118, 257, 35, 108, 113, 35, 119, 107, 104, 35, 103, 108, 118, 102, 114, 256, 108, 113, 35, 119, 107, 104, 35, 115, 100, 117, 110, 49, 35, 87, 107, 104, 35, 103, 114, 106, 35, 108, 118, 35, 119, 107, 104, 35, 114, 113, 104, 35, 122, 107, 114, 35, 103, 114, 104, 118, 35, 100, 35, 101, 100, 111, 111, 35, 108, 113, 255, 35, 108, 113, 35, 119, 107, 104, 35, 115, 100, 117, 110, 49] ^- Note how 258 descends to 257, 256, 255 Now we need to split on the sentinel tokens, let's write a short loop for this output_ids_list = [] start_token = 0 sentinel_token = 258 while sentinel_token in output_ids: split_idx = output_ids.index(sentinel_token) output_ids_list.append(output_ids[start_token:split_idx]) start_token = split_idx sentinel_token -= 1 output_ids_list.append(output_ids[start_token:]) output_string = tokenizer.batch_decode(output_ids_list) output_string ['', 'is the one who does', ' in the disco', 'in the park. The dog is the one who does a ball in', ' in the park.']
ByT5Tokenizer [[autodoc]] ByT5Tokenizer See [ByT5Tokenizer] for all details.
FLAN-T5 Overview FLAN-T5 was released in the paper Scaling Instruction-Finetuned Language Models - it is an enhanced version of T5 that has been finetuned in a mixture of tasks. One can directly use FLAN-T5 weights without finetuning the model: thon
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer model = AutoModelForSeq2SeqLM.from_pretrained("google/flan-t5-small") tokenizer = AutoTokenizer.from_pretrained("google/flan-t5-small") inputs = tokenizer("A step by step recipe to make bolognese pasta:", return_tensors="pt") outputs = model.generate(**inputs) print(tokenizer.batch_decode(outputs, skip_special_tokens=True)) ['Pour a cup of bolognese into a large bowl and add the pasta']
FLAN-T5 includes the same improvements as T5 version 1.1 (see here for the full details of the model's improvements.) Google has released the following variants: google/flan-t5-small google/flan-t5-base google/flan-t5-large google/flan-t5-xl google/flan-t5-xxl. The original checkpoints can be found here. Refer to T5's documentation page for all API reference, code examples and notebooks. For more details regarding training and evaluation of the FLAN-T5, refer to the model card.
CTRL
Overview CTRL model was proposed in CTRL: A Conditional Transformer Language Model for Controllable Generation by Nitish Shirish Keskar, Bryan McCann, Lav R. Varshney, Caiming Xiong and Richard Socher. It's a causal (unidirectional) transformer pre-trained using language modeling on a very large corpus of ~140 GB of text data with the first token reserved as a control code (such as Links, Books, Wikipedia etc.). The abstract from the paper is the following: Large-scale language models show promising text generation capabilities, but users cannot easily control particular aspects of the generated text. We release CTRL, a 1.63 billion-parameter conditional transformer language model, trained to condition on control codes that govern style, content, and task-specific behavior. Control codes were derived from structure that naturally co-occurs with raw text, preserving the advantages of unsupervised learning while providing more explicit control over text generation. These codes also allow CTRL to predict which parts of the training data are most likely given a sequence. This provides a potential method for analyzing large amounts of data via model-based source attribution. This model was contributed by keskarnitishr. The original code can be found here. Usage tips
CTRL makes use of control codes to generate text: it requires generations to be started by certain words, sentences or links to generate coherent text. Refer to the original implementation for more information. CTRL is a model with absolute position embeddings so it's usually advised to pad the inputs on the right rather than the left. CTRL was trained with a causal language modeling (CLM) objective and is therefore powerful at predicting the next token in a sequence. Leveraging this feature allows CTRL to generate syntactically coherent text as it can be observed in the run_generation.py example script. The PyTorch models can take the past_key_values as input, which is the previously computed key/value attention pairs. TensorFlow models accepts past as input. Using the past_key_values value prevents the model from re-computing pre-computed values in the context of text generation. See the forward method for more information on the usage of this argument.
Resources Text classification task guide Causal language modeling task guide CTRLConfig [[autodoc]] CTRLConfig CTRLTokenizer [[autodoc]] CTRLTokenizer - save_vocabulary CTRLModel [[autodoc]] CTRLModel - forward CTRLLMHeadModel [[autodoc]] CTRLLMHeadModel - forward CTRLForSequenceClassification [[autodoc]] CTRLForSequenceClassification - forward
CTRLModel [[autodoc]] CTRLModel - forward CTRLLMHeadModel [[autodoc]] CTRLLMHeadModel - forward CTRLForSequenceClassification [[autodoc]] CTRLForSequenceClassification - forward TFCTRLModel [[autodoc]] TFCTRLModel - call TFCTRLLMHeadModel [[autodoc]] TFCTRLLMHeadModel - call TFCTRLForSequenceClassification [[autodoc]] TFCTRLForSequenceClassification - call
GIT Overview The GIT model was proposed in GIT: A Generative Image-to-text Transformer for Vision and Language by Jianfeng Wang, Zhengyuan Yang, Xiaowei Hu, Linjie Li, Kevin Lin, Zhe Gan, Zicheng Liu, Ce Liu, Lijuan Wang. GIT is a decoder-only Transformer that leverages CLIP's vision encoder to condition the model on vision inputs besides text. The model obtains state-of-the-art results on image captioning and visual question answering benchmarks. The abstract from the paper is the following: In this paper, we design and train a Generative Image-to-text Transformer, GIT, to unify vision-language tasks such as image/video captioning and question answering. While generative models provide a consistent network architecture between pre-training and fine-tuning, existing work typically contains complex structures (uni/multi-modal encoder/decoder) and depends on external modules such as object detectors/taggers and optical character recognition (OCR). In GIT, we simplify the architecture as one image encoder and one text decoder under a single language modeling task. We also scale up the pre-training data and the model size to boost the model performance. Without bells and whistles, our GIT establishes new state of the arts on 12 challenging benchmarks with a large margin. For instance, our model surpasses the human performance for the first time on TextCaps (138.2 vs. 125.5 in CIDEr). Furthermore, we present a new scheme of generation-based image classification and scene text recognition, achieving decent performance on standard benchmarks.
GIT architecture. Taken from the original paper. This model was contributed by nielsr. The original code can be found here. Usage tips GIT is implemented in a very similar way to GPT-2, the only difference being that the model is also conditioned on pixel_values. Resources A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with GIT.
Resources A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with GIT. Demo notebooks regarding inference + fine-tuning GIT on custom data can be found here. See also: Causal language modeling task guide
If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we will review it. The resource should ideally demonstrate something new instead of duplicating an existing resource. GitVisionConfig [[autodoc]] GitVisionConfig GitVisionModel [[autodoc]] GitVisionModel - forward GitConfig [[autodoc]] GitConfig - all GitProcessor [[autodoc]] GitProcessor - call GitModel [[autodoc]] GitModel - forward GitForCausalLM [[autodoc]] GitForCausalLM - forward
CLAP Overview The CLAP model was proposed in Large Scale Contrastive Language-Audio pretraining with feature fusion and keyword-to-caption augmentation by Yusong Wu, Ke Chen, Tianyu Zhang, Yuchen Hui, Taylor Berg-Kirkpatrick, Shlomo Dubnov. CLAP (Contrastive Language-Audio Pretraining) is a neural network trained on a variety of (audio, text) pairs. It can be instructed in to predict the most relevant text snippet, given an audio, without directly optimizing for the task. The CLAP model uses a SWINTransformer to get audio features from a log-Mel spectrogram input, and a RoBERTa model to get text features. Both the text and audio features are then projected to a latent space with identical dimension. The dot product between the projected audio and text features is then used as a similar score. The abstract from the paper is the following: Contrastive learning has shown remarkable success in the field of multimodal representation learning. In this paper, we propose a pipeline of contrastive language-audio pretraining to develop an audio representation by combining audio data with natural language descriptions. To accomplish this target, we first release LAION-Audio-630K, a large collection of 633,526 audio-text pairs from different data sources. Second, we construct a contrastive language-audio pretraining model by considering different audio encoders and text encoders. We incorporate the feature fusion mechanism and keyword-to-caption augmentation into the model design to further enable the model to process audio inputs of variable lengths and enhance the performance. Third, we perform comprehensive experiments to evaluate our model across three tasks: text-to-audio retrieval, zero-shot audio classification, and supervised audio classification. The results demonstrate that our model achieves superior performance in text-to-audio retrieval task. In audio classification tasks, the model achieves state-of-the-art performance in the zeroshot setting and is able to obtain performance comparable to models' results in the non-zero-shot setting. LAION-Audio-6 This model was contributed by Younes Belkada and Arthur Zucker . The original code can be found here. ClapConfig [[autodoc]] ClapConfig - from_text_audio_configs ClapTextConfig [[autodoc]] ClapTextConfig ClapAudioConfig [[autodoc]] ClapAudioConfig ClapFeatureExtractor [[autodoc]] ClapFeatureExtractor ClapProcessor [[autodoc]] ClapProcessor ClapModel [[autodoc]] ClapModel - forward - get_text_features - get_audio_features ClapTextModel [[autodoc]] ClapTextModel - forward ClapTextModelWithProjection [[autodoc]] ClapTextModelWithProjection - forward ClapAudioModel [[autodoc]] ClapAudioModel - forward ClapAudioModelWithProjection [[autodoc]] ClapAudioModelWithProjection - forward
CLVP Overview The CLVP (Contrastive Language-Voice Pretrained Transformer) model was proposed in Better speech synthesis through scaling by James Betker. The abstract from the paper is the following: In recent years, the field of image generation has been revolutionized by the application of autoregressive transformers and DDPMs. These approaches model the process of image generation as a step-wise probabilistic processes and leverage large amounts of compute and data to learn the image distribution. This methodology of improving performance need not be confined to images. This paper describes a way to apply advances in the image generative domain to speech synthesis. The result is TorToise - an expressive, multi-voice text-to-speech system. This model was contributed by Susnato Dhar. The original code can be found here. Usage tips
CLVP is an integral part of the Tortoise TTS model. CLVP can be used to compare different generated speech candidates with the provided text, and the best speech tokens are forwarded to the diffusion model. The use of the [ClvpModelForConditionalGeneration.generate()] method is strongly recommended for tortoise usage. Note that the CLVP model expects the audio to be sampled at 22.05 kHz contrary to other audio models which expects 16 kHz. Brief Explanation:
The [ClvpTokenizer] tokenizes the text input, and the [ClvpFeatureExtractor] extracts the log mel-spectrogram from the desired audio. [ClvpConditioningEncoder] takes those text tokens and audio representations and converts them into embeddings conditioned on the text and audio. The [ClvpForCausalLM] uses those embeddings to generate multiple speech candidates. Each speech candidate is passed through the speech encoder ([ClvpEncoder]) which converts them into a vector representation, and the text encoder ([ClvpEncoder]) converts the text tokens into the same latent space. At the end, we compare each speech vector with the text vector to see which speech vector is most similar to the text vector. [ClvpModelForConditionalGeneration.generate()] compresses all of the logic described above into a single method.
Example : thon
import datasets from transformers import ClvpProcessor, ClvpModelForConditionalGeneration Define the Text and Load the Audio (We are taking an audio example from HuggingFace Hub using datasets library). text = "This is an example text." ds = datasets.load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") ds = ds.cast_column("audio", datasets.Audio(sampling_rate=22050)) sample = ds[0]["audio"] Define processor and model. processor = ClvpProcessor.from_pretrained("susnato/clvp_dev") model = ClvpModelForConditionalGeneration.from_pretrained("susnato/clvp_dev") Generate processor output and model output. processor_output = processor(raw_speech=sample["array"], sampling_rate=sample["sampling_rate"], text=text, return_tensors="pt") generated_output = model.generate(**processor_output)
ClvpConfig [[autodoc]] ClvpConfig - from_sub_model_configs ClvpEncoderConfig [[autodoc]] ClvpEncoderConfig ClvpDecoderConfig [[autodoc]] ClvpDecoderConfig ClvpTokenizer [[autodoc]] ClvpTokenizer - save_vocabulary ClvpFeatureExtractor [[autodoc]] ClvpFeatureExtractor - call ClvpProcessor [[autodoc]] ClvpProcessor - call - decode - batch_decode ClvpModelForConditionalGeneration [[autodoc]] ClvpModelForConditionalGeneration - forward - generate - get_text_features - get_speech_features ClvpForCausalLM [[autodoc]] ClvpForCausalLM ClvpModel [[autodoc]] ClvpModel ClvpEncoder [[autodoc]] ClvpEncoder ClvpDecoder [[autodoc]] ClvpDecoder
DETR Overview The DETR model was proposed in End-to-End Object Detection with Transformers by Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov and Sergey Zagoruyko. DETR consists of a convolutional backbone followed by an encoder-decoder Transformer which can be trained end-to-end for object detection. It greatly simplifies a lot of the complexity of models like Faster-R-CNN and Mask-R-CNN, which use things like region proposals, non-maximum suppression procedure and anchor generation. Moreover, DETR can also be naturally extended to perform panoptic segmentation, by simply adding a mask head on top of the decoder outputs. The abstract from the paper is the following: We present a new method that views object detection as a direct set prediction problem. Our approach streamlines the detection pipeline, effectively removing the need for many hand-designed components like a non-maximum suppression procedure or anchor generation that explicitly encode our prior knowledge about the task. The main ingredients of the new framework, called DEtection TRansformer or DETR, are a set-based global loss that forces unique predictions via bipartite matching, and a transformer encoder-decoder architecture. Given a fixed small set of learned object queries, DETR reasons about the relations of the objects and the global image context to directly output the final set of predictions in parallel. The new model is conceptually simple and does not require a specialized library, unlike many other modern detectors. DETR demonstrates accuracy and run-time performance on par with the well-established and highly-optimized Faster RCNN baseline on the challenging COCO object detection dataset. Moreover, DETR can be easily generalized to produce panoptic segmentation in a unified manner. We show that it significantly outperforms competitive baselines. This model was contributed by nielsr. The original code can be found here. How DETR works Here's a TLDR explaining how [~transformers.DetrForObjectDetection] works: First, an image is sent through a pre-trained convolutional backbone (in the paper, the authors use ResNet-50/ResNet-101). Let's assume we also add a batch dimension. This means that the input to the backbone is a tensor of shape (batch_size, 3, height, width), assuming the image has 3 color channels (RGB). The CNN backbone outputs a new lower-resolution feature map, typically of shape (batch_size, 2048, height/32, width/32). This is then projected to match the hidden dimension of the Transformer of DETR, which is 256 by default, using a nn.Conv2D layer. So now, we have a tensor of shape (batch_size, 256, height/32, width/32). Next, the feature map is flattened and transposed to obtain a tensor of shape (batch_size, seq_len, d_model) = (batch_size, width/32*height/32, 256). So a difference with NLP models is that the sequence length is actually longer than usual, but with a smaller d_model (which in NLP is typically 768 or higher). Next, this is sent through the encoder, outputting encoder_hidden_states of the same shape (you can consider these as image features). Next, so-called object queries are sent through the decoder. This is a tensor of shape (batch_size, num_queries, d_model), with num_queries typically set to 100 and initialized with zeros. These input embeddings are learnt positional encodings that the authors refer to as object queries, and similarly to the encoder, they are added to the input of each attention layer. Each object query will look for a particular object in the image. The decoder updates these embeddings through multiple self-attention and encoder-decoder attention layers to output decoder_hidden_states of the same shape: (batch_size, num_queries, d_model). Next, two heads are added on top for object detection: a linear layer for classifying each object query into one of the objects or "no object", and a MLP to predict bounding boxes for each query. The model is trained using a bipartite matching loss: so what we actually do is compare the predicted classes + bounding boxes of each of the N = 100 object queries to the ground truth annotations, padded up to the same length N (so if an image only contains 4 objects, 96 annotations will just have a "no object" as class and "no bounding box" as bounding box). The Hungarian matching algorithm is used to find an optimal one-to-one mapping of each of the N queries to each of the N annotations. Next, standard cross-entropy (for the classes) and a linear combination of the L1 and generalized IoU loss (for the bounding boxes) are used to optimize the parameters of the model. DETR can be naturally extended to perform panoptic segmentation (which unifies semantic segmentation and instance segmentation). [~transformers.DetrForSegmentation] adds a segmentation mask head on top of [~transformers.DetrForObjectDetection]. The mask head can be trained either jointly, or in a two steps process, where one first trains a [~transformers.DetrForObjectDetection] model to detect bounding boxes around both "things" (instances) and "stuff" (background things like trees, roads, sky), then freeze all the weights and train only the mask head for 25 epochs. Experimentally, these two approaches give similar results. Note that predicting boxes is required for the training to be possible, since the Hungarian matching is computed using distances between boxes. Usage tips
DETR uses so-called object queries to detect objects in an image. The number of queries determines the maximum number of objects that can be detected in a single image, and is set to 100 by default (see parameter num_queries of [~transformers.DetrConfig]). Note that it's good to have some slack (in COCO, the authors used 100, while the maximum number of objects in a COCO image is ~70). The decoder of DETR updates the query embeddings in parallel. This is different from language models like GPT-2, which use autoregressive decoding instead of parallel. Hence, no causal attention mask is used. DETR adds position embeddings to the hidden states at each self-attention and cross-attention layer before projecting to queries and keys. For the position embeddings of the image, one can choose between fixed sinusoidal or learned absolute position embeddings. By default, the parameter position_embedding_type of [~transformers.DetrConfig] is set to "sine". During training, the authors of DETR did find it helpful to use auxiliary losses in the decoder, especially to help the model output the correct number of objects of each class. If you set the parameter auxiliary_loss of [~transformers.DetrConfig] to True, then prediction feedforward neural networks and Hungarian losses are added after each decoder layer (with the FFNs sharing parameters). If you want to train the model in a distributed environment across multiple nodes, then one should update the num_boxes variable in the DetrLoss class of modeling_detr.py. When training on multiple nodes, this should be set to the average number of target boxes across all nodes, as can be seen in the original implementation here. [~transformers.DetrForObjectDetection] and [~transformers.DetrForSegmentation] can be initialized with any convolutional backbone available in the timm library. Initializing with a MobileNet backbone for example can be done by setting the backbone attribute of [~transformers.DetrConfig] to "tf_mobilenetv3_small_075", and then initializing the model with that config. DETR resizes the input images such that the shortest side is at least a certain amount of pixels while the longest is at most 1333 pixels. At training time, scale augmentation is used such that the shortest side is randomly set to at least 480 and at most 800 pixels. At inference time, the shortest side is set to 800. One can use [~transformers.DetrImageProcessor] to prepare images (and optional annotations in COCO format) for the model. Due to this resizing, images in a batch can have different sizes. DETR solves this by padding images up to the largest size in a batch, and by creating a pixel mask that indicates which pixels are real/which are padding. Alternatively, one can also define a custom collate_fn in order to batch images together, using [~transformers.DetrImageProcessor.pad_and_create_pixel_mask]. The size of the images will determine the amount of memory being used, and will thus determine the batch_size. It is advised to use a batch size of 2 per GPU. See this Github thread for more info.
There are three ways to instantiate a DETR model (depending on what you prefer): Option 1: Instantiate DETR with pre-trained weights for entire model from transformers import DetrForObjectDetection model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50") Option 2: Instantiate DETR with randomly initialized weights for Transformer, but pre-trained weights for backbone
Option 2: Instantiate DETR with randomly initialized weights for Transformer, but pre-trained weights for backbone from transformers import DetrConfig, DetrForObjectDetection config = DetrConfig() model = DetrForObjectDetection(config) Option 3: Instantiate DETR with randomly initialized weights for backbone + Transformerpy config = DetrConfig(use_pretrained_backbone=False) model = DetrForObjectDetection(config)
As a summary, consider the following table: | Task | Object detection | Instance segmentation | Panoptic segmentation | |------|------------------|-----------------------|-----------------------| | Description | Predicting bounding boxes and class labels around objects in an image | Predicting masks around objects (i.e. instances) in an image | Predicting masks around both objects (i.e. instances) as well as "stuff" (i.e. background things like trees and roads) in an image | | Model | [~transformers.DetrForObjectDetection] | [~transformers.DetrForSegmentation] | [~transformers.DetrForSegmentation] | | Example dataset | COCO detection | COCO detection, COCO panoptic | COCO panoptic | | | Format of annotations to provide to [~transformers.DetrImageProcessor] | {'image_id': int, 'annotations': List[Dict]} each Dict being a COCO object annotation | {'image_id': int, 'annotations': List[Dict]} (in case of COCO detection) or {'file_name': str, 'image_id': int, 'segments_info': List[Dict]} (in case of COCO panoptic) | {'file_name': str, 'image_id': int, 'segments_info': List[Dict]} and masks_path (path to directory containing PNG files of the masks) | | Postprocessing (i.e. converting the output of the model to Pascal VOC format) | [~transformers.DetrImageProcessor.post_process] | [~transformers.DetrImageProcessor.post_process_segmentation] | [~transformers.DetrImageProcessor.post_process_segmentation], [~transformers.DetrImageProcessor.post_process_panoptic] | | evaluators | CocoEvaluator with iou_types="bbox" | CocoEvaluator with iou_types="bbox" or "segm" | CocoEvaluator with iou_tupes="bbox" or "segm", PanopticEvaluator | In short, one should prepare the data either in COCO detection or COCO panoptic format, then use [~transformers.DetrImageProcessor] to create pixel_values, pixel_mask and optional labels, which can then be used to train (or fine-tune) a model. For evaluation, one should first convert the outputs of the model using one of the postprocessing methods of [~transformers.DetrImageProcessor]. These can be be provided to either CocoEvaluator or PanopticEvaluator, which allow you to calculate metrics like mean Average Precision (mAP) and Panoptic Quality (PQ). The latter objects are implemented in the original repository. See the example notebooks for more info regarding evaluation. Resources A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with DETR.
All example notebooks illustrating fine-tuning [DetrForObjectDetection] and [DetrForSegmentation] on a custom dataset an be found here. See also: Object detection task guide
If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. DetrConfig [[autodoc]] DetrConfig DetrImageProcessor [[autodoc]] DetrImageProcessor - preprocess - post_process_object_detection - post_process_semantic_segmentation - post_process_instance_segmentation - post_process_panoptic_segmentation DetrFeatureExtractor [[autodoc]] DetrFeatureExtractor - call - post_process_object_detection - post_process_semantic_segmentation - post_process_instance_segmentation - post_process_panoptic_segmentation DETR specific outputs [[autodoc]] models.detr.modeling_detr.DetrModelOutput [[autodoc]] models.detr.modeling_detr.DetrObjectDetectionOutput [[autodoc]] models.detr.modeling_detr.DetrSegmentationOutput DetrModel [[autodoc]] DetrModel - forward DetrForObjectDetection [[autodoc]] DetrForObjectDetection - forward DetrForSegmentation [[autodoc]] DetrForSegmentation - forward
XLNet
Overview The XLNet model was proposed in XLNet: Generalized Autoregressive Pretraining for Language Understanding by Zhilin Yang, Zihang Dai, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le. XLnet is an extension of the Transformer-XL model pre-trained using an autoregressive method to learn bidirectional contexts by maximizing the expected likelihood over all permutations of the input sequence factorization order. The abstract from the paper is the following: With the capability of modeling bidirectional contexts, denoising autoencoding based pretraining like BERT achieves better performance than pretraining approaches based on autoregressive language modeling. However, relying on corrupting the input with masks, BERT neglects dependency between the masked positions and suffers from a pretrain-finetune discrepancy. In light of these pros and cons, we propose XLNet, a generalized autoregressive pretraining method that (1) enables learning bidirectional contexts by maximizing the expected likelihood over all permutations of the factorization order and (2) overcomes the limitations of BERT thanks to its autoregressive formulation. Furthermore, XLNet integrates ideas from Transformer-XL, the state-of-the-art autoregressive model, into pretraining. Empirically, under comparable experiment settings, XLNet outperforms BERT on 20 tasks, often by a large margin, including question answering, natural language inference, sentiment analysis, and document ranking. This model was contributed by thomwolf. The original code can be found here. Usage tips
The specific attention pattern can be controlled at training and test time using the perm_mask input. Due to the difficulty of training a fully auto-regressive model over various factorization order, XLNet is pretrained using only a sub-set of the output tokens as target which are selected with the target_mapping input. To use XLNet for sequential decoding (i.e. not in fully bi-directional setting), use the perm_mask and target_mapping inputs to control the attention span and outputs (see examples in examples/pytorch/text-generation/run_generation.py) XLNet is one of the few models that has no sequence length limit. XLNet is not a traditional autoregressive model but uses a training strategy that builds on that. It permutes the tokens in the sentence, then allows the model to use the last n tokens to predict the token n+1. Since this is all done with a mask, the sentence is actually fed in the model in the right order, but instead of masking the first n tokens for n+1, XLNet uses a mask that hides the previous tokens in some given permutation of 1,…,sequence length. XLNet also uses the same recurrence mechanism as Transformer-XL to build long-term dependencies.
Resources Text classification task guide Token classification task guide Question answering task guide Causal language modeling task guide Multiple choice task guide
XLNetConfig [[autodoc]] XLNetConfig XLNetTokenizer [[autodoc]] XLNetTokenizer - build_inputs_with_special_tokens - get_special_tokens_mask - create_token_type_ids_from_sequences - save_vocabulary XLNetTokenizerFast [[autodoc]] XLNetTokenizerFast XLNet specific outputs [[autodoc]] models.xlnet.modeling_xlnet.XLNetModelOutput [[autodoc]] models.xlnet.modeling_xlnet.XLNetLMHeadModelOutput [[autodoc]] models.xlnet.modeling_xlnet.XLNetForSequenceClassificationOutput [[autodoc]] models.xlnet.modeling_xlnet.XLNetForMultipleChoiceOutput [[autodoc]] models.xlnet.modeling_xlnet.XLNetForTokenClassificationOutput [[autodoc]] models.xlnet.modeling_xlnet.XLNetForQuestionAnsweringSimpleOutput [[autodoc]] models.xlnet.modeling_xlnet.XLNetForQuestionAnsweringOutput [[autodoc]] models.xlnet.modeling_tf_xlnet.TFXLNetModelOutput [[autodoc]] models.xlnet.modeling_tf_xlnet.TFXLNetLMHeadModelOutput [[autodoc]] models.xlnet.modeling_tf_xlnet.TFXLNetForSequenceClassificationOutput [[autodoc]] models.xlnet.modeling_tf_xlnet.TFXLNetForMultipleChoiceOutput [[autodoc]] models.xlnet.modeling_tf_xlnet.TFXLNetForTokenClassificationOutput [[autodoc]] models.xlnet.modeling_tf_xlnet.TFXLNetForQuestionAnsweringSimpleOutput