# ViTDet

## 概要

ViTDetモデルは、Yanghao Li、Hanzi Mao、Ross Girshick、Kaiming He による [Exploring Plain Vision Transformer Backbones for Object Detection](https://huggingface.co/papers/2203.16527) で提案されました。ViTDetは、オブジェクト検出タスクのためにプレーンな [Vision Transformer](vit) を活用しています。

論文の抄録は以下の通りです。

*当研究では、オブジェクト検出のバックボーンネットワークとして、階層構造を持たないプレーンなVision Transformer (ViT) を検討します。この設計により、事前学習のために階層型バックボーンを再設計する必要なく、元のViTアーキテクチャをオブジェクト検出向けにファインチューニングできます。ファインチューニングのための最小限の適応により、当社のプレーンバックボーン検出器は競争力のある結果を達成します。驚くべきことに、以下の点が観察されました：(i) 一般的なFPN設計を用いずに、単一スケールの特徴量マップから単純な特徴量ピラミッドを構築するだけで十分であること、および (ii) ウィンドウシフトなしのウィンドウアテンションと、ごく少数のウィンドウ間伝播ブロックを併用するだけで十分であること。Masked Autoencoders (MAE) として事前学習されたプレーンViTバックボーンを用いた当社の検出器 ViTDet は、すべて階層型バックボーンに基づいた従来の最先端手法と競合し、ImageNet-1K の事前学習のみを用いて COCO データセットで最大 61.3 AP_box に達します。本研究が、プレーンバックボーン検出器に関する研究への関心を高めることを期待しています。*

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

ヒント:

- 現時点では、バックボーンのみが利用可能です。

## VitDetConfig[[transformers.VitDetConfig]]

#### transformers.VitDetConfig[[transformers.VitDetConfig]]

```python
transformers.VitDetConfig(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, hidden_size: int = 768, num_hidden_layers: int = 12, num_attention_heads: int = 12, mlp_ratio: int = 4, hidden_act: str = 'gelu', dropout_prob: float | int = 0.0, initializer_range: float = 0.02, layer_norm_eps: float = 1e-06, image_size: int | list[int] | tuple[int, int] = 224, pretrain_image_size: int | list[int] | tuple[int, int] = 224, patch_size: int | list[int] | tuple[int, int] = 16, num_channels: int = 3, qkv_bias: bool = True, drop_path_rate: float | int = 0.0, window_block_indices: list[int] | tuple[int, ...] = (), residual_block_indices: list[int] | tuple[int, ...] = (), use_absolute_position_embeddings: bool = True, use_relative_position_embeddings: bool = False, window_size: int = 0, _out_features: list[str] | None = None, _out_indices: list[int] | None = None)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/vitdet/configuration_vitdet.py#L25)

**パラメータ:**

hidden_size (`int`、*任意*、デフォルトは`768`) : 隠れ表現の次元数。

num_hidden_layers (`int`, *任意*, デフォルトは `12`) : Transformer デコーダーの隠れ層の数。

num_attention_heads (`int`、*任意*、デフォルトは `12`) : Transformer デコーダーの各アテンション層におけるアテンションヘッドの数。

mlp_ratio (`int`、*任意*、デフォルトは`4`) : MLPの隠れ層次元と埋め込み次元の比率。

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

dropout_prob (`Union[float, int]`、*任意*、デフォルトは`0.0`) : すべての dropout レイヤーの比率。

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

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

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

pretrain_image_size (`int`、*optional*、デフォルトは 224) : プリトレーニング中の各画像のサイズ（解像度）。

patch_size (`Union[int, list[int], tuple[int, int]]`、*任意*、デフォルトは`16`) : 各パッチのサイズ（解像度）。

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

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

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

window_block_indices (`list[int]`、*任意*、デフォルトは`[]`) : 通常のグローバル自己注意ではなくウィンドウ注意を使用すべきブロックのインデックスのリスト。

residual_block_indices (`list[int]`、*optional*、デフォルトは`[]`) : MLPの後に追加の残差ブロックを持つべきブロックのインデックスのリスト。

use_absolute_position_embeddings (`bool`、*任意*、デフォルトは`True`) : 絶対位置埋め込みを使用するかどうか。

use_relative_position_embeddings (`bool`、*任意*、デフォルトは`False`) : アテンションマップに相対位置埋め込みを追加するかどうか。

window_size (`int`、*任意*、デフォルトは 0) : アテンションウィンドウのサイズ。

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

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

例:

```python
>>> from transformers import VitDetConfig, VitDetModel

>>> # Initializing a VitDet configuration
>>> configuration = VitDetConfig()

>>> # Initializing a model (with random weights) from the configuration
>>> model = VitDetModel(configuration)

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

## VitDetModel[[transformers.VitDetModel]]

#### transformers.VitDetModel[[transformers.VitDetModel]]

```python
transformers.VitDetModel(config: VitDetConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/vitdet/modeling_vitdet.py#L600)

**パラメータ:**

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

特定のヘッドを付加せず、生のhidden-statesを出力する素のVitdet 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.VitDetModel.forward]]

```python
forward(pixel_values: 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/vitdet/modeling_vitdet.py#L614)

**パラメータ:**

pixel_values (`torch.Tensor`、shape `(batch_size, num_channels, image_size, image_size)`、*optional*) : 入力画像に対応するテンソルです。ピクセル値は `image_processor_class` を使用して取得できます。詳細は `image_processor_class.__call__` を参照してください（`processor_class` は画像の処理に `image_processor_class` を使用します）。

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.Tensor)`

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

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

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

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

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

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

例:

```python
>>> from transformers import VitDetConfig, VitDetModel
>>> import torch

>>> config = VitDetConfig()
>>> model = VitDetModel(config)

>>> pixel_values = torch.randn(1, 3, 224, 224)

>>> with torch.no_grad():
...     outputs = model(pixel_values)

>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 768, 14, 14]
```

