# Dilated Neighborhood Attention Transformer

## 概要

DiNATは、Ali Hassani氏とHumphrey Shi氏による[Dilated Neighborhood Attention Transformer](https://huggingface.co/papers/2209.15001)で提案されました。

[NAT](https://huggingface.co/papers/2204.07143)を拡張し、Dilated Neighborhood Attentionパターンを追加してグローバルなコンテキストを捉えることで、それに対する顕著な性能向上を示しています。

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

*Transformers は、モダリティ、ドメイン、タスクを問わず、最も広く応用されている深層学習アーキテクチャの一つになりつつあります。ビジョン分野では、プレーンな Transformer への継続的な取り組みに加え、その性能と既存フレームワークへの容易な統合により、階層型 Transformer も大きな注目を集めています。これらのモデルは、スライディングウィンドウの Neighborhood Attention (NA) や Swin Transformer の Shifted Window Self Attention のような、局所化されたアテンション機構を典型的に採用しています。自己アテンションの二次的な計算量を削減する点では効果的ですが、局所アテンションは、自己アテンションの最も望ましい特性である長距離の相互依存関係のモデリングと、グローバルな受容野の 2 つを弱めてしまいます。本論文では、NA の自然で柔軟かつ効率的な拡張である Dilated Neighborhood Attention (DiNA) を提案します。DiNA は追加のコストなしによりグローバルなコンテキストを捉え、受容野を指数関数的に拡大できます。NA の局所アテンションと DiNA のスパースなグローバルアテンションは互いを補完し合うため、両方を基盤とする新しい階層型ビジョン Transformer、Dilated Neighborhood Attention Transformer (DiNAT) を提案します。DiNAT の各バリアントは、NAT、Swin、ConvNeXt といった強力なベースラインと比較して大幅な改善を実現しています。私たちの大規模モデルは、Swin の同等モデルよりも速く、COCO オブジェクト検出で 1.5% box AP、COCO インスタセグメンテーションで 1.3% mask AP、ADE20K セマンティックセグメンテーションで 1.1% mIoU 上回っています。新しいフレームワークと組み合わせることで、私たちの大規模バリアントは、COCO (58.2 PQ) と ADE20K (48.5 PQ) のパノプティックセグメンテーション、Cityscapes (44.5 AP) と ADE20K (35.4 AP) のインスタセグメンテーションにおいて、新たな最良のモデルとなりました（追加データなし）。また、ADE20K (58.2 mIoU) のセマンティックセグメンテーションでは最良の専用モデルに匹敵し、Cityscapes (84.5 mIoU) では 2 位にランクインしています（追加データなし）。*

<img
src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/dilated-neighborhood-attention-pattern.jpg"
alt="drawing" width="600"/>

 異なるdilation値を用いたNeighborhood Attention。元の論文より引用。

このモデルは[Ali Hassani](https://huggingface.co/alihassanijr)によって提供されました。元のコードは[こちら](https://github.com/SHI-Labs/Neighborhood-Attention-Transformer)で確認できます。

## 使用のコツ

DiNATは*backbone*として使用できます。`output_hidden_states = True`の場合、`hidden_states`と`reshaped_hidden_states`の両方が出力されます。`reshaped_hidden_states`の形状は`(batch_size, height, width, num_channels)`ではなく、`(batch, num_channels, height, width)`です。

注:

- DiNATは、[NATTEN](https://github.com/SHI-Labs/NATTEN/)によるNeighborhood AttentionおよびDilated Neighborhood Attentionの実装に依存しています。
[shi-labs.com/natten](https://shi-labs.com/natten) を参照して、Linux 向けの事前ビルド済みホイールをインストールするか、`pip install natten` を実行してシステム上でビルドできます。後者の場合、コンパイルに時間がかかる可能性があります。なお、NATTEN はまだ Windows デバイスをサポートしていません。
- 現時点では、4のPatch sizeのみサポートされています。

## リソース

DiNATの入門を支援するための、Hugging Face公式およびコミュニティ（🌎で示す）のリソースのリストです。

- [DinatForImageClassification](/docs/transformers/v5.23.0/ja/model_doc/dinat#transformers.DinatForImageClassification) は、この [ノートブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb) でサポートされています。
- 関連項目: [画像分類タスクガイド](../tasks/image_classification)

ここにリソースを掲載していただくことを希望される場合は、Pull Request を開いてください。レビューいたします。リソースは、既存のリソースと重複するのではなく、新しいものを示すことが望ましいです。

## DinatConfig[[transformers.DinatConfig]]

#### transformers.DinatConfig[[transformers.DinatConfig]]

```python
transformers.DinatConfig(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, patch_size: int | list[int] | tuple[int, int] = 4, num_channels: int = 3, embed_dim: int = 64, depths: list[int] | tuple[int, ...] = (3, 4, 6, 5), num_heads: list[int] | tuple[int, ...] = (2, 4, 8, 16), kernel_size: int = 7, dilations: list | tuple | None = None, mlp_ratio: float = 3.0, qkv_bias: bool = True, hidden_dropout_prob: float | int = 0.0, attention_probs_dropout_prob: float | int = 0.0, drop_path_rate: float | int = 0.1, hidden_act: str = 'gelu', initializer_range: float = 0.02, layer_norm_eps: float = 1e-05, layer_scale_init_value: float = 0.0, _out_features: list[str] | None = None, _out_indices: list[int] | None = None)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dinat/configuration_dinat.py#L25)

**パラメータ:**

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

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

embed_dim (`int`、*任意*、デフォルトは`64`) : 埋め込みおよび隠れ状態の次元数。

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

num_heads (`Union[list[int], tuple[int, ...]]`、*任意*、デフォルトは`(2, 4, 8, 16)`) : Transformerデコーダーの各アテンション層におけるアテンションヘッドの数。

kernel_size (`int`、*任意*、デフォルトは`7`) : 畳み込みカーネルのサイズです。

dilations (`list[list[int]]`、*任意*、デフォルトは`[[1, 8, 1], [1, 4, 1, 4], [1, 2, 1, 2, 1, 2], [1, 1, 1, 1, 1]]`) : Transformerエンコーダーの各NA層のDilation値です。

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

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

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

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

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

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

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

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

layer_scale_init_value (`float`、*任意*、デフォルトは `0.0`) : self-attention 層で使用するスケール。base モデルでは 0.1、large モデルでは 1e-6 を使用します。0 に設定すると layer scale が無効になります。

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

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

例:

```python
>>> from transformers import DinatConfig, DinatModel

>>> # Initializing a Dinat shi-labs/dinat-mini-in1k-224 style configuration
>>> configuration = DinatConfig()

>>> # Initializing a model (with random weights) from the shi-labs/dinat-mini-in1k-224 style configuration
>>> model = DinatModel(configuration)

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

## DinatModel[[transformers.DinatModel]]

#### transformers.DinatModel[[transformers.DinatModel]]

```python
transformers.DinatModel(config: DinatConfig, add_pooling_layer = True)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dinat/modeling_dinat.py#L541)

**パラメータ:**

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

add_pooling_layer (`bool`、*任意*、デフォルトは`True`) : プーリング層を追加するかどうか

特定のヘッドを上に載せず、生のhidden-statesを出力する素のDinat Model。

このモデルは [PreTrainedModel](/docs/transformers/v5.23.0/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.DinatModel.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/v5.23.0/src/transformers/models/dinat/modeling_dinat.py#L567)

**パラメータ:**

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

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

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

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

**戻り値:** `DinatModelOutput` または `tuple(torch.Tensor)`

`DinatModelOutput`、または`torch.Tensor`のタプル（`return_dict=False`が渡された場合、または`config.return_dict=False`の場合）。設定（[DinatConfig](/docs/transformers/v5.23.0/ja/model_doc/dinat#transformers.DinatConfig)）と入力に応じて、さまざまな要素で構成されます。

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

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

- **last_hidden_state** (`torch.Tensor`、形状 `(batch_size, sequence_length, hidden_size)`、*任意*) -- モデルの最終層の出力における隠れ状態のシーケンス。
- **pooler_output** (`torch.Tensor`、形状 `(batch_size, hidden_size)`、*任意*、`add_pooling_layer=True` が渡された場合に返されます) -- 最終層の隠れ状態の平均プーリング。
- **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後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
- **reshaped_hidden_states** (`tuple(torch.Tensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.Tensor` のタプル（埋め込みの出力用 1 つ + 各ステージの出力用 1 つ）、形状は `(batch_size, hidden_size, height, width)`。

  各層の出力におけるモデルのHidden-states、および空間次元を含むように整形された初期embeddingの出力。

例:

```python
```

## DinatForImageClassification[[transformers.DinatForImageClassification]]

#### transformers.DinatForImageClassification[[transformers.DinatForImageClassification]]

```python
transformers.DinatForImageClassification(config: DinatConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dinat/modeling_dinat.py#L622)

**パラメータ:**

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

Dinat Model は、[CLS] トークンの最終的な隠れ状態の上に線形層を配置した画像分類ヘッドを備えた transformer です。ImageNet などの用途に適しています。

このモデルは [PreTrainedModel](/docs/transformers/v5.23.0/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.DinatForImageClassification.forward]]

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

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dinat/modeling_dinat.py#L639)

**パラメータ:**

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

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/v5.23.0/ja/main_classes/output#transformers.utils.ModelOutput) を返すかどうか。

**戻り値:** `DinatImageClassifierOutput` または `tuple(torch.Tensor)`

`DinatImageClassifierOutput`、または`torch.Tensor`のタプル（`return_dict=False`が渡された場合、または`config.return_dict=False`の場合）。設定（[DinatConfig](/docs/transformers/v5.23.0/ja/model_doc/dinat#transformers.DinatConfig)）や入力に応じて、さまざまな要素で構成されます。

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

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

- **loss** (`torch.Tensor`、shape `(1,)`、*optional*、`labels` が指定された場合に返されます) -- 分類損失（config.num_labels==1 の場合は回帰損失）。
- **logits** (`torch.Tensor`、形状 `(batch_size, config.num_labels)`) -- SoftMax 適用前の分類（または config.num_labels==1 の場合は回帰）スコア。
- **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後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
- **reshaped_hidden_states** (`tuple(torch.Tensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.Tensor` のタプル（埋め込みの出力用 1 つ + 各ステージの出力用 1 つ）、形状は `(batch_size, hidden_size, height, width)`。

  各層の出力におけるモデルのHidden-states、および空間次元を含むように整形された初期embeddingの出力。

例:

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

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

>>> image_processor = AutoImageProcessor.from_pretrained("shi-labs/dinat-mini-in1k-224")
>>> model = DinatForImageClassification.from_pretrained("shi-labs/dinat-mini-in1k-224")

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

