Stage Harbor release files 13001-13500
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/swin.md +107 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/swin2sr.md +61 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/swinv2.md +62 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/switch_transformers.md +71 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/t5.md +456 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/t5v1.1.md +71 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/table-transformer.md +67 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/tapas.md +634 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/tapex.md +149 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/textnet.md +55 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/time_series_transformer.md +72 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/timesformer.md +52 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/timm_wrapper.md +67 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/trajectory_transformer.md +61 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/transfo-xl.md +162 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/trocr.md +126 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/tvlt.md +85 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/tvp.md +186 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/udop.md +113 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/ul2.md +43 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/umt5.md +112 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/unispeech-sat.md +92 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/unispeech.md +77 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/univnet.md +80 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/upernet.md +79 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/van.md +72 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/video_llava.md +215 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/videomae.md +105 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/vilt.md +104 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/vipllava.md +101 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/vision-encoder-decoder.md +182 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/vision-text-dual-encoder.md +64 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/visual_bert.md +127 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/vit.md +211 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/vit_hybrid.md +106 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/vit_mae.md +123 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/vit_msn.md +103 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/vitdet.md +38 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/vitmatte.md +55 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/vitpose.md +254 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/vits.md +182 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/vivit.md +80 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/wav2vec2-bert.md +90 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/wav2vec2-conformer.md +83 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/wav2vec2.md +279 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/wav2vec2_phoneme.md +65 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/wavlm.md +83 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/whisper.md +257 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/xclip.md +80 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/xglm.md +105 -0
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/swin.md
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Swin Transformer
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
The Swin Transformer was proposed in [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://arxiv.org/abs/2103.14030)
|
| 22 |
+
by Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo.
|
| 23 |
+
|
| 24 |
+
The abstract from the paper is the following:
|
| 25 |
+
|
| 26 |
+
*This paper presents a new vision Transformer, called Swin Transformer, that capably serves as a general-purpose backbone
|
| 27 |
+
for computer vision. Challenges in adapting Transformer from language to vision arise from differences between the two domains,
|
| 28 |
+
such as large variations in the scale of visual entities and the high resolution of pixels in images compared to words in text.
|
| 29 |
+
To address these differences, we propose a hierarchical Transformer whose representation is computed with \bold{S}hifted
|
| 30 |
+
\bold{win}dows. The shifted windowing scheme brings greater efficiency by limiting self-attention computation to non-overlapping
|
| 31 |
+
local windows while also allowing for cross-window connection. This hierarchical architecture has the flexibility to model at
|
| 32 |
+
various scales and has linear computational complexity with respect to image size. These qualities of Swin Transformer make it
|
| 33 |
+
compatible with a broad range of vision tasks, including image classification (87.3 top-1 accuracy on ImageNet-1K) and dense
|
| 34 |
+
prediction tasks such as object detection (58.7 box AP and 51.1 mask AP on COCO test-dev) and semantic segmentation
|
| 35 |
+
(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
|
| 36 |
+
+2.6 mask AP on COCO, and +3.2 mIoU on ADE20K, demonstrating the potential of Transformer-based models as vision backbones.
|
| 37 |
+
The hierarchical design and the shifted window approach also prove beneficial for all-MLP architectures.*
|
| 38 |
+
|
| 39 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/swin_transformer_architecture.png"
|
| 40 |
+
alt="drawing" width="600"/>
|
| 41 |
+
|
| 42 |
+
<small> Swin Transformer architecture. Taken from the <a href="https://arxiv.org/abs/2102.03334">original paper</a>.</small>
|
| 43 |
+
|
| 44 |
+
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).
|
| 45 |
+
|
| 46 |
+
## Usage tips
|
| 47 |
+
|
| 48 |
+
- Swin pads the inputs supporting any input height and width (if divisible by `32`).
|
| 49 |
+
- 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)`.
|
| 50 |
+
|
| 51 |
+
## Resources
|
| 52 |
+
|
| 53 |
+
A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with Swin Transformer.
|
| 54 |
+
|
| 55 |
+
<PipelineTag pipeline="image-classification"/>
|
| 56 |
+
|
| 57 |
+
- [`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).
|
| 58 |
+
- See also: [Image classification task guide](../tasks/image_classification)
|
| 59 |
+
|
| 60 |
+
Besides that:
|
| 61 |
+
|
| 62 |
+
- [`SwinForMaskedImageModeling`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-pretraining).
|
| 63 |
+
|
| 64 |
+
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.
|
| 65 |
+
|
| 66 |
+
## SwinConfig
|
| 67 |
+
|
| 68 |
+
[[autodoc]] SwinConfig
|
| 69 |
+
|
| 70 |
+
<frameworkcontent>
|
| 71 |
+
<pt>
|
| 72 |
+
|
| 73 |
+
## SwinModel
|
| 74 |
+
|
| 75 |
+
[[autodoc]] SwinModel
|
| 76 |
+
- forward
|
| 77 |
+
|
| 78 |
+
## SwinForMaskedImageModeling
|
| 79 |
+
|
| 80 |
+
[[autodoc]] SwinForMaskedImageModeling
|
| 81 |
+
- forward
|
| 82 |
+
|
| 83 |
+
## SwinForImageClassification
|
| 84 |
+
|
| 85 |
+
[[autodoc]] transformers.SwinForImageClassification
|
| 86 |
+
- forward
|
| 87 |
+
|
| 88 |
+
</pt>
|
| 89 |
+
<tf>
|
| 90 |
+
|
| 91 |
+
## TFSwinModel
|
| 92 |
+
|
| 93 |
+
[[autodoc]] TFSwinModel
|
| 94 |
+
- call
|
| 95 |
+
|
| 96 |
+
## TFSwinForMaskedImageModeling
|
| 97 |
+
|
| 98 |
+
[[autodoc]] TFSwinForMaskedImageModeling
|
| 99 |
+
- call
|
| 100 |
+
|
| 101 |
+
## TFSwinForImageClassification
|
| 102 |
+
|
| 103 |
+
[[autodoc]] transformers.TFSwinForImageClassification
|
| 104 |
+
- call
|
| 105 |
+
|
| 106 |
+
</tf>
|
| 107 |
+
</frameworkcontent>
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/swin2sr.md
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Swin2SR
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
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.
|
| 22 |
+
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
|
| 23 |
+
and fine-tuning, and hunger on data.
|
| 24 |
+
|
| 25 |
+
The abstract from the paper is the following:
|
| 26 |
+
|
| 27 |
+
*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.
|
| 28 |
+
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".*
|
| 29 |
+
|
| 30 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/swin2sr_architecture.png"
|
| 31 |
+
alt="drawing" width="600"/>
|
| 32 |
+
|
| 33 |
+
<small> Swin2SR architecture. Taken from the <a href="https://arxiv.org/abs/2209.11345">original paper.</a> </small>
|
| 34 |
+
|
| 35 |
+
This model was contributed by [nielsr](https://huggingface.co/nielsr).
|
| 36 |
+
The original code can be found [here](https://github.com/mv-lab/swin2sr).
|
| 37 |
+
|
| 38 |
+
## Resources
|
| 39 |
+
|
| 40 |
+
Demo notebooks for Swin2SR can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/Swin2SR).
|
| 41 |
+
|
| 42 |
+
A demo Space for image super-resolution with SwinSR can be found [here](https://huggingface.co/spaces/jjourney1125/swin2sr).
|
| 43 |
+
|
| 44 |
+
## Swin2SRImageProcessor
|
| 45 |
+
|
| 46 |
+
[[autodoc]] Swin2SRImageProcessor
|
| 47 |
+
- preprocess
|
| 48 |
+
|
| 49 |
+
## Swin2SRConfig
|
| 50 |
+
|
| 51 |
+
[[autodoc]] Swin2SRConfig
|
| 52 |
+
|
| 53 |
+
## Swin2SRModel
|
| 54 |
+
|
| 55 |
+
[[autodoc]] Swin2SRModel
|
| 56 |
+
- forward
|
| 57 |
+
|
| 58 |
+
## Swin2SRForImageSuperResolution
|
| 59 |
+
|
| 60 |
+
[[autodoc]] Swin2SRForImageSuperResolution
|
| 61 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/swinv2.md
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Swin Transformer V2
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
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.
|
| 22 |
+
|
| 23 |
+
The abstract from the paper is the following:
|
| 24 |
+
|
| 25 |
+
*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.*
|
| 26 |
+
|
| 27 |
+
This model was contributed by [nandwalritik](https://huggingface.co/nandwalritik).
|
| 28 |
+
The original code can be found [here](https://github.com/microsoft/Swin-Transformer).
|
| 29 |
+
|
| 30 |
+
## Resources
|
| 31 |
+
|
| 32 |
+
A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with Swin Transformer v2.
|
| 33 |
+
|
| 34 |
+
<PipelineTag pipeline="image-classification"/>
|
| 35 |
+
|
| 36 |
+
- [`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).
|
| 37 |
+
- See also: [Image classification task guide](../tasks/image_classification)
|
| 38 |
+
|
| 39 |
+
Besides that:
|
| 40 |
+
|
| 41 |
+
- [`Swinv2ForMaskedImageModeling`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-pretraining).
|
| 42 |
+
|
| 43 |
+
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.
|
| 44 |
+
|
| 45 |
+
## Swinv2Config
|
| 46 |
+
|
| 47 |
+
[[autodoc]] Swinv2Config
|
| 48 |
+
|
| 49 |
+
## Swinv2Model
|
| 50 |
+
|
| 51 |
+
[[autodoc]] Swinv2Model
|
| 52 |
+
- forward
|
| 53 |
+
|
| 54 |
+
## Swinv2ForMaskedImageModeling
|
| 55 |
+
|
| 56 |
+
[[autodoc]] Swinv2ForMaskedImageModeling
|
| 57 |
+
- forward
|
| 58 |
+
|
| 59 |
+
## Swinv2ForImageClassification
|
| 60 |
+
|
| 61 |
+
[[autodoc]] transformers.Swinv2ForImageClassification
|
| 62 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/switch_transformers.md
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# SwitchTransformers
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
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.
|
| 22 |
+
|
| 23 |
+
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.
|
| 24 |
+
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.
|
| 25 |
+
|
| 26 |
+
The abstract from the paper is the following:
|
| 27 |
+
|
| 28 |
+
*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.*
|
| 29 |
+
|
| 30 |
+
This model was contributed by [Younes Belkada](https://huggingface.co/ybelkada) and [Arthur Zucker](https://huggingface.co/ArthurZ).
|
| 31 |
+
The original code can be found [here](https://github.com/google/flaxformer/tree/main/flaxformer/architectures/moe).
|
| 32 |
+
|
| 33 |
+
## Usage tips
|
| 34 |
+
|
| 35 |
+
- SwitchTransformers uses the [`T5Tokenizer`], which can be loaded directly from each model's repository.
|
| 36 |
+
- 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.
|
| 37 |
+
|
| 38 |
+
## Resources
|
| 39 |
+
|
| 40 |
+
- [Translation task guide](../tasks/translation)
|
| 41 |
+
- [Summarization task guide](../tasks/summarization)
|
| 42 |
+
|
| 43 |
+
## SwitchTransformersConfig
|
| 44 |
+
|
| 45 |
+
[[autodoc]] SwitchTransformersConfig
|
| 46 |
+
|
| 47 |
+
## SwitchTransformersTop1Router
|
| 48 |
+
|
| 49 |
+
[[autodoc]] SwitchTransformersTop1Router
|
| 50 |
+
- _compute_router_probabilities
|
| 51 |
+
- forward
|
| 52 |
+
|
| 53 |
+
## SwitchTransformersSparseMLP
|
| 54 |
+
|
| 55 |
+
[[autodoc]] SwitchTransformersSparseMLP
|
| 56 |
+
- forward
|
| 57 |
+
|
| 58 |
+
## SwitchTransformersModel
|
| 59 |
+
|
| 60 |
+
[[autodoc]] SwitchTransformersModel
|
| 61 |
+
- forward
|
| 62 |
+
|
| 63 |
+
## SwitchTransformersForConditionalGeneration
|
| 64 |
+
|
| 65 |
+
[[autodoc]] SwitchTransformersForConditionalGeneration
|
| 66 |
+
- forward
|
| 67 |
+
|
| 68 |
+
## SwitchTransformersEncoderModel
|
| 69 |
+
|
| 70 |
+
[[autodoc]] SwitchTransformersEncoderModel
|
| 71 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/t5.md
ADDED
|
@@ -0,0 +1,456 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# T5
|
| 18 |
+
|
| 19 |
+
<div class="flex flex-wrap space-x-1">
|
| 20 |
+
<a href="https://huggingface.co/models?filter=t5">
|
| 21 |
+
<img alt="Models" src="https://img.shields.io/badge/All_model_pages-t5-blueviolet">
|
| 22 |
+
</a>
|
| 23 |
+
<a href="https://huggingface.co/spaces/docs-demos/t5-base">
|
| 24 |
+
<img alt="Spaces" src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue">
|
| 25 |
+
</a>
|
| 26 |
+
<a href="https://huggingface.co/papers/1910.10683">
|
| 27 |
+
<img alt="Paper page" src="https://img.shields.io/badge/Paper%20page-1910.10683-green">
|
| 28 |
+
</a>
|
| 29 |
+
</div>
|
| 30 |
+
|
| 31 |
+
## Overview
|
| 32 |
+
|
| 33 |
+
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,
|
| 34 |
+
Michael Matena, Yanqi Zhou, Wei Li, [Peter J. Liu](https://huggingface.co/peterjliu).
|
| 35 |
+
|
| 36 |
+
The abstract from the paper is the following:
|
| 37 |
+
|
| 38 |
+
*Transfer learning, where a model is first pre-trained on a data-rich task before being fine-tuned on a downstream
|
| 39 |
+
task, has emerged as a powerful technique in natural language processing (NLP). The effectiveness of transfer learning
|
| 40 |
+
has given rise to a diversity of approaches, methodology, and practice. In this paper, we explore the landscape of
|
| 41 |
+
transfer learning techniques for NLP by introducing a unified framework that converts every language problem into a
|
| 42 |
+
text-to-text format. Our systematic study compares pretraining objectives, architectures, unlabeled datasets, transfer
|
| 43 |
+
approaches, and other factors on dozens of language understanding tasks. By combining the insights from our exploration
|
| 44 |
+
with scale and our new "Colossal Clean Crawled Corpus", we achieve state-of-the-art results on many benchmarks covering
|
| 45 |
+
summarization, question answering, text classification, and more. To facilitate future work on transfer learning for
|
| 46 |
+
NLP, we release our dataset, pre-trained models, and code.*
|
| 47 |
+
|
| 48 |
+
All checkpoints can be found on the [hub](https://huggingface.co/models?search=t5).
|
| 49 |
+
|
| 50 |
+
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).
|
| 51 |
+
|
| 52 |
+
## Usage tips
|
| 53 |
+
|
| 54 |
+
- T5 is an encoder-decoder model pre-trained on a multi-task mixture of unsupervised and supervised tasks and for which
|
| 55 |
+
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
|
| 56 |
+
different prefix to the input corresponding to each task, e.g., for translation: *translate English to German: ...*,
|
| 57 |
+
for summarization: *summarize: ...*.
|
| 58 |
+
- 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).
|
| 59 |
+
- 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.
|
| 60 |
+
|
| 61 |
+
- T5 uses relative scalar embeddings. Encoder input padding can be done on the left and on the right.
|
| 62 |
+
|
| 63 |
+
- See the [training](#training), [inference](#inference) and [resources](#resources) sections below for all details regarding usage.
|
| 64 |
+
|
| 65 |
+
T5 comes in different sizes:
|
| 66 |
+
|
| 67 |
+
- [google-t5/t5-small](https://huggingface.co/google-t5/t5-small)
|
| 68 |
+
|
| 69 |
+
- [google-t5/t5-base](https://huggingface.co/google-t5/t5-base)
|
| 70 |
+
|
| 71 |
+
- [google-t5/t5-large](https://huggingface.co/google-t5/t5-large)
|
| 72 |
+
|
| 73 |
+
- [google-t5/t5-3b](https://huggingface.co/google-t5/t5-3b)
|
| 74 |
+
|
| 75 |
+
- [google-t5/t5-11b](https://huggingface.co/google-t5/t5-11b).
|
| 76 |
+
|
| 77 |
+
Based on the original T5 model, Google has released some follow-up works:
|
| 78 |
+
|
| 79 |
+
- **T5v1.1**: T5v1.1 is an improved version of T5 with some architectural tweaks, and is pre-trained on C4 only without
|
| 80 |
+
mixing in the supervised tasks. Refer to the documentation of T5v1.1 which can be found [here](t5v1.1).
|
| 81 |
+
|
| 82 |
+
- **mT5**: mT5 is a multilingual T5 model. It is pre-trained on the mC4 corpus, which includes 101 languages. Refer to
|
| 83 |
+
the documentation of mT5 which can be found [here](mt5).
|
| 84 |
+
|
| 85 |
+
- **byT5**: byT5 is a T5 model pre-trained on byte sequences rather than SentencePiece subword token sequences. Refer
|
| 86 |
+
to the documentation of byT5 which can be found [here](byt5).
|
| 87 |
+
|
| 88 |
+
- **UL2**: UL2 is a T5 like model pretrained on various denoising objectives
|
| 89 |
+
|
| 90 |
+
- **Flan-T5**: Flan is a pretraining methods that is based on prompting. The Flan-T5 are T5 models trained on the Flan collection of
|
| 91 |
+
datasets which include: `taskmaster2`, `djaym7/wiki_dialog`, `deepmind/code_contests`, `lambada`, `gsm8k`, `aqua_rat`, `esnli`, `quasc` and `qed`.
|
| 92 |
+
|
| 93 |
+
- **FLan-UL2** : the UL2 model finetuned using the "Flan" prompt tuning and dataset collection.
|
| 94 |
+
|
| 95 |
+
- **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
|
| 96 |
+
the documentation of mT5 which can be found [here](umt5).
|
| 97 |
+
|
| 98 |
+
## Training
|
| 99 |
+
|
| 100 |
+
T5 is an encoder-decoder model and converts all NLP problems into a text-to-text format. It is trained using teacher
|
| 101 |
+
forcing. This means that for training, we always need an input sequence and a corresponding target sequence. The input
|
| 102 |
+
sequence is fed to the model using `input_ids`. The target sequence is shifted to the right, i.e., prepended by a
|
| 103 |
+
start-sequence token and fed to the decoder using the `decoder_input_ids`. In teacher-forcing style, the target
|
| 104 |
+
sequence is then appended by the EOS token and corresponds to the `labels`. The PAD token is hereby used as the
|
| 105 |
+
start-sequence token. T5 can be trained / fine-tuned both in a supervised and unsupervised fashion.
|
| 106 |
+
|
| 107 |
+
One can use [`T5ForConditionalGeneration`] (or the Tensorflow/Flax variant), which includes the
|
| 108 |
+
language modeling head on top of the decoder.
|
| 109 |
+
|
| 110 |
+
- Unsupervised denoising training
|
| 111 |
+
|
| 112 |
+
In this setup, spans of the input sequence are masked by so-called sentinel tokens (*a.k.a* unique mask tokens) and
|
| 113 |
+
the output sequence is formed as a concatenation of the same sentinel tokens and the *real* masked tokens. Each
|
| 114 |
+
sentinel token represents a unique mask token for this sentence and should start with `<extra_id_0>`,
|
| 115 |
+
`<extra_id_1>`, ... up to `<extra_id_99>`. As a default, 100 sentinel tokens are available in
|
| 116 |
+
[`T5Tokenizer`].
|
| 117 |
+
|
| 118 |
+
For instance, the sentence "The cute dog walks in the park" with the masks put on "cute dog" and "the" should be
|
| 119 |
+
processed as follows:
|
| 120 |
+
|
| 121 |
+
```python
|
| 122 |
+
>>> from transformers import T5Tokenizer, T5ForConditionalGeneration
|
| 123 |
+
|
| 124 |
+
>>> tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-small")
|
| 125 |
+
>>> model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small")
|
| 126 |
+
|
| 127 |
+
>>> input_ids = tokenizer("The <extra_id_0> walks in <extra_id_1> park", return_tensors="pt").input_ids
|
| 128 |
+
>>> labels = tokenizer("<extra_id_0> cute dog <extra_id_1> the <extra_id_2>", return_tensors="pt").input_ids
|
| 129 |
+
|
| 130 |
+
>>> # the forward function automatically creates the correct decoder_input_ids
|
| 131 |
+
>>> loss = model(input_ids=input_ids, labels=labels).loss
|
| 132 |
+
>>> loss.item()
|
| 133 |
+
3.7837
|
| 134 |
+
```
|
| 135 |
+
|
| 136 |
+
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
|
| 137 |
+
directory.
|
| 138 |
+
|
| 139 |
+
- Supervised training
|
| 140 |
+
|
| 141 |
+
In this setup, the input sequence and output sequence are a standard sequence-to-sequence input-output mapping.
|
| 142 |
+
Suppose that we want to fine-tune the model for translation for example, and we have a training example: the input
|
| 143 |
+
sequence "The house is wonderful." and output sequence "Das Haus ist wunderbar.", then they should be prepared for
|
| 144 |
+
the model as follows:
|
| 145 |
+
|
| 146 |
+
```python
|
| 147 |
+
>>> from transformers import T5Tokenizer, T5ForConditionalGeneration
|
| 148 |
+
|
| 149 |
+
>>> tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-small")
|
| 150 |
+
>>> model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small")
|
| 151 |
+
|
| 152 |
+
>>> input_ids = tokenizer("translate English to German: The house is wonderful.", return_tensors="pt").input_ids
|
| 153 |
+
>>> labels = tokenizer("Das Haus ist wunderbar.", return_tensors="pt").input_ids
|
| 154 |
+
|
| 155 |
+
>>> # the forward function automatically creates the correct decoder_input_ids
|
| 156 |
+
>>> loss = model(input_ids=input_ids, labels=labels).loss
|
| 157 |
+
>>> loss.item()
|
| 158 |
+
0.2542
|
| 159 |
+
```
|
| 160 |
+
|
| 161 |
+
As you can see, only 2 inputs are required for the model in order to compute a loss: `input_ids` (which are the
|
| 162 |
+
`input_ids` of the encoded input sequence) and `labels` (which are the `input_ids` of the encoded
|
| 163 |
+
target sequence). The model will automatically create the `decoder_input_ids` based on the `labels`, by
|
| 164 |
+
shifting them one position to the right and prepending the `config.decoder_start_token_id`, which for T5 is
|
| 165 |
+
equal to 0 (i.e. the id of the pad token). Also note the task prefix: we prepend the input sequence with 'translate
|
| 166 |
+
English to German: ' before encoding it. This will help in improving the performance, as this task prefix was used
|
| 167 |
+
during T5's pre-training.
|
| 168 |
+
|
| 169 |
+
However, the example above only shows a single training example. In practice, one trains deep learning models in
|
| 170 |
+
batches. This entails that we must pad/truncate examples to the same length. For encoder-decoder models, one
|
| 171 |
+
typically defines a `max_source_length` and `max_target_length`, which determine the maximum length of the
|
| 172 |
+
input and output sequences respectively (otherwise they are truncated). These should be carefully set depending on
|
| 173 |
+
the task.
|
| 174 |
+
|
| 175 |
+
In addition, we must make sure that padding token id's of the `labels` are not taken into account by the loss
|
| 176 |
+
function. In PyTorch and Tensorflow, this can be done by replacing them with -100, which is the `ignore_index`
|
| 177 |
+
of the `CrossEntropyLoss`. In Flax, one can use the `decoder_attention_mask` to ignore padded tokens from
|
| 178 |
+
the loss (see the [Flax summarization script](https://github.com/huggingface/transformers/tree/main/examples/flax/summarization) for details). We also pass
|
| 179 |
+
`attention_mask` as additional input to the model, which makes sure that padding tokens of the inputs are
|
| 180 |
+
ignored. The code example below illustrates all of this.
|
| 181 |
+
|
| 182 |
+
```python
|
| 183 |
+
>>> from transformers import T5Tokenizer, T5ForConditionalGeneration
|
| 184 |
+
>>> import torch
|
| 185 |
+
|
| 186 |
+
>>> tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-small")
|
| 187 |
+
>>> model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small")
|
| 188 |
+
|
| 189 |
+
>>> # the following 2 hyperparameters are task-specific
|
| 190 |
+
>>> max_source_length = 512
|
| 191 |
+
>>> max_target_length = 128
|
| 192 |
+
|
| 193 |
+
>>> # Suppose we have the following 2 training examples:
|
| 194 |
+
>>> input_sequence_1 = "Welcome to NYC"
|
| 195 |
+
>>> output_sequence_1 = "Bienvenue à NYC"
|
| 196 |
+
|
| 197 |
+
>>> input_sequence_2 = "HuggingFace is a company"
|
| 198 |
+
>>> output_sequence_2 = "HuggingFace est une entreprise"
|
| 199 |
+
|
| 200 |
+
>>> # encode the inputs
|
| 201 |
+
>>> task_prefix = "translate English to French: "
|
| 202 |
+
>>> input_sequences = [input_sequence_1, input_sequence_2]
|
| 203 |
+
|
| 204 |
+
>>> encoding = tokenizer(
|
| 205 |
+
... [task_prefix + sequence for sequence in input_sequences],
|
| 206 |
+
... padding="longest",
|
| 207 |
+
... max_length=max_source_length,
|
| 208 |
+
... truncation=True,
|
| 209 |
+
... return_tensors="pt",
|
| 210 |
+
... )
|
| 211 |
+
|
| 212 |
+
>>> input_ids, attention_mask = encoding.input_ids, encoding.attention_mask
|
| 213 |
+
|
| 214 |
+
>>> # encode the targets
|
| 215 |
+
>>> target_encoding = tokenizer(
|
| 216 |
+
... [output_sequence_1, output_sequence_2],
|
| 217 |
+
... padding="longest",
|
| 218 |
+
... max_length=max_target_length,
|
| 219 |
+
... truncation=True,
|
| 220 |
+
... return_tensors="pt",
|
| 221 |
+
... )
|
| 222 |
+
>>> labels = target_encoding.input_ids
|
| 223 |
+
|
| 224 |
+
>>> # replace padding token id's of the labels by -100 so it's ignored by the loss
|
| 225 |
+
>>> labels[labels == tokenizer.pad_token_id] = -100
|
| 226 |
+
|
| 227 |
+
>>> # forward pass
|
| 228 |
+
>>> loss = model(input_ids=input_ids, attention_mask=attention_mask, labels=labels).loss
|
| 229 |
+
>>> loss.item()
|
| 230 |
+
0.188
|
| 231 |
+
```
|
| 232 |
+
|
| 233 |
+
Additional training tips:
|
| 234 |
+
|
| 235 |
+
- T5 models need a slightly higher learning rate than the default one set in the `Trainer` when using the AdamW
|
| 236 |
+
optimizer. Typically, 1e-4 and 3e-4 work well for most problems (classification, summarization, translation, question
|
| 237 |
+
answering, question generation). Note that T5 was pre-trained using the AdaFactor optimizer.
|
| 238 |
+
|
| 239 |
+
According to [this forum post](https://discuss.huggingface.co/t/t5-finetuning-tips/684), task prefixes matter when
|
| 240 |
+
(1) doing multi-task training (2) your task is similar or related to one of the supervised tasks used in T5's
|
| 241 |
+
pre-training mixture (see Appendix D of the [paper](https://arxiv.org/pdf/1910.10683.pdf) for the task prefixes
|
| 242 |
+
used).
|
| 243 |
+
|
| 244 |
+
If training on TPU, it is recommended to pad all examples of the dataset to the same length or make use of
|
| 245 |
+
*pad_to_multiple_of* to have a small number of predefined bucket sizes to fit all examples in. Dynamically padding
|
| 246 |
+
batches to the longest example is not recommended on TPU as it triggers a recompilation for every batch shape that is
|
| 247 |
+
encountered during training thus significantly slowing down the training. only padding up to the longest example in a
|
| 248 |
+
batch) leads to very slow training on TPU.
|
| 249 |
+
|
| 250 |
+
## Inference
|
| 251 |
+
|
| 252 |
+
At inference time, it is recommended to use [`~generation.GenerationMixin.generate`]. This
|
| 253 |
+
method takes care of encoding the input and feeding the encoded hidden states via cross-attention layers to the decoder
|
| 254 |
+
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.
|
| 255 |
+
There's also [this blog post](https://huggingface.co/blog/encoder-decoder#encoder-decoder) which explains how
|
| 256 |
+
generation works in general in encoder-decoder models.
|
| 257 |
+
|
| 258 |
+
```python
|
| 259 |
+
>>> from transformers import T5Tokenizer, T5ForConditionalGeneration
|
| 260 |
+
|
| 261 |
+
>>> tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-small")
|
| 262 |
+
>>> model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small")
|
| 263 |
+
|
| 264 |
+
>>> input_ids = tokenizer("translate English to German: The house is wonderful.", return_tensors="pt").input_ids
|
| 265 |
+
>>> outputs = model.generate(input_ids)
|
| 266 |
+
>>> print(tokenizer.decode(outputs[0], skip_special_tokens=True))
|
| 267 |
+
Das Haus ist wunderbar.
|
| 268 |
+
```
|
| 269 |
+
|
| 270 |
+
Note that T5 uses the `pad_token_id` as the `decoder_start_token_id`, so when doing generation without using
|
| 271 |
+
[`~generation.GenerationMixin.generate`], make sure you start it with the `pad_token_id`.
|
| 272 |
+
|
| 273 |
+
The example above only shows a single example. You can also do batched inference, like so:
|
| 274 |
+
|
| 275 |
+
```python
|
| 276 |
+
>>> from transformers import T5Tokenizer, T5ForConditionalGeneration
|
| 277 |
+
|
| 278 |
+
>>> tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-small")
|
| 279 |
+
>>> model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small")
|
| 280 |
+
|
| 281 |
+
>>> task_prefix = "translate English to German: "
|
| 282 |
+
>>> # use different length sentences to test batching
|
| 283 |
+
>>> sentences = ["The house is wonderful.", "I like to work in NYC."]
|
| 284 |
+
|
| 285 |
+
>>> inputs = tokenizer([task_prefix + sentence for sentence in sentences], return_tensors="pt", padding=True)
|
| 286 |
+
|
| 287 |
+
>>> output_sequences = model.generate(
|
| 288 |
+
... input_ids=inputs["input_ids"],
|
| 289 |
+
... attention_mask=inputs["attention_mask"],
|
| 290 |
+
... do_sample=False, # disable sampling to test if batching affects output
|
| 291 |
+
... )
|
| 292 |
+
|
| 293 |
+
>>> print(tokenizer.batch_decode(output_sequences, skip_special_tokens=True))
|
| 294 |
+
['Das Haus ist wunderbar.', 'Ich arbeite gerne in NYC.']
|
| 295 |
+
```
|
| 296 |
+
|
| 297 |
+
Because T5 has been trained with the span-mask denoising objective,
|
| 298 |
+
it can be used to predict the sentinel (masked-out) tokens during inference.
|
| 299 |
+
The predicted tokens will then be placed between the sentinel tokens.
|
| 300 |
+
|
| 301 |
+
```python
|
| 302 |
+
>>> from transformers import T5Tokenizer, T5ForConditionalGeneration
|
| 303 |
+
|
| 304 |
+
>>> tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-small")
|
| 305 |
+
>>> model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small")
|
| 306 |
+
|
| 307 |
+
>>> input_ids = tokenizer("The <extra_id_0> walks in <extra_id_1> park", return_tensors="pt").input_ids
|
| 308 |
+
|
| 309 |
+
>>> sequence_ids = model.generate(input_ids)
|
| 310 |
+
>>> sequences = tokenizer.batch_decode(sequence_ids)
|
| 311 |
+
>>> sequences
|
| 312 |
+
['<pad> <extra_id_0> park offers <extra_id_1> the <extra_id_2> park.</s>']
|
| 313 |
+
```
|
| 314 |
+
|
| 315 |
+
## Performance
|
| 316 |
+
|
| 317 |
+
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.
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
## Resources
|
| 321 |
+
|
| 322 |
+
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.
|
| 323 |
+
|
| 324 |
+
<PipelineTag pipeline="text-classification"/>
|
| 325 |
+
|
| 326 |
+
- 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).
|
| 327 |
+
- 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). 🌎
|
| 328 |
+
|
| 329 |
+
<PipelineTag pipeline="token-classification"/>
|
| 330 |
+
|
| 331 |
+
- A notebook for how to [finetune T5 for named entity recognition](https://colab.research.google.com/drive/1obr78FY_cBmWY5ODViCmzdY6O1KB65Vc?usp=sharing). 🌎
|
| 332 |
+
|
| 333 |
+
<PipelineTag pipeline="text-generation"/>
|
| 334 |
+
|
| 335 |
+
- 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).
|
| 336 |
+
|
| 337 |
+
<PipelineTag pipeline="summarization"/>
|
| 338 |
+
|
| 339 |
+
- 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).
|
| 340 |
+
- 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). 🌎
|
| 341 |
+
- A blog post on [Distributed Training: Train BART/T5 for Summarization using 🤗 Transformers and Amazon SageMaker](https://huggingface.co/blog/sagemaker-distributed-training-seq2seq).
|
| 342 |
+
- [`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).
|
| 343 |
+
- [`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).
|
| 344 |
+
- [`FlaxT5ForConditionalGeneration`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/flax/summarization).
|
| 345 |
+
- [Summarization](https://huggingface.co/course/chapter7/5?fw=pt#summarization) chapter of the 🤗 Hugging Face course.
|
| 346 |
+
- [Summarization task guide](../tasks/summarization)
|
| 347 |
+
|
| 348 |
+
<PipelineTag pipeline="fill-mask"/>
|
| 349 |
+
|
| 350 |
+
- [`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).
|
| 351 |
+
|
| 352 |
+
<PipelineTag pipeline="translation"/>
|
| 353 |
+
|
| 354 |
+
- [`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).
|
| 355 |
+
- [`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).
|
| 356 |
+
- [Translation task guide](../tasks/translation)
|
| 357 |
+
|
| 358 |
+
<PipelineTag pipeline="question-answering"/>
|
| 359 |
+
|
| 360 |
+
- 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). 🌎
|
| 361 |
+
- 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).
|
| 362 |
+
|
| 363 |
+
🚀 **Deploy**
|
| 364 |
+
- A blog post on how to deploy [T5 11B for inference for less than $500](https://www.philschmid.de/deploy-t5-11b).
|
| 365 |
+
|
| 366 |
+
## T5Config
|
| 367 |
+
|
| 368 |
+
[[autodoc]] T5Config
|
| 369 |
+
|
| 370 |
+
## T5Tokenizer
|
| 371 |
+
|
| 372 |
+
[[autodoc]] T5Tokenizer
|
| 373 |
+
- build_inputs_with_special_tokens
|
| 374 |
+
- get_special_tokens_mask
|
| 375 |
+
- create_token_type_ids_from_sequences
|
| 376 |
+
- save_vocabulary
|
| 377 |
+
|
| 378 |
+
## T5TokenizerFast
|
| 379 |
+
|
| 380 |
+
[[autodoc]] T5TokenizerFast
|
| 381 |
+
|
| 382 |
+
<frameworkcontent>
|
| 383 |
+
<pt>
|
| 384 |
+
|
| 385 |
+
## T5Model
|
| 386 |
+
|
| 387 |
+
[[autodoc]] T5Model
|
| 388 |
+
- forward
|
| 389 |
+
|
| 390 |
+
## T5ForConditionalGeneration
|
| 391 |
+
|
| 392 |
+
[[autodoc]] T5ForConditionalGeneration
|
| 393 |
+
- forward
|
| 394 |
+
|
| 395 |
+
## T5EncoderModel
|
| 396 |
+
|
| 397 |
+
[[autodoc]] T5EncoderModel
|
| 398 |
+
- forward
|
| 399 |
+
|
| 400 |
+
## T5ForSequenceClassification
|
| 401 |
+
|
| 402 |
+
[[autodoc]] T5ForSequenceClassification
|
| 403 |
+
- forward
|
| 404 |
+
|
| 405 |
+
## T5ForTokenClassification
|
| 406 |
+
|
| 407 |
+
[[autodoc]] T5ForTokenClassification
|
| 408 |
+
- forward
|
| 409 |
+
|
| 410 |
+
## T5ForQuestionAnswering
|
| 411 |
+
|
| 412 |
+
[[autodoc]] T5ForQuestionAnswering
|
| 413 |
+
- forward
|
| 414 |
+
|
| 415 |
+
</pt>
|
| 416 |
+
<tf>
|
| 417 |
+
|
| 418 |
+
## TFT5Model
|
| 419 |
+
|
| 420 |
+
[[autodoc]] TFT5Model
|
| 421 |
+
- call
|
| 422 |
+
|
| 423 |
+
## TFT5ForConditionalGeneration
|
| 424 |
+
|
| 425 |
+
[[autodoc]] TFT5ForConditionalGeneration
|
| 426 |
+
- call
|
| 427 |
+
|
| 428 |
+
## TFT5EncoderModel
|
| 429 |
+
|
| 430 |
+
[[autodoc]] TFT5EncoderModel
|
| 431 |
+
- call
|
| 432 |
+
|
| 433 |
+
</tf>
|
| 434 |
+
<jax>
|
| 435 |
+
|
| 436 |
+
## FlaxT5Model
|
| 437 |
+
|
| 438 |
+
[[autodoc]] FlaxT5Model
|
| 439 |
+
- __call__
|
| 440 |
+
- encode
|
| 441 |
+
- decode
|
| 442 |
+
|
| 443 |
+
## FlaxT5ForConditionalGeneration
|
| 444 |
+
|
| 445 |
+
[[autodoc]] FlaxT5ForConditionalGeneration
|
| 446 |
+
- __call__
|
| 447 |
+
- encode
|
| 448 |
+
- decode
|
| 449 |
+
|
| 450 |
+
## FlaxT5EncoderModel
|
| 451 |
+
|
| 452 |
+
[[autodoc]] FlaxT5EncoderModel
|
| 453 |
+
- __call__
|
| 454 |
+
|
| 455 |
+
</jax>
|
| 456 |
+
</frameworkcontent>
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/t5v1.1.md
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2021 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# T5v1.1
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
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)
|
| 22 |
+
repository by Colin Raffel et al. It's an improved version of the original T5 model.
|
| 23 |
+
This model was contributed by [patrickvonplaten](https://huggingface.co/patrickvonplaten). The original code can be
|
| 24 |
+
found [here](https://github.com/google-research/text-to-text-transfer-transformer/blob/main/released_checkpoints.md#t511).
|
| 25 |
+
|
| 26 |
+
## Usage tips
|
| 27 |
+
|
| 28 |
+
One can directly plug in the weights of T5v1.1 into a T5 model, like so:
|
| 29 |
+
|
| 30 |
+
```python
|
| 31 |
+
>>> from transformers import T5ForConditionalGeneration
|
| 32 |
+
|
| 33 |
+
>>> model = T5ForConditionalGeneration.from_pretrained("google/t5-v1_1-base")
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
T5 Version 1.1 includes the following improvements compared to the original T5 model:
|
| 37 |
+
|
| 38 |
+
- GEGLU activation in the feed-forward hidden layer, rather than ReLU. See [this paper](https://arxiv.org/abs/2002.05202).
|
| 39 |
+
|
| 40 |
+
- Dropout was turned off in pre-training (quality win). Dropout should be re-enabled during fine-tuning.
|
| 41 |
+
|
| 42 |
+
- Pre-trained on C4 only without mixing in the downstream tasks.
|
| 43 |
+
|
| 44 |
+
- No parameter sharing between the embedding and classifier layer.
|
| 45 |
+
|
| 46 |
+
- "xl" and "xxl" replace "3B" and "11B". The model shapes are a bit different - larger `d_model` and smaller
|
| 47 |
+
`num_heads` and `d_ff`.
|
| 48 |
+
|
| 49 |
+
Note: T5 Version 1.1 was only pre-trained on [C4](https://huggingface.co/datasets/c4) excluding any supervised
|
| 50 |
+
training. Therefore, this model has to be fine-tuned before it is usable on a downstream task, unlike the original T5
|
| 51 |
+
model. Since t5v1.1 was pre-trained unsupervisedly, there's no real advantage to using a task prefix during single-task
|
| 52 |
+
fine-tuning. If you are doing multi-task fine-tuning, you should use a prefix.
|
| 53 |
+
|
| 54 |
+
Google has released the following variants:
|
| 55 |
+
|
| 56 |
+
- [google/t5-v1_1-small](https://huggingface.co/google/t5-v1_1-small)
|
| 57 |
+
|
| 58 |
+
- [google/t5-v1_1-base](https://huggingface.co/google/t5-v1_1-base)
|
| 59 |
+
|
| 60 |
+
- [google/t5-v1_1-large](https://huggingface.co/google/t5-v1_1-large)
|
| 61 |
+
|
| 62 |
+
- [google/t5-v1_1-xl](https://huggingface.co/google/t5-v1_1-xl)
|
| 63 |
+
|
| 64 |
+
- [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl).
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
<Tip>
|
| 68 |
+
|
| 69 |
+
Refer to [T5's documentation page](t5) for all API reference, tips, code examples and notebooks.
|
| 70 |
+
|
| 71 |
+
</Tip>
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/table-transformer.md
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Table Transformer
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
The Table Transformer model was proposed in [PubTables-1M: Towards comprehensive table extraction from unstructured documents](https://arxiv.org/abs/2110.00061) by
|
| 22 |
+
Brandon Smock, Rohith Pesala, Robin Abraham. The authors introduce a new dataset, PubTables-1M, to benchmark progress in table extraction from unstructured documents,
|
| 23 |
+
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.
|
| 24 |
+
|
| 25 |
+
The abstract from the paper is the following:
|
| 26 |
+
|
| 27 |
+
*Recently, significant progress has been made applying machine learning to the problem of table structure inference and extraction from unstructured documents.
|
| 28 |
+
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
|
| 29 |
+
comprehensive dataset for table extraction, called PubTables-1M. PubTables-1M contains nearly one million tables from scientific articles, supports multiple input
|
| 30 |
+
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
|
| 31 |
+
source of ground truth inconsistency observed in prior datasets called oversegmentation, using a novel canonicalization procedure. We demonstrate that these improvements lead to a
|
| 32 |
+
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
|
| 33 |
+
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
|
| 34 |
+
special customization for these tasks.*
|
| 35 |
+
|
| 36 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/table_transformer_architecture.jpeg"
|
| 37 |
+
alt="drawing" width="600"/>
|
| 38 |
+
|
| 39 |
+
<small> Table detection and table structure recognition clarified. Taken from the <a href="https://arxiv.org/abs/2110.00061">original paper</a>. </small>
|
| 40 |
+
|
| 41 |
+
The authors released 2 models, one for [table detection](https://huggingface.co/microsoft/table-transformer-detection) in
|
| 42 |
+
documents, one for [table structure recognition](https://huggingface.co/microsoft/table-transformer-structure-recognition)
|
| 43 |
+
(the task of recognizing the individual rows, columns etc. in a table).
|
| 44 |
+
|
| 45 |
+
This model was contributed by [nielsr](https://huggingface.co/nielsr). The original code can be
|
| 46 |
+
found [here](https://github.com/microsoft/table-transformer).
|
| 47 |
+
|
| 48 |
+
## Resources
|
| 49 |
+
|
| 50 |
+
<PipelineTag pipeline="object-detection"/>
|
| 51 |
+
|
| 52 |
+
- A demo notebook for the Table Transformer can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/Table%20Transformer).
|
| 53 |
+
- 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).
|
| 54 |
+
|
| 55 |
+
## TableTransformerConfig
|
| 56 |
+
|
| 57 |
+
[[autodoc]] TableTransformerConfig
|
| 58 |
+
|
| 59 |
+
## TableTransformerModel
|
| 60 |
+
|
| 61 |
+
[[autodoc]] TableTransformerModel
|
| 62 |
+
- forward
|
| 63 |
+
|
| 64 |
+
## TableTransformerForObjectDetection
|
| 65 |
+
|
| 66 |
+
[[autodoc]] TableTransformerForObjectDetection
|
| 67 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/tapas.md
ADDED
|
@@ -0,0 +1,634 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# TAPAS
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
The TAPAS model was proposed in [TAPAS: Weakly Supervised Table Parsing via Pre-training](https://www.aclweb.org/anthology/2020.acl-main.398)
|
| 22 |
+
by Jonathan Herzig, Paweł Krzysztof Nowak, Thomas Müller, Francesco Piccinno and Julian Martin Eisenschlos. It's a BERT-based model specifically
|
| 23 |
+
designed (and pre-trained) for answering questions about tabular data. Compared to BERT, TAPAS uses relative position embeddings and has 7
|
| 24 |
+
token types that encode tabular structure. TAPAS is pre-trained on the masked language modeling (MLM) objective on a large dataset comprising
|
| 25 |
+
millions of tables from English Wikipedia and corresponding texts.
|
| 26 |
+
|
| 27 |
+
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:
|
| 28 |
+
- [SQA](https://www.microsoft.com/en-us/download/details.aspx?id=54253) (Sequential Question Answering by Microsoft)
|
| 29 |
+
- [WTQ](https://github.com/ppasupat/WikiTableQuestions) (Wiki Table Questions by Stanford University)
|
| 30 |
+
- [WikiSQL](https://github.com/salesforce/WikiSQL) (by Salesforce).
|
| 31 |
+
|
| 32 |
+
It achieves state-of-the-art on both SQA and WTQ, while having comparable performance to SOTA on WikiSQL, with a much simpler architecture.
|
| 33 |
+
|
| 34 |
+
The abstract from the paper is the following:
|
| 35 |
+
|
| 36 |
+
*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.*
|
| 37 |
+
|
| 38 |
+
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.
|
| 39 |
+
|
| 40 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/tapas_architecture.png"
|
| 41 |
+
alt="drawing" width="600"/>
|
| 42 |
+
|
| 43 |
+
<small> TAPAS architecture. Taken from the <a href="https://ai.googleblog.com/2020/04/using-neural-networks-to-find-answers.html">original blog post</a>.</small>
|
| 44 |
+
|
| 45 |
+
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).
|
| 46 |
+
|
| 47 |
+
## Usage tips
|
| 48 |
+
|
| 49 |
+
- 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.
|
| 50 |
+
- 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).
|
| 51 |
+
- 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.
|
| 52 |
+
- 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.
|
| 53 |
+
|
| 54 |
+
## Usage: fine-tuning
|
| 55 |
+
|
| 56 |
+
Here we explain how you can fine-tune [`TapasForQuestionAnswering`] on your own dataset.
|
| 57 |
+
|
| 58 |
+
**STEP 1: Choose one of the 3 ways in which you can use TAPAS - or experiment**
|
| 59 |
+
|
| 60 |
+
Basically, there are 3 different ways in which one can fine-tune [`TapasForQuestionAnswering`], corresponding to the different datasets on which Tapas was fine-tuned:
|
| 61 |
+
|
| 62 |
+
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).
|
| 63 |
+
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.
|
| 64 |
+
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.
|
| 65 |
+
|
| 66 |
+
To summarize:
|
| 67 |
+
|
| 68 |
+
| **Task** | **Example dataset** | **Description** |
|
| 69 |
+
|-------------------------------------|---------------------|---------------------------------------------------------------------------------------------------------|
|
| 70 |
+
| Conversational | SQA | Conversational, only cell selection questions |
|
| 71 |
+
| Weak supervision for aggregation | WTQ | Questions might involve aggregation, and the model must learn this given only the answer as supervision |
|
| 72 |
+
| Strong supervision for aggregation | WikiSQL-supervised | Questions might involve aggregation, and the model must learn this given the gold aggregation operator |
|
| 73 |
+
|
| 74 |
+
<frameworkcontent>
|
| 75 |
+
<pt>
|
| 76 |
+
Initializing a model with a pre-trained base and randomly initialized classification heads from the hub can be done as shown below.
|
| 77 |
+
|
| 78 |
+
```py
|
| 79 |
+
>>> from transformers import TapasConfig, TapasForQuestionAnswering
|
| 80 |
+
|
| 81 |
+
>>> # for example, the base sized model with default SQA configuration
|
| 82 |
+
>>> model = TapasForQuestionAnswering.from_pretrained("google/tapas-base")
|
| 83 |
+
|
| 84 |
+
>>> # or, the base sized model with WTQ configuration
|
| 85 |
+
>>> config = TapasConfig.from_pretrained("google/tapas-base-finetuned-wtq")
|
| 86 |
+
>>> model = TapasForQuestionAnswering.from_pretrained("google/tapas-base", config=config)
|
| 87 |
+
|
| 88 |
+
>>> # or, the base sized model with WikiSQL configuration
|
| 89 |
+
>>> config = TapasConfig("google-base-finetuned-wikisql-supervised")
|
| 90 |
+
>>> model = TapasForQuestionAnswering.from_pretrained("google/tapas-base", config=config)
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
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:
|
| 94 |
+
|
| 95 |
+
```py
|
| 96 |
+
>>> from transformers import TapasConfig, TapasForQuestionAnswering
|
| 97 |
+
|
| 98 |
+
>>> # you can initialize the classification heads any way you want (see docs of TapasConfig)
|
| 99 |
+
>>> config = TapasConfig(num_aggregation_labels=3, average_logits_per_cell=True)
|
| 100 |
+
>>> # initializing the pre-trained base sized model with our custom classification heads
|
| 101 |
+
>>> model = TapasForQuestionAnswering.from_pretrained("google/tapas-base", config=config)
|
| 102 |
+
```
|
| 103 |
+
</pt>
|
| 104 |
+
<tf>
|
| 105 |
+
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:
|
| 106 |
+
|
| 107 |
+
```py
|
| 108 |
+
>>> from transformers import TapasConfig, TFTapasForQuestionAnswering
|
| 109 |
+
|
| 110 |
+
>>> # for example, the base sized model with default SQA configuration
|
| 111 |
+
>>> model = TFTapasForQuestionAnswering.from_pretrained("google/tapas-base")
|
| 112 |
+
|
| 113 |
+
>>> # or, the base sized model with WTQ configuration
|
| 114 |
+
>>> config = TapasConfig.from_pretrained("google/tapas-base-finetuned-wtq")
|
| 115 |
+
>>> model = TFTapasForQuestionAnswering.from_pretrained("google/tapas-base", config=config)
|
| 116 |
+
|
| 117 |
+
>>> # or, the base sized model with WikiSQL configuration
|
| 118 |
+
>>> config = TapasConfig("google-base-finetuned-wikisql-supervised")
|
| 119 |
+
>>> model = TFTapasForQuestionAnswering.from_pretrained("google/tapas-base", config=config)
|
| 120 |
+
```
|
| 121 |
+
|
| 122 |
+
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:
|
| 123 |
+
|
| 124 |
+
```py
|
| 125 |
+
>>> from transformers import TapasConfig, TFTapasForQuestionAnswering
|
| 126 |
+
|
| 127 |
+
>>> # you can initialize the classification heads any way you want (see docs of TapasConfig)
|
| 128 |
+
>>> config = TapasConfig(num_aggregation_labels=3, average_logits_per_cell=True)
|
| 129 |
+
>>> # initializing the pre-trained base sized model with our custom classification heads
|
| 130 |
+
>>> model = TFTapasForQuestionAnswering.from_pretrained("google/tapas-base", config=config)
|
| 131 |
+
```
|
| 132 |
+
</tf>
|
| 133 |
+
</frameworkcontent>
|
| 134 |
+
|
| 135 |
+
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.
|
| 136 |
+
|
| 137 |
+
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).
|
| 138 |
+
|
| 139 |
+
**STEP 2: Prepare your data in the SQA format**
|
| 140 |
+
|
| 141 |
+
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:
|
| 142 |
+
|
| 143 |
+
- `id`: optional, id of the table-question pair, for bookkeeping purposes.
|
| 144 |
+
- `annotator`: optional, id of the person who annotated the table-question pair, for bookkeeping purposes.
|
| 145 |
+
- `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.
|
| 146 |
+
- `question`: string
|
| 147 |
+
- `table_file`: string, name of a csv file containing the tabular data
|
| 148 |
+
- `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)
|
| 149 |
+
- `answer_text`: list of one or more strings (each string being a cell value that is part of the answer)
|
| 150 |
+
- `aggregation_label`: index of the aggregation operator. Only required in case of strong supervision for aggregation (the WikiSQL-supervised case)
|
| 151 |
+
- `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)
|
| 152 |
+
|
| 153 |
+
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.
|
| 154 |
+
|
| 155 |
+
**STEP 3: Convert your data into tensors using TapasTokenizer**
|
| 156 |
+
|
| 157 |
+
<frameworkcontent>
|
| 158 |
+
<pt>
|
| 159 |
+
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
|
| 160 |
+
inputs to be fine-tuned:
|
| 161 |
+
|
| 162 |
+
| **Task** | **Required inputs** |
|
| 163 |
+
|------------------------------------|---------------------------------------------------------------------------------------------------------------------|
|
| 164 |
+
| Conversational | `input_ids`, `attention_mask`, `token_type_ids`, `labels` |
|
| 165 |
+
| Weak supervision for aggregation | `input_ids`, `attention_mask`, `token_type_ids`, `labels`, `numeric_values`, `numeric_values_scale`, `float_answer` |
|
| 166 |
+
| Strong supervision for aggregation | `input ids`, `attention mask`, `token type ids`, `labels`, `aggregation_labels` |
|
| 167 |
+
|
| 168 |
+
[`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:
|
| 169 |
+
|
| 170 |
+
```py
|
| 171 |
+
>>> from transformers import TapasTokenizer
|
| 172 |
+
>>> import pandas as pd
|
| 173 |
+
|
| 174 |
+
>>> model_name = "google/tapas-base"
|
| 175 |
+
>>> tokenizer = TapasTokenizer.from_pretrained(model_name)
|
| 176 |
+
|
| 177 |
+
>>> data = {"Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"], "Number of movies": ["87", "53", "69"]}
|
| 178 |
+
>>> queries = [
|
| 179 |
+
... "What is the name of the first actor?",
|
| 180 |
+
... "How many movies has George Clooney played in?",
|
| 181 |
+
... "What is the total number of movies?",
|
| 182 |
+
... ]
|
| 183 |
+
>>> answer_coordinates = [[(0, 0)], [(2, 1)], [(0, 1), (1, 1), (2, 1)]]
|
| 184 |
+
>>> answer_text = [["Brad Pitt"], ["69"], ["209"]]
|
| 185 |
+
>>> table = pd.DataFrame.from_dict(data)
|
| 186 |
+
>>> inputs = tokenizer(
|
| 187 |
+
... table=table,
|
| 188 |
+
... queries=queries,
|
| 189 |
+
... answer_coordinates=answer_coordinates,
|
| 190 |
+
... answer_text=answer_text,
|
| 191 |
+
... padding="max_length",
|
| 192 |
+
... return_tensors="pt",
|
| 193 |
+
... )
|
| 194 |
+
>>> inputs
|
| 195 |
+
{'input_ids': tensor([[ ... ]]), 'attention_mask': tensor([[...]]), 'token_type_ids': tensor([[[...]]]),
|
| 196 |
+
'numeric_values': tensor([[ ... ]]), 'numeric_values_scale: tensor([[ ... ]]), labels: tensor([[ ... ]])}
|
| 197 |
+
```
|
| 198 |
+
|
| 199 |
+
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.
|
| 200 |
+
Of course, this only shows how to encode a single training example. It is advised to create a dataloader to iterate over batches:
|
| 201 |
+
|
| 202 |
+
```py
|
| 203 |
+
>>> import torch
|
| 204 |
+
>>> import pandas as pd
|
| 205 |
+
|
| 206 |
+
>>> tsv_path = "your_path_to_the_tsv_file"
|
| 207 |
+
>>> table_csv_path = "your_path_to_a_directory_containing_all_csv_files"
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
>>> class TableDataset(torch.utils.data.Dataset):
|
| 211 |
+
... def __init__(self, data, tokenizer):
|
| 212 |
+
... self.data = data
|
| 213 |
+
... self.tokenizer = tokenizer
|
| 214 |
+
|
| 215 |
+
... def __getitem__(self, idx):
|
| 216 |
+
... item = data.iloc[idx]
|
| 217 |
+
... table = pd.read_csv(table_csv_path + item.table_file).astype(
|
| 218 |
+
... str
|
| 219 |
+
... ) # be sure to make your table data text only
|
| 220 |
+
... encoding = self.tokenizer(
|
| 221 |
+
... table=table,
|
| 222 |
+
... queries=item.question,
|
| 223 |
+
... answer_coordinates=item.answer_coordinates,
|
| 224 |
+
... answer_text=item.answer_text,
|
| 225 |
+
... truncation=True,
|
| 226 |
+
... padding="max_length",
|
| 227 |
+
... return_tensors="pt",
|
| 228 |
+
... )
|
| 229 |
+
... # remove the batch dimension which the tokenizer adds by default
|
| 230 |
+
... encoding = {key: val.squeeze(0) for key, val in encoding.items()}
|
| 231 |
+
... # add the float_answer which is also required (weak supervision for aggregation case)
|
| 232 |
+
... encoding["float_answer"] = torch.tensor(item.float_answer)
|
| 233 |
+
... return encoding
|
| 234 |
+
|
| 235 |
+
... def __len__(self):
|
| 236 |
+
... return len(self.data)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
>>> data = pd.read_csv(tsv_path, sep="\t")
|
| 240 |
+
>>> train_dataset = TableDataset(data, tokenizer)
|
| 241 |
+
>>> train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=32)
|
| 242 |
+
```
|
| 243 |
+
</pt>
|
| 244 |
+
<tf>
|
| 245 |
+
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
|
| 246 |
+
inputs to be fine-tuned:
|
| 247 |
+
|
| 248 |
+
| **Task** | **Required inputs** |
|
| 249 |
+
|------------------------------------|---------------------------------------------------------------------------------------------------------------------|
|
| 250 |
+
| Conversational | `input_ids`, `attention_mask`, `token_type_ids`, `labels` |
|
| 251 |
+
| Weak supervision for aggregation | `input_ids`, `attention_mask`, `token_type_ids`, `labels`, `numeric_values`, `numeric_values_scale`, `float_answer` |
|
| 252 |
+
| Strong supervision for aggregation | `input ids`, `attention mask`, `token type ids`, `labels`, `aggregation_labels` |
|
| 253 |
+
|
| 254 |
+
[`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:
|
| 255 |
+
|
| 256 |
+
```py
|
| 257 |
+
>>> from transformers import TapasTokenizer
|
| 258 |
+
>>> import pandas as pd
|
| 259 |
+
|
| 260 |
+
>>> model_name = "google/tapas-base"
|
| 261 |
+
>>> tokenizer = TapasTokenizer.from_pretrained(model_name)
|
| 262 |
+
|
| 263 |
+
>>> data = {"Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"], "Number of movies": ["87", "53", "69"]}
|
| 264 |
+
>>> queries = [
|
| 265 |
+
... "What is the name of the first actor?",
|
| 266 |
+
... "How many movies has George Clooney played in?",
|
| 267 |
+
... "What is the total number of movies?",
|
| 268 |
+
... ]
|
| 269 |
+
>>> answer_coordinates = [[(0, 0)], [(2, 1)], [(0, 1), (1, 1), (2, 1)]]
|
| 270 |
+
>>> answer_text = [["Brad Pitt"], ["69"], ["209"]]
|
| 271 |
+
>>> table = pd.DataFrame.from_dict(data)
|
| 272 |
+
>>> inputs = tokenizer(
|
| 273 |
+
... table=table,
|
| 274 |
+
... queries=queries,
|
| 275 |
+
... answer_coordinates=answer_coordinates,
|
| 276 |
+
... answer_text=answer_text,
|
| 277 |
+
... padding="max_length",
|
| 278 |
+
... return_tensors="tf",
|
| 279 |
+
... )
|
| 280 |
+
>>> inputs
|
| 281 |
+
{'input_ids': tensor([[ ... ]]), 'attention_mask': tensor([[...]]), 'token_type_ids': tensor([[[...]]]),
|
| 282 |
+
'numeric_values': tensor([[ ... ]]), 'numeric_values_scale: tensor([[ ... ]]), labels: tensor([[ ... ]])}
|
| 283 |
+
```
|
| 284 |
+
|
| 285 |
+
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.
|
| 286 |
+
Of course, this only shows how to encode a single training example. It is advised to create a dataloader to iterate over batches:
|
| 287 |
+
|
| 288 |
+
```py
|
| 289 |
+
>>> import tensorflow as tf
|
| 290 |
+
>>> import pandas as pd
|
| 291 |
+
|
| 292 |
+
>>> tsv_path = "your_path_to_the_tsv_file"
|
| 293 |
+
>>> table_csv_path = "your_path_to_a_directory_containing_all_csv_files"
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
>>> class TableDataset:
|
| 297 |
+
... def __init__(self, data, tokenizer):
|
| 298 |
+
... self.data = data
|
| 299 |
+
... self.tokenizer = tokenizer
|
| 300 |
+
|
| 301 |
+
... def __iter__(self):
|
| 302 |
+
... for idx in range(self.__len__()):
|
| 303 |
+
... item = self.data.iloc[idx]
|
| 304 |
+
... table = pd.read_csv(table_csv_path + item.table_file).astype(
|
| 305 |
+
... str
|
| 306 |
+
... ) # be sure to make your table data text only
|
| 307 |
+
... encoding = self.tokenizer(
|
| 308 |
+
... table=table,
|
| 309 |
+
... queries=item.question,
|
| 310 |
+
... answer_coordinates=item.answer_coordinates,
|
| 311 |
+
... answer_text=item.answer_text,
|
| 312 |
+
... truncation=True,
|
| 313 |
+
... padding="max_length",
|
| 314 |
+
... return_tensors="tf",
|
| 315 |
+
... )
|
| 316 |
+
... # remove the batch dimension which the tokenizer adds by default
|
| 317 |
+
... encoding = {key: tf.squeeze(val, 0) for key, val in encoding.items()}
|
| 318 |
+
... # add the float_answer which is also required (weak supervision for aggregation case)
|
| 319 |
+
... encoding["float_answer"] = tf.convert_to_tensor(item.float_answer, dtype=tf.float32)
|
| 320 |
+
... yield encoding["input_ids"], encoding["attention_mask"], encoding["numeric_values"], encoding[
|
| 321 |
+
... "numeric_values_scale"
|
| 322 |
+
... ], encoding["token_type_ids"], encoding["labels"], encoding["float_answer"]
|
| 323 |
+
|
| 324 |
+
... def __len__(self):
|
| 325 |
+
... return len(self.data)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
>>> data = pd.read_csv(tsv_path, sep="\t")
|
| 329 |
+
>>> train_dataset = TableDataset(data, tokenizer)
|
| 330 |
+
>>> output_signature = (
|
| 331 |
+
... tf.TensorSpec(shape=(512,), dtype=tf.int32),
|
| 332 |
+
... tf.TensorSpec(shape=(512,), dtype=tf.int32),
|
| 333 |
+
... tf.TensorSpec(shape=(512,), dtype=tf.float32),
|
| 334 |
+
... tf.TensorSpec(shape=(512,), dtype=tf.float32),
|
| 335 |
+
... tf.TensorSpec(shape=(512, 7), dtype=tf.int32),
|
| 336 |
+
... tf.TensorSpec(shape=(512,), dtype=tf.int32),
|
| 337 |
+
... tf.TensorSpec(shape=(512,), dtype=tf.float32),
|
| 338 |
+
... )
|
| 339 |
+
>>> train_dataloader = tf.data.Dataset.from_generator(train_dataset, output_signature=output_signature).batch(32)
|
| 340 |
+
```
|
| 341 |
+
</tf>
|
| 342 |
+
</frameworkcontent>
|
| 343 |
+
|
| 344 |
+
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`
|
| 345 |
+
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.
|
| 346 |
+
|
| 347 |
+
**STEP 4: Train (fine-tune) the model
|
| 348 |
+
|
| 349 |
+
<frameworkcontent>
|
| 350 |
+
<pt>
|
| 351 |
+
You can then fine-tune [`TapasForQuestionAnswering`] as follows (shown here for the weak supervision for aggregation case):
|
| 352 |
+
|
| 353 |
+
```py
|
| 354 |
+
>>> from transformers import TapasConfig, TapasForQuestionAnswering, AdamW
|
| 355 |
+
|
| 356 |
+
>>> # this is the default WTQ configuration
|
| 357 |
+
>>> config = TapasConfig(
|
| 358 |
+
... num_aggregation_labels=4,
|
| 359 |
+
... use_answer_as_supervision=True,
|
| 360 |
+
... answer_loss_cutoff=0.664694,
|
| 361 |
+
... cell_selection_preference=0.207951,
|
| 362 |
+
... huber_loss_delta=0.121194,
|
| 363 |
+
... init_cell_selection_weights_to_zero=True,
|
| 364 |
+
... select_one_column=True,
|
| 365 |
+
... allow_empty_column_selection=False,
|
| 366 |
+
... temperature=0.0352513,
|
| 367 |
+
... )
|
| 368 |
+
>>> model = TapasForQuestionAnswering.from_pretrained("google/tapas-base", config=config)
|
| 369 |
+
|
| 370 |
+
>>> optimizer = AdamW(model.parameters(), lr=5e-5)
|
| 371 |
+
|
| 372 |
+
>>> model.train()
|
| 373 |
+
>>> for epoch in range(2): # loop over the dataset multiple times
|
| 374 |
+
... for batch in train_dataloader:
|
| 375 |
+
... # get the inputs;
|
| 376 |
+
... input_ids = batch["input_ids"]
|
| 377 |
+
... attention_mask = batch["attention_mask"]
|
| 378 |
+
... token_type_ids = batch["token_type_ids"]
|
| 379 |
+
... labels = batch["labels"]
|
| 380 |
+
... numeric_values = batch["numeric_values"]
|
| 381 |
+
... numeric_values_scale = batch["numeric_values_scale"]
|
| 382 |
+
... float_answer = batch["float_answer"]
|
| 383 |
+
|
| 384 |
+
... # zero the parameter gradients
|
| 385 |
+
... optimizer.zero_grad()
|
| 386 |
+
|
| 387 |
+
... # forward + backward + optimize
|
| 388 |
+
... outputs = model(
|
| 389 |
+
... input_ids=input_ids,
|
| 390 |
+
... attention_mask=attention_mask,
|
| 391 |
+
... token_type_ids=token_type_ids,
|
| 392 |
+
... labels=labels,
|
| 393 |
+
... numeric_values=numeric_values,
|
| 394 |
+
... numeric_values_scale=numeric_values_scale,
|
| 395 |
+
... float_answer=float_answer,
|
| 396 |
+
... )
|
| 397 |
+
... loss = outputs.loss
|
| 398 |
+
... loss.backward()
|
| 399 |
+
... optimizer.step()
|
| 400 |
+
```
|
| 401 |
+
</pt>
|
| 402 |
+
<tf>
|
| 403 |
+
You can then fine-tune [`TFTapasForQuestionAnswering`] as follows (shown here for the weak supervision for aggregation case):
|
| 404 |
+
|
| 405 |
+
```py
|
| 406 |
+
>>> import tensorflow as tf
|
| 407 |
+
>>> from transformers import TapasConfig, TFTapasForQuestionAnswering
|
| 408 |
+
|
| 409 |
+
>>> # this is the default WTQ configuration
|
| 410 |
+
>>> config = TapasConfig(
|
| 411 |
+
... num_aggregation_labels=4,
|
| 412 |
+
... use_answer_as_supervision=True,
|
| 413 |
+
... answer_loss_cutoff=0.664694,
|
| 414 |
+
... cell_selection_preference=0.207951,
|
| 415 |
+
... huber_loss_delta=0.121194,
|
| 416 |
+
... init_cell_selection_weights_to_zero=True,
|
| 417 |
+
... select_one_column=True,
|
| 418 |
+
... allow_empty_column_selection=False,
|
| 419 |
+
... temperature=0.0352513,
|
| 420 |
+
... )
|
| 421 |
+
>>> model = TFTapasForQuestionAnswering.from_pretrained("google/tapas-base", config=config)
|
| 422 |
+
|
| 423 |
+
>>> optimizer = tf.keras.optimizers.Adam(learning_rate=5e-5)
|
| 424 |
+
|
| 425 |
+
>>> for epoch in range(2): # loop over the dataset multiple times
|
| 426 |
+
... for batch in train_dataloader:
|
| 427 |
+
... # get the inputs;
|
| 428 |
+
... input_ids = batch[0]
|
| 429 |
+
... attention_mask = batch[1]
|
| 430 |
+
... token_type_ids = batch[4]
|
| 431 |
+
... labels = batch[-1]
|
| 432 |
+
... numeric_values = batch[2]
|
| 433 |
+
... numeric_values_scale = batch[3]
|
| 434 |
+
... float_answer = batch[6]
|
| 435 |
+
|
| 436 |
+
... # forward + backward + optimize
|
| 437 |
+
... with tf.GradientTape() as tape:
|
| 438 |
+
... outputs = model(
|
| 439 |
+
... input_ids=input_ids,
|
| 440 |
+
... attention_mask=attention_mask,
|
| 441 |
+
... token_type_ids=token_type_ids,
|
| 442 |
+
... labels=labels,
|
| 443 |
+
... numeric_values=numeric_values,
|
| 444 |
+
... numeric_values_scale=numeric_values_scale,
|
| 445 |
+
... float_answer=float_answer,
|
| 446 |
+
... )
|
| 447 |
+
... grads = tape.gradient(outputs.loss, model.trainable_weights)
|
| 448 |
+
... optimizer.apply_gradients(zip(grads, model.trainable_weights))
|
| 449 |
+
```
|
| 450 |
+
</tf>
|
| 451 |
+
</frameworkcontent>
|
| 452 |
+
|
| 453 |
+
## Usage: inference
|
| 454 |
+
|
| 455 |
+
<frameworkcontent>
|
| 456 |
+
<pt>
|
| 457 |
+
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.
|
| 458 |
+
|
| 459 |
+
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:
|
| 460 |
+
|
| 461 |
+
```py
|
| 462 |
+
>>> from transformers import TapasTokenizer, TapasForQuestionAnswering
|
| 463 |
+
>>> import pandas as pd
|
| 464 |
+
|
| 465 |
+
>>> model_name = "google/tapas-base-finetuned-wtq"
|
| 466 |
+
>>> model = TapasForQuestionAnswering.from_pretrained(model_name)
|
| 467 |
+
>>> tokenizer = TapasTokenizer.from_pretrained(model_name)
|
| 468 |
+
|
| 469 |
+
>>> data = {"Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"], "Number of movies": ["87", "53", "69"]}
|
| 470 |
+
>>> queries = [
|
| 471 |
+
... "What is the name of the first actor?",
|
| 472 |
+
... "How many movies has George Clooney played in?",
|
| 473 |
+
... "What is the total number of movies?",
|
| 474 |
+
... ]
|
| 475 |
+
>>> table = pd.DataFrame.from_dict(data)
|
| 476 |
+
>>> inputs = tokenizer(table=table, queries=queries, padding="max_length", return_tensors="pt")
|
| 477 |
+
>>> outputs = model(**inputs)
|
| 478 |
+
>>> predicted_answer_coordinates, predicted_aggregation_indices = tokenizer.convert_logits_to_predictions(
|
| 479 |
+
... inputs, outputs.logits.detach(), outputs.logits_aggregation.detach()
|
| 480 |
+
... )
|
| 481 |
+
|
| 482 |
+
>>> # let's print out the results:
|
| 483 |
+
>>> id2aggregation = {0: "NONE", 1: "SUM", 2: "AVERAGE", 3: "COUNT"}
|
| 484 |
+
>>> aggregation_predictions_string = [id2aggregation[x] for x in predicted_aggregation_indices]
|
| 485 |
+
|
| 486 |
+
>>> answers = []
|
| 487 |
+
>>> for coordinates in predicted_answer_coordinates:
|
| 488 |
+
... if len(coordinates) == 1:
|
| 489 |
+
... # only a single cell:
|
| 490 |
+
... answers.append(table.iat[coordinates[0]])
|
| 491 |
+
... else:
|
| 492 |
+
... # multiple cells
|
| 493 |
+
... cell_values = []
|
| 494 |
+
... for coordinate in coordinates:
|
| 495 |
+
... cell_values.append(table.iat[coordinate])
|
| 496 |
+
... answers.append(", ".join(cell_values))
|
| 497 |
+
|
| 498 |
+
>>> display(table)
|
| 499 |
+
>>> print("")
|
| 500 |
+
>>> for query, answer, predicted_agg in zip(queries, answers, aggregation_predictions_string):
|
| 501 |
+
... print(query)
|
| 502 |
+
... if predicted_agg == "NONE":
|
| 503 |
+
... print("Predicted answer: " + answer)
|
| 504 |
+
... else:
|
| 505 |
+
... print("Predicted answer: " + predicted_agg + " > " + answer)
|
| 506 |
+
What is the name of the first actor?
|
| 507 |
+
Predicted answer: Brad Pitt
|
| 508 |
+
How many movies has George Clooney played in?
|
| 509 |
+
Predicted answer: COUNT > 69
|
| 510 |
+
What is the total number of movies?
|
| 511 |
+
Predicted answer: SUM > 87, 53, 69
|
| 512 |
+
```
|
| 513 |
+
</pt>
|
| 514 |
+
<tf>
|
| 515 |
+
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.
|
| 516 |
+
|
| 517 |
+
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:
|
| 518 |
+
|
| 519 |
+
```py
|
| 520 |
+
>>> from transformers import TapasTokenizer, TFTapasForQuestionAnswering
|
| 521 |
+
>>> import pandas as pd
|
| 522 |
+
|
| 523 |
+
>>> model_name = "google/tapas-base-finetuned-wtq"
|
| 524 |
+
>>> model = TFTapasForQuestionAnswering.from_pretrained(model_name)
|
| 525 |
+
>>> tokenizer = TapasTokenizer.from_pretrained(model_name)
|
| 526 |
+
|
| 527 |
+
>>> data = {"Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"], "Number of movies": ["87", "53", "69"]}
|
| 528 |
+
>>> queries = [
|
| 529 |
+
... "What is the name of the first actor?",
|
| 530 |
+
... "How many movies has George Clooney played in?",
|
| 531 |
+
... "What is the total number of movies?",
|
| 532 |
+
... ]
|
| 533 |
+
>>> table = pd.DataFrame.from_dict(data)
|
| 534 |
+
>>> inputs = tokenizer(table=table, queries=queries, padding="max_length", return_tensors="tf")
|
| 535 |
+
>>> outputs = model(**inputs)
|
| 536 |
+
>>> predicted_answer_coordinates, predicted_aggregation_indices = tokenizer.convert_logits_to_predictions(
|
| 537 |
+
... inputs, outputs.logits, outputs.logits_aggregation
|
| 538 |
+
... )
|
| 539 |
+
|
| 540 |
+
>>> # let's print out the results:
|
| 541 |
+
>>> id2aggregation = {0: "NONE", 1: "SUM", 2: "AVERAGE", 3: "COUNT"}
|
| 542 |
+
>>> aggregation_predictions_string = [id2aggregation[x] for x in predicted_aggregation_indices]
|
| 543 |
+
|
| 544 |
+
>>> answers = []
|
| 545 |
+
>>> for coordinates in predicted_answer_coordinates:
|
| 546 |
+
... if len(coordinates) == 1:
|
| 547 |
+
... # only a single cell:
|
| 548 |
+
... answers.append(table.iat[coordinates[0]])
|
| 549 |
+
... else:
|
| 550 |
+
... # multiple cells
|
| 551 |
+
... cell_values = []
|
| 552 |
+
... for coordinate in coordinates:
|
| 553 |
+
... cell_values.append(table.iat[coordinate])
|
| 554 |
+
... answers.append(", ".join(cell_values))
|
| 555 |
+
|
| 556 |
+
>>> display(table)
|
| 557 |
+
>>> print("")
|
| 558 |
+
>>> for query, answer, predicted_agg in zip(queries, answers, aggregation_predictions_string):
|
| 559 |
+
... print(query)
|
| 560 |
+
... if predicted_agg == "NONE":
|
| 561 |
+
... print("Predicted answer: " + answer)
|
| 562 |
+
... else:
|
| 563 |
+
... print("Predicted answer: " + predicted_agg + " > " + answer)
|
| 564 |
+
What is the name of the first actor?
|
| 565 |
+
Predicted answer: Brad Pitt
|
| 566 |
+
How many movies has George Clooney played in?
|
| 567 |
+
Predicted answer: COUNT > 69
|
| 568 |
+
What is the total number of movies?
|
| 569 |
+
Predicted answer: SUM > 87, 53, 69
|
| 570 |
+
```
|
| 571 |
+
</tf>
|
| 572 |
+
</frameworkcontent>
|
| 573 |
+
|
| 574 |
+
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).
|
| 575 |
+
|
| 576 |
+
## Resources
|
| 577 |
+
|
| 578 |
+
- [Text classification task guide](../tasks/sequence_classification)
|
| 579 |
+
- [Masked language modeling task guide](../tasks/masked_language_modeling)
|
| 580 |
+
|
| 581 |
+
## TAPAS specific outputs
|
| 582 |
+
[[autodoc]] models.tapas.modeling_tapas.TableQuestionAnsweringOutput
|
| 583 |
+
|
| 584 |
+
## TapasConfig
|
| 585 |
+
[[autodoc]] TapasConfig
|
| 586 |
+
|
| 587 |
+
## TapasTokenizer
|
| 588 |
+
[[autodoc]] TapasTokenizer
|
| 589 |
+
- __call__
|
| 590 |
+
- convert_logits_to_predictions
|
| 591 |
+
- save_vocabulary
|
| 592 |
+
|
| 593 |
+
<frameworkcontent>
|
| 594 |
+
<pt>
|
| 595 |
+
|
| 596 |
+
## TapasModel
|
| 597 |
+
[[autodoc]] TapasModel
|
| 598 |
+
- forward
|
| 599 |
+
|
| 600 |
+
## TapasForMaskedLM
|
| 601 |
+
[[autodoc]] TapasForMaskedLM
|
| 602 |
+
- forward
|
| 603 |
+
|
| 604 |
+
## TapasForSequenceClassification
|
| 605 |
+
[[autodoc]] TapasForSequenceClassification
|
| 606 |
+
- forward
|
| 607 |
+
|
| 608 |
+
## TapasForQuestionAnswering
|
| 609 |
+
[[autodoc]] TapasForQuestionAnswering
|
| 610 |
+
- forward
|
| 611 |
+
|
| 612 |
+
</pt>
|
| 613 |
+
<tf>
|
| 614 |
+
|
| 615 |
+
## TFTapasModel
|
| 616 |
+
[[autodoc]] TFTapasModel
|
| 617 |
+
- call
|
| 618 |
+
|
| 619 |
+
## TFTapasForMaskedLM
|
| 620 |
+
[[autodoc]] TFTapasForMaskedLM
|
| 621 |
+
- call
|
| 622 |
+
|
| 623 |
+
## TFTapasForSequenceClassification
|
| 624 |
+
[[autodoc]] TFTapasForSequenceClassification
|
| 625 |
+
- call
|
| 626 |
+
|
| 627 |
+
## TFTapasForQuestionAnswering
|
| 628 |
+
[[autodoc]] TFTapasForQuestionAnswering
|
| 629 |
+
- call
|
| 630 |
+
|
| 631 |
+
</tf>
|
| 632 |
+
</frameworkcontent>
|
| 633 |
+
|
| 634 |
+
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/tapex.md
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# TAPEX
|
| 18 |
+
|
| 19 |
+
<Tip warning={true}>
|
| 20 |
+
|
| 21 |
+
This model is in maintenance mode only, we don't accept any new PRs changing its code.
|
| 22 |
+
|
| 23 |
+
If you run into any issues running this model, please reinstall the last version that supported this model: v4.30.0.
|
| 24 |
+
You can do so by running the following command: `pip install -U transformers==4.30.0`.
|
| 25 |
+
|
| 26 |
+
</Tip>
|
| 27 |
+
|
| 28 |
+
## Overview
|
| 29 |
+
|
| 30 |
+
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,
|
| 31 |
+
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
|
| 32 |
+
which it can be fine-tuned to answer natural language questions related to tabular data, as well as performing table fact checking.
|
| 33 |
+
|
| 34 |
+
TAPEX has been fine-tuned on several datasets:
|
| 35 |
+
- [SQA](https://www.microsoft.com/en-us/download/details.aspx?id=54253) (Sequential Question Answering by Microsoft)
|
| 36 |
+
- [WTQ](https://github.com/ppasupat/WikiTableQuestions) (Wiki Table Questions by Stanford University)
|
| 37 |
+
- [WikiSQL](https://github.com/salesforce/WikiSQL) (by Salesforce)
|
| 38 |
+
- [TabFact](https://tabfact.github.io/) (by USCB NLP Lab).
|
| 39 |
+
|
| 40 |
+
The abstract from the paper is the following:
|
| 41 |
+
|
| 42 |
+
*Recent progress in language model pre-training has achieved a great success via leveraging large-scale unstructured textual data. However, it is
|
| 43 |
+
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
|
| 44 |
+
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
|
| 45 |
+
synthesizing executable SQL queries and their execution outputs. TAPEX addresses the data scarcity challenge via guiding the language model to mimic a SQL
|
| 46 |
+
executor on the diverse, large-scale and high-quality synthetic corpus. We evaluate TAPEX on four benchmark datasets. Experimental results demonstrate that
|
| 47 |
+
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
|
| 48 |
+
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
|
| 49 |
+
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
|
| 50 |
+
and to achieve new state-of-the-art results on various downstream tasks.*
|
| 51 |
+
|
| 52 |
+
## Usage tips
|
| 53 |
+
|
| 54 |
+
- TAPEX is a generative (seq2seq) model. One can directly plug in the weights of TAPEX into a BART model.
|
| 55 |
+
- TAPEX has checkpoints on the hub that are either pre-trained only, or fine-tuned on WTQ, SQA, WikiSQL and TabFact.
|
| 56 |
+
- Sentences + tables are presented to the model as `sentence + " " + linearized table`. The linearized table has the following format:
|
| 57 |
+
`col: col1 | col2 | col 3 row 1 : val1 | val2 | val3 row 2 : ...`.
|
| 58 |
+
- 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,
|
| 59 |
+
and it will automatically create the `input_ids` and `attention_mask` (as shown in the usage examples below).
|
| 60 |
+
|
| 61 |
+
### Usage: inference
|
| 62 |
+
|
| 63 |
+
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.
|
| 64 |
+
We use the [Auto API](auto), which will automatically instantiate the appropriate tokenizer ([`TapexTokenizer`]) and model ([`BartForConditionalGeneration`]) for us,
|
| 65 |
+
based on the configuration file of the checkpoint on the hub.
|
| 66 |
+
|
| 67 |
+
```python
|
| 68 |
+
>>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
|
| 69 |
+
>>> import pandas as pd
|
| 70 |
+
|
| 71 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/tapex-large-finetuned-wtq")
|
| 72 |
+
>>> model = AutoModelForSeq2SeqLM.from_pretrained("microsoft/tapex-large-finetuned-wtq")
|
| 73 |
+
|
| 74 |
+
>>> # prepare table + question
|
| 75 |
+
>>> data = {"Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"], "Number of movies": ["87", "53", "69"]}
|
| 76 |
+
>>> table = pd.DataFrame.from_dict(data)
|
| 77 |
+
>>> question = "how many movies does Leonardo Di Caprio have?"
|
| 78 |
+
|
| 79 |
+
>>> encoding = tokenizer(table, question, return_tensors="pt")
|
| 80 |
+
|
| 81 |
+
>>> # let the model generate an answer autoregressively
|
| 82 |
+
>>> outputs = model.generate(**encoding)
|
| 83 |
+
|
| 84 |
+
>>> # decode back to text
|
| 85 |
+
>>> predicted_answer = tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]
|
| 86 |
+
>>> print(predicted_answer)
|
| 87 |
+
53
|
| 88 |
+
```
|
| 89 |
+
|
| 90 |
+
Note that [`TapexTokenizer`] also supports batched inference. Hence, one can provide a batch of different tables/questions, or a batch of a single table
|
| 91 |
+
and multiple questions, or a batch of a single query and multiple tables. Let's illustrate this:
|
| 92 |
+
|
| 93 |
+
```python
|
| 94 |
+
>>> # prepare table + question
|
| 95 |
+
>>> data = {"Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"], "Number of movies": ["87", "53", "69"]}
|
| 96 |
+
>>> table = pd.DataFrame.from_dict(data)
|
| 97 |
+
>>> questions = [
|
| 98 |
+
... "how many movies does Leonardo Di Caprio have?",
|
| 99 |
+
... "which actor has 69 movies?",
|
| 100 |
+
... "what's the first name of the actor who has 87 movies?",
|
| 101 |
+
... ]
|
| 102 |
+
>>> encoding = tokenizer(table, questions, padding=True, return_tensors="pt")
|
| 103 |
+
|
| 104 |
+
>>> # let the model generate an answer autoregressively
|
| 105 |
+
>>> outputs = model.generate(**encoding)
|
| 106 |
+
|
| 107 |
+
>>> # decode back to text
|
| 108 |
+
>>> tokenizer.batch_decode(outputs, skip_special_tokens=True)
|
| 109 |
+
[' 53', ' george clooney', ' brad pitt']
|
| 110 |
+
```
|
| 111 |
+
|
| 112 |
+
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
|
| 113 |
+
of a table), one can instantiate a [`BartForSequenceClassification`] model. TAPEX has checkpoints on the hub fine-tuned on TabFact, an important
|
| 114 |
+
benchmark for table fact checking (it achieves 84% accuracy). The code example below again leverages the [Auto API](auto).
|
| 115 |
+
|
| 116 |
+
```python
|
| 117 |
+
>>> from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 118 |
+
|
| 119 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/tapex-large-finetuned-tabfact")
|
| 120 |
+
>>> model = AutoModelForSequenceClassification.from_pretrained("microsoft/tapex-large-finetuned-tabfact")
|
| 121 |
+
|
| 122 |
+
>>> # prepare table + sentence
|
| 123 |
+
>>> data = {"Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"], "Number of movies": ["87", "53", "69"]}
|
| 124 |
+
>>> table = pd.DataFrame.from_dict(data)
|
| 125 |
+
>>> sentence = "George Clooney has 30 movies"
|
| 126 |
+
|
| 127 |
+
>>> encoding = tokenizer(table, sentence, return_tensors="pt")
|
| 128 |
+
|
| 129 |
+
>>> # forward pass
|
| 130 |
+
>>> outputs = model(**encoding)
|
| 131 |
+
|
| 132 |
+
>>> # print prediction
|
| 133 |
+
>>> predicted_class_idx = outputs.logits[0].argmax(dim=0).item()
|
| 134 |
+
>>> print(model.config.id2label[predicted_class_idx])
|
| 135 |
+
Refused
|
| 136 |
+
```
|
| 137 |
+
|
| 138 |
+
<Tip>
|
| 139 |
+
|
| 140 |
+
TAPEX architecture is the same as BART, except for tokenization. Refer to [BART documentation](bart) for information on
|
| 141 |
+
configuration classes and their parameters. TAPEX-specific tokenizer is documented below.
|
| 142 |
+
|
| 143 |
+
</Tip>
|
| 144 |
+
|
| 145 |
+
## TapexTokenizer
|
| 146 |
+
|
| 147 |
+
[[autodoc]] TapexTokenizer
|
| 148 |
+
- __call__
|
| 149 |
+
- save_vocabulary
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/textnet.md
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# TextNet
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
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).
|
| 22 |
+
|
| 23 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/fast_architecture.png"
|
| 24 |
+
alt="drawing" width="600"/>
|
| 25 |
+
|
| 26 |
+
<small> TextNet backbone as part of FAST. Taken from the <a href="https://arxiv.org/abs/2111.02394">original paper.</a> </small>
|
| 27 |
+
|
| 28 |
+
This model was contributed by [Raghavan](https://huggingface.co/Raghavan), [jadechoghari](https://huggingface.co/jadechoghari) and [nielsr](https://huggingface.co/nielsr).
|
| 29 |
+
|
| 30 |
+
## Usage tips
|
| 31 |
+
|
| 32 |
+
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.
|
| 33 |
+
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.
|
| 34 |
+
|
| 35 |
+
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
|
| 36 |
+
|
| 37 |
+
## TextNetConfig
|
| 38 |
+
|
| 39 |
+
[[autodoc]] TextNetConfig
|
| 40 |
+
|
| 41 |
+
## TextNetImageProcessor
|
| 42 |
+
|
| 43 |
+
[[autodoc]] TextNetImageProcessor
|
| 44 |
+
- preprocess
|
| 45 |
+
|
| 46 |
+
## TextNetModel
|
| 47 |
+
|
| 48 |
+
[[autodoc]] TextNetModel
|
| 49 |
+
- forward
|
| 50 |
+
|
| 51 |
+
## TextNetForImageClassification
|
| 52 |
+
|
| 53 |
+
[[autodoc]] TextNetForImageClassification
|
| 54 |
+
- forward
|
| 55 |
+
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/time_series_transformer.md
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Time Series Transformer
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
The Time Series Transformer model is a vanilla encoder-decoder Transformer for time series forecasting.
|
| 22 |
+
This model was contributed by [kashif](https://huggingface.co/kashif).
|
| 23 |
+
|
| 24 |
+
## Usage tips
|
| 25 |
+
|
| 26 |
+
- Similar to other models in the library, [`TimeSeriesTransformerModel`] is the raw Transformer without any head on top, and [`TimeSeriesTransformerForPrediction`]
|
| 27 |
+
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
|
| 28 |
+
point forecasting model. This means that the model learns a distribution, from which one can sample. The model doesn't directly output values.
|
| 29 |
+
- [`TimeSeriesTransformerForPrediction`] consists of 2 blocks: an encoder, which takes a `context_length` of time series values as input (called `past_values`),
|
| 30 |
+
and a decoder, which predicts a `prediction_length` of time series values into the future (called `future_values`). During training, one needs to provide
|
| 31 |
+
pairs of (`past_values` and `future_values`) to the model.
|
| 32 |
+
- In addition to the raw (`past_values` and `future_values`), one typically provides additional features to the model. These can be the following:
|
| 33 |
+
- `past_time_features`: temporal features which the model will add to `past_values`. These serve as "positional encodings" for the Transformer encoder.
|
| 34 |
+
Examples are "day of the month", "month of the year", etc. as scalar values (and then stacked together as a vector).
|
| 35 |
+
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").
|
| 36 |
+
- `future_time_features`: temporal features which the model will add to `future_values`. These serve as "positional encodings" for the Transformer decoder.
|
| 37 |
+
Examples are "day of the month", "month of the year", etc. as scalar values (and then stacked together as a vector).
|
| 38 |
+
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").
|
| 39 |
+
- `static_categorical_features`: categorical features which are static over time (i.e., have the same value for all `past_values` and `future_values`).
|
| 40 |
+
An example here is the store ID or region ID that identifies a given time-series.
|
| 41 |
+
Note that these features need to be known for ALL data points (also those in the future).
|
| 42 |
+
- `static_real_features`: real-valued features which are static over time (i.e., have the same value for all `past_values` and `future_values`).
|
| 43 |
+
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,
|
| 44 |
+
if your time-series is about the sales of shoes).
|
| 45 |
+
Note that these features need to be known for ALL data points (also those in the future).
|
| 46 |
+
- 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
|
| 47 |
+
`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
|
| 48 |
+
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
|
| 49 |
+
of the context as initial input for the decoder).
|
| 50 |
+
- 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,
|
| 51 |
+
which is then fed to the decoder in order to make the next prediction (also called autoregressive generation).
|
| 52 |
+
|
| 53 |
+
## Resources
|
| 54 |
+
|
| 55 |
+
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.
|
| 56 |
+
|
| 57 |
+
- Check out the Time Series Transformer blog-post in HuggingFace blog: [Probabilistic Time Series Forecasting with 🤗 Transformers](https://huggingface.co/blog/time-series-transformers)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
## TimeSeriesTransformerConfig
|
| 61 |
+
|
| 62 |
+
[[autodoc]] TimeSeriesTransformerConfig
|
| 63 |
+
|
| 64 |
+
## TimeSeriesTransformerModel
|
| 65 |
+
|
| 66 |
+
[[autodoc]] TimeSeriesTransformerModel
|
| 67 |
+
- forward
|
| 68 |
+
|
| 69 |
+
## TimeSeriesTransformerForPrediction
|
| 70 |
+
|
| 71 |
+
[[autodoc]] TimeSeriesTransformerForPrediction
|
| 72 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/timesformer.md
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# TimeSformer
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
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.
|
| 22 |
+
This work is a milestone in action-recognition field being the first video transformer. It inspired many transformer based video understanding and classification papers.
|
| 23 |
+
|
| 24 |
+
The abstract from the paper is the following:
|
| 25 |
+
|
| 26 |
+
*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).*
|
| 27 |
+
|
| 28 |
+
This model was contributed by [fcakyon](https://huggingface.co/fcakyon).
|
| 29 |
+
The original code can be found [here](https://github.com/facebookresearch/TimeSformer).
|
| 30 |
+
|
| 31 |
+
## Usage tips
|
| 32 |
+
|
| 33 |
+
There are many pretrained variants. Select your pretrained model based on the dataset it is trained on. Moreover,
|
| 34 |
+
the number of input frames per clip changes based on the model size so you should consider this parameter while selecting your pretrained model.
|
| 35 |
+
|
| 36 |
+
## Resources
|
| 37 |
+
|
| 38 |
+
- [Video classification task guide](../tasks/video_classification)
|
| 39 |
+
|
| 40 |
+
## TimesformerConfig
|
| 41 |
+
|
| 42 |
+
[[autodoc]] TimesformerConfig
|
| 43 |
+
|
| 44 |
+
## TimesformerModel
|
| 45 |
+
|
| 46 |
+
[[autodoc]] TimesformerModel
|
| 47 |
+
- forward
|
| 48 |
+
|
| 49 |
+
## TimesformerForVideoClassification
|
| 50 |
+
|
| 51 |
+
[[autodoc]] TimesformerForVideoClassification
|
| 52 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/timm_wrapper.md
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# TimmWrapper
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
Helper class to enable loading timm models to be used with the transformers library and its autoclasses.
|
| 22 |
+
|
| 23 |
+
```python
|
| 24 |
+
>>> import torch
|
| 25 |
+
>>> from PIL import Image
|
| 26 |
+
>>> from urllib.request import urlopen
|
| 27 |
+
>>> from transformers import AutoModelForImageClassification, AutoImageProcessor
|
| 28 |
+
|
| 29 |
+
>>> # Load image
|
| 30 |
+
>>> image = Image.open(urlopen(
|
| 31 |
+
... 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/beignets-task-guide.png'
|
| 32 |
+
... ))
|
| 33 |
+
|
| 34 |
+
>>> # Load model and image processor
|
| 35 |
+
>>> checkpoint = "timm/resnet50.a1_in1k"
|
| 36 |
+
>>> image_processor = AutoImageProcessor.from_pretrained(checkpoint)
|
| 37 |
+
>>> model = AutoModelForImageClassification.from_pretrained(checkpoint).eval()
|
| 38 |
+
|
| 39 |
+
>>> # Preprocess image
|
| 40 |
+
>>> inputs = image_processor(image)
|
| 41 |
+
|
| 42 |
+
>>> # Forward pass
|
| 43 |
+
>>> with torch.no_grad():
|
| 44 |
+
... logits = model(**inputs).logits
|
| 45 |
+
|
| 46 |
+
>>> # Get top 5 predictions
|
| 47 |
+
>>> top5_probabilities, top5_class_indices = torch.topk(logits.softmax(dim=1) * 100, k=5)
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
## TimmWrapperConfig
|
| 51 |
+
|
| 52 |
+
[[autodoc]] TimmWrapperConfig
|
| 53 |
+
|
| 54 |
+
## TimmWrapperImageProcessor
|
| 55 |
+
|
| 56 |
+
[[autodoc]] TimmWrapperImageProcessor
|
| 57 |
+
- preprocess
|
| 58 |
+
|
| 59 |
+
## TimmWrapperModel
|
| 60 |
+
|
| 61 |
+
[[autodoc]] TimmWrapperModel
|
| 62 |
+
- forward
|
| 63 |
+
|
| 64 |
+
## TimmWrapperForImageClassification
|
| 65 |
+
|
| 66 |
+
[[autodoc]] TimmWrapperForImageClassification
|
| 67 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/trajectory_transformer.md
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Trajectory Transformer
|
| 18 |
+
|
| 19 |
+
<Tip warning={true}>
|
| 20 |
+
|
| 21 |
+
This model is in maintenance mode only, so we won't accept any new PRs changing its code.
|
| 22 |
+
|
| 23 |
+
If you run into any issues running this model, please reinstall the last version that supported this model: v4.30.0.
|
| 24 |
+
You can do so by running the following command: `pip install -U transformers==4.30.0`.
|
| 25 |
+
|
| 26 |
+
</Tip>
|
| 27 |
+
|
| 28 |
+
## Overview
|
| 29 |
+
|
| 30 |
+
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.
|
| 31 |
+
|
| 32 |
+
The abstract from the paper is the following:
|
| 33 |
+
|
| 34 |
+
*Reinforcement learning (RL) is typically concerned with estimating stationary policies or single-step models,
|
| 35 |
+
leveraging the Markov property to factorize problems in time. However, we can also view RL as a generic sequence
|
| 36 |
+
modeling problem, with the goal being to produce a sequence of actions that leads to a sequence of high rewards.
|
| 37 |
+
Viewed in this way, it is tempting to consider whether high-capacity sequence prediction models that work well
|
| 38 |
+
in other domains, such as natural-language processing, can also provide effective solutions to the RL problem.
|
| 39 |
+
To this end, we explore how RL can be tackled with the tools of sequence modeling, using a Transformer architecture
|
| 40 |
+
to model distributions over trajectories and repurposing beam search as a planning algorithm. Framing RL as sequence
|
| 41 |
+
modeling problem simplifies a range of design decisions, allowing us to dispense with many of the components common
|
| 42 |
+
in offline RL algorithms. We demonstrate the flexibility of this approach across long-horizon dynamics prediction,
|
| 43 |
+
imitation learning, goal-conditioned RL, and offline RL. Further, we show that this approach can be combined with
|
| 44 |
+
existing model-free algorithms to yield a state-of-the-art planner in sparse-reward, long-horizon tasks.*
|
| 45 |
+
|
| 46 |
+
This model was contributed by [CarlCochet](https://huggingface.co/CarlCochet). The original code can be found [here](https://github.com/jannerm/trajectory-transformer).
|
| 47 |
+
|
| 48 |
+
## Usage tips
|
| 49 |
+
|
| 50 |
+
This Transformer is used for deep reinforcement learning. To use it, you need to create sequences from
|
| 51 |
+
actions, states and rewards from all previous timesteps. This model will treat all these elements together
|
| 52 |
+
as one big sequence (a trajectory).
|
| 53 |
+
|
| 54 |
+
## TrajectoryTransformerConfig
|
| 55 |
+
|
| 56 |
+
[[autodoc]] TrajectoryTransformerConfig
|
| 57 |
+
|
| 58 |
+
## TrajectoryTransformerModel
|
| 59 |
+
|
| 60 |
+
[[autodoc]] TrajectoryTransformerModel
|
| 61 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/transfo-xl.md
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Transformer XL
|
| 18 |
+
|
| 19 |
+
<Tip warning={true}>
|
| 20 |
+
|
| 21 |
+
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`.
|
| 22 |
+
|
| 23 |
+
We recommend switching to more recent models for improved security.
|
| 24 |
+
|
| 25 |
+
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.
|
| 26 |
+
|
| 27 |
+
You will need to set the environment variable `TRUST_REMOTE_CODE` to `True` in order to allow the
|
| 28 |
+
usage of `pickle.load()`:
|
| 29 |
+
|
| 30 |
+
```python
|
| 31 |
+
import os
|
| 32 |
+
from transformers import TransfoXLTokenizer, TransfoXLLMHeadModel
|
| 33 |
+
|
| 34 |
+
os.environ["TRUST_REMOTE_CODE"] = "True"
|
| 35 |
+
|
| 36 |
+
checkpoint = 'transfo-xl/transfo-xl-wt103'
|
| 37 |
+
revision = '40a186da79458c9f9de846edfaea79c412137f97'
|
| 38 |
+
|
| 39 |
+
tokenizer = TransfoXLTokenizer.from_pretrained(checkpoint, revision=revision)
|
| 40 |
+
model = TransfoXLLMHeadModel.from_pretrained(checkpoint, revision=revision)
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
If you run into any issues running this model, please reinstall the last version that supported this model: v4.35.0.
|
| 44 |
+
You can do so by running the following command: `pip install -U transformers==4.35.0`.
|
| 45 |
+
|
| 46 |
+
</Tip>
|
| 47 |
+
|
| 48 |
+
<div class="flex flex-wrap space-x-1">
|
| 49 |
+
<a href="https://huggingface.co/models?filter=transfo-xl">
|
| 50 |
+
<img alt="Models" src="https://img.shields.io/badge/All_model_pages-transfo--xl-blueviolet">
|
| 51 |
+
</a>
|
| 52 |
+
<a href="https://huggingface.co/spaces/docs-demos/transfo-xl-wt103">
|
| 53 |
+
<img alt="Spaces" src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue">
|
| 54 |
+
</a>
|
| 55 |
+
</div>
|
| 56 |
+
|
| 57 |
+
## Overview
|
| 58 |
+
|
| 59 |
+
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
|
| 60 |
+
Salakhutdinov. It's a causal (uni-directional) transformer with relative positioning (sinusoïdal) embeddings which can
|
| 61 |
+
reuse previously computed hidden-states to attend to longer context (memory). This model also uses adaptive softmax
|
| 62 |
+
inputs and outputs (tied).
|
| 63 |
+
|
| 64 |
+
The abstract from the paper is the following:
|
| 65 |
+
|
| 66 |
+
*Transformers have a potential of learning longer-term dependency, but are limited by a fixed-length context in the
|
| 67 |
+
setting of language modeling. We propose a novel neural architecture Transformer-XL that enables learning dependency
|
| 68 |
+
beyond a fixed length without disrupting temporal coherence. It consists of a segment-level recurrence mechanism and a
|
| 69 |
+
novel positional encoding scheme. Our method not only enables capturing longer-term dependency, but also resolves the
|
| 70 |
+
context fragmentation problem. As a result, Transformer-XL learns dependency that is 80% longer than RNNs and 450%
|
| 71 |
+
longer than vanilla Transformers, achieves better performance on both short and long sequences, and is up to 1,800+
|
| 72 |
+
times faster than vanilla Transformers during evaluation. Notably, we improve the state-of-the-art results of
|
| 73 |
+
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
|
| 74 |
+
Treebank (without finetuning). When trained only on WikiText-103, Transformer-XL manages to generate reasonably
|
| 75 |
+
coherent, novel text articles with thousands of tokens.*
|
| 76 |
+
|
| 77 |
+
This model was contributed by [thomwolf](https://huggingface.co/thomwolf). The original code can be found [here](https://github.com/kimiyoung/transformer-xl).
|
| 78 |
+
|
| 79 |
+
## Usage tips
|
| 80 |
+
|
| 81 |
+
- Transformer-XL uses relative sinusoidal positional embeddings. Padding can be done on the left or on the right. The
|
| 82 |
+
original implementation trains on SQuAD with padding on the left, therefore the padding defaults are set to left.
|
| 83 |
+
- Transformer-XL is one of the few models that has no sequence length limit.
|
| 84 |
+
- 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.
|
| 85 |
+
- 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.
|
| 86 |
+
- 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.
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
<Tip warning={true}>
|
| 90 |
+
|
| 91 |
+
TransformerXL does **not** work with *torch.nn.DataParallel* due to a bug in PyTorch, see [issue #36035](https://github.com/pytorch/pytorch/issues/36035)
|
| 92 |
+
|
| 93 |
+
</Tip>
|
| 94 |
+
|
| 95 |
+
## Resources
|
| 96 |
+
|
| 97 |
+
- [Text classification task guide](../tasks/sequence_classification)
|
| 98 |
+
- [Causal language modeling task guide](../tasks/language_modeling)
|
| 99 |
+
|
| 100 |
+
## TransfoXLConfig
|
| 101 |
+
|
| 102 |
+
[[autodoc]] TransfoXLConfig
|
| 103 |
+
|
| 104 |
+
## TransfoXLTokenizer
|
| 105 |
+
|
| 106 |
+
[[autodoc]] TransfoXLTokenizer
|
| 107 |
+
- save_vocabulary
|
| 108 |
+
|
| 109 |
+
## TransfoXL specific outputs
|
| 110 |
+
|
| 111 |
+
[[autodoc]] models.deprecated.transfo_xl.modeling_transfo_xl.TransfoXLModelOutput
|
| 112 |
+
|
| 113 |
+
[[autodoc]] models.deprecated.transfo_xl.modeling_transfo_xl.TransfoXLLMHeadModelOutput
|
| 114 |
+
|
| 115 |
+
[[autodoc]] models.deprecated.transfo_xl.modeling_tf_transfo_xl.TFTransfoXLModelOutput
|
| 116 |
+
|
| 117 |
+
[[autodoc]] models.deprecated.transfo_xl.modeling_tf_transfo_xl.TFTransfoXLLMHeadModelOutput
|
| 118 |
+
|
| 119 |
+
<frameworkcontent>
|
| 120 |
+
<pt>
|
| 121 |
+
|
| 122 |
+
## TransfoXLModel
|
| 123 |
+
|
| 124 |
+
[[autodoc]] TransfoXLModel
|
| 125 |
+
- forward
|
| 126 |
+
|
| 127 |
+
## TransfoXLLMHeadModel
|
| 128 |
+
|
| 129 |
+
[[autodoc]] TransfoXLLMHeadModel
|
| 130 |
+
- forward
|
| 131 |
+
|
| 132 |
+
## TransfoXLForSequenceClassification
|
| 133 |
+
|
| 134 |
+
[[autodoc]] TransfoXLForSequenceClassification
|
| 135 |
+
- forward
|
| 136 |
+
|
| 137 |
+
</pt>
|
| 138 |
+
<tf>
|
| 139 |
+
|
| 140 |
+
## TFTransfoXLModel
|
| 141 |
+
|
| 142 |
+
[[autodoc]] TFTransfoXLModel
|
| 143 |
+
- call
|
| 144 |
+
|
| 145 |
+
## TFTransfoXLLMHeadModel
|
| 146 |
+
|
| 147 |
+
[[autodoc]] TFTransfoXLLMHeadModel
|
| 148 |
+
- call
|
| 149 |
+
|
| 150 |
+
## TFTransfoXLForSequenceClassification
|
| 151 |
+
|
| 152 |
+
[[autodoc]] TFTransfoXLForSequenceClassification
|
| 153 |
+
- call
|
| 154 |
+
|
| 155 |
+
</tf>
|
| 156 |
+
</frameworkcontent>
|
| 157 |
+
|
| 158 |
+
## Internal Layers
|
| 159 |
+
|
| 160 |
+
[[autodoc]] AdaptiveEmbedding
|
| 161 |
+
|
| 162 |
+
[[autodoc]] TFAdaptiveEmbedding
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/trocr.md
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2021 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
|
| 4 |
+
License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
|
| 9 |
+
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
|
| 11 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 12 |
+
rendered properly in your Markdown viewer.
|
| 13 |
+
|
| 14 |
+
specific language governing permissions and limitations under the License. -->
|
| 15 |
+
|
| 16 |
+
# TrOCR
|
| 17 |
+
|
| 18 |
+
## Overview
|
| 19 |
+
|
| 20 |
+
The TrOCR model was proposed in [TrOCR: Transformer-based Optical Character Recognition with Pre-trained
|
| 21 |
+
Models](https://arxiv.org/abs/2109.10282) by Minghao Li, Tengchao Lv, Lei Cui, Yijuan Lu, Dinei Florencio, Cha Zhang,
|
| 22 |
+
Zhoujun Li, Furu Wei. TrOCR consists of an image Transformer encoder and an autoregressive text Transformer decoder to
|
| 23 |
+
perform [optical character recognition (OCR)](https://en.wikipedia.org/wiki/Optical_character_recognition).
|
| 24 |
+
|
| 25 |
+
The abstract from the paper is the following:
|
| 26 |
+
|
| 27 |
+
*Text recognition is a long-standing research problem for document digitalization. Existing approaches for text recognition
|
| 28 |
+
are usually built based on CNN for image understanding and RNN for char-level text generation. In addition, another language
|
| 29 |
+
model is usually needed to improve the overall accuracy as a post-processing step. In this paper, we propose an end-to-end
|
| 30 |
+
text recognition approach with pre-trained image Transformer and text Transformer models, namely TrOCR, which leverages the
|
| 31 |
+
Transformer architecture for both image understanding and wordpiece-level text generation. The TrOCR model is simple but
|
| 32 |
+
effective, and can be pre-trained with large-scale synthetic data and fine-tuned with human-labeled datasets. Experiments
|
| 33 |
+
show that the TrOCR model outperforms the current state-of-the-art models on both printed and handwritten text recognition
|
| 34 |
+
tasks.*
|
| 35 |
+
|
| 36 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/trocr_architecture.jpg"
|
| 37 |
+
alt="drawing" width="600"/>
|
| 38 |
+
|
| 39 |
+
<small> TrOCR architecture. Taken from the <a href="https://arxiv.org/abs/2109.10282">original paper</a>. </small>
|
| 40 |
+
|
| 41 |
+
Please refer to the [`VisionEncoderDecoder`] class on how to use this model.
|
| 42 |
+
|
| 43 |
+
This model was contributed by [nielsr](https://huggingface.co/nielsr). The original code can be found
|
| 44 |
+
[here](https://github.com/microsoft/unilm/tree/6f60612e7cc86a2a1ae85c47231507a587ab4e01/trocr).
|
| 45 |
+
|
| 46 |
+
## Usage tips
|
| 47 |
+
|
| 48 |
+
- The quickest way to get started with TrOCR is by checking the [tutorial
|
| 49 |
+
notebooks](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/TrOCR), which show how to use the model
|
| 50 |
+
at inference time as well as fine-tuning on custom data.
|
| 51 |
+
- TrOCR is pre-trained in 2 stages before being fine-tuned on downstream datasets. It achieves state-of-the-art results
|
| 52 |
+
on both printed (e.g. the [SROIE dataset](https://paperswithcode.com/dataset/sroie) and handwritten (e.g. the [IAM
|
| 53 |
+
Handwriting dataset](https://fki.tic.heia-fr.ch/databases/iam-handwriting-database>) text recognition tasks. For more
|
| 54 |
+
information, see the [official models](https://huggingface.co/models?other=trocr>).
|
| 55 |
+
- TrOCR is always used within the [VisionEncoderDecoder](vision-encoder-decoder) framework.
|
| 56 |
+
|
| 57 |
+
## Resources
|
| 58 |
+
|
| 59 |
+
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.
|
| 60 |
+
|
| 61 |
+
<PipelineTag pipeline="text-classification"/>
|
| 62 |
+
|
| 63 |
+
- A blog post on [Accelerating Document AI](https://huggingface.co/blog/document-ai) with TrOCR.
|
| 64 |
+
- A blog post on how to [Document AI](https://github.com/philschmid/document-ai-transformers) with TrOCR.
|
| 65 |
+
- 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).
|
| 66 |
+
- 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.
|
| 67 |
+
- 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.
|
| 68 |
+
- 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).
|
| 69 |
+
|
| 70 |
+
<PipelineTag pipeline="text-generation"/>
|
| 71 |
+
|
| 72 |
+
- [Casual language modeling](https://huggingface.co/docs/transformers/tasks/language_modeling) task guide.
|
| 73 |
+
|
| 74 |
+
⚡️ Inference
|
| 75 |
+
|
| 76 |
+
- An interactive-demo on [TrOCR handwritten character recognition](https://huggingface.co/spaces/nielsr/TrOCR-handwritten).
|
| 77 |
+
|
| 78 |
+
## Inference
|
| 79 |
+
|
| 80 |
+
TrOCR's [`VisionEncoderDecoder`] model accepts images as input and makes use of
|
| 81 |
+
[`~generation.GenerationMixin.generate`] to autoregressively generate text given the input image.
|
| 82 |
+
|
| 83 |
+
The [`ViTImageProcessor`/`DeiTImageProcessor`] class is responsible for preprocessing the input image and
|
| 84 |
+
[`RobertaTokenizer`/`XLMRobertaTokenizer`] decodes the generated target tokens to the target string. The
|
| 85 |
+
[`TrOCRProcessor`] wraps [`ViTImageProcessor`/`DeiTImageProcessor`] and [`RobertaTokenizer`/`XLMRobertaTokenizer`]
|
| 86 |
+
into a single instance to both extract the input features and decode the predicted token ids.
|
| 87 |
+
|
| 88 |
+
- Step-by-step Optical Character Recognition (OCR)
|
| 89 |
+
|
| 90 |
+
``` py
|
| 91 |
+
>>> from transformers import TrOCRProcessor, VisionEncoderDecoderModel
|
| 92 |
+
>>> import requests
|
| 93 |
+
>>> from PIL import Image
|
| 94 |
+
|
| 95 |
+
>>> processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-handwritten")
|
| 96 |
+
>>> model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten")
|
| 97 |
+
|
| 98 |
+
>>> # load image from the IAM dataset
|
| 99 |
+
>>> url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg"
|
| 100 |
+
>>> image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
|
| 101 |
+
|
| 102 |
+
>>> pixel_values = processor(image, return_tensors="pt").pixel_values
|
| 103 |
+
>>> generated_ids = model.generate(pixel_values)
|
| 104 |
+
|
| 105 |
+
>>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 106 |
+
```
|
| 107 |
+
|
| 108 |
+
See the [model hub](https://huggingface.co/models?filter=trocr) to look for TrOCR checkpoints.
|
| 109 |
+
|
| 110 |
+
## TrOCRConfig
|
| 111 |
+
|
| 112 |
+
[[autodoc]] TrOCRConfig
|
| 113 |
+
|
| 114 |
+
## TrOCRProcessor
|
| 115 |
+
|
| 116 |
+
[[autodoc]] TrOCRProcessor
|
| 117 |
+
- __call__
|
| 118 |
+
- from_pretrained
|
| 119 |
+
- save_pretrained
|
| 120 |
+
- batch_decode
|
| 121 |
+
- decode
|
| 122 |
+
|
| 123 |
+
## TrOCRForCausalLM
|
| 124 |
+
|
| 125 |
+
[[autodoc]] TrOCRForCausalLM
|
| 126 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/tvlt.md
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# TVLT
|
| 18 |
+
|
| 19 |
+
<Tip warning={true}>
|
| 20 |
+
|
| 21 |
+
This model is in maintenance mode only, we don't accept any new PRs changing its code.
|
| 22 |
+
If you run into any issues running this model, please reinstall the last version that supported this model: v4.40.2.
|
| 23 |
+
You can do so by running the following command: `pip install -U transformers==4.40.2`.
|
| 24 |
+
|
| 25 |
+
</Tip>
|
| 26 |
+
|
| 27 |
+
## Overview
|
| 28 |
+
|
| 29 |
+
The TVLT model was proposed in [TVLT: Textless Vision-Language Transformer](https://arxiv.org/abs/2209.14156)
|
| 30 |
+
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.
|
| 31 |
+
|
| 32 |
+
The abstract from the paper is the following:
|
| 33 |
+
|
| 34 |
+
*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.*
|
| 35 |
+
|
| 36 |
+
<p align="center">
|
| 37 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/tvlt_architecture.png"
|
| 38 |
+
alt="drawing" width="600"/>
|
| 39 |
+
</p>
|
| 40 |
+
|
| 41 |
+
<small> TVLT architecture. Taken from the <a href="[https://arxiv.org/abs/2102.03334](https://arxiv.org/abs/2209.14156)">original paper</a>. </small>
|
| 42 |
+
|
| 43 |
+
The original code can be found [here](https://github.com/zinengtang/TVLT). This model was contributed by [Zineng Tang](https://huggingface.co/ZinengTang).
|
| 44 |
+
|
| 45 |
+
## Usage tips
|
| 46 |
+
|
| 47 |
+
- TVLT is a model that takes both `pixel_values` and `audio_values` as input. One can use [`TvltProcessor`] to prepare data for the model.
|
| 48 |
+
This processor wraps an image processor (for the image/video modality) and an audio feature extractor (for the audio modality) into one.
|
| 49 |
+
- 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.
|
| 50 |
+
- 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.
|
| 51 |
+
- The PyTorch version of this model is only available in torch 1.10 and higher.
|
| 52 |
+
|
| 53 |
+
## TvltConfig
|
| 54 |
+
|
| 55 |
+
[[autodoc]] TvltConfig
|
| 56 |
+
|
| 57 |
+
## TvltProcessor
|
| 58 |
+
|
| 59 |
+
[[autodoc]] TvltProcessor
|
| 60 |
+
- __call__
|
| 61 |
+
|
| 62 |
+
## TvltImageProcessor
|
| 63 |
+
|
| 64 |
+
[[autodoc]] TvltImageProcessor
|
| 65 |
+
- preprocess
|
| 66 |
+
|
| 67 |
+
## TvltFeatureExtractor
|
| 68 |
+
|
| 69 |
+
[[autodoc]] TvltFeatureExtractor
|
| 70 |
+
- __call__
|
| 71 |
+
|
| 72 |
+
## TvltModel
|
| 73 |
+
|
| 74 |
+
[[autodoc]] TvltModel
|
| 75 |
+
- forward
|
| 76 |
+
|
| 77 |
+
## TvltForPreTraining
|
| 78 |
+
|
| 79 |
+
[[autodoc]] TvltForPreTraining
|
| 80 |
+
- forward
|
| 81 |
+
|
| 82 |
+
## TvltForAudioVisualClassification
|
| 83 |
+
|
| 84 |
+
[[autodoc]] TvltForAudioVisualClassification
|
| 85 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/tvp.md
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2023 The Intel Team Authors and HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
-->
|
| 12 |
+
|
| 13 |
+
# TVP
|
| 14 |
+
|
| 15 |
+
## Overview
|
| 16 |
+
|
| 17 |
+
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.
|
| 18 |
+
|
| 19 |
+
The abstract from the paper is the following:
|
| 20 |
+
|
| 21 |
+
*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.*
|
| 22 |
+
|
| 23 |
+
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.
|
| 24 |
+
|
| 25 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/tvp_architecture.png"
|
| 26 |
+
alt="drawing" width="600"/>
|
| 27 |
+
|
| 28 |
+
<small> TVP architecture. Taken from the <a href="https://arxiv.org/abs/2303.04995">original paper.</a> </small>
|
| 29 |
+
|
| 30 |
+
This model was contributed by [Jiqing Feng](https://huggingface.co/Jiqing). The original code can be found [here](https://github.com/intel/TVP).
|
| 31 |
+
|
| 32 |
+
## Usage tips and examples
|
| 33 |
+
|
| 34 |
+
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.
|
| 35 |
+
|
| 36 |
+
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.
|
| 37 |
+
|
| 38 |
+
The goal of this model is to incorporate trainable prompts into both visual inputs and textual features to temporal video grounding(TVG) problems.
|
| 39 |
+
In principle, one can apply any visual, cross-modal encoder in the proposed architecture.
|
| 40 |
+
|
| 41 |
+
The [`TvpProcessor`] wraps [`BertTokenizer`] and [`TvpImageProcessor`] into a single instance to both
|
| 42 |
+
encode the text and prepare the images respectively.
|
| 43 |
+
|
| 44 |
+
The following example shows how to run temporal video grounding using [`TvpProcessor`] and [`TvpForVideoGrounding`].
|
| 45 |
+
```python
|
| 46 |
+
import av
|
| 47 |
+
import cv2
|
| 48 |
+
import numpy as np
|
| 49 |
+
import torch
|
| 50 |
+
from huggingface_hub import hf_hub_download
|
| 51 |
+
from transformers import AutoProcessor, TvpForVideoGrounding
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def pyav_decode(container, sampling_rate, num_frames, clip_idx, num_clips, target_fps):
|
| 55 |
+
'''
|
| 56 |
+
Convert the video from its original fps to the target_fps and decode the video with PyAV decoder.
|
| 57 |
+
Args:
|
| 58 |
+
container (container): pyav container.
|
| 59 |
+
sampling_rate (int): frame sampling rate (interval between two sampled frames).
|
| 60 |
+
num_frames (int): number of frames to sample.
|
| 61 |
+
clip_idx (int): if clip_idx is -1, perform random temporal sampling.
|
| 62 |
+
If clip_idx is larger than -1, uniformly split the video to num_clips
|
| 63 |
+
clips, and select the clip_idx-th video clip.
|
| 64 |
+
num_clips (int): overall number of clips to uniformly sample from the given video.
|
| 65 |
+
target_fps (int): the input video may have different fps, convert it to
|
| 66 |
+
the target video fps before frame sampling.
|
| 67 |
+
Returns:
|
| 68 |
+
frames (tensor): decoded frames from the video. Return None if the no
|
| 69 |
+
video stream was found.
|
| 70 |
+
fps (float): the number of frames per second of the video.
|
| 71 |
+
'''
|
| 72 |
+
video = container.streams.video[0]
|
| 73 |
+
fps = float(video.average_rate)
|
| 74 |
+
clip_size = sampling_rate * num_frames / target_fps * fps
|
| 75 |
+
delta = max(num_frames - clip_size, 0)
|
| 76 |
+
start_idx = delta * clip_idx / num_clips
|
| 77 |
+
end_idx = start_idx + clip_size - 1
|
| 78 |
+
timebase = video.duration / num_frames
|
| 79 |
+
video_start_pts = int(start_idx * timebase)
|
| 80 |
+
video_end_pts = int(end_idx * timebase)
|
| 81 |
+
seek_offset = max(video_start_pts - 1024, 0)
|
| 82 |
+
container.seek(seek_offset, any_frame=False, backward=True, stream=video)
|
| 83 |
+
frames = {}
|
| 84 |
+
for frame in container.decode(video=0):
|
| 85 |
+
if frame.pts < video_start_pts:
|
| 86 |
+
continue
|
| 87 |
+
frames[frame.pts] = frame
|
| 88 |
+
if frame.pts > video_end_pts:
|
| 89 |
+
break
|
| 90 |
+
frames = [frames[pts] for pts in sorted(frames)]
|
| 91 |
+
return frames, fps
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def decode(container, sampling_rate, num_frames, clip_idx, num_clips, target_fps):
|
| 95 |
+
'''
|
| 96 |
+
Decode the video and perform temporal sampling.
|
| 97 |
+
Args:
|
| 98 |
+
container (container): pyav container.
|
| 99 |
+
sampling_rate (int): frame sampling rate (interval between two sampled frames).
|
| 100 |
+
num_frames (int): number of frames to sample.
|
| 101 |
+
clip_idx (int): if clip_idx is -1, perform random temporal sampling.
|
| 102 |
+
If clip_idx is larger than -1, uniformly split the video to num_clips
|
| 103 |
+
clips, and select the clip_idx-th video clip.
|
| 104 |
+
num_clips (int): overall number of clips to uniformly sample from the given video.
|
| 105 |
+
target_fps (int): the input video may have different fps, convert it to
|
| 106 |
+
the target video fps before frame sampling.
|
| 107 |
+
Returns:
|
| 108 |
+
frames (tensor): decoded frames from the video.
|
| 109 |
+
'''
|
| 110 |
+
assert clip_idx >= -2, "Not a valied clip_idx {}".format(clip_idx)
|
| 111 |
+
frames, fps = pyav_decode(container, sampling_rate, num_frames, clip_idx, num_clips, target_fps)
|
| 112 |
+
clip_size = sampling_rate * num_frames / target_fps * fps
|
| 113 |
+
index = np.linspace(0, clip_size - 1, num_frames)
|
| 114 |
+
index = np.clip(index, 0, len(frames) - 1).astype(np.int64)
|
| 115 |
+
frames = np.array([frames[idx].to_rgb().to_ndarray() for idx in index])
|
| 116 |
+
frames = frames.transpose(0, 3, 1, 2)
|
| 117 |
+
return frames
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
file = hf_hub_download(repo_id="Intel/tvp_demo", filename="AK2KG.mp4", repo_type="dataset")
|
| 121 |
+
model = TvpForVideoGrounding.from_pretrained("Intel/tvp-base")
|
| 122 |
+
|
| 123 |
+
decoder_kwargs = dict(
|
| 124 |
+
container=av.open(file, metadata_errors="ignore"),
|
| 125 |
+
sampling_rate=1,
|
| 126 |
+
num_frames=model.config.num_frames,
|
| 127 |
+
clip_idx=0,
|
| 128 |
+
num_clips=1,
|
| 129 |
+
target_fps=3,
|
| 130 |
+
)
|
| 131 |
+
raw_sampled_frms = decode(**decoder_kwargs)
|
| 132 |
+
|
| 133 |
+
text = "a person is sitting on a bed."
|
| 134 |
+
processor = AutoProcessor.from_pretrained("Intel/tvp-base")
|
| 135 |
+
model_inputs = processor(
|
| 136 |
+
text=[text], videos=list(raw_sampled_frms), return_tensors="pt", max_text_length=100#, size=size
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
model_inputs["pixel_values"] = model_inputs["pixel_values"].to(model.dtype)
|
| 140 |
+
output = model(**model_inputs)
|
| 141 |
+
|
| 142 |
+
def get_video_duration(filename):
|
| 143 |
+
cap = cv2.VideoCapture(filename)
|
| 144 |
+
if cap.isOpened():
|
| 145 |
+
rate = cap.get(5)
|
| 146 |
+
frame_num = cap.get(7)
|
| 147 |
+
duration = frame_num/rate
|
| 148 |
+
return duration
|
| 149 |
+
return -1
|
| 150 |
+
|
| 151 |
+
duration = get_video_duration(file)
|
| 152 |
+
start, end = processor.post_process_video_grounding(output.logits, duration)
|
| 153 |
+
|
| 154 |
+
print(f"The time slot of the video corresponding to the text \"{text}\" is from {start}s to {end}s")
|
| 155 |
+
```
|
| 156 |
+
|
| 157 |
+
Tips:
|
| 158 |
+
|
| 159 |
+
- This implementation of TVP uses [`BertTokenizer`] to generate text embeddings and Resnet-50 model to compute visual embeddings.
|
| 160 |
+
- Checkpoints for pre-trained [tvp-base](https://huggingface.co/Intel/tvp-base) is released.
|
| 161 |
+
- Please refer to [Table 2](https://arxiv.org/pdf/2303.04995.pdf) for TVP's performance on Temporal Video Grounding task.
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
## TvpConfig
|
| 165 |
+
|
| 166 |
+
[[autodoc]] TvpConfig
|
| 167 |
+
|
| 168 |
+
## TvpImageProcessor
|
| 169 |
+
|
| 170 |
+
[[autodoc]] TvpImageProcessor
|
| 171 |
+
- preprocess
|
| 172 |
+
|
| 173 |
+
## TvpProcessor
|
| 174 |
+
|
| 175 |
+
[[autodoc]] TvpProcessor
|
| 176 |
+
- __call__
|
| 177 |
+
|
| 178 |
+
## TvpModel
|
| 179 |
+
|
| 180 |
+
[[autodoc]] TvpModel
|
| 181 |
+
- forward
|
| 182 |
+
|
| 183 |
+
## TvpForVideoGrounding
|
| 184 |
+
|
| 185 |
+
[[autodoc]] TvpForVideoGrounding
|
| 186 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/udop.md
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
-->
|
| 12 |
+
|
| 13 |
+
# UDOP
|
| 14 |
+
|
| 15 |
+
## Overview
|
| 16 |
+
|
| 17 |
+
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.
|
| 18 |
+
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.
|
| 19 |
+
|
| 20 |
+
The abstract from the paper is the following:
|
| 21 |
+
|
| 22 |
+
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).*
|
| 23 |
+
|
| 24 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/udop_architecture.jpg"
|
| 25 |
+
alt="drawing" width="600"/>
|
| 26 |
+
|
| 27 |
+
<small> UDOP architecture. Taken from the <a href="https://arxiv.org/abs/2212.02623">original paper.</a> </small>
|
| 28 |
+
|
| 29 |
+
## Usage tips
|
| 30 |
+
|
| 31 |
+
- In addition to *input_ids*, [`UdopForConditionalGeneration`] also expects the input `bbox`, which are
|
| 32 |
+
the bounding boxes (i.e. 2D-positions) of the input tokens. These can be obtained using an external OCR engine such
|
| 33 |
+
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
|
| 34 |
+
position of the lower right corner. Note that one first needs to normalize the bounding boxes to be on a 0-1000
|
| 35 |
+
scale. To normalize, you can use the following function:
|
| 36 |
+
|
| 37 |
+
```python
|
| 38 |
+
def normalize_bbox(bbox, width, height):
|
| 39 |
+
return [
|
| 40 |
+
int(1000 * (bbox[0] / width)),
|
| 41 |
+
int(1000 * (bbox[1] / height)),
|
| 42 |
+
int(1000 * (bbox[2] / width)),
|
| 43 |
+
int(1000 * (bbox[3] / height)),
|
| 44 |
+
]
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
Here, `width` and `height` correspond to the width and height of the original document in which the token
|
| 48 |
+
occurs. Those can be obtained using the Python Image Library (PIL) library for example, as follows:
|
| 49 |
+
|
| 50 |
+
```python
|
| 51 |
+
from PIL import Image
|
| 52 |
+
|
| 53 |
+
# Document can be a png, jpg, etc. PDFs must be converted to images.
|
| 54 |
+
image = Image.open(name_of_your_document).convert("RGB")
|
| 55 |
+
|
| 56 |
+
width, height = image.size
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
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).
|
| 60 |
+
|
| 61 |
+
- 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.
|
| 62 |
+
- At inference time, it's recommended to use the `generate` method to autoregressively generate text given a document image.
|
| 63 |
+
- 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.
|
| 64 |
+
- 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.
|
| 65 |
+
|
| 66 |
+
This model was contributed by [nielsr](https://huggingface.co/nielsr).
|
| 67 |
+
The original code can be found [here](https://github.com/microsoft/UDOP).
|
| 68 |
+
|
| 69 |
+
## Resources
|
| 70 |
+
|
| 71 |
+
A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with UDOP. If
|
| 72 |
+
you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll
|
| 73 |
+
review it! The resource should ideally demonstrate something new instead of duplicating an existing resource.
|
| 74 |
+
|
| 75 |
+
- Demo notebooks regarding UDOP can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/UDOP) that show how
|
| 76 |
+
to fine-tune UDOP on a custom dataset as well as inference. 🌎
|
| 77 |
+
- [Document question answering task guide](../tasks/document_question_answering)
|
| 78 |
+
|
| 79 |
+
## UdopConfig
|
| 80 |
+
|
| 81 |
+
[[autodoc]] UdopConfig
|
| 82 |
+
|
| 83 |
+
## UdopTokenizer
|
| 84 |
+
|
| 85 |
+
[[autodoc]] UdopTokenizer
|
| 86 |
+
- build_inputs_with_special_tokens
|
| 87 |
+
- get_special_tokens_mask
|
| 88 |
+
- create_token_type_ids_from_sequences
|
| 89 |
+
- save_vocabulary
|
| 90 |
+
|
| 91 |
+
## UdopTokenizerFast
|
| 92 |
+
|
| 93 |
+
[[autodoc]] UdopTokenizerFast
|
| 94 |
+
|
| 95 |
+
## UdopProcessor
|
| 96 |
+
|
| 97 |
+
[[autodoc]] UdopProcessor
|
| 98 |
+
- __call__
|
| 99 |
+
|
| 100 |
+
## UdopModel
|
| 101 |
+
|
| 102 |
+
[[autodoc]] UdopModel
|
| 103 |
+
- forward
|
| 104 |
+
|
| 105 |
+
## UdopForConditionalGeneration
|
| 106 |
+
|
| 107 |
+
[[autodoc]] UdopForConditionalGeneration
|
| 108 |
+
- forward
|
| 109 |
+
|
| 110 |
+
## UdopEncoderModel
|
| 111 |
+
|
| 112 |
+
[[autodoc]] UdopEncoderModel
|
| 113 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/ul2.md
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# UL2
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
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.
|
| 22 |
+
|
| 23 |
+
The abstract from the paper is the following:
|
| 24 |
+
|
| 25 |
+
*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.*
|
| 26 |
+
|
| 27 |
+
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).
|
| 28 |
+
|
| 29 |
+
## Usage tips
|
| 30 |
+
|
| 31 |
+
- 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.
|
| 32 |
+
- UL2 has the same architecture as [T5v1.1](t5v1.1) but uses the Gated-SiLU activation function instead of Gated-GELU.
|
| 33 |
+
- The authors release checkpoints of one architecture which can be seen [here](https://huggingface.co/google/ul2)
|
| 34 |
+
|
| 35 |
+
<Tip>
|
| 36 |
+
|
| 37 |
+
As UL2 has the same architecture as T5v1.1, refer to [T5's documentation page](t5) for API reference, tips, code examples and notebooks.
|
| 38 |
+
|
| 39 |
+
</Tip>
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/umt5.md
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# UMT5
|
| 18 |
+
|
| 19 |
+
<div class="flex flex-wrap space-x-1">
|
| 20 |
+
<a href="https://huggingface.co/models?filter=umt5">
|
| 21 |
+
<img alt="Models" src="https://img.shields.io/badge/All_model_pages-mt5-blueviolet">
|
| 22 |
+
</a>
|
| 23 |
+
<a href="https://huggingface.co/spaces/docs-demos/mt5-small-finetuned-arxiv-cs-finetuned-arxiv-cs-full">
|
| 24 |
+
<img alt="Spaces" src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue">
|
| 25 |
+
</a>
|
| 26 |
+
</div>
|
| 27 |
+
|
| 28 |
+
## Overview
|
| 29 |
+
|
| 30 |
+
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.
|
| 31 |
+
|
| 32 |
+
The abstract from the paper is the following:
|
| 33 |
+
|
| 34 |
+
*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.*
|
| 35 |
+
|
| 36 |
+
Google has released the following variants:
|
| 37 |
+
|
| 38 |
+
- [google/umt5-small](https://huggingface.co/google/umt5-small)
|
| 39 |
+
- [google/umt5-base](https://huggingface.co/google/umt5-base)
|
| 40 |
+
- [google/umt5-xl](https://huggingface.co/google/umt5-xl)
|
| 41 |
+
- [google/umt5-xxl](https://huggingface.co/google/umt5-xxl).
|
| 42 |
+
|
| 43 |
+
This model was contributed by [agemagician](https://huggingface.co/agemagician) and [stefan-it](https://huggingface.co/stefan-it). The original code can be
|
| 44 |
+
found [here](https://github.com/google-research/t5x).
|
| 45 |
+
|
| 46 |
+
## Usage tips
|
| 47 |
+
|
| 48 |
+
- UMT5 was only pre-trained on [mC4](https://huggingface.co/datasets/mc4) excluding any supervised training.
|
| 49 |
+
Therefore, this model has to be fine-tuned before it is usable on a downstream task, unlike the original T5 model.
|
| 50 |
+
- Since umT5 was pre-trained in an unsupervised manner, there's no real advantage to using a task prefix during single-task
|
| 51 |
+
fine-tuning. If you are doing multi-task fine-tuning, you should use a prefix.
|
| 52 |
+
|
| 53 |
+
## Differences with mT5?
|
| 54 |
+
`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.
|
| 55 |
+
The conversion script is also different because the model was saved in t5x's latest checkpointing format.
|
| 56 |
+
|
| 57 |
+
# Sample usage
|
| 58 |
+
|
| 59 |
+
```python
|
| 60 |
+
>>> from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
|
| 61 |
+
|
| 62 |
+
>>> model = AutoModelForSeq2SeqLM.from_pretrained("google/umt5-small")
|
| 63 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/umt5-small")
|
| 64 |
+
|
| 65 |
+
>>> inputs = tokenizer(
|
| 66 |
+
... "A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.",
|
| 67 |
+
... return_tensors="pt",
|
| 68 |
+
... )
|
| 69 |
+
>>> outputs = model.generate(**inputs)
|
| 70 |
+
>>> print(tokenizer.batch_decode(outputs))
|
| 71 |
+
['<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s>']
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
<Tip>
|
| 75 |
+
|
| 76 |
+
Refer to [T5's documentation page](t5) for more tips, code examples and notebooks.
|
| 77 |
+
</Tip>
|
| 78 |
+
|
| 79 |
+
## UMT5Config
|
| 80 |
+
|
| 81 |
+
[[autodoc]] UMT5Config
|
| 82 |
+
|
| 83 |
+
## UMT5Model
|
| 84 |
+
|
| 85 |
+
[[autodoc]] UMT5Model
|
| 86 |
+
- forward
|
| 87 |
+
|
| 88 |
+
## UMT5ForConditionalGeneration
|
| 89 |
+
|
| 90 |
+
[[autodoc]] UMT5ForConditionalGeneration
|
| 91 |
+
- forward
|
| 92 |
+
|
| 93 |
+
## UMT5EncoderModel
|
| 94 |
+
|
| 95 |
+
[[autodoc]] UMT5EncoderModel
|
| 96 |
+
- forward
|
| 97 |
+
|
| 98 |
+
## UMT5ForSequenceClassification
|
| 99 |
+
|
| 100 |
+
[[autodoc]] UMT5ForSequenceClassification
|
| 101 |
+
- forward
|
| 102 |
+
|
| 103 |
+
## UMT5ForTokenClassification
|
| 104 |
+
|
| 105 |
+
[[autodoc]] UMT5ForTokenClassification
|
| 106 |
+
- forward
|
| 107 |
+
|
| 108 |
+
## UMT5ForQuestionAnswering
|
| 109 |
+
|
| 110 |
+
[[autodoc]] UMT5ForQuestionAnswering
|
| 111 |
+
- forward
|
| 112 |
+
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/unispeech-sat.md
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2021 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# UniSpeech-SAT
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
The UniSpeech-SAT model was proposed in [UniSpeech-SAT: Universal Speech Representation Learning with Speaker Aware
|
| 22 |
+
Pre-Training](https://arxiv.org/abs/2110.05752) by Sanyuan Chen, Yu Wu, Chengyi Wang, Zhengyang Chen, Zhuo Chen,
|
| 23 |
+
Shujie Liu, Jian Wu, Yao Qian, Furu Wei, Jinyu Li, Xiangzhan Yu .
|
| 24 |
+
|
| 25 |
+
The abstract from the paper is the following:
|
| 26 |
+
|
| 27 |
+
*Self-supervised learning (SSL) is a long-standing goal for speech processing, since it utilizes large-scale unlabeled
|
| 28 |
+
data and avoids extensive human labeling. Recent years witness great successes in applying self-supervised learning in
|
| 29 |
+
speech recognition, while limited exploration was attempted in applying SSL for modeling speaker characteristics. In
|
| 30 |
+
this paper, we aim to improve the existing SSL framework for speaker representation learning. Two methods are
|
| 31 |
+
introduced for enhancing the unsupervised speaker information extraction. First, we apply the multi-task learning to
|
| 32 |
+
the current SSL framework, where we integrate the utterance-wise contrastive loss with the SSL objective function.
|
| 33 |
+
Second, for better speaker discrimination, we propose an utterance mixing strategy for data augmentation, where
|
| 34 |
+
additional overlapped utterances are created unsupervisedly and incorporate during training. We integrate the proposed
|
| 35 |
+
methods into the HuBERT framework. Experiment results on SUPERB benchmark show that the proposed system achieves
|
| 36 |
+
state-of-the-art performance in universal representation learning, especially for speaker identification oriented
|
| 37 |
+
tasks. An ablation study is performed verifying the efficacy of each proposed method. Finally, we scale up training
|
| 38 |
+
dataset to 94 thousand hours public audio data and achieve further performance improvement in all SUPERB tasks.*
|
| 39 |
+
|
| 40 |
+
This model was contributed by [patrickvonplaten](https://huggingface.co/patrickvonplaten). The Authors' code can be
|
| 41 |
+
found [here](https://github.com/microsoft/UniSpeech/tree/main/UniSpeech-SAT).
|
| 42 |
+
|
| 43 |
+
## Usage tips
|
| 44 |
+
|
| 45 |
+
- UniSpeechSat is a speech model that accepts a float array corresponding to the raw waveform of the speech signal.
|
| 46 |
+
Please use [`Wav2Vec2Processor`] for the feature extraction.
|
| 47 |
+
- UniSpeechSat model can be fine-tuned using connectionist temporal classification (CTC) so the model output has to be
|
| 48 |
+
decoded using [`Wav2Vec2CTCTokenizer`].
|
| 49 |
+
- UniSpeechSat performs especially well on speaker verification, speaker identification, and speaker diarization tasks.
|
| 50 |
+
|
| 51 |
+
## Resources
|
| 52 |
+
|
| 53 |
+
- [Audio classification task guide](../tasks/audio_classification)
|
| 54 |
+
- [Automatic speech recognition task guide](../tasks/asr)
|
| 55 |
+
|
| 56 |
+
## UniSpeechSatConfig
|
| 57 |
+
|
| 58 |
+
[[autodoc]] UniSpeechSatConfig
|
| 59 |
+
|
| 60 |
+
## UniSpeechSat specific outputs
|
| 61 |
+
|
| 62 |
+
[[autodoc]] models.unispeech_sat.modeling_unispeech_sat.UniSpeechSatForPreTrainingOutput
|
| 63 |
+
|
| 64 |
+
## UniSpeechSatModel
|
| 65 |
+
|
| 66 |
+
[[autodoc]] UniSpeechSatModel
|
| 67 |
+
- forward
|
| 68 |
+
|
| 69 |
+
## UniSpeechSatForCTC
|
| 70 |
+
|
| 71 |
+
[[autodoc]] UniSpeechSatForCTC
|
| 72 |
+
- forward
|
| 73 |
+
|
| 74 |
+
## UniSpeechSatForSequenceClassification
|
| 75 |
+
|
| 76 |
+
[[autodoc]] UniSpeechSatForSequenceClassification
|
| 77 |
+
- forward
|
| 78 |
+
|
| 79 |
+
## UniSpeechSatForAudioFrameClassification
|
| 80 |
+
|
| 81 |
+
[[autodoc]] UniSpeechSatForAudioFrameClassification
|
| 82 |
+
- forward
|
| 83 |
+
|
| 84 |
+
## UniSpeechSatForXVector
|
| 85 |
+
|
| 86 |
+
[[autodoc]] UniSpeechSatForXVector
|
| 87 |
+
- forward
|
| 88 |
+
|
| 89 |
+
## UniSpeechSatForPreTraining
|
| 90 |
+
|
| 91 |
+
[[autodoc]] UniSpeechSatForPreTraining
|
| 92 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/unispeech.md
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2021 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# UniSpeech
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
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
|
| 22 |
+
Zeng, Xuedong Huang .
|
| 23 |
+
|
| 24 |
+
The abstract from the paper is the following:
|
| 25 |
+
|
| 26 |
+
*In this paper, we propose a unified pre-training approach called UniSpeech to learn speech representations with both
|
| 27 |
+
unlabeled and labeled data, in which supervised phonetic CTC learning and phonetically-aware contrastive
|
| 28 |
+
self-supervised learning are conducted in a multi-task learning manner. The resultant representations can capture
|
| 29 |
+
information more correlated with phonetic structures and improve the generalization across languages and domains. We
|
| 30 |
+
evaluate the effectiveness of UniSpeech for cross-lingual representation learning on public CommonVoice corpus. The
|
| 31 |
+
results show that UniSpeech outperforms self-supervised pretraining and supervised transfer learning for speech
|
| 32 |
+
recognition by a maximum of 13.4% and 17.8% relative phone error rate reductions respectively (averaged over all
|
| 33 |
+
testing languages). The transferability of UniSpeech is also demonstrated on a domain-shift speech recognition task,
|
| 34 |
+
i.e., a relative word error rate reduction of 6% against the previous approach.*
|
| 35 |
+
|
| 36 |
+
This model was contributed by [patrickvonplaten](https://huggingface.co/patrickvonplaten). The Authors' code can be
|
| 37 |
+
found [here](https://github.com/microsoft/UniSpeech/tree/main/UniSpeech).
|
| 38 |
+
|
| 39 |
+
## Usage tips
|
| 40 |
+
|
| 41 |
+
- UniSpeech is a speech model that accepts a float array corresponding to the raw waveform of the speech signal. Please
|
| 42 |
+
use [`Wav2Vec2Processor`] for the feature extraction.
|
| 43 |
+
- UniSpeech model can be fine-tuned using connectionist temporal classification (CTC) so the model output has to be
|
| 44 |
+
decoded using [`Wav2Vec2CTCTokenizer`].
|
| 45 |
+
|
| 46 |
+
## Resources
|
| 47 |
+
|
| 48 |
+
- [Audio classification task guide](../tasks/audio_classification)
|
| 49 |
+
- [Automatic speech recognition task guide](../tasks/asr)
|
| 50 |
+
|
| 51 |
+
## UniSpeechConfig
|
| 52 |
+
|
| 53 |
+
[[autodoc]] UniSpeechConfig
|
| 54 |
+
|
| 55 |
+
## UniSpeech specific outputs
|
| 56 |
+
|
| 57 |
+
[[autodoc]] models.unispeech.modeling_unispeech.UniSpeechForPreTrainingOutput
|
| 58 |
+
|
| 59 |
+
## UniSpeechModel
|
| 60 |
+
|
| 61 |
+
[[autodoc]] UniSpeechModel
|
| 62 |
+
- forward
|
| 63 |
+
|
| 64 |
+
## UniSpeechForCTC
|
| 65 |
+
|
| 66 |
+
[[autodoc]] UniSpeechForCTC
|
| 67 |
+
- forward
|
| 68 |
+
|
| 69 |
+
## UniSpeechForSequenceClassification
|
| 70 |
+
|
| 71 |
+
[[autodoc]] UniSpeechForSequenceClassification
|
| 72 |
+
- forward
|
| 73 |
+
|
| 74 |
+
## UniSpeechForPreTraining
|
| 75 |
+
|
| 76 |
+
[[autodoc]] UniSpeechForPreTraining
|
| 77 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/univnet.md
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# UnivNet
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
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.
|
| 22 |
+
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.
|
| 23 |
+
|
| 24 |
+
The abstract from the paper is the following:
|
| 25 |
+
|
| 26 |
+
*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.*
|
| 27 |
+
|
| 28 |
+
Tips:
|
| 29 |
+
|
| 30 |
+
- 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.)
|
| 31 |
+
- Padding added by [`UnivNetFeatureExtractor`] can be removed from the [`UnivNetModel`] output through the [`UnivNetFeatureExtractor.batch_decode`] method, as shown in the usage example below.
|
| 32 |
+
- 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.
|
| 33 |
+
|
| 34 |
+
Usage Example:
|
| 35 |
+
|
| 36 |
+
```python
|
| 37 |
+
import torch
|
| 38 |
+
from scipy.io.wavfile import write
|
| 39 |
+
from datasets import Audio, load_dataset
|
| 40 |
+
|
| 41 |
+
from transformers import UnivNetFeatureExtractor, UnivNetModel
|
| 42 |
+
|
| 43 |
+
model_id_or_path = "dg845/univnet-dev"
|
| 44 |
+
model = UnivNetModel.from_pretrained(model_id_or_path)
|
| 45 |
+
feature_extractor = UnivNetFeatureExtractor.from_pretrained(model_id_or_path)
|
| 46 |
+
|
| 47 |
+
ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
|
| 48 |
+
# Resample the audio to the model and feature extractor's sampling rate.
|
| 49 |
+
ds = ds.cast_column("audio", Audio(sampling_rate=feature_extractor.sampling_rate))
|
| 50 |
+
# Pad the end of the converted waveforms to reduce artifacts at the end of the output audio samples.
|
| 51 |
+
inputs = feature_extractor(
|
| 52 |
+
ds[0]["audio"]["array"], sampling_rate=ds[0]["audio"]["sampling_rate"], pad_end=True, return_tensors="pt"
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
with torch.no_grad():
|
| 56 |
+
audio = model(**inputs)
|
| 57 |
+
|
| 58 |
+
# Remove the extra padding at the end of the output.
|
| 59 |
+
audio = feature_extractor.batch_decode(**audio)[0]
|
| 60 |
+
# Convert to wav file
|
| 61 |
+
write("sample_audio.wav", feature_extractor.sampling_rate, audio)
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
This model was contributed by [dg845](https://huggingface.co/dg845).
|
| 65 |
+
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).
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
## UnivNetConfig
|
| 69 |
+
|
| 70 |
+
[[autodoc]] UnivNetConfig
|
| 71 |
+
|
| 72 |
+
## UnivNetFeatureExtractor
|
| 73 |
+
|
| 74 |
+
[[autodoc]] UnivNetFeatureExtractor
|
| 75 |
+
- __call__
|
| 76 |
+
|
| 77 |
+
## UnivNetModel
|
| 78 |
+
|
| 79 |
+
[[autodoc]] UnivNetModel
|
| 80 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/upernet.md
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# UPerNet
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
The UPerNet model was proposed in [Unified Perceptual Parsing for Scene Understanding](https://arxiv.org/abs/1807.10221)
|
| 22 |
+
by Tete Xiao, Yingcheng Liu, Bolei Zhou, Yuning Jiang, Jian Sun. UPerNet is a general framework to effectively segment
|
| 23 |
+
a wide range of concepts from images, leveraging any vision backbone like [ConvNeXt](convnext) or [Swin](swin).
|
| 24 |
+
|
| 25 |
+
The abstract from the paper is the following:
|
| 26 |
+
|
| 27 |
+
*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.*
|
| 28 |
+
|
| 29 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/upernet_architecture.jpg"
|
| 30 |
+
alt="drawing" width="600"/>
|
| 31 |
+
|
| 32 |
+
<small> UPerNet framework. Taken from the <a href="https://arxiv.org/abs/1807.10221">original paper</a>. </small>
|
| 33 |
+
|
| 34 |
+
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).
|
| 35 |
+
|
| 36 |
+
## Usage examples
|
| 37 |
+
|
| 38 |
+
UPerNet is a general framework for semantic segmentation. It can be used with any vision backbone, like so:
|
| 39 |
+
|
| 40 |
+
```py
|
| 41 |
+
from transformers import SwinConfig, UperNetConfig, UperNetForSemanticSegmentation
|
| 42 |
+
|
| 43 |
+
backbone_config = SwinConfig(out_features=["stage1", "stage2", "stage3", "stage4"])
|
| 44 |
+
|
| 45 |
+
config = UperNetConfig(backbone_config=backbone_config)
|
| 46 |
+
model = UperNetForSemanticSegmentation(config)
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
To use another vision backbone, like [ConvNeXt](convnext), simply instantiate the model with the appropriate backbone:
|
| 50 |
+
|
| 51 |
+
```py
|
| 52 |
+
from transformers import ConvNextConfig, UperNetConfig, UperNetForSemanticSegmentation
|
| 53 |
+
|
| 54 |
+
backbone_config = ConvNextConfig(out_features=["stage1", "stage2", "stage3", "stage4"])
|
| 55 |
+
|
| 56 |
+
config = UperNetConfig(backbone_config=backbone_config)
|
| 57 |
+
model = UperNetForSemanticSegmentation(config)
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
Note that this will randomly initialize all the weights of the model.
|
| 61 |
+
|
| 62 |
+
## Resources
|
| 63 |
+
|
| 64 |
+
A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with UPerNet.
|
| 65 |
+
|
| 66 |
+
- Demo notebooks for UPerNet can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/UPerNet).
|
| 67 |
+
- [`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).
|
| 68 |
+
- See also: [Semantic segmentation task guide](../tasks/semantic_segmentation)
|
| 69 |
+
|
| 70 |
+
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.
|
| 71 |
+
|
| 72 |
+
## UperNetConfig
|
| 73 |
+
|
| 74 |
+
[[autodoc]] UperNetConfig
|
| 75 |
+
|
| 76 |
+
## UperNetForSemanticSegmentation
|
| 77 |
+
|
| 78 |
+
[[autodoc]] UperNetForSemanticSegmentation
|
| 79 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/van.md
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# VAN
|
| 18 |
+
|
| 19 |
+
<Tip warning={true}>
|
| 20 |
+
|
| 21 |
+
This model is in maintenance mode only, we don't accept any new PRs changing its code.
|
| 22 |
+
|
| 23 |
+
If you run into any issues running this model, please reinstall the last version that supported this model: v4.30.0.
|
| 24 |
+
You can do so by running the following command: `pip install -U transformers==4.30.0`.
|
| 25 |
+
|
| 26 |
+
</Tip>
|
| 27 |
+
|
| 28 |
+
## Overview
|
| 29 |
+
|
| 30 |
+
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.
|
| 31 |
+
|
| 32 |
+
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.
|
| 33 |
+
|
| 34 |
+
The abstract from the paper is the following:
|
| 35 |
+
|
| 36 |
+
*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).*
|
| 37 |
+
|
| 38 |
+
Tips:
|
| 39 |
+
|
| 40 |
+
- VAN does not have an embedding layer, thus the `hidden_states` will have a length equal to the number of stages.
|
| 41 |
+
|
| 42 |
+
The figure below illustrates the architecture of a Visual Attention Layer. Taken from the [original paper](https://arxiv.org/abs/2202.09741).
|
| 43 |
+
|
| 44 |
+
<img width="600" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/van_architecture.png"/>
|
| 45 |
+
|
| 46 |
+
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).
|
| 47 |
+
|
| 48 |
+
## Resources
|
| 49 |
+
|
| 50 |
+
A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with VAN.
|
| 51 |
+
|
| 52 |
+
<PipelineTag pipeline="image-classification"/>
|
| 53 |
+
|
| 54 |
+
- [`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).
|
| 55 |
+
- See also: [Image classification task guide](../tasks/image_classification)
|
| 56 |
+
|
| 57 |
+
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.
|
| 58 |
+
|
| 59 |
+
## VanConfig
|
| 60 |
+
|
| 61 |
+
[[autodoc]] VanConfig
|
| 62 |
+
|
| 63 |
+
## VanModel
|
| 64 |
+
|
| 65 |
+
[[autodoc]] VanModel
|
| 66 |
+
- forward
|
| 67 |
+
|
| 68 |
+
## VanForImageClassification
|
| 69 |
+
|
| 70 |
+
[[autodoc]] VanForImageClassification
|
| 71 |
+
- forward
|
| 72 |
+
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/video_llava.md
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Video-LLaVA
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
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.
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
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.
|
| 25 |
+
|
| 26 |
+
The abstract from the paper is the following:
|
| 27 |
+
|
| 28 |
+
*The Large Vision-Language Model (LVLM) has enhanced the performance of various downstream tasks in
|
| 29 |
+
visual-language understanding. Most existing approaches
|
| 30 |
+
encode images and videos into separate feature spaces,
|
| 31 |
+
which are then fed as inputs to large language models.
|
| 32 |
+
However, due to the lack of unified tokenization for images and videos, namely misalignment before projection, it
|
| 33 |
+
becomes challenging for a Large Language Model (LLM)
|
| 34 |
+
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,
|
| 35 |
+
which learns from a mixed dataset of images and videos,
|
| 36 |
+
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
|
| 37 |
+
image benchmark toolkits. Additionally, our Video-LLaVA
|
| 38 |
+
also outperforms Video-ChatGPT by 5.8%, 9.9%, 18.6%,
|
| 39 |
+
and 10.1% on MSRVTT, MSVD, TGIF, and ActivityNet, respectively. Notably, extensive experiments demonstrate that
|
| 40 |
+
Video-LLaVA mutually benefits images and videos within
|
| 41 |
+
a unified visual representation, outperforming models designed specifically for images or videos. We aim for this
|
| 42 |
+
work to provide modest insights into the multi-modal inputs
|
| 43 |
+
for the LLM*
|
| 44 |
+
|
| 45 |
+
## Usage tips:
|
| 46 |
+
|
| 47 |
+
- 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.
|
| 48 |
+
|
| 49 |
+
- 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.
|
| 50 |
+
|
| 51 |
+
- Note that the video inputs should have exactly 8 frames at the input, since the models were trained in that setting.
|
| 52 |
+
|
| 53 |
+
This model was contributed by [RaushanTurganbay](https://huggingface.co/RaushanTurganbay).
|
| 54 |
+
The original code can be found [here](https://github.com/PKU-YuanGroup/Video-LLaVA).
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
> [!NOTE]
|
| 58 |
+
> 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.
|
| 59 |
+
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 `<image>` 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.
|
| 60 |
+
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.
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
## Usage example
|
| 64 |
+
|
| 65 |
+
### Single Media Mode
|
| 66 |
+
|
| 67 |
+
The model can accept both images and videos as input. Here's an example code for inference in half-precision (`torch.float16`):
|
| 68 |
+
|
| 69 |
+
```python
|
| 70 |
+
import av
|
| 71 |
+
import torch
|
| 72 |
+
import numpy as np
|
| 73 |
+
from transformers import VideoLlavaForConditionalGeneration, VideoLlavaProcessor
|
| 74 |
+
|
| 75 |
+
def read_video_pyav(container, indices):
|
| 76 |
+
'''
|
| 77 |
+
Decode the video with PyAV decoder.
|
| 78 |
+
Args:
|
| 79 |
+
container (`av.container.input.InputContainer`): PyAV container.
|
| 80 |
+
indices (`List[int]`): List of frame indices to decode.
|
| 81 |
+
Returns:
|
| 82 |
+
result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
|
| 83 |
+
'''
|
| 84 |
+
frames = []
|
| 85 |
+
container.seek(0)
|
| 86 |
+
start_index = indices[0]
|
| 87 |
+
end_index = indices[-1]
|
| 88 |
+
for i, frame in enumerate(container.decode(video=0)):
|
| 89 |
+
if i > end_index:
|
| 90 |
+
break
|
| 91 |
+
if i >= start_index and i in indices:
|
| 92 |
+
frames.append(frame)
|
| 93 |
+
return np.stack([x.to_ndarray(format="rgb24") for x in frames])
|
| 94 |
+
|
| 95 |
+
# Load the model in half-precision
|
| 96 |
+
model = VideoLlavaForConditionalGeneration.from_pretrained("LanguageBind/Video-LLaVA-7B-hf", torch_dtype=torch.float16, device_map="auto")
|
| 97 |
+
processor = VideoLlavaProcessor.from_pretrained("LanguageBind/Video-LLaVA-7B-hf")
|
| 98 |
+
|
| 99 |
+
# Load the video as an np.arrau, sampling uniformly 8 frames
|
| 100 |
+
video_path = hf_hub_download(repo_id="raushan-testing-hf/videos-test", filename="sample_demo_1.mp4", repo_type="dataset")
|
| 101 |
+
container = av.open(video_path)
|
| 102 |
+
total_frames = container.streams.video[0].frames
|
| 103 |
+
indices = np.arange(0, total_frames, total_frames / 8).astype(int)
|
| 104 |
+
video = read_video_pyav(container, indices)
|
| 105 |
+
|
| 106 |
+
# For better results, we recommend to prompt the model in the following format
|
| 107 |
+
prompt = "USER: <video>\nWhy is this funny? ASSISTANT:"
|
| 108 |
+
inputs = processor(text=prompt, videos=video, return_tensors="pt")
|
| 109 |
+
|
| 110 |
+
out = model.generate(**inputs, max_new_tokens=60)
|
| 111 |
+
processor.batch_decode(out, skip_special_tokens=True, clean_up_tokenization_spaces=True)
|
| 112 |
+
```
|
| 113 |
+
|
| 114 |
+
For multiple turns conversation change the prompt format to:
|
| 115 |
+
|
| 116 |
+
```bash
|
| 117 |
+
"USER: <video>\nWhat do you see in this video? ASSISTANT: A baby reading a book. USER: Why is the it funny? ASSISTANT:"
|
| 118 |
+
```
|
| 119 |
+
|
| 120 |
+
### Mixed Media Mode
|
| 121 |
+
|
| 122 |
+
The model can also generate from an interleaved image-video inputs. However note, that it was not trained in interleaved image-video setting which might affect the performance. Below is an example usage for mixed media input, add the following lines to the above code snippet:
|
| 123 |
+
|
| 124 |
+
```python
|
| 125 |
+
from PIL import Image
|
| 126 |
+
import requests
|
| 127 |
+
|
| 128 |
+
# Generate from image and video mixed inputs
|
| 129 |
+
# Load and image and write a new prompt
|
| 130 |
+
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 131 |
+
image = Image.open(requests.get(url, stream=True).raw)
|
| 132 |
+
prompt = "USER: <image>\nHow many cats are there in the image? ASSISTANT: There are two cats. USER: <video>\nWhy is this video funny? ASSISTANT:"
|
| 133 |
+
|
| 134 |
+
inputs = processor(text=prompt, images=image, videos=clip, padding=True, return_tensors="pt")
|
| 135 |
+
|
| 136 |
+
# Generate
|
| 137 |
+
generate_ids = model.generate(**inputs, max_length=50)
|
| 138 |
+
processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)
|
| 139 |
+
|
| 140 |
+
```
|
| 141 |
+
|
| 142 |
+
## Model optimization
|
| 143 |
+
|
| 144 |
+
### Quantization using Bitsandbytes for memory efficiency
|
| 145 |
+
|
| 146 |
+
The model can be loaded in lower bits, significantly reducing memory burden while maintaining the performance of the original model. his allows for efficient deployment on resource-constrained cases.
|
| 147 |
+
|
| 148 |
+
First make sure to install bitsandbytes by running `pip install bitsandbytes` and to have access to a GPU/accelerator that is supported by the library.
|
| 149 |
+
|
| 150 |
+
<Tip>
|
| 151 |
+
|
| 152 |
+
bitsandbytes is being refactored to support multiple backends beyond CUDA. Currently, ROCm (AMD GPU) and Intel CPU implementations are mature, with Intel XPU in progress and Apple Silicon support expected by Q4/Q1. For installation instructions and the latest backend updates, visit [this link](https://huggingface.co/docs/bitsandbytes/main/en/installation#multi-backend).
|
| 153 |
+
|
| 154 |
+
We value your feedback to help identify bugs before the full release! Check out [these docs](https://huggingface.co/docs/bitsandbytes/main/en/non_cuda_backends) for more details and feedback links.
|
| 155 |
+
|
| 156 |
+
</Tip>
|
| 157 |
+
|
| 158 |
+
Load the quantized model by simply adding [`BitsAndBytesConfig`](../main_classes/quantization#transformers.BitsAndBytesConfig) as shown below:
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
```python
|
| 162 |
+
from transformers import VideoLlavaForConditionalGeneration, BitsAndBytesConfig
|
| 163 |
+
|
| 164 |
+
# specify how to quantize the model
|
| 165 |
+
quantization_config = BitsAndBytesConfig(
|
| 166 |
+
load_in_4bit=True,
|
| 167 |
+
bnb_4bit_quant_type="nf4",
|
| 168 |
+
bnb_4bit_compute_dtype=torch.float16,
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
model = VideoLlavaForConditionalGeneration.from_pretrained("LanguageBind/Video-LLaVA-7B-hf", quantization_config=quantization_config, device_map="auto")
|
| 172 |
+
```
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
### Flash-Attention 2 to speed-up generation
|
| 176 |
+
|
| 177 |
+
Additionally, we can greatly speed-up model inference by using [Flash Attention](../perf_train_gpu_one#flash-attention-2), which is a faster implementation of the attention mechanism used inside the model.
|
| 178 |
+
|
| 179 |
+
First, make sure to install the latest version of Flash Attention 2:
|
| 180 |
+
|
| 181 |
+
```bash
|
| 182 |
+
pip install -U flash-attn --no-build-isolation
|
| 183 |
+
```
|
| 184 |
+
|
| 185 |
+
Also, you should have a hardware that is compatible with Flash-Attention 2. Read more about it in the official documentation of the [flash attention repository](https://github.com/Dao-AILab/flash-attention). FlashAttention-2 can only be used when a model is loaded in `torch.float16` or `torch.bfloat16`.
|
| 186 |
+
|
| 187 |
+
To load and run a model using Flash Attention-2, simply add `attn_implementation="flash_attention_2"` when loading the model as follows:
|
| 188 |
+
|
| 189 |
+
```python
|
| 190 |
+
from transformers import VideoLlavaForConditionalGeneration
|
| 191 |
+
|
| 192 |
+
model = VideoLlavaForConditionalGeneration.from_pretrained(
|
| 193 |
+
"LanguageBind/Video-LLaVA-7B-hf",
|
| 194 |
+
torch_dtype=torch.float16,
|
| 195 |
+
attn_implementation="flash_attention_2",
|
| 196 |
+
).to(0)
|
| 197 |
+
```
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
## VideoLlavaConfig
|
| 201 |
+
|
| 202 |
+
[[autodoc]] VideoLlavaConfig
|
| 203 |
+
|
| 204 |
+
## VideoLlavaImageProcessor
|
| 205 |
+
|
| 206 |
+
[[autodoc]] VideoLlavaImageProcessor
|
| 207 |
+
|
| 208 |
+
## VideoLlavaProcessor
|
| 209 |
+
|
| 210 |
+
[[autodoc]] VideoLlavaProcessor
|
| 211 |
+
|
| 212 |
+
## VideoLlavaForConditionalGeneration
|
| 213 |
+
|
| 214 |
+
[[autodoc]] VideoLlavaForConditionalGeneration
|
| 215 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/videomae.md
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# VideoMAE
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
The VideoMAE model was proposed in [VideoMAE: Masked Autoencoders are Data-Efficient Learners for Self-Supervised Video Pre-Training](https://arxiv.org/abs/2203.12602) by Zhan Tong, Yibing Song, Jue Wang, Limin Wang.
|
| 22 |
+
VideoMAE extends masked auto encoders ([MAE](vit_mae)) to video, claiming state-of-the-art performance on several video classification benchmarks.
|
| 23 |
+
|
| 24 |
+
The abstract from the paper is the following:
|
| 25 |
+
|
| 26 |
+
*Pre-training video transformers on extra large-scale datasets is generally required to achieve premier performance on relatively small datasets. In this paper, we show that video masked autoencoders (VideoMAE) are data-efficient learners for self-supervised video pre-training (SSVP). We are inspired by the recent ImageMAE and propose customized video tube masking and reconstruction. These simple designs turn out to be effective for overcoming information leakage caused by the temporal correlation during video reconstruction. We obtain three important findings on SSVP: (1) An extremely high proportion of masking ratio (i.e., 90% to 95%) still yields favorable performance of VideoMAE. The temporally redundant video content enables higher masking ratio than that of images. (2) VideoMAE achieves impressive results on very small datasets (i.e., around 3k-4k videos) without using any extra data. This is partially ascribed to the challenging task of video reconstruction to enforce high-level structure learning. (3) VideoMAE shows that data quality is more important than data quantity for SSVP. Domain shift between pre-training and target datasets are important issues in SSVP. Notably, our VideoMAE with the vanilla ViT backbone can achieve 83.9% on Kinects-400, 75.3% on Something-Something V2, 90.8% on UCF101, and 61.1% on HMDB51 without using any extra data.*
|
| 27 |
+
|
| 28 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/videomae_architecture.jpeg"
|
| 29 |
+
alt="drawing" width="600"/>
|
| 30 |
+
|
| 31 |
+
<small> VideoMAE pre-training. Taken from the <a href="https://arxiv.org/abs/2203.12602">original paper</a>. </small>
|
| 32 |
+
|
| 33 |
+
This model was contributed by [nielsr](https://huggingface.co/nielsr).
|
| 34 |
+
The original code can be found [here](https://github.com/MCG-NJU/VideoMAE).
|
| 35 |
+
|
| 36 |
+
## Using Scaled Dot Product Attention (SDPA)
|
| 37 |
+
|
| 38 |
+
PyTorch includes a native scaled dot-product attention (SDPA) operator as part of `torch.nn.functional`. This function
|
| 39 |
+
encompasses several implementations that can be applied depending on the inputs and the hardware in use. See the
|
| 40 |
+
[official documentation](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html)
|
| 41 |
+
or the [GPU Inference](https://huggingface.co/docs/transformers/main/en/perf_infer_gpu_one#pytorch-scaled-dot-product-attention)
|
| 42 |
+
page for more information.
|
| 43 |
+
|
| 44 |
+
SDPA is used by default for `torch>=2.1.1` when an implementation is available, but you may also set
|
| 45 |
+
`attn_implementation="sdpa"` in `from_pretrained()` to explicitly request SDPA to be used.
|
| 46 |
+
|
| 47 |
+
```
|
| 48 |
+
from transformers import VideoMAEForVideoClassification
|
| 49 |
+
model = VideoMAEForVideoClassification.from_pretrained("MCG-NJU/videomae-base-finetuned-kinetics", attn_implementation="sdpa", torch_dtype=torch.float16)
|
| 50 |
+
...
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
For the best speedups, we recommend loading the model in half-precision (e.g. `torch.float16` or `torch.bfloat16`).
|
| 54 |
+
|
| 55 |
+
On a local benchmark (A100-40GB, PyTorch 2.3.0, OS Ubuntu 22.04) with `float32` and `MCG-NJU/videomae-base-finetuned-kinetics` model, we saw the following speedups during inference.
|
| 56 |
+
|
| 57 |
+
| Batch size | Average inference time (ms), eager mode | Average inference time (ms), sdpa model | Speed up, Sdpa / Eager (x) |
|
| 58 |
+
|--------------|-------------------------------------------|-------------------------------------------|------------------------------|
|
| 59 |
+
| 1 | 37 | 10 | 3.7 |
|
| 60 |
+
| 2 | 24 | 18 | 1.33 |
|
| 61 |
+
| 4 | 43 | 32 | 1.34 |
|
| 62 |
+
| 8 | 84 | 60 | 1.4 |
|
| 63 |
+
|
| 64 |
+
## Resources
|
| 65 |
+
|
| 66 |
+
A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with VideoMAE. If
|
| 67 |
+
you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll
|
| 68 |
+
review it! The resource should ideally demonstrate something new instead of duplicating an existing resource.
|
| 69 |
+
|
| 70 |
+
**Video classification**
|
| 71 |
+
- [A notebook](https://github.com/huggingface/notebooks/blob/main/examples/video_classification.ipynb) that shows how
|
| 72 |
+
to fine-tune a VideoMAE model on a custom dataset.
|
| 73 |
+
- [Video classification task guide](../tasks/video_classification)
|
| 74 |
+
- [A 🤗 Space](https://huggingface.co/spaces/sayakpaul/video-classification-ucf101-subset) showing how to perform inference with a video classification model.
|
| 75 |
+
|
| 76 |
+
## VideoMAEConfig
|
| 77 |
+
|
| 78 |
+
[[autodoc]] VideoMAEConfig
|
| 79 |
+
|
| 80 |
+
## VideoMAEFeatureExtractor
|
| 81 |
+
|
| 82 |
+
[[autodoc]] VideoMAEFeatureExtractor
|
| 83 |
+
- __call__
|
| 84 |
+
|
| 85 |
+
## VideoMAEImageProcessor
|
| 86 |
+
|
| 87 |
+
[[autodoc]] VideoMAEImageProcessor
|
| 88 |
+
- preprocess
|
| 89 |
+
|
| 90 |
+
## VideoMAEModel
|
| 91 |
+
|
| 92 |
+
[[autodoc]] VideoMAEModel
|
| 93 |
+
- forward
|
| 94 |
+
|
| 95 |
+
## VideoMAEForPreTraining
|
| 96 |
+
|
| 97 |
+
`VideoMAEForPreTraining` includes the decoder on top for self-supervised pre-training.
|
| 98 |
+
|
| 99 |
+
[[autodoc]] transformers.VideoMAEForPreTraining
|
| 100 |
+
- forward
|
| 101 |
+
|
| 102 |
+
## VideoMAEForVideoClassification
|
| 103 |
+
|
| 104 |
+
[[autodoc]] transformers.VideoMAEForVideoClassification
|
| 105 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/vilt.md
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2021 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# ViLT
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
The ViLT model was proposed in [ViLT: Vision-and-Language Transformer Without Convolution or Region Supervision](https://arxiv.org/abs/2102.03334)
|
| 22 |
+
by Wonjae Kim, Bokyung Son, Ildoo Kim. ViLT incorporates text embeddings into a Vision Transformer (ViT), allowing it to have a minimal design
|
| 23 |
+
for Vision-and-Language Pre-training (VLP).
|
| 24 |
+
|
| 25 |
+
The abstract from the paper is the following:
|
| 26 |
+
|
| 27 |
+
*Vision-and-Language Pre-training (VLP) has improved performance on various joint vision-and-language downstream tasks.
|
| 28 |
+
Current approaches to VLP heavily rely on image feature extraction processes, most of which involve region supervision
|
| 29 |
+
(e.g., object detection) and the convolutional architecture (e.g., ResNet). Although disregarded in the literature, we
|
| 30 |
+
find it problematic in terms of both (1) efficiency/speed, that simply extracting input features requires much more
|
| 31 |
+
computation than the multimodal interaction steps; and (2) expressive power, as it is upper bounded to the expressive
|
| 32 |
+
power of the visual embedder and its predefined visual vocabulary. In this paper, we present a minimal VLP model,
|
| 33 |
+
Vision-and-Language Transformer (ViLT), monolithic in the sense that the processing of visual inputs is drastically
|
| 34 |
+
simplified to just the same convolution-free manner that we process textual inputs. We show that ViLT is up to tens of
|
| 35 |
+
times faster than previous VLP models, yet with competitive or better downstream task performance.*
|
| 36 |
+
|
| 37 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/vilt_architecture.jpg"
|
| 38 |
+
alt="drawing" width="600"/>
|
| 39 |
+
|
| 40 |
+
<small> ViLT architecture. Taken from the <a href="https://arxiv.org/abs/2102.03334">original paper</a>. </small>
|
| 41 |
+
|
| 42 |
+
This model was contributed by [nielsr](https://huggingface.co/nielsr). The original code can be found [here](https://github.com/dandelin/ViLT).
|
| 43 |
+
|
| 44 |
+
## Usage tips
|
| 45 |
+
|
| 46 |
+
- The quickest way to get started with ViLT is by checking the [example notebooks](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/ViLT)
|
| 47 |
+
(which showcase both inference and fine-tuning on custom data).
|
| 48 |
+
- ViLT is a model that takes both `pixel_values` and `input_ids` as input. One can use [`ViltProcessor`] to prepare data for the model.
|
| 49 |
+
This processor wraps a image processor (for the image modality) and a tokenizer (for the language modality) into one.
|
| 50 |
+
- ViLT is trained with images of various sizes: the authors resize the shorter edge of input images to 384 and limit the longer edge to
|
| 51 |
+
under 640 while preserving the aspect ratio. To make batching of images possible, the authors use a `pixel_mask` that indicates
|
| 52 |
+
which pixel values are real and which are padding. [`ViltProcessor`] automatically creates this for you.
|
| 53 |
+
- The design of ViLT is very similar to that of a standard Vision Transformer (ViT). The only difference is that the model includes
|
| 54 |
+
additional embedding layers for the language modality.
|
| 55 |
+
- The PyTorch version of this model is only available in torch 1.10 and higher.
|
| 56 |
+
|
| 57 |
+
## ViltConfig
|
| 58 |
+
|
| 59 |
+
[[autodoc]] ViltConfig
|
| 60 |
+
|
| 61 |
+
## ViltFeatureExtractor
|
| 62 |
+
|
| 63 |
+
[[autodoc]] ViltFeatureExtractor
|
| 64 |
+
- __call__
|
| 65 |
+
|
| 66 |
+
## ViltImageProcessor
|
| 67 |
+
|
| 68 |
+
[[autodoc]] ViltImageProcessor
|
| 69 |
+
- preprocess
|
| 70 |
+
|
| 71 |
+
## ViltProcessor
|
| 72 |
+
|
| 73 |
+
[[autodoc]] ViltProcessor
|
| 74 |
+
- __call__
|
| 75 |
+
|
| 76 |
+
## ViltModel
|
| 77 |
+
|
| 78 |
+
[[autodoc]] ViltModel
|
| 79 |
+
- forward
|
| 80 |
+
|
| 81 |
+
## ViltForMaskedLM
|
| 82 |
+
|
| 83 |
+
[[autodoc]] ViltForMaskedLM
|
| 84 |
+
- forward
|
| 85 |
+
|
| 86 |
+
## ViltForQuestionAnswering
|
| 87 |
+
|
| 88 |
+
[[autodoc]] ViltForQuestionAnswering
|
| 89 |
+
- forward
|
| 90 |
+
|
| 91 |
+
## ViltForImagesAndTextClassification
|
| 92 |
+
|
| 93 |
+
[[autodoc]] ViltForImagesAndTextClassification
|
| 94 |
+
- forward
|
| 95 |
+
|
| 96 |
+
## ViltForImageAndTextRetrieval
|
| 97 |
+
|
| 98 |
+
[[autodoc]] ViltForImageAndTextRetrieval
|
| 99 |
+
- forward
|
| 100 |
+
|
| 101 |
+
## ViltForTokenClassification
|
| 102 |
+
|
| 103 |
+
[[autodoc]] ViltForTokenClassification
|
| 104 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/vipllava.md
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# VipLlava
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
The VipLlava model was proposed in [Making Large Multimodal Models Understand Arbitrary Visual Prompts](https://arxiv.org/abs/2312.00784) by Mu Cai, Haotian Liu, Siva Karthik Mustikovela, Gregory P. Meyer, Yuning Chai, Dennis Park, Yong Jae Lee.
|
| 22 |
+
|
| 23 |
+
VipLlava enhances the training protocol of Llava by marking images and interact with the model using natural cues like a "red bounding box" or "pointed arrow" during training.
|
| 24 |
+
|
| 25 |
+
The abstract from the paper is the following:
|
| 26 |
+
|
| 27 |
+
*While existing large vision-language multimodal models focus on whole image understanding, there is a prominent gap in achieving region-specific comprehension. Current approaches that use textual coordinates or spatial encodings often fail to provide a user-friendly interface for visual prompting. To address this challenge, we introduce a novel multimodal model capable of decoding arbitrary visual prompts. This allows users to intuitively mark images and interact with the model using natural cues like a "red bounding box" or "pointed arrow". Our simple design directly overlays visual markers onto the RGB image, eliminating the need for complex region encodings, yet achieves state-of-the-art performance on region-understanding tasks like Visual7W, PointQA, and Visual Commonsense Reasoning benchmark. Furthermore, we present ViP-Bench, a comprehensive benchmark to assess the capability of models in understanding visual prompts across multiple dimensions, enabling future research in this domain. Code, data, and model are publicly available.*
|
| 28 |
+
|
| 29 |
+
The original code can be found [here](https://github.com/mu-cai/ViP-LLaVA).
|
| 30 |
+
|
| 31 |
+
This model was contributed by [Younes Belkada](https://huggingface.co/ybelkada)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
## Usage tips:
|
| 35 |
+
|
| 36 |
+
- The architecture is similar than llava architecture except that the multi-modal projector takes a set of concatenated vision hidden states and has an additional layernorm layer on that module.
|
| 37 |
+
|
| 38 |
+
- 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.
|
| 39 |
+
|
| 40 |
+
- Note the model has not been explicitly trained to process multiple images in the same prompt, although this is technically possible, you may experience inaccurate results.
|
| 41 |
+
|
| 42 |
+
> [!NOTE]
|
| 43 |
+
> 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.
|
| 44 |
+
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 `<image>` 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.
|
| 45 |
+
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.
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
- For better results, we recommend users to use the processor's `apply_chat_template()` method to format your prompt correctly. For that you need to construct a conversation history, passing in a plain string will not format your prompt. Each message in the conversation history for chat templates is a dictionary with keys "role" and "content". The "content" should be a list of dictionaries, for "text" and "image" modalities, as follows:
|
| 49 |
+
|
| 50 |
+
```python
|
| 51 |
+
from transformers import AutoProcessor
|
| 52 |
+
|
| 53 |
+
processor = AutoProcessor.from_pretrained("llava-hf/vip-llava-7b-hf")
|
| 54 |
+
|
| 55 |
+
conversation = [
|
| 56 |
+
{
|
| 57 |
+
"role": "user",
|
| 58 |
+
"content": [
|
| 59 |
+
{"type": "image"},
|
| 60 |
+
{"type": "text", "text": "What’s shown in this image?"},
|
| 61 |
+
],
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"role": "assistant",
|
| 65 |
+
"content": [{"type": "text", "text": "This image shows a red stop sign."},]
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
|
| 69 |
+
"role": "user",
|
| 70 |
+
"content": [
|
| 71 |
+
{"type": "text", "text": "Describe the image in more details."},
|
| 72 |
+
],
|
| 73 |
+
},
|
| 74 |
+
]
|
| 75 |
+
|
| 76 |
+
text_prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
|
| 77 |
+
|
| 78 |
+
# Note that the template simply formats your prompt, you still have to tokenize it and obtain pixel values for your images
|
| 79 |
+
print(text_prompt)
|
| 80 |
+
>>> "###Human: <image>\nWhat’s shown in this image?###Assistant: This image shows a red stop sign.###Human: Describe the image in more details.###Assistant:"
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
- If you want to construct a chat prompt yourself, below is a list of prompt formats accepted by VipLLaVa checkpoints:
|
| 84 |
+
```bash
|
| 85 |
+
A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.###Human: <image>\n<prompt>###Assistant:
|
| 86 |
+
```
|
| 87 |
+
|
| 88 |
+
For multiple turns conversation:
|
| 89 |
+
```bash
|
| 90 |
+
A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.###Human: <image>\n<prompt1>###Assistant: <answer1>###Human: <prompt2>###Assistant:
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
## VipLlavaConfig
|
| 95 |
+
|
| 96 |
+
[[autodoc]] VipLlavaConfig
|
| 97 |
+
|
| 98 |
+
## VipLlavaForConditionalGeneration
|
| 99 |
+
|
| 100 |
+
[[autodoc]] VipLlavaForConditionalGeneration
|
| 101 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/vision-encoder-decoder.md
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2021 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Vision Encoder Decoder Models
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
The [`VisionEncoderDecoderModel`] can be used to initialize an image-to-text model with any
|
| 22 |
+
pretrained Transformer-based vision model as the encoder (*e.g.* [ViT](vit), [BEiT](beit), [DeiT](deit), [Swin](swin))
|
| 23 |
+
and any pretrained language model as the decoder (*e.g.* [RoBERTa](roberta), [GPT2](gpt2), [BERT](bert), [DistilBERT](distilbert)).
|
| 24 |
+
|
| 25 |
+
The effectiveness of initializing image-to-text-sequence models with pretrained checkpoints has been shown in (for
|
| 26 |
+
example) [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,
|
| 27 |
+
Zhoujun Li, Furu Wei.
|
| 28 |
+
|
| 29 |
+
After such a [`VisionEncoderDecoderModel`] has been trained/fine-tuned, it can be saved/loaded just like any other models (see the examples below
|
| 30 |
+
for more information).
|
| 31 |
+
|
| 32 |
+
An example application is image captioning, in which the encoder is used to encode the image, after which an autoregressive language model generates
|
| 33 |
+
the caption. Another example is optical character recognition. Refer to [TrOCR](trocr), which is an instance of [`VisionEncoderDecoderModel`].
|
| 34 |
+
|
| 35 |
+
## Randomly initializing `VisionEncoderDecoderModel` from model configurations.
|
| 36 |
+
|
| 37 |
+
[`VisionEncoderDecoderModel`] can be randomly initialized from an encoder and a decoder config. In the following example, we show how to do this using the default [`ViTModel`] configuration for the encoder
|
| 38 |
+
and the default [`BertForCausalLM`] configuration for the decoder.
|
| 39 |
+
|
| 40 |
+
```python
|
| 41 |
+
>>> from transformers import BertConfig, ViTConfig, VisionEncoderDecoderConfig, VisionEncoderDecoderModel
|
| 42 |
+
|
| 43 |
+
>>> config_encoder = ViTConfig()
|
| 44 |
+
>>> config_decoder = BertConfig()
|
| 45 |
+
|
| 46 |
+
>>> config = VisionEncoderDecoderConfig.from_encoder_decoder_configs(config_encoder, config_decoder)
|
| 47 |
+
>>> model = VisionEncoderDecoderModel(config=config)
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
## Initialising `VisionEncoderDecoderModel` from a pretrained encoder and a pretrained decoder.
|
| 51 |
+
|
| 52 |
+
[`VisionEncoderDecoderModel`] can be initialized from a pretrained encoder checkpoint and a pretrained decoder checkpoint. Note that any pretrained Transformer-based vision model, *e.g.* [Swin](swin), can serve as the encoder and both pretrained auto-encoding models, *e.g.* BERT, pretrained causal language models, *e.g.* GPT2, as well as the pretrained decoder part of sequence-to-sequence models, *e.g.* decoder of BART, can be used as the decoder.
|
| 53 |
+
Depending on which architecture you choose as the decoder, the cross-attention layers might be randomly initialized.
|
| 54 |
+
Initializing [`VisionEncoderDecoderModel`] from a pretrained encoder and decoder checkpoint requires the model to be fine-tuned on a downstream task, as has been shown in [the *Warm-starting-encoder-decoder blog post*](https://huggingface.co/blog/warm-starting-encoder-decoder).
|
| 55 |
+
To do so, the `VisionEncoderDecoderModel` class provides a [`VisionEncoderDecoderModel.from_encoder_decoder_pretrained`] method.
|
| 56 |
+
|
| 57 |
+
```python
|
| 58 |
+
>>> from transformers import VisionEncoderDecoderModel
|
| 59 |
+
|
| 60 |
+
>>> model = VisionEncoderDecoderModel.from_encoder_decoder_pretrained(
|
| 61 |
+
... "microsoft/swin-base-patch4-window7-224-in22k", "google-bert/bert-base-uncased"
|
| 62 |
+
... )
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
## Loading an existing `VisionEncoderDecoderModel` checkpoint and perform inference.
|
| 66 |
+
|
| 67 |
+
To load fine-tuned checkpoints of the `VisionEncoderDecoderModel` class, [`VisionEncoderDecoderModel`] provides the `from_pretrained(...)` method just like any other model architecture in Transformers.
|
| 68 |
+
|
| 69 |
+
To perform inference, one uses the [`generate`] method, which allows to autoregressively generate text. This method supports various forms of decoding, such as greedy, beam search and multinomial sampling.
|
| 70 |
+
|
| 71 |
+
```python
|
| 72 |
+
>>> import requests
|
| 73 |
+
>>> from PIL import Image
|
| 74 |
+
|
| 75 |
+
>>> from transformers import GPT2TokenizerFast, ViTImageProcessor, VisionEncoderDecoderModel
|
| 76 |
+
|
| 77 |
+
>>> # load a fine-tuned image captioning model and corresponding tokenizer and image processor
|
| 78 |
+
>>> model = VisionEncoderDecoderModel.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
|
| 79 |
+
>>> tokenizer = GPT2TokenizerFast.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
|
| 80 |
+
>>> image_processor = ViTImageProcessor.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
|
| 81 |
+
|
| 82 |
+
>>> # let's perform inference on an image
|
| 83 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 84 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 85 |
+
>>> pixel_values = image_processor(image, return_tensors="pt").pixel_values
|
| 86 |
+
|
| 87 |
+
>>> # autoregressively generate caption (uses greedy decoding by default)
|
| 88 |
+
>>> generated_ids = model.generate(pixel_values)
|
| 89 |
+
>>> generated_text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 90 |
+
>>> print(generated_text)
|
| 91 |
+
a cat laying on a blanket next to a cat laying on a bed
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
## Loading a PyTorch checkpoint into `TFVisionEncoderDecoderModel`.
|
| 95 |
+
|
| 96 |
+
[`TFVisionEncoderDecoderModel.from_pretrained`] currently doesn't support initializing the model from a
|
| 97 |
+
PyTorch checkpoint. Passing `from_pt=True` to this method will throw an exception. If there are only PyTorch
|
| 98 |
+
checkpoints for a particular vision encoder-decoder model, a workaround is:
|
| 99 |
+
|
| 100 |
+
```python
|
| 101 |
+
>>> from transformers import VisionEncoderDecoderModel, TFVisionEncoderDecoderModel
|
| 102 |
+
|
| 103 |
+
>>> _model = VisionEncoderDecoderModel.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
|
| 104 |
+
|
| 105 |
+
>>> _model.encoder.save_pretrained("./encoder")
|
| 106 |
+
>>> _model.decoder.save_pretrained("./decoder")
|
| 107 |
+
|
| 108 |
+
>>> model = TFVisionEncoderDecoderModel.from_encoder_decoder_pretrained(
|
| 109 |
+
... "./encoder", "./decoder", encoder_from_pt=True, decoder_from_pt=True
|
| 110 |
+
... )
|
| 111 |
+
>>> # This is only for copying some specific attributes of this particular model.
|
| 112 |
+
>>> model.config = _model.config
|
| 113 |
+
```
|
| 114 |
+
|
| 115 |
+
## Training
|
| 116 |
+
|
| 117 |
+
Once the model is created, it can be fine-tuned similar to BART, T5 or any other encoder-decoder model on a dataset of (image, text) pairs.
|
| 118 |
+
As you can see, only 2 inputs are required for the model in order to compute a loss: `pixel_values` (which are the
|
| 119 |
+
images) and `labels` (which are the `input_ids` of the encoded target sequence).
|
| 120 |
+
|
| 121 |
+
```python
|
| 122 |
+
>>> from transformers import ViTImageProcessor, BertTokenizer, VisionEncoderDecoderModel
|
| 123 |
+
>>> from datasets import load_dataset
|
| 124 |
+
|
| 125 |
+
>>> image_processor = ViTImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k")
|
| 126 |
+
>>> tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased")
|
| 127 |
+
>>> model = VisionEncoderDecoderModel.from_encoder_decoder_pretrained(
|
| 128 |
+
... "google/vit-base-patch16-224-in21k", "google-bert/bert-base-uncased"
|
| 129 |
+
... )
|
| 130 |
+
|
| 131 |
+
>>> model.config.decoder_start_token_id = tokenizer.cls_token_id
|
| 132 |
+
>>> model.config.pad_token_id = tokenizer.pad_token_id
|
| 133 |
+
|
| 134 |
+
>>> dataset = load_dataset("huggingface/cats-image")
|
| 135 |
+
>>> image = dataset["test"]["image"][0]
|
| 136 |
+
>>> pixel_values = image_processor(image, return_tensors="pt").pixel_values
|
| 137 |
+
|
| 138 |
+
>>> labels = tokenizer(
|
| 139 |
+
... "an image of two cats chilling on a couch",
|
| 140 |
+
... return_tensors="pt",
|
| 141 |
+
... ).input_ids
|
| 142 |
+
|
| 143 |
+
>>> # the forward function automatically creates the correct decoder_input_ids
|
| 144 |
+
>>> loss = model(pixel_values=pixel_values, labels=labels).loss
|
| 145 |
+
```
|
| 146 |
+
|
| 147 |
+
This model was contributed by [nielsr](https://github.com/nielsrogge). This model's TensorFlow and Flax versions
|
| 148 |
+
were contributed by [ydshieh](https://github.com/ydshieh).
|
| 149 |
+
|
| 150 |
+
## VisionEncoderDecoderConfig
|
| 151 |
+
|
| 152 |
+
[[autodoc]] VisionEncoderDecoderConfig
|
| 153 |
+
|
| 154 |
+
<frameworkcontent>
|
| 155 |
+
<pt>
|
| 156 |
+
|
| 157 |
+
## VisionEncoderDecoderModel
|
| 158 |
+
|
| 159 |
+
[[autodoc]] VisionEncoderDecoderModel
|
| 160 |
+
- forward
|
| 161 |
+
- from_encoder_decoder_pretrained
|
| 162 |
+
|
| 163 |
+
</pt>
|
| 164 |
+
<tf>
|
| 165 |
+
|
| 166 |
+
## TFVisionEncoderDecoderModel
|
| 167 |
+
|
| 168 |
+
[[autodoc]] TFVisionEncoderDecoderModel
|
| 169 |
+
- call
|
| 170 |
+
- from_encoder_decoder_pretrained
|
| 171 |
+
|
| 172 |
+
</tf>
|
| 173 |
+
<jax>
|
| 174 |
+
|
| 175 |
+
## FlaxVisionEncoderDecoderModel
|
| 176 |
+
|
| 177 |
+
[[autodoc]] FlaxVisionEncoderDecoderModel
|
| 178 |
+
- __call__
|
| 179 |
+
- from_encoder_decoder_pretrained
|
| 180 |
+
|
| 181 |
+
</jax>
|
| 182 |
+
</frameworkcontent>
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/vision-text-dual-encoder.md
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2021 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# VisionTextDualEncoder
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
The [`VisionTextDualEncoderModel`] can be used to initialize a vision-text dual encoder model with
|
| 22 |
+
any pretrained vision autoencoding model as the vision encoder (*e.g.* [ViT](vit), [BEiT](beit), [DeiT](deit)) and any pretrained text autoencoding model as the text encoder (*e.g.* [RoBERTa](roberta), [BERT](bert)). Two projection layers are added on top of both the vision and text encoder to project the output embeddings
|
| 23 |
+
to a shared latent space. The projection layers are randomly initialized so the model should be fine-tuned on a
|
| 24 |
+
downstream task. This model can be used to align the vision-text embeddings using CLIP like contrastive image-text
|
| 25 |
+
training and then can be used for zero-shot vision tasks such image-classification or retrieval.
|
| 26 |
+
|
| 27 |
+
In [LiT: Zero-Shot Transfer with Locked-image Text Tuning](https://arxiv.org/abs/2111.07991) it is shown how
|
| 28 |
+
leveraging pre-trained (locked/frozen) image and text model for contrastive learning yields significant improvement on
|
| 29 |
+
new zero-shot vision tasks such as image classification or retrieval.
|
| 30 |
+
|
| 31 |
+
## VisionTextDualEncoderConfig
|
| 32 |
+
|
| 33 |
+
[[autodoc]] VisionTextDualEncoderConfig
|
| 34 |
+
|
| 35 |
+
## VisionTextDualEncoderProcessor
|
| 36 |
+
|
| 37 |
+
[[autodoc]] VisionTextDualEncoderProcessor
|
| 38 |
+
|
| 39 |
+
<frameworkcontent>
|
| 40 |
+
<pt>
|
| 41 |
+
|
| 42 |
+
## VisionTextDualEncoderModel
|
| 43 |
+
|
| 44 |
+
[[autodoc]] VisionTextDualEncoderModel
|
| 45 |
+
- forward
|
| 46 |
+
|
| 47 |
+
</pt>
|
| 48 |
+
<tf>
|
| 49 |
+
|
| 50 |
+
## FlaxVisionTextDualEncoderModel
|
| 51 |
+
|
| 52 |
+
[[autodoc]] FlaxVisionTextDualEncoderModel
|
| 53 |
+
- __call__
|
| 54 |
+
|
| 55 |
+
</tf>
|
| 56 |
+
<jax>
|
| 57 |
+
|
| 58 |
+
## TFVisionTextDualEncoderModel
|
| 59 |
+
|
| 60 |
+
[[autodoc]] TFVisionTextDualEncoderModel
|
| 61 |
+
- call
|
| 62 |
+
|
| 63 |
+
</jax>
|
| 64 |
+
</frameworkcontent>
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/visual_bert.md
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2021 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# VisualBERT
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
The VisualBERT model was proposed in [VisualBERT: A Simple and Performant Baseline for Vision and Language](https://arxiv.org/pdf/1908.03557) by Liunian Harold Li, Mark Yatskar, Da Yin, Cho-Jui Hsieh, Kai-Wei Chang.
|
| 22 |
+
VisualBERT is a neural network trained on a variety of (image, text) pairs.
|
| 23 |
+
|
| 24 |
+
The abstract from the paper is the following:
|
| 25 |
+
|
| 26 |
+
*We propose VisualBERT, a simple and flexible framework for modeling a broad range of vision-and-language tasks.
|
| 27 |
+
VisualBERT consists of a stack of Transformer layers that implicitly align elements of an input text and regions in an
|
| 28 |
+
associated input image with self-attention. We further propose two visually-grounded language model objectives for
|
| 29 |
+
pre-training VisualBERT on image caption data. Experiments on four vision-and-language tasks including VQA, VCR, NLVR2,
|
| 30 |
+
and Flickr30K show that VisualBERT outperforms or rivals with state-of-the-art models while being significantly
|
| 31 |
+
simpler. Further analysis demonstrates that VisualBERT can ground elements of language to image regions without any
|
| 32 |
+
explicit supervision and is even sensitive to syntactic relationships, tracking, for example, associations between
|
| 33 |
+
verbs and image regions corresponding to their arguments.*
|
| 34 |
+
|
| 35 |
+
This model was contributed by [gchhablani](https://huggingface.co/gchhablani). The original code can be found [here](https://github.com/uclanlp/visualbert).
|
| 36 |
+
|
| 37 |
+
## Usage tips
|
| 38 |
+
|
| 39 |
+
1. Most of the checkpoints provided work with the [`VisualBertForPreTraining`] configuration. Other
|
| 40 |
+
checkpoints provided are the fine-tuned checkpoints for down-stream tasks - VQA ('visualbert-vqa'), VCR
|
| 41 |
+
('visualbert-vcr'), NLVR2 ('visualbert-nlvr2'). Hence, if you are not working on these downstream tasks, it is
|
| 42 |
+
recommended that you use the pretrained checkpoints.
|
| 43 |
+
|
| 44 |
+
2. For the VCR task, the authors use a fine-tuned detector for generating visual embeddings, for all the checkpoints.
|
| 45 |
+
We do not provide the detector and its weights as a part of the package, but it will be available in the research
|
| 46 |
+
projects, and the states can be loaded directly into the detector provided.
|
| 47 |
+
|
| 48 |
+
VisualBERT is a multi-modal vision and language model. It can be used for visual question answering, multiple choice,
|
| 49 |
+
visual reasoning and region-to-phrase correspondence tasks. VisualBERT uses a BERT-like transformer to prepare
|
| 50 |
+
embeddings for image-text pairs. Both the text and visual features are then projected to a latent space with identical
|
| 51 |
+
dimension.
|
| 52 |
+
|
| 53 |
+
To feed images to the model, each image is passed through a pre-trained object detector and the regions and the
|
| 54 |
+
bounding boxes are extracted. The authors use the features generated after passing these regions through a pre-trained
|
| 55 |
+
CNN like ResNet as visual embeddings. They also add absolute position embeddings, and feed the resulting sequence of
|
| 56 |
+
vectors to a standard BERT model. The text input is concatenated in the front of the visual embeddings in the embedding
|
| 57 |
+
layer, and is expected to be bound by [CLS] and a [SEP] tokens, as in BERT. The segment IDs must also be set
|
| 58 |
+
appropriately for the textual and visual parts.
|
| 59 |
+
|
| 60 |
+
The [`BertTokenizer`] is used to encode the text. A custom detector/image processor must be used
|
| 61 |
+
to get the visual embeddings. The following example notebooks show how to use VisualBERT with Detectron-like models:
|
| 62 |
+
|
| 63 |
+
- [VisualBERT VQA demo notebook](https://github.com/huggingface/transformers/tree/main/examples/research_projects/visual_bert) : This notebook
|
| 64 |
+
contains an example on VisualBERT VQA.
|
| 65 |
+
|
| 66 |
+
- [Generate Embeddings for VisualBERT (Colab Notebook)](https://colab.research.google.com/drive/1bLGxKdldwqnMVA5x4neY7-l_8fKGWQYI?usp=sharing) : This notebook contains
|
| 67 |
+
an example on how to generate visual embeddings.
|
| 68 |
+
|
| 69 |
+
The following example shows how to get the last hidden state using [`VisualBertModel`]:
|
| 70 |
+
|
| 71 |
+
```python
|
| 72 |
+
>>> import torch
|
| 73 |
+
>>> from transformers import BertTokenizer, VisualBertModel
|
| 74 |
+
|
| 75 |
+
>>> model = VisualBertModel.from_pretrained("uclanlp/visualbert-vqa-coco-pre")
|
| 76 |
+
>>> tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased")
|
| 77 |
+
|
| 78 |
+
>>> inputs = tokenizer("What is the man eating?", return_tensors="pt")
|
| 79 |
+
>>> # this is a custom function that returns the visual embeddings given the image path
|
| 80 |
+
>>> visual_embeds = get_visual_embeddings(image_path)
|
| 81 |
+
|
| 82 |
+
>>> visual_token_type_ids = torch.ones(visual_embeds.shape[:-1], dtype=torch.long)
|
| 83 |
+
>>> visual_attention_mask = torch.ones(visual_embeds.shape[:-1], dtype=torch.float)
|
| 84 |
+
>>> inputs.update(
|
| 85 |
+
... {
|
| 86 |
+
... "visual_embeds": visual_embeds,
|
| 87 |
+
... "visual_token_type_ids": visual_token_type_ids,
|
| 88 |
+
... "visual_attention_mask": visual_attention_mask,
|
| 89 |
+
... }
|
| 90 |
+
... )
|
| 91 |
+
>>> outputs = model(**inputs)
|
| 92 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
| 93 |
+
```
|
| 94 |
+
|
| 95 |
+
## VisualBertConfig
|
| 96 |
+
|
| 97 |
+
[[autodoc]] VisualBertConfig
|
| 98 |
+
|
| 99 |
+
## VisualBertModel
|
| 100 |
+
|
| 101 |
+
[[autodoc]] VisualBertModel
|
| 102 |
+
- forward
|
| 103 |
+
|
| 104 |
+
## VisualBertForPreTraining
|
| 105 |
+
|
| 106 |
+
[[autodoc]] VisualBertForPreTraining
|
| 107 |
+
- forward
|
| 108 |
+
|
| 109 |
+
## VisualBertForQuestionAnswering
|
| 110 |
+
|
| 111 |
+
[[autodoc]] VisualBertForQuestionAnswering
|
| 112 |
+
- forward
|
| 113 |
+
|
| 114 |
+
## VisualBertForMultipleChoice
|
| 115 |
+
|
| 116 |
+
[[autodoc]] VisualBertForMultipleChoice
|
| 117 |
+
- forward
|
| 118 |
+
|
| 119 |
+
## VisualBertForVisualReasoning
|
| 120 |
+
|
| 121 |
+
[[autodoc]] VisualBertForVisualReasoning
|
| 122 |
+
- forward
|
| 123 |
+
|
| 124 |
+
## VisualBertForRegionToPhraseAlignment
|
| 125 |
+
|
| 126 |
+
[[autodoc]] VisualBertForRegionToPhraseAlignment
|
| 127 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/vit.md
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2021 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Vision Transformer (ViT)
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
The Vision Transformer (ViT) model was proposed in [An Image is Worth 16x16 Words: Transformers for Image Recognition
|
| 22 |
+
at Scale](https://arxiv.org/abs/2010.11929) by Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk
|
| 23 |
+
Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob
|
| 24 |
+
Uszkoreit, Neil Houlsby. It's the first paper that successfully trains a Transformer encoder on ImageNet, attaining
|
| 25 |
+
very good results compared to familiar convolutional architectures.
|
| 26 |
+
|
| 27 |
+
The abstract from the paper is the following:
|
| 28 |
+
|
| 29 |
+
*While the Transformer architecture has become the de-facto standard for natural language processing tasks, its
|
| 30 |
+
applications to computer vision remain limited. In vision, attention is either applied in conjunction with
|
| 31 |
+
convolutional networks, or used to replace certain components of convolutional networks while keeping their overall
|
| 32 |
+
structure in place. We show that this reliance on CNNs is not necessary and a pure transformer applied directly to
|
| 33 |
+
sequences of image patches can perform very well on image classification tasks. When pre-trained on large amounts of
|
| 34 |
+
data and transferred to multiple mid-sized or small image recognition benchmarks (ImageNet, CIFAR-100, VTAB, etc.),
|
| 35 |
+
Vision Transformer (ViT) attains excellent results compared to state-of-the-art convolutional networks while requiring
|
| 36 |
+
substantially fewer computational resources to train.*
|
| 37 |
+
|
| 38 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/vit_architecture.jpg"
|
| 39 |
+
alt="drawing" width="600"/>
|
| 40 |
+
|
| 41 |
+
<small> ViT architecture. Taken from the <a href="https://arxiv.org/abs/2010.11929">original paper.</a> </small>
|
| 42 |
+
|
| 43 |
+
Following the original Vision Transformer, some follow-up works have been made:
|
| 44 |
+
|
| 45 |
+
- [DeiT](deit) (Data-efficient Image Transformers) by Facebook AI. DeiT models are distilled vision transformers.
|
| 46 |
+
The authors of DeiT also released more efficiently trained ViT models, which you can directly plug into [`ViTModel`] or
|
| 47 |
+
[`ViTForImageClassification`]. There are 4 variants available (in 3 different sizes): *facebook/deit-tiny-patch16-224*,
|
| 48 |
+
*facebook/deit-small-patch16-224*, *facebook/deit-base-patch16-224* and *facebook/deit-base-patch16-384*. Note that one should
|
| 49 |
+
use [`DeiTImageProcessor`] in order to prepare images for the model.
|
| 50 |
+
|
| 51 |
+
- [BEiT](beit) (BERT pre-training of Image Transformers) by Microsoft Research. BEiT models outperform supervised pre-trained
|
| 52 |
+
vision transformers using a self-supervised method inspired by BERT (masked image modeling) and based on a VQ-VAE.
|
| 53 |
+
|
| 54 |
+
- DINO (a method for self-supervised training of Vision Transformers) by Facebook AI. Vision Transformers trained using
|
| 55 |
+
the DINO method show very interesting properties not seen with convolutional models. They are capable of segmenting
|
| 56 |
+
objects, without having ever been trained to do so. DINO checkpoints can be found on the [hub](https://huggingface.co/models?other=dino).
|
| 57 |
+
|
| 58 |
+
- [MAE](vit_mae) (Masked Autoencoders) by Facebook AI. By pre-training Vision Transformers to reconstruct pixel values for a high portion
|
| 59 |
+
(75%) of masked patches (using an asymmetric encoder-decoder architecture), the authors show that this simple method outperforms
|
| 60 |
+
supervised pre-training after fine-tuning.
|
| 61 |
+
|
| 62 |
+
This model was contributed by [nielsr](https://huggingface.co/nielsr). The original code (written in JAX) can be
|
| 63 |
+
found [here](https://github.com/google-research/vision_transformer).
|
| 64 |
+
|
| 65 |
+
Note that we converted the weights from Ross Wightman's [timm library](https://github.com/rwightman/pytorch-image-models),
|
| 66 |
+
who already converted the weights from JAX to PyTorch. Credits go to him!
|
| 67 |
+
|
| 68 |
+
## Usage tips
|
| 69 |
+
|
| 70 |
+
- To feed images to the Transformer encoder, each image is split into a sequence of fixed-size non-overlapping patches,
|
| 71 |
+
which are then linearly embedded. A [CLS] token is added to serve as representation of an entire image, which can be
|
| 72 |
+
used for classification. The authors also add absolute position embeddings, and feed the resulting sequence of
|
| 73 |
+
vectors to a standard Transformer encoder.
|
| 74 |
+
- As the Vision Transformer expects each image to be of the same size (resolution), one can use
|
| 75 |
+
[`ViTImageProcessor`] to resize (or rescale) and normalize images for the model.
|
| 76 |
+
- Both the patch resolution and image resolution used during pre-training or fine-tuning are reflected in the name of
|
| 77 |
+
each checkpoint. For example, `google/vit-base-patch16-224` refers to a base-sized architecture with patch
|
| 78 |
+
resolution of 16x16 and fine-tuning resolution of 224x224. All checkpoints can be found on the [hub](https://huggingface.co/models?search=vit).
|
| 79 |
+
- The available checkpoints are either (1) pre-trained on [ImageNet-21k](http://www.image-net.org/) (a collection of
|
| 80 |
+
14 million images and 21k classes) only, or (2) also fine-tuned on [ImageNet](http://www.image-net.org/challenges/LSVRC/2012/) (also referred to as ILSVRC 2012, a collection of 1.3 million
|
| 81 |
+
images and 1,000 classes).
|
| 82 |
+
- The Vision Transformer was pre-trained using a resolution of 224x224. During fine-tuning, it is often beneficial to
|
| 83 |
+
use a higher resolution than pre-training [(Touvron et al., 2019)](https://arxiv.org/abs/1906.06423), [(Kolesnikov
|
| 84 |
+
et al., 2020)](https://arxiv.org/abs/1912.11370). In order to fine-tune at higher resolution, the authors perform
|
| 85 |
+
2D interpolation of the pre-trained position embeddings, according to their location in the original image.
|
| 86 |
+
- The best results are obtained with supervised pre-training, which is not the case in NLP. The authors also performed
|
| 87 |
+
an experiment with a self-supervised pre-training objective, namely masked patched prediction (inspired by masked
|
| 88 |
+
language modeling). With this approach, the smaller ViT-B/16 model achieves 79.9% accuracy on ImageNet, a significant
|
| 89 |
+
improvement of 2% to training from scratch, but still 4% behind supervised pre-training.
|
| 90 |
+
|
| 91 |
+
### Using Scaled Dot Product Attention (SDPA)
|
| 92 |
+
|
| 93 |
+
PyTorch includes a native scaled dot-product attention (SDPA) operator as part of `torch.nn.functional`. This function
|
| 94 |
+
encompasses several implementations that can be applied depending on the inputs and the hardware in use. See the
|
| 95 |
+
[official documentation](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html)
|
| 96 |
+
or the [GPU Inference](https://huggingface.co/docs/transformers/main/en/perf_infer_gpu_one#pytorch-scaled-dot-product-attention)
|
| 97 |
+
page for more information.
|
| 98 |
+
|
| 99 |
+
SDPA is used by default for `torch>=2.1.1` when an implementation is available, but you may also set
|
| 100 |
+
`attn_implementation="sdpa"` in `from_pretrained()` to explicitly request SDPA to be used.
|
| 101 |
+
|
| 102 |
+
```
|
| 103 |
+
from transformers import ViTForImageClassification
|
| 104 |
+
model = ViTForImageClassification.from_pretrained("google/vit-base-patch16-224", attn_implementation="sdpa", torch_dtype=torch.float16)
|
| 105 |
+
...
|
| 106 |
+
```
|
| 107 |
+
|
| 108 |
+
For the best speedups, we recommend loading the model in half-precision (e.g. `torch.float16` or `torch.bfloat16`).
|
| 109 |
+
|
| 110 |
+
On a local benchmark (A100-40GB, PyTorch 2.3.0, OS Ubuntu 22.04) with `float32` and `google/vit-base-patch16-224` model, we saw the following speedups during inference.
|
| 111 |
+
|
| 112 |
+
| Batch size | Average inference time (ms), eager mode | Average inference time (ms), sdpa model | Speed up, Sdpa / Eager (x) |
|
| 113 |
+
|--------------|-------------------------------------------|-------------------------------------------|------------------------------|
|
| 114 |
+
| 1 | 7 | 6 | 1.17 |
|
| 115 |
+
| 2 | 8 | 6 | 1.33 |
|
| 116 |
+
| 4 | 8 | 6 | 1.33 |
|
| 117 |
+
| 8 | 8 | 6 | 1.33 |
|
| 118 |
+
|
| 119 |
+
## Resources
|
| 120 |
+
|
| 121 |
+
Demo notebooks regarding inference as well as fine-tuning ViT on custom data can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/VisionTransformer).
|
| 122 |
+
A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with ViT. 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.
|
| 123 |
+
|
| 124 |
+
`ViTForImageClassification` is supported by:
|
| 125 |
+
<PipelineTag pipeline="image-classification"/>
|
| 126 |
+
|
| 127 |
+
- A blog post on how to [Fine-Tune ViT for Image Classification with Hugging Face Transformers](https://huggingface.co/blog/fine-tune-vit)
|
| 128 |
+
- A blog post on [Image Classification with Hugging Face Transformers and `Keras`](https://www.philschmid.de/image-classification-huggingface-transformers-keras)
|
| 129 |
+
- A notebook on [Fine-tuning for Image Classification with Hugging Face Transformers](https://github.com/huggingface/notebooks/blob/main/examples/image_classification.ipynb)
|
| 130 |
+
- A notebook on how to [Fine-tune the Vision Transformer on CIFAR-10 with the Hugging Face Trainer](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/VisionTransformer/Fine_tuning_the_Vision_Transformer_on_CIFAR_10_with_the_%F0%9F%A4%97_Trainer.ipynb)
|
| 131 |
+
- A notebook on how to [Fine-tune the Vision Transformer on CIFAR-10 with PyTorch Lightning](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/VisionTransformer/Fine_tuning_the_Vision_Transformer_on_CIFAR_10_with_PyTorch_Lightning.ipynb)
|
| 132 |
+
|
| 133 |
+
⚗️ Optimization
|
| 134 |
+
|
| 135 |
+
- A blog post on how to [Accelerate Vision Transformer (ViT) with Quantization using Optimum](https://www.philschmid.de/optimizing-vision-transformer)
|
| 136 |
+
|
| 137 |
+
⚡️ Inference
|
| 138 |
+
|
| 139 |
+
- A notebook on [Quick demo: Vision Transformer (ViT) by Google Brain](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/VisionTransformer/Quick_demo_of_HuggingFace_version_of_Vision_Transformer_inference.ipynb)
|
| 140 |
+
|
| 141 |
+
🚀 Deploy
|
| 142 |
+
|
| 143 |
+
- A blog post on [Deploying Tensorflow Vision Models in Hugging Face with TF Serving](https://huggingface.co/blog/tf-serving-vision)
|
| 144 |
+
- A blog post on [Deploying Hugging Face ViT on Vertex AI](https://huggingface.co/blog/deploy-vertex-ai)
|
| 145 |
+
- A blog post on [Deploying Hugging Face ViT on Kubernetes with TF Serving](https://huggingface.co/blog/deploy-tfserving-kubernetes)
|
| 146 |
+
|
| 147 |
+
## ViTConfig
|
| 148 |
+
|
| 149 |
+
[[autodoc]] ViTConfig
|
| 150 |
+
|
| 151 |
+
## ViTFeatureExtractor
|
| 152 |
+
|
| 153 |
+
[[autodoc]] ViTFeatureExtractor
|
| 154 |
+
- __call__
|
| 155 |
+
|
| 156 |
+
## ViTImageProcessor
|
| 157 |
+
|
| 158 |
+
[[autodoc]] ViTImageProcessor
|
| 159 |
+
- preprocess
|
| 160 |
+
|
| 161 |
+
## ViTImageProcessorFast
|
| 162 |
+
|
| 163 |
+
[[autodoc]] ViTImageProcessorFast
|
| 164 |
+
- preprocess
|
| 165 |
+
|
| 166 |
+
<frameworkcontent>
|
| 167 |
+
<pt>
|
| 168 |
+
|
| 169 |
+
## ViTModel
|
| 170 |
+
|
| 171 |
+
[[autodoc]] ViTModel
|
| 172 |
+
- forward
|
| 173 |
+
|
| 174 |
+
## ViTForMaskedImageModeling
|
| 175 |
+
|
| 176 |
+
[[autodoc]] ViTForMaskedImageModeling
|
| 177 |
+
- forward
|
| 178 |
+
|
| 179 |
+
## ViTForImageClassification
|
| 180 |
+
|
| 181 |
+
[[autodoc]] ViTForImageClassification
|
| 182 |
+
- forward
|
| 183 |
+
|
| 184 |
+
</pt>
|
| 185 |
+
<tf>
|
| 186 |
+
|
| 187 |
+
## TFViTModel
|
| 188 |
+
|
| 189 |
+
[[autodoc]] TFViTModel
|
| 190 |
+
- call
|
| 191 |
+
|
| 192 |
+
## TFViTForImageClassification
|
| 193 |
+
|
| 194 |
+
[[autodoc]] TFViTForImageClassification
|
| 195 |
+
- call
|
| 196 |
+
|
| 197 |
+
</tf>
|
| 198 |
+
<jax>
|
| 199 |
+
|
| 200 |
+
## FlaxVitModel
|
| 201 |
+
|
| 202 |
+
[[autodoc]] FlaxViTModel
|
| 203 |
+
- __call__
|
| 204 |
+
|
| 205 |
+
## FlaxViTForImageClassification
|
| 206 |
+
|
| 207 |
+
[[autodoc]] FlaxViTForImageClassification
|
| 208 |
+
- __call__
|
| 209 |
+
|
| 210 |
+
</jax>
|
| 211 |
+
</frameworkcontent>
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/vit_hybrid.md
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Hybrid Vision Transformer (ViT Hybrid)
|
| 18 |
+
|
| 19 |
+
<Tip warning={true}>
|
| 20 |
+
|
| 21 |
+
This model is in maintenance mode only, we don't accept any new PRs changing its code.
|
| 22 |
+
If you run into any issues running this model, please reinstall the last version that supported this model: v4.40.2.
|
| 23 |
+
You can do so by running the following command: `pip install -U transformers==4.40.2`.
|
| 24 |
+
|
| 25 |
+
</Tip>
|
| 26 |
+
|
| 27 |
+
## Overview
|
| 28 |
+
|
| 29 |
+
The hybrid Vision Transformer (ViT) model was proposed in [An Image is Worth 16x16 Words: Transformers for Image Recognition
|
| 30 |
+
at Scale](https://arxiv.org/abs/2010.11929) by Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk
|
| 31 |
+
Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob
|
| 32 |
+
Uszkoreit, Neil Houlsby. It's the first paper that successfully trains a Transformer encoder on ImageNet, attaining
|
| 33 |
+
very good results compared to familiar convolutional architectures. ViT hybrid is a slight variant of the [plain Vision Transformer](vit),
|
| 34 |
+
by leveraging a convolutional backbone (specifically, [BiT](bit)) whose features are used as initial "tokens" for the Transformer.
|
| 35 |
+
|
| 36 |
+
The abstract from the paper is the following:
|
| 37 |
+
|
| 38 |
+
*While the Transformer architecture has become the de-facto standard for natural language processing tasks, its
|
| 39 |
+
applications to computer vision remain limited. In vision, attention is either applied in conjunction with
|
| 40 |
+
convolutional networks, or used to replace certain components of convolutional networks while keeping their overall
|
| 41 |
+
structure in place. We show that this reliance on CNNs is not necessary and a pure transformer applied directly to
|
| 42 |
+
sequences of image patches can perform very well on image classification tasks. When pre-trained on large amounts of
|
| 43 |
+
data and transferred to multiple mid-sized or small image recognition benchmarks (ImageNet, CIFAR-100, VTAB, etc.),
|
| 44 |
+
Vision Transformer (ViT) attains excellent results compared to state-of-the-art convolutional networks while requiring
|
| 45 |
+
substantially fewer computational resources to train.*
|
| 46 |
+
|
| 47 |
+
This model was contributed by [nielsr](https://huggingface.co/nielsr). The original code (written in JAX) can be
|
| 48 |
+
found [here](https://github.com/google-research/vision_transformer).
|
| 49 |
+
|
| 50 |
+
## Using Scaled Dot Product Attention (SDPA)
|
| 51 |
+
|
| 52 |
+
PyTorch includes a native scaled dot-product attention (SDPA) operator as part of `torch.nn.functional`. This function
|
| 53 |
+
encompasses several implementations that can be applied depending on the inputs and the hardware in use. See the
|
| 54 |
+
[official documentation](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html)
|
| 55 |
+
or the [GPU Inference](https://huggingface.co/docs/transformers/main/en/perf_infer_gpu_one#pytorch-scaled-dot-product-attention)
|
| 56 |
+
page for more information.
|
| 57 |
+
|
| 58 |
+
SDPA is used by default for `torch>=2.1.1` when an implementation is available, but you may also set
|
| 59 |
+
`attn_implementation="sdpa"` in `from_pretrained()` to explicitly request SDPA to be used.
|
| 60 |
+
|
| 61 |
+
```
|
| 62 |
+
from transformers import ViTHybridForImageClassification
|
| 63 |
+
model = ViTHybridForImageClassification.from_pretrained("google/vit-hybrid-base-bit-384", attn_implementation="sdpa", torch_dtype=torch.float16)
|
| 64 |
+
...
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
For the best speedups, we recommend loading the model in half-precision (e.g. `torch.float16` or `torch.bfloat16`).
|
| 68 |
+
|
| 69 |
+
On a local benchmark (A100-40GB, PyTorch 2.3.0, OS Ubuntu 22.04) with `float32` and `google/vit-hybrid-base-bit-384` model, we saw the following speedups during inference.
|
| 70 |
+
|
| 71 |
+
| Batch size | Average inference time (ms), eager mode | Average inference time (ms), sdpa model | Speed up, Sdpa / Eager (x) |
|
| 72 |
+
|--------------|-------------------------------------------|-------------------------------------------|------------------------------|
|
| 73 |
+
| 1 | 29 | 18 | 1.61 |
|
| 74 |
+
| 2 | 26 | 18 | 1.44 |
|
| 75 |
+
| 4 | 25 | 18 | 1.39 |
|
| 76 |
+
| 8 | 34 | 24 | 1.42 |
|
| 77 |
+
|
| 78 |
+
## Resources
|
| 79 |
+
|
| 80 |
+
A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with ViT Hybrid.
|
| 81 |
+
|
| 82 |
+
<PipelineTag pipeline="image-classification"/>
|
| 83 |
+
|
| 84 |
+
- [`ViTHybridForImageClassification`] 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).
|
| 85 |
+
- See also: [Image classification task guide](../tasks/image_classification)
|
| 86 |
+
|
| 87 |
+
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.
|
| 88 |
+
|
| 89 |
+
## ViTHybridConfig
|
| 90 |
+
|
| 91 |
+
[[autodoc]] ViTHybridConfig
|
| 92 |
+
|
| 93 |
+
## ViTHybridImageProcessor
|
| 94 |
+
|
| 95 |
+
[[autodoc]] ViTHybridImageProcessor
|
| 96 |
+
- preprocess
|
| 97 |
+
|
| 98 |
+
## ViTHybridModel
|
| 99 |
+
|
| 100 |
+
[[autodoc]] ViTHybridModel
|
| 101 |
+
- forward
|
| 102 |
+
|
| 103 |
+
## ViTHybridForImageClassification
|
| 104 |
+
|
| 105 |
+
[[autodoc]] ViTHybridForImageClassification
|
| 106 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/vit_mae.md
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# ViTMAE
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
The ViTMAE model was proposed in [Masked Autoencoders Are Scalable Vision Learners](https://arxiv.org/abs/2111.06377v2) by Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li,
|
| 22 |
+
Piotr Dollár, Ross Girshick. The paper shows that, by pre-training a Vision Transformer (ViT) to reconstruct pixel values for masked patches, one can get results after
|
| 23 |
+
fine-tuning that outperform supervised pre-training.
|
| 24 |
+
|
| 25 |
+
The abstract from the paper is the following:
|
| 26 |
+
|
| 27 |
+
*This paper shows that masked autoencoders (MAE) are scalable self-supervised learners for computer vision. Our MAE approach is simple: we mask random patches of the
|
| 28 |
+
input image and reconstruct the missing pixels. It is based on two core designs. First, we develop an asymmetric encoder-decoder architecture, with an encoder that operates
|
| 29 |
+
only on the visible subset of patches (without mask tokens), along with a lightweight decoder that reconstructs the original image from the latent representation and mask
|
| 30 |
+
tokens. Second, we find that masking a high proportion of the input image, e.g., 75%, yields a nontrivial and meaningful self-supervisory task. Coupling these two designs
|
| 31 |
+
enables us to train large models efficiently and effectively: we accelerate training (by 3x or more) and improve accuracy. Our scalable approach allows for learning high-capacity
|
| 32 |
+
models that generalize well: e.g., a vanilla ViT-Huge model achieves the best accuracy (87.8%) among methods that use only ImageNet-1K data. Transfer performance in downstream
|
| 33 |
+
tasks outperforms supervised pre-training and shows promising scaling behavior.*
|
| 34 |
+
|
| 35 |
+
<img src="https://user-images.githubusercontent.com/11435359/146857310-f258c86c-fde6-48e8-9cee-badd2b21bd2c.png"
|
| 36 |
+
alt="drawing" width="600"/>
|
| 37 |
+
|
| 38 |
+
<small> MAE architecture. Taken from the <a href="https://arxiv.org/abs/2111.06377">original paper.</a> </small>
|
| 39 |
+
|
| 40 |
+
This model was contributed by [nielsr](https://huggingface.co/nielsr). TensorFlow version of the model was contributed by [sayakpaul](https://github.com/sayakpaul) and
|
| 41 |
+
[ariG23498](https://github.com/ariG23498) (equal contribution). The original code can be found [here](https://github.com/facebookresearch/mae).
|
| 42 |
+
|
| 43 |
+
## Usage tips
|
| 44 |
+
|
| 45 |
+
- MAE (masked auto encoding) is a method for self-supervised pre-training of Vision Transformers (ViTs). The pre-training objective is relatively simple:
|
| 46 |
+
by masking a large portion (75%) of the image patches, the model must reconstruct raw pixel values. One can use [`ViTMAEForPreTraining`] for this purpose.
|
| 47 |
+
- After pre-training, one "throws away" the decoder used to reconstruct pixels, and one uses the encoder for fine-tuning/linear probing. This means that after
|
| 48 |
+
fine-tuning, one can directly plug in the weights into a [`ViTForImageClassification`].
|
| 49 |
+
- One can use [`ViTImageProcessor`] to prepare images for the model. See the code examples for more info.
|
| 50 |
+
- Note that the encoder of MAE is only used to encode the visual patches. The encoded patches are then concatenated with mask tokens, which the decoder (which also
|
| 51 |
+
consists of Transformer blocks) takes as input. Each mask token is a shared, learned vector that indicates the presence of a missing patch to be predicted. Fixed
|
| 52 |
+
sin/cos position embeddings are added both to the input of the encoder and the decoder.
|
| 53 |
+
- For a visual understanding of how MAEs work you can check out this [post](https://keras.io/examples/vision/masked_image_modeling/).
|
| 54 |
+
|
| 55 |
+
### Using Scaled Dot Product Attention (SDPA)
|
| 56 |
+
|
| 57 |
+
PyTorch includes a native scaled dot-product attention (SDPA) operator as part of `torch.nn.functional`. This function
|
| 58 |
+
encompasses several implementations that can be applied depending on the inputs and the hardware in use. See the
|
| 59 |
+
[official documentation](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html)
|
| 60 |
+
or the [GPU Inference](https://huggingface.co/docs/transformers/main/en/perf_infer_gpu_one#pytorch-scaled-dot-product-attention)
|
| 61 |
+
page for more information.
|
| 62 |
+
|
| 63 |
+
SDPA is used by default for `torch>=2.1.1` when an implementation is available, but you may also set
|
| 64 |
+
`attn_implementation="sdpa"` in `from_pretrained()` to explicitly request SDPA to be used.
|
| 65 |
+
|
| 66 |
+
```
|
| 67 |
+
from transformers import ViTMAEModel
|
| 68 |
+
model = ViTMAEModel.from_pretrained("facebook/vit-mae-base", attn_implementation="sdpa", torch_dtype=torch.float16)
|
| 69 |
+
...
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
For the best speedups, we recommend loading the model in half-precision (e.g. `torch.float16` or `torch.bfloat16`).
|
| 73 |
+
|
| 74 |
+
On a local benchmark (A100-40GB, PyTorch 2.3.0, OS Ubuntu 22.04) with `float32` and `facebook/vit-mae-base` model, we saw the following speedups during inference.
|
| 75 |
+
|
| 76 |
+
| Batch size | Average inference time (ms), eager mode | Average inference time (ms), sdpa model | Speed up, Sdpa / Eager (x) |
|
| 77 |
+
|--------------|-------------------------------------------|-------------------------------------------|------------------------------|
|
| 78 |
+
| 1 | 11 | 6 | 1.83 |
|
| 79 |
+
| 2 | 8 | 6 | 1.33 |
|
| 80 |
+
| 4 | 8 | 6 | 1.33 |
|
| 81 |
+
| 8 | 8 | 6 | 1.33 |
|
| 82 |
+
|
| 83 |
+
## Resources
|
| 84 |
+
|
| 85 |
+
A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with ViTMAE.
|
| 86 |
+
|
| 87 |
+
- [`ViTMAEForPreTraining`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-pretraining), allowing you to pre-train the model from scratch/further pre-train the model on custom data.
|
| 88 |
+
- A notebook that illustrates how to visualize reconstructed pixel values with [`ViTMAEForPreTraining`] can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/ViTMAE/ViT_MAE_visualization_demo.ipynb).
|
| 89 |
+
|
| 90 |
+
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.
|
| 91 |
+
|
| 92 |
+
## ViTMAEConfig
|
| 93 |
+
|
| 94 |
+
[[autodoc]] ViTMAEConfig
|
| 95 |
+
|
| 96 |
+
<frameworkcontent>
|
| 97 |
+
<pt>
|
| 98 |
+
|
| 99 |
+
## ViTMAEModel
|
| 100 |
+
|
| 101 |
+
[[autodoc]] ViTMAEModel
|
| 102 |
+
- forward
|
| 103 |
+
|
| 104 |
+
## ViTMAEForPreTraining
|
| 105 |
+
|
| 106 |
+
[[autodoc]] transformers.ViTMAEForPreTraining
|
| 107 |
+
- forward
|
| 108 |
+
|
| 109 |
+
</pt>
|
| 110 |
+
<tf>
|
| 111 |
+
|
| 112 |
+
## TFViTMAEModel
|
| 113 |
+
|
| 114 |
+
[[autodoc]] TFViTMAEModel
|
| 115 |
+
- call
|
| 116 |
+
|
| 117 |
+
## TFViTMAEForPreTraining
|
| 118 |
+
|
| 119 |
+
[[autodoc]] transformers.TFViTMAEForPreTraining
|
| 120 |
+
- call
|
| 121 |
+
|
| 122 |
+
</tf>
|
| 123 |
+
</frameworkcontent>
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/vit_msn.md
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# ViTMSN
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
The ViTMSN model was proposed in [Masked Siamese Networks for Label-Efficient Learning](https://arxiv.org/abs/2204.07141) by Mahmoud Assran, Mathilde Caron, Ishan Misra, Piotr Bojanowski, Florian Bordes,
|
| 22 |
+
Pascal Vincent, Armand Joulin, Michael Rabbat, Nicolas Ballas. The paper presents a joint-embedding architecture to match the prototypes
|
| 23 |
+
of masked patches with that of the unmasked patches. With this setup, their method yields excellent performance in the low-shot and extreme low-shot
|
| 24 |
+
regimes.
|
| 25 |
+
|
| 26 |
+
The abstract from the paper is the following:
|
| 27 |
+
|
| 28 |
+
*We propose Masked Siamese Networks (MSN), a self-supervised learning framework for learning image representations. Our
|
| 29 |
+
approach matches the representation of an image view containing randomly masked patches to the representation of the original
|
| 30 |
+
unmasked image. This self-supervised pre-training strategy is particularly scalable when applied to Vision Transformers since only the
|
| 31 |
+
unmasked patches are processed by the network. As a result, MSNs improve the scalability of joint-embedding architectures,
|
| 32 |
+
while producing representations of a high semantic level that perform competitively on low-shot image classification. For instance,
|
| 33 |
+
on ImageNet-1K, with only 5,000 annotated images, our base MSN model achieves 72.4% top-1 accuracy,
|
| 34 |
+
and with 1% of ImageNet-1K labels, we achieve 75.7% top-1 accuracy, setting a new state-of-the-art for self-supervised learning on this benchmark.*
|
| 35 |
+
|
| 36 |
+
<img src="https://i.ibb.co/W6PQMdC/Screenshot-2022-09-13-at-9-08-40-AM.png" alt="drawing" width="600"/>
|
| 37 |
+
|
| 38 |
+
<small> MSN architecture. Taken from the <a href="https://arxiv.org/abs/2204.07141">original paper.</a> </small>
|
| 39 |
+
|
| 40 |
+
This model was contributed by [sayakpaul](https://huggingface.co/sayakpaul). The original code can be found [here](https://github.com/facebookresearch/msn).
|
| 41 |
+
|
| 42 |
+
## Usage tips
|
| 43 |
+
|
| 44 |
+
- MSN (masked siamese networks) is a method for self-supervised pre-training of Vision Transformers (ViTs). The pre-training
|
| 45 |
+
objective is to match the prototypes assigned to the unmasked views of the images to that of the masked views of the same images.
|
| 46 |
+
- The authors have only released pre-trained weights of the backbone (ImageNet-1k pre-training). So, to use that on your own image classification dataset,
|
| 47 |
+
use the [`ViTMSNForImageClassification`] class which is initialized from [`ViTMSNModel`]. Follow
|
| 48 |
+
[this notebook](https://github.com/huggingface/notebooks/blob/main/examples/image_classification.ipynb) for a detailed tutorial on fine-tuning.
|
| 49 |
+
- MSN is particularly useful in the low-shot and extreme low-shot regimes. Notably, it achieves 75.7% top-1 accuracy with only 1% of ImageNet-1K
|
| 50 |
+
labels when fine-tuned.
|
| 51 |
+
|
| 52 |
+
### Using Scaled Dot Product Attention (SDPA)
|
| 53 |
+
|
| 54 |
+
PyTorch includes a native scaled dot-product attention (SDPA) operator as part of `torch.nn.functional`. This function
|
| 55 |
+
encompasses several implementations that can be applied depending on the inputs and the hardware in use. See the
|
| 56 |
+
[official documentation](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html)
|
| 57 |
+
or the [GPU Inference](https://huggingface.co/docs/transformers/main/en/perf_infer_gpu_one#pytorch-scaled-dot-product-attention)
|
| 58 |
+
page for more information.
|
| 59 |
+
|
| 60 |
+
SDPA is used by default for `torch>=2.1.1` when an implementation is available, but you may also set
|
| 61 |
+
`attn_implementation="sdpa"` in `from_pretrained()` to explicitly request SDPA to be used.
|
| 62 |
+
|
| 63 |
+
```
|
| 64 |
+
from transformers import ViTMSNForImageClassification
|
| 65 |
+
model = ViTMSNForImageClassification.from_pretrained("facebook/vit-msn-base", attn_implementation="sdpa", torch_dtype=torch.float16)
|
| 66 |
+
...
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
For the best speedups, we recommend loading the model in half-precision (e.g. `torch.float16` or `torch.bfloat16`).
|
| 70 |
+
|
| 71 |
+
On a local benchmark (A100-40GB, PyTorch 2.3.0, OS Ubuntu 22.04) with `float32` and `facebook/vit-msn-base` model, we saw the following speedups during inference.
|
| 72 |
+
|
| 73 |
+
| Batch size | Average inference time (ms), eager mode | Average inference time (ms), sdpa model | Speed up, Sdpa / Eager (x) |
|
| 74 |
+
|--------------|-------------------------------------------|-------------------------------------------|------------------------------|
|
| 75 |
+
| 1 | 7 | 6 | 1.17 |
|
| 76 |
+
| 2 | 8 | 6 | 1.33 |
|
| 77 |
+
| 4 | 8 | 6 | 1.33 |
|
| 78 |
+
| 8 | 8 | 6 | 1.33 |
|
| 79 |
+
|
| 80 |
+
## Resources
|
| 81 |
+
|
| 82 |
+
A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with ViT MSN.
|
| 83 |
+
|
| 84 |
+
<PipelineTag pipeline="image-classification"/>
|
| 85 |
+
|
| 86 |
+
- [`ViTMSNForImageClassification`] 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).
|
| 87 |
+
- See also: [Image classification task guide](../tasks/image_classification)
|
| 88 |
+
|
| 89 |
+
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.
|
| 90 |
+
|
| 91 |
+
## ViTMSNConfig
|
| 92 |
+
|
| 93 |
+
[[autodoc]] ViTMSNConfig
|
| 94 |
+
|
| 95 |
+
## ViTMSNModel
|
| 96 |
+
|
| 97 |
+
[[autodoc]] ViTMSNModel
|
| 98 |
+
- forward
|
| 99 |
+
|
| 100 |
+
## ViTMSNForImageClassification
|
| 101 |
+
|
| 102 |
+
[[autodoc]] ViTMSNForImageClassification
|
| 103 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/vitdet.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
-->
|
| 12 |
+
|
| 13 |
+
# ViTDet
|
| 14 |
+
|
| 15 |
+
## Overview
|
| 16 |
+
|
| 17 |
+
The ViTDet model was proposed in [Exploring Plain Vision Transformer Backbones for Object Detection](https://arxiv.org/abs/2203.16527) by Yanghao Li, Hanzi Mao, Ross Girshick, Kaiming He.
|
| 18 |
+
VitDet leverages the plain [Vision Transformer](vit) for the task of object detection.
|
| 19 |
+
|
| 20 |
+
The abstract from the paper is the following:
|
| 21 |
+
|
| 22 |
+
*We explore the plain, non-hierarchical Vision Transformer (ViT) as a backbone network for object detection. This design enables the original ViT architecture to be fine-tuned for object detection without needing to redesign a hierarchical backbone for pre-training. With minimal adaptations for fine-tuning, our plain-backbone detector can achieve competitive results. Surprisingly, we observe: (i) it is sufficient to build a simple feature pyramid from a single-scale feature map (without the common FPN design) and (ii) it is sufficient to use window attention (without shifting) aided with very few cross-window propagation blocks. With plain ViT backbones pre-trained as Masked Autoencoders (MAE), our detector, named ViTDet, can compete with the previous leading methods that were all based on hierarchical backbones, reaching up to 61.3 AP_box on the COCO dataset using only ImageNet-1K pre-training. We hope our study will draw attention to research on plain-backbone detectors.*
|
| 23 |
+
|
| 24 |
+
This model was contributed by [nielsr](https://huggingface.co/nielsr).
|
| 25 |
+
The original code can be found [here](https://github.com/facebookresearch/detectron2/tree/main/projects/ViTDet).
|
| 26 |
+
|
| 27 |
+
Tips:
|
| 28 |
+
|
| 29 |
+
- At the moment, only the backbone is available.
|
| 30 |
+
|
| 31 |
+
## VitDetConfig
|
| 32 |
+
|
| 33 |
+
[[autodoc]] VitDetConfig
|
| 34 |
+
|
| 35 |
+
## VitDetModel
|
| 36 |
+
|
| 37 |
+
[[autodoc]] VitDetModel
|
| 38 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/vitmatte.md
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
-->
|
| 12 |
+
|
| 13 |
+
# ViTMatte
|
| 14 |
+
|
| 15 |
+
## Overview
|
| 16 |
+
|
| 17 |
+
The ViTMatte model was proposed in [Boosting Image Matting with Pretrained Plain Vision Transformers](https://arxiv.org/abs/2305.15272) by Jingfeng Yao, Xinggang Wang, Shusheng Yang, Baoyuan Wang.
|
| 18 |
+
ViTMatte leverages plain [Vision Transformers](vit) for the task of image matting, which is the process of accurately estimating the foreground object in images and videos.
|
| 19 |
+
|
| 20 |
+
The abstract from the paper is the following:
|
| 21 |
+
|
| 22 |
+
*Recently, plain vision Transformers (ViTs) have shown impressive performance on various computer vision tasks, thanks to their strong modeling capacity and large-scale pretraining. However, they have not yet conquered the problem of image matting. We hypothesize that image matting could also be boosted by ViTs and present a new efficient and robust ViT-based matting system, named ViTMatte. Our method utilizes (i) a hybrid attention mechanism combined with a convolution neck to help ViTs achieve an excellent performance-computation trade-off in matting tasks. (ii) Additionally, we introduce the detail capture module, which just consists of simple lightweight convolutions to complement the detailed information required by matting. To the best of our knowledge, ViTMatte is the first work to unleash the potential of ViT on image matting with concise adaptation. It inherits many superior properties from ViT to matting, including various pretraining strategies, concise architecture design, and flexible inference strategies. We evaluate ViTMatte on Composition-1k and Distinctions-646, the most commonly used benchmark for image matting, our method achieves state-of-the-art performance and outperforms prior matting works by a large margin.*
|
| 23 |
+
|
| 24 |
+
This model was contributed by [nielsr](https://huggingface.co/nielsr).
|
| 25 |
+
The original code can be found [here](https://github.com/hustvl/ViTMatte).
|
| 26 |
+
|
| 27 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/vitmatte_architecture.png"
|
| 28 |
+
alt="drawing" width="600"/>
|
| 29 |
+
|
| 30 |
+
<small> ViTMatte high-level overview. Taken from the <a href="https://arxiv.org/abs/2305.15272">original paper.</a> </small>
|
| 31 |
+
|
| 32 |
+
## Resources
|
| 33 |
+
|
| 34 |
+
A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with ViTMatte.
|
| 35 |
+
|
| 36 |
+
- A demo notebook regarding inference with [`VitMatteForImageMatting`], including background replacement, can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/ViTMatte).
|
| 37 |
+
|
| 38 |
+
<Tip>
|
| 39 |
+
|
| 40 |
+
The model expects both the image and trimap (concatenated) as input. Use [`ViTMatteImageProcessor`] for this purpose.
|
| 41 |
+
</Tip>
|
| 42 |
+
|
| 43 |
+
## VitMatteConfig
|
| 44 |
+
|
| 45 |
+
[[autodoc]] VitMatteConfig
|
| 46 |
+
|
| 47 |
+
## VitMatteImageProcessor
|
| 48 |
+
|
| 49 |
+
[[autodoc]] VitMatteImageProcessor
|
| 50 |
+
- preprocess
|
| 51 |
+
|
| 52 |
+
## VitMatteForImageMatting
|
| 53 |
+
|
| 54 |
+
[[autodoc]] VitMatteForImageMatting
|
| 55 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/vitpose.md
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
-->
|
| 12 |
+
|
| 13 |
+
# VitPose
|
| 14 |
+
|
| 15 |
+
## Overview
|
| 16 |
+
|
| 17 |
+
The VitPose model was proposed in [ViTPose: Simple Vision Transformer Baselines for Human Pose Estimation](https://arxiv.org/abs/2204.12484) by Yufei Xu, Jing Zhang, Qiming Zhang, Dacheng Tao. VitPose employs a standard, non-hierarchical [Vision Transformer](https://arxiv.org/pdf/2010.11929v2) as backbone for the task of keypoint estimation. A simple decoder head is added on top to predict the heatmaps from a given image. Despite its simplicity, the model gets state-of-the-art results on the challenging MS COCO Keypoint Detection benchmark.
|
| 18 |
+
|
| 19 |
+
The abstract from the paper is the following:
|
| 20 |
+
|
| 21 |
+
*Although no specific domain knowledge is considered in the design, plain vision transformers have shown excellent performance in visual recognition tasks. However, little effort has been made to reveal the potential of such simple structures for pose estimation tasks. In this paper, we show the surprisingly good capabilities of plain vision transformers for pose estimation from various aspects, namely simplicity in model structure, scalability in model size, flexibility in training paradigm, and transferability of knowledge between models, through a simple baseline model called ViTPose. Specifically, ViTPose employs plain and non-hierarchical vision transformers as backbones to extract features for a given person instance and a lightweight decoder for pose estimation. It can be scaled up from 100M to 1B parameters by taking the advantages of the scalable model capacity and high parallelism of transformers, setting a new Pareto front between throughput and performance. Besides, ViTPose is very flexible regarding the attention type, input resolution, pre-training and finetuning strategy, as well as dealing with multiple pose tasks. We also empirically demonstrate that the knowledge of large ViTPose models can be easily transferred to small ones via a simple knowledge token. Experimental results show that our basic ViTPose model outperforms representative methods on the challenging MS COCO Keypoint Detection benchmark, while the largest model sets a new state-of-the-art.*
|
| 22 |
+
|
| 23 |
+

|
| 24 |
+
|
| 25 |
+
This model was contributed by [nielsr](https://huggingface.co/nielsr) and [sangbumchoi](https://github.com/SangbumChoi).
|
| 26 |
+
The original code can be found [here](https://github.com/ViTAE-Transformer/ViTPose).
|
| 27 |
+
|
| 28 |
+
## Usage Tips
|
| 29 |
+
|
| 30 |
+
ViTPose is a so-called top-down keypoint detection model. This means that one first uses an object detector, like [RT-DETR](rt_detr.md), to detect people (or other instances) in an image. Next, ViTPose takes the cropped images as input and predicts the keypoints.
|
| 31 |
+
|
| 32 |
+
```py
|
| 33 |
+
import torch
|
| 34 |
+
import requests
|
| 35 |
+
import numpy as np
|
| 36 |
+
|
| 37 |
+
from PIL import Image
|
| 38 |
+
|
| 39 |
+
from transformers import (
|
| 40 |
+
AutoProcessor,
|
| 41 |
+
RTDetrForObjectDetection,
|
| 42 |
+
VitPoseForPoseEstimation,
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 46 |
+
|
| 47 |
+
url = "http://images.cocodataset.org/val2017/000000000139.jpg"
|
| 48 |
+
image = Image.open(requests.get(url, stream=True).raw)
|
| 49 |
+
|
| 50 |
+
# ------------------------------------------------------------------------
|
| 51 |
+
# Stage 1. Detect humans on the image
|
| 52 |
+
# ------------------------------------------------------------------------
|
| 53 |
+
|
| 54 |
+
# You can choose detector by your choice
|
| 55 |
+
person_image_processor = AutoProcessor.from_pretrained("PekingU/rtdetr_r50vd_coco_o365")
|
| 56 |
+
person_model = RTDetrForObjectDetection.from_pretrained("PekingU/rtdetr_r50vd_coco_o365", device_map=device)
|
| 57 |
+
|
| 58 |
+
inputs = person_image_processor(images=image, return_tensors="pt").to(device)
|
| 59 |
+
|
| 60 |
+
with torch.no_grad():
|
| 61 |
+
outputs = person_model(**inputs)
|
| 62 |
+
|
| 63 |
+
results = person_image_processor.post_process_object_detection(
|
| 64 |
+
outputs, target_sizes=torch.tensor([(image.height, image.width)]), threshold=0.3
|
| 65 |
+
)
|
| 66 |
+
result = results[0] # take first image results
|
| 67 |
+
|
| 68 |
+
# Human label refers 0 index in COCO dataset
|
| 69 |
+
person_boxes = result["boxes"][result["labels"] == 0]
|
| 70 |
+
person_boxes = person_boxes.cpu().numpy()
|
| 71 |
+
|
| 72 |
+
# Convert boxes from VOC (x1, y1, x2, y2) to COCO (x1, y1, w, h) format
|
| 73 |
+
person_boxes[:, 2] = person_boxes[:, 2] - person_boxes[:, 0]
|
| 74 |
+
person_boxes[:, 3] = person_boxes[:, 3] - person_boxes[:, 1]
|
| 75 |
+
|
| 76 |
+
# ------------------------------------------------------------------------
|
| 77 |
+
# Stage 2. Detect keypoints for each person found
|
| 78 |
+
# ------------------------------------------------------------------------
|
| 79 |
+
|
| 80 |
+
image_processor = AutoProcessor.from_pretrained("usyd-community/vitpose-base-simple")
|
| 81 |
+
model = VitPoseForPoseEstimation.from_pretrained("usyd-community/vitpose-base-simple", device_map=device)
|
| 82 |
+
|
| 83 |
+
inputs = image_processor(image, boxes=[person_boxes], return_tensors="pt").to(device)
|
| 84 |
+
|
| 85 |
+
with torch.no_grad():
|
| 86 |
+
outputs = model(**inputs)
|
| 87 |
+
|
| 88 |
+
pose_results = image_processor.post_process_pose_estimation(outputs, boxes=[person_boxes])
|
| 89 |
+
image_pose_result = pose_results[0] # results for first image
|
| 90 |
+
```
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
### Visualization for supervision user
|
| 94 |
+
```py
|
| 95 |
+
import supervision as sv
|
| 96 |
+
|
| 97 |
+
xy = torch.stack([pose_result['keypoints'] for pose_result in image_pose_result]).cpu().numpy()
|
| 98 |
+
scores = torch.stack([pose_result['scores'] for pose_result in image_pose_result]).cpu().numpy()
|
| 99 |
+
|
| 100 |
+
key_points = sv.KeyPoints(
|
| 101 |
+
xy=xy, confidence=scores
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
edge_annotator = sv.EdgeAnnotator(
|
| 105 |
+
color=sv.Color.GREEN,
|
| 106 |
+
thickness=1
|
| 107 |
+
)
|
| 108 |
+
vertex_annotator = sv.VertexAnnotator(
|
| 109 |
+
color=sv.Color.RED,
|
| 110 |
+
radius=2
|
| 111 |
+
)
|
| 112 |
+
annotated_frame = edge_annotator.annotate(
|
| 113 |
+
scene=image.copy(),
|
| 114 |
+
key_points=key_points
|
| 115 |
+
)
|
| 116 |
+
annotated_frame = vertex_annotator.annotate(
|
| 117 |
+
scene=annotated_frame,
|
| 118 |
+
key_points=key_points
|
| 119 |
+
)
|
| 120 |
+
```
|
| 121 |
+
|
| 122 |
+
### Visualization for advanced user
|
| 123 |
+
```py
|
| 124 |
+
import math
|
| 125 |
+
import cv2
|
| 126 |
+
|
| 127 |
+
def draw_points(image, keypoints, scores, pose_keypoint_color, keypoint_score_threshold, radius, show_keypoint_weight):
|
| 128 |
+
if pose_keypoint_color is not None:
|
| 129 |
+
assert len(pose_keypoint_color) == len(keypoints)
|
| 130 |
+
for kid, (kpt, kpt_score) in enumerate(zip(keypoints, scores)):
|
| 131 |
+
x_coord, y_coord = int(kpt[0]), int(kpt[1])
|
| 132 |
+
if kpt_score > keypoint_score_threshold:
|
| 133 |
+
color = tuple(int(c) for c in pose_keypoint_color[kid])
|
| 134 |
+
if show_keypoint_weight:
|
| 135 |
+
cv2.circle(image, (int(x_coord), int(y_coord)), radius, color, -1)
|
| 136 |
+
transparency = max(0, min(1, kpt_score))
|
| 137 |
+
cv2.addWeighted(image, transparency, image, 1 - transparency, 0, dst=image)
|
| 138 |
+
else:
|
| 139 |
+
cv2.circle(image, (int(x_coord), int(y_coord)), radius, color, -1)
|
| 140 |
+
|
| 141 |
+
def draw_links(image, keypoints, scores, keypoint_edges, link_colors, keypoint_score_threshold, thickness, show_keypoint_weight, stick_width = 2):
|
| 142 |
+
height, width, _ = image.shape
|
| 143 |
+
if keypoint_edges is not None and link_colors is not None:
|
| 144 |
+
assert len(link_colors) == len(keypoint_edges)
|
| 145 |
+
for sk_id, sk in enumerate(keypoint_edges):
|
| 146 |
+
x1, y1, score1 = (int(keypoints[sk[0], 0]), int(keypoints[sk[0], 1]), scores[sk[0]])
|
| 147 |
+
x2, y2, score2 = (int(keypoints[sk[1], 0]), int(keypoints[sk[1], 1]), scores[sk[1]])
|
| 148 |
+
if (
|
| 149 |
+
x1 > 0
|
| 150 |
+
and x1 < width
|
| 151 |
+
and y1 > 0
|
| 152 |
+
and y1 < height
|
| 153 |
+
and x2 > 0
|
| 154 |
+
and x2 < width
|
| 155 |
+
and y2 > 0
|
| 156 |
+
and y2 < height
|
| 157 |
+
and score1 > keypoint_score_threshold
|
| 158 |
+
and score2 > keypoint_score_threshold
|
| 159 |
+
):
|
| 160 |
+
color = tuple(int(c) for c in link_colors[sk_id])
|
| 161 |
+
if show_keypoint_weight:
|
| 162 |
+
X = (x1, x2)
|
| 163 |
+
Y = (y1, y2)
|
| 164 |
+
mean_x = np.mean(X)
|
| 165 |
+
mean_y = np.mean(Y)
|
| 166 |
+
length = ((Y[0] - Y[1]) ** 2 + (X[0] - X[1]) ** 2) ** 0.5
|
| 167 |
+
angle = math.degrees(math.atan2(Y[0] - Y[1], X[0] - X[1]))
|
| 168 |
+
polygon = cv2.ellipse2Poly(
|
| 169 |
+
(int(mean_x), int(mean_y)), (int(length / 2), int(stick_width)), int(angle), 0, 360, 1
|
| 170 |
+
)
|
| 171 |
+
cv2.fillConvexPoly(image, polygon, color)
|
| 172 |
+
transparency = max(0, min(1, 0.5 * (keypoints[sk[0], 2] + keypoints[sk[1], 2])))
|
| 173 |
+
cv2.addWeighted(image, transparency, image, 1 - transparency, 0, dst=image)
|
| 174 |
+
else:
|
| 175 |
+
cv2.line(image, (x1, y1), (x2, y2), color, thickness=thickness)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
# Note: keypoint_edges and color palette are dataset-specific
|
| 179 |
+
keypoint_edges = model.config.edges
|
| 180 |
+
|
| 181 |
+
palette = np.array(
|
| 182 |
+
[
|
| 183 |
+
[255, 128, 0],
|
| 184 |
+
[255, 153, 51],
|
| 185 |
+
[255, 178, 102],
|
| 186 |
+
[230, 230, 0],
|
| 187 |
+
[255, 153, 255],
|
| 188 |
+
[153, 204, 255],
|
| 189 |
+
[255, 102, 255],
|
| 190 |
+
[255, 51, 255],
|
| 191 |
+
[102, 178, 255],
|
| 192 |
+
[51, 153, 255],
|
| 193 |
+
[255, 153, 153],
|
| 194 |
+
[255, 102, 102],
|
| 195 |
+
[255, 51, 51],
|
| 196 |
+
[153, 255, 153],
|
| 197 |
+
[102, 255, 102],
|
| 198 |
+
[51, 255, 51],
|
| 199 |
+
[0, 255, 0],
|
| 200 |
+
[0, 0, 255],
|
| 201 |
+
[255, 0, 0],
|
| 202 |
+
[255, 255, 255],
|
| 203 |
+
]
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
link_colors = palette[[0, 0, 0, 0, 7, 7, 7, 9, 9, 9, 9, 9, 16, 16, 16, 16, 16, 16, 16]]
|
| 207 |
+
keypoint_colors = palette[[16, 16, 16, 16, 16, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0]]
|
| 208 |
+
|
| 209 |
+
numpy_image = np.array(image)
|
| 210 |
+
|
| 211 |
+
for pose_result in image_pose_result:
|
| 212 |
+
scores = np.array(pose_result["scores"])
|
| 213 |
+
keypoints = np.array(pose_result["keypoints"])
|
| 214 |
+
|
| 215 |
+
# draw each point on image
|
| 216 |
+
draw_points(numpy_image, keypoints, scores, keypoint_colors, keypoint_score_threshold=0.3, radius=4, show_keypoint_weight=False)
|
| 217 |
+
|
| 218 |
+
# draw links
|
| 219 |
+
draw_links(numpy_image, keypoints, scores, keypoint_edges, link_colors, keypoint_score_threshold=0.3, thickness=1, show_keypoint_weight=False)
|
| 220 |
+
|
| 221 |
+
pose_image = Image.fromarray(numpy_image)
|
| 222 |
+
pose_image
|
| 223 |
+
```
|
| 224 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/vitpose-coco.jpg" alt="drawing" width="600"/>
|
| 225 |
+
|
| 226 |
+
### MoE backbone
|
| 227 |
+
|
| 228 |
+
To enable MoE (Mixture of Experts) function in the backbone, user has to give appropriate configuration such as `num_experts` and input value `dataset_index` to the backbone model. However, it is not used in default parameters. Below is the code snippet for usage of MoE function.
|
| 229 |
+
|
| 230 |
+
```py
|
| 231 |
+
>>> from transformers import VitPoseBackboneConfig, VitPoseBackbone
|
| 232 |
+
>>> import torch
|
| 233 |
+
|
| 234 |
+
>>> config = VitPoseBackboneConfig(num_experts=3, out_indices=[-1])
|
| 235 |
+
>>> model = VitPoseBackbone(config)
|
| 236 |
+
|
| 237 |
+
>>> pixel_values = torch.randn(3, 3, 256, 192)
|
| 238 |
+
>>> dataset_index = torch.tensor([1, 2, 3])
|
| 239 |
+
>>> outputs = model(pixel_values, dataset_index)
|
| 240 |
+
```
|
| 241 |
+
|
| 242 |
+
## VitPoseImageProcessor
|
| 243 |
+
|
| 244 |
+
[[autodoc]] VitPoseImageProcessor
|
| 245 |
+
- preprocess
|
| 246 |
+
|
| 247 |
+
## VitPoseConfig
|
| 248 |
+
|
| 249 |
+
[[autodoc]] VitPoseConfig
|
| 250 |
+
|
| 251 |
+
## VitPoseForPoseEstimation
|
| 252 |
+
|
| 253 |
+
[[autodoc]] VitPoseForPoseEstimation
|
| 254 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/vits.md
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
-->
|
| 12 |
+
|
| 13 |
+
# VITS
|
| 14 |
+
|
| 15 |
+
## Overview
|
| 16 |
+
|
| 17 |
+
The VITS model was proposed in [Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech](https://arxiv.org/abs/2106.06103) by Jaehyeon Kim, Jungil Kong, Juhee Son.
|
| 18 |
+
|
| 19 |
+
VITS (**V**ariational **I**nference with adversarial learning for end-to-end **T**ext-to-**S**peech) is an end-to-end
|
| 20 |
+
speech synthesis model that predicts a speech waveform conditional on an input text sequence. It is a conditional variational
|
| 21 |
+
autoencoder (VAE) comprised of a posterior encoder, decoder, and conditional prior.
|
| 22 |
+
|
| 23 |
+
A set of spectrogram-based acoustic features are predicted by the flow-based module, which is formed of a Transformer-based
|
| 24 |
+
text encoder and multiple coupling layers. The spectrogram is decoded using a stack of transposed convolutional layers,
|
| 25 |
+
much in the same style as the HiFi-GAN vocoder. Motivated by the one-to-many nature of the TTS problem, where the same text
|
| 26 |
+
input can be spoken in multiple ways, the model also includes a stochastic duration predictor, which allows the model to
|
| 27 |
+
synthesise speech with different rhythms from the same input text.
|
| 28 |
+
|
| 29 |
+
The model is trained end-to-end with a combination of losses derived from variational lower bound and adversarial training.
|
| 30 |
+
To improve the expressiveness of the model, normalizing flows are applied to the conditional prior distribution. During
|
| 31 |
+
inference, the text encodings are up-sampled based on the duration prediction module, and then mapped into the
|
| 32 |
+
waveform using a cascade of the flow module and HiFi-GAN decoder. Due to the stochastic nature of the duration predictor,
|
| 33 |
+
the model is non-deterministic, and thus requires a fixed seed to generate the same speech waveform.
|
| 34 |
+
|
| 35 |
+
The abstract from the paper is the following:
|
| 36 |
+
|
| 37 |
+
*Several recent end-to-end text-to-speech (TTS) models enabling single-stage training and parallel sampling have been proposed, but their sample quality does not match that of two-stage TTS systems. In this work, we present a parallel end-to-end TTS method that generates more natural sounding audio than current two-stage models. Our method adopts variational inference augmented with normalizing flows and an adversarial training process, which improves the expressive power of generative modeling. We also propose a stochastic duration predictor to synthesize speech with diverse rhythms from input text. With the uncertainty modeling over latent variables and the stochastic duration predictor, our method expresses the natural one-to-many relationship in which a text input can be spoken in multiple ways with different pitches and rhythms. A subjective human evaluation (mean opinion score, or MOS) on the LJ Speech, a single speaker dataset, shows that our method outperforms the best publicly available TTS systems and achieves a MOS comparable to ground truth.*
|
| 38 |
+
|
| 39 |
+
This model can also be used with TTS checkpoints from [Massively Multilingual Speech (MMS)](https://arxiv.org/abs/2305.13516)
|
| 40 |
+
as these checkpoints use the same architecture and a slightly modified tokenizer.
|
| 41 |
+
|
| 42 |
+
This model was contributed by [Matthijs](https://huggingface.co/Matthijs) and [sanchit-gandhi](https://huggingface.co/sanchit-gandhi). The original code can be found [here](https://github.com/jaywalnut310/vits).
|
| 43 |
+
|
| 44 |
+
## Usage examples
|
| 45 |
+
|
| 46 |
+
Both the VITS and MMS-TTS checkpoints can be used with the same API. Since the flow-based model is non-deterministic, it
|
| 47 |
+
is good practice to set a seed to ensure reproducibility of the outputs. For languages with a Roman alphabet,
|
| 48 |
+
such as English or French, the tokenizer can be used directly to pre-process the text inputs. The following code example
|
| 49 |
+
runs a forward pass using the MMS-TTS English checkpoint:
|
| 50 |
+
|
| 51 |
+
```python
|
| 52 |
+
import torch
|
| 53 |
+
from transformers import VitsTokenizer, VitsModel, set_seed
|
| 54 |
+
|
| 55 |
+
tokenizer = VitsTokenizer.from_pretrained("facebook/mms-tts-eng")
|
| 56 |
+
model = VitsModel.from_pretrained("facebook/mms-tts-eng")
|
| 57 |
+
|
| 58 |
+
inputs = tokenizer(text="Hello - my dog is cute", return_tensors="pt")
|
| 59 |
+
|
| 60 |
+
set_seed(555) # make deterministic
|
| 61 |
+
|
| 62 |
+
with torch.no_grad():
|
| 63 |
+
outputs = model(**inputs)
|
| 64 |
+
|
| 65 |
+
waveform = outputs.waveform[0]
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
The resulting waveform can be saved as a `.wav` file:
|
| 69 |
+
|
| 70 |
+
```python
|
| 71 |
+
import scipy
|
| 72 |
+
|
| 73 |
+
scipy.io.wavfile.write("techno.wav", rate=model.config.sampling_rate, data=waveform)
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
Or displayed in a Jupyter Notebook / Google Colab:
|
| 77 |
+
|
| 78 |
+
```python
|
| 79 |
+
from IPython.display import Audio
|
| 80 |
+
|
| 81 |
+
Audio(waveform, rate=model.config.sampling_rate)
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
For certain languages with a non-Roman alphabet, such as Arabic, Mandarin or Hindi, the [`uroman`](https://github.com/isi-nlp/uroman)
|
| 85 |
+
perl package is required to pre-process the text inputs to the Roman alphabet.
|
| 86 |
+
|
| 87 |
+
You can check whether you require the `uroman` package for your language by inspecting the `is_uroman` attribute of
|
| 88 |
+
the pre-trained `tokenizer`:
|
| 89 |
+
|
| 90 |
+
```python
|
| 91 |
+
from transformers import VitsTokenizer
|
| 92 |
+
|
| 93 |
+
tokenizer = VitsTokenizer.from_pretrained("facebook/mms-tts-eng")
|
| 94 |
+
print(tokenizer.is_uroman)
|
| 95 |
+
```
|
| 96 |
+
If the is_uroman attribute is `True`, the tokenizer will automatically apply the `uroman` package to your text inputs, but you need to install uroman if not already installed using:
|
| 97 |
+
```
|
| 98 |
+
pip install --upgrade uroman
|
| 99 |
+
```
|
| 100 |
+
Note: Python version required to use `uroman` as python package should be >= `3.10`.
|
| 101 |
+
You can use the tokenizer as usual without any additional preprocessing steps:
|
| 102 |
+
```python
|
| 103 |
+
import torch
|
| 104 |
+
from transformers import VitsTokenizer, VitsModel, set_seed
|
| 105 |
+
import os
|
| 106 |
+
import subprocess
|
| 107 |
+
|
| 108 |
+
tokenizer = VitsTokenizer.from_pretrained("facebook/mms-tts-kor")
|
| 109 |
+
model = VitsModel.from_pretrained("facebook/mms-tts-kor")
|
| 110 |
+
text = "이봐 무슨 일이야"
|
| 111 |
+
inputs = tokenizer(text=text, return_tensors="pt")
|
| 112 |
+
|
| 113 |
+
set_seed(555) # make deterministic
|
| 114 |
+
with torch.no_grad():
|
| 115 |
+
outputs = model(inputs["input_ids"])
|
| 116 |
+
|
| 117 |
+
waveform = outputs.waveform[0]
|
| 118 |
+
```
|
| 119 |
+
If you don't want to upgrade to python >= `3.10`, then you can use the `uroman` perl package to pre-process the text inputs to the Roman alphabet.
|
| 120 |
+
To do this, first clone the uroman repository to your local machine and set the bash variable `UROMAN` to the local path:
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
```bash
|
| 124 |
+
git clone https://github.com/isi-nlp/uroman.git
|
| 125 |
+
cd uroman
|
| 126 |
+
export UROMAN=$(pwd)
|
| 127 |
+
```
|
| 128 |
+
|
| 129 |
+
You can then pre-process the text input using the following code snippet. You can either rely on using the bash variable
|
| 130 |
+
`UROMAN` to point to the uroman repository, or you can pass the uroman directory as an argument to the `uromanize` function:
|
| 131 |
+
|
| 132 |
+
```python
|
| 133 |
+
import torch
|
| 134 |
+
from transformers import VitsTokenizer, VitsModel, set_seed
|
| 135 |
+
import os
|
| 136 |
+
import subprocess
|
| 137 |
+
|
| 138 |
+
tokenizer = VitsTokenizer.from_pretrained("facebook/mms-tts-kor")
|
| 139 |
+
model = VitsModel.from_pretrained("facebook/mms-tts-kor")
|
| 140 |
+
|
| 141 |
+
def uromanize(input_string, uroman_path):
|
| 142 |
+
"""Convert non-Roman strings to Roman using the `uroman` perl package."""
|
| 143 |
+
script_path = os.path.join(uroman_path, "bin", "uroman.pl")
|
| 144 |
+
|
| 145 |
+
command = ["perl", script_path]
|
| 146 |
+
|
| 147 |
+
process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
| 148 |
+
# Execute the perl command
|
| 149 |
+
stdout, stderr = process.communicate(input=input_string.encode())
|
| 150 |
+
|
| 151 |
+
if process.returncode != 0:
|
| 152 |
+
raise ValueError(f"Error {process.returncode}: {stderr.decode()}")
|
| 153 |
+
|
| 154 |
+
# Return the output as a string and skip the new-line character at the end
|
| 155 |
+
return stdout.decode()[:-1]
|
| 156 |
+
|
| 157 |
+
text = "이봐 무슨 일이야"
|
| 158 |
+
uromanized_text = uromanize(text, uroman_path=os.environ["UROMAN"])
|
| 159 |
+
|
| 160 |
+
inputs = tokenizer(text=uromanized_text, return_tensors="pt")
|
| 161 |
+
|
| 162 |
+
set_seed(555) # make deterministic
|
| 163 |
+
with torch.no_grad():
|
| 164 |
+
outputs = model(inputs["input_ids"])
|
| 165 |
+
|
| 166 |
+
waveform = outputs.waveform[0]
|
| 167 |
+
```
|
| 168 |
+
|
| 169 |
+
## VitsConfig
|
| 170 |
+
|
| 171 |
+
[[autodoc]] VitsConfig
|
| 172 |
+
|
| 173 |
+
## VitsTokenizer
|
| 174 |
+
|
| 175 |
+
[[autodoc]] VitsTokenizer
|
| 176 |
+
- __call__
|
| 177 |
+
- save_vocabulary
|
| 178 |
+
|
| 179 |
+
## VitsModel
|
| 180 |
+
|
| 181 |
+
[[autodoc]] VitsModel
|
| 182 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/vivit.md
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
-->
|
| 12 |
+
|
| 13 |
+
# Video Vision Transformer (ViViT)
|
| 14 |
+
|
| 15 |
+
## Overview
|
| 16 |
+
|
| 17 |
+
The Vivit model was proposed in [ViViT: A Video Vision Transformer](https://arxiv.org/abs/2103.15691) by Anurag Arnab, Mostafa Dehghani, Georg Heigold, Chen Sun, Mario Lučić, Cordelia Schmid.
|
| 18 |
+
The paper proposes one of the first successful pure-transformer based set of models for video understanding.
|
| 19 |
+
|
| 20 |
+
The abstract from the paper is the following:
|
| 21 |
+
|
| 22 |
+
*We present pure-transformer based models for video classification, drawing upon the recent success of such models in image classification. Our model extracts spatio-temporal tokens from the input video, which are then encoded by a series of transformer layers. In order to handle the long sequences of tokens encountered in video, we propose several, efficient variants of our model which factorise the spatial- and temporal-dimensions of the input. Although transformer-based models are known to only be effective when large training datasets are available, we show how we can effectively regularise the model during training and leverage pretrained image models to be able to train on comparatively small datasets. We conduct thorough ablation studies, and achieve state-of-the-art results on multiple video classification benchmarks including Kinetics 400 and 600, Epic Kitchens, Something-Something v2 and Moments in Time, outperforming prior methods based on deep 3D convolutional networks.*
|
| 23 |
+
|
| 24 |
+
This model was contributed by [jegormeister](https://huggingface.co/jegormeister). The original code (written in JAX) can be found [here](https://github.com/google-research/scenic/tree/main/scenic/projects/vivit).
|
| 25 |
+
|
| 26 |
+
### Using Scaled Dot Product Attention (SDPA)
|
| 27 |
+
|
| 28 |
+
PyTorch includes a native scaled dot-product attention (SDPA) operator as part of `torch.nn.functional`. This function
|
| 29 |
+
encompasses several implementations that can be applied depending on the inputs and the hardware in use. See the
|
| 30 |
+
[official documentation](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html)
|
| 31 |
+
or the [GPU Inference](https://huggingface.co/docs/transformers/main/en/perf_infer_gpu_one#pytorch-scaled-dot-product-attention)
|
| 32 |
+
page for more information.
|
| 33 |
+
|
| 34 |
+
SDPA is used by default for `torch>=2.1.1` when an implementation is available, but you may also set
|
| 35 |
+
`attn_implementation="sdpa"` in `from_pretrained()` to explicitly request SDPA to be used.
|
| 36 |
+
|
| 37 |
+
```
|
| 38 |
+
from transformers import VivitModel
|
| 39 |
+
model = VivitModel.from_pretrained("google/vivit-b-16x2-kinetics400", attn_implementation="sdpa", torch_dtype=torch.float16)
|
| 40 |
+
...
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
For the best speedups, we recommend loading the model in half-precision (e.g. `torch.float16` or `torch.bfloat16`).
|
| 44 |
+
|
| 45 |
+
On a local benchmark (A100-40GB, PyTorch 2.3.0, OS Ubuntu 22.04) with `float32` and `google/vivit-b-16x2-kinetics400` model, we saw the following speedups during inference.
|
| 46 |
+
|
| 47 |
+
### Training
|
| 48 |
+
| num_training_steps | batch_size | is cuda | Speedup (%) | Eager peak mem (MB) | sdpa peak mem (MB) | Mem saving (%) |
|
| 49 |
+
|---------------------:|-------------:|----------:|--------------:|----------------------:|---------------------:|-----------------:|
|
| 50 |
+
| 100 | 1 | True | 7.122 | 2575.28 | 5932.54 | 130.364 |
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
### Inference
|
| 55 |
+
| num_batches | batch_size | is cuda | is half | Speedup (%) | Mem eager (MB) | Mem BT (MB) | Mem saved (%) |
|
| 56 |
+
|---------------|--------------|-----------|-----------|---------------|------------------|---------------|-----------------|
|
| 57 |
+
| 20 | 1 | True | False | 15.422 | 715.807 | 317.079 | 125.75 |
|
| 58 |
+
| 20 | 2 | True | False | 17.146 | 1234.75 | 447.175 | 176.122 |
|
| 59 |
+
| 20 | 4 | True | False | 18.093 | 2275.82 | 709.864 | 220.6 |
|
| 60 |
+
| 20 | 8 | True | False | 19.284 | 4358.19 | 1233.24 | 253.393 |
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
## VivitConfig
|
| 64 |
+
|
| 65 |
+
[[autodoc]] VivitConfig
|
| 66 |
+
|
| 67 |
+
## VivitImageProcessor
|
| 68 |
+
|
| 69 |
+
[[autodoc]] VivitImageProcessor
|
| 70 |
+
- preprocess
|
| 71 |
+
|
| 72 |
+
## VivitModel
|
| 73 |
+
|
| 74 |
+
[[autodoc]] VivitModel
|
| 75 |
+
- forward
|
| 76 |
+
|
| 77 |
+
## VivitForVideoClassification
|
| 78 |
+
|
| 79 |
+
[[autodoc]] transformers.VivitForVideoClassification
|
| 80 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/wav2vec2-bert.md
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Wav2Vec2-BERT
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
The Wav2Vec2-BERT model was proposed in [Seamless: Multilingual Expressive and Streaming Speech Translation](https://ai.meta.com/research/publications/seamless-multilingual-expressive-and-streaming-speech-translation/) by the Seamless Communication team from Meta AI.
|
| 22 |
+
|
| 23 |
+
This model was pre-trained on 4.5M hours of unlabeled audio data covering more than 143 languages. It requires finetuning to be used for downstream tasks such as Automatic Speech Recognition (ASR), or Audio Classification.
|
| 24 |
+
|
| 25 |
+
The official results of the model can be found in Section 3.2.1 of the paper.
|
| 26 |
+
|
| 27 |
+
The abstract from the paper is the following:
|
| 28 |
+
|
| 29 |
+
*Recent advancements in automatic speech translation have dramatically expanded language coverage, improved multimodal capabilities, and enabled a wide range of tasks and functionalities. That said, large-scale automatic speech translation systems today lack key features that help machine-mediated communication feel seamless when compared to human-to-human dialogue. In this work, we introduce a family of models that enable end-to-end expressive and multilingual translations in a streaming fashion. First, we contribute an improved version of the massively multilingual and multimodal SeamlessM4T model—SeamlessM4T v2. This newer model, incorporating an updated UnitY2 framework, was trained on more low-resource language data. The expanded version of SeamlessAlign adds 114,800 hours of automatically aligned data for a total of 76 languages. SeamlessM4T v2 provides the foundation on which our two newest models, SeamlessExpressive and SeamlessStreaming, are initiated. SeamlessExpressive enables translation that preserves vocal styles and prosody. Compared to previous efforts in expressive speech research, our work addresses certain underexplored aspects of prosody, such as speech rate and pauses, while also preserving the style of one’s voice. As for SeamlessStreaming, our model leverages the Efficient Monotonic Multihead Attention (EMMA) mechanism to generate low-latency target translations without waiting for complete source utterances. As the first of its kind, SeamlessStreaming enables simultaneous speech-to-speech/text translation for multiple source and target languages. To understand the performance of these models, we combined novel and modified versions of existing automatic metrics to evaluate prosody, latency, and robustness. For human evaluations, we adapted existing protocols tailored for measuring the most relevant attributes in the preservation of meaning, naturalness, and expressivity. To ensure that our models can be used safely and responsibly, we implemented the first known red-teaming effort for multimodal machine translation, a system for the detection and mitigation of added toxicity, a systematic evaluation of gender bias, and an inaudible localized watermarking mechanism designed to dampen the impact of deepfakes. Consequently, we bring major components from SeamlessExpressive and SeamlessStreaming together to form Seamless, the first publicly available system that unlocks expressive cross-lingual communication in real-time. In sum, Seamless gives us a pivotal look at the technical foundation needed to turn the Universal Speech Translator from a science fiction concept into a real-world technology. Finally, contributions in this work—including models, code, and a watermark detector—are publicly released and accessible at the link below.*
|
| 30 |
+
|
| 31 |
+
This model was contributed by [ylacombe](https://huggingface.co/ylacombe). The original code can be found [here](https://github.com/facebookresearch/seamless_communication).
|
| 32 |
+
|
| 33 |
+
## Usage tips
|
| 34 |
+
|
| 35 |
+
- Wav2Vec2-BERT follows the same architecture as Wav2Vec2-Conformer, but employs a causal depthwise convolutional layer and uses as input a mel-spectrogram representation of the audio instead of the raw waveform.
|
| 36 |
+
- Wav2Vec2-BERT can use either no relative position embeddings, Shaw-like position embeddings, Transformer-XL-like position embeddings, or
|
| 37 |
+
rotary position embeddings by setting the correct `config.position_embeddings_type`.
|
| 38 |
+
- Wav2Vec2-BERT also introduces a Conformer-based adapter network instead of a simple convolutional network.
|
| 39 |
+
|
| 40 |
+
## Resources
|
| 41 |
+
|
| 42 |
+
<PipelineTag pipeline="automatic-speech-recognition"/>
|
| 43 |
+
|
| 44 |
+
- [`Wav2Vec2BertForCTC`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/speech-recognition).
|
| 45 |
+
- You can also adapt these notebooks on [how to finetune a speech recognition model in English](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/speech_recognition.ipynb), and [how to finetune a speech recognition model in any language](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multi_lingual_speech_recognition.ipynb).
|
| 46 |
+
|
| 47 |
+
<PipelineTag pipeline="audio-classification"/>
|
| 48 |
+
|
| 49 |
+
- [`Wav2Vec2BertForSequenceClassification`] can be used by adapting this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/audio-classification).
|
| 50 |
+
- See also: [Audio classification task guide](../tasks/audio_classification)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
## Wav2Vec2BertConfig
|
| 54 |
+
|
| 55 |
+
[[autodoc]] Wav2Vec2BertConfig
|
| 56 |
+
|
| 57 |
+
## Wav2Vec2BertProcessor
|
| 58 |
+
|
| 59 |
+
[[autodoc]] Wav2Vec2BertProcessor
|
| 60 |
+
- __call__
|
| 61 |
+
- pad
|
| 62 |
+
- from_pretrained
|
| 63 |
+
- save_pretrained
|
| 64 |
+
- batch_decode
|
| 65 |
+
- decode
|
| 66 |
+
|
| 67 |
+
## Wav2Vec2BertModel
|
| 68 |
+
|
| 69 |
+
[[autodoc]] Wav2Vec2BertModel
|
| 70 |
+
- forward
|
| 71 |
+
|
| 72 |
+
## Wav2Vec2BertForCTC
|
| 73 |
+
|
| 74 |
+
[[autodoc]] Wav2Vec2BertForCTC
|
| 75 |
+
- forward
|
| 76 |
+
|
| 77 |
+
## Wav2Vec2BertForSequenceClassification
|
| 78 |
+
|
| 79 |
+
[[autodoc]] Wav2Vec2BertForSequenceClassification
|
| 80 |
+
- forward
|
| 81 |
+
|
| 82 |
+
## Wav2Vec2BertForAudioFrameClassification
|
| 83 |
+
|
| 84 |
+
[[autodoc]] Wav2Vec2BertForAudioFrameClassification
|
| 85 |
+
- forward
|
| 86 |
+
|
| 87 |
+
## Wav2Vec2BertForXVector
|
| 88 |
+
|
| 89 |
+
[[autodoc]] Wav2Vec2BertForXVector
|
| 90 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/wav2vec2-conformer.md
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Wav2Vec2-Conformer
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
The Wav2Vec2-Conformer was added to an updated version of [fairseq S2T: Fast Speech-to-Text Modeling with fairseq](https://arxiv.org/abs/2010.05171) by Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Sravya Popuri, Dmytro Okhonko, Juan Pino.
|
| 22 |
+
|
| 23 |
+
The official results of the model can be found in Table 3 and Table 4 of the paper.
|
| 24 |
+
|
| 25 |
+
The Wav2Vec2-Conformer weights were released by the Meta AI team within the [Fairseq library](https://github.com/pytorch/fairseq/blob/main/examples/wav2vec/README.md#pre-trained-models).
|
| 26 |
+
|
| 27 |
+
This model was contributed by [patrickvonplaten](https://huggingface.co/patrickvonplaten).
|
| 28 |
+
The original code can be found [here](https://github.com/pytorch/fairseq/tree/main/examples/wav2vec).
|
| 29 |
+
|
| 30 |
+
Note: Meta (FAIR) released a new version of [Wav2Vec2-BERT 2.0](https://huggingface.co/docs/transformers/en/model_doc/wav2vec2-bert) - it's pretrained on 4.5M hours of audio. We especially recommend using it for fine-tuning tasks, e.g. as per [this guide](https://huggingface.co/blog/fine-tune-w2v2-bert).
|
| 31 |
+
|
| 32 |
+
## Usage tips
|
| 33 |
+
|
| 34 |
+
- Wav2Vec2-Conformer follows the same architecture as Wav2Vec2, but replaces the *Attention*-block with a *Conformer*-block
|
| 35 |
+
as introduced in [Conformer: Convolution-augmented Transformer for Speech Recognition](https://arxiv.org/abs/2005.08100).
|
| 36 |
+
- For the same number of layers, Wav2Vec2-Conformer requires more parameters than Wav2Vec2, but also yields
|
| 37 |
+
an improved word error rate.
|
| 38 |
+
- Wav2Vec2-Conformer uses the same tokenizer and feature extractor as Wav2Vec2.
|
| 39 |
+
- Wav2Vec2-Conformer can use either no relative position embeddings, Transformer-XL-like position embeddings, or
|
| 40 |
+
rotary position embeddings by setting the correct `config.position_embeddings_type`.
|
| 41 |
+
|
| 42 |
+
## Resources
|
| 43 |
+
|
| 44 |
+
- [Audio classification task guide](../tasks/audio_classification)
|
| 45 |
+
- [Automatic speech recognition task guide](../tasks/asr)
|
| 46 |
+
|
| 47 |
+
## Wav2Vec2ConformerConfig
|
| 48 |
+
|
| 49 |
+
[[autodoc]] Wav2Vec2ConformerConfig
|
| 50 |
+
|
| 51 |
+
## Wav2Vec2Conformer specific outputs
|
| 52 |
+
|
| 53 |
+
[[autodoc]] models.wav2vec2_conformer.modeling_wav2vec2_conformer.Wav2Vec2ConformerForPreTrainingOutput
|
| 54 |
+
|
| 55 |
+
## Wav2Vec2ConformerModel
|
| 56 |
+
|
| 57 |
+
[[autodoc]] Wav2Vec2ConformerModel
|
| 58 |
+
- forward
|
| 59 |
+
|
| 60 |
+
## Wav2Vec2ConformerForCTC
|
| 61 |
+
|
| 62 |
+
[[autodoc]] Wav2Vec2ConformerForCTC
|
| 63 |
+
- forward
|
| 64 |
+
|
| 65 |
+
## Wav2Vec2ConformerForSequenceClassification
|
| 66 |
+
|
| 67 |
+
[[autodoc]] Wav2Vec2ConformerForSequenceClassification
|
| 68 |
+
- forward
|
| 69 |
+
|
| 70 |
+
## Wav2Vec2ConformerForAudioFrameClassification
|
| 71 |
+
|
| 72 |
+
[[autodoc]] Wav2Vec2ConformerForAudioFrameClassification
|
| 73 |
+
- forward
|
| 74 |
+
|
| 75 |
+
## Wav2Vec2ConformerForXVector
|
| 76 |
+
|
| 77 |
+
[[autodoc]] Wav2Vec2ConformerForXVector
|
| 78 |
+
- forward
|
| 79 |
+
|
| 80 |
+
## Wav2Vec2ConformerForPreTraining
|
| 81 |
+
|
| 82 |
+
[[autodoc]] Wav2Vec2ConformerForPreTraining
|
| 83 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/wav2vec2.md
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2021 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Wav2Vec2
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
The Wav2Vec2 model was proposed in [wav2vec 2.0: A Framework for Self-Supervised Learning of Speech Representations](https://arxiv.org/abs/2006.11477) by Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli.
|
| 22 |
+
|
| 23 |
+
The abstract from the paper is the following:
|
| 24 |
+
|
| 25 |
+
*We show for the first time that learning powerful representations from speech audio alone followed by fine-tuning on
|
| 26 |
+
transcribed speech can outperform the best semi-supervised methods while being conceptually simpler. wav2vec 2.0 masks
|
| 27 |
+
the speech input in the latent space and solves a contrastive task defined over a quantization of the latent
|
| 28 |
+
representations which are jointly learned. Experiments using all labeled data of Librispeech achieve 1.8/3.3 WER on the
|
| 29 |
+
clean/other test sets. When lowering the amount of labeled data to one hour, wav2vec 2.0 outperforms the previous state
|
| 30 |
+
of the art on the 100 hour subset while using 100 times less labeled data. Using just ten minutes of labeled data and
|
| 31 |
+
pre-training on 53k hours of unlabeled data still achieves 4.8/8.2 WER. This demonstrates the feasibility of speech
|
| 32 |
+
recognition with limited amounts of labeled data.*
|
| 33 |
+
|
| 34 |
+
This model was contributed by [patrickvonplaten](https://huggingface.co/patrickvonplaten).
|
| 35 |
+
|
| 36 |
+
Note: Meta (FAIR) released a new version of [Wav2Vec2-BERT 2.0](https://huggingface.co/docs/transformers/en/model_doc/wav2vec2-bert) - it's pretrained on 4.5M hours of audio. We especially recommend using it for fine-tuning tasks, e.g. as per [this guide](https://huggingface.co/blog/fine-tune-w2v2-bert).
|
| 37 |
+
|
| 38 |
+
## Usage tips
|
| 39 |
+
|
| 40 |
+
- Wav2Vec2 is a speech model that accepts a float array corresponding to the raw waveform of the speech signal.
|
| 41 |
+
- Wav2Vec2 model was trained using connectionist temporal classification (CTC) so the model output has to be decoded
|
| 42 |
+
using [`Wav2Vec2CTCTokenizer`].
|
| 43 |
+
|
| 44 |
+
## Using Flash Attention 2
|
| 45 |
+
|
| 46 |
+
Flash Attention 2 is an faster, optimized version of the model.
|
| 47 |
+
|
| 48 |
+
### Installation
|
| 49 |
+
|
| 50 |
+
First, check whether your hardware is compatible with Flash Attention 2. The latest list of compatible hardware can be found in the [official documentation](https://github.com/Dao-AILab/flash-attention#installation-and-features). If your hardware is not compatible with Flash Attention 2, you can still benefit from attention kernel optimisations through Better Transformer support covered [above](https://huggingface.co/docs/transformers/main/en/model_doc/bark#using-better-transformer).
|
| 51 |
+
|
| 52 |
+
Next, [install](https://github.com/Dao-AILab/flash-attention#installation-and-features) the latest version of Flash Attention 2:
|
| 53 |
+
|
| 54 |
+
```bash
|
| 55 |
+
pip install -U flash-attn --no-build-isolation
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
### Usage
|
| 59 |
+
|
| 60 |
+
To load a model using Flash Attention 2, we can pass the argument `attn_implementation="flash_attention_2"` to [`.from_pretrained`](https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel.from_pretrained). We'll also load the model in half-precision (e.g. `torch.float16`), since it results in almost no degradation to audio quality but significantly lower memory usage and faster inference:
|
| 61 |
+
|
| 62 |
+
```python
|
| 63 |
+
>>> from transformers import Wav2Vec2Model
|
| 64 |
+
|
| 65 |
+
model = Wav2Vec2Model.from_pretrained("facebook/wav2vec2-large-960h-lv60-self", torch_dtype=torch.float16, attn_implementation="flash_attention_2").to(device)
|
| 66 |
+
...
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
### Expected speedups
|
| 70 |
+
|
| 71 |
+
Below is an expected speedup diagram comparing the pure inference time between the native implementation in transformers of the `facebook/wav2vec2-large-960h-lv60-self` model and the flash-attention-2 and sdpa (scale-dot-product-attention) versions. . We show the average speedup obtained on the `librispeech_asr` `clean` validation split:
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
<div style="text-align: center">
|
| 75 |
+
<img src="https://huggingface.co/datasets/kamilakesbi/transformers_image_doc/resolve/main/data/Wav2Vec2_speedup.png">
|
| 76 |
+
</div>
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
## Resources
|
| 81 |
+
|
| 82 |
+
A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with Wav2Vec2. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource.
|
| 83 |
+
|
| 84 |
+
<PipelineTag pipeline="audio-classification"/>
|
| 85 |
+
|
| 86 |
+
- A notebook on how to [leverage a pretrained Wav2Vec2 model for emotion classification](https://colab.research.google.com/github/m3hrdadfi/soxan/blob/main/notebooks/Emotion_recognition_in_Greek_speech_using_Wav2Vec2.ipynb). 🌎
|
| 87 |
+
- [`Wav2Vec2ForCTC`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/audio-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/audio_classification.ipynb).
|
| 88 |
+
- [Audio classification task guide](../tasks/audio_classification)
|
| 89 |
+
|
| 90 |
+
<PipelineTag pipeline="automatic-speech-recognition"/>
|
| 91 |
+
|
| 92 |
+
- A blog post on [boosting Wav2Vec2 with n-grams in 🤗 Transformers](https://huggingface.co/blog/wav2vec2-with-ngram).
|
| 93 |
+
- A blog post on how to [finetune Wav2Vec2 for English ASR with 🤗 Transformers](https://huggingface.co/blog/fine-tune-wav2vec2-english).
|
| 94 |
+
- A blog post on [finetuning XLS-R for Multi-Lingual ASR with 🤗 Transformers](https://huggingface.co/blog/fine-tune-xlsr-wav2vec2).
|
| 95 |
+
- A notebook on how to [create YouTube captions from any video by transcribing audio with Wav2Vec2](https://colab.research.google.com/github/Muennighoff/ytclipcc/blob/main/wav2vec_youtube_captions.ipynb). 🌎
|
| 96 |
+
- [`Wav2Vec2ForCTC`] is supported by a notebook on [how to finetune a speech recognition model in English](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/speech_recognition.ipynb), and [how to finetune a speech recognition model in any language](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multi_lingual_speech_recognition.ipynb).
|
| 97 |
+
- [Automatic speech recognition task guide](../tasks/asr)
|
| 98 |
+
|
| 99 |
+
🚀 Deploy
|
| 100 |
+
|
| 101 |
+
- A blog post on how to deploy Wav2Vec2 for [Automatic Speech Recognition with Hugging Face's Transformers & Amazon SageMaker](https://www.philschmid.de/automatic-speech-recognition-sagemaker).
|
| 102 |
+
|
| 103 |
+
## Wav2Vec2Config
|
| 104 |
+
|
| 105 |
+
[[autodoc]] Wav2Vec2Config
|
| 106 |
+
|
| 107 |
+
## Wav2Vec2CTCTokenizer
|
| 108 |
+
|
| 109 |
+
[[autodoc]] Wav2Vec2CTCTokenizer
|
| 110 |
+
- __call__
|
| 111 |
+
- save_vocabulary
|
| 112 |
+
- decode
|
| 113 |
+
- batch_decode
|
| 114 |
+
- set_target_lang
|
| 115 |
+
|
| 116 |
+
## Wav2Vec2FeatureExtractor
|
| 117 |
+
|
| 118 |
+
[[autodoc]] Wav2Vec2FeatureExtractor
|
| 119 |
+
- __call__
|
| 120 |
+
|
| 121 |
+
## Wav2Vec2Processor
|
| 122 |
+
|
| 123 |
+
[[autodoc]] Wav2Vec2Processor
|
| 124 |
+
- __call__
|
| 125 |
+
- pad
|
| 126 |
+
- from_pretrained
|
| 127 |
+
- save_pretrained
|
| 128 |
+
- batch_decode
|
| 129 |
+
- decode
|
| 130 |
+
|
| 131 |
+
## Wav2Vec2ProcessorWithLM
|
| 132 |
+
|
| 133 |
+
[[autodoc]] Wav2Vec2ProcessorWithLM
|
| 134 |
+
- __call__
|
| 135 |
+
- pad
|
| 136 |
+
- from_pretrained
|
| 137 |
+
- save_pretrained
|
| 138 |
+
- batch_decode
|
| 139 |
+
- decode
|
| 140 |
+
|
| 141 |
+
### Decoding multiple audios
|
| 142 |
+
|
| 143 |
+
If you are planning to decode multiple batches of audios, you should consider using [`~Wav2Vec2ProcessorWithLM.batch_decode`] and passing an instantiated `multiprocessing.Pool`.
|
| 144 |
+
Otherwise, [`~Wav2Vec2ProcessorWithLM.batch_decode`] performance will be slower than calling [`~Wav2Vec2ProcessorWithLM.decode`] for each audio individually, as it internally instantiates a new `Pool` for every call. See the example below:
|
| 145 |
+
|
| 146 |
+
```python
|
| 147 |
+
>>> # Let's see how to use a user-managed pool for batch decoding multiple audios
|
| 148 |
+
>>> from multiprocessing import get_context
|
| 149 |
+
>>> from transformers import AutoTokenizer, AutoProcessor, AutoModelForCTC
|
| 150 |
+
>>> from datasets import load_dataset
|
| 151 |
+
>>> import datasets
|
| 152 |
+
>>> import torch
|
| 153 |
+
|
| 154 |
+
>>> # import model, feature extractor, tokenizer
|
| 155 |
+
>>> model = AutoModelForCTC.from_pretrained("patrickvonplaten/wav2vec2-base-100h-with-lm").to("cuda")
|
| 156 |
+
>>> processor = AutoProcessor.from_pretrained("patrickvonplaten/wav2vec2-base-100h-with-lm")
|
| 157 |
+
|
| 158 |
+
>>> # load example dataset
|
| 159 |
+
>>> dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
|
| 160 |
+
>>> dataset = dataset.cast_column("audio", datasets.Audio(sampling_rate=16_000))
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
>>> def map_to_array(batch):
|
| 164 |
+
... batch["speech"] = batch["audio"]["array"]
|
| 165 |
+
... return batch
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
>>> # prepare speech data for batch inference
|
| 169 |
+
>>> dataset = dataset.map(map_to_array, remove_columns=["audio"])
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
>>> def map_to_pred(batch, pool):
|
| 173 |
+
... inputs = processor(batch["speech"], sampling_rate=16_000, padding=True, return_tensors="pt")
|
| 174 |
+
... inputs = {k: v.to("cuda") for k, v in inputs.items()}
|
| 175 |
+
|
| 176 |
+
... with torch.no_grad():
|
| 177 |
+
... logits = model(**inputs).logits
|
| 178 |
+
|
| 179 |
+
... transcription = processor.batch_decode(logits.cpu().numpy(), pool).text
|
| 180 |
+
... batch["transcription"] = transcription
|
| 181 |
+
... return batch
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
>>> # note: pool should be instantiated *after* `Wav2Vec2ProcessorWithLM`.
|
| 185 |
+
>>> # otherwise, the LM won't be available to the pool's sub-processes
|
| 186 |
+
>>> # select number of processes and batch_size based on number of CPU cores available and on dataset size
|
| 187 |
+
>>> with get_context("fork").Pool(processes=2) as pool:
|
| 188 |
+
... result = dataset.map(
|
| 189 |
+
... map_to_pred, batched=True, batch_size=2, fn_kwargs={"pool": pool}, remove_columns=["speech"]
|
| 190 |
+
... )
|
| 191 |
+
|
| 192 |
+
>>> result["transcription"][:2]
|
| 193 |
+
['MISTER QUILTER IS THE APOSTLE OF THE MIDDLE CLASSES AND WE ARE GLAD TO WELCOME HIS GOSPEL', "NOR IS MISTER COULTER'S MANNER LESS INTERESTING THAN HIS MATTER"]
|
| 194 |
+
```
|
| 195 |
+
|
| 196 |
+
## Wav2Vec2 specific outputs
|
| 197 |
+
|
| 198 |
+
[[autodoc]] models.wav2vec2_with_lm.processing_wav2vec2_with_lm.Wav2Vec2DecoderWithLMOutput
|
| 199 |
+
|
| 200 |
+
[[autodoc]] models.wav2vec2.modeling_wav2vec2.Wav2Vec2BaseModelOutput
|
| 201 |
+
|
| 202 |
+
[[autodoc]] models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForPreTrainingOutput
|
| 203 |
+
|
| 204 |
+
[[autodoc]] models.wav2vec2.modeling_flax_wav2vec2.FlaxWav2Vec2BaseModelOutput
|
| 205 |
+
|
| 206 |
+
[[autodoc]] models.wav2vec2.modeling_flax_wav2vec2.FlaxWav2Vec2ForPreTrainingOutput
|
| 207 |
+
|
| 208 |
+
<frameworkcontent>
|
| 209 |
+
<pt>
|
| 210 |
+
|
| 211 |
+
## Wav2Vec2Model
|
| 212 |
+
|
| 213 |
+
[[autodoc]] Wav2Vec2Model
|
| 214 |
+
- forward
|
| 215 |
+
|
| 216 |
+
## Wav2Vec2ForCTC
|
| 217 |
+
|
| 218 |
+
[[autodoc]] Wav2Vec2ForCTC
|
| 219 |
+
- forward
|
| 220 |
+
- load_adapter
|
| 221 |
+
|
| 222 |
+
## Wav2Vec2ForSequenceClassification
|
| 223 |
+
|
| 224 |
+
[[autodoc]] Wav2Vec2ForSequenceClassification
|
| 225 |
+
- forward
|
| 226 |
+
|
| 227 |
+
## Wav2Vec2ForAudioFrameClassification
|
| 228 |
+
|
| 229 |
+
[[autodoc]] Wav2Vec2ForAudioFrameClassification
|
| 230 |
+
- forward
|
| 231 |
+
|
| 232 |
+
## Wav2Vec2ForXVector
|
| 233 |
+
|
| 234 |
+
[[autodoc]] Wav2Vec2ForXVector
|
| 235 |
+
- forward
|
| 236 |
+
|
| 237 |
+
## Wav2Vec2ForPreTraining
|
| 238 |
+
|
| 239 |
+
[[autodoc]] Wav2Vec2ForPreTraining
|
| 240 |
+
- forward
|
| 241 |
+
|
| 242 |
+
</pt>
|
| 243 |
+
<tf>
|
| 244 |
+
|
| 245 |
+
## TFWav2Vec2Model
|
| 246 |
+
|
| 247 |
+
[[autodoc]] TFWav2Vec2Model
|
| 248 |
+
- call
|
| 249 |
+
|
| 250 |
+
## TFWav2Vec2ForSequenceClassification
|
| 251 |
+
|
| 252 |
+
[[autodoc]] TFWav2Vec2ForSequenceClassification
|
| 253 |
+
- call
|
| 254 |
+
|
| 255 |
+
## TFWav2Vec2ForCTC
|
| 256 |
+
|
| 257 |
+
[[autodoc]] TFWav2Vec2ForCTC
|
| 258 |
+
- call
|
| 259 |
+
|
| 260 |
+
</tf>
|
| 261 |
+
<jax>
|
| 262 |
+
|
| 263 |
+
## FlaxWav2Vec2Model
|
| 264 |
+
|
| 265 |
+
[[autodoc]] FlaxWav2Vec2Model
|
| 266 |
+
- __call__
|
| 267 |
+
|
| 268 |
+
## FlaxWav2Vec2ForCTC
|
| 269 |
+
|
| 270 |
+
[[autodoc]] FlaxWav2Vec2ForCTC
|
| 271 |
+
- __call__
|
| 272 |
+
|
| 273 |
+
## FlaxWav2Vec2ForPreTraining
|
| 274 |
+
|
| 275 |
+
[[autodoc]] FlaxWav2Vec2ForPreTraining
|
| 276 |
+
- __call__
|
| 277 |
+
|
| 278 |
+
</jax>
|
| 279 |
+
</frameworkcontent>
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/wav2vec2_phoneme.md
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2021 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Wav2Vec2Phoneme
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
The Wav2Vec2Phoneme model was proposed in [Simple and Effective Zero-shot Cross-lingual Phoneme Recognition (Xu et al.,
|
| 22 |
+
2021](https://arxiv.org/abs/2109.11680) by Qiantong Xu, Alexei Baevski, Michael Auli.
|
| 23 |
+
|
| 24 |
+
The abstract from the paper is the following:
|
| 25 |
+
|
| 26 |
+
*Recent progress in self-training, self-supervised pretraining and unsupervised learning enabled well performing speech
|
| 27 |
+
recognition systems without any labeled data. However, in many cases there is labeled data available for related
|
| 28 |
+
languages which is not utilized by these methods. This paper extends previous work on zero-shot cross-lingual transfer
|
| 29 |
+
learning by fine-tuning a multilingually pretrained wav2vec 2.0 model to transcribe unseen languages. This is done by
|
| 30 |
+
mapping phonemes of the training languages to the target language using articulatory features. Experiments show that
|
| 31 |
+
this simple method significantly outperforms prior work which introduced task-specific architectures and used only part
|
| 32 |
+
of a monolingually pretrained model.*
|
| 33 |
+
|
| 34 |
+
Relevant checkpoints can be found under https://huggingface.co/models?other=phoneme-recognition.
|
| 35 |
+
|
| 36 |
+
This model was contributed by [patrickvonplaten](https://huggingface.co/patrickvonplaten)
|
| 37 |
+
|
| 38 |
+
The original code can be found [here](https://github.com/pytorch/fairseq/tree/master/fairseq/models/wav2vec).
|
| 39 |
+
|
| 40 |
+
## Usage tips
|
| 41 |
+
|
| 42 |
+
- Wav2Vec2Phoneme uses the exact same architecture as Wav2Vec2
|
| 43 |
+
- Wav2Vec2Phoneme is a speech model that accepts a float array corresponding to the raw waveform of the speech signal.
|
| 44 |
+
- Wav2Vec2Phoneme model was trained using connectionist temporal classification (CTC) so the model output has to be
|
| 45 |
+
decoded using [`Wav2Vec2PhonemeCTCTokenizer`].
|
| 46 |
+
- Wav2Vec2Phoneme can be fine-tuned on multiple language at once and decode unseen languages in a single forward pass
|
| 47 |
+
to a sequence of phonemes
|
| 48 |
+
- By default, the model outputs a sequence of phonemes. In order to transform the phonemes to a sequence of words one
|
| 49 |
+
should make use of a dictionary and language model.
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
<Tip>
|
| 53 |
+
|
| 54 |
+
Wav2Vec2Phoneme's architecture is based on the Wav2Vec2 model, for API reference, check out [`Wav2Vec2`](wav2vec2)'s documentation page
|
| 55 |
+
except for the tokenizer.
|
| 56 |
+
|
| 57 |
+
</Tip>
|
| 58 |
+
|
| 59 |
+
## Wav2Vec2PhonemeCTCTokenizer
|
| 60 |
+
|
| 61 |
+
[[autodoc]] Wav2Vec2PhonemeCTCTokenizer
|
| 62 |
+
- __call__
|
| 63 |
+
- batch_decode
|
| 64 |
+
- decode
|
| 65 |
+
- phonemize
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/wavlm.md
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2021 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# WavLM
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
The WavLM model was proposed in [WavLM: Large-Scale Self-Supervised Pre-Training for Full Stack Speech Processing](https://arxiv.org/abs/2110.13900) by Sanyuan Chen, Chengyi Wang, Zhengyang Chen, Yu Wu, Shujie Liu, Zhuo Chen,
|
| 22 |
+
Jinyu Li, Naoyuki Kanda, Takuya Yoshioka, Xiong Xiao, Jian Wu, Long Zhou, Shuo Ren, Yanmin Qian, Yao Qian, Jian Wu,
|
| 23 |
+
Michael Zeng, Furu Wei.
|
| 24 |
+
|
| 25 |
+
The abstract from the paper is the following:
|
| 26 |
+
|
| 27 |
+
*Self-supervised learning (SSL) achieves great success in speech recognition, while limited exploration has been
|
| 28 |
+
attempted for other speech processing tasks. As speech signal contains multi-faceted information including speaker
|
| 29 |
+
identity, paralinguistics, spoken content, etc., learning universal representations for all speech tasks is
|
| 30 |
+
challenging. In this paper, we propose a new pre-trained model, WavLM, to solve full-stack downstream speech tasks.
|
| 31 |
+
WavLM is built based on the HuBERT framework, with an emphasis on both spoken content modeling and speaker identity
|
| 32 |
+
preservation. We first equip the Transformer structure with gated relative position bias to improve its capability on
|
| 33 |
+
recognition tasks. For better speaker discrimination, we propose an utterance mixing training strategy, where
|
| 34 |
+
additional overlapped utterances are created unsupervisedly and incorporated during model training. Lastly, we scale up
|
| 35 |
+
the training dataset from 60k hours to 94k hours. WavLM Large achieves state-of-the-art performance on the SUPERB
|
| 36 |
+
benchmark, and brings significant improvements for various speech processing tasks on their representative benchmarks.*
|
| 37 |
+
|
| 38 |
+
Relevant checkpoints can be found under https://huggingface.co/models?other=wavlm.
|
| 39 |
+
|
| 40 |
+
This model was contributed by [patrickvonplaten](https://huggingface.co/patrickvonplaten). The Authors' code can be
|
| 41 |
+
found [here](https://github.com/microsoft/unilm/tree/master/wavlm).
|
| 42 |
+
|
| 43 |
+
## Usage tips
|
| 44 |
+
|
| 45 |
+
- WavLM is a speech model that accepts a float array corresponding to the raw waveform of the speech signal. Please use
|
| 46 |
+
[`Wav2Vec2Processor`] for the feature extraction.
|
| 47 |
+
- WavLM model can be fine-tuned using connectionist temporal classification (CTC) so the model output has to be decoded
|
| 48 |
+
using [`Wav2Vec2CTCTokenizer`].
|
| 49 |
+
- WavLM performs especially well on speaker verification, speaker identification, and speaker diarization tasks.
|
| 50 |
+
|
| 51 |
+
## Resources
|
| 52 |
+
|
| 53 |
+
- [Audio classification task guide](../tasks/audio_classification)
|
| 54 |
+
- [Automatic speech recognition task guide](../tasks/asr)
|
| 55 |
+
|
| 56 |
+
## WavLMConfig
|
| 57 |
+
|
| 58 |
+
[[autodoc]] WavLMConfig
|
| 59 |
+
|
| 60 |
+
## WavLMModel
|
| 61 |
+
|
| 62 |
+
[[autodoc]] WavLMModel
|
| 63 |
+
- forward
|
| 64 |
+
|
| 65 |
+
## WavLMForCTC
|
| 66 |
+
|
| 67 |
+
[[autodoc]] WavLMForCTC
|
| 68 |
+
- forward
|
| 69 |
+
|
| 70 |
+
## WavLMForSequenceClassification
|
| 71 |
+
|
| 72 |
+
[[autodoc]] WavLMForSequenceClassification
|
| 73 |
+
- forward
|
| 74 |
+
|
| 75 |
+
## WavLMForAudioFrameClassification
|
| 76 |
+
|
| 77 |
+
[[autodoc]] WavLMForAudioFrameClassification
|
| 78 |
+
- forward
|
| 79 |
+
|
| 80 |
+
## WavLMForXVector
|
| 81 |
+
|
| 82 |
+
[[autodoc]] WavLMForXVector
|
| 83 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/whisper.md
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Whisper
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
The Whisper model was proposed in [Robust Speech Recognition via Large-Scale Weak Supervision](https://cdn.openai.com/papers/whisper.pdf) by Alec Radford, Jong Wook Kim, Tao Xu, Greg Brockman, Christine McLeavey, Ilya Sutskever.
|
| 22 |
+
|
| 23 |
+
The abstract from the paper is the following:
|
| 24 |
+
|
| 25 |
+
*We study the capabilities of speech processing systems trained simply to predict large amounts of transcripts of audio on the internet. When scaled to 680,000 hours of multilingual and multitask supervision, the resulting models generalize well to standard benchmarks and are often competitive with prior fully supervised results but in a zeroshot transfer setting without the need for any finetuning. When compared to humans, the models approach their accuracy and robustness. We are releasing models and inference code to serve as a foundation for further work on robust speech processing.*
|
| 26 |
+
|
| 27 |
+
This model was contributed by [Arthur Zucker](https://huggingface.co/ArthurZ). The Tensorflow version of this model was contributed by [amyeroberts](https://huggingface.co/amyeroberts).
|
| 28 |
+
The original code can be found [here](https://github.com/openai/whisper).
|
| 29 |
+
|
| 30 |
+
## Quick usage
|
| 31 |
+
|
| 32 |
+
You can run Whisper in less than 4 lines of code and transcribe in less than a minute!
|
| 33 |
+
|
| 34 |
+
```python
|
| 35 |
+
# pip install transformers torch
|
| 36 |
+
|
| 37 |
+
import torch
|
| 38 |
+
from transformers import pipeline
|
| 39 |
+
|
| 40 |
+
whisper = pipeline("automatic-speech-recognition", "openai/whisper-large-v3", torch_dtype=torch.float16, device="cuda:0")
|
| 41 |
+
|
| 42 |
+
transcription = whisper("<audio_file.mp3>")
|
| 43 |
+
|
| 44 |
+
print(transcription["text"])
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
Voila! You can swap the model with any [Whisper checkpoints](https://huggingface.co/models?other=whisper&sort=downloads) on the Hugging Face Hub with the same pipeline based on your needs.
|
| 48 |
+
|
| 49 |
+
Bonus: You can replace `"cuda"` with `"mps"` to make it seamlessly work on Macs.
|
| 50 |
+
|
| 51 |
+
## Usage tips
|
| 52 |
+
|
| 53 |
+
- The model usually performs well without requiring any finetuning.
|
| 54 |
+
- The architecture follows a classic encoder-decoder architecture, which means that it relies on the [`~generation.GenerationMixin.generate`] function for inference.
|
| 55 |
+
- One can use [`WhisperProcessor`] to prepare audio for the model, and decode the predicted ID's back into text.
|
| 56 |
+
|
| 57 |
+
- To convert the model and the processor, we recommend using the following:
|
| 58 |
+
|
| 59 |
+
```bash
|
| 60 |
+
python src/transformers/models/whisper/convert_openai_to_hf.py --checkpoint_path "" --pytorch_dump_folder_path "Arthur/whisper-3" --convert_preprocessor True
|
| 61 |
+
```
|
| 62 |
+
The script will automatically determine all necessary parameters from the OpenAI checkpoint. A `tiktoken` library needs to be installed
|
| 63 |
+
to perform the conversion of the OpenAI tokenizer to the `tokenizers` version.
|
| 64 |
+
|
| 65 |
+
## Inference
|
| 66 |
+
|
| 67 |
+
Here is a step-by-step guide to transcribing an audio sample using a pre-trained Whisper model:
|
| 68 |
+
|
| 69 |
+
```python
|
| 70 |
+
>>> from datasets import load_dataset
|
| 71 |
+
>>> from transformers import WhisperProcessor, WhisperForConditionalGeneration
|
| 72 |
+
|
| 73 |
+
>>> # Select an audio file and read it:
|
| 74 |
+
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
|
| 75 |
+
>>> audio_sample = ds[0]["audio"]
|
| 76 |
+
|
| 77 |
+
>>> # Load the Whisper model in Hugging Face format:
|
| 78 |
+
>>> processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en")
|
| 79 |
+
>>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")
|
| 80 |
+
|
| 81 |
+
>>> # Use the model and processor to transcribe the audio:
|
| 82 |
+
>>> input_features = processor(
|
| 83 |
+
... audio_sample["array"], sampling_rate=audio_sample["sampling_rate"], return_tensors="pt"
|
| 84 |
+
... ).input_features
|
| 85 |
+
|
| 86 |
+
>>> # Generate token ids
|
| 87 |
+
>>> predicted_ids = model.generate(input_features)
|
| 88 |
+
|
| 89 |
+
>>> # Decode token ids to text
|
| 90 |
+
>>> transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)
|
| 91 |
+
|
| 92 |
+
>>> transcription[0]
|
| 93 |
+
' Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
Whisper is compatible with the following optimisations for both short and long-form generation:
|
| 97 |
+
- [PyTorch Scaled Dot Product Attention (SDPA)](../perf_infer_gpu_one#pytorch-scaled-dot-product-attention): flash attention and memory-efficient attention kernels. Enabled by default for `torch>=2.1.1`.
|
| 98 |
+
- [Flash Attention 2](../perf_infer_gpu_one#flashattention-2): improved implementation of flash attention through better parallelism and work partitioning.
|
| 99 |
+
- [torch.compile](../llm_optims#static-kv-cache-and-torchcompile): JIT-compile the forward pass to dispatch to efficient fused kernels.
|
| 100 |
+
|
| 101 |
+
As an example, the following codesnippet enables SDPA and `torch.compile` for up to 5x faster inference:
|
| 102 |
+
|
| 103 |
+
```python
|
| 104 |
+
>>> from datasets import load_dataset
|
| 105 |
+
>>> from transformers import WhisperProcessor, WhisperForConditionalGeneration
|
| 106 |
+
|
| 107 |
+
>>> # Select an audio file and read it:
|
| 108 |
+
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
|
| 109 |
+
>>> audio_sample = ds[0]["audio"]
|
| 110 |
+
|
| 111 |
+
>>> # Load the Whisper model with SDPA attention
|
| 112 |
+
>>> processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en")
|
| 113 |
+
>>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en", attn_implementation="sdpa")
|
| 114 |
+
|
| 115 |
+
>>> # Enable static cache and compile the forward pass
|
| 116 |
+
>>> model.generation_config.cache_implementation = "static"
|
| 117 |
+
>>> model.forward = torch.compile(model.forward, mode="reduce-overhead", fullgraph=True)
|
| 118 |
+
|
| 119 |
+
>>> # Use the model and processor to transcribe the audio:
|
| 120 |
+
>>> input_features = processor(
|
| 121 |
+
... audio_sample["array"], sampling_rate=audio_sample["sampling_rate"], return_tensors="pt"
|
| 122 |
+
... ).input_features
|
| 123 |
+
|
| 124 |
+
>>> # Compile the forward pass
|
| 125 |
+
>>> for _ in range(2):
|
| 126 |
+
>>> model.generate(input_features)
|
| 127 |
+
|
| 128 |
+
>>> # Generate token ids using compiled graph (fast!)
|
| 129 |
+
>>> predicted_ids = model.generate(input_features)
|
| 130 |
+
|
| 131 |
+
>>> # Decode token ids to text
|
| 132 |
+
>>> transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)
|
| 133 |
+
|
| 134 |
+
>>> transcription[0]
|
| 135 |
+
' Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'
|
| 136 |
+
```
|
| 137 |
+
|
| 138 |
+
For more details on each optimisation, refer to the documentation linked above.
|
| 139 |
+
|
| 140 |
+
## Resources
|
| 141 |
+
|
| 142 |
+
A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with Whisper. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource.
|
| 143 |
+
|
| 144 |
+
- [Fine-tune Whisper](https://huggingface.co/blog/fine-tune-whisper) on your own dataset for better downstream performance.
|
| 145 |
+
- [Distil-Whisper](https://huggingface.co/distil-whisper): Upto 6x faster, 2x smaller distilled Whisper models for English. We release the [model checkpoints](https://huggingface.co/distil-whisper), and [distillation code](https://github.com/huggingface/distil-whisper).
|
| 146 |
+
- A fork with a script to [convert a Whisper model in Hugging Face format to OpenAI format](https://github.com/zuazo-forks/transformers/blob/convert_hf_to_openai/src/transformers/models/whisper/convert_hf_to_openai.py). 🌎
|
| 147 |
+
Usage example:
|
| 148 |
+
```bash
|
| 149 |
+
pip install -U openai-whisper
|
| 150 |
+
python convert_hf_to_openai.py \
|
| 151 |
+
--checkpoint openai/whisper-tiny \
|
| 152 |
+
--whisper_dump_path whisper-tiny-openai.pt
|
| 153 |
+
```
|
| 154 |
+
|
| 155 |
+
## WhisperConfig
|
| 156 |
+
|
| 157 |
+
[[autodoc]] WhisperConfig
|
| 158 |
+
|
| 159 |
+
## WhisperTokenizer
|
| 160 |
+
|
| 161 |
+
[[autodoc]] WhisperTokenizer
|
| 162 |
+
- set_prefix_tokens
|
| 163 |
+
- build_inputs_with_special_tokens
|
| 164 |
+
- get_special_tokens_mask
|
| 165 |
+
- create_token_type_ids_from_sequences
|
| 166 |
+
- save_vocabulary
|
| 167 |
+
- batch_decode
|
| 168 |
+
- decode
|
| 169 |
+
- basic_normalize
|
| 170 |
+
- normalize
|
| 171 |
+
|
| 172 |
+
## WhisperTokenizerFast
|
| 173 |
+
|
| 174 |
+
[[autodoc]] WhisperTokenizerFast
|
| 175 |
+
- set_prefix_tokens
|
| 176 |
+
- build_inputs_with_special_tokens
|
| 177 |
+
- get_special_tokens_mask
|
| 178 |
+
- create_token_type_ids_from_sequences
|
| 179 |
+
- save_vocabulary
|
| 180 |
+
- batch_decode
|
| 181 |
+
- decode
|
| 182 |
+
- basic_normalize
|
| 183 |
+
- normalize
|
| 184 |
+
|
| 185 |
+
## WhisperFeatureExtractor
|
| 186 |
+
|
| 187 |
+
[[autodoc]] WhisperFeatureExtractor
|
| 188 |
+
- __call__
|
| 189 |
+
|
| 190 |
+
## WhisperProcessor
|
| 191 |
+
|
| 192 |
+
[[autodoc]] WhisperProcessor
|
| 193 |
+
- __call__
|
| 194 |
+
- from_pretrained
|
| 195 |
+
- save_pretrained
|
| 196 |
+
- batch_decode
|
| 197 |
+
- decode
|
| 198 |
+
|
| 199 |
+
<frameworkcontent>
|
| 200 |
+
<pt>
|
| 201 |
+
|
| 202 |
+
## WhisperModel
|
| 203 |
+
|
| 204 |
+
[[autodoc]] WhisperModel
|
| 205 |
+
- forward
|
| 206 |
+
- _mask_input_features
|
| 207 |
+
|
| 208 |
+
## WhisperForConditionalGeneration
|
| 209 |
+
|
| 210 |
+
[[autodoc]] WhisperForConditionalGeneration
|
| 211 |
+
- forward
|
| 212 |
+
- generate
|
| 213 |
+
|
| 214 |
+
## WhisperForCausalLM
|
| 215 |
+
|
| 216 |
+
[[autodoc]] WhisperForCausalLM
|
| 217 |
+
- forward
|
| 218 |
+
|
| 219 |
+
## WhisperForAudioClassification
|
| 220 |
+
|
| 221 |
+
[[autodoc]] WhisperForAudioClassification
|
| 222 |
+
- forward
|
| 223 |
+
|
| 224 |
+
</pt>
|
| 225 |
+
<tf>
|
| 226 |
+
|
| 227 |
+
## TFWhisperModel
|
| 228 |
+
|
| 229 |
+
[[autodoc]] TFWhisperModel
|
| 230 |
+
- call
|
| 231 |
+
|
| 232 |
+
## TFWhisperForConditionalGeneration
|
| 233 |
+
|
| 234 |
+
[[autodoc]] TFWhisperForConditionalGeneration
|
| 235 |
+
- call
|
| 236 |
+
|
| 237 |
+
</tf>
|
| 238 |
+
<jax>
|
| 239 |
+
|
| 240 |
+
## FlaxWhisperModel
|
| 241 |
+
|
| 242 |
+
[[autodoc]] FlaxWhisperModel
|
| 243 |
+
- __call__
|
| 244 |
+
|
| 245 |
+
## FlaxWhisperForConditionalGeneration
|
| 246 |
+
|
| 247 |
+
[[autodoc]] FlaxWhisperForConditionalGeneration
|
| 248 |
+
- __call__
|
| 249 |
+
|
| 250 |
+
## FlaxWhisperForAudioClassification
|
| 251 |
+
|
| 252 |
+
[[autodoc]] FlaxWhisperForAudioClassification
|
| 253 |
+
- __call__
|
| 254 |
+
|
| 255 |
+
</jax>
|
| 256 |
+
</frameworkcontent>
|
| 257 |
+
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/xclip.md
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# X-CLIP
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
The X-CLIP model was proposed in [Expanding Language-Image Pretrained Models for General Video Recognition](https://arxiv.org/abs/2208.02816) by Bolin Ni, Houwen Peng, Minghao Chen, Songyang Zhang, Gaofeng Meng, Jianlong Fu, Shiming Xiang, Haibin Ling.
|
| 22 |
+
X-CLIP is a minimal extension of [CLIP](clip) for video. The model consists of a text encoder, a cross-frame vision encoder, a multi-frame integration Transformer, and a video-specific prompt generator.
|
| 23 |
+
|
| 24 |
+
The abstract from the paper is the following:
|
| 25 |
+
|
| 26 |
+
*Contrastive language-image pretraining has shown great success in learning visual-textual joint representation from web-scale data, demonstrating remarkable "zero-shot" generalization ability for various image tasks. However, how to effectively expand such new language-image pretraining methods to video domains is still an open problem. In this work, we present a simple yet effective approach that adapts the pretrained language-image models to video recognition directly, instead of pretraining a new model from scratch. More concretely, to capture the long-range dependencies of frames along the temporal dimension, we propose a cross-frame attention mechanism that explicitly exchanges information across frames. Such module is lightweight and can be plugged into pretrained language-image models seamlessly. Moreover, we propose a video-specific prompting scheme, which leverages video content information for generating discriminative textual prompts. Extensive experiments demonstrate that our approach is effective and can be generalized to different video recognition scenarios. In particular, under fully-supervised settings, our approach achieves a top-1 accuracy of 87.1% on Kinectics-400, while using 12 times fewer FLOPs compared with Swin-L and ViViT-H. In zero-shot experiments, our approach surpasses the current state-of-the-art methods by +7.6% and +14.9% in terms of top-1 accuracy under two popular protocols. In few-shot scenarios, our approach outperforms previous best methods by +32.1% and +23.1% when the labeled data is extremely limited.*
|
| 27 |
+
|
| 28 |
+
Tips:
|
| 29 |
+
|
| 30 |
+
- Usage of X-CLIP is identical to [CLIP](clip).
|
| 31 |
+
|
| 32 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/xclip_architecture.png"
|
| 33 |
+
alt="drawing" width="600"/>
|
| 34 |
+
|
| 35 |
+
<small> X-CLIP architecture. Taken from the <a href="https://arxiv.org/abs/2208.02816">original paper.</a> </small>
|
| 36 |
+
|
| 37 |
+
This model was contributed by [nielsr](https://huggingface.co/nielsr).
|
| 38 |
+
The original code can be found [here](https://github.com/microsoft/VideoX/tree/master/X-CLIP).
|
| 39 |
+
|
| 40 |
+
## Resources
|
| 41 |
+
|
| 42 |
+
A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with X-CLIP.
|
| 43 |
+
|
| 44 |
+
- Demo notebooks for X-CLIP can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/X-CLIP).
|
| 45 |
+
|
| 46 |
+
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.
|
| 47 |
+
|
| 48 |
+
## XCLIPProcessor
|
| 49 |
+
|
| 50 |
+
[[autodoc]] XCLIPProcessor
|
| 51 |
+
|
| 52 |
+
## XCLIPConfig
|
| 53 |
+
|
| 54 |
+
[[autodoc]] XCLIPConfig
|
| 55 |
+
- from_text_vision_configs
|
| 56 |
+
|
| 57 |
+
## XCLIPTextConfig
|
| 58 |
+
|
| 59 |
+
[[autodoc]] XCLIPTextConfig
|
| 60 |
+
|
| 61 |
+
## XCLIPVisionConfig
|
| 62 |
+
|
| 63 |
+
[[autodoc]] XCLIPVisionConfig
|
| 64 |
+
|
| 65 |
+
## XCLIPModel
|
| 66 |
+
|
| 67 |
+
[[autodoc]] XCLIPModel
|
| 68 |
+
- forward
|
| 69 |
+
- get_text_features
|
| 70 |
+
- get_video_features
|
| 71 |
+
|
| 72 |
+
## XCLIPTextModel
|
| 73 |
+
|
| 74 |
+
[[autodoc]] XCLIPTextModel
|
| 75 |
+
- forward
|
| 76 |
+
|
| 77 |
+
## XCLIPVisionModel
|
| 78 |
+
|
| 79 |
+
[[autodoc]] XCLIPVisionModel
|
| 80 |
+
- forward
|
tasks/tasksmith-333d8be2d5aa/tests/source/docs/source/en/model_doc/xglm.md
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2021 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# XGLM
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
The XGLM model was proposed in [Few-shot Learning with Multilingual Language Models](https://arxiv.org/abs/2112.10668)
|
| 22 |
+
by Xi Victoria Lin, Todor Mihaylov, Mikel Artetxe, Tianlu Wang, Shuohui Chen, Daniel Simig, Myle Ott, Naman Goyal,
|
| 23 |
+
Shruti Bhosale, Jingfei Du, Ramakanth Pasunuru, Sam Shleifer, Punit Singh Koura, Vishrav Chaudhary, Brian O'Horo,
|
| 24 |
+
Jeff Wang, Luke Zettlemoyer, Zornitsa Kozareva, Mona Diab, Veselin Stoyanov, Xian Li.
|
| 25 |
+
|
| 26 |
+
The abstract from the paper is the following:
|
| 27 |
+
|
| 28 |
+
*Large-scale autoregressive language models such as GPT-3 are few-shot learners that can perform a wide range of language
|
| 29 |
+
tasks without fine-tuning. While these models are known to be able to jointly represent many different languages,
|
| 30 |
+
their training data is dominated by English, potentially limiting their cross-lingual generalization.
|
| 31 |
+
In this work, we train multilingual autoregressive language models on a balanced corpus covering a diverse set of languages,
|
| 32 |
+
and study their few- and zero-shot learning capabilities in a wide range of tasks. Our largest model with 7.5 billion parameters
|
| 33 |
+
sets new state of the art in few-shot learning in more than 20 representative languages, outperforming GPT-3 of comparable size
|
| 34 |
+
in multilingual commonsense reasoning (with +7.4% absolute accuracy improvement in 0-shot settings and +9.4% in 4-shot settings)
|
| 35 |
+
and natural language inference (+5.4% in each of 0-shot and 4-shot settings). On the FLORES-101 machine translation benchmark,
|
| 36 |
+
our model outperforms GPT-3 on 171 out of 182 translation directions with 32 training examples, while surpassing the
|
| 37 |
+
official supervised baseline in 45 directions. We present a detailed analysis of where the model succeeds and fails,
|
| 38 |
+
showing in particular that it enables cross-lingual in-context learning on some tasks, while there is still room for improvement
|
| 39 |
+
on surface form robustness and adaptation to tasks that do not have a natural cloze form. Finally, we evaluate our models
|
| 40 |
+
in social value tasks such as hate speech detection in five languages and find it has limitations similar to comparable sized GPT-3 models.*
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
This model was contributed by [Suraj](https://huggingface.co/valhalla). The original code can be found [here](https://github.com/pytorch/fairseq/tree/main/examples/xglm).
|
| 44 |
+
|
| 45 |
+
## Resources
|
| 46 |
+
|
| 47 |
+
- [Causal language modeling task guide](../tasks/language_modeling)
|
| 48 |
+
|
| 49 |
+
## XGLMConfig
|
| 50 |
+
|
| 51 |
+
[[autodoc]] XGLMConfig
|
| 52 |
+
|
| 53 |
+
## XGLMTokenizer
|
| 54 |
+
|
| 55 |
+
[[autodoc]] XGLMTokenizer
|
| 56 |
+
- build_inputs_with_special_tokens
|
| 57 |
+
- get_special_tokens_mask
|
| 58 |
+
- create_token_type_ids_from_sequences
|
| 59 |
+
- save_vocabulary
|
| 60 |
+
|
| 61 |
+
## XGLMTokenizerFast
|
| 62 |
+
|
| 63 |
+
[[autodoc]] XGLMTokenizerFast
|
| 64 |
+
|
| 65 |
+
<frameworkcontent>
|
| 66 |
+
<pt>
|
| 67 |
+
|
| 68 |
+
## XGLMModel
|
| 69 |
+
|
| 70 |
+
[[autodoc]] XGLMModel
|
| 71 |
+
- forward
|
| 72 |
+
|
| 73 |
+
## XGLMForCausalLM
|
| 74 |
+
|
| 75 |
+
[[autodoc]] XGLMForCausalLM
|
| 76 |
+
- forward
|
| 77 |
+
|
| 78 |
+
</pt>
|
| 79 |
+
<tf>
|
| 80 |
+
|
| 81 |
+
## TFXGLMModel
|
| 82 |
+
|
| 83 |
+
[[autodoc]] TFXGLMModel
|
| 84 |
+
- call
|
| 85 |
+
|
| 86 |
+
## TFXGLMForCausalLM
|
| 87 |
+
|
| 88 |
+
[[autodoc]] TFXGLMForCausalLM
|
| 89 |
+
- call
|
| 90 |
+
|
| 91 |
+
</tf>
|
| 92 |
+
<jax>
|
| 93 |
+
|
| 94 |
+
## FlaxXGLMModel
|
| 95 |
+
|
| 96 |
+
[[autodoc]] FlaxXGLMModel
|
| 97 |
+
- __call__
|
| 98 |
+
|
| 99 |
+
## FlaxXGLMForCausalLM
|
| 100 |
+
|
| 101 |
+
[[autodoc]] FlaxXGLMForCausalLM
|
| 102 |
+
- __call__
|
| 103 |
+
|
| 104 |
+
</jax>
|
| 105 |
+
</frameworkcontent>
|