diff --git a/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/swin.md b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/swin.md new file mode 100644 index 0000000000000000000000000000000000000000..e23c882a3f097aef0bcc3e04469ed0a3104be982 --- /dev/null +++ b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/swin.md @@ -0,0 +1,107 @@ + + +# Swin Transformer + +## Overview + +The Swin Transformer was proposed in [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://arxiv.org/abs/2103.14030) +by Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo. + +The abstract from the paper is the following: + +*This paper presents a new vision Transformer, called Swin Transformer, that capably serves as a general-purpose backbone +for computer vision. Challenges in adapting Transformer from language to vision arise from differences between the two domains, +such as large variations in the scale of visual entities and the high resolution of pixels in images compared to words in text. +To address these differences, we propose a hierarchical Transformer whose representation is computed with \bold{S}hifted +\bold{win}dows. The shifted windowing scheme brings greater efficiency by limiting self-attention computation to non-overlapping +local windows while also allowing for cross-window connection. This hierarchical architecture has the flexibility to model at +various scales and has linear computational complexity with respect to image size. These qualities of Swin Transformer make it +compatible with a broad range of vision tasks, including image classification (87.3 top-1 accuracy on ImageNet-1K) and dense +prediction tasks such as object detection (58.7 box AP and 51.1 mask AP on COCO test-dev) and semantic segmentation +(53.5 mIoU on ADE20K val). Its performance surpasses the previous state-of-the-art by a large margin of +2.7 box AP and ++2.6 mask AP on COCO, and +3.2 mIoU on ADE20K, demonstrating the potential of Transformer-based models as vision backbones. +The hierarchical design and the shifted window approach also prove beneficial for all-MLP architectures.* + + + + Swin Transformer architecture. Taken from the original paper. + +This model was contributed by [novice03](https://huggingface.co/novice03). The Tensorflow version of this model was contributed by [amyeroberts](https://huggingface.co/amyeroberts). The original code can be found [here](https://github.com/microsoft/Swin-Transformer). + +## Usage tips + +- Swin pads the inputs supporting any input height and width (if divisible by `32`). +- Swin can be used as a *backbone*. When `output_hidden_states = True`, it will output both `hidden_states` and `reshaped_hidden_states`. The `reshaped_hidden_states` have a shape of `(batch, num_channels, height, width)` rather than `(batch_size, sequence_length, num_channels)`. + +## Resources + +A list of official Hugging Face and community (indicated by ๐ŸŒŽ) resources to help you get started with Swin Transformer. + + + +- [`SwinForImageClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb). +- See also: [Image classification task guide](../tasks/image_classification) + +Besides that: + +- [`SwinForMaskedImageModeling`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-pretraining). + +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. + +## SwinConfig + +[[autodoc]] SwinConfig + + + + +## SwinModel + +[[autodoc]] SwinModel + - forward + +## SwinForMaskedImageModeling + +[[autodoc]] SwinForMaskedImageModeling + - forward + +## SwinForImageClassification + +[[autodoc]] transformers.SwinForImageClassification + - forward + + + + +## TFSwinModel + +[[autodoc]] TFSwinModel + - call + +## TFSwinForMaskedImageModeling + +[[autodoc]] TFSwinForMaskedImageModeling + - call + +## TFSwinForImageClassification + +[[autodoc]] transformers.TFSwinForImageClassification + - call + + + \ No newline at end of file diff --git a/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/swin2sr.md b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/swin2sr.md new file mode 100644 index 0000000000000000000000000000000000000000..18d6635feffce2b968cbd2d2f5061801773d1bad --- /dev/null +++ b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/swin2sr.md @@ -0,0 +1,61 @@ + + +# Swin2SR + +## Overview + +The Swin2SR model was proposed in [Swin2SR: SwinV2 Transformer for Compressed Image Super-Resolution and Restoration](https://arxiv.org/abs/2209.11345) by Marcos V. Conde, Ui-Jin Choi, Maxime Burchi, Radu Timofte. +Swin2SR improves the [SwinIR](https://github.com/JingyunLiang/SwinIR/) model by incorporating [Swin Transformer v2](swinv2) layers which mitigates issues such as training instability, resolution gaps between pre-training +and fine-tuning, and hunger on data. + +The abstract from the paper is the following: + +*Compression plays an important role on the efficient transmission and storage of images and videos through band-limited systems such as streaming services, virtual reality or videogames. However, compression unavoidably leads to artifacts and the loss of the original information, which may severely degrade the visual quality. For these reasons, quality enhancement of compressed images has become a popular research topic. While most state-of-the-art image restoration methods are based on convolutional neural networks, other transformers-based methods such as SwinIR, show impressive performance on these tasks. +In this paper, we explore the novel Swin Transformer V2, to improve SwinIR for image super-resolution, and in particular, the compressed input scenario. Using this method we can tackle the major issues in training transformer vision models, such as training instability, resolution gaps between pre-training and fine-tuning, and hunger on data. We conduct experiments on three representative tasks: JPEG compression artifacts removal, image super-resolution (classical and lightweight), and compressed image super-resolution. Experimental results demonstrate that our method, Swin2SR, can improve the training convergence and performance of SwinIR, and is a top-5 solution at the "AIM 2022 Challenge on Super-Resolution of Compressed Image and Video".* + + + + Swin2SR architecture. Taken from the original paper. + +This model was contributed by [nielsr](https://huggingface.co/nielsr). +The original code can be found [here](https://github.com/mv-lab/swin2sr). + +## Resources + +Demo notebooks for Swin2SR can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/Swin2SR). + +A demo Space for image super-resolution with SwinSR can be found [here](https://huggingface.co/spaces/jjourney1125/swin2sr). + +## Swin2SRImageProcessor + +[[autodoc]] Swin2SRImageProcessor + - preprocess + +## Swin2SRConfig + +[[autodoc]] Swin2SRConfig + +## Swin2SRModel + +[[autodoc]] Swin2SRModel + - forward + +## Swin2SRForImageSuperResolution + +[[autodoc]] Swin2SRForImageSuperResolution + - forward diff --git a/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/swinv2.md b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/swinv2.md new file mode 100644 index 0000000000000000000000000000000000000000..25233dca33954554c92f177fe076a779e99f0be6 --- /dev/null +++ b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/swinv2.md @@ -0,0 +1,62 @@ + + +# Swin Transformer V2 + +## Overview + +The Swin Transformer V2 model was proposed in [Swin Transformer V2: Scaling Up Capacity and Resolution](https://arxiv.org/abs/2111.09883) by Ze Liu, Han Hu, Yutong Lin, Zhuliang Yao, Zhenda Xie, Yixuan Wei, Jia Ning, Yue Cao, Zheng Zhang, Li Dong, Furu Wei, Baining Guo. + +The abstract from the paper is the following: + +*Large-scale NLP models have been shown to significantly improve the performance on language tasks with no signs of saturation. They also demonstrate amazing few-shot capabilities like that of human beings. This paper aims to explore large-scale models in computer vision. We tackle three major issues in training and application of large vision models, including training instability, resolution gaps between pre-training and fine-tuning, and hunger on labelled data. Three main techniques are proposed: 1) a residual-post-norm method combined with cosine attention to improve training stability; 2) A log-spaced continuous position bias method to effectively transfer models pre-trained using low-resolution images to downstream tasks with high-resolution inputs; 3) A self-supervised pre-training method, SimMIM, to reduce the needs of vast labeled images. Through these techniques, this paper successfully trained a 3 billion-parameter Swin Transformer V2 model, which is the largest dense vision model to date, and makes it capable of training with images of up to 1,536ร—1,536 resolution. It set new performance records on 4 representative vision tasks, including ImageNet-V2 image classification, COCO object detection, ADE20K semantic segmentation, and Kinetics-400 video action classification. Also note our training is much more efficient than that in Google's billion-level visual models, which consumes 40 times less labelled data and 40 times less training time.* + +This model was contributed by [nandwalritik](https://huggingface.co/nandwalritik). +The original code can be found [here](https://github.com/microsoft/Swin-Transformer). + +## Resources + +A list of official Hugging Face and community (indicated by ๐ŸŒŽ) resources to help you get started with Swin Transformer v2. + + + +- [`Swinv2ForImageClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb). +- See also: [Image classification task guide](../tasks/image_classification) + +Besides that: + +- [`Swinv2ForMaskedImageModeling`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-pretraining). + +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. + +## Swinv2Config + +[[autodoc]] Swinv2Config + +## Swinv2Model + +[[autodoc]] Swinv2Model + - forward + +## Swinv2ForMaskedImageModeling + +[[autodoc]] Swinv2ForMaskedImageModeling + - forward + +## Swinv2ForImageClassification + +[[autodoc]] transformers.Swinv2ForImageClassification + - forward diff --git a/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/switch_transformers.md b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/switch_transformers.md new file mode 100644 index 0000000000000000000000000000000000000000..ca6748167f5e014f32448b3b62e0f5050f08ce1d --- /dev/null +++ b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/switch_transformers.md @@ -0,0 +1,71 @@ + + +# SwitchTransformers + +## Overview + +The SwitchTransformers model was proposed in [Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity](https://arxiv.org/abs/2101.03961) by William Fedus, Barret Zoph, Noam Shazeer. + +The Switch Transformer model uses a sparse T5 encoder-decoder architecture, where the MLP are replaced by a Mixture of Experts (MoE). A routing mechanism (top 1 in this case) associates each token to one of the expert, where each expert is a dense MLP. While switch transformers have a lot more weights than their equivalent dense models, the sparsity allows better scaling and better finetuning performance at scale. +During a forward pass, only a fraction of the weights are used. The routing mechanism allows the model to select relevant weights on the fly which increases the model capacity without increasing the number of operations. + +The abstract from the paper is the following: + +*In deep learning, models typically reuse the same parameters for all inputs. Mixture of Experts (MoE) defies this and instead selects different parameters for each incoming example. The result is a sparsely-activated model -- with outrageous numbers of parameters -- but a constant computational cost. However, despite several notable successes of MoE, widespread adoption has been hindered by complexity, communication costs and training instability -- we address these with the Switch Transformer. We simplify the MoE routing algorithm and design intuitive improved models with reduced communication and computational costs. Our proposed training techniques help wrangle the instabilities and we show large sparse models may be trained, for the first time, with lower precision (bfloat16) formats. We design models based off T5-Base and T5-Large to obtain up to 7x increases in pre-training speed with the same computational resources. These improvements extend into multilingual settings where we measure gains over the mT5-Base version across all 101 languages. Finally, we advance the current scale of language models by pre-training up to trillion parameter models on the "Colossal Clean Crawled Corpus" and achieve a 4x speedup over the T5-XXL model.* + +This model was contributed by [Younes Belkada](https://huggingface.co/ybelkada) and [Arthur Zucker](https://huggingface.co/ArthurZ). +The original code can be found [here](https://github.com/google/flaxformer/tree/main/flaxformer/architectures/moe). + +## Usage tips + +- SwitchTransformers uses the [`T5Tokenizer`], which can be loaded directly from each model's repository. +- The released weights are pretrained on English [Masked Language Modeling](https://moon-ci-docs.huggingface.co/docs/transformers/pr_19323/en/glossary#general-terms) task, and should be finetuned. + +## Resources + +- [Translation task guide](../tasks/translation) +- [Summarization task guide](../tasks/summarization) + +## SwitchTransformersConfig + +[[autodoc]] SwitchTransformersConfig + +## SwitchTransformersTop1Router + +[[autodoc]] SwitchTransformersTop1Router + - _compute_router_probabilities + - forward + +## SwitchTransformersSparseMLP + +[[autodoc]] SwitchTransformersSparseMLP + - forward + +## SwitchTransformersModel + +[[autodoc]] SwitchTransformersModel + - forward + +## SwitchTransformersForConditionalGeneration + +[[autodoc]] SwitchTransformersForConditionalGeneration + - forward + +## SwitchTransformersEncoderModel + +[[autodoc]] SwitchTransformersEncoderModel + - forward diff --git a/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/t5.md b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/t5.md new file mode 100644 index 0000000000000000000000000000000000000000..86a645512c6cde8a02c6f81eb2d61a91c0d037dd --- /dev/null +++ b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/t5.md @@ -0,0 +1,456 @@ + + +# T5 + +
+ +Models + + +Spaces + + +Paper page + +
+ +## Overview + +The T5 model was presented in [Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer](https://arxiv.org/pdf/1910.10683.pdf) by [Colin Raffel](https://huggingface.co/craffel), Noam Shazeer, [Adam Roberts](https://huggingface.co/adarob), Katherine Lee, Sharan Narang, +Michael Matena, Yanqi Zhou, Wei Li, [Peter J. Liu](https://huggingface.co/peterjliu). + +The abstract from the paper is the following: + +*Transfer learning, where a model is first pre-trained on a data-rich task before being fine-tuned on a downstream +task, has emerged as a powerful technique in natural language processing (NLP). The effectiveness of transfer learning +has given rise to a diversity of approaches, methodology, and practice. In this paper, we explore the landscape of +transfer learning techniques for NLP by introducing a unified framework that converts every language problem into a +text-to-text format. Our systematic study compares pretraining objectives, architectures, unlabeled datasets, transfer +approaches, and other factors on dozens of language understanding tasks. By combining the insights from our exploration +with scale and our new "Colossal Clean Crawled Corpus", we achieve state-of-the-art results on many benchmarks covering +summarization, question answering, text classification, and more. To facilitate future work on transfer learning for +NLP, we release our dataset, pre-trained models, and code.* + +All checkpoints can be found on the [hub](https://huggingface.co/models?search=t5). + +This model was contributed by [thomwolf](https://huggingface.co/thomwolf). The original code can be found [here](https://github.com/google-research/text-to-text-transfer-transformer). + +## Usage tips + +- T5 is an encoder-decoder model pre-trained on a multi-task mixture of unsupervised and supervised tasks and for which +each task is converted into a text-to-text format. T5 works well on a variety of tasks out-of-the-box by prepending a +different prefix to the input corresponding to each task, e.g., for translation: *translate English to German: ...*, +for summarization: *summarize: ...*. +- The pretraining includes both supervised and self-supervised training. Supervised training is conducted on downstream tasks provided by the GLUE and SuperGLUE benchmarks (converting them into text-to-text tasks as explained above). +- Self-supervised training uses corrupted tokens, by randomly removing 15% of the tokens and replacing them with individual sentinel tokens (if several consecutive tokens are marked for removal, the whole group is replaced with a single sentinel token). The input of the encoder is the corrupted sentence, the input of the decoder is the original sentence and the target is then the dropped out tokens delimited by their sentinel tokens. + +- T5 uses relative scalar embeddings. Encoder input padding can be done on the left and on the right. + +- See the [training](#training), [inference](#inference) and [resources](#resources) sections below for all details regarding usage. + +T5 comes in different sizes: + +- [google-t5/t5-small](https://huggingface.co/google-t5/t5-small) + +- [google-t5/t5-base](https://huggingface.co/google-t5/t5-base) + +- [google-t5/t5-large](https://huggingface.co/google-t5/t5-large) + +- [google-t5/t5-3b](https://huggingface.co/google-t5/t5-3b) + +- [google-t5/t5-11b](https://huggingface.co/google-t5/t5-11b). + +Based on the original T5 model, Google has released some follow-up works: + +- **T5v1.1**: T5v1.1 is an improved version of T5 with some architectural tweaks, and is pre-trained on C4 only without + mixing in the supervised tasks. Refer to the documentation of T5v1.1 which can be found [here](t5v1.1). + +- **mT5**: mT5 is a multilingual T5 model. It is pre-trained on the mC4 corpus, which includes 101 languages. Refer to + the documentation of mT5 which can be found [here](mt5). + +- **byT5**: byT5 is a T5 model pre-trained on byte sequences rather than SentencePiece subword token sequences. Refer + to the documentation of byT5 which can be found [here](byt5). + +- **UL2**: UL2 is a T5 like model pretrained on various denoising objectives + +- **Flan-T5**: Flan is a pretraining methods that is based on prompting. The Flan-T5 are T5 models trained on the Flan collection of + datasets which include: `taskmaster2`, `djaym7/wiki_dialog`, `deepmind/code_contests`, `lambada`, `gsm8k`, `aqua_rat`, `esnli`, `quasc` and `qed`. + +- **FLan-UL2** : the UL2 model finetuned using the "Flan" prompt tuning and dataset collection. + +- **UMT5**: UmT5 is a multilingual T5 model trained on an improved and refreshed mC4 multilingual corpus, 29 trillion characters across 107 language, using a new sampling method, UniMax. Refer to + the documentation of mT5 which can be found [here](umt5). + +## Training + +T5 is an encoder-decoder model and converts all NLP problems into a text-to-text format. It is trained using teacher +forcing. This means that for training, we always need an input sequence and a corresponding target sequence. The input +sequence is fed to the model using `input_ids`. The target sequence is shifted to the right, i.e., prepended by a +start-sequence token and fed to the decoder using the `decoder_input_ids`. In teacher-forcing style, the target +sequence is then appended by the EOS token and corresponds to the `labels`. The PAD token is hereby used as the +start-sequence token. T5 can be trained / fine-tuned both in a supervised and unsupervised fashion. + +One can use [`T5ForConditionalGeneration`] (or the Tensorflow/Flax variant), which includes the +language modeling head on top of the decoder. + +- Unsupervised denoising training + +In this setup, spans of the input sequence are masked by so-called sentinel tokens (*a.k.a* unique mask tokens) and +the output sequence is formed as a concatenation of the same sentinel tokens and the *real* masked tokens. Each +sentinel token represents a unique mask token for this sentence and should start with ``, +``, ... up to ``. As a default, 100 sentinel tokens are available in +[`T5Tokenizer`]. + +For instance, the sentence "The cute dog walks in the park" with the masks put on "cute dog" and "the" should be +processed as follows: + +```python +>>> from transformers import T5Tokenizer, T5ForConditionalGeneration + +>>> tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-small") +>>> model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small") + +>>> input_ids = tokenizer("The walks in park", return_tensors="pt").input_ids +>>> labels = tokenizer(" cute dog the ", return_tensors="pt").input_ids + +>>> # the forward function automatically creates the correct decoder_input_ids +>>> loss = model(input_ids=input_ids, labels=labels).loss +>>> loss.item() +3.7837 +``` + +If you're interested in pre-training T5 on a new corpus, check out the [run_t5_mlm_flax.py](https://github.com/huggingface/transformers/tree/main/examples/flax/language-modeling) script in the Examples +directory. + +- Supervised training + +In this setup, the input sequence and output sequence are a standard sequence-to-sequence input-output mapping. +Suppose that we want to fine-tune the model for translation for example, and we have a training example: the input +sequence "The house is wonderful." and output sequence "Das Haus ist wunderbar.", then they should be prepared for +the model as follows: + +```python +>>> from transformers import T5Tokenizer, T5ForConditionalGeneration + +>>> tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-small") +>>> model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small") + +>>> input_ids = tokenizer("translate English to German: The house is wonderful.", return_tensors="pt").input_ids +>>> labels = tokenizer("Das Haus ist wunderbar.", return_tensors="pt").input_ids + +>>> # the forward function automatically creates the correct decoder_input_ids +>>> loss = model(input_ids=input_ids, labels=labels).loss +>>> loss.item() +0.2542 +``` + +As you can see, only 2 inputs are required for the model in order to compute a loss: `input_ids` (which are the +`input_ids` of the encoded input sequence) and `labels` (which are the `input_ids` of the encoded +target sequence). The model will automatically create the `decoder_input_ids` based on the `labels`, by +shifting them one position to the right and prepending the `config.decoder_start_token_id`, which for T5 is +equal to 0 (i.e. the id of the pad token). Also note the task prefix: we prepend the input sequence with 'translate +English to German: ' before encoding it. This will help in improving the performance, as this task prefix was used +during T5's pre-training. + +However, the example above only shows a single training example. In practice, one trains deep learning models in +batches. This entails that we must pad/truncate examples to the same length. For encoder-decoder models, one +typically defines a `max_source_length` and `max_target_length`, which determine the maximum length of the +input and output sequences respectively (otherwise they are truncated). These should be carefully set depending on +the task. + +In addition, we must make sure that padding token id's of the `labels` are not taken into account by the loss +function. In PyTorch and Tensorflow, this can be done by replacing them with -100, which is the `ignore_index` +of the `CrossEntropyLoss`. In Flax, one can use the `decoder_attention_mask` to ignore padded tokens from +the loss (see the [Flax summarization script](https://github.com/huggingface/transformers/tree/main/examples/flax/summarization) for details). We also pass +`attention_mask` as additional input to the model, which makes sure that padding tokens of the inputs are +ignored. The code example below illustrates all of this. + +```python +>>> from transformers import T5Tokenizer, T5ForConditionalGeneration +>>> import torch + +>>> tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-small") +>>> model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small") + +>>> # the following 2 hyperparameters are task-specific +>>> max_source_length = 512 +>>> max_target_length = 128 + +>>> # Suppose we have the following 2 training examples: +>>> input_sequence_1 = "Welcome to NYC" +>>> output_sequence_1 = "Bienvenue ร  NYC" + +>>> input_sequence_2 = "HuggingFace is a company" +>>> output_sequence_2 = "HuggingFace est une entreprise" + +>>> # encode the inputs +>>> task_prefix = "translate English to French: " +>>> input_sequences = [input_sequence_1, input_sequence_2] + +>>> encoding = tokenizer( +... [task_prefix + sequence for sequence in input_sequences], +... padding="longest", +... max_length=max_source_length, +... truncation=True, +... return_tensors="pt", +... ) + +>>> input_ids, attention_mask = encoding.input_ids, encoding.attention_mask + +>>> # encode the targets +>>> target_encoding = tokenizer( +... [output_sequence_1, output_sequence_2], +... padding="longest", +... max_length=max_target_length, +... truncation=True, +... return_tensors="pt", +... ) +>>> labels = target_encoding.input_ids + +>>> # replace padding token id's of the labels by -100 so it's ignored by the loss +>>> labels[labels == tokenizer.pad_token_id] = -100 + +>>> # forward pass +>>> loss = model(input_ids=input_ids, attention_mask=attention_mask, labels=labels).loss +>>> loss.item() +0.188 +``` + +Additional training tips: + +- T5 models need a slightly higher learning rate than the default one set in the `Trainer` when using the AdamW +optimizer. Typically, 1e-4 and 3e-4 work well for most problems (classification, summarization, translation, question +answering, question generation). Note that T5 was pre-trained using the AdaFactor optimizer. + +According to [this forum post](https://discuss.huggingface.co/t/t5-finetuning-tips/684), task prefixes matter when +(1) doing multi-task training (2) your task is similar or related to one of the supervised tasks used in T5's +pre-training mixture (see Appendix D of the [paper](https://arxiv.org/pdf/1910.10683.pdf) for the task prefixes +used). + +If training on TPU, it is recommended to pad all examples of the dataset to the same length or make use of +*pad_to_multiple_of* to have a small number of predefined bucket sizes to fit all examples in. Dynamically padding +batches to the longest example is not recommended on TPU as it triggers a recompilation for every batch shape that is +encountered during training thus significantly slowing down the training. only padding up to the longest example in a +batch) leads to very slow training on TPU. + +## Inference + +At inference time, it is recommended to use [`~generation.GenerationMixin.generate`]. This +method takes care of encoding the input and feeding the encoded hidden states via cross-attention layers to the decoder +and auto-regressively generates the decoder output. Check out [this blog post](https://huggingface.co/blog/how-to-generate) to know all the details about generating text with Transformers. +There's also [this blog post](https://huggingface.co/blog/encoder-decoder#encoder-decoder) which explains how +generation works in general in encoder-decoder models. + +```python +>>> from transformers import T5Tokenizer, T5ForConditionalGeneration + +>>> tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-small") +>>> model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small") + +>>> input_ids = tokenizer("translate English to German: The house is wonderful.", return_tensors="pt").input_ids +>>> outputs = model.generate(input_ids) +>>> print(tokenizer.decode(outputs[0], skip_special_tokens=True)) +Das Haus ist wunderbar. +``` + +Note that T5 uses the `pad_token_id` as the `decoder_start_token_id`, so when doing generation without using +[`~generation.GenerationMixin.generate`], make sure you start it with the `pad_token_id`. + +The example above only shows a single example. You can also do batched inference, like so: + +```python +>>> from transformers import T5Tokenizer, T5ForConditionalGeneration + +>>> tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-small") +>>> model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small") + +>>> task_prefix = "translate English to German: " +>>> # use different length sentences to test batching +>>> sentences = ["The house is wonderful.", "I like to work in NYC."] + +>>> inputs = tokenizer([task_prefix + sentence for sentence in sentences], return_tensors="pt", padding=True) + +>>> output_sequences = model.generate( +... input_ids=inputs["input_ids"], +... attention_mask=inputs["attention_mask"], +... do_sample=False, # disable sampling to test if batching affects output +... ) + +>>> print(tokenizer.batch_decode(output_sequences, skip_special_tokens=True)) +['Das Haus ist wunderbar.', 'Ich arbeite gerne in NYC.'] +``` + +Because T5 has been trained with the span-mask denoising objective, +it can be used to predict the sentinel (masked-out) tokens during inference. +The predicted tokens will then be placed between the sentinel tokens. + +```python +>>> from transformers import T5Tokenizer, T5ForConditionalGeneration + +>>> tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-small") +>>> model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small") + +>>> input_ids = tokenizer("The walks in park", return_tensors="pt").input_ids + +>>> sequence_ids = model.generate(input_ids) +>>> sequences = tokenizer.batch_decode(sequence_ids) +>>> sequences +[' park offers the park.'] +``` + +## Performance + +If you'd like a faster training and inference performance, install [NVIDIA APEX](https://github.com/NVIDIA/apex#quick-start) for NVIDIA GPUs, or [ROCm APEX](https://github.com/ROCmSoftwarePlatform/apex) for AMD GPUs and then the model will automatically use `apex.normalization.FusedRMSNorm` instead of `T5LayerNorm`. The former uses an optimized fused kernel which is several times faster than the latter. + + +## Resources + +A list of official Hugging Face and community (indicated by ๐ŸŒŽ) resources to help you get started with T5. 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 for how to [finetune T5 for classification and multiple choice](https://colab.research.google.com/github/patil-suraj/exploring-T5/blob/master/t5_fine_tuning.ipynb). +- A notebook for how to [finetune T5 for sentiment span extraction](https://colab.research.google.com/github/enzoampil/t5-intro/blob/master/t5_qa_training_pytorch_span_extraction.ipynb). ๐ŸŒŽ + + + +- A notebook for how to [finetune T5 for named entity recognition](https://colab.research.google.com/drive/1obr78FY_cBmWY5ODViCmzdY6O1KB65Vc?usp=sharing). ๐ŸŒŽ + + + +- A notebook for [Finetuning CodeT5 for generating docstrings from Ruby code](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/T5/Fine_tune_CodeT5_for_generating_docstrings_from_Ruby_code.ipynb). + + + +- A notebook to [Finetune T5-base-dutch to perform Dutch abstractive summarization on a TPU](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/T5/Fine_tuning_Dutch_T5_base_on_CNN_Daily_Mail_for_summarization_(on_TPU_using_HuggingFace_Accelerate).ipynb). +- A notebook for how to [finetune T5 for summarization in PyTorch and track experiments with WandB](https://colab.research.google.com/github/abhimishra91/transformers-tutorials/blob/master/transformers_summarization_wandb.ipynb#scrollTo=OKRpFvYhBauC). ๐ŸŒŽ +- A blog post on [Distributed Training: Train BART/T5 for Summarization using ๐Ÿค— Transformers and Amazon SageMaker](https://huggingface.co/blog/sagemaker-distributed-training-seq2seq). +- [`T5ForConditionalGeneration`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/summarization) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/summarization.ipynb). +- [`TFT5ForConditionalGeneration`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/summarization) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/summarization-tf.ipynb). +- [`FlaxT5ForConditionalGeneration`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/flax/summarization). +- [Summarization](https://huggingface.co/course/chapter7/5?fw=pt#summarization) chapter of the ๐Ÿค— Hugging Face course. +- [Summarization task guide](../tasks/summarization) + + + +- [`FlaxT5ForConditionalGeneration`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/flax/language-modeling#t5-like-span-masked-language-modeling) for training T5 with a span-masked language model objective. The script also shows how to train a T5 tokenizer. [`FlaxT5ForConditionalGeneration`] is also supported by this [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/masked_language_modeling_flax.ipynb). + + + +- [`T5ForConditionalGeneration`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/translation) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/translation.ipynb). +- [`TFT5ForConditionalGeneration`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/translation) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/translation-tf.ipynb). +- [Translation task guide](../tasks/translation) + + + +- A notebook on how to [finetune T5 for question answering with TensorFlow 2](https://colab.research.google.com/github/snapthat/TF-T5-text-to-text/blob/master/snapthatT5/notebooks/TF-T5-Datasets%20Training.ipynb). ๐ŸŒŽ +- A notebook on how to [finetune T5 for question answering on a TPU](https://colab.research.google.com/github/patil-suraj/exploring-T5/blob/master/T5_on_TPU.ipynb#scrollTo=QLGiFCDqvuil). + +๐Ÿš€ **Deploy** +- A blog post on how to deploy [T5 11B for inference for less than $500](https://www.philschmid.de/deploy-t5-11b). + +## T5Config + +[[autodoc]] T5Config + +## T5Tokenizer + +[[autodoc]] T5Tokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary + +## T5TokenizerFast + +[[autodoc]] T5TokenizerFast + + + + +## T5Model + +[[autodoc]] T5Model + - forward + +## T5ForConditionalGeneration + +[[autodoc]] T5ForConditionalGeneration + - forward + +## T5EncoderModel + +[[autodoc]] T5EncoderModel + - forward + +## T5ForSequenceClassification + +[[autodoc]] T5ForSequenceClassification + - forward + +## T5ForTokenClassification + +[[autodoc]] T5ForTokenClassification + - forward + +## T5ForQuestionAnswering + +[[autodoc]] T5ForQuestionAnswering + - forward + + + + +## TFT5Model + +[[autodoc]] TFT5Model + - call + +## TFT5ForConditionalGeneration + +[[autodoc]] TFT5ForConditionalGeneration + - call + +## TFT5EncoderModel + +[[autodoc]] TFT5EncoderModel + - call + + + + +## FlaxT5Model + +[[autodoc]] FlaxT5Model + - __call__ + - encode + - decode + +## FlaxT5ForConditionalGeneration + +[[autodoc]] FlaxT5ForConditionalGeneration + - __call__ + - encode + - decode + +## FlaxT5EncoderModel + +[[autodoc]] FlaxT5EncoderModel + - __call__ + + + diff --git a/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/t5v1.1.md b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/t5v1.1.md new file mode 100644 index 0000000000000000000000000000000000000000..e18696f629df51c93af94f16d4365305e65d9875 --- /dev/null +++ b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/t5v1.1.md @@ -0,0 +1,71 @@ + + +# T5v1.1 + +## Overview + +T5v1.1 was released in the [google-research/text-to-text-transfer-transformer](https://github.com/google-research/text-to-text-transfer-transformer/blob/main/released_checkpoints.md#t511) +repository by Colin Raffel et al. It's an improved version of the original T5 model. +This model was contributed by [patrickvonplaten](https://huggingface.co/patrickvonplaten). The original code can be +found [here](https://github.com/google-research/text-to-text-transfer-transformer/blob/main/released_checkpoints.md#t511). + +## Usage tips + +One can directly plug in the weights of T5v1.1 into a T5 model, like so: + +```python +>>> from transformers import T5ForConditionalGeneration + +>>> model = T5ForConditionalGeneration.from_pretrained("google/t5-v1_1-base") +``` + +T5 Version 1.1 includes the following improvements compared to the original T5 model: + +- GEGLU activation in the feed-forward hidden layer, rather than ReLU. See [this paper](https://arxiv.org/abs/2002.05202). + +- Dropout was turned off in pre-training (quality win). Dropout should be re-enabled during fine-tuning. + +- Pre-trained on C4 only without mixing in the downstream tasks. + +- No parameter sharing between the embedding and classifier layer. + +- "xl" and "xxl" replace "3B" and "11B". The model shapes are a bit different - larger `d_model` and smaller + `num_heads` and `d_ff`. + +Note: T5 Version 1.1 was only pre-trained on [C4](https://huggingface.co/datasets/c4) excluding any supervised +training. Therefore, this model has to be fine-tuned before it is usable on a downstream task, unlike the original T5 +model. Since t5v1.1 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. + +Google has released the following variants: + +- [google/t5-v1_1-small](https://huggingface.co/google/t5-v1_1-small) + +- [google/t5-v1_1-base](https://huggingface.co/google/t5-v1_1-base) + +- [google/t5-v1_1-large](https://huggingface.co/google/t5-v1_1-large) + +- [google/t5-v1_1-xl](https://huggingface.co/google/t5-v1_1-xl) + +- [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl). + + + + +Refer to [T5's documentation page](t5) for all API reference, tips, code examples and notebooks. + + \ No newline at end of file diff --git a/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/table-transformer.md b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/table-transformer.md new file mode 100644 index 0000000000000000000000000000000000000000..850e7f50aa610f9548c395ab37eaa2d9e681dd99 --- /dev/null +++ b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/table-transformer.md @@ -0,0 +1,67 @@ + + +# Table Transformer + +## Overview + +The Table Transformer model was proposed in [PubTables-1M: Towards comprehensive table extraction from unstructured documents](https://arxiv.org/abs/2110.00061) by +Brandon Smock, Rohith Pesala, Robin Abraham. The authors introduce a new dataset, PubTables-1M, to benchmark progress in table extraction from unstructured documents, +as well as table structure recognition and functional analysis. The authors train 2 [DETR](detr) models, one for table detection and one for table structure recognition, dubbed Table Transformers. + +The abstract from the paper is the following: + +*Recently, significant progress has been made applying machine learning to the problem of table structure inference and extraction from unstructured documents. +However, one of the greatest challenges remains the creation of datasets with complete, unambiguous ground truth at scale. To address this, we develop a new, more +comprehensive dataset for table extraction, called PubTables-1M. PubTables-1M contains nearly one million tables from scientific articles, supports multiple input +modalities, and contains detailed header and location information for table structures, making it useful for a wide variety of modeling approaches. It also addresses a significant +source of ground truth inconsistency observed in prior datasets called oversegmentation, using a novel canonicalization procedure. We demonstrate that these improvements lead to a +significant increase in training performance and a more reliable estimate of model performance at evaluation for table structure recognition. Further, we show that transformer-based +object detection models trained on PubTables-1M produce excellent results for all three tasks of detection, structure recognition, and functional analysis without the need for any +special customization for these tasks.* + + + + Table detection and table structure recognition clarified. Taken from the original paper. + +The authors released 2 models, one for [table detection](https://huggingface.co/microsoft/table-transformer-detection) in +documents, one for [table structure recognition](https://huggingface.co/microsoft/table-transformer-structure-recognition) +(the task of recognizing the individual rows, columns etc. in a table). + +This model was contributed by [nielsr](https://huggingface.co/nielsr). The original code can be +found [here](https://github.com/microsoft/table-transformer). + +## Resources + + + +- A demo notebook for the Table Transformer can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/Table%20Transformer). +- It turns out padding of images is quite important for detection. An interesting Github thread with replies from the authors can be found [here](https://github.com/microsoft/table-transformer/issues/68). + +## TableTransformerConfig + +[[autodoc]] TableTransformerConfig + +## TableTransformerModel + +[[autodoc]] TableTransformerModel + - forward + +## TableTransformerForObjectDetection + +[[autodoc]] TableTransformerForObjectDetection + - forward diff --git a/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/tapas.md b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/tapas.md new file mode 100644 index 0000000000000000000000000000000000000000..79bbe3e819cf864728baea5a5d556a42ca740202 --- /dev/null +++ b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/tapas.md @@ -0,0 +1,634 @@ + + +# TAPAS + +## Overview + +The TAPAS model was proposed in [TAPAS: Weakly Supervised Table Parsing via Pre-training](https://www.aclweb.org/anthology/2020.acl-main.398) +by Jonathan Herzig, Paweล‚ Krzysztof Nowak, Thomas Mรผller, Francesco Piccinno and Julian Martin Eisenschlos. It's a BERT-based model specifically +designed (and pre-trained) for answering questions about tabular data. Compared to BERT, TAPAS uses relative position embeddings and has 7 +token types that encode tabular structure. TAPAS is pre-trained on the masked language modeling (MLM) objective on a large dataset comprising +millions of tables from English Wikipedia and corresponding texts. + +For question answering, TAPAS has 2 heads on top: a cell selection head and an aggregation head, for (optionally) performing aggregations (such as counting or summing) among selected cells. TAPAS has been fine-tuned on several datasets: +- [SQA](https://www.microsoft.com/en-us/download/details.aspx?id=54253) (Sequential Question Answering by Microsoft) +- [WTQ](https://github.com/ppasupat/WikiTableQuestions) (Wiki Table Questions by Stanford University) +- [WikiSQL](https://github.com/salesforce/WikiSQL) (by Salesforce). + +It achieves state-of-the-art on both SQA and WTQ, while having comparable performance to SOTA on WikiSQL, with a much simpler architecture. + +The abstract from the paper is the following: + +*Answering natural language questions over tables is usually seen as a semantic parsing task. To alleviate the collection cost of full logical forms, one popular approach focuses on weak supervision consisting of denotations instead of logical forms. However, training semantic parsers from weak supervision poses difficulties, and in addition, the generated logical forms are only used as an intermediate step prior to retrieving the denotation. In this paper, we present TAPAS, an approach to question answering over tables without generating logical forms. TAPAS trains from weak supervision, and predicts the denotation by selecting table cells and optionally applying a corresponding aggregation operator to such selection. TAPAS extends BERT's architecture to encode tables as input, initializes from an effective joint pre-training of text segments and tables crawled from Wikipedia, and is trained end-to-end. We experiment with three different semantic parsing datasets, and find that TAPAS outperforms or rivals semantic parsing models by improving state-of-the-art accuracy on SQA from 55.1 to 67.2 and performing on par with the state-of-the-art on WIKISQL and WIKITQ, but with a simpler model architecture. We additionally find that transfer learning, which is trivial in our setting, from WIKISQL to WIKITQ, yields 48.7 accuracy, 4.2 points above the state-of-the-art.* + +In addition, the authors have further pre-trained TAPAS to recognize **table entailment**, by creating a balanced dataset of millions of automatically created training examples which are learned in an intermediate step prior to fine-tuning. The authors of TAPAS call this further pre-training intermediate pre-training (since TAPAS is first pre-trained on MLM, and then on another dataset). They found that intermediate pre-training further improves performance on SQA, achieving a new state-of-the-art as well as state-of-the-art on [TabFact](https://github.com/wenhuchen/Table-Fact-Checking), a large-scale dataset with 16k Wikipedia tables for table entailment (a binary classification task). For more details, see their follow-up paper: [Understanding tables with intermediate pre-training](https://www.aclweb.org/anthology/2020.findings-emnlp.27/) by Julian Martin Eisenschlos, Syrine Krichene and Thomas Mรผller. + + + + TAPAS architecture. Taken from the original blog post. + +This model was contributed by [nielsr](https://huggingface.co/nielsr). The Tensorflow version of this model was contributed by [kamalkraj](https://huggingface.co/kamalkraj). The original code can be found [here](https://github.com/google-research/tapas). + +## Usage tips + +- TAPAS is a model that uses relative position embeddings by default (restarting the position embeddings at every cell of the table). Note that this is something that was added after the publication of the original TAPAS paper. According to the authors, this usually results in a slightly better performance, and allows you to encode longer sequences without running out of embeddings. This is reflected in the `reset_position_index_per_cell` parameter of [`TapasConfig`], which is set to `True` by default. The default versions of the models available on the [hub](https://huggingface.co/models?search=tapas) all use relative position embeddings. You can still use the ones with absolute position embeddings by passing in an additional argument `revision="no_reset"` when calling the `from_pretrained()` method. Note that it's usually advised to pad the inputs on the right rather than the left. +- TAPAS is based on BERT, so `TAPAS-base` for example corresponds to a `BERT-base` architecture. Of course, `TAPAS-large` will result in the best performance (the results reported in the paper are from `TAPAS-large`). Results of the various sized models are shown on the [original GitHub repository](https://github.com/google-research/tapas). +- TAPAS has checkpoints fine-tuned on SQA, which are capable of answering questions related to a table in a conversational set-up. This means that you can ask follow-up questions such as "what is his age?" related to the previous question. Note that the forward pass of TAPAS is a bit different in case of a conversational set-up: in that case, you have to feed every table-question pair one by one to the model, such that the `prev_labels` token type ids can be overwritten by the predicted `labels` of the model to the previous question. See "Usage" section for more info. +- TAPAS is similar to BERT and therefore relies on the masked language modeling (MLM) objective. It is therefore efficient at predicting masked tokens and at NLU in general, but is not optimal for text generation. Models trained with a causal language modeling (CLM) objective are better in that regard. Note that TAPAS can be used as an encoder in the EncoderDecoderModel framework, to combine it with an autoregressive text decoder such as GPT-2. + +## Usage: fine-tuning + +Here we explain how you can fine-tune [`TapasForQuestionAnswering`] on your own dataset. + +**STEP 1: Choose one of the 3 ways in which you can use TAPAS - or experiment** + +Basically, there are 3 different ways in which one can fine-tune [`TapasForQuestionAnswering`], corresponding to the different datasets on which Tapas was fine-tuned: + +1. SQA: if you're interested in asking follow-up questions related to a table, in a conversational set-up. For example if you first ask "what's the name of the first actor?" then you can ask a follow-up question such as "how old is he?". Here, questions do not involve any aggregation (all questions are cell selection questions). +2. WTQ: if you're not interested in asking questions in a conversational set-up, but rather just asking questions related to a table, which might involve aggregation, such as counting a number of rows, summing up cell values or averaging cell values. You can then for example ask "what's the total number of goals Cristiano Ronaldo made in his career?". This case is also called **weak supervision**, since the model itself must learn the appropriate aggregation operator (SUM/COUNT/AVERAGE/NONE) given only the answer to the question as supervision. +3. WikiSQL-supervised: this dataset is based on WikiSQL with the model being given the ground truth aggregation operator during training. This is also called **strong supervision**. Here, learning the appropriate aggregation operator is much easier. + +To summarize: + +| **Task** | **Example dataset** | **Description** | +|-------------------------------------|---------------------|---------------------------------------------------------------------------------------------------------| +| Conversational | SQA | Conversational, only cell selection questions | +| Weak supervision for aggregation | WTQ | Questions might involve aggregation, and the model must learn this given only the answer as supervision | +| Strong supervision for aggregation | WikiSQL-supervised | Questions might involve aggregation, and the model must learn this given the gold aggregation operator | + + + +Initializing a model with a pre-trained base and randomly initialized classification heads from the hub can be done as shown below. + +```py +>>> from transformers import TapasConfig, TapasForQuestionAnswering + +>>> # for example, the base sized model with default SQA configuration +>>> model = TapasForQuestionAnswering.from_pretrained("google/tapas-base") + +>>> # or, the base sized model with WTQ configuration +>>> config = TapasConfig.from_pretrained("google/tapas-base-finetuned-wtq") +>>> model = TapasForQuestionAnswering.from_pretrained("google/tapas-base", config=config) + +>>> # or, the base sized model with WikiSQL configuration +>>> config = TapasConfig("google-base-finetuned-wikisql-supervised") +>>> model = TapasForQuestionAnswering.from_pretrained("google/tapas-base", config=config) +``` + +Of course, you don't necessarily have to follow one of these three ways in which TAPAS was fine-tuned. You can also experiment by defining any hyperparameters you want when initializing [`TapasConfig`], and then create a [`TapasForQuestionAnswering`] based on that configuration. For example, if you have a dataset that has both conversational questions and questions that might involve aggregation, then you can do it this way. Here's an example: + +```py +>>> from transformers import TapasConfig, TapasForQuestionAnswering + +>>> # you can initialize the classification heads any way you want (see docs of TapasConfig) +>>> config = TapasConfig(num_aggregation_labels=3, average_logits_per_cell=True) +>>> # initializing the pre-trained base sized model with our custom classification heads +>>> model = TapasForQuestionAnswering.from_pretrained("google/tapas-base", config=config) +``` + + +Initializing a model with a pre-trained base and randomly initialized classification heads from the hub can be done as shown below. Be sure to have installed the [tensorflow_probability](https://github.com/tensorflow/probability) dependency: + +```py +>>> from transformers import TapasConfig, TFTapasForQuestionAnswering + +>>> # for example, the base sized model with default SQA configuration +>>> model = TFTapasForQuestionAnswering.from_pretrained("google/tapas-base") + +>>> # or, the base sized model with WTQ configuration +>>> config = TapasConfig.from_pretrained("google/tapas-base-finetuned-wtq") +>>> model = TFTapasForQuestionAnswering.from_pretrained("google/tapas-base", config=config) + +>>> # or, the base sized model with WikiSQL configuration +>>> config = TapasConfig("google-base-finetuned-wikisql-supervised") +>>> model = TFTapasForQuestionAnswering.from_pretrained("google/tapas-base", config=config) +``` + +Of course, you don't necessarily have to follow one of these three ways in which TAPAS was fine-tuned. You can also experiment by defining any hyperparameters you want when initializing [`TapasConfig`], and then create a [`TFTapasForQuestionAnswering`] based on that configuration. For example, if you have a dataset that has both conversational questions and questions that might involve aggregation, then you can do it this way. Here's an example: + +```py +>>> from transformers import TapasConfig, TFTapasForQuestionAnswering + +>>> # you can initialize the classification heads any way you want (see docs of TapasConfig) +>>> config = TapasConfig(num_aggregation_labels=3, average_logits_per_cell=True) +>>> # initializing the pre-trained base sized model with our custom classification heads +>>> model = TFTapasForQuestionAnswering.from_pretrained("google/tapas-base", config=config) +``` + + + +What you can also do is start from an already fine-tuned checkpoint. A note here is that the already fine-tuned checkpoint on WTQ has some issues due to the L2-loss which is somewhat brittle. See [here](https://github.com/google-research/tapas/issues/91#issuecomment-735719340) for more info. + +For a list of all pre-trained and fine-tuned TAPAS checkpoints available on HuggingFace's hub, see [here](https://huggingface.co/models?search=tapas). + +**STEP 2: Prepare your data in the SQA format** + +Second, no matter what you picked above, you should prepare your dataset in the [SQA](https://www.microsoft.com/en-us/download/details.aspx?id=54253) format. This format is a TSV/CSV file with the following columns: + +- `id`: optional, id of the table-question pair, for bookkeeping purposes. +- `annotator`: optional, id of the person who annotated the table-question pair, for bookkeeping purposes. +- `position`: integer indicating if the question is the first, second, third,... related to the table. Only required in case of conversational setup (SQA). You don't need this column in case you're going for WTQ/WikiSQL-supervised. +- `question`: string +- `table_file`: string, name of a csv file containing the tabular data +- `answer_coordinates`: list of one or more tuples (each tuple being a cell coordinate, i.e. row, column pair that is part of the answer) +- `answer_text`: list of one or more strings (each string being a cell value that is part of the answer) +- `aggregation_label`: index of the aggregation operator. Only required in case of strong supervision for aggregation (the WikiSQL-supervised case) +- `float_answer`: the float answer to the question, if there is one (np.nan if there isn't). Only required in case of weak supervision for aggregation (such as WTQ and WikiSQL) + +The tables themselves should be present in a folder, each table being a separate csv file. Note that the authors of the TAPAS algorithm used conversion scripts with some automated logic to convert the other datasets (WTQ, WikiSQL) into the SQA format. The author explains this [here](https://github.com/google-research/tapas/issues/50#issuecomment-705465960). A conversion of this script that works with HuggingFace's implementation can be found [here](https://github.com/NielsRogge/tapas_utils). Interestingly, these conversion scripts are not perfect (the `answer_coordinates` and `float_answer` fields are populated based on the `answer_text`), meaning that WTQ and WikiSQL results could actually be improved. + +**STEP 3: Convert your data into tensors using TapasTokenizer** + + + +Third, given that you've prepared your data in this TSV/CSV format (and corresponding CSV files containing the tabular data), you can then use [`TapasTokenizer`] to convert table-question pairs into `input_ids`, `attention_mask`, `token_type_ids` and so on. Again, based on which of the three cases you picked above, [`TapasForQuestionAnswering`] requires different +inputs to be fine-tuned: + +| **Task** | **Required inputs** | +|------------------------------------|---------------------------------------------------------------------------------------------------------------------| +| Conversational | `input_ids`, `attention_mask`, `token_type_ids`, `labels` | +| Weak supervision for aggregation | `input_ids`, `attention_mask`, `token_type_ids`, `labels`, `numeric_values`, `numeric_values_scale`, `float_answer` | +| Strong supervision for aggregation | `input ids`, `attention mask`, `token type ids`, `labels`, `aggregation_labels` | + +[`TapasTokenizer`] creates the `labels`, `numeric_values` and `numeric_values_scale` based on the `answer_coordinates` and `answer_text` columns of the TSV file. The `float_answer` and `aggregation_labels` are already in the TSV file of step 2. Here's an example: + +```py +>>> from transformers import TapasTokenizer +>>> import pandas as pd + +>>> model_name = "google/tapas-base" +>>> 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?", +... ] +>>> answer_coordinates = [[(0, 0)], [(2, 1)], [(0, 1), (1, 1), (2, 1)]] +>>> answer_text = [["Brad Pitt"], ["69"], ["209"]] +>>> table = pd.DataFrame.from_dict(data) +>>> inputs = tokenizer( +... table=table, +... queries=queries, +... answer_coordinates=answer_coordinates, +... answer_text=answer_text, +... padding="max_length", +... return_tensors="pt", +... ) +>>> inputs +{'input_ids': tensor([[ ... ]]), 'attention_mask': tensor([[...]]), 'token_type_ids': tensor([[[...]]]), +'numeric_values': tensor([[ ... ]]), 'numeric_values_scale: tensor([[ ... ]]), labels: tensor([[ ... ]])} +``` + +Note that [`TapasTokenizer`] expects the data of the table to be **text-only**. You can use `.astype(str)` on a dataframe to turn it into text-only data. +Of course, this only shows how to encode a single training example. It is advised to create a dataloader to iterate over batches: + +```py +>>> import torch +>>> import pandas as pd + +>>> tsv_path = "your_path_to_the_tsv_file" +>>> table_csv_path = "your_path_to_a_directory_containing_all_csv_files" + + +>>> class TableDataset(torch.utils.data.Dataset): +... def __init__(self, data, tokenizer): +... self.data = data +... self.tokenizer = tokenizer + +... def __getitem__(self, idx): +... item = data.iloc[idx] +... table = pd.read_csv(table_csv_path + item.table_file).astype( +... str +... ) # be sure to make your table data text only +... encoding = self.tokenizer( +... table=table, +... queries=item.question, +... answer_coordinates=item.answer_coordinates, +... answer_text=item.answer_text, +... truncation=True, +... padding="max_length", +... return_tensors="pt", +... ) +... # remove the batch dimension which the tokenizer adds by default +... encoding = {key: val.squeeze(0) for key, val in encoding.items()} +... # add the float_answer which is also required (weak supervision for aggregation case) +... encoding["float_answer"] = torch.tensor(item.float_answer) +... return encoding + +... def __len__(self): +... return len(self.data) + + +>>> data = pd.read_csv(tsv_path, sep="\t") +>>> train_dataset = TableDataset(data, tokenizer) +>>> train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=32) +``` + + +Third, given that you've prepared your data in this TSV/CSV format (and corresponding CSV files containing the tabular data), you can then use [`TapasTokenizer`] to convert table-question pairs into `input_ids`, `attention_mask`, `token_type_ids` and so on. Again, based on which of the three cases you picked above, [`TFTapasForQuestionAnswering`] requires different +inputs to be fine-tuned: + +| **Task** | **Required inputs** | +|------------------------------------|---------------------------------------------------------------------------------------------------------------------| +| Conversational | `input_ids`, `attention_mask`, `token_type_ids`, `labels` | +| Weak supervision for aggregation | `input_ids`, `attention_mask`, `token_type_ids`, `labels`, `numeric_values`, `numeric_values_scale`, `float_answer` | +| Strong supervision for aggregation | `input ids`, `attention mask`, `token type ids`, `labels`, `aggregation_labels` | + +[`TapasTokenizer`] creates the `labels`, `numeric_values` and `numeric_values_scale` based on the `answer_coordinates` and `answer_text` columns of the TSV file. The `float_answer` and `aggregation_labels` are already in the TSV file of step 2. Here's an example: + +```py +>>> from transformers import TapasTokenizer +>>> import pandas as pd + +>>> model_name = "google/tapas-base" +>>> 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?", +... ] +>>> answer_coordinates = [[(0, 0)], [(2, 1)], [(0, 1), (1, 1), (2, 1)]] +>>> answer_text = [["Brad Pitt"], ["69"], ["209"]] +>>> table = pd.DataFrame.from_dict(data) +>>> inputs = tokenizer( +... table=table, +... queries=queries, +... answer_coordinates=answer_coordinates, +... answer_text=answer_text, +... padding="max_length", +... return_tensors="tf", +... ) +>>> inputs +{'input_ids': tensor([[ ... ]]), 'attention_mask': tensor([[...]]), 'token_type_ids': tensor([[[...]]]), +'numeric_values': tensor([[ ... ]]), 'numeric_values_scale: tensor([[ ... ]]), labels: tensor([[ ... ]])} +``` + +Note that [`TapasTokenizer`] expects the data of the table to be **text-only**. You can use `.astype(str)` on a dataframe to turn it into text-only data. +Of course, this only shows how to encode a single training example. It is advised to create a dataloader to iterate over batches: + +```py +>>> import tensorflow as tf +>>> import pandas as pd + +>>> tsv_path = "your_path_to_the_tsv_file" +>>> table_csv_path = "your_path_to_a_directory_containing_all_csv_files" + + +>>> class TableDataset: +... def __init__(self, data, tokenizer): +... self.data = data +... self.tokenizer = tokenizer + +... def __iter__(self): +... for idx in range(self.__len__()): +... item = self.data.iloc[idx] +... table = pd.read_csv(table_csv_path + item.table_file).astype( +... str +... ) # be sure to make your table data text only +... encoding = self.tokenizer( +... table=table, +... queries=item.question, +... answer_coordinates=item.answer_coordinates, +... answer_text=item.answer_text, +... truncation=True, +... padding="max_length", +... return_tensors="tf", +... ) +... # remove the batch dimension which the tokenizer adds by default +... encoding = {key: tf.squeeze(val, 0) for key, val in encoding.items()} +... # add the float_answer which is also required (weak supervision for aggregation case) +... encoding["float_answer"] = tf.convert_to_tensor(item.float_answer, dtype=tf.float32) +... yield encoding["input_ids"], encoding["attention_mask"], encoding["numeric_values"], encoding[ +... "numeric_values_scale" +... ], encoding["token_type_ids"], encoding["labels"], encoding["float_answer"] + +... def __len__(self): +... return len(self.data) + + +>>> data = pd.read_csv(tsv_path, sep="\t") +>>> train_dataset = TableDataset(data, tokenizer) +>>> output_signature = ( +... tf.TensorSpec(shape=(512,), dtype=tf.int32), +... tf.TensorSpec(shape=(512,), dtype=tf.int32), +... tf.TensorSpec(shape=(512,), dtype=tf.float32), +... tf.TensorSpec(shape=(512,), dtype=tf.float32), +... tf.TensorSpec(shape=(512, 7), dtype=tf.int32), +... tf.TensorSpec(shape=(512,), dtype=tf.int32), +... tf.TensorSpec(shape=(512,), dtype=tf.float32), +... ) +>>> train_dataloader = tf.data.Dataset.from_generator(train_dataset, output_signature=output_signature).batch(32) +``` + + + +Note that here, we encode each table-question pair independently. This is fine as long as your dataset is **not conversational**. In case your dataset involves conversational questions (such as in SQA), then you should first group together the `queries`, `answer_coordinates` and `answer_text` per table (in the order of their `position` +index) and batch encode each table with its questions. This will make sure that the `prev_labels` token types (see docs of [`TapasTokenizer`]) are set correctly. See [this notebook](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/TAPAS/Fine_tuning_TapasForQuestionAnswering_on_SQA.ipynb) for more info. See [this notebook](https://github.com/kamalkraj/Tapas-Tutorial/blob/master/TAPAS/Fine_tuning_TapasForQuestionAnswering_on_SQA.ipynb) for more info regarding using the TensorFlow model. + +**STEP 4: Train (fine-tune) the model + + + +You can then fine-tune [`TapasForQuestionAnswering`] as follows (shown here for the weak supervision for aggregation case): + +```py +>>> from transformers import TapasConfig, TapasForQuestionAnswering, AdamW + +>>> # this is the default WTQ configuration +>>> config = TapasConfig( +... num_aggregation_labels=4, +... use_answer_as_supervision=True, +... answer_loss_cutoff=0.664694, +... cell_selection_preference=0.207951, +... huber_loss_delta=0.121194, +... init_cell_selection_weights_to_zero=True, +... select_one_column=True, +... allow_empty_column_selection=False, +... temperature=0.0352513, +... ) +>>> model = TapasForQuestionAnswering.from_pretrained("google/tapas-base", config=config) + +>>> optimizer = AdamW(model.parameters(), lr=5e-5) + +>>> model.train() +>>> for epoch in range(2): # loop over the dataset multiple times +... for batch in train_dataloader: +... # get the inputs; +... input_ids = batch["input_ids"] +... attention_mask = batch["attention_mask"] +... token_type_ids = batch["token_type_ids"] +... labels = batch["labels"] +... numeric_values = batch["numeric_values"] +... numeric_values_scale = batch["numeric_values_scale"] +... float_answer = batch["float_answer"] + +... # zero the parameter gradients +... optimizer.zero_grad() + +... # forward + backward + optimize +... outputs = model( +... input_ids=input_ids, +... attention_mask=attention_mask, +... token_type_ids=token_type_ids, +... labels=labels, +... numeric_values=numeric_values, +... numeric_values_scale=numeric_values_scale, +... float_answer=float_answer, +... ) +... loss = outputs.loss +... loss.backward() +... optimizer.step() +``` + + +You can then fine-tune [`TFTapasForQuestionAnswering`] as follows (shown here for the weak supervision for aggregation case): + +```py +>>> import tensorflow as tf +>>> from transformers import TapasConfig, TFTapasForQuestionAnswering + +>>> # this is the default WTQ configuration +>>> config = TapasConfig( +... num_aggregation_labels=4, +... use_answer_as_supervision=True, +... answer_loss_cutoff=0.664694, +... cell_selection_preference=0.207951, +... huber_loss_delta=0.121194, +... init_cell_selection_weights_to_zero=True, +... select_one_column=True, +... allow_empty_column_selection=False, +... temperature=0.0352513, +... ) +>>> model = TFTapasForQuestionAnswering.from_pretrained("google/tapas-base", config=config) + +>>> optimizer = tf.keras.optimizers.Adam(learning_rate=5e-5) + +>>> for epoch in range(2): # loop over the dataset multiple times +... for batch in train_dataloader: +... # get the inputs; +... input_ids = batch[0] +... attention_mask = batch[1] +... token_type_ids = batch[4] +... labels = batch[-1] +... numeric_values = batch[2] +... numeric_values_scale = batch[3] +... float_answer = batch[6] + +... # forward + backward + optimize +... with tf.GradientTape() as tape: +... outputs = model( +... input_ids=input_ids, +... attention_mask=attention_mask, +... token_type_ids=token_type_ids, +... labels=labels, +... numeric_values=numeric_values, +... numeric_values_scale=numeric_values_scale, +... float_answer=float_answer, +... ) +... grads = tape.gradient(outputs.loss, model.trainable_weights) +... optimizer.apply_gradients(zip(grads, model.trainable_weights)) +``` + + + +## Usage: inference + + + +Here we explain how you can use [`TapasForQuestionAnswering`] or [`TFTapasForQuestionAnswering`] for inference (i.e. making predictions on new data). For inference, only `input_ids`, `attention_mask` and `token_type_ids` (which you can obtain using [`TapasTokenizer`]) have to be provided to the model to obtain the logits. Next, you can use the handy [`~models.tapas.tokenization_tapas.convert_logits_to_predictions`] method to convert these into predicted coordinates and optional aggregation indices. + +However, note that inference is **different** depending on whether or not the setup is conversational. In a non-conversational set-up, inference can be done in parallel on all table-question pairs of a batch. Here's an example of that: + +```py +>>> from transformers import TapasTokenizer, TapasForQuestionAnswering +>>> import pandas as pd + +>>> model_name = "google/tapas-base-finetuned-wtq" +>>> model = TapasForQuestionAnswering.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="pt") +>>> outputs = model(**inputs) +>>> predicted_answer_coordinates, predicted_aggregation_indices = tokenizer.convert_logits_to_predictions( +... inputs, outputs.logits.detach(), outputs.logits_aggregation.detach() +... ) + +>>> # 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 +``` + + +Here we explain how you can use [`TFTapasForQuestionAnswering`] for inference (i.e. making predictions on new data). For inference, only `input_ids`, `attention_mask` and `token_type_ids` (which you can obtain using [`TapasTokenizer`]) have to be provided to the model to obtain the logits. Next, you can use the handy [`~models.tapas.tokenization_tapas.convert_logits_to_predictions`] method to convert these into predicted coordinates and optional aggregation indices. + +However, note that inference is **different** depending on whether or not the setup is conversational. In a non-conversational set-up, inference can be done in parallel on all table-question pairs of a batch. Here's an example of that: + +```py +>>> 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](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/TAPAS/Fine_tuning_TapasForQuestionAnswering_on_SQA.ipynb) (for PyTorch) and [this notebook](https://github.com/kamalkraj/Tapas-Tutorial/blob/master/TAPAS/Fine_tuning_TapasForQuestionAnswering_on_SQA.ipynb) (for TensorFlow). + +## Resources + +- [Text classification task guide](../tasks/sequence_classification) +- [Masked language modeling task guide](../tasks/masked_language_modeling) + +## 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 + + + + + diff --git a/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/tapex.md b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/tapex.md new file mode 100644 index 0000000000000000000000000000000000000000..15ac2463fd851dca72d82c43ab05a1253e202dce --- /dev/null +++ b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/tapex.md @@ -0,0 +1,149 @@ + + +# TAPEX + + + +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 TAPEX model was proposed in [TAPEX: Table Pre-training via Learning a Neural SQL Executor](https://arxiv.org/abs/2107.07653) by Qian Liu, +Bei Chen, Jiaqi Guo, Morteza Ziyadi, Zeqi Lin, Weizhu Chen, Jian-Guang Lou. TAPEX pre-trains a BART model to solve synthetic SQL queries, after +which it can be fine-tuned to answer natural language questions related to tabular data, as well as performing table fact checking. + +TAPEX has been fine-tuned on several datasets: +- [SQA](https://www.microsoft.com/en-us/download/details.aspx?id=54253) (Sequential Question Answering by Microsoft) +- [WTQ](https://github.com/ppasupat/WikiTableQuestions) (Wiki Table Questions by Stanford University) +- [WikiSQL](https://github.com/salesforce/WikiSQL) (by Salesforce) +- [TabFact](https://tabfact.github.io/) (by USCB NLP Lab). + +The abstract from the paper is the following: + +*Recent progress in language model pre-training has achieved a great success via leveraging large-scale unstructured textual data. However, it is +still a challenge to apply pre-training on structured tabular data due to the absence of large-scale high-quality tabular data. In this paper, we +propose TAPEX to show that table pre-training can be achieved by learning a neural SQL executor over a synthetic corpus, which is obtained by automatically +synthesizing executable SQL queries and their execution outputs. TAPEX addresses the data scarcity challenge via guiding the language model to mimic a SQL +executor on the diverse, large-scale and high-quality synthetic corpus. We evaluate TAPEX on four benchmark datasets. Experimental results demonstrate that +TAPEX outperforms previous table pre-training approaches by a large margin and achieves new state-of-the-art results on all of them. This includes improvements +on the weakly-supervised WikiSQL denotation accuracy to 89.5% (+2.3%), the WikiTableQuestions denotation accuracy to 57.5% (+4.8%), the SQA denotation accuracy +to 74.5% (+3.5%), and the TabFact accuracy to 84.2% (+3.2%). To our knowledge, this is the first work to exploit table pre-training via synthetic executable programs +and to achieve new state-of-the-art results on various downstream tasks.* + +## Usage tips + +- TAPEX is a generative (seq2seq) model. One can directly plug in the weights of TAPEX into a BART model. +- TAPEX has checkpoints on the hub that are either pre-trained only, or fine-tuned on WTQ, SQA, WikiSQL and TabFact. +- Sentences + tables are presented to the model as `sentence + " " + linearized table`. The linearized table has the following format: + `col: col1 | col2 | col 3 row 1 : val1 | val2 | val3 row 2 : ...`. +- TAPEX has its own tokenizer, that allows to prepare all data for the model easily. One can pass Pandas DataFrames and strings to the tokenizer, + and it will automatically create the `input_ids` and `attention_mask` (as shown in the usage examples below). + +### Usage: inference + +Below, we illustrate how to use TAPEX for table question answering. As one can see, one can directly plug in the weights of TAPEX into a BART model. +We use the [Auto API](auto), which will automatically instantiate the appropriate tokenizer ([`TapexTokenizer`]) and model ([`BartForConditionalGeneration`]) for us, +based on the configuration file of the checkpoint on the hub. + +```python +>>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM +>>> import pandas as pd + +>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/tapex-large-finetuned-wtq") +>>> model = AutoModelForSeq2SeqLM.from_pretrained("microsoft/tapex-large-finetuned-wtq") + +>>> # prepare table + question +>>> data = {"Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"], "Number of movies": ["87", "53", "69"]} +>>> table = pd.DataFrame.from_dict(data) +>>> question = "how many movies does Leonardo Di Caprio have?" + +>>> encoding = tokenizer(table, question, return_tensors="pt") + +>>> # let the model generate an answer autoregressively +>>> outputs = model.generate(**encoding) + +>>> # decode back to text +>>> predicted_answer = tokenizer.batch_decode(outputs, skip_special_tokens=True)[0] +>>> print(predicted_answer) +53 +``` + +Note that [`TapexTokenizer`] also supports batched inference. Hence, one can provide a batch of different tables/questions, or a batch of a single table +and multiple questions, or a batch of a single query and multiple tables. Let's illustrate this: + +```python +>>> # prepare table + question +>>> data = {"Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"], "Number of movies": ["87", "53", "69"]} +>>> table = pd.DataFrame.from_dict(data) +>>> questions = [ +... "how many movies does Leonardo Di Caprio have?", +... "which actor has 69 movies?", +... "what's the first name of the actor who has 87 movies?", +... ] +>>> encoding = tokenizer(table, questions, padding=True, return_tensors="pt") + +>>> # let the model generate an answer autoregressively +>>> outputs = model.generate(**encoding) + +>>> # decode back to text +>>> tokenizer.batch_decode(outputs, skip_special_tokens=True) +[' 53', ' george clooney', ' brad pitt'] +``` + +In case one wants to do table verification (i.e. the task of determining whether a given sentence is supported or refuted by the contents +of a table), one can instantiate a [`BartForSequenceClassification`] model. TAPEX has checkpoints on the hub fine-tuned on TabFact, an important +benchmark for table fact checking (it achieves 84% accuracy). The code example below again leverages the [Auto API](auto). + +```python +>>> from transformers import AutoTokenizer, AutoModelForSequenceClassification + +>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/tapex-large-finetuned-tabfact") +>>> model = AutoModelForSequenceClassification.from_pretrained("microsoft/tapex-large-finetuned-tabfact") + +>>> # prepare table + sentence +>>> data = {"Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"], "Number of movies": ["87", "53", "69"]} +>>> table = pd.DataFrame.from_dict(data) +>>> sentence = "George Clooney has 30 movies" + +>>> encoding = tokenizer(table, sentence, return_tensors="pt") + +>>> # forward pass +>>> outputs = model(**encoding) + +>>> # print prediction +>>> predicted_class_idx = outputs.logits[0].argmax(dim=0).item() +>>> print(model.config.id2label[predicted_class_idx]) +Refused +``` + + + +TAPEX architecture is the same as BART, except for tokenization. Refer to [BART documentation](bart) for information on +configuration classes and their parameters. TAPEX-specific tokenizer is documented below. + + + +## TapexTokenizer + +[[autodoc]] TapexTokenizer + - __call__ + - save_vocabulary \ No newline at end of file diff --git a/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/textnet.md b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/textnet.md new file mode 100644 index 0000000000000000000000000000000000000000..d6b431e648f21bf985964a4bbc0d85c9db95d824 --- /dev/null +++ b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/textnet.md @@ -0,0 +1,55 @@ + + +# TextNet + +## Overview + +The TextNet model was proposed in [FAST: Faster Arbitrarily-Shaped Text Detector with Minimalist Kernel Representation](https://arxiv.org/abs/2111.02394) by Zhe Chen, Jiahao Wang, Wenhai Wang, Guo Chen, Enze Xie, Ping Luo, Tong Lu. TextNet is a vision backbone useful for text detection tasks. It is the result of neural architecture search (NAS) on backbones with reward function as text detection task (to provide powerful features for text detection). + + + + TextNet backbone as part of FAST. Taken from the original paper. + +This model was contributed by [Raghavan](https://huggingface.co/Raghavan), [jadechoghari](https://huggingface.co/jadechoghari) and [nielsr](https://huggingface.co/nielsr). + +## Usage tips + +TextNet is mainly used as a backbone network for the architecture search of text detection. Each stage of the backbone network is comprised of a stride-2 convolution and searchable blocks. +Specifically, we present a layer-level candidate set, defined as {conv3ร—3, conv1ร—3, conv3ร—1, identity}. As the 1ร—3 and 3ร—1 convolutions have asymmetric kernels and oriented structure priors, they may help to capture the features of extreme aspect-ratio and rotated text lines. + +TextNet is the backbone for Fast, but can also be used as an efficient text/image classification, we add a `TextNetForImageClassification` as is it would allow people to train an image classifier on top of the pre-trained textnet weights + +## TextNetConfig + +[[autodoc]] TextNetConfig + +## TextNetImageProcessor + +[[autodoc]] TextNetImageProcessor + - preprocess + +## TextNetModel + +[[autodoc]] TextNetModel + - forward + +## TextNetForImageClassification + +[[autodoc]] TextNetForImageClassification + - forward + diff --git a/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/time_series_transformer.md b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/time_series_transformer.md new file mode 100644 index 0000000000000000000000000000000000000000..c5bfcfc15ea2a244d01bd5f94788a063200e394c --- /dev/null +++ b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/time_series_transformer.md @@ -0,0 +1,72 @@ + + +# Time Series Transformer + +## Overview + +The Time Series Transformer model is a vanilla encoder-decoder Transformer for time series forecasting. +This model was contributed by [kashif](https://huggingface.co/kashif). + +## Usage tips + +- Similar to other models in the library, [`TimeSeriesTransformerModel`] is the raw Transformer without any head on top, and [`TimeSeriesTransformerForPrediction`] +adds a distribution head on top of the former, which can be used for time-series forecasting. Note that this is a so-called probabilistic forecasting model, not a +point forecasting model. This means that the model learns a distribution, from which one can sample. The model doesn't directly output values. +- [`TimeSeriesTransformerForPrediction`] consists of 2 blocks: an encoder, which takes a `context_length` of time series values as input (called `past_values`), +and a decoder, which predicts a `prediction_length` of time series values into the future (called `future_values`). During training, one needs to provide +pairs of (`past_values` and `future_values`) to the model. +- In addition to the raw (`past_values` and `future_values`), one typically provides additional features to the model. These can be the following: + - `past_time_features`: temporal features which the model will add to `past_values`. These serve as "positional encodings" for the Transformer encoder. + Examples are "day of the month", "month of the year", etc. as scalar values (and then stacked together as a vector). + e.g. if a given time-series value was obtained on the 11th of August, then one could have [11, 8] as time feature vector (11 being "day of the month", 8 being "month of the year"). + - `future_time_features`: temporal features which the model will add to `future_values`. These serve as "positional encodings" for the Transformer decoder. + Examples are "day of the month", "month of the year", etc. as scalar values (and then stacked together as a vector). + e.g. if a given time-series value was obtained on the 11th of August, then one could have [11, 8] as time feature vector (11 being "day of the month", 8 being "month of the year"). + - `static_categorical_features`: categorical features which are static over time (i.e., have the same value for all `past_values` and `future_values`). + An example here is the store ID or region ID that identifies a given time-series. + Note that these features need to be known for ALL data points (also those in the future). + - `static_real_features`: real-valued features which are static over time (i.e., have the same value for all `past_values` and `future_values`). + An example here is the image representation of the product for which you have the time-series values (like the [ResNet](resnet) embedding of a "shoe" picture, + if your time-series is about the sales of shoes). + Note that these features need to be known for ALL data points (also those in the future). +- The model is trained using "teacher-forcing", similar to how a Transformer is trained for machine translation. This means that, during training, one shifts the +`future_values` one position to the right as input to the decoder, prepended by the last value of `past_values`. At each time step, the model needs to predict the +next target. So the set-up of training is similar to a GPT model for language, except that there's no notion of `decoder_start_token_id` (we just use the last value +of the context as initial input for the decoder). +- At inference time, we give the final value of the `past_values` as input to the decoder. Next, we can sample from the model to make a prediction at the next time step, +which is then fed to the decoder in order to make the next prediction (also called autoregressive generation). + +## Resources + +A list of official Hugging Face and community (indicated by ๐ŸŒŽ) resources to help you get started. 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. + +- Check out the Time Series Transformer blog-post in HuggingFace blog: [Probabilistic Time Series Forecasting with ๐Ÿค— Transformers](https://huggingface.co/blog/time-series-transformers) + + +## TimeSeriesTransformerConfig + +[[autodoc]] TimeSeriesTransformerConfig + +## TimeSeriesTransformerModel + +[[autodoc]] TimeSeriesTransformerModel + - forward + +## TimeSeriesTransformerForPrediction + +[[autodoc]] TimeSeriesTransformerForPrediction + - forward diff --git a/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/timesformer.md b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/timesformer.md new file mode 100644 index 0000000000000000000000000000000000000000..fe75bee5b2897eb1dfb4bbb28fd7d5534083db9a --- /dev/null +++ b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/timesformer.md @@ -0,0 +1,52 @@ + + +# TimeSformer + +## Overview + +The TimeSformer model was proposed in [TimeSformer: Is Space-Time Attention All You Need for Video Understanding?](https://arxiv.org/abs/2102.05095) by Facebook Research. +This work is a milestone in action-recognition field being the first video transformer. It inspired many transformer based video understanding and classification papers. + +The abstract from the paper is the following: + +*We present a convolution-free approach to video classification built exclusively on self-attention over space and time. Our method, named "TimeSformer," adapts the standard Transformer architecture to video by enabling spatiotemporal feature learning directly from a sequence of frame-level patches. Our experimental study compares different self-attention schemes and suggests that "divided attention," where temporal attention and spatial attention are separately applied within each block, leads to the best video classification accuracy among the design choices considered. Despite the radically new design, TimeSformer achieves state-of-the-art results on several action recognition benchmarks, including the best reported accuracy on Kinetics-400 and Kinetics-600. Finally, compared to 3D convolutional networks, our model is faster to train, it can achieve dramatically higher test efficiency (at a small drop in accuracy), and it can also be applied to much longer video clips (over one minute long). Code and models are available at: [this https URL](https://github.com/facebookresearch/TimeSformer).* + +This model was contributed by [fcakyon](https://huggingface.co/fcakyon). +The original code can be found [here](https://github.com/facebookresearch/TimeSformer). + +## Usage tips + +There are many pretrained variants. Select your pretrained model based on the dataset it is trained on. Moreover, +the number of input frames per clip changes based on the model size so you should consider this parameter while selecting your pretrained model. + +## Resources + +- [Video classification task guide](../tasks/video_classification) + +## TimesformerConfig + +[[autodoc]] TimesformerConfig + +## TimesformerModel + +[[autodoc]] TimesformerModel + - forward + +## TimesformerForVideoClassification + +[[autodoc]] TimesformerForVideoClassification + - forward \ No newline at end of file diff --git a/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/timm_wrapper.md b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/timm_wrapper.md new file mode 100644 index 0000000000000000000000000000000000000000..5af3d51746c325cc9085076fdfc8feaaa1ddb350 --- /dev/null +++ b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/timm_wrapper.md @@ -0,0 +1,67 @@ + + +# TimmWrapper + +## Overview + +Helper class to enable loading timm models to be used with the transformers library and its autoclasses. + +```python +>>> import torch +>>> from PIL import Image +>>> from urllib.request import urlopen +>>> from transformers import AutoModelForImageClassification, AutoImageProcessor + +>>> # Load image +>>> image = Image.open(urlopen( +... 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/beignets-task-guide.png' +... )) + +>>> # Load model and image processor +>>> checkpoint = "timm/resnet50.a1_in1k" +>>> image_processor = AutoImageProcessor.from_pretrained(checkpoint) +>>> model = AutoModelForImageClassification.from_pretrained(checkpoint).eval() + +>>> # Preprocess image +>>> inputs = image_processor(image) + +>>> # Forward pass +>>> with torch.no_grad(): +... logits = model(**inputs).logits + +>>> # Get top 5 predictions +>>> top5_probabilities, top5_class_indices = torch.topk(logits.softmax(dim=1) * 100, k=5) +``` + +## TimmWrapperConfig + +[[autodoc]] TimmWrapperConfig + +## TimmWrapperImageProcessor + +[[autodoc]] TimmWrapperImageProcessor + - preprocess + +## TimmWrapperModel + +[[autodoc]] TimmWrapperModel + - forward + +## TimmWrapperForImageClassification + +[[autodoc]] TimmWrapperForImageClassification + - forward diff --git a/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/trajectory_transformer.md b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/trajectory_transformer.md new file mode 100644 index 0000000000000000000000000000000000000000..45616255871a0807a023b31101af2685bd0685ae --- /dev/null +++ b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/trajectory_transformer.md @@ -0,0 +1,61 @@ + + +# Trajectory Transformer + + + +This model is in maintenance mode only, so we won'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 Trajectory Transformer model was proposed in [Offline Reinforcement Learning as One Big Sequence Modeling Problem](https://arxiv.org/abs/2106.02039) by Michael Janner, Qiyang Li, Sergey Levine. + +The abstract from the paper is the following: + +*Reinforcement learning (RL) is typically concerned with estimating stationary policies or single-step models, +leveraging the Markov property to factorize problems in time. However, we can also view RL as a generic sequence +modeling problem, with the goal being to produce a sequence of actions that leads to a sequence of high rewards. +Viewed in this way, it is tempting to consider whether high-capacity sequence prediction models that work well +in other domains, such as natural-language processing, can also provide effective solutions to the RL problem. +To this end, we explore how RL can be tackled with the tools of sequence modeling, using a Transformer architecture +to model distributions over trajectories and repurposing beam search as a planning algorithm. Framing RL as sequence +modeling problem simplifies a range of design decisions, allowing us to dispense with many of the components common +in offline RL algorithms. We demonstrate the flexibility of this approach across long-horizon dynamics prediction, +imitation learning, goal-conditioned RL, and offline RL. Further, we show that this approach can be combined with +existing model-free algorithms to yield a state-of-the-art planner in sparse-reward, long-horizon tasks.* + +This model was contributed by [CarlCochet](https://huggingface.co/CarlCochet). The original code can be found [here](https://github.com/jannerm/trajectory-transformer). + +## Usage tips + +This Transformer is used for deep reinforcement learning. To use it, you need to create sequences from +actions, states and rewards from all previous timesteps. This model will treat all these elements together +as one big sequence (a trajectory). + +## TrajectoryTransformerConfig + +[[autodoc]] TrajectoryTransformerConfig + +## TrajectoryTransformerModel + +[[autodoc]] TrajectoryTransformerModel + - forward diff --git a/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/transfo-xl.md b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/transfo-xl.md new file mode 100644 index 0000000000000000000000000000000000000000..c80d9352b5aef6376aad210a39ff6f2cc056d967 --- /dev/null +++ b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/transfo-xl.md @@ -0,0 +1,162 @@ + + +# Transformer XL + + + +This model is in maintenance mode only, so we won't accept any new PRs changing its code. This model was deprecated due to security issues linked to `pickle.load`. + +We recommend switching to more recent models for improved security. + +In case you would still like to use `TransfoXL` in your experiments, we recommend using the [Hub checkpoint](https://huggingface.co/transfo-xl/transfo-xl-wt103) with a specific revision to ensure you are downloading safe files from the Hub. + +You will need to set the environment variable `TRUST_REMOTE_CODE` to `True` in order to allow the +usage of `pickle.load()`: + +```python +import os +from transformers import TransfoXLTokenizer, TransfoXLLMHeadModel + +os.environ["TRUST_REMOTE_CODE"] = "True" + +checkpoint = 'transfo-xl/transfo-xl-wt103' +revision = '40a186da79458c9f9de846edfaea79c412137f97' + +tokenizer = TransfoXLTokenizer.from_pretrained(checkpoint, revision=revision) +model = TransfoXLLMHeadModel.from_pretrained(checkpoint, revision=revision) +``` + +If you run into any issues running this model, please reinstall the last version that supported this model: v4.35.0. +You can do so by running the following command: `pip install -U transformers==4.35.0`. + + + +
+ +Models + + +Spaces + +
+ +## Overview + +The Transformer-XL model was proposed in [Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context](https://arxiv.org/abs/1901.02860) by Zihang Dai, Zhilin Yang, Yiming Yang, Jaime Carbonell, Quoc V. Le, Ruslan +Salakhutdinov. It's a causal (uni-directional) transformer with relative positioning (sinusoรฏdal) embeddings which can +reuse previously computed hidden-states to attend to longer context (memory). This model also uses adaptive softmax +inputs and outputs (tied). + +The abstract from the paper is the following: + +*Transformers have a potential of learning longer-term dependency, but are limited by a fixed-length context in the +setting of language modeling. We propose a novel neural architecture Transformer-XL that enables learning dependency +beyond a fixed length without disrupting temporal coherence. It consists of a segment-level recurrence mechanism and a +novel positional encoding scheme. Our method not only enables capturing longer-term dependency, but also resolves the +context fragmentation problem. As a result, Transformer-XL learns dependency that is 80% longer than RNNs and 450% +longer than vanilla Transformers, achieves better performance on both short and long sequences, and is up to 1,800+ +times faster than vanilla Transformers during evaluation. Notably, we improve the state-of-the-art results of +bpc/perplexity to 0.99 on enwiki8, 1.08 on text8, 18.3 on WikiText-103, 21.8 on One Billion Word, and 54.5 on Penn +Treebank (without finetuning). When trained only on WikiText-103, Transformer-XL manages to generate reasonably +coherent, novel text articles with thousands of tokens.* + +This model was contributed by [thomwolf](https://huggingface.co/thomwolf). The original code can be found [here](https://github.com/kimiyoung/transformer-xl). + +## Usage tips + +- Transformer-XL uses relative sinusoidal positional embeddings. Padding can be done on the left or on the right. The + original implementation trains on SQuAD with padding on the left, therefore the padding defaults are set to left. +- Transformer-XL is one of the few models that has no sequence length limit. +- Same as a regular GPT model, but introduces a recurrence mechanism for two consecutive segments (similar to a regular RNNs with two consecutive inputs). In this context, a segment is a number of consecutive tokens (for instance 512) that may span across multiple documents, and segments are fed in order to the model. +- Basically, the hidden states of the previous segment are concatenated to the current input to compute the attention scores. This allows the model to pay attention to information that was in the previous segment as well as the current one. By stacking multiple attention layers, the receptive field can be increased to multiple previous segments. +- This changes the positional embeddings to positional relative embeddings (as the regular positional embeddings would give the same results in the current input and the current hidden state at a given position) and needs to make some adjustments in the way attention scores are computed. + + + + +TransformerXL does **not** work with *torch.nn.DataParallel* due to a bug in PyTorch, see [issue #36035](https://github.com/pytorch/pytorch/issues/36035) + + + +## Resources + +- [Text classification task guide](../tasks/sequence_classification) +- [Causal language modeling task guide](../tasks/language_modeling) + +## TransfoXLConfig + +[[autodoc]] TransfoXLConfig + +## TransfoXLTokenizer + +[[autodoc]] TransfoXLTokenizer + - save_vocabulary + +## TransfoXL specific outputs + +[[autodoc]] models.deprecated.transfo_xl.modeling_transfo_xl.TransfoXLModelOutput + +[[autodoc]] models.deprecated.transfo_xl.modeling_transfo_xl.TransfoXLLMHeadModelOutput + +[[autodoc]] models.deprecated.transfo_xl.modeling_tf_transfo_xl.TFTransfoXLModelOutput + +[[autodoc]] models.deprecated.transfo_xl.modeling_tf_transfo_xl.TFTransfoXLLMHeadModelOutput + + + + +## TransfoXLModel + +[[autodoc]] TransfoXLModel + - forward + +## TransfoXLLMHeadModel + +[[autodoc]] TransfoXLLMHeadModel + - forward + +## TransfoXLForSequenceClassification + +[[autodoc]] TransfoXLForSequenceClassification + - forward + + + + +## TFTransfoXLModel + +[[autodoc]] TFTransfoXLModel + - call + +## TFTransfoXLLMHeadModel + +[[autodoc]] TFTransfoXLLMHeadModel + - call + +## TFTransfoXLForSequenceClassification + +[[autodoc]] TFTransfoXLForSequenceClassification + - call + + + + +## Internal Layers + +[[autodoc]] AdaptiveEmbedding + +[[autodoc]] TFAdaptiveEmbedding diff --git a/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/trocr.md b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/trocr.md new file mode 100644 index 0000000000000000000000000000000000000000..c471a13bbd23c5338abda049aa87c5922c46a5b8 --- /dev/null +++ b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/trocr.md @@ -0,0 +1,126 @@ + + +# TrOCR + +## Overview + +The TrOCR model was proposed in [TrOCR: Transformer-based Optical Character Recognition with Pre-trained +Models](https://arxiv.org/abs/2109.10282) by Minghao Li, Tengchao Lv, Lei Cui, Yijuan Lu, Dinei Florencio, Cha Zhang, +Zhoujun Li, Furu Wei. TrOCR consists of an image Transformer encoder and an autoregressive text Transformer decoder to +perform [optical character recognition (OCR)](https://en.wikipedia.org/wiki/Optical_character_recognition). + +The abstract from the paper is the following: + +*Text recognition is a long-standing research problem for document digitalization. Existing approaches for text recognition +are usually built based on CNN for image understanding and RNN for char-level text generation. In addition, another language +model is usually needed to improve the overall accuracy as a post-processing step. In this paper, we propose an end-to-end +text recognition approach with pre-trained image Transformer and text Transformer models, namely TrOCR, which leverages the +Transformer architecture for both image understanding and wordpiece-level text generation. The TrOCR model is simple but +effective, and can be pre-trained with large-scale synthetic data and fine-tuned with human-labeled datasets. Experiments +show that the TrOCR model outperforms the current state-of-the-art models on both printed and handwritten text recognition +tasks.* + + + + TrOCR architecture. Taken from the original paper. + +Please refer to the [`VisionEncoderDecoder`] class on how to use this model. + +This model was contributed by [nielsr](https://huggingface.co/nielsr). The original code can be found +[here](https://github.com/microsoft/unilm/tree/6f60612e7cc86a2a1ae85c47231507a587ab4e01/trocr). + +## Usage tips + +- The quickest way to get started with TrOCR is by checking the [tutorial + notebooks](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/TrOCR), which show how to use the model + at inference time as well as fine-tuning on custom data. +- TrOCR is pre-trained in 2 stages before being fine-tuned on downstream datasets. It achieves state-of-the-art results + on both printed (e.g. the [SROIE dataset](https://paperswithcode.com/dataset/sroie) and handwritten (e.g. the [IAM + Handwriting dataset](https://fki.tic.heia-fr.ch/databases/iam-handwriting-database>) text recognition tasks. For more + information, see the [official models](https://huggingface.co/models?other=trocr>). +- TrOCR is always used within the [VisionEncoderDecoder](vision-encoder-decoder) framework. + +## Resources + +A list of official Hugging Face and community (indicated by ๐ŸŒŽ) resources to help you get started with TrOCR. 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 blog post on [Accelerating Document AI](https://huggingface.co/blog/document-ai) with TrOCR. +- A blog post on how to [Document AI](https://github.com/philschmid/document-ai-transformers) with TrOCR. +- A notebook on how to [finetune TrOCR on IAM Handwriting Database using Seq2SeqTrainer](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/TrOCR/Fine_tune_TrOCR_on_IAM_Handwriting_Database_using_Seq2SeqTrainer.ipynb). +- A notebook on [inference with TrOCR](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/TrOCR/Inference_with_TrOCR_%2B_Gradio_demo.ipynb) and Gradio demo. +- A notebook on [finetune TrOCR on the IAM Handwriting Database](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/TrOCR/Fine_tune_TrOCR_on_IAM_Handwriting_Database_using_native_PyTorch.ipynb) using native PyTorch. +- A notebook on [evaluating TrOCR on the IAM test set](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/TrOCR/Evaluating_TrOCR_base_handwritten_on_the_IAM_test_set.ipynb). + + + +- [Casual language modeling](https://huggingface.co/docs/transformers/tasks/language_modeling) task guide. + +โšก๏ธ Inference + +- An interactive-demo on [TrOCR handwritten character recognition](https://huggingface.co/spaces/nielsr/TrOCR-handwritten). + +## Inference + +TrOCR's [`VisionEncoderDecoder`] model accepts images as input and makes use of +[`~generation.GenerationMixin.generate`] to autoregressively generate text given the input image. + +The [`ViTImageProcessor`/`DeiTImageProcessor`] class is responsible for preprocessing the input image and +[`RobertaTokenizer`/`XLMRobertaTokenizer`] decodes the generated target tokens to the target string. The +[`TrOCRProcessor`] wraps [`ViTImageProcessor`/`DeiTImageProcessor`] and [`RobertaTokenizer`/`XLMRobertaTokenizer`] +into a single instance to both extract the input features and decode the predicted token ids. + +- Step-by-step Optical Character Recognition (OCR) + +``` py +>>> from transformers import TrOCRProcessor, VisionEncoderDecoderModel +>>> import requests +>>> from PIL import Image + +>>> processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-handwritten") +>>> model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten") + +>>> # load image from the IAM dataset +>>> url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg" +>>> image = Image.open(requests.get(url, stream=True).raw).convert("RGB") + +>>> pixel_values = processor(image, return_tensors="pt").pixel_values +>>> generated_ids = model.generate(pixel_values) + +>>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0] +``` + +See the [model hub](https://huggingface.co/models?filter=trocr) to look for TrOCR checkpoints. + +## TrOCRConfig + +[[autodoc]] TrOCRConfig + +## TrOCRProcessor + +[[autodoc]] TrOCRProcessor + - __call__ + - from_pretrained + - save_pretrained + - batch_decode + - decode + +## TrOCRForCausalLM + +[[autodoc]] TrOCRForCausalLM + - forward diff --git a/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/tvlt.md b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/tvlt.md new file mode 100644 index 0000000000000000000000000000000000000000..0a0f50e47315693a684b369d7119315a85fb6883 --- /dev/null +++ b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/tvlt.md @@ -0,0 +1,85 @@ + + +# TVLT + + + +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.40.2. +You can do so by running the following command: `pip install -U transformers==4.40.2`. + + + +## Overview + +The TVLT model was proposed in [TVLT: Textless Vision-Language Transformer](https://arxiv.org/abs/2209.14156) +by Zineng Tang, Jaemin Cho, Yixin Nie, Mohit Bansal (the first three authors contributed equally). The Textless Vision-Language Transformer (TVLT) is a model that uses raw visual and audio inputs for vision-and-language representation learning, without using text-specific modules such as tokenization or automatic speech recognition (ASR). It can perform various audiovisual and vision-language tasks like retrieval, question answering, etc. + +The abstract from the paper is the following: + +*In this work, we present the Textless Vision-Language Transformer (TVLT), where homogeneous transformer blocks take raw visual and audio inputs for vision-and-language representation learning with minimal modality-specific design, and do not use text-specific modules such as tokenization or automatic speech recognition (ASR). TVLT is trained by reconstructing masked patches of continuous video frames and audio spectrograms (masked autoencoding) and contrastive modeling to align video and audio. TVLT attains performance comparable to its text-based counterpart on various multimodal tasks, such as visual question answering, image retrieval, video retrieval, and multimodal sentiment analysis, with 28x faster inference speed and only 1/3 of the parameters. Our findings suggest the possibility of learning compact and efficient visual-linguistic representations from low-level visual and audio signals without assuming the prior existence of text.* + +

+ +

+ + TVLT architecture. Taken from the original paper. + +The original code can be found [here](https://github.com/zinengtang/TVLT). This model was contributed by [Zineng Tang](https://huggingface.co/ZinengTang). + +## Usage tips + +- TVLT is a model that takes both `pixel_values` and `audio_values` as input. One can use [`TvltProcessor`] to prepare data for the model. + This processor wraps an image processor (for the image/video modality) and an audio feature extractor (for the audio modality) into one. +- TVLT is trained with images/videos and audios of various sizes: the authors resize and crop the input images/videos to 224 and limit the length of audio spectrogram to 2048. To make batching of videos and audios possible, the authors use a `pixel_mask` that indicates which pixels are real/padding and `audio_mask` that indicates which audio values are real/padding. +- The design of TVLT is very similar to that of a standard Vision Transformer (ViT) and masked autoencoder (MAE) as in [ViTMAE](vitmae). The difference is that the model includes embedding layers for the audio modality. +- The PyTorch version of this model is only available in torch 1.10 and higher. + +## TvltConfig + +[[autodoc]] TvltConfig + +## TvltProcessor + +[[autodoc]] TvltProcessor + - __call__ + +## TvltImageProcessor + +[[autodoc]] TvltImageProcessor + - preprocess + +## TvltFeatureExtractor + +[[autodoc]] TvltFeatureExtractor + - __call__ + +## TvltModel + +[[autodoc]] TvltModel + - forward + +## TvltForPreTraining + +[[autodoc]] TvltForPreTraining + - forward + +## TvltForAudioVisualClassification + +[[autodoc]] TvltForAudioVisualClassification + - forward diff --git a/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/tvp.md b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/tvp.md new file mode 100644 index 0000000000000000000000000000000000000000..22b400a06c736afd890f8a1a551d83cd573ac5ab --- /dev/null +++ b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/tvp.md @@ -0,0 +1,186 @@ + + +# TVP + +## Overview + +The text-visual prompting (TVP) framework was proposed in the paper [Text-Visual Prompting for Efficient 2D Temporal Video Grounding](https://arxiv.org/abs/2303.04995) 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](https://huggingface.co/Jiqing). The original code can be found [here](https://github.com/intel/TVP). + +## 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`]. +```python +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](https://huggingface.co/Intel/tvp-base) is released. +- Please refer to [Table 2](https://arxiv.org/pdf/2303.04995.pdf) 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 diff --git a/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/udop.md b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/udop.md new file mode 100644 index 0000000000000000000000000000000000000000..614bd2ff4fd7156e094b83f20dfb4a76bf32a4cf --- /dev/null +++ b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/udop.md @@ -0,0 +1,113 @@ + + +# UDOP + +## Overview + +The UDOP model was proposed in [Unifying Vision, Text, and Layout for Universal Document Processing](https://arxiv.org/abs/2212.02623) by Zineng Tang, Ziyi Yang, Guoxin Wang, Yuwei Fang, Yang Liu, Chenguang Zhu, Michael Zeng, Cha Zhang, Mohit Bansal. +UDOP adopts an encoder-decoder Transformer architecture based on [T5](t5) for document AI tasks like document image classification, document parsing and document visual question answering. + +The abstract from the paper is the following: + +We propose Universal Document Processing (UDOP), a foundation Document AI model which unifies text, image, and layout modalities together with varied task formats, including document understanding and generation. UDOP leverages the spatial correlation between textual content and document image to model image, text, and layout modalities with one uniform representation. With a novel Vision-Text-Layout Transformer, UDOP unifies pretraining and multi-domain downstream tasks into a prompt-based sequence generation scheme. UDOP is pretrained on both large-scale unlabeled document corpora using innovative self-supervised objectives and diverse labeled data. UDOP also learns to generate document images from text and layout modalities via masked image reconstruction. To the best of our knowledge, this is the first time in the field of document AI that one model simultaneously achieves high-quality neural document editing and content customization. Our method sets the state-of-the-art on 9 Document AI tasks, e.g., document understanding and QA, across diverse data domains like finance reports, academic papers, and websites. UDOP ranks first on the leaderboard of the Document Understanding Benchmark (DUE).* + + + + UDOP architecture. Taken from the original paper. + +## Usage tips + +- In addition to *input_ids*, [`UdopForConditionalGeneration`] also expects the input `bbox`, which are + the bounding boxes (i.e. 2D-positions) of the input tokens. These can be obtained using an external OCR engine such + as Google's [Tesseract](https://github.com/tesseract-ocr/tesseract) (there's a [Python wrapper](https://pypi.org/project/pytesseract/) available). Each bounding box should be in (x0, y0, x1, y1) format, where (x0, y0) corresponds to the position of the upper left corner in the bounding box, and (x1, y1) represents the + position of the lower right corner. Note that one first needs to normalize the bounding boxes to be on a 0-1000 + scale. To normalize, you can use the following function: + +```python +def normalize_bbox(bbox, width, height): + return [ + int(1000 * (bbox[0] / width)), + int(1000 * (bbox[1] / height)), + int(1000 * (bbox[2] / width)), + int(1000 * (bbox[3] / height)), + ] +``` + +Here, `width` and `height` correspond to the width and height of the original document in which the token +occurs. Those can be obtained using the Python Image Library (PIL) library for example, as follows: + +```python +from PIL import Image + +# Document can be a png, jpg, etc. PDFs must be converted to images. +image = Image.open(name_of_your_document).convert("RGB") + +width, height = image.size +``` + +One can use [`UdopProcessor`] to prepare images and text for the model, which takes care of all of this. By default, this class uses the Tesseract engine to extract a list of words and boxes (coordinates) from a given document. Its functionality is equivalent to that of [`LayoutLMv3Processor`], hence it supports passing either `apply_ocr=False` in case you prefer to use your own OCR engine or `apply_ocr=True` in case you want the default OCR engine to be used. Refer to the [usage guide of LayoutLMv2](layoutlmv2#usage-layoutlmv2processor) regarding all possible use cases (the functionality of `UdopProcessor` is identical). + +- If using an own OCR engine of choice, one recommendation is Azure's [Read API](https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/how-to/call-read-api), which supports so-called line segments. Use of segment position embeddings typically results in better performance. +- At inference time, it's recommended to use the `generate` method to autoregressively generate text given a document image. +- The model has been pre-trained on both self-supervised and supervised objectives. One can use the various task prefixes (prompts) used during pre-training to test out the out-of-the-box capabilities. For instance, the model can be prompted with "Question answering. What is the date?", as "Question answering." is the task prefix used during pre-training for DocVQA. Refer to the [paper](https://arxiv.org/abs/2212.02623) (table 1) for all task prefixes. +- One can also fine-tune [`UdopEncoderModel`], which is the encoder-only part of UDOP, which can be seen as a LayoutLMv3-like Transformer encoder. For discriminative tasks, one can just add a linear classifier on top of it and fine-tune it on a labeled dataset. + +This model was contributed by [nielsr](https://huggingface.co/nielsr). +The original code can be found [here](https://github.com/microsoft/UDOP). + +## Resources + +A list of official Hugging Face and community (indicated by ๐ŸŒŽ) resources to help you get started with UDOP. 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. + +- Demo notebooks regarding UDOP can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/UDOP) that show how +to fine-tune UDOP on a custom dataset as well as inference. ๐ŸŒŽ +- [Document question answering task guide](../tasks/document_question_answering) + +## UdopConfig + +[[autodoc]] UdopConfig + +## UdopTokenizer + +[[autodoc]] UdopTokenizer + - build_inputs_with_special_tokens + - get_special_tokens_mask + - create_token_type_ids_from_sequences + - save_vocabulary + +## UdopTokenizerFast + +[[autodoc]] UdopTokenizerFast + +## UdopProcessor + +[[autodoc]] UdopProcessor + - __call__ + +## UdopModel + +[[autodoc]] UdopModel + - forward + +## UdopForConditionalGeneration + +[[autodoc]] UdopForConditionalGeneration + - forward + +## UdopEncoderModel + +[[autodoc]] UdopEncoderModel + - forward \ No newline at end of file diff --git a/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/ul2.md b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/ul2.md new file mode 100644 index 0000000000000000000000000000000000000000..f4d01c40b0c10944e5ddb3451f355e4c95bf2d9a --- /dev/null +++ b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/ul2.md @@ -0,0 +1,43 @@ + + +# UL2 + +## Overview + +The T5 model was presented in [Unifying Language Learning Paradigms](https://arxiv.org/pdf/2205.05131v1.pdf) by Yi Tay, Mostafa Dehghani, Vinh Q. Tran, Xavier Garcia, Dara Bahri, Tal Schuster, Huaixiu Steven Zheng, Neil Houlsby, Donald Metzler. + +The abstract from the paper is the following: + +*Existing pre-trained models are generally geared towards a particular class of problems. To date, there seems to be still no consensus on what the right architecture and pre-training setup should be. This paper presents a unified framework for pre-training models that are universally effective across datasets and setups. We begin by disentangling architectural archetypes with pre-training objectives -- two concepts that are commonly conflated. Next, we present a generalized and unified perspective for self-supervision in NLP and show how different pre-training objectives can be cast as one another and how interpolating between different objectives can be effective. We then propose Mixture-of-Denoisers (MoD), a pre-training objective that combines diverse pre-training paradigms together. We furthermore introduce a notion of mode switching, wherein downstream fine-tuning is associated with specific pre-training schemes. We conduct extensive ablative experiments to compare multiple pre-training objectives and find that our method pushes the Pareto-frontier by outperforming T5 and/or GPT-like models across multiple diverse setups. Finally, by scaling our model up to 20B parameters, we achieve SOTA performance on 50 well-established supervised NLP tasks ranging from language generation (with automated and human evaluation), language understanding, text classification, question answering, commonsense reasoning, long text reasoning, structured knowledge grounding and information retrieval. Our model also achieve strong results at in-context learning, outperforming 175B GPT-3 on zero-shot SuperGLUE and tripling the performance of T5-XXL on one-shot summarization.* + +This model was contributed by [DanielHesslow](https://huggingface.co/Seledorn). The original code can be found [here](https://github.com/google-research/google-research/tree/master/ul2). + +## Usage tips + +- UL2 is an encoder-decoder model pre-trained on a mixture of denoising functions as well as fine-tuned on an array of downstream tasks. +- UL2 has the same architecture as [T5v1.1](t5v1.1) but uses the Gated-SiLU activation function instead of Gated-GELU. +- The authors release checkpoints of one architecture which can be seen [here](https://huggingface.co/google/ul2) + + + +As UL2 has the same architecture as T5v1.1, refer to [T5's documentation page](t5) for API reference, tips, code examples and notebooks. + + + + + + diff --git a/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/umt5.md b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/umt5.md new file mode 100644 index 0000000000000000000000000000000000000000..b9f86a0304e89234e9c6be31d854fd6851e050d7 --- /dev/null +++ b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/umt5.md @@ -0,0 +1,112 @@ + + +# UMT5 + +
+ +Models + + +Spaces + +
+ +## Overview + +The UMT5 model was proposed in [UniMax: Fairer and More Effective Language Sampling for Large-Scale Multilingual Pretraining](https://openreview.net/forum?id=kXwdL1cWOAi) by Hyung Won Chung, Xavier Garcia, Adam Roberts, Yi Tay, Orhan Firat, Sharan Narang, Noah Constant. + +The abstract from the paper is the following: + +*Pretrained multilingual large language models have typically used heuristic temperature-based sampling to balance between different languages. However previous work has not systematically evaluated the efficacy of different pretraining language distributions across model scales. In this paper, we propose a new sampling method, UniMax, that delivers more uniform coverage of head languages while mitigating overfitting on tail languages by explicitly capping the number of repeats over each language's corpus. We perform an extensive series of ablations testing a range of sampling strategies on a suite of multilingual benchmarks, while varying model scale. We find that UniMax outperforms standard temperature-based sampling, and the benefits persist as scale increases. As part of our contribution, we release: (i) an improved and refreshed mC4 multilingual corpus consisting of 29 trillion characters across 107 languages, and (ii) a suite of pretrained umT5 model checkpoints trained with UniMax sampling.* + +Google has released the following variants: + +- [google/umt5-small](https://huggingface.co/google/umt5-small) +- [google/umt5-base](https://huggingface.co/google/umt5-base) +- [google/umt5-xl](https://huggingface.co/google/umt5-xl) +- [google/umt5-xxl](https://huggingface.co/google/umt5-xxl). + +This model was contributed by [agemagician](https://huggingface.co/agemagician) and [stefan-it](https://huggingface.co/stefan-it). The original code can be +found [here](https://github.com/google-research/t5x). + +## Usage tips + +- UMT5 was only pre-trained on [mC4](https://huggingface.co/datasets/mc4) excluding any supervised training. +Therefore, this model has to be fine-tuned before it is usable on a downstream task, unlike the original T5 model. +- Since umT5 was pre-trained in an unsupervised manner, 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. + +## Differences with mT5? +`UmT5` is based on mT5, with a non-shared relative positional bias that is computed for each layer. This means that the model set `has_relative_bias` for each layer. +The conversion script is also different because the model was saved in t5x's latest checkpointing format. + +# Sample usage + +```python +>>> from transformers import AutoModelForSeq2SeqLM, AutoTokenizer + +>>> model = AutoModelForSeq2SeqLM.from_pretrained("google/umt5-small") +>>> tokenizer = AutoTokenizer.from_pretrained("google/umt5-small") + +>>> inputs = tokenizer( +... "A walks into a bar and orders a with pinch of .", +... return_tensors="pt", +... ) +>>> outputs = model.generate(**inputs) +>>> print(tokenizer.batch_decode(outputs)) +['nyone who drink a alcohol A A. This I'] +``` + + + +Refer to [T5's documentation page](t5) for more tips, code examples and notebooks. + + +## UMT5Config + +[[autodoc]] UMT5Config + +## UMT5Model + +[[autodoc]] UMT5Model + - forward + +## UMT5ForConditionalGeneration + +[[autodoc]] UMT5ForConditionalGeneration + - forward + +## UMT5EncoderModel + +[[autodoc]] UMT5EncoderModel + - forward + +## UMT5ForSequenceClassification + +[[autodoc]] UMT5ForSequenceClassification + - forward + +## UMT5ForTokenClassification + +[[autodoc]] UMT5ForTokenClassification + - forward + +## UMT5ForQuestionAnswering + +[[autodoc]] UMT5ForQuestionAnswering + - forward + diff --git a/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/unispeech-sat.md b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/unispeech-sat.md new file mode 100644 index 0000000000000000000000000000000000000000..3f0bbcc79323f23271c555fca6fe4c0864ad69ed --- /dev/null +++ b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/unispeech-sat.md @@ -0,0 +1,92 @@ + + +# UniSpeech-SAT + +## Overview + +The UniSpeech-SAT model was proposed in [UniSpeech-SAT: Universal Speech Representation Learning with Speaker Aware +Pre-Training](https://arxiv.org/abs/2110.05752) by Sanyuan Chen, Yu Wu, Chengyi Wang, Zhengyang Chen, Zhuo Chen, +Shujie Liu, Jian Wu, Yao Qian, Furu Wei, Jinyu Li, Xiangzhan Yu . + +The abstract from the paper is the following: + +*Self-supervised learning (SSL) is a long-standing goal for speech processing, since it utilizes large-scale unlabeled +data and avoids extensive human labeling. Recent years witness great successes in applying self-supervised learning in +speech recognition, while limited exploration was attempted in applying SSL for modeling speaker characteristics. In +this paper, we aim to improve the existing SSL framework for speaker representation learning. Two methods are +introduced for enhancing the unsupervised speaker information extraction. First, we apply the multi-task learning to +the current SSL framework, where we integrate the utterance-wise contrastive loss with the SSL objective function. +Second, for better speaker discrimination, we propose an utterance mixing strategy for data augmentation, where +additional overlapped utterances are created unsupervisedly and incorporate during training. We integrate the proposed +methods into the HuBERT framework. Experiment results on SUPERB benchmark show that the proposed system achieves +state-of-the-art performance in universal representation learning, especially for speaker identification oriented +tasks. An ablation study is performed verifying the efficacy of each proposed method. Finally, we scale up training +dataset to 94 thousand hours public audio data and achieve further performance improvement in all SUPERB tasks.* + +This model was contributed by [patrickvonplaten](https://huggingface.co/patrickvonplaten). The Authors' code can be +found [here](https://github.com/microsoft/UniSpeech/tree/main/UniSpeech-SAT). + +## Usage tips + +- UniSpeechSat 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. +- UniSpeechSat model can be fine-tuned using connectionist temporal classification (CTC) so the model output has to be + decoded using [`Wav2Vec2CTCTokenizer`]. +- UniSpeechSat performs especially well on speaker verification, speaker identification, and speaker diarization tasks. + +## Resources + +- [Audio classification task guide](../tasks/audio_classification) +- [Automatic speech recognition task guide](../tasks/asr) + +## UniSpeechSatConfig + +[[autodoc]] UniSpeechSatConfig + +## UniSpeechSat specific outputs + +[[autodoc]] models.unispeech_sat.modeling_unispeech_sat.UniSpeechSatForPreTrainingOutput + +## UniSpeechSatModel + +[[autodoc]] UniSpeechSatModel + - forward + +## UniSpeechSatForCTC + +[[autodoc]] UniSpeechSatForCTC + - forward + +## UniSpeechSatForSequenceClassification + +[[autodoc]] UniSpeechSatForSequenceClassification + - forward + +## UniSpeechSatForAudioFrameClassification + +[[autodoc]] UniSpeechSatForAudioFrameClassification + - forward + +## UniSpeechSatForXVector + +[[autodoc]] UniSpeechSatForXVector + - forward + +## UniSpeechSatForPreTraining + +[[autodoc]] UniSpeechSatForPreTraining + - forward diff --git a/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/unispeech.md b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/unispeech.md new file mode 100644 index 0000000000000000000000000000000000000000..2b2b13bed52c17890f63e0e86d88a13907eb29e5 --- /dev/null +++ b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/unispeech.md @@ -0,0 +1,77 @@ + + +# UniSpeech + +## Overview + +The UniSpeech model was proposed in [UniSpeech: Unified Speech Representation Learning with Labeled and Unlabeled Data](https://arxiv.org/abs/2101.07597) 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](https://huggingface.co/patrickvonplaten). The Authors' code can be +found [here](https://github.com/microsoft/UniSpeech/tree/main/UniSpeech). + +## 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](../tasks/audio_classification) +- [Automatic speech recognition task guide](../tasks/asr) + +## 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 diff --git a/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/univnet.md b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/univnet.md new file mode 100644 index 0000000000000000000000000000000000000000..45bd94732773ae48ee39dc847019a50a4a036d73 --- /dev/null +++ b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/univnet.md @@ -0,0 +1,80 @@ + + +# UnivNet + +## Overview + +The UnivNet model was proposed in [UnivNet: A Neural Vocoder with Multi-Resolution Spectrogram Discriminators for High-Fidelity Waveform Generation](https://arxiv.org/abs/2106.07889) by Won Jang, Dan Lim, Jaesam Yoon, Bongwan Kin, and Juntae Kim. +The UnivNet model is a generative adversarial network (GAN) trained to synthesize high fidelity speech waveforms. The UnivNet model shared in `transformers` is the *generator*, which maps a conditioning log-mel spectrogram and optional noise sequence to a speech waveform (e.g. a vocoder). Only the generator is required for inference. The *discriminator* used to train the `generator` is not implemented. + +The abstract from the paper is the following: + +*Most neural vocoders employ band-limited mel-spectrograms to generate waveforms. If full-band spectral features are used as the input, the vocoder can be provided with as much acoustic information as possible. However, in some models employing full-band mel-spectrograms, an over-smoothing problem occurs as part of which non-sharp spectrograms are generated. To address this problem, we propose UnivNet, a neural vocoder that synthesizes high-fidelity waveforms in real time. Inspired by works in the field of voice activity detection, we added a multi-resolution spectrogram discriminator that employs multiple linear spectrogram magnitudes computed using various parameter sets. Using full-band mel-spectrograms as input, we expect to generate high-resolution signals by adding a discriminator that employs spectrograms of multiple resolutions as the input. In an evaluation on a dataset containing information on hundreds of speakers, UnivNet obtained the best objective and subjective results among competing models for both seen and unseen speakers. These results, including the best subjective score for text-to-speech, demonstrate the potential for fast adaptation to new speakers without a need for training from scratch.* + +Tips: + +- The `noise_sequence` argument for [`UnivNetModel.forward`] should be standard Gaussian noise (such as from `torch.randn`) of shape `([batch_size], noise_length, model.config.model_in_channels)`, where `noise_length` should match the length dimension (dimension 1) of the `input_features` argument. If not supplied, it will be randomly generated; a `torch.Generator` can be supplied to the `generator` argument so that the forward pass can be reproduced. (Note that [`UnivNetFeatureExtractor`] will return generated noise by default, so it shouldn't be necessary to generate `noise_sequence` manually.) +- Padding added by [`UnivNetFeatureExtractor`] can be removed from the [`UnivNetModel`] output through the [`UnivNetFeatureExtractor.batch_decode`] method, as shown in the usage example below. +- Padding the end of each waveform with silence can reduce artifacts at the end of the generated audio sample. This can be done by supplying `pad_end = True` to [`UnivNetFeatureExtractor.__call__`]. See [this issue](https://github.com/seungwonpark/melgan/issues/8) for more details. + +Usage Example: + +```python +import torch +from scipy.io.wavfile import write +from datasets import Audio, load_dataset + +from transformers import UnivNetFeatureExtractor, UnivNetModel + +model_id_or_path = "dg845/univnet-dev" +model = UnivNetModel.from_pretrained(model_id_or_path) +feature_extractor = UnivNetFeatureExtractor.from_pretrained(model_id_or_path) + +ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") +# Resample the audio to the model and feature extractor's sampling rate. +ds = ds.cast_column("audio", Audio(sampling_rate=feature_extractor.sampling_rate)) +# Pad the end of the converted waveforms to reduce artifacts at the end of the output audio samples. +inputs = feature_extractor( + ds[0]["audio"]["array"], sampling_rate=ds[0]["audio"]["sampling_rate"], pad_end=True, return_tensors="pt" +) + +with torch.no_grad(): + audio = model(**inputs) + +# Remove the extra padding at the end of the output. +audio = feature_extractor.batch_decode(**audio)[0] +# Convert to wav file +write("sample_audio.wav", feature_extractor.sampling_rate, audio) +``` + +This model was contributed by [dg845](https://huggingface.co/dg845). +To the best of my knowledge, there is no official code release, but an unofficial implementation can be found at [maum-ai/univnet](https://github.com/maum-ai/univnet) with pretrained checkpoints [here](https://github.com/maum-ai/univnet#pre-trained-model). + + +## UnivNetConfig + +[[autodoc]] UnivNetConfig + +## UnivNetFeatureExtractor + +[[autodoc]] UnivNetFeatureExtractor + - __call__ + +## UnivNetModel + +[[autodoc]] UnivNetModel + - forward \ No newline at end of file diff --git a/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/upernet.md b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/upernet.md new file mode 100644 index 0000000000000000000000000000000000000000..418c3ef1786b52d5f265336994dabf93a12cf8af --- /dev/null +++ b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/upernet.md @@ -0,0 +1,79 @@ + + +# UPerNet + +## Overview + +The UPerNet model was proposed in [Unified Perceptual Parsing for Scene Understanding](https://arxiv.org/abs/1807.10221) +by Tete Xiao, Yingcheng Liu, Bolei Zhou, Yuning Jiang, Jian Sun. UPerNet is a general framework to effectively segment +a wide range of concepts from images, leveraging any vision backbone like [ConvNeXt](convnext) or [Swin](swin). + +The abstract from the paper is the following: + +*Humans recognize the visual world at multiple levels: we effortlessly categorize scenes and detect objects inside, while also identifying the textures and surfaces of the objects along with their different compositional parts. In this paper, we study a new task called Unified Perceptual Parsing, which requires the machine vision systems to recognize as many visual concepts as possible from a given image. A multi-task framework called UPerNet and a training strategy are developed to learn from heterogeneous image annotations. We benchmark our framework on Unified Perceptual Parsing and show that it is able to effectively segment a wide range of concepts from images. The trained networks are further applied to discover visual knowledge in natural scenes.* + + + + UPerNet framework. Taken from the original paper. + +This model was contributed by [nielsr](https://huggingface.co/nielsr). The original code is based on OpenMMLab's mmsegmentation [here](https://github.com/open-mmlab/mmsegmentation/blob/master/mmseg/models/decode_heads/uper_head.py). + +## Usage examples + +UPerNet is a general framework for semantic segmentation. It can be used with any vision backbone, like so: + +```py +from transformers import SwinConfig, UperNetConfig, UperNetForSemanticSegmentation + +backbone_config = SwinConfig(out_features=["stage1", "stage2", "stage3", "stage4"]) + +config = UperNetConfig(backbone_config=backbone_config) +model = UperNetForSemanticSegmentation(config) +``` + +To use another vision backbone, like [ConvNeXt](convnext), simply instantiate the model with the appropriate backbone: + +```py +from transformers import ConvNextConfig, UperNetConfig, UperNetForSemanticSegmentation + +backbone_config = ConvNextConfig(out_features=["stage1", "stage2", "stage3", "stage4"]) + +config = UperNetConfig(backbone_config=backbone_config) +model = UperNetForSemanticSegmentation(config) +``` + +Note that this will randomly initialize all the weights of the model. + +## Resources + +A list of official Hugging Face and community (indicated by ๐ŸŒŽ) resources to help you get started with UPerNet. + +- Demo notebooks for UPerNet can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/UPerNet). +- [`UperNetForSemanticSegmentation`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/semantic-segmentation) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/semantic_segmentation.ipynb). +- See also: [Semantic segmentation task guide](../tasks/semantic_segmentation) + +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. + +## UperNetConfig + +[[autodoc]] UperNetConfig + +## UperNetForSemanticSegmentation + +[[autodoc]] UperNetForSemanticSegmentation + - forward \ No newline at end of file diff --git a/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/van.md b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/van.md new file mode 100644 index 0000000000000000000000000000000000000000..2fb8475ce72f3285904df831617a8450d3300776 --- /dev/null +++ b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/van.md @@ -0,0 +1,72 @@ + + +# 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](https://arxiv.org/abs/2202.09741) 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](https://github.com/Visual-Attention-Network/VAN-Classification).* + +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](https://arxiv.org/abs/2202.09741). + + + +This model was contributed by [Francesco](https://huggingface.co/Francesco). The original code can be found [here](https://github.com/Visual-Attention-Network/VAN-Classification). + +## 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](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb). +- See also: [Image classification task guide](../tasks/image_classification) + +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 + diff --git a/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/video_llava.md b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/video_llava.md new file mode 100644 index 0000000000000000000000000000000000000000..a3ba1258ecfa061fc63bb7971e5dbb1e8833c16b --- /dev/null +++ b/tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/video_llava.md @@ -0,0 +1,215 @@ + + +# Video-LLaVA + +## Overview + +Video-LLaVa is an open-source multimodal LLM trained by fine-tuning LlamA/Vicuna on multimodal instruction-following data generated by Llava1.5 and VideChat. It is an auto-regressive language model, based on the transformer architecture. Video-LLaVa unifies visual representations to the language feature space, and enables an LLM to perform visual reasoning capabilities on both images and videos simultaneously. + + +The Video-LLaVA model was proposed in [Video-LLaVA: Learning United Visual Representation by Alignment Before Projection](https://arxiv.org/abs/2311.10122) by Bin Lin, Yang Ye, Bin Zhu, Jiaxi Cui, Munang Ning, Peng Jin, Li Yuan. + +The abstract from the paper is the following: + +*The Large Vision-Language Model (LVLM) has enhanced the performance of various downstream tasks in +visual-language understanding. Most existing approaches +encode images and videos into separate feature spaces, +which are then fed as inputs to large language models. +However, due to the lack of unified tokenization for images and videos, namely misalignment before projection, it +becomes challenging for a Large Language Model (LLM) +to learn multi-modal interactions from several poor projection layers. In this work, we unify visual representation into the language feature space to advance the foundational LLM towards a unified LVLM. As a result, we establish a simple but robust LVLM baseline, Video-LLaVA, +which learns from a mixed dataset of images and videos, +mutually enhancing each other. Video-LLaVA achieves superior performances on a broad range of 9 image benchmarks across 5 image question-answering datasets and 4 +image benchmark toolkits. Additionally, our Video-LLaVA +also outperforms Video-ChatGPT by 5.8%, 9.9%, 18.6%, +and 10.1% on MSRVTT, MSVD, TGIF, and ActivityNet, respectively. Notably, extensive experiments demonstrate that +Video-LLaVA mutually benefits images and videos within +a unified visual representation, outperforming models designed specifically for images or videos. We aim for this +work to provide modest insights into the multi-modal inputs +for the LLM* + +## Usage tips: + +- 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/videos in the same prompt, although this is technically possible, you may experience inaccurate results. + +- Note that the video inputs should have exactly 8 frames at the input, since the models were trained in that setting. + +This model was contributed by [RaushanTurganbay](https://huggingface.co/RaushanTurganbay). +The original code can be found [here](https://github.com/PKU-YuanGroup/Video-LLaVA). + + +> [!NOTE] +> LLaVA models after release v4.46 will raise warnings about adding `processor.patch_size = {{patch_size}}`, `processor.num_additional_image_tokens = {{num_additional_image_tokens}}` and processor.vision_feature_select_strategy = {{vision_feature_select_strategy}}`. It is strongly recommended to add the attributes to the processor if you own the model checkpoint, or open a PR if it is not owned by you. +Adding these attributes means that LLaVA will try to infer the number of image tokens required per image and expand the text with as many `` placeholders as there will be tokens. Usually it is around 500 tokens per image, so make sure that the text is not truncated as otherwise there will be failure when merging the embeddings. +The attributes can be obtained from model config, as `model.config.vision_config.patch_size` or `model.config.vision_feature_select_strategy`. The `num_additional_image_tokens` should be `1` if the vision backbone adds a CLS token or `0` if nothing extra is added to the vision patches. + + +## Usage example + +### Single Media Mode + +The model can accept both images and videos as input. Here's an example code for inference in half-precision (`torch.float16`): + +```python +import av +import torch +import numpy as np +from transformers import VideoLlavaForConditionalGeneration, VideoLlavaProcessor + +def read_video_pyav(container, indices): + ''' + Decode the video with PyAV decoder. + Args: + container (`av.container.input.InputContainer`): PyAV container. + indices (`List[int]`): List of frame indices to decode. + Returns: + result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3). + ''' + frames = [] + container.seek(0) + start_index = indices[0] + end_index = indices[-1] + for i, frame in enumerate(container.decode(video=0)): + if i > end_index: + break + if i >= start_index and i in indices: + frames.append(frame) + return np.stack([x.to_ndarray(format="rgb24") for x in frames]) + +# Load the model in half-precision +model = VideoLlavaForConditionalGeneration.from_pretrained("LanguageBind/Video-LLaVA-7B-hf", torch_dtype=torch.float16, device_map="auto") +processor = VideoLlavaProcessor.from_pretrained("LanguageBind/Video-LLaVA-7B-hf") + +# Load the video as an np.arrau, sampling uniformly 8 frames +video_path = hf_hub_download(repo_id="raushan-testing-hf/videos-test", filename="sample_demo_1.mp4", repo_type="dataset") +container = av.open(video_path) +total_frames = container.streams.video[0].frames +indices = np.arange(0, total_frames, total_frames / 8).astype(int) +video = read_video_pyav(container, indices) + +# For better results, we recommend to prompt the model in the following format +prompt = "USER: