# 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을 포함한 여러 영상 분류 벤치마크에서 최첨단(SOTA) 결과를 달성했으며, 심층 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`의 일부로 네이티브 scaled dot-product attention(SDPA) 연산자가 포함되어 있습니다. 이 함수는 입력과 사용 중인 하드웨어에 따라 적용할 수 있는 여러 구현을 포함합니다. 자세한 내용은 [공식 문서](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html) 또는 [GPU Inference](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")
...
```

최고의 속도 향상을 위해 모델은 반정밀(half-precision, 예: `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 |   cuda |   속도 향상 (%) |   Eager 피크 메모리 (MB) |   sdpa 피크 메모리 (MB) |   메모리 절약 (%) |
|---------------------:|-------------:|----------:|--------------:|----------------------:|---------------------:|-----------------:|
|                  100 |            1 |      True |         7.122 |               2575.28 |              5932.54 |           130.364 |

### 추론

|   num_batches |   batch_size |   cuda |   is half |   속도 향상 (%) |   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`, *선택 사항*, 기본값 32) : 각 비디오의 프레임 수입니다.

tubelet_size (`list[int]`, *선택 사항*, 기본값 `[2, 16, 16]`) : 각 tubelet의 크기(해상도).

num_channels (`int`, *선택 사항*, 기본값 `3`) : 입력 채널의 수입니다.

hidden_size (`int`, *선택 사항*, 기본값 `768`) : 숨겨진 표현의 차원.

num_hidden_layers (`int`, *선택 사항*, 기본값 `12`) : Transformer decoder의 숨겨진 레이어 수입니다.

num_attention_heads (`int`, *선택 사항*, 기본값 `12`) : Transformer decoder의 각 attention layer에 사용되는 attention head의 수입니다.

intermediate_size (`int`, *선택 사항*, 기본값 `3072`) : MLP 표현의 차원.

hidden_act (`str`, *선택 사항*, 기본값 `gelu_fast`) : 디코더의 비선형 활성화 함수(함수 또는 문자열). 예를 들어, `"gelu"`, `"relu"`, `"silu"` 등.

hidden_dropout_prob (`Union[float, int]`, *선택 사항*, 기본값 `0.0`) : 임베딩, 인코더, 풀러의 모든 완전 연결 계층에 적용되는 dropout 확률입니다.

attention_probs_dropout_prob (`Union[float, int]`, *선택 사항*, 기본값 `0.0`) : attention 확률에 적용할 dropout 비율입니다.

initializer_range (`float`, *선택 사항*, 기본값 `0.02`) : 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다.

layer_norm_eps (`float`, *선택 사항*, 기본값 `1e-06`) : 레이어 정규화 레이어에서 사용되는 epsilon 값입니다.

qkv_bias (`bool`, *선택 사항*, 기본값 `True`) : 쿼리, 키, 값에 bias를 추가할지 여부.

pooler_output_size (`int`, *선택 사항*) : 풀러 레이어의 차원입니다. None인 경우 기본값은 `hidden_size`입니다.

pooler_act (`str`, *선택 사항*, 기본값 `"tanh"`) : pooler에서 사용할 활성화 함수입니다.

이것은 VivitModel의 구성을 저장하기 위한 구성 클래스입니다. 지정된 인자에 따라 Vivit 모델을 초기화하고 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 구성을 초기화하면 [google/vivit-b-16x2-kinetics400](https://huggingface.co/google/vivit-b-16x2-kinetics400)과 유사한 구성이 생성됩니다.

Configuration 객체는 [PreTrainedConfig](/docs/transformers/main/ko/main_classes/configuration#transformers.PreTrainedConfig)를 상속하며, 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 [PreTrainedConfig](/docs/transformers/main/ko/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`) : 이미지의 (height, width) 차원을 지정된 `size`로 조정할지 여부. `preprocess` 메서드의 `do_resize` 파라미터로 재정의할 수 있습니다.

size (`dict[str, int]` *선택 사항*, 기본값은 `{"shortest_edge" : 256}`): 리사이즈 후 출력 이미지의 크기입니다. 원본 이미지의 종횡비를 유지하면서 이미지의 가장 짧은 변을 `size["shortest_edge"]`로 리사이즈합니다. `preprocess` 메서드의 `size`로 재정의할 수 있습니다.

resample (`PILImageResampling`, *선택 사항*, 기본값 `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`, *선택*, 기본값 `self.resample`) : 이미지를 리사이즈할 때 사용할 리샘플링 필터입니다. 이는 `PILImageResampling` enum 중 하나일 수 있으며, `do_resize`가 `True`로 설정된 경우에만 효과가 있습니다.

do_center_crop (`bool`, *선택 사항*, 기본값 `self.do_centre_crop`) : 이미지를 중앙으로 크롭할지 여부.

crop_size (`dict[str, int]`, *선택 사항*, 기본값 `self.crop_size`) : 중앙 크롭을 적용한 후의 이미지 크기.

do_rescale (`bool`, *선택 사항*, 기본값 `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` 유형의 배치(batch)를 반환합니다. - `TensorType.NUMPY` 또는 `'np'`: `np.ndarray` 유형의 배치(batch)를 반환합니다.

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) 형식의 이미지.

이미지 또는 이미지 배치(batch)를 전처리합니다.

## 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*, *선택 사항*, 기본값 `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*, *선택 사항*, 기본값 `False`) : size가 int인 경우 리사이즈 시 정사각형 이미지로 설정할지 여부.

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*, 기본값 `2`) : 이미지를 리사이즈할 때 사용할 리샘플링 필터입니다. 이는 `PILImageResampling` enum 중 하나일 수 있습니다. `do_resize`가 `True`로 설정된 경우에만 효과가 있습니다.

do_rescale (`bool`, *kwargs*, *선택 사항*, 기본값 `True`) : 이미지를 다시 스케일링할지 여부.

rescale_factor (`float`, *kwargs*, *선택 사항*, 기본값은 `0.00784313725490196`) : `do_rescale`이 `True`로 설정된 경우 이미지를 재조정하기 위한 재조정 계수입니다.

do_normalize (`bool`, *kwargs*, *선택 사항*, 기본값 `True`) : 이미지를 정규화할지 여부.

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *선택*, 기본값은 `[0.5, 0.5, 0.5]`) : 정규화에 사용할 이미지 평균입니다. `do_normalize`가 `True`로 설정된 경우에만 효과가 있습니다.

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *선택*, 기본값 `[0.5, 0.5, 0.5]`) : 정규화에 사용할 이미지 표준 편차. `do_normalize`가 `True`로 설정된 경우에만 효과가 있습니다.

do_center_crop (`bool`, *kwargs*, *선택 사항*, 기본값 `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*, *선택*) : `ChannelDimension.FIRST`만 지원됩니다. 느린 프로세서와의 호환성을 위해 추가되었습니다.

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*, *선택 사항*, 기본값 `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`일 때 초당 샘플링할 대상 프레임 수.

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/ko/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 범위로 이루어진 단일 비디오 또는 비디오 배치(batch)를 입력으로 기대합니다. 픽셀 값이 0에서 1 범위로 이루어진 비디오를 전달하는 경우, `do_rescale=False`로 설정하십시오.

do_convert_rgb (`bool`, *kwargs*, *선택*) : 이미지를 RGB로 변환할지 여부.

do_resize (`bool`, *kwargs*, *선택*) : 이미지를 리사이즈할지 여부.

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 모델의 최대 입력 차원을 설명합니다.

default_to_square (`bool`, *kwargs*, *선택*) : size가 int인 경우 리사이즈 시 정사각형 이미지로 기본 설정할지 여부.

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*) : 이미지를 리사이즈할 때 사용할 리샘플링 필터입니다. `PILImageResampling` enum 중 하나를 사용할 수 있습니다. `do_resize`가 `True`로 설정된 경우에만 효과가 있습니다.

do_rescale (`bool`, *kwargs*, *선택*) : 이미지를 다시 스케일링할지 여부.

rescale_factor (`float`, *kwargs*, *선택*) : `do_rescale`가 `True`로 설정된 경우 이미지를 재조정하는 데 사용되는 재조정 계수입니다.

do_normalize (`bool`, *kwargs*, *선택*) : 이미지를 정규화할지 여부.

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *선택*) : 정규화에 사용할 이미지 평균값. `do_normalize`이 `True`로 설정된 경우에만 효과가 있습니다.

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *선택*) : 정규화에 사용할 이미지 표준 편차. `do_normalize`가 `True`로 설정된 경우에만 효과가 있습니다.

do_center_crop (`bool`, *kwargs*, *선택*) : 이미지를 중앙 크롭할지 여부.

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*, *선택*) : `ChannelDimension.FIRST`만 지원됩니다. 느린 프로세서와의 호환성을 위해 추가되었습니다.

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*, *선택*) : 처리 전에 비디오에서 프레임을 샘플링할지, 아니면 비디오 전체를 처리할지 여부.

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`일 때 초당 샘플링할 대상 프레임 수.

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_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/ko/model_doc/vivit#transformers.VivitConfig)) : 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 [from_pretrained()](/docs/transformers/main/ko/main_classes/model#transformers.PreTrainedModel.from_pretrained) 메서드를 확인하세요.

add_pooling_layer (`bool`, *선택 사항*, 기본값 `True`) : 풀링 레이어를 추가할지 여부

특정 헤드가 위에 없는 상태에서 원시 hidden-states를 출력하는 기본 Vivit Model입니다.

이 모델은 [PreTrainedModel](/docs/transformers/main/ko/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.Tensor] = 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.Tensor`, shape `(batch_size, num_channels, image_size, image_size)`, *선택 사항*) : 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 [VivitImageProcessor](/docs/transformers/main/ko/model_doc/vivit#transformers.VivitImageProcessor)를 사용하여 얻을 수 있습니다. 자세한 내용은 [VivitImageProcessor.__call__()](/docs/transformers/main/ko/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)를 참조하세요 (`processor_class`는 이미지 처리에 [VivitImageProcessor](/docs/transformers/main/ko/model_doc/vivit#transformers.VivitImageProcessor)를 사용합니다).

interpolate_pos_encoding (`bool`, *선택 사항*, 기본값 `False`) : 사전 학습된 위치 인코딩을 보간할지 여부.

attention_mask (`torch.Tensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크입니다. `[0, 1]`에서 선택된 마스크 값: - **마스크되지 않은** 토큰은 1, - **마스크된** 토큰은 0. [attention 마스크란?](../glossary#attention-mask)

**반환값:** [BaseModelOutputWithPooling](/docs/transformers/main/ko/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 또는 `tuple(torch.Tensor)`

구성([VivitConfig](/docs/transformers/main/ko/model_doc/vivit#transformers.VivitConfig))과 입력에 따라 다양한 요소를 포함하는 [BaseModelOutputWithPooling](/docs/transformers/main/ko/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 또는 `torch.Tensor`의 튜플(`return_dict=False`가 전달되거나 `config.return_dict=False`인 경우).

[VivitModel](/docs/transformers/main/ko/model_doc/vivit#transformers.VivitModel)의 forward 메서드는 `__call__` 특수 메서드를 오버라이드합니다.

`Module` 인스턴스는 전처리 및 후처리 단계를 실행하는 것을 처리하지만, 이 함수는 해당 단계를 조용히 무시하므로, 순전파(forward pass) 레시피를 이 함수 내에서 정의해야 하더라도 이후에는 이 함수 대신 `Module` 인스턴스를 호출해야 합니다.

- **last_hidden_state** (`torch.Tensor`, shape `(batch_size, sequence_length, hidden_size)`) -- 모델의 마지막 레이어 출력에서 생성된 hidden-state 시퀀스입니다.
- **pooler_output** (`torch.Tensor`, shape `(batch_size, hidden_size)`) -- 시퀀스의 첫 번째 토큰(분류 토큰)의 마지막 레이어 hidden-state입니다. 보조 사전학습 작업을 위해 사용되는 레이어들을 통해 추가 처리된 값입니다. 예를 들어 BERT 계열 모델의 경우, 선형 레이어와 tanh 활성화 함수를 통해 처리된 분류 토큰을 반환합니다. 선형 레이어의 가중치는 사전학습 단계에서 다음 문장 예측(분류) 목적 함수를 통해 학습됩니다.
- **hidden_states** (`tuple(torch.Tensor)`, *선택 사항*, `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)`, *선택 사항*, `output_attentions=True`가 전달되었거나 `config.output_attentions=True`인 경우 반환됨) -- 각 레이어마다 하나씩 포함된 `torch.Tensor`의 튜플로, 모양은 `(batch_size, num_heads, sequence_length, sequence_length)`입니다.

  self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치입니다.

예:

```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/ko/model_doc/vivit#transformers.VivitConfig)) : 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 [from_pretrained()](/docs/transformers/main/ko/main_classes/model#transformers.PreTrainedModel.from_pretrained) 메서드를 확인하세요.

ViViT Transformer 모델의 상단에 비디오 분류 헤드가 있는 경우(예: Kinetics-400). 이는 [CLS] 토큰의 최종 숨겨진 상태 위에 선형 레이어를 배치한 것입니다.

모델의 forward에서 `interpolate_pos_encoding`을 `True`로 설정하면, 학습에 사용된 해상도보다 높은 해상도의 이미지로 ViT를 fine-tune할 수 있습니다. 이렇게 하면 사전 학습된 position embeddings이 더 높은 해상도에 맞게 보간됩니다.

이 모델은 [PreTrainedModel](/docs/transformers/main/ko/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.Tensor] = 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.Tensor`, shape `(batch_size, num_channels, image_size, image_size)`, *선택 사항*) : 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 [VivitImageProcessor](/docs/transformers/main/ko/model_doc/vivit#transformers.VivitImageProcessor)를 사용하여 얻을 수 있습니다. 자세한 내용은 [VivitImageProcessor.__call__()](/docs/transformers/main/ko/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)를 참조하세요 (`processor_class`는 이미지 처리에 [VivitImageProcessor](/docs/transformers/main/ko/model_doc/vivit#transformers.VivitImageProcessor)를 사용합니다).

labels (`torch.LongTensor`, shape `(batch_size,)`, *선택 사항*) : 이미지 분류/회귀 손실을 계산하는 데 사용되는 라벨. 인덱스는 `[0, ..., config.num_labels - 1]` 범위에 있어야 합니다. `config.num_labels == 1`인 경우 회귀 손실(평균 제곱 손실)이 계산되고, `config.num_labels > 1`인 경우 분류 손실(크로스 엔트로피)이 계산됩니다.

interpolate_pos_encoding (`bool`, *선택 사항*, 기본값 `False`) : 사전 학습된 위치 인코딩을 보간할지 여부.

**반환값:** [ImageClassifierOutput](/docs/transformers/main/ko/main_classes/output#transformers.modeling_outputs.ImageClassifierOutput) 또는 `tuple(torch.Tensor)`

구성([VivitConfig](/docs/transformers/main/ko/model_doc/vivit#transformers.VivitConfig))과 입력에 따라 다양한 요소를 포함하는 [ImageClassifierOutput](/docs/transformers/main/ko/main_classes/output#transformers.modeling_outputs.ImageClassifierOutput) 또는 `torch.Tensor`의 튜플(`return_dict=False`가 전달되거나 `config.return_dict=False`인 경우).

[VivitForVideoClassification](/docs/transformers/main/ko/model_doc/vivit#transformers.VivitForVideoClassification)의 forward 메서드는 `__call__` 특수 메서드를 오버라이드합니다.

`Module` 인스턴스는 전처리 및 후처리 단계를 실행하는 것을 처리하지만, 이 함수는 해당 단계를 조용히 무시하므로, 순전파(forward pass) 레시피를 이 함수 내에서 정의해야 하더라도 이후에는 이 함수 대신 `Module` 인스턴스를 호출해야 합니다.

- **loss** (`torch.Tensor`, shape `(1,)`, *선택*, `labels`이 제공될 때 반환됨) -- 분류(또는 config.num_labels==1인 경우 회귀) 손실.
- **logits** (`torch.Tensor`, shape `(batch_size, config.num_labels)`) -- SoftMax 적용 전 분류(또는 config.num_labels==1인 경우 회귀) 점수.
- **hidden_states** (`tuple(torch.Tensor)`, *선택*, `output_hidden_states=True`가 전달되거나 `config.output_hidden_states=True`인 경우 반환) -- `torch.Tensor`의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력용 1개 + 각 단계 출력용 1개)로, shape이 `(batch_size, sequence_length, hidden_size)`입니다. 각 단계 출력 시점의 모델 hidden-states(또는 feature maps)입니다.
- **attentions** (`tuple(torch.Tensor)`, *선택 사항*, `output_attentions=True`가 전달되었거나 `config.output_attentions=True`인 경우 반환) -- 각 레이어당 하나씩, shape가 `(batch_size, num_heads, patch_size, sequence_length)`인 `torch.Tensor`의 튜플.

  self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치입니다.

예:

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

