text
stringlengths
2
11.8k
from transformers import MBartForConditionalGeneration, MBartTokenizer tokenizer = MBartTokenizer.from_pretrained("facebook/mbart-large-en-ro", src_lang="en_XX") article = "UN Chief Says There Is No Military Solution in Syria" inputs = tokenizer(article, return_tensors="pt") translated_tokens = model.generate(**inputs, decoder_start_token_id=tokenizer.lang_code_to_id["ro_RO"]) tokenizer.batch_decode(translated_tokens, skip_special_tokens=True)[0] "Şeful ONU declară că nu există o soluţie militară în Siria"
Overview of MBart-50 MBart-50 was introduced in the Multilingual Translation with Extensible Multilingual Pretraining and Finetuning paper by Yuqing Tang, Chau Tran, Xian Li, Peng-Jen Chen, Naman Goyal, Vishrav Chaudhary, Jiatao Gu, Angela Fan. MBart-50 is created using the original mbart-large-cc25 checkpoint by extendeding its embedding layers with randomly initialized vectors for an extra set of 25 language tokens and then pretrained on 50 languages. According to the abstract Multilingual translation models can be created through multilingual finetuning. Instead of finetuning on one direction, a pretrained model is finetuned on many directions at the same time. It demonstrates that pretrained models can be extended to incorporate additional languages without loss of performance. Multilingual finetuning improves on average 1 BLEU over the strongest baselines (being either multilingual from scratch or bilingual finetuning) while improving 9.3 BLEU on average over bilingual baselines from scratch. Training of MBart-50 The text format for MBart-50 is slightly different from mBART. For MBart-50 the language id token is used as a prefix for both source and target text i.e the text format is [lang_code] X [eos], where lang_code is source language id for source text and target language id for target text, with X being the source or target text respectively. MBart-50 has its own tokenizer [MBart50Tokenizer].
Supervised training
thon from transformers import MBartForConditionalGeneration, MBart50TokenizerFast model = MBartForConditionalGeneration.from_pretrained("facebook/mbart-large-50") tokenizer = MBart50TokenizerFast.from_pretrained("facebook/mbart-large-50", src_lang="en_XX", tgt_lang="ro_RO") src_text = " UN Chief Says There Is No Military Solution in Syria" tgt_text = "Şeful ONU declară că nu există o soluţie militară în Siria" model_inputs = tokenizer(src_text, text_target=tgt_text, return_tensors="pt") model(**model_inputs) # forward pass
Generation
To generate using the mBART-50 multilingual translation models, eos_token_id is used as the decoder_start_token_id and the target language id is forced as the first generated token. To force the target language id as the first generated token, pass the forced_bos_token_id parameter to the generate method. The following example shows how to translate between Hindi to French and Arabic to English using the facebook/mbart-50-large-many-to-many checkpoint. thon from transformers import MBartForConditionalGeneration, MBart50TokenizerFast article_hi = "संयुक्त राष्ट्र के प्रमुख का कहना है कि सीरिया में कोई सैन्य समाधान नहीं है" article_ar = "الأمين العام للأمم المتحدة يقول إنه لا يوجد حل عسكري في سوريا." model = MBartForConditionalGeneration.from_pretrained("facebook/mbart-large-50-many-to-many-mmt") tokenizer = MBart50TokenizerFast.from_pretrained("facebook/mbart-large-50-many-to-many-mmt") translate Hindi to French tokenizer.src_lang = "hi_IN" encoded_hi = tokenizer(article_hi, return_tensors="pt") generated_tokens = model.generate(**encoded_hi, forced_bos_token_id=tokenizer.lang_code_to_id["fr_XX"]) tokenizer.batch_decode(generated_tokens, skip_special_tokens=True) => "Le chef de l 'ONU affirme qu 'il n 'y a pas de solution militaire en Syria." translate Arabic to English tokenizer.src_lang = "ar_AR" encoded_ar = tokenizer(article_ar, return_tensors="pt") generated_tokens = model.generate(**encoded_ar, forced_bos_token_id=tokenizer.lang_code_to_id["en_XX"]) tokenizer.batch_decode(generated_tokens, skip_special_tokens=True) => "The Secretary-General of the United Nations says there is no military solution in Syria."
Documentation resources Text classification task guide Question answering task guide Causal language modeling task guide Masked language modeling task guide Translation task guide Summarization task guide MBartConfig [[autodoc]] MBartConfig MBartTokenizer [[autodoc]] MBartTokenizer - build_inputs_with_special_tokens MBartTokenizerFast [[autodoc]] MBartTokenizerFast MBart50Tokenizer [[autodoc]] MBart50Tokenizer MBart50TokenizerFast [[autodoc]] MBart50TokenizerFast
MBartModel [[autodoc]] MBartModel MBartForConditionalGeneration [[autodoc]] MBartForConditionalGeneration MBartForQuestionAnswering [[autodoc]] MBartForQuestionAnswering MBartForSequenceClassification [[autodoc]] MBartForSequenceClassification MBartForCausalLM [[autodoc]] MBartForCausalLM - forward TFMBartModel [[autodoc]] TFMBartModel - call TFMBartForConditionalGeneration [[autodoc]] TFMBartForConditionalGeneration - call
FlaxMBartModel [[autodoc]] FlaxMBartModel - call - encode - decode FlaxMBartForConditionalGeneration [[autodoc]] FlaxMBartForConditionalGeneration - call - encode - decode FlaxMBartForSequenceClassification [[autodoc]] FlaxMBartForSequenceClassification - call - encode - decode FlaxMBartForQuestionAnswering [[autodoc]] FlaxMBartForQuestionAnswering - call - encode - decode
Whisper Overview The Whisper model was proposed in Robust Speech Recognition via Large-Scale Weak Supervision by Alec Radford, Jong Wook Kim, Tao Xu, Greg Brockman, Christine McLeavey, Ilya Sutskever. The abstract from the paper is the following: We study the capabilities of speech processing systems trained simply to predict large amounts of transcripts of audio on the internet. When scaled to 680,000 hours of multilingual and multitask supervision, the resulting models generalize well to standard benchmarks and are often competitive with prior fully supervised results but in a zeroshot transfer setting without the need for any finetuning. When compared to humans, the models approach their accuracy and robustness. We are releasing models and inference code to serve as a foundation for further work on robust speech processing. This model was contributed by Arthur Zucker. The Tensorflow version of this model was contributed by amyeroberts. The original code can be found here. Usage tips
The model usually performs well without requiring any finetuning. The architecture follows a classic encoder-decoder architecture, which means that it relies on the [~generation.GenerationMixin.generate] function for inference. One can use [WhisperProcessor] to prepare audio for the model, and decode the predicted ID's back into text. To convert the model and the processor, we recommend using the following:
python src/transformers/models/whisper/convert_openai_to_hf.py --checkpoint_path "" --pytorch_dump_folder_path "Arthur/whisper-3" --convert_preprocessor True The script will automatically determine all necessary parameters from the OpenAI checkpoint. A tiktoken library needs to be installed to perform the conversion of the OpenAI tokenizer to the tokenizers version. Inference Here is a step-by-step guide to transcribing an audio sample using a pre-trained Whisper model: thon
from datasets import load_dataset from transformers import WhisperProcessor, WhisperForConditionalGeneration Select an audio file and read it: ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") audio_sample = ds[0]["audio"] waveform = audio_sample["array"] sampling_rate = audio_sample["sampling_rate"] Load the Whisper model in Hugging Face format: processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en") model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en") Use the model and processor to transcribe the audio: input_features = processor( waveform, sampling_rate=sampling_rate, return_tensors="pt" ).input_features Generate token ids predicted_ids = model.generate(input_features) Decode token ids to text transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True) transcription[0] ' Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'
Resources A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with Whisper. 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. A fork with a script to convert a Whisper model in Hugging Face format to OpenAI format. 🌎 Usage example:
A fork with a script to convert a Whisper model in Hugging Face format to OpenAI format. 🌎 Usage example: pip install -U openai-whisper python convert_hf_to_openai.py \ --checkpoint openai/whisper-tiny \ --whisper_dump_path whisper-tiny-openai.pt
WhisperConfig [[autodoc]] WhisperConfig WhisperTokenizer [[autodoc]] WhisperTokenizer - set_prefix_tokens - build_inputs_with_special_tokens - get_special_tokens_mask - create_token_type_ids_from_sequences - save_vocabulary - batch_decode - decode - basic_normalize - normalize WhisperTokenizerFast [[autodoc]] WhisperTokenizerFast - set_prefix_tokens - build_inputs_with_special_tokens - get_special_tokens_mask - create_token_type_ids_from_sequences - save_vocabulary - batch_decode - decode - basic_normalize - normalize WhisperFeatureExtractor [[autodoc]] WhisperFeatureExtractor - call WhisperProcessor [[autodoc]] WhisperProcessor - call - from_pretrained - save_pretrained - batch_decode - decode
WhisperModel [[autodoc]] WhisperModel - forward - _mask_input_features WhisperForConditionalGeneration [[autodoc]] WhisperForConditionalGeneration - forward - generate WhisperForCausalLM [[autodoc]] WhisperForCausalLM - forward WhisperForAudioClassification [[autodoc]] WhisperForAudioClassification - forward TFWhisperModel [[autodoc]] TFWhisperModel - call TFWhisperForConditionalGeneration [[autodoc]] TFWhisperForConditionalGeneration - call
TFWhisperModel [[autodoc]] TFWhisperModel - call TFWhisperForConditionalGeneration [[autodoc]] TFWhisperForConditionalGeneration - call FlaxWhisperModel [[autodoc]] FlaxWhisperModel - call FlaxWhisperForConditionalGeneration [[autodoc]] FlaxWhisperForConditionalGeneration - call FlaxWhisperForAudioClassification [[autodoc]] FlaxWhisperForAudioClassification - call
LayoutLMv3 Overview The LayoutLMv3 model was proposed in LayoutLMv3: Pre-training for Document AI with Unified Text and Image Masking by Yupan Huang, Tengchao Lv, Lei Cui, Yutong Lu, Furu Wei. LayoutLMv3 simplifies LayoutLMv2 by using patch embeddings (as in ViT) instead of leveraging a CNN backbone, and pre-trains the model on 3 objectives: masked language modeling (MLM), masked image modeling (MIM) and word-patch alignment (WPA). The abstract from the paper is the following: Self-supervised pre-training techniques have achieved remarkable progress in Document AI. Most multimodal pre-trained models use a masked language modeling objective to learn bidirectional representations on the text modality, but they differ in pre-training objectives for the image modality. This discrepancy adds difficulty to multimodal representation learning. In this paper, we propose LayoutLMv3 to pre-train multimodal Transformers for Document AI with unified text and image masking. Additionally, LayoutLMv3 is pre-trained with a word-patch alignment objective to learn cross-modal alignment by predicting whether the corresponding image patch of a text word is masked. The simple unified architecture and training objectives make LayoutLMv3 a general-purpose pre-trained model for both text-centric and image-centric Document AI tasks. Experimental results show that LayoutLMv3 achieves state-of-the-art performance not only in text-centric tasks, including form understanding, receipt understanding, and document visual question answering, but also in image-centric tasks such as document image classification and document layout analysis.
LayoutLMv3 architecture. Taken from the original paper. This model was contributed by nielsr. The TensorFlow version of this model was added by chriskoo, tokec, and lre. The original code can be found here. Usage tips
In terms of data processing, LayoutLMv3 is identical to its predecessor LayoutLMv2, except that: images need to be resized and normalized with channels in regular RGB format. LayoutLMv2 on the other hand normalizes the images internally and expects the channels in BGR format. text is tokenized using byte-pair encoding (BPE), as opposed to WordPiece. Due to these differences in data preprocessing, one can use [LayoutLMv3Processor] which internally combines a [LayoutLMv3ImageProcessor] (for the image modality) and a [LayoutLMv3Tokenizer]/[LayoutLMv3TokenizerFast] (for the text modality) to prepare all data for the model.
Regarding usage of [LayoutLMv3Processor], we refer to the usage guide of its predecessor. Resources A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with LayoutLMv3. 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.
LayoutLMv3 is nearly identical to LayoutLMv2, so we've also included LayoutLMv2 resources you can adapt for LayoutLMv3 tasks. For these notebooks, take care to use [LayoutLMv2Processor] instead when preparing data for the model! Demo notebooks for LayoutLMv3 can be found here. Demo scripts can be found here. [LayoutLMv2ForSequenceClassification] is supported by this notebook. Text classification task guide
[LayoutLMv2ForSequenceClassification] is supported by this notebook. Text classification task guide [LayoutLMv3ForTokenClassification] is supported by this example script and notebook. A notebook for how to perform inference with [LayoutLMv2ForTokenClassification] and a notebook for how to perform inference when no labels are available with [LayoutLMv2ForTokenClassification]. A notebook for how to finetune [LayoutLMv2ForTokenClassification] with the 🤗 Trainer. Token classification task guide
[LayoutLMv2ForQuestionAnswering] is supported by this notebook. Question answering task guide
Document question answering - Document question answering task guide LayoutLMv3Config [[autodoc]] LayoutLMv3Config LayoutLMv3FeatureExtractor [[autodoc]] LayoutLMv3FeatureExtractor - call LayoutLMv3ImageProcessor [[autodoc]] LayoutLMv3ImageProcessor - preprocess LayoutLMv3Tokenizer [[autodoc]] LayoutLMv3Tokenizer - call - save_vocabulary LayoutLMv3TokenizerFast [[autodoc]] LayoutLMv3TokenizerFast - call LayoutLMv3Processor [[autodoc]] LayoutLMv3Processor - call
LayoutLMv3Model [[autodoc]] LayoutLMv3Model - forward LayoutLMv3ForSequenceClassification [[autodoc]] LayoutLMv3ForSequenceClassification - forward LayoutLMv3ForTokenClassification [[autodoc]] LayoutLMv3ForTokenClassification - forward LayoutLMv3ForQuestionAnswering [[autodoc]] LayoutLMv3ForQuestionAnswering - forward
TFLayoutLMv3Model [[autodoc]] TFLayoutLMv3Model - call TFLayoutLMv3ForSequenceClassification [[autodoc]] TFLayoutLMv3ForSequenceClassification - call TFLayoutLMv3ForTokenClassification [[autodoc]] TFLayoutLMv3ForTokenClassification - call TFLayoutLMv3ForQuestionAnswering [[autodoc]] TFLayoutLMv3ForQuestionAnswering - call
Deformable DETR Overview The Deformable DETR model was proposed in Deformable DETR: Deformable Transformers for End-to-End Object Detection by Xizhou Zhu, Weijie Su, Lewei Lu, Bin Li, Xiaogang Wang, Jifeng Dai. Deformable DETR mitigates the slow convergence issues and limited feature spatial resolution of the original DETR by leveraging a new deformable attention module which only attends to a small set of key sampling points around a reference. The abstract from the paper is the following: DETR has been recently proposed to eliminate the need for many hand-designed components in object detection while demonstrating good performance. However, it suffers from slow convergence and limited feature spatial resolution, due to the limitation of Transformer attention modules in processing image feature maps. To mitigate these issues, we proposed Deformable DETR, whose attention modules only attend to a small set of key sampling points around a reference. Deformable DETR can achieve better performance than DETR (especially on small objects) with 10 times less training epochs. Extensive experiments on the COCO benchmark demonstrate the effectiveness of our approach.
Deformable DETR architecture. Taken from the original paper. This model was contributed by nielsr. The original code can be found here. Usage tips Training Deformable DETR is equivalent to training the original DETR model. See the resources section below for demo notebooks. Resources A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with Deformable DETR.
Resources A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with Deformable DETR. Demo notebooks regarding inference + fine-tuning on a custom dataset for [DeformableDetrForObjectDetection] can 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. DeformableDetrImageProcessor [[autodoc]] DeformableDetrImageProcessor - preprocess - post_process_object_detection DeformableDetrFeatureExtractor [[autodoc]] DeformableDetrFeatureExtractor - call - post_process_object_detection DeformableDetrConfig [[autodoc]] DeformableDetrConfig DeformableDetrModel [[autodoc]] DeformableDetrModel - forward DeformableDetrForObjectDetection [[autodoc]] DeformableDetrForObjectDetection - forward
BLIP Overview The BLIP model was proposed in BLIP: Bootstrapping Language-Image Pre-training for Unified Vision-Language Understanding and Generation by Junnan Li, Dongxu Li, Caiming Xiong, Steven Hoi. BLIP is a model that is able to perform various multi-modal tasks including: - Visual Question Answering - Image-Text retrieval (Image-text matching) - Image Captioning The abstract from the paper is the following: Vision-Language Pre-training (VLP) has advanced the performance for many vision-language tasks. However, most existing pre-trained models only excel in either understanding-based tasks or generation-based tasks. Furthermore, performance improvement has been largely achieved by scaling up the dataset with noisy image-text pairs collected from the web, which is a suboptimal source of supervision. In this paper, we propose BLIP, a new VLP framework which transfers flexibly to both vision-language understanding and generation tasks. BLIP effectively utilizes the noisy web data by bootstrapping the captions, where a captioner generates synthetic captions and a filter removes the noisy ones. We achieve state-of-the-art results on a wide range of vision-language tasks, such as image-text retrieval (+2.7% in average recall@1), image captioning (+2.8% in CIDEr), and VQA (+1.6% in VQA score). BLIP also demonstrates strong generalization ability when directly transferred to videolanguage tasks in a zero-shot manner. Code, models, and datasets are released.
This model was contributed by ybelkada. The original code can be found here. Resources Jupyter notebook on how to fine-tune BLIP for image captioning on a custom dataset BlipConfig [[autodoc]] BlipConfig - from_text_vision_configs BlipTextConfig [[autodoc]] BlipTextConfig BlipVisionConfig [[autodoc]] BlipVisionConfig BlipProcessor [[autodoc]] BlipProcessor BlipImageProcessor [[autodoc]] BlipImageProcessor - preprocess
BlipModel [[autodoc]] BlipModel - forward - get_text_features - get_image_features BlipTextModel [[autodoc]] BlipTextModel - forward BlipVisionModel [[autodoc]] BlipVisionModel - forward BlipForConditionalGeneration [[autodoc]] BlipForConditionalGeneration - forward BlipForImageTextRetrieval [[autodoc]] BlipForImageTextRetrieval - forward BlipForQuestionAnswering [[autodoc]] BlipForQuestionAnswering - forward
TFBlipModel [[autodoc]] TFBlipModel - call - get_text_features - get_image_features TFBlipTextModel [[autodoc]] TFBlipTextModel - call TFBlipVisionModel [[autodoc]] TFBlipVisionModel - call TFBlipForConditionalGeneration [[autodoc]] TFBlipForConditionalGeneration - call TFBlipForImageTextRetrieval [[autodoc]] TFBlipForImageTextRetrieval - call TFBlipForQuestionAnswering [[autodoc]] TFBlipForQuestionAnswering - call
Persimmon Overview The Persimmon model was created by ADEPT, and authored by Erich Elsen, Augustus Odena, Maxwell Nye, Sağnak Taşırlar, Tri Dao, Curtis Hawthorne, Deepak Moparthi, Arushi Somani. The authors introduced Persimmon-8B, a decoder model based on the classic transformers architecture, with query and key normalization. Persimmon-8B is a fully permissively-licensed model with approximately 8 billion parameters, released under the Apache license. Some of the key attributes of Persimmon-8B are long context size (16K), performance, and capabilities for multimodal extensions. The authors showcase their approach to model evaluation, focusing on practical text generation, mirroring how users interact with language models. The work also includes a comparative analysis, pitting Persimmon-8B against other prominent models (MPT 7B Instruct and Llama 2 Base 7B 1-Shot), across various evaluation tasks. The results demonstrate Persimmon-8B's competitive performance, even with limited training data. In terms of model details, the work outlines the architecture and training methodology of Persimmon-8B, providing insights into its design choices, sequence length, and dataset composition. The authors present a fast inference code that outperforms traditional implementations through operator fusion and CUDA graph utilization while maintaining code coherence. They express their anticipation of how the community will leverage this contribution to drive innovation, hinting at further upcoming releases as part of an ongoing series of developments. This model was contributed by ArthurZ. The original code can be found here. Usage tips
The Persimmon models were trained using bfloat16, but the original inference uses float16 The checkpoints uploaded on the hub use torch_dtype = 'float16' which will be used by the AutoModel API to cast the checkpoints from torch.float32 to torch.float16. The dtype of the online weights is mostly irrelevant, unless you are using torch_dtype="auto" when initializing a model using model = AutoModelForCausalLM.from_pretrained("path", torch_dtype = "auto"). The reason is that the model will first be downloaded ( using the dtype of the checkpoints online) then it will be cast to the default dtype of torch (becomes torch.float32). Users should specify the torch_dtype they want, and if they don't it will be torch.float32. Finetuning the model in float16 is not recommended and known to produce nan, as such the model should be fine-tuned in bfloat16.
Tips: To convert the model, you need to clone the original repository using git clone https://github.com/persimmon-ai-labs/adept-inference, then get the checkpoints:
git clone https://github.com/persimmon-ai-labs/adept-inference wget https://axtkn4xl5cip.objectstorage.us-phoenix-1.oci.customer-oci.com/n/axtkn4xl5cip/b/adept-public-data/o/8b_base_model_release.tar tar -xvf 8b_base_model_release.tar python src/transformers/models/persimmon/convert_persimmon_weights_to_hf.py --input_dir /path/to/downloaded/persimmon/weights/ --output_dir /output/path \ --pt_model_path /path/to/8b_chat_model_release/iter_0001251/mp_rank_00/model_optim_rng.pt --ada_lib_path /path/to/adept-inference For the chat model:
wget https://axtkn4xl5cip.objectstorage.us-phoenix-1.oci.customer-oci.com/n/axtkn4xl5cip/b/adept-public-data/o/8b_chat_model_release.tar tar -xvf 8b_base_model_release.tar Thereafter, models can be loaded via: from transformers import PersimmonForCausalLM, PersimmonTokenizer model = PersimmonForCausalLM.from_pretrained("/output/path") tokenizer = PersimmonTokenizer.from_pretrained("/output/path")
Perismmon uses a sentencepiece based tokenizer, with a Unigram model. It supports bytefallback, which is only available in tokenizers==0.14.0 for the fast tokenizer. The LlamaTokenizer is used as it is a standard wrapper around sentencepiece. The chat template will be updated with the templating functions in a follow up PR! The authors suggest to use the following prompt format for the chat mode: f"human: {prompt}\n\nadept:"
The authors suggest to use the following prompt format for the chat mode: f"human: {prompt}\n\nadept:" PersimmonConfig [[autodoc]] PersimmonConfig PersimmonModel [[autodoc]] PersimmonModel - forward PersimmonForCausalLM [[autodoc]] PersimmonForCausalLM - forward PersimmonForSequenceClassification [[autodoc]] PersimmonForSequenceClassification - forward
DePlot Overview DePlot was proposed in the paper DePlot: One-shot visual language reasoning by plot-to-table translation from Fangyu Liu, Julian Martin Eisenschlos, Francesco Piccinno, Syrine Krichene, Chenxi Pang, Kenton Lee, Mandar Joshi, Wenhu Chen, Nigel Collier, Yasemin Altun. The abstract of the paper states the following: Visual language such as charts and plots is ubiquitous in the human world. Comprehending plots and charts requires strong reasoning skills. Prior state-of-the-art (SOTA) models require at least tens of thousands of training examples and their reasoning capabilities are still much limited, especially on complex human-written queries. This paper presents the first one-shot solution to visual language reasoning. We decompose the challenge of visual language reasoning into two steps: (1) plot-to-text translation, and (2) reasoning over the translated text. The key in this method is a modality conversion module, named as DePlot, which translates the image of a plot or chart to a linearized table. The output of DePlot can then be directly used to prompt a pretrained large language model (LLM), exploiting the few-shot reasoning capabilities of LLMs. To obtain DePlot, we standardize the plot-to-table task by establishing unified task formats and metrics, and train DePlot end-to-end on this task. DePlot can then be used off-the-shelf together with LLMs in a plug-and-play fashion. Compared with a SOTA model finetuned on more than >28k data points, DePlot+LLM with just one-shot prompting achieves a 24.0% improvement over finetuned SOTA on human-written queries from the task of chart QA. DePlot is a model that is trained using Pix2Struct architecture. You can find more information about Pix2Struct in the Pix2Struct documentation. DePlot is a Visual Question Answering subset of Pix2Struct architecture. It renders the input question on the image and predicts the answer. Usage example Currently one checkpoint is available for DePlot:
google/deplot: DePlot fine-tuned on ChartQA dataset
thon from transformers import AutoProcessor, Pix2StructForConditionalGeneration import requests from PIL import Image model = Pix2StructForConditionalGeneration.from_pretrained("google/deplot") processor = AutoProcessor.from_pretrained("google/deplot") url = "https://raw.githubusercontent.com/vis-nlp/ChartQA/main/ChartQA%20Dataset/val/png/5090.png" image = Image.open(requests.get(url, stream=True).raw) inputs = processor(images=image, text="Generate underlying data table of the figure below:", return_tensors="pt") predictions = model.generate(**inputs, max_new_tokens=512) print(processor.decode(predictions[0], skip_special_tokens=True))
Fine-tuning To fine-tune DePlot, refer to the pix2struct fine-tuning notebook. For Pix2Struct models, we have found out that fine-tuning the model with Adafactor and cosine learning rate scheduler leads to faster convergence: thon from transformers.optimization import Adafactor, get_cosine_schedule_with_warmup optimizer = Adafactor(self.parameters(), scale_parameter=False, relative_step=False, lr=0.01, weight_decay=1e-05) scheduler = get_cosine_schedule_with_warmup(optimizer, num_warmup_steps=1000, num_training_steps=40000)
DePlot is a model trained using Pix2Struct architecture. For API reference, see Pix2Struct documentation.
MaskFormer This is a recently introduced model so the API hasn't been tested extensively. There may be some bugs or slight breaking changes to fix it in the future. If you see something strange, file a Github Issue.
Overview The MaskFormer model was proposed in Per-Pixel Classification is Not All You Need for Semantic Segmentation by Bowen Cheng, Alexander G. Schwing, Alexander Kirillov. MaskFormer addresses semantic segmentation with a mask classification paradigm instead of performing classic pixel-level classification. The abstract from the paper is the following: Modern approaches typically formulate semantic segmentation as a per-pixel classification task, while instance-level segmentation is handled with an alternative mask classification. Our key insight: mask classification is sufficiently general to solve both semantic- and instance-level segmentation tasks in a unified manner using the exact same model, loss, and training procedure. Following this observation, we propose MaskFormer, a simple mask classification model which predicts a set of binary masks, each associated with a single global class label prediction. Overall, the proposed mask classification-based method simplifies the landscape of effective approaches to semantic and panoptic segmentation tasks and shows excellent empirical results. In particular, we observe that MaskFormer outperforms per-pixel classification baselines when the number of classes is large. Our mask classification-based method outperforms both current state-of-the-art semantic (55.6 mIoU on ADE20K) and panoptic segmentation (52.7 PQ on COCO) models. The figure below illustrates the architecture of MaskFormer. Taken from the original paper.
This model was contributed by francesco. The original code can be found here. Usage tips
MaskFormer's Transformer decoder is identical to the decoder of DETR. 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 use_auxiliary_loss of [MaskFormerConfig] 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 get_num_masks function inside in the MaskFormerLoss class of modeling_maskformer.py. When training on multiple nodes, this should be set to the average number of target masks across all nodes, as can be seen in the original implementation here. One can use [MaskFormerImageProcessor] to prepare images for the model and optional targets for the model. To get the final segmentation, depending on the task, you can call [~MaskFormerImageProcessor.post_process_semantic_segmentation] or [~MaskFormerImageProcessor.post_process_panoptic_segmentation]. Both tasks can be solved using [MaskFormerForInstanceSegmentation] output, panoptic segmentation accepts an optional label_ids_to_fuse argument to fuse instances of the target object/s (e.g. sky) together.
Resources All notebooks that illustrate inference as well as fine-tuning on custom data with MaskFormer can be found here.
MaskFormer specific outputs [[autodoc]] models.maskformer.modeling_maskformer.MaskFormerModelOutput [[autodoc]] models.maskformer.modeling_maskformer.MaskFormerForInstanceSegmentationOutput MaskFormerConfig [[autodoc]] MaskFormerConfig MaskFormerImageProcessor [[autodoc]] MaskFormerImageProcessor - preprocess - encode_inputs - post_process_semantic_segmentation - post_process_instance_segmentation - post_process_panoptic_segmentation MaskFormerFeatureExtractor [[autodoc]] MaskFormerFeatureExtractor - call - encode_inputs - post_process_semantic_segmentation - post_process_instance_segmentation - post_process_panoptic_segmentation MaskFormerModel [[autodoc]] MaskFormerModel - forward MaskFormerForInstanceSegmentation [[autodoc]] MaskFormerForInstanceSegmentation - forward
KOSMOS-2 Overview The KOSMOS-2 model was proposed in Kosmos-2: Grounding Multimodal Large Language Models to the World by Zhiliang Peng, Wenhui Wang, Li Dong, Yaru Hao, Shaohan Huang, Shuming Ma, Furu Wei. KOSMOS-2 is a Transformer-based causal language model and is trained using the next-word prediction task on a web-scale dataset of grounded image-text pairs GRIT. The spatial coordinates of the bounding boxes in the dataset are converted to a sequence of location tokens, which are appended to their respective entity text spans (for example, a snowman followed by <patch_index_0044><patch_index_0863>). The data format is similar to “hyperlinks” that connect the object regions in an image to their text span in the corresponding caption. The abstract from the paper is the following: We introduce Kosmos-2, a Multimodal Large Language Model (MLLM), enabling new capabilities of perceiving object descriptions (e.g., bounding boxes) and grounding text to the visual world. Specifically, we represent refer expressions as links in Markdown, i.e., ``text span'', where object descriptions are sequences of location tokens. Together with multimodal corpora, we construct large-scale data of grounded image-text pairs (called GrIT) to train the model. In addition to the existing capabilities of MLLMs (e.g., perceiving general modalities, following instructions, and performing in-context learning), Kosmos-2 integrates the grounding capability into downstream applications. We evaluate Kosmos-2 on a wide range of tasks, including (i) multimodal grounding, such as referring expression comprehension, and phrase grounding, (ii) multimodal referring, such as referring expression generation, (iii) perception-language tasks, and (iv) language understanding and generation. This work lays out the foundation for the development of Embodiment AI and sheds light on the big convergence of language, multimodal perception, action, and world modeling, which is a key step toward artificial general intelligence. Code and pretrained models are available at https://aka.ms/kosmos-2.
Overview of tasks that KOSMOS-2 can handle. Taken from the original paper. Example thon
from PIL import Image import requests from transformers import AutoProcessor, Kosmos2ForConditionalGeneration model = Kosmos2ForConditionalGeneration.from_pretrained("microsoft/kosmos-2-patch14-224") processor = AutoProcessor.from_pretrained("microsoft/kosmos-2-patch14-224") url = "https://huggingface.co/microsoft/kosmos-2-patch14-224/resolve/main/snowman.jpg" image = Image.open(requests.get(url, stream=True).raw) prompt = " An image of" inputs = processor(text=prompt, images=image, return_tensors="pt") generated_ids = model.generate( pixel_values=inputs["pixel_values"], input_ids=inputs["input_ids"], attention_mask=inputs["attention_mask"], image_embeds=None, image_embeds_position_mask=inputs["image_embeds_position_mask"], use_cache=True, max_new_tokens=64, ) generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0] processed_text = processor.post_process_generation(generated_text, cleanup_and_extract=False) processed_text ' An image of a snowman warming himself by a fire.' caption, entities = processor.post_process_generation(generated_text) caption 'An image of a snowman warming himself by a fire.' entities [('a snowman', (12, 21), [(0.390625, 0.046875, 0.984375, 0.828125)]), ('a fire', (41, 47), [(0.171875, 0.015625, 0.484375, 0.890625)])]
This model was contributed by Yih-Dar SHIEH. The original code can be found here. Kosmos2Config [[autodoc]] Kosmos2Config Kosmos2ImageProcessor Kosmos2Processor [[autodoc]] Kosmos2Processor - call Kosmos2Model [[autodoc]] Kosmos2Model - forward Kosmos2ForConditionalGeneration [[autodoc]] Kosmos2ForConditionalGeneration - forward
Wav2Vec2 Overview The Wav2Vec2 model was proposed in wav2vec 2.0: A Framework for Self-Supervised Learning of Speech Representations by Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli. The abstract from the paper is the following: We show for the first time that learning powerful representations from speech audio alone followed by fine-tuning on transcribed speech can outperform the best semi-supervised methods while being conceptually simpler. wav2vec 2.0 masks the speech input in the latent space and solves a contrastive task defined over a quantization of the latent representations which are jointly learned. Experiments using all labeled data of Librispeech achieve 1.8/3.3 WER on the clean/other test sets. When lowering the amount of labeled data to one hour, wav2vec 2.0 outperforms the previous state of the art on the 100 hour subset while using 100 times less labeled data. Using just ten minutes of labeled data and pre-training on 53k hours of unlabeled data still achieves 4.8/8.2 WER. This demonstrates the feasibility of speech recognition with limited amounts of labeled data. This model was contributed by patrickvonplaten. Usage tips
Wav2Vec2 is a speech model that accepts a float array corresponding to the raw waveform of the speech signal. Wav2Vec2 model was trained using connectionist temporal classification (CTC) so the model output has to be decoded using [Wav2Vec2CTCTokenizer].
Resources A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with Wav2Vec2. 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.
A notebook on how to leverage a pretrained Wav2Vec2 model for emotion classification. 🌎 [Wav2Vec2ForCTC] is supported by this example script and notebook. Audio classification task guide
A blog post on boosting Wav2Vec2 with n-grams in 🤗 Transformers. A blog post on how to finetune Wav2Vec2 for English ASR with 🤗 Transformers. A blog post on finetuning XLS-R for Multi-Lingual ASR with 🤗 Transformers. A notebook on how to create YouTube captions from any video by transcribing audio with Wav2Vec2. 🌎 [Wav2Vec2ForCTC] is supported by a notebook on how to finetune a speech recognition model in English, and how to finetune a speech recognition model in any language. Automatic speech recognition task guide
🚀 Deploy A blog post on how to deploy Wav2Vec2 for Automatic Speech Recognition with Hugging Face's Transformers & Amazon SageMaker.
Wav2Vec2Config [[autodoc]] Wav2Vec2Config Wav2Vec2CTCTokenizer [[autodoc]] Wav2Vec2CTCTokenizer - call - save_vocabulary - decode - batch_decode - set_target_lang Wav2Vec2FeatureExtractor [[autodoc]] Wav2Vec2FeatureExtractor - call Wav2Vec2Processor [[autodoc]] Wav2Vec2Processor - call - pad - from_pretrained - save_pretrained - batch_decode - decode Wav2Vec2ProcessorWithLM [[autodoc]] Wav2Vec2ProcessorWithLM - call - pad - from_pretrained - save_pretrained - batch_decode - decode Decoding multiple audios If you are planning to decode multiple batches of audios, you should consider using [~Wav2Vec2ProcessorWithLM.batch_decode] and passing an instantiated multiprocessing.Pool. Otherwise, [~Wav2Vec2ProcessorWithLM.batch_decode] performance will be slower than calling [~Wav2Vec2ProcessorWithLM.decode] for each audio individually, as it internally instantiates a new Pool for every call. See the example below: thon
Let's see how to use a user-managed pool for batch decoding multiple audios from multiprocessing import get_context from transformers import AutoTokenizer, AutoProcessor, AutoModelForCTC from datasets import load_dataset import datasets import torch import model, feature extractor, tokenizer model = AutoModelForCTC.from_pretrained("patrickvonplaten/wav2vec2-base-100h-with-lm").to("cuda") processor = AutoProcessor.from_pretrained("patrickvonplaten/wav2vec2-base-100h-with-lm") load example dataset dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") dataset = dataset.cast_column("audio", datasets.Audio(sampling_rate=16_000)) def map_to_array(batch): batch["speech"] = batch["audio"]["array"] return batch prepare speech data for batch inference dataset = dataset.map(map_to_array, remove_columns=["audio"]) def map_to_pred(batch, pool): inputs = processor(batch["speech"], sampling_rate=16_000, padding=True, return_tensors="pt") inputs = {k: v.to("cuda") for k, v in inputs.items()}
with torch.no_grad(): logits = model(**inputs).logits transcription = processor.batch_decode(logits.cpu().numpy(), pool).text batch["transcription"] = transcription return batch
note: pool should be instantiated after Wav2Vec2ProcessorWithLM. otherwise, the LM won't be available to the pool's sub-processes select number of processes and batch_size based on number of CPU cores available and on dataset size with get_context("fork").Pool(processes=2) as pool: result = dataset.map( map_to_pred, batched=True, batch_size=2, fn_kwargs={"pool": pool}, remove_columns=["speech"] ) result["transcription"][:2] ['MISTER QUILTER IS THE APOSTLE OF THE MIDDLE CLASSES AND WE ARE GLAD TO WELCOME HIS GOSPEL', "NOR IS MISTER COULTER'S MANNER LESS INTERESTING THAN HIS MATTER"]
Wav2Vec2 specific outputs [[autodoc]] models.wav2vec2_with_lm.processing_wav2vec2_with_lm.Wav2Vec2DecoderWithLMOutput [[autodoc]] models.wav2vec2.modeling_wav2vec2.Wav2Vec2BaseModelOutput [[autodoc]] models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForPreTrainingOutput [[autodoc]] models.wav2vec2.modeling_flax_wav2vec2.FlaxWav2Vec2BaseModelOutput [[autodoc]] models.wav2vec2.modeling_flax_wav2vec2.FlaxWav2Vec2ForPreTrainingOutput
Wav2Vec2Model [[autodoc]] Wav2Vec2Model - forward Wav2Vec2ForCTC [[autodoc]] Wav2Vec2ForCTC - forward - load_adapter Wav2Vec2ForSequenceClassification [[autodoc]] Wav2Vec2ForSequenceClassification - forward Wav2Vec2ForAudioFrameClassification [[autodoc]] Wav2Vec2ForAudioFrameClassification - forward Wav2Vec2ForXVector [[autodoc]] Wav2Vec2ForXVector - forward Wav2Vec2ForPreTraining [[autodoc]] Wav2Vec2ForPreTraining - forward
TFWav2Vec2Model [[autodoc]] TFWav2Vec2Model - call TFWav2Vec2ForSequenceClassification [[autodoc]] TFWav2Vec2ForSequenceClassification - call TFWav2Vec2ForCTC [[autodoc]] TFWav2Vec2ForCTC - call FlaxWav2Vec2Model [[autodoc]] FlaxWav2Vec2Model - call FlaxWav2Vec2ForCTC [[autodoc]] FlaxWav2Vec2ForCTC - call FlaxWav2Vec2ForPreTraining [[autodoc]] FlaxWav2Vec2ForPreTraining - call
GPT-Sw3 Overview The GPT-Sw3 model was first proposed in Lessons Learned from GPT-SW3: Building the First Large-Scale Generative Language Model for Swedish by Ariel Ekgren, Amaru Cuba Gyllensten, Evangelia Gogoulou, Alice Heiman, Severine Verlinden, Joey Öhman, Fredrik Carlsson, Magnus Sahlgren. Since that first paper the authors have extended their work and trained new models on their new 1.2TB corpora named The Nordic Pile. GPT-Sw3 is a collection of large decoder-only pretrained transformer language models that were developed by AI Sweden in collaboration with RISE and the WASP WARA for Media and Language. GPT-Sw3 has been trained on a dataset containing 320B tokens in Swedish, Norwegian, Danish, Icelandic, English, and programming code. The model was pretrained using a causal language modeling (CLM) objective utilizing the NeMo Megatron GPT implementation. This model was contributed by AI Sweden Models. Usage example thon
from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("AI-Sweden-Models/gpt-sw3-356m") model = AutoModelForCausalLM.from_pretrained("AI-Sweden-Models/gpt-sw3-356m") input_ids = tokenizer("Träd är fina för att", return_tensors="pt")["input_ids"] generated_token_ids = model.generate(inputs=input_ids, max_new_tokens=10, do_sample=True)[0] print(tokenizer.decode(generated_token_ids)) Träd är fina för att de är färgstarka. Men ibland är det fint Resources
Resources Text classification task guide Token classification task guide Causal language modeling task guide The implementation uses the GPT2Model coupled with our GPTSw3Tokenizer. Refer to GPT2Model documentation for API reference and examples. Note that sentencepiece is required to use our tokenizer and can be installed with pip install transformers[sentencepiece] or pip install sentencepiece GPTSw3Tokenizer [[autodoc]] GPTSw3Tokenizer - save_vocabulary
Video Vision Transformer (ViViT) Overview The Vivit model was proposed in ViViT: A Video Vision Transformer by Anurag Arnab, Mostafa Dehghani, Georg Heigold, Chen Sun, Mario Lučić, Cordelia Schmid. The paper proposes one of the first successful pure-transformer based set of models for video understanding. The abstract from the paper is the following: We present pure-transformer based models for video classification, drawing upon the recent success of such models in image classification. Our model extracts spatio-temporal tokens from the input video, which are then encoded by a series of transformer layers. In order to handle the long sequences of tokens encountered in video, we propose several, efficient variants of our model which factorise the spatial- and temporal-dimensions of the input. Although transformer-based models are known to only be effective when large training datasets are available, we show how we can effectively regularise the model during training and leverage pretrained image models to be able to train on comparatively small datasets. We conduct thorough ablation studies, and achieve state-of-the-art results on multiple video classification benchmarks including Kinetics 400 and 600, Epic Kitchens, Something-Something v2 and Moments in Time, outperforming prior methods based on deep 3D convolutional networks. This model was contributed by jegormeister. The original code (written in JAX) can be found here. VivitConfig [[autodoc]] VivitConfig VivitImageProcessor [[autodoc]] VivitImageProcessor - preprocess VivitModel [[autodoc]] VivitModel - forward VivitForVideoClassification [[autodoc]] transformers.VivitForVideoClassification - forward
ResNet Overview The ResNet model was proposed in Deep Residual Learning for Image Recognition by Kaiming He, Xiangyu Zhang, Shaoqing Ren and Jian Sun. Our implementation follows the small changes made by Nvidia, we apply the stride=2 for downsampling in bottleneck's 3x3 conv and not in the first 1x1. This is generally known as "ResNet v1.5". ResNet introduced residual connections, they allow to train networks with an unseen number of layers (up to 1000). ResNet won the 2015 ILSVRC & COCO competition, one important milestone in deep computer vision. The abstract from the paper is the following: Deeper neural networks are more difficult to train. We present a residual learning framework to ease the training of networks that are substantially deeper than those used previously. We explicitly reformulate the layers as learning residual functions with reference to the layer inputs, instead of learning unreferenced functions. We provide comprehensive empirical evidence showing that these residual networks are easier to optimize, and can gain accuracy from considerably increased depth. On the ImageNet dataset we evaluate residual nets with a depth of up to 152 layers---8x deeper than VGG nets but still having lower complexity. An ensemble of these residual nets achieves 3.57% error on the ImageNet test set. This result won the 1st place on the ILSVRC 2015 classification task. We also present analysis on CIFAR-10 with 100 and 1000 layers. The depth of representations is of central importance for many visual recognition tasks. Solely due to our extremely deep representations, we obtain a 28% relative improvement on the COCO object detection dataset. Deep residual nets are foundations of our submissions to ILSVRC & COCO 2015 competitions, where we also won the 1st places on the tasks of ImageNet detection, ImageNet localization, COCO detection, and COCO segmentation. The figure below illustrates the architecture of ResNet. Taken from the original paper.
This model was contributed by Francesco. The TensorFlow version of this model was added by amyeroberts. The original code can be found here. Resources A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with ResNet. [ResNetForImageClassification] is supported by this example script and notebook. See also: Image classification task guide
[ResNetForImageClassification] is supported by this example script and notebook. See also: Image classification 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. ResNetConfig [[autodoc]] ResNetConfig
ResNetModel [[autodoc]] ResNetModel - forward ResNetForImageClassification [[autodoc]] ResNetForImageClassification - forward TFResNetModel [[autodoc]] TFResNetModel - call TFResNetForImageClassification [[autodoc]] TFResNetForImageClassification - call FlaxResNetModel [[autodoc]] FlaxResNetModel - call FlaxResNetForImageClassification [[autodoc]] FlaxResNetForImageClassification - call
VAN This model is in maintenance mode only, we don't accept any new PRs changing its code. If you run into any issues running this model, please reinstall the last version that supported this model: v4.30.0. You can do so by running the following command: pip install -U transformers==4.30.0.
Overview The VAN model was proposed in Visual Attention Network by Meng-Hao Guo, Cheng-Ze Lu, Zheng-Ning Liu, Ming-Ming Cheng, Shi-Min Hu. This paper introduces a new attention layer based on convolution operations able to capture both local and distant relationships. This is done by combining normal and large kernel convolution layers. The latter uses a dilated convolution to capture distant correlations. The abstract from the paper is the following: While originally designed for natural language processing tasks, the self-attention mechanism has recently taken various computer vision areas by storm. However, the 2D nature of images brings three challenges for applying self-attention in computer vision. (1) Treating images as 1D sequences neglects their 2D structures. (2) The quadratic complexity is too expensive for high-resolution images. (3) It only captures spatial adaptability but ignores channel adaptability. In this paper, we propose a novel large kernel attention (LKA) module to enable self-adaptive and long-range correlations in self-attention while avoiding the above issues. We further introduce a novel neural network based on LKA, namely Visual Attention Network (VAN). While extremely simple, VAN outperforms the state-of-the-art vision transformers and convolutional neural networks with a large margin in extensive experiments, including image classification, object detection, semantic segmentation, instance segmentation, etc. Code is available at this https URL. Tips:
VAN does not have an embedding layer, thus the hidden_states will have a length equal to the number of stages. The figure below illustrates the architecture of a Visual Attention Layer. Taken from the original paper. This model was contributed by Francesco. The original code can be found here. Resources A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with VAN.
This model was contributed by Francesco. The original code can be found here. Resources A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with VAN. [VanForImageClassification] is supported by this example script and notebook. See also: Image classification task guide
[VanForImageClassification] is supported by this example script and notebook. See also: Image classification 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. VanConfig [[autodoc]] VanConfig VanModel [[autodoc]] VanModel - forward VanForImageClassification [[autodoc]] VanForImageClassification - forward
FlauBERT
Overview The FlauBERT model was proposed in the paper FlauBERT: Unsupervised Language Model Pre-training for French by Hang Le et al. It's a transformer model pretrained using a masked language modeling (MLM) objective (like BERT). The abstract from the paper is the following: Language models have become a key step to achieve state-of-the art results in many different Natural Language Processing (NLP) tasks. Leveraging the huge amount of unlabeled texts nowadays available, they provide an efficient way to pre-train continuous word representations that can be fine-tuned for a downstream task, along with their contextualization at the sentence level. This has been widely demonstrated for English using contextualized representations (Dai and Le, 2015; Peters et al., 2018; Howard and Ruder, 2018; Radford et al., 2018; Devlin et al., 2019; Yang et al., 2019b). In this paper, we introduce and share FlauBERT, a model learned on a very large and heterogeneous French corpus. Models of different sizes are trained using the new CNRS (French National Centre for Scientific Research) Jean Zay supercomputer. We apply our French language models to diverse NLP tasks (text classification, paraphrasing, natural language inference, parsing, word sense disambiguation) and show that most of the time they outperform other pretraining approaches. Different versions of FlauBERT as well as a unified evaluation protocol for the downstream tasks, called FLUE (French Language Understanding Evaluation), are shared to the research community for further reproducible experiments in French NLP. This model was contributed by formiel. The original code can be found here. Tips: - Like RoBERTa, without the sentence ordering prediction (so just trained on the MLM objective). Resources
Text classification task guide Token classification task guide Question answering task guide Masked language modeling task guide Multiple choice task guide FlaubertConfig [[autodoc]] FlaubertConfig FlaubertTokenizer [[autodoc]] FlaubertTokenizer
FlaubertModel [[autodoc]] FlaubertModel - forward FlaubertWithLMHeadModel [[autodoc]] FlaubertWithLMHeadModel - forward FlaubertForSequenceClassification [[autodoc]] FlaubertForSequenceClassification - forward FlaubertForMultipleChoice [[autodoc]] FlaubertForMultipleChoice - forward FlaubertForTokenClassification [[autodoc]] FlaubertForTokenClassification - forward FlaubertForQuestionAnsweringSimple [[autodoc]] FlaubertForQuestionAnsweringSimple - forward FlaubertForQuestionAnswering [[autodoc]] FlaubertForQuestionAnswering - forward
TFFlaubertModel [[autodoc]] TFFlaubertModel - call TFFlaubertWithLMHeadModel [[autodoc]] TFFlaubertWithLMHeadModel - call TFFlaubertForSequenceClassification [[autodoc]] TFFlaubertForSequenceClassification - call TFFlaubertForMultipleChoice [[autodoc]] TFFlaubertForMultipleChoice - call TFFlaubertForTokenClassification [[autodoc]] TFFlaubertForTokenClassification - call TFFlaubertForQuestionAnsweringSimple [[autodoc]] TFFlaubertForQuestionAnsweringSimple - call
TVP Overview The text-visual prompting (TVP) framework was proposed in the paper Text-Visual Prompting for Efficient 2D Temporal Video Grounding by Yimeng Zhang, Xin Chen, Jinghan Jia, Sijia Liu, Ke Ding. The abstract from the paper is the following: In this paper, we study the problem of temporal video grounding (TVG), which aims to predict the starting/ending time points of moments described by a text sentence within a long untrimmed video. Benefiting from fine-grained 3D visual features, the TVG techniques have achieved remarkable progress in recent years. However, the high complexity of 3D convolutional neural networks (CNNs) makes extracting dense 3D visual features time-consuming, which calls for intensive memory and computing resources. Towards efficient TVG, we propose a novel text-visual prompting (TVP) framework, which incorporates optimized perturbation patterns (that we call ‘prompts’) into both visual inputs and textual features of a TVG model. In sharp contrast to 3D CNNs, we show that TVP allows us to effectively co-train vision encoder and language encoder in a 2D TVG model and improves the performance of cross-modal feature fusion using only low-complexity sparse 2D visual features. Further, we propose a Temporal-Distance IoU (TDIoU) loss for efficient learning of TVG. Experiments on two benchmark datasets, Charades-STA and ActivityNet Captions datasets, empirically show that the proposed TVP significantly boosts the performance of 2D TVG (e.g., 9.79% improvement on Charades-STA and 30.77% improvement on ActivityNet Captions) and achieves 5× inference acceleration over TVG using 3D visual features. This research addresses temporal video grounding (TVG), which is the process of pinpointing the start and end times of specific events in a long video, as described by a text sentence. Text-visual prompting (TVP), is proposed to enhance TVG. TVP involves integrating specially designed patterns, known as 'prompts', into both the visual (image-based) and textual (word-based) input components of a TVG model. These prompts provide additional spatial-temporal context, improving the model's ability to accurately determine event timings in the video. The approach employs 2D visual inputs in place of 3D ones. Although 3D inputs offer more spatial-temporal detail, they are also more time-consuming to process. The use of 2D inputs with the prompting method aims to provide similar levels of context and accuracy more efficiently.
TVP architecture. Taken from the original paper. This model was contributed by Jiqing Feng. The original code can be found here. Usage tips and examples Prompts are optimized perturbation patterns, which would be added to input video frames or text features. Universal set refers to using the same exact set of prompts for any input, this means that these prompts are added consistently to all video frames and text features, regardless of the input's content. TVP consists of a visual encoder and cross-modal encoder. A universal set of visual prompts and text prompts to be integrated into sampled video frames and textual features, respectively. Specially, a set of different visual prompts are applied to uniformly-sampled frames of one untrimmed video in order. The goal of this model is to incorporate trainable prompts into both visual inputs and textual features to temporal video grounding(TVG) problems. In principle, one can apply any visual, cross-modal encoder in the proposed architecture. The [TvpProcessor] wraps [BertTokenizer] and [TvpImageProcessor] into a single instance to both encode the text and prepare the images respectively. The following example shows how to run temporal video grounding using [TvpProcessor] and [TvpForVideoGrounding]. thon import av import cv2 import numpy as np import torch from huggingface_hub import hf_hub_download from transformers import AutoProcessor, TvpForVideoGrounding def pyav_decode(container, sampling_rate, num_frames, clip_idx, num_clips, target_fps): ''' Convert the video from its original fps to the target_fps and decode the video with PyAV decoder. Args: container (container): pyav container. sampling_rate (int): frame sampling rate (interval between two sampled frames). num_frames (int): number of frames to sample. clip_idx (int): if clip_idx is -1, perform random temporal sampling. If clip_idx is larger than -1, uniformly split the video to num_clips clips, and select the clip_idx-th video clip. num_clips (int): overall number of clips to uniformly sample from the given video. target_fps (int): the input video may have different fps, convert it to the target video fps before frame sampling. Returns: frames (tensor): decoded frames from the video. Return None if the no video stream was found. fps (float): the number of frames per second of the video. ''' video = container.streams.video[0] fps = float(video.average_rate) clip_size = sampling_rate * num_frames / target_fps * fps delta = max(num_frames - clip_size, 0) start_idx = delta * clip_idx / num_clips end_idx = start_idx + clip_size - 1 timebase = video.duration / num_frames video_start_pts = int(start_idx * timebase) video_end_pts = int(end_idx * timebase) seek_offset = max(video_start_pts - 1024, 0) container.seek(seek_offset, any_frame=False, backward=True, stream=video) frames = {} for frame in container.decode(video=0): if frame.pts < video_start_pts: continue frames[frame.pts] = frame if frame.pts > video_end_pts: break frames = [frames[pts] for pts in sorted(frames)] return frames, fps def decode(container, sampling_rate, num_frames, clip_idx, num_clips, target_fps): ''' Decode the video and perform temporal sampling. Args: container (container): pyav container. sampling_rate (int): frame sampling rate (interval between two sampled frames). num_frames (int): number of frames to sample. clip_idx (int): if clip_idx is -1, perform random temporal sampling. If clip_idx is larger than -1, uniformly split the video to num_clips clips, and select the clip_idx-th video clip. num_clips (int): overall number of clips to uniformly sample from the given video. target_fps (int): the input video may have different fps, convert it to the target video fps before frame sampling. Returns: frames (tensor): decoded frames from the video. ''' assert clip_idx >= -2, "Not a valied clip_idx {}".format(clip_idx) frames, fps = pyav_decode(container, sampling_rate, num_frames, clip_idx, num_clips, target_fps) clip_size = sampling_rate * num_frames / target_fps * fps index = np.linspace(0, clip_size - 1, num_frames) index = np.clip(index, 0, len(frames) - 1).astype(np.int64) frames = np.array([frames[idx].to_rgb().to_ndarray() for idx in index]) frames = frames.transpose(0, 3, 1, 2) return frames file = hf_hub_download(repo_id="Intel/tvp_demo", filename="AK2KG.mp4", repo_type="dataset") model = TvpForVideoGrounding.from_pretrained("Intel/tvp-base") decoder_kwargs = dict( container=av.open(file, metadata_errors="ignore"), sampling_rate=1, num_frames=model.config.num_frames, clip_idx=0, num_clips=1, target_fps=3, ) raw_sampled_frms = decode(**decoder_kwargs) text = "a person is sitting on a bed." processor = AutoProcessor.from_pretrained("Intel/tvp-base") model_inputs = processor( text=[text], videos=list(raw_sampled_frms), return_tensors="pt", max_text_length=100#, size=size ) model_inputs["pixel_values"] = model_inputs["pixel_values"].to(model.dtype) output = model(**model_inputs) def get_video_duration(filename): cap = cv2.VideoCapture(filename) if cap.isOpened(): rate = cap.get(5) frame_num = cap.get(7) duration = frame_num/rate return duration return -1 duration = get_video_duration(file) start, end = processor.post_process_video_grounding(output.logits, duration) print(f"The time slot of the video corresponding to the text \"{text}\" is from {start}s to {end}s")
Tips: This implementation of TVP uses [BertTokenizer] to generate text embeddings and Resnet-50 model to compute visual embeddings. Checkpoints for pre-trained tvp-base is released. Please refer to Table 2 for TVP's performance on Temporal Video Grounding task.
TvpConfig [[autodoc]] TvpConfig TvpImageProcessor [[autodoc]] TvpImageProcessor - preprocess TvpProcessor [[autodoc]] TvpProcessor - call TvpModel [[autodoc]] TvpModel - forward TvpForVideoGrounding [[autodoc]] TvpForVideoGrounding - forward
FNet Overview The FNet model was proposed in FNet: Mixing Tokens with Fourier Transforms by James Lee-Thorp, Joshua Ainslie, Ilya Eckstein, Santiago Ontanon. The model replaces the self-attention layer in a BERT model with a fourier transform which returns only the real parts of the transform. The model is significantly faster than the BERT model because it has fewer parameters and is more memory efficient. The model achieves about 92-97% accuracy of BERT counterparts on GLUE benchmark, and trains much faster than the BERT model. The abstract from the paper is the following: We show that Transformer encoder architectures can be sped up, with limited accuracy costs, by replacing the self-attention sublayers with simple linear transformations that "mix" input tokens. These linear mixers, along with standard nonlinearities in feed-forward layers, prove competent at modeling semantic relationships in several text classification tasks. Most surprisingly, we find that replacing the self-attention sublayer in a Transformer encoder with a standard, unparameterized Fourier Transform achieves 92-97% of the accuracy of BERT counterparts on the GLUE benchmark, but trains 80% faster on GPUs and 70% faster on TPUs at standard 512 input lengths. At longer input lengths, our FNet model is significantly faster: when compared to the "efficient" Transformers on the Long Range Arena benchmark, FNet matches the accuracy of the most accurate models, while outpacing the fastest models across all sequence lengths on GPUs (and across relatively shorter lengths on TPUs). Finally, FNet has a light memory footprint and is particularly efficient at smaller model sizes; for a fixed speed and accuracy budget, small FNet models outperform Transformer counterparts. This model was contributed by gchhablani. The original code can be found here. Usage tips The model was trained without an attention mask as it is based on Fourier Transform. The model was trained with maximum sequence length 512 which includes pad tokens. Hence, it is highly recommended to use the same maximum sequence length for fine-tuning and inference. Resources
Text classification task guide Token classification task guide Question answering task guide Masked language modeling task guide Multiple choice task guide
FNetConfig [[autodoc]] FNetConfig FNetTokenizer [[autodoc]] FNetTokenizer - build_inputs_with_special_tokens - get_special_tokens_mask - create_token_type_ids_from_sequences - save_vocabulary FNetTokenizerFast [[autodoc]] FNetTokenizerFast FNetModel [[autodoc]] FNetModel - forward FNetForPreTraining [[autodoc]] FNetForPreTraining - forward FNetForMaskedLM [[autodoc]] FNetForMaskedLM - forward FNetForNextSentencePrediction [[autodoc]] FNetForNextSentencePrediction - forward FNetForSequenceClassification [[autodoc]] FNetForSequenceClassification - forward FNetForMultipleChoice [[autodoc]] FNetForMultipleChoice - forward FNetForTokenClassification [[autodoc]] FNetForTokenClassification - forward FNetForQuestionAnswering [[autodoc]] FNetForQuestionAnswering - forward
UniSpeech Overview The UniSpeech model was proposed in UniSpeech: Unified Speech Representation Learning with Labeled and Unlabeled Data by Chengyi Wang, Yu Wu, Yao Qian, Kenichi Kumatani, Shujie Liu, Furu Wei, Michael Zeng, Xuedong Huang . The abstract from the paper is the following: In this paper, we propose a unified pre-training approach called UniSpeech to learn speech representations with both unlabeled and labeled data, in which supervised phonetic CTC learning and phonetically-aware contrastive self-supervised learning are conducted in a multi-task learning manner. The resultant representations can capture information more correlated with phonetic structures and improve the generalization across languages and domains. We evaluate the effectiveness of UniSpeech for cross-lingual representation learning on public CommonVoice corpus. The results show that UniSpeech outperforms self-supervised pretraining and supervised transfer learning for speech recognition by a maximum of 13.4% and 17.8% relative phone error rate reductions respectively (averaged over all testing languages). The transferability of UniSpeech is also demonstrated on a domain-shift speech recognition task, i.e., a relative word error rate reduction of 6% against the previous approach. This model was contributed by patrickvonplaten. The Authors' code can be found here. Usage tips
UniSpeech is a speech model that accepts a float array corresponding to the raw waveform of the speech signal. Please use [Wav2Vec2Processor] for the feature extraction. UniSpeech model can be fine-tuned using connectionist temporal classification (CTC) so the model output has to be decoded using [Wav2Vec2CTCTokenizer]. Resources Audio classification task guide Automatic speech recognition task guide
Audio classification task guide Automatic speech recognition task guide UniSpeechConfig [[autodoc]] UniSpeechConfig UniSpeech specific outputs [[autodoc]] models.unispeech.modeling_unispeech.UniSpeechForPreTrainingOutput UniSpeechModel [[autodoc]] UniSpeechModel - forward UniSpeechForCTC [[autodoc]] UniSpeechForCTC - forward UniSpeechForSequenceClassification [[autodoc]] UniSpeechForSequenceClassification - forward UniSpeechForPreTraining [[autodoc]] UniSpeechForPreTraining - forward
CPMAnt Overview CPM-Ant is an open-source Chinese pre-trained language model (PLM) with 10B parameters. It is also the first milestone of the live training process of CPM-Live. The training process is cost-effective and environment-friendly. CPM-Ant also achieves promising results with delta tuning on the CUGE benchmark. Besides the full model, we also provide various compressed versions to meet the requirements of different hardware configurations. See more This model was contributed by OpenBMB. The original code can be found here. Resources