# Pyramid Vision Transformer V2 (PVTv2)

## 概要

PVTv2モデルは、Wenhai Wang、Enze Xie、Xiang Li、Deng-Ping Fan、Kaitao Song、Ding Liang、Tong Lu、Ping Luo、Ling Shao によって提案された [PVT v2: Improved Baselines with Pyramid Vision Transformer](https://huggingface.co/papers/2106.13797) に記載されています。PVTの改良版として、位置埋め込みを排除し、代わりにゼロパディングと重複するパッチ埋め込みによってエンコードされる位置情報に依存しています。この位置埋め込みへの依存性の排除により、アーキテクチャが簡素化され、それらの補間を行うことなく任意の解像度で推論を実行できるようになります。

PVTv2エンコーダー構造は、セマンティックセグメンテーションの[Segformer](https://huggingface.co/papers/2105.15203)、単眼深度推定の[GLPN](https://huggingface.co/papers/2201.07436)、パノプティックセグメンテーションの[Panoptic Segformer](https://huggingface.co/papers/2109.03814)において、最先端のスコアを達成するために正常にデプロイされました。

PVTv2 は、[階層型トランスフォーマー](https://natecibik.medium.com/the-rise-of-vision-transformers-f623c980419f) と呼ばれるモデルファミリーに属しています。このファミリーは、マルチスケールの特徴マップを生成するためにトランスフォーマー層に適応を加えます。Vision Transformer ([ViT](https://huggingface.co/papers/2010.11929)) の列状構造は微細な詳細を失う傾向がありますが、マルチスケールの特徴マップはこれらの詳細を保持し、高密度予測タスクの性能向上に寄与することが知られています。PVTv2 の場合、これは各エンコーダー層において、重なり合うカーネルを用いた 2 次元畳み込みで画像パッチトークンを生成することによって実現されています。

階層型 Transformer のマルチスケール特徴により、ResNet などの従来の主力コンピュータビジョンバックボーンモデルを、より大規模なアーキテクチャ内で容易に置き換えることができます。Segformer と Panoptic Segformer の両方で、バックボーンに PVTv2 を使用した構成が、同サイズの ResNet バックボーンを使用する構成を一貫して上回ることが示されました。

PVTv2のもう一つの強力な機能は、自己注意層における複雑度の低減です。これはSpatial Reduction Attention (SRA) と呼ばれ、2D 畳み込み層を使用して隠れ状態をより低い解像度に射影してからクエリで注意を向けることで、自己注意の $O(n^2)$ の複雑度を $O(n^2/R)$ に改善します。ここで $R$ は空間削減率 (`sr_ratio`、2D 畳み込みにおけるカーネルサイズとストライドに相当) です。

SRAはPVTで導入され、PVTv2で使用されるデフォルトの注意複雑度削減手法です。ただし、PVTv2では、画像サイズに線形に関連する複雑度を持つ自己注意機構を使用するオプションも導入されており、これは「Linear SRA」と呼ばれます。この手法は、平均プーリングを使用して隠れ状態を元の解像度に依存しない固定サイズに削減します（ただし、これは通常のSRAよりも本質的に損失が大きくなります）。このオプションは、PVTv2Configで`linear_attention`を`True`に設定することで有効にできます。

### 論文からの抜粋

*Transformer は最近、コンピュータビジョンにおいて有望な進歩を示しています。本研究では、元の Pyramid Vision Transformer (PVT v1) に 3 つの設計、すなわち (1) 線形計算量のアテンション層、(2) 重複するパッチ埋め込み、(3) 畳み込みフィードフォワードネットワークを追加することで、新しいベースラインを提示します。これらの修正により、PVT v2 は PVT v1 の計算複雑さを線形に低減し、分類、検出、セグメンテーションといった基本的なビジョンタスクにおいて大幅な性能向上を達成しました。特に、提案する PVT v2 は、Swin Transformer などの最近の研究と比較して同等以上の性能を発揮します。本研究がコンピュータビジョンにおける最先端の Transformer 研究を促進することを期待しています。コードは https://github.com/whai362/PVT で利用可能です。*

このモデルは[FoamoftheSea](https://huggingface.co/FoamoftheSea)によって提供されました。元のコードは[こちら](https://github.com/whai362/PVT)で確認できます。

## 使用のコツ

- [PVTv2](https://huggingface.co/papers/2106.13797) は階層型 Transformer モデルであり、画像分類をはじめとする複数のタスクで優れた性能を示しています。[Segformer](https://huggingface.co/papers/2105.15203) におけるセマンティックセグメンテーション、[GLPN](https://huggingface.co/papers/2201.07436) における単眼深度推定、[Panoptic Segformer](https://huggingface.co/papers/2109.03814) におけるパノプティックセグメンテーションのバックボーンとして使用されており、同様の ResNet 構成と比較して一貫して高い性能を発揮しています。
- PVTv2のような階層型transformersは、エンコーダーに畳み込みニューラルネットワーク（CNN）の設計要素を取り入れることで、純粋なtransformersアーキテクチャと比較して、画像データにおいて優れたデータ効率とパラメータ効率を実現します。これにより、[transformers](https://huggingface.co/papers/1706.03762)の自己注意機構が提供する動的なデータ応答とグローバルな関係モデリングの利点を享受しつつ、ネットワークにCNNの有用な帰納的バイアス（移動等変性や局所性など）を付与する、両者の長所を兼ね備えたアーキテクチャが構築されます。
- PVTv2 は、重複するパッチ埋め込みを使用してマルチスケールの特徴マップを作成し、ゼロパディングと深度方向畳み込みを用いて位置情報を付与します。
- アテンション層の複雑さを低減するために、PVTv2 は、ストライド付き 2D 畳み込み (SRA) または固定サイズのアベレージプーリング (Linear SRA) を使用して、隠れ状態に対して空間的削減を行います。Linear SRA は本質的に損失が大きく、画像サイズに対して線形な複雑さを持ちながら、優れたパフォーマンスを発揮します。自己アテンション層で Linear SRA を使用するには、`PvtV2Config` で `linear_attention=True` を設定します。
- [PvtV2Model](/docs/transformers/main/ja/model_doc/pvt_v2#transformers.PvtV2Model) は階層型 Transformer エンコーダーです（文献では Mix Transformer や MiT と呼ばれることも多いです）。[PvtV2ForImageClassification](/docs/transformers/main/ja/model_doc/pvt_v2#transformers.PvtV2ForImageClassification) はその上にシンプルな分類ヘッドを追加して、Image Classification を行います。`PvtV2Backbone` は、Deformable DETR のような大規模なアーキテクチャにおいて [AutoBackbone](/docs/transformers/main/ja/main_classes/backbones#transformers.AutoBackbone) システムと組み合わせて使用できます。
- すべてのモデルサイズに対応したImageNet事前学習済み重みは、[ハブ](https://huggingface.co/models?other=pvt_v2)で入手できます。

 PVTv2の使い方を始める最善の方法は、`AutoModelForImageClassification`を使用して、希望するサイズの事前学習済みチェックポイントをロードすることです:

```python
import requests
import torch
from PIL import Image

from transformers import AutoImageProcessor, AutoModelForImageClassification

model = AutoModelForImageClassification.from_pretrained("OpenGVLab/pvt_v2_b0", device_map="auto")
image_processor = AutoImageProcessor.from_pretrained("OpenGVLab/pvt_v2_b0")
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)
processed = image_processor(image)
outputs = model(torch.tensor(processed["pixel_values"]))
```

DeformableDETRのようなより複雑なアーキテクチャのバックボーンとしてPVTv2を使用するには、AutoBackboneを使用できます（事前学習済みモデルのバックボーンを置き換えるため、ランダムな重みで初期化されるため、このモデルはファインチューニングが必要です）：

```python
import requests
import torch
from PIL import Image

from transformers import AutoConfig, AutoImageProcessor, AutoModelForObjectDetection

model = AutoModelForObjectDetection.from_config(
    config=AutoConfig.from_pretrained(
        "SenseTime/deformable-detr",
        backbone_config=AutoConfig.from_pretrained("OpenGVLab/pvt_v2_b5"),
    ),
)

image_processor = AutoImageProcessor.from_pretrained("SenseTime/deformable-detr")
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)
processed = image_processor(image)
outputs = model(torch.tensor(processed["pixel_values"]))
```

モデルサイズ（B0-B5）別のImageNet-1Kにおける[PVTv2](https://github.com/whai362/PVT/tree/v2)の性能:

| メソッド           | サイズ | Acc@1 | #パラメータ数 (M) |
|------------------|:----:|:-----:|:-----------:|
| PVT-V2-B0        |  224 |  70.5 |     3.7     |
| PVT-V2-B1        |  224 |  78.7 |     14.0    |
| PVT-V2-B2-Linear |  224 |  82.1 |     22.6    |
| PVT-V2-B2        |  224 |  82.0 |     25.4    |
| PVT-V2-B3        |  224 |  83.1 |     45.2    |
| PVT-V2-B4        |  224 |  83.6 |     62.6    |
| PVT-V2-B5        |  224 |  83.8 |     82.0    |

## PvtV2Config[[transformers.PvtV2Config]]

#### transformers.PvtV2Config[[transformers.PvtV2Config]]

```python
transformers.PvtV2Config(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, image_size: int | list[int] | tuple[int, int] | dict = 224, num_channels: int = 3, num_encoder_blocks: int = 4, depths: list[int] | tuple[int, ...] = (2, 2, 2, 2), sr_ratios: list[int] | tuple[int, ...] = (8, 4, 2, 1), hidden_sizes: list[int] | tuple[int, ...] = (32, 64, 160, 256), patch_sizes: list[int] | tuple[int, ...] = (7, 3, 3, 3), strides: list[int] | tuple[int, ...] = (4, 2, 2, 2), num_attention_heads: list[int] | tuple[int, ...] = (1, 2, 5, 8), mlp_ratios: list[int] | tuple[int, ...] = (8, 8, 4, 4), hidden_act: str = 'gelu', hidden_dropout_prob: float | int = 0.0, attention_probs_dropout_prob: float | int = 0.0, initializer_range: float = 0.02, drop_path_rate: float | int = 0.0, layer_norm_eps: float = 1e-06, qkv_bias: bool = True, linear_attention: bool = False, _out_features: list[str] | None = None, _out_indices: list[int] | None = None)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/pvt_v2/configuration_pvt_v2.py#L27)

**パラメータ:**

image_size (`Union[int, list[int], tuple[int, int], dict]`, *任意*、デフォルトは`224`) : 各画像のサイズ（解像度）。

num_channels (`int`、*任意*、デフォルトは`3`) : 入力チャネル数。

num_encoder_blocks (`[int]`, *optional*, デフォルトは 4) : エンコーダーブロックの数（つまり、Mix Transformer エンコーダーのステージ数）。

depths (`Union[list[int], tuple[int, ...]]`、*任意*、デフォルトは`(2, 2, 2, 2)`) : Transformerの各層の深さ。

sr_ratios (`list[int]`、*optional*、デフォルトは`[8, 4, 2, 1]`) : 各エンコーダーブロックにおける空間的削減比率。

hidden_sizes (`Union[list[int], tuple[int, ...]]`、*任意*、デフォルトは`(32, 64, 160, 256)`) : モデルの各ステージにおける次元数（隠れ層サイズ）。

patch_sizes (`list[int]`、*optional*、デフォルトは`[7, 3, 3, 3]`) : 各エンコーダーブロックの前に適用される、重複するパッチ埋め込みのパッチサイズです。

strides (`list[int]`、*optional*、デフォルトは`[4, 2, 2, 2]`) : 各エンコーダーブロックの前に適用される、重複するパッチ埋め込みのストライド。

num_attention_heads (`list[int]`、*任意*、デフォルトは `[1, 2, 5, 8]`) : Transformer エンコーダーの各ブロックにおける、各アテンション層のアテンションヘッド数。

mlp_ratios (`list[int]`、*optional*、デフォルトは`[8, 8, 4, 4]`) : エンコーダーブロック内のMix FFNにおいて、隠れ層のサイズと入力層のサイズの比率。

hidden_act (`str`、*任意*、デフォルトは`gelu`) : デコーダーで使用する非線形活性化関数（関数または文字列）。例えば、`"gelu"`、`"relu"`、`"silu"`など。

hidden_dropout_prob (`Union[float, int]`、*任意*、デフォルトは`0.0`) : embeddings、encoder、pooler 内のすべての全結合層における dropout 確率。

attention_probs_dropout_prob (`Union[float, int]`、*任意*、デフォルトは`0.0`) : 注意確率のドロップアウト率。

initializer_range (`float`、*任意*、デフォルトは`0.02`) : すべての重み行列を初期化するためのtruncated_normal_initializerの標準偏差です。

drop_path_rate (`Union[float, int]`、*任意*、デフォルトは`0.0`) : パッチ融合のドロップパス率。

layer_norm_eps (`float`、*任意*、デフォルトは`1e-06`) : Layer Normalization 層で使用する epsilon です。

qkv_bias (`bool`, *任意*, デフォルトは `True`) : クエリ、キー、バリューにバイアスを追加するかどうか。

linear_attention (`bool`、*任意*、デフォルトは`False`) : 線形アテンションの計算量を使用します。True に設定すると、`sr_ratio` は無視され、アテンション層の次元削減にはストライド付き畳み込みではなく平均プーリングが使用されます。

これは PvtV2Model の設定を保存するための設定クラスです。指定された引数に基づいて Pvt V2 モデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[OpenGVLab/pvt_v2_b0](https://huggingface.co/OpenGVLab/pvt_v2_b0) と同様の設定が得られます。

設定オブジェクトは [PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) を継承し、モデルの出力を制御するために使用できます。詳細については、[PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) のドキュメントを参照してください。

例:

```python
>>> from transformers import PvtV2Model, PvtV2Config

>>> # Initializing a pvt_v2_b0 style configuration
>>> configuration = PvtV2Config()

>>> # Initializing a model from the OpenGVLab/pvt_v2_b0 style configuration
>>> model = PvtV2Model(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config
```

## PvtForImageClassification[[transformers.PvtV2ForImageClassification]]

#### transformers.PvtV2ForImageClassification[[transformers.PvtV2ForImageClassification]]

```python
transformers.PvtV2ForImageClassification(config: PvtV2Config)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/pvt_v2/modeling_pvt_v2.py#L432)

**パラメータ:**

config ([PvtV2Config](/docs/transformers/main/ja/model_doc/pvt_v2#transformers.PvtV2Config)) : モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、[from_pretrained()](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) メソッドを参照してください。

Pvt-v2 Model は、[CLS] トークンの最終的な隠れ状態の上に線形層を配置した画像分類ヘッドを備えた transformer です。ImageNet などが例として挙げられます。

このモデルは [PreTrainedModel](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel) を継承しています。ライブラリがすべてのモデルに対して実装している汎用的なメソッド（ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど）については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchの[torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)のサブクラスでもあります。通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

#### forward[[transformers.PvtV2ForImageClassification.forward]]

```python
forward(pixel_values: typing.Optional[torch.Tensor], labels: typing.Optional[torch.Tensor] = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/pvt_v2/modeling_pvt_v2.py#L447)

**パラメータ:**

pixel_values (`torch.Tensor`、形状 `(batch_size, num_channels, image_size, image_size)`、*任意*) : 入力画像に対応するテンソルです。ピクセル値は [PvtImageProcessor](/docs/transformers/main/ja/model_doc/pvt#transformers.PvtImageProcessor) を使用して取得できます。詳細については [PvtImageProcessor.__call__()](/docs/transformers/main/ja/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) を参照してください（`processor_class` は画像の処理に [PvtImageProcessor](/docs/transformers/main/ja/model_doc/pvt#transformers.PvtImageProcessor) を使用します）。

labels (`torch.LongTensor`、shape `(batch_size,)`、*任意*) : 画像分類/回帰の損失を計算するためのラベル。インデックスは `[0, ..., config.num_labels - 1]` の範囲である必要があります。`config.num_labels == 1` の場合は回帰損失（Mean-Square loss）が計算され、`config.num_labels > 1` の場合は分類損失（Cross-Entropy）が計算されます。

output_attentions (`bool`, *任意*) : すべてのアテンション層のアテンションテンソルを返すかどうか。詳細は、返されるテンソルの `attentions` を参照してください。

output_hidden_states (`bool`, *任意*) : 全レイヤーの hidden states を返すかどうかを指定します。詳細は、返されるテンソルの `hidden_states` を参照してください。

return_dict (`bool`, *任意*) : プレーンなタプルではなく [ModelOutput](/docs/transformers/main/ja/main_classes/output#transformers.utils.ModelOutput) を返すかどうか。

**戻り値:** [ImageClassifierOutput](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.ImageClassifierOutput) または `tuple(torch.FloatTensor)`

設定（[PvtV2Config](/docs/transformers/main/ja/model_doc/pvt_v2#transformers.PvtV2Config)）や入力に応じて、さまざまな要素で構成される [ImageClassifierOutput](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.ImageClassifierOutput)、または `torch.FloatTensor` のタプル（`return_dict=False` が渡された場合、または `config.return_dict=False` の場合）。

[PvtV2ForImageClassification](/docs/transformers/main/ja/model_doc/pvt_v2#transformers.PvtV2ForImageClassification)のforwardメソッドは、`__call__`特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく`Module`インスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを無視してしまいます。

- **loss** (`torch.FloatTensor`、shape `(1,)`、*optional*、`labels` が指定された場合に返されます) -- 分類（または config.num_labels==1 の場合は回帰）の損失。
- **logits** (`torch.FloatTensor`、shape `(batch_size, config.num_labels)`) -- SoftMax 適用前の分類（または config.num_labels==1 の場合は回帰）スコア。
- **hidden_states** (`tuple(torch.FloatTensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返される) -- `torch.FloatTensor` のタプル（モデルに埋め込み層がある場合はその出力用 1 つ、各ステージの出力用 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。各ステージの出力におけるモデルの隠れ状態（特徴マップとも呼ばれる）です。
- **attentions** (`tuple(torch.FloatTensor)`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.FloatTensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, patch_size, sequence_length)`。

  アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

例:

```python
>>> from transformers import AutoImageProcessor, PvtV2ForImageClassification
>>> import torch
>>> from datasets import load_dataset

>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]

>>> image_processor = AutoImageProcessor.from_pretrained("OpenGVLab/pvt_v2_b0")
>>> model = PvtV2ForImageClassification.from_pretrained("OpenGVLab/pvt_v2_b0")

>>> inputs = image_processor(image, return_tensors="pt")

>>> with torch.no_grad():
...     logits = model(**inputs).logits

>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_label = logits.argmax(-1).item()
>>> print(model.config.id2label[predicted_label])
...
```

## PvtModel[[transformers.PvtV2Model]]

#### transformers.PvtV2Model[[transformers.PvtV2Model]]

```python
transformers.PvtV2Model(config: PvtV2Config)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/pvt_v2/modeling_pvt_v2.py#L382)

**パラメータ:**

config ([PvtV2Config](/docs/transformers/main/ja/model_doc/pvt_v2#transformers.PvtV2Config)) : モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、[from_pretrained()](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) メソッドを参照してください。

特定のヘッドが上に付いていない、生のhidden-statesを出力する素のPvt V2 Model。

このモデルは [PreTrainedModel](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel) を継承しています。ライブラリがすべてのモデルに対して実装している汎用的なメソッド（ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど）については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchの[torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)のサブクラスでもあります。通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

#### forward[[transformers.PvtV2Model.forward]]

```python
forward(pixel_values: FloatTensor, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/pvt_v2/modeling_pvt_v2.py#L393)

**パラメータ:**

pixel_values (`torch.FloatTensor`、shape `(batch_size, num_channels, image_size, image_size)`) : 入力画像に対応するテンソルです。ピクセル値は [PvtImageProcessor](/docs/transformers/main/ja/model_doc/pvt#transformers.PvtImageProcessor) を使用して取得できます。詳細は [PvtImageProcessor.__call__()](/docs/transformers/main/ja/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) を参照してください（`processor_class` は画像の処理に [PvtImageProcessor](/docs/transformers/main/ja/model_doc/pvt#transformers.PvtImageProcessor) を使用します）。

output_attentions (`bool`, *任意*) : すべてのアテンション層のアテンションテンソルを返すかどうか。詳細は、返されるテンソルの `attentions` を参照してください。

output_hidden_states (`bool`, *任意*) : 全レイヤーの hidden states を返すかどうかを指定します。詳細は、返されるテンソルの `hidden_states` を参照してください。

return_dict (`bool`, *任意*) : プレーンなタプルではなく [ModelOutput](/docs/transformers/main/ja/main_classes/output#transformers.utils.ModelOutput) を返すかどうか。

**戻り値:** [BaseModelOutput](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutput) または `tuple(torch.FloatTensor)`

[BaseModelOutput](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutput) または `torch.FloatTensor` のタプル（`return_dict=False` が渡された場合、または `config.return_dict=False` の場合）。設定（[PvtV2Config](/docs/transformers/main/ja/model_doc/pvt_v2#transformers.PvtV2Config)）と入力に応じて、さまざまな要素で構成されます。

[PvtV2Model](/docs/transformers/main/ja/model_doc/pvt_v2#transformers.PvtV2Model)のforwardメソッドは、`__call__`特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく`Module`インスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを無視してしまいます。

- **last_hidden_state** (`torch.FloatTensor`、shape `(batch_size, sequence_length, hidden_size)`) -- モデルの最終層の出力における隠れ状態のシーケンス。
- **hidden_states** (`tuple(torch.FloatTensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.FloatTensor` のタプル（埋め込み層を持つモデルの場合、埋め込みの出力用が 1 つ、各層の出力用が 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

  各層の出力におけるモデルのHidden-states、および任意の初期埋め込み出力。
- **attentions** (`tuple(torch.FloatTensor)`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.FloatTensor` のタプル（各レイヤーごとに1つ）で、形状は `(batch_size, num_heads, sequence_length, sequence_length)` です。

  アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

