# Registers付きDINOv2

## 概要

Registers付きDINOv2モデルは、Timothée Darcet、Maxime Oquab、Julien Mairal、Piotr Bojanowskiによる[Vision Transformers Need Registers](https://huggingface.co/papers/2309.16588)で提案されました。

[Vision Transformer](vit)（ViT）は、ImageNet での教師あり画像分類のために最初に提案された、Transformer エンコーダーモデル（BERT 類似）です。

次に、ラベルなしの画像から意味のある特徴（埋め込みとも呼ばれる）を学習する、自己教師あり画像特徴抽出において ViT を非常に効果的に機能させる方法が次々と考案されました。関連する論文の例としては、[DINOv2](dinov2)や[MAE](vit_mae)などが挙げられます。

DINOv2の著者たちは、ViTの注意マップにアーティファクトが存在することを確認しました。これは、モデルが一部の画像パッチを「レジスター」として使用しているためです。著者たちは修正策を提案しています。それは、新しいトークン（「レジスター」トークンと呼ばれます）を追加し、事前学習の段階でのみ使用して、その後は破棄するというものです。これにより、以下のような結果が得られます。

- アーティファクトなし
- 解釈可能なアテンションマップ
- そして、パフォーマンスの向上。

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

*Transformers は、視覚表現の学習において強力なツールとして近年登場しました。本論文では、教師あり ViT ネットワークと自己教師あり ViT ネットワークの両方の特徴マップにおけるアーティファクトを特定し、その特性を明らかにします。これらのアーティファクトは、推論時に主に画像の低情報量な背景領域に現れる高ノルムトークンに対応しており、内部計算のために転用されています。私たちは、Vision Transformer の入力シーケンスに追加のトークンを提供してその役割を担わせるという、シンプルかつ効果的な解決策を提案します。この解決策が、教師ありモデルと自己教師ありモデルの両方において当該問題を完全に解消し、密な視覚予測タスクにおける自己教師あり視覚モデルの新たな最良性能を達成し、より大きなモデルを用いたオブジェクト発見手法を可能にし、最も重要なのは、下流の視覚処理においてより滑らかな特徴マップとアテンションマップをもたらすことを示します。*

<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/dinov2_with_registers_visualization.png"
alt="drawing" width="600"/>

 レジスターあり/なしで訓練されたさまざまなモデルのアテンションマップの可視化。元の論文より引用。

ヒント:

- Registers付きDINOv2の使用方法は、RegistersなしのDINOv2と同一であり、パフォーマンスが向上するだけです。

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

## Dinov2WithRegistersConfig[[transformers.Dinov2WithRegistersConfig]]

#### transformers.Dinov2WithRegistersConfig[[transformers.Dinov2WithRegistersConfig]]

```python
transformers.Dinov2WithRegistersConfig(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', hidden_dropout_prob: float | int = 0.0, attention_probs_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, patch_size: int | list[int] | tuple[int, int] = 16, num_channels: int = 3, qkv_bias: bool = True, layerscale_value: float = 1.0, drop_path_rate: float | int = 0.0, use_swiglu_ffn: bool = False, num_register_tokens: int = 4, _out_features: list[str] | None = None, _out_indices: list[int] | None = None, apply_layernorm: bool = True, reshape_hidden_states: bool = True)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/dinov2_with_registers/configuration_dinov2_with_registers.py#L32)

**パラメータ:**

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"`など。

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の標準偏差です。

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

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

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

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

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

layerscale_value (`float`、*任意*、デフォルト値は 1.0) : layer scale に使用する初期値。

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

use_swiglu_ffn (`bool`, *任意*, デフォルトは `False`) : SwiGLUフィードフォワードニューラルネットワークを使用するかどうか。

num_register_tokens (`int`、*任意*、デフォルトは 4) : 使用するレジスタトークンの数。

apply_layernorm (`bool`、*任意*、デフォルトは`True`) : モデルがバックボーンとして使用される場合、特徴量マップにレイヤーノルマイズを適用するかどうかを指定します。

reshape_hidden_states (`bool`、*任意*、デフォルトは`True`) : モデルがバックボーンとして使用される場合、特徴マップを`(batch_size, hidden_size, height, width)`の形状の4次元テンソルにリサイズするかどうか。`False`の場合、特徴マップは`(batch_size, seq_len, hidden_size)`の形状の3次元テンソルになります。

This is the configuration class to store the configuration of a Dinov2WithRegistersModel. It is used to instantiate a Dinov2 With Registers model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the [facebook/dinov2-with-registers-base](https://huggingface.co/facebook/dinov2-with-registers-base)

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

例:

```python
>>> from transformers import Dinov2WithRegistersConfig, Dinov2WithRegistersModel

>>> # Initializing a Dinov2WithRegisters base style configuration
>>> configuration = Dinov2WithRegistersConfig()

>>> # Initializing a model (with random weights) from the base style configuration
>>> model = Dinov2WithRegistersModel(configuration)

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

## Dinov2WithRegistersModel[[transformers.Dinov2WithRegistersModel]]

#### transformers.Dinov2WithRegistersModel[[transformers.Dinov2WithRegistersModel]]

```python
transformers.Dinov2WithRegistersModel(config: Dinov2WithRegistersConfig)
```

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

**パラメータ:**

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

裸のDinov2 With Registers Modelは、特定のヘッドを付加せずに生のhidden-statesを出力します。

このモデルは [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.Dinov2WithRegistersModel.forward]]

```python
forward(pixel_values: typing.Optional[torch.Tensor] = None, bool_masked_pos: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/dinov2_with_registers/modeling_dinov2_with_registers.py#L402)

**パラメータ:**

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` を使用します）。

bool_masked_pos (`torch.BoolTensor`、shape `(batch_size, sequence_length)`) : ブール型のマスク位置。どのパッチがマスクされているか（1）、されていないか（0）を示します。事前学習でのみ関連します。

attention_mask (`torch.Tensor`、shape `(batch_size, sequence_length)`、*任意*) : padding トークンのインデックスに対する attention を回避するためのマスクです。マスクの値は `[0, 1]` から選択されます:  - **マスクされない**トークンは 1、- **マスクされる**トークンは 0。  [attention マスクとは?](../glossary#attention-mask)

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

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

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

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

- **last_hidden_state** (`torch.FloatTensor`、shape `(batch_size, sequence_length, hidden_size)`) -- モデルの最終層の出力における隠れ状態のシーケンス。
- **pooler_output** (`torch.FloatTensor`、shape `(batch_size, hidden_size)`) -- 補助事前学習タスクに使用される層をさらに通して処理された後、シーケンスの最初のトークン（分類トークン）の最終層の隠れ状態です。例えば、BERT 系のモデルでは、線形層と tanh 活性化関数を経て処理された後の分類トークンを返します。この線形層の重みは、事前学習中の次文予測（分類）目的から学習されます。
- **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後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

例:

```python
```

## Dinov2WithRegistersForImageClassification[[transformers.Dinov2WithRegistersForImageClassification]]

#### transformers.Dinov2WithRegistersForImageClassification[[transformers.Dinov2WithRegistersForImageClassification]]

```python
transformers.Dinov2WithRegistersForImageClassification(config: Dinov2WithRegistersConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/dinov2_with_registers/modeling_dinov2_with_registers.py#L439)

**パラメータ:**

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

Dinov2WithRegisters 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.Dinov2WithRegistersForImageClassification.forward]]

```python
forward(pixel_values: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/dinov2_with_registers/modeling_dinov2_with_registers.py#L452)

**パラメータ:**

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` を使用します）。

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

attention_mask (`torch.Tensor`、shape `(batch_size, sequence_length)`、*任意*) : padding トークンのインデックスに対する attention を回避するためのマスクです。マスクの値は `[0, 1]` から選択されます:  - **マスクされない**トークンは 1、- **マスクされる**トークンは 0。  [attention マスクとは?](../glossary#attention-mask)

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

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

[Dinov2WithRegistersForImageClassification](/docs/transformers/main/ja/model_doc/dinov2_with_registers#transformers.Dinov2WithRegistersForImageClassification) の 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, Dinov2WithRegistersForImageClassification
>>> import torch
>>> from datasets import load_dataset

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

>>> image_processor = AutoImageProcessor.from_pretrained("facebook/dinov2-with-registers-base")
>>> model = Dinov2WithRegistersForImageClassification.from_pretrained("facebook/dinov2-with-registers-base")

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

