# Video Vision Transformer (ViViT)

## 概要

Vivitモデルは、Anurag Arnab、Mostafa Dehghani、Georg Heigold、Chen Sun、Mario Lučić、Cordelia Schmid による [ViViT: A Video Vision Transformer](https://huggingface.co/papers/2103.15691) で提案されました。この論文は、動画理解のための純粋なTransformerベースのモデルセットの初期の成功例の一つを提案しています。

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

*画像分類における最近の成功を踏まえ、動画分類のための純粋なTransformerベースのモデルを提案します。本モデルは入力動画から時空間トークンを抽出し、一連のTransformer層によってエンコードします。動画で遭遇する長いトークンシーケンスを処理するために、入力の空間次元と時間次元を因数分解する、いくつかの効率的なモデルバリアントを提案します。Transformerベースのモデルは、大規模な学習データセットが利用可能な場合のみ有効であることが知られていますが、学習時にモデルを効果的に正則化し、事前学習済みの画像モデルを活用することで、比較的小規模なデータセットでの学習が可能であることを示します。徹底的なアブレーション研究を行い、Kinetics 400および600、Epic Kitchens、Something-Something v2、Moments in Timeを含む複数の動画分類ベンチマークで最先端の結果を達成し、従来の深い3D畳み込みネットワークベースの手法を上回りました。*

このモデルは[jegormeister](https://huggingface.co/jegormeister)によって提供されました。元のコード（JAXで記述）は[こちら](https://github.com/google-research/scenic/tree/main/scenic/projects/vivit)で確認できます。

### Scaled Dot Product Attention (SDPA) の使用

PyTorchには、`torch.nn.functional`の一部として、ネイティブなスケーリングドットプロダクトアテンション（SDPA）オペレーターが含まれています。この関数は、入力や使用しているハードウェアに応じて適用できる複数の実装を備えています。詳細については、[公式ドキュメント](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html)または[GPU推論](https://huggingface.co/docs/transformers/main/en/perf_infer_gpu_one#pytorch-scaled-dot-product-attention)ページを参照してください。

`torch>=2.1.1` の場合、実装が利用可能な場合はデフォルトで SDPA が使用されますが、`from_pretrained()` で `attn_implementation="sdpa"` を設定することで、SDPA の使用を明示的に指定することもできます。

```python
from transformers import VivitModel

model = VivitModel.from_pretrained("google/vivit-b-16x2-kinetics400", attn_implementation="sdpa", device_map="auto")
...
```

最大限の高速化を実現するには、モデルを半精度（例: `torch.float16` または `torch.bfloat16`）で読み込むことをお勧めします。

ローカル環境でのベンチマーク（A100-40GB、PyTorch 2.3.0、OS Ubuntu 22.04）において、`float32` と `google/vivit-b-16x2-kinetics400` モデルを使用した場合、推論時に以下の速度向上を確認しました。

### トレーニング

|   num_training_steps |   batch_size |   is cuda |   高速化率 (%) |   Eager ピークメモリ (MB) |   sdpa ピークメモリ (MB) |   メモリ削減率(%) |
|---------------------:|-------------:|----------:|--------------:|----------------------:|---------------------:|-----------------:|
|                  100 |            1 |      True |         7.122 |               2575.28 |              5932.54 |           130.364 |

### 推論

|   num_batches |   batch_size |   is cuda |   は半分の |   高速化率 (%) |   Mem eager (MB) |   メモリ BT (MB) |   メモリ削減率 (%) |
|---------------|--------------|-----------|-----------|---------------|------------------|---------------|-----------------|
|            20 |             1 |   True    |   False   |      15.422   |     715.807      |    317.079    |      125.75     |
|            20 |             2 |   True    |   False   |      17.146   |    1234.75       |    447.175    |      176.122    |
|            20 |             4 |   True    |   False   |      18.093   |    2275.82       |    709.864    |      220.6      |
|            20 |             8 |   True    |   False   |      19.284   |    4358.19       |   1233.24     |      253.393    |

## VivitConfig[[transformers.VivitConfig]]

#### transformers.VivitConfig[[transformers.VivitConfig]]

```python
transformers.VivitConfig(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] = 224, num_frames: int = 32, tubelet_size: list[int] | tuple[int, ...] = (2, 16, 16), num_channels: int = 3, hidden_size: int = 768, num_hidden_layers: int = 12, num_attention_heads: int = 12, intermediate_size: int = 3072, hidden_act: str = 'gelu_fast', 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, qkv_bias: bool = True, pooler_output_size: int | None = None, pooler_act: str = 'tanh')
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/vivit/configuration_vivit.py#L24)

**パラメータ:**

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

num_frames (`int`、*optional*、デフォルトは 32) : 各動画のフレーム数。

tubelet_size (`list[int]`, *任意*, デフォルトは `[2, 16, 16]`) : 各チューブレットのサイズ（解像度）。

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

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

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

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

intermediate_size (`int`、*任意*、デフォルトは `3072`) : MLP 表現の次元数。

hidden_act (`str`、*任意*、デフォルトは`gelu_fast`) : デコーダーで使用される非線形活性化関数（関数または文字列）。例えば、`"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 です。

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

pooler_output_size (`int`, *optional*) : プーラー層の次元数。None の場合、デフォルトで `hidden_size` になります。

pooler_act (`str`、*任意*、デフォルトは`"tanh"`) : pooler で使用される活性化関数。

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

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

例:

```python
>>> from transformers import VivitConfig, VivitModel

>>> # Initializing a ViViT google/vivit-b-16x2-kinetics400 style configuration
>>> configuration = VivitConfig()

>>> # Initializing a model (with random weights) from the google/vivit-b-16x2-kinetics400 style configuration
>>> model = VivitModel(configuration)

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

## VivitImageProcessor[[transformers.VivitImageProcessor]]

#### transformers.VivitImageProcessor[[transformers.VivitImageProcessor]]

```python
transformers.VivitImageProcessor(do_resize: bool = True, size: dict[str, int] | None = None, resample: Resampling = <Resampling.BILINEAR: 2>, do_center_crop: bool = True, crop_size: dict[str, int] | None = None, do_rescale: bool = True, rescale_factor: int | float = 0.00784313725490196, offset: bool = True, do_normalize: bool = True, image_mean: float | list[float] | None = None, image_std: float | list[float] | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/vivit/image_processing_vivit.py#L63)

**パラメータ:**

do_resize (`bool`、*任意*、デフォルトは`True`) : 画像の (高さ、幅) 次元を指定された`size`にリサイズするかどうか。`preprocess`メソッドの`do_resize`パラメータによって上書きできます。

size (`dict[str, int]` *任意*、デフォルトは `{"shortest_edge" : 256}`): リサイズ後の出力画像のサイズ。画像の短い辺は、元の画像のアスペクト比を維持したまま `size["shortest_edge"]` にリサイズされます。`preprocess` メソッド内の `size` によって上書きできます。

resample (`PILImageResampling`、*optional*、デフォルトは`Resampling.BILINEAR`) : 画像のリサイズ時に使用するリサンプリングフィルター。`preprocess`メソッドの`resample`パラメータによって上書きできます。

do_center_crop (`bool`、*任意*、デフォルトは`True`) : 画像を指定された`crop_size`にセンタークロップするかどうか。`preprocess`メソッドの`do_center_crop`パラメータによって上書きできます。

crop_size (`dict[str, int]`、*任意*、デフォルトは`{"height" : 224, "width": 224}`): センタークロップを適用した後の画像サイズ。`preprocess`メソッドの`crop_size`パラメータによって上書きできます。

do_rescale (`bool`、*任意*、デフォルトは`True`) : 指定されたスケーリング`rescale_factor`によって画像をリスケールするかどうか。`preprocess`メソッドの`do_rescale`パラメータによって上書きできます。

rescale_factor (`int` または `float`、*任意*、デフォルトは `1/127.5`) : 画像をリスケールする場合に使用するスケール係数を定義します。`preprocess` メソッドの `rescale_factor` パラメータによって上書きできます。

offset (`bool`、*任意*、デフォルトは`True`) : 画像を負方向と正方向の両方にスケーリングするかどうか。`preprocess`メソッドの`offset`によって上書きできます。

do_normalize (`bool`、*任意*、デフォルトは`True`) : 画像を正規化するかどうかを指定します。`preprocess`メソッドの`do_normalize`パラメータによって上書きできます。

image_mean (`float` または `list[float]`、*任意*、デフォルトは `IMAGENET_STANDARD_MEAN`) : 画像を正規化する場合に使用する平均値です。これは、画像のチャネル数と同じ長さの float または float のリストです。`preprocess` メソッドの `image_mean` パラメータによって上書きできます。

image_std (`float` または `list[float]`、*任意*、デフォルトは `IMAGENET_STANDARD_STD`) : 画像を正規化する場合に使用する標準偏差。これは、画像のチャネル数と同じ長さの float または float のリストです。`preprocess` メソッドの `image_std` パラメータによって上書きできます。

Vivit の画像プロセッサを構築します。

#### preprocess[[transformers.VivitImageProcessor.preprocess]]

```python
preprocess(videos: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']], do_resize: bool | None = None, size: dict[str, int] | None = None, resample: PIL.Image.Resampling | None = None, do_center_crop: bool | None = None, crop_size: dict[str, int] | None = None, do_rescale: bool | None = None, rescale_factor: float | None = None, offset: bool | None = None, do_normalize: bool | None = None, image_mean: float | list[float] | None = None, image_std: float | list[float] | None = None, return_tensors: str | transformers.utils.generic.TensorType | None = None, data_format: ChannelDimension = <ChannelDimension.FIRST: 'channels_first'>, input_data_format: str | transformers.image_utils.ChannelDimension | None = None)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/vivit/image_processing_vivit.py#L285)

**パラメータ:**

videos (`ImageInput`) : 前処理対象の動画フレーム。ピクセル値が0から255の範囲にある単一の動画フレームまたはバッチを期待します。ピクセル値が0から1の範囲にあるフレームを渡す場合は、`do_rescale=False`を設定してください。

do_resize (`bool`、*任意*、デフォルトは`self.do_resize`) : 画像をリサイズするかどうか。

size (`dict[str, int]`、*任意*、デフォルトは`self.size`) : リサイズを適用した後の画像のサイズ。

resample (`PILImageResampling`、*optional*、デフォルトは`self.resample`) : 画像のリサイズ時に使用するリサンプリングフィルタです。`PILImageResampling`の列挙型のいずれかになります。`do_resize`が`True`に設定されている場合のみ、効果が現れます。

do_center_crop (`bool`, *任意*, デフォルトは `self.do_centre_crop`) : 画像を中央クロップするかどうか。

crop_size (`dict[str, int]`, *任意*, デフォルトは `self.crop_size`) : 中央クロップを適用した後の画像のサイズ。

do_rescale (`bool`, *optional*, デフォルトは `self.do_rescale`) : `offset` が `True` の場合、画像の値を `[-1 - 1]` に、それ以外の場合は `[0, 1]` にリスケールするかどうか。

rescale_factor (`float`、*任意*、デフォルトは `self.rescale_factor`) : `do_rescale` が `True` に設定されている場合、画像をリスケールするためのリスケール係数。

offset (`bool`、*任意*、デフォルトは`self.offset`) : 画像を負方向と正方向の両方にスケーリングするかどうか。

do_normalize (`bool`, *任意*, デフォルトは `self.do_normalize`) : 画像を正規化するか否か。

image_mean (`float`または`list[float]`、*任意*、デフォルトは`self.image_mean`) : 画像の平均値。

image_std (`float` または `list[float]`、*任意*、デフォルトは `self.image_std`) : 画像の標準偏差。

return_tensors (`str` または `TensorType`、*任意*) : 返すテンソルの型です。以下のいずれかになります: - 未設定: `np.ndarray` のリストを返します。 - `TensorType.PYTORCH` または `'pt'`: `torch.Tensor` 型のバッチを返します。 - `TensorType.NUMPY` または `'np'`: `np.ndarray` 型のバッチを返します。

data_format (`ChannelDimension` または `str`、*任意*、デフォルトは `ChannelDimension.FIRST`) : 出力画像のチャネル次元の形式です。以下のいずれかになります: - `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - 未設定: 入力画像から推定されたチャネル次元の形式を使用します。

input_data_format (`ChannelDimension` または `str`、*任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

画像または画像のバッチを前処理します。

## VivitVideoProcessor[[transformers.VivitVideoProcessor]]

#### transformers.VivitVideoProcessor[[transformers.VivitVideoProcessor]]

```python
transformers.VivitVideoProcessor(**kwargs: *<class 'transformers.processing_utils.VideosKwargs'>)
```

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

**パラメータ:**

do_convert_rgb (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *任意*, デフォルトは `True`) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*、デフォルト値は`{'shortest_edge' : 256}`): モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *optional*, デフォルトは `False`) : size が int の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*、デフォルト値は`2`) : 画像のリサイズ時に使用するリサンプリングフィルタです。これは列挙型`PILImageResampling`のいずれかになります。`do_resize`が`True`に設定されている場合のみ、効果が現れます。

do_rescale (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*, デフォルトは `0.00784313725490196`) : `do_rescale` が `True` に設定されている場合、画像をリスケールするための係数。

do_normalize (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.5, 0.5, 0.5]`) : 正規化に使用する画像の平均値。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.5, 0.5, 0.5]`) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

do_center_crop (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像を中央クロップするかどうか。

do_pad (`bool`, *kwargs*, *任意*) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*、デフォルト値は `{'height' : 224, 'width': 224}`): `center_crop` を適用した後の出力画像のサイズ。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

do_sample_frames (`bool`, *kwargs*, *optional*, デフォルトは `False`) : 処理前に動画からフレームをサンプリングするか、動画全体を処理するかを指定します。

video_metadata (`Annotated[~video_utils.VideoMetadata | dict | list[dict | ~video_utils.VideoMetadata] | list[list[dict | ~video_utils.VideoMetadata]] | None, None]`, *kwargs*) : 動画のメタデータ。総再生時間、fps、総フレーム数などの情報を含みます。動画からのフレームサンプリングやタイムスタンプの計算に使用されます。動画を処理する前に手動でデコードしようとしている場合を除き、メタデータは渡さないでください。

fps (`Annotated[int | float | None, None]`, *kwargs*) : `do_sample_frames=True` の場合、1 秒あたりにサンプリングするターゲットフレーム数。

num_frames (`Annotated[int | None, None]`, *kwargs*) : `do_sample_frames=True` の場合、サンプリングするフレームの最大数。

return_metadata (`bool`, *kwargs*, *任意*、デフォルトは `False`) : ビデオメタデータを返すかどうかを指定します。ビデオメタデータは、ビデオの長さ、fps、デコードバックエンドなどの情報を含むオブジェクトです。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : 設定されている場合、特定のフレームワークのテンソルを返します。許可される値は以下の通りです。 - `'pt'`: PyTorch の `torch.Tensor` オブジェクトを返します。 - `'np'`: NumPy の `np.ndarray` オブジェクトを返します。

- ****kwargs** ([VideosKwargs](/docs/transformers/main/ja/main_classes/processors#transformers.VideosKwargs)、*optional*) : 各モダリティ（テキスト、画像、動画、音声）の追加処理オプションです。モデル固有のパラメータは上記に記載されています。サポートされている引数の完全なリストについては、TypedDict クラスを参照してください。

VivitVideoProcessorのビデオプロセッサを構築します。

#### preprocess[[transformers.VivitVideoProcessor.preprocess]]

```python
preprocess(videos: typing.Union[list['PIL.Image.Image'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]]], **kwargs: *<class 'transformers.processing_utils.VideosKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/vivit/video_processing_vivit.py#L49)

**パラメータ:**

videos (`Union[list[PIL.Image.Image], numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor], list[list[PIL.Image.Image]], list[list[numpy.ndarray]], list[list[torch.Tensor]], ~video_utils.URL, list[~video_utils.URL], list[list[~video_utils.URL]], ~video_utils.Path, list[~video_utils.Path], list[list[~video_utils.Path]]]`) : 前処理対象の動画。ピクセル値が 0 から 255 の範囲にある、単一の動画またはバッチの動画を想定しています。ピクセル値が 0 から 1 の範囲にある動画を渡す場合は、`do_rescale=False` を設定してください。

do_convert_rgb (`bool`, *kwargs*, *optional*) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *optional*) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *optional*) : size が int の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*) : 画像をリサイズする場合に使用するリサンプリングフィルタ。`PILImageResampling` の列挙型のいずれかです。`do_resize` が `True` に設定されている場合のみ有効です。

do_rescale (`bool`, *kwargs*, *任意*) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*) : `do_rescale` が `True` に設定されている場合、画像をリサイズするためのリスケール係数。

do_normalize (`bool`, *kwargs*, *optional*) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の平均値。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

do_center_crop (`bool`, *kwargs*, *optional*) : 画像を中央クロップするかどうか。

do_pad (`bool`, *kwargs*, *任意*) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : `center_crop` を適用した後の出力画像のサイズ。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

do_sample_frames (`bool`, *kwargs*, *optional*) : 処理前に動画からフレームをサンプリングするか、動画全体を処理するかを指定します。

video_metadata (`Annotated[~video_utils.VideoMetadata | dict | list[dict | ~video_utils.VideoMetadata] | list[list[dict | ~video_utils.VideoMetadata]] | None, None]`, *kwargs*) : 動画のメタデータ。総再生時間、fps、総フレーム数などの情報を含みます。動画からのフレームサンプリングやタイムスタンプの計算に使用されます。動画を処理する前に手動でデコードしようとしている場合を除き、メタデータは渡さないでください。

fps (`Annotated[int | float | None, None]`, *kwargs*) : `do_sample_frames=True` の場合、1 秒あたりにサンプリングするターゲットフレーム数。

num_frames (`Annotated[int | None, None]`, *kwargs*) : `do_sample_frames=True` の場合、サンプリングするフレームの最大数。

return_metadata (`bool`, *kwargs*, *任意*) : ビデオメタデータを返すかどうかを指定します。ビデオメタデータは、ビデオの再生時間、fps、デコードバックエンドなどの情報を含むオブジェクトです。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : `'pt'`に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。

**戻り値:** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- __call__ メソッドによって返されるリスト/配列/テンソルの辞書（'pixel_values' など）。
- **tensor_type** (`Union[None, str, TensorType]`、*省略可*) -- 初期化時に PyTorch/Numpy の Tensor 内の整数リストを変換するために、ここで tensor_type を指定できます。

## VivitModel[[transformers.VivitModel]]

#### transformers.VivitModel[[transformers.VivitModel]]

```python
transformers.VivitModel(config: VivitConfig, add_pooling_layer: bool = True)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/vivit/modeling_vivit.py#L318)

**パラメータ:**

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

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

特定のヘッドを付加せず、生の隠れ状態を出力する素のVivitモデル。

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

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

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/vivit/modeling_vivit.py#L333)

**パラメータ:**

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

interpolate_pos_encoding (`bool`、*任意*、デフォルトは`False`) : 事前学習済みの位置エンコーディングを補間するかどうかを指定します。

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

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

[VivitModel](/docs/transformers/main/ja/model_doc/vivit#transformers.VivitModel)の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
>>> import av
>>> import numpy as np

>>> from transformers import VivitImageProcessor, VivitModel
>>> from huggingface_hub import hf_hub_download

>>> np.random.seed(0)

>>> def read_video_pyav(container, indices):
...     '''
...     Decode the video with PyAV decoder.
...     Args:
...         container (`av.container.input.InputContainer`): PyAV container.
...         indices (`list[int]`): List of frame indices to decode.
...     Returns:
...         result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
...     '''
...     frames = []
...     container.seek(0)
...     start_index = indices[0]
...     end_index = indices[-1]
...     for i, frame in enumerate(container.decode(video=0)):
...         if i > end_index:
...             break
...         if i >= start_index and i in indices:
...             frames.append(frame)
...     return np.stack([x.to_ndarray(format="rgb24") for x in frames])

>>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
...     '''
...     Sample a given number of frame indices from the video.
...     Args:
...         clip_len (`int`): Total number of frames to sample.
...         frame_sample_rate (`int`): Sample every n-th frame.
...         seg_len (`int`): Maximum allowed index of sample's last frame.
...     Returns:
...         indices (`list[int]`): List of sampled frame indices
...     '''
...     converted_len = int(clip_len * frame_sample_rate)
...     end_idx = np.random.randint(converted_len, seg_len)
...     start_idx = end_idx - converted_len
...     indices = np.linspace(start_idx, end_idx, num=clip_len)
...     indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
...     return indices

>>> # video clip consists of 300 frames (10 seconds at 30 FPS)
>>> file_path = hf_hub_download(
...     repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
... )
>>> container = av.open(file_path)

>>> # sample 32 frames
>>> indices = sample_frame_indices(clip_len=32, frame_sample_rate=1, seg_len=container.streams.video[0].frames)
>>> video = read_video_pyav(container=container, indices=indices)

>>> image_processor = VivitImageProcessor.from_pretrained("google/vivit-b-16x2-kinetics400")
>>> model = VivitModel.from_pretrained("google/vivit-b-16x2-kinetics400")

>>> # prepare video for the model
>>> inputs = image_processor(list(video), return_tensors="pt")

>>> # forward pass
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 3137, 768]
```

## VivitForVideoClassification[[transformers.VivitForVideoClassification]]

#### transformers.VivitForVideoClassification[[transformers.VivitForVideoClassification]]

```python
transformers.VivitForVideoClassification(config: VivitConfig)
```

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

**パラメータ:**

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

ViViT Transformerモデルの上部に動画分類ヘッド（[CLS]トークンの最終隠れ状態の上に配置された線形層）を備えた構成。例えばKinetics-400向け。

モデルの forward で `interpolate_pos_encoding` を `True` に設定することで、ViT を学習時に使用した解像度よりも高い解像度の画像でファインチューニングすることが可能です。これにより、事前学習済みの位置埋め込みがより高い解像度に補間されます。

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

```python
forward(pixel_values: typing.Optional[torch.FloatTensor] = None, labels: typing.Optional[torch.LongTensor] = None, interpolate_pos_encoding: bool = False, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/vivit/modeling_vivit.py#L460)

**パラメータ:**

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

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

interpolate_pos_encoding (`bool`、*任意*、デフォルトは`False`) : 事前学習済みの位置エンコーディングを補間するかどうかを指定します。

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

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

[VivitForVideoClassification](/docs/transformers/main/ja/model_doc/vivit#transformers.VivitForVideoClassification)の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
>>> import av
>>> import numpy as np
>>> import torch

>>> from transformers import VivitImageProcessor, VivitForVideoClassification
>>> from huggingface_hub import hf_hub_download

>>> np.random.seed(0)

>>> def read_video_pyav(container, indices):
...     '''
...     Decode the video with PyAV decoder.
...     Args:
...         container (`av.container.input.InputContainer`): PyAV container.
...         indices (`list[int]`): List of frame indices to decode.
...     Returns:
...         result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
...     '''
...     frames = []
...     container.seek(0)
...     start_index = indices[0]
...     end_index = indices[-1]
...     for i, frame in enumerate(container.decode(video=0)):
...         if i > end_index:
...             break
...         if i >= start_index and i in indices:
...             frames.append(frame)
...     return np.stack([x.to_ndarray(format="rgb24") for x in frames])

>>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
...     '''
...     Sample a given number of frame indices from the video.
...     Args:
...         clip_len (`int`): Total number of frames to sample.
...         frame_sample_rate (`int`): Sample every n-th frame.
...         seg_len (`int`): Maximum allowed index of sample's last frame.
...     Returns:
...         indices (`list[int]`): List of sampled frame indices
...     '''
...     converted_len = int(clip_len * frame_sample_rate)
...     end_idx = np.random.randint(converted_len, seg_len)
...     start_idx = end_idx - converted_len
...     indices = np.linspace(start_idx, end_idx, num=clip_len)
...     indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
...     return indices

>>> # video clip consists of 300 frames (10 seconds at 30 FPS)
>>> file_path = hf_hub_download(
...     repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
... )
>>> container = av.open(file_path)

>>> # sample 32 frames
>>> indices = sample_frame_indices(clip_len=32, frame_sample_rate=4, seg_len=container.streams.video[0].frames)
>>> video = read_video_pyav(container=container, indices=indices)

>>> image_processor = VivitImageProcessor.from_pretrained("google/vivit-b-16x2-kinetics400")
>>> model = VivitForVideoClassification.from_pretrained("google/vivit-b-16x2-kinetics400")

>>> inputs = image_processor(list(video), return_tensors="pt")

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

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

