# X-CLIP

## 개요

X-CLIP 모델은 Bolin Ni, Houwen Peng, Minghao Chen, Songyang Zhang, Gaofeng Meng, Jianlong Fu, Shiming Xiang, Haibin Ling이 [Expanding Language-Image Pretrained Models for General Video Recognition](https://huggingface.co/papers/2208.02816)에서 제안했습니다. X-CLIP은 비디오를 위한 [CLIP](clip)의 최소 확장입니다. 이 모델은 텍스트 인코더, 크로스 프레임 비전 인코더, 멀티 프레임 통합 Transformer, 비디오 전용 프롬프트 생성기로 구성됩니다.

해당 논문의 초록은 다음과 같습니다:

*대조적 언어-이미지 사전학습은 웹 규모 데이터에서 시각-텍스트 결합 표현을 학습하는 데 큰 성공을 거두며, 다양한 이미지 작업에서 뛰어난 "제로샷" 일반화 능력을 입증했습니다. 그러나 이러한 새로운 언어-이미지 사전학습 방법을 비디오 도메인에 효과적으로 확장하는 방법은 여전히 미해결 과제로 남아 있습니다. 본 연구에서는 새 모델을 처음부터 사전학습하는 대신, 사전학습된 언어-이미지 모델을 비디오 인식에 직접 적용하는 단순하면서도 효과적인 접근법을 제시합니다. 보다 구체적으로, 시간 차원 프레임의 장거리 의존성을 포착하기 위해 프레임 간 정보를 명시적으로 교환하는 크로스 프레임 어텐션 메커니즘을 제안합니다. 해당 모듈은 경량이며 사전학습된 언어-이미지 모델에 매끄럽게 통합할 수 있습니다. 또한, 비디오 콘텐츠 정보를 활용하여 차별적인 텍스트 프롬프트를 생성하는 비디오 전용 프롬프팅 스킴을 제안합니다. 광범위한 실험을 통해 본 접근법의 효과성과 다양한 비디오 인식 시나리오로의 일반화 가능성을 입증했습니다. 특히, 완전 지도 학습 설정에서 본 접근법은 Kinectics-400에서 87.1%의 top-1 정확도를 달성했으며, Swin-L 및 ViViT-H와 비교할 때 FLOPs를 12분의 1로 줄였습니다. 제로샷 실험에서 본 접근법은 두 가지 인기 있는 프로토콜 기준 top-1 정확도에서 각각 +7.6% 및 +14.9%로 현재 최첨단(SOTA) 방법들을 능가했습니다. 소수샷 시나리오에서, 레이블이 붙은 데이터가 극도로 제한적인 경우 본 접근법은 이전 최고 방법들보다 각각 +32.1% 및 +23.1% 높은 성능을 보였습니다.*

팁:

- X-CLIP의 사용법은 [CLIP](clip)와 동일합니다.

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

 X-CLIP 아키텍처. 원 논문에서 가져왔습니다.

이 모델은 [nielsr](https://huggingface.co/nielsr)에 의해 기여되었습니다. 원본 코드는 [여기](https://github.com/microsoft/VideoX/tree/master/X-CLIP)에서 찾을 수 있습니다.

## 리소스

X-CLIP을 시작하는 데 도움이 되는 공식 Hugging Face 및 커뮤니티(🌎로 표시) 리소스 목록입니다.

- X-CLIP 데모 노트북은 [여기](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/X-CLIP)에서 찾을 수 있습니다.

여기에 포함할 리소스를 제출하고 싶으시면 Pull Request를 열어 주시면 검토하겠습니다! 기존 리소스와 중복되지 않고 새로운 것을 보여주는 것이 이상적입니다.

## XCLIPProcessor[[transformers.XCLIPProcessor]]

#### transformers.XCLIPProcessor[[transformers.XCLIPProcessor]]

```python
transformers.XCLIPProcessor(image_processor = None, tokenizer = None, **kwargs)
```

[소스](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/x_clip/processing_x_clip.py#L23)

**매개변수:**

image_processor (`image_processor_class`) : 이미지 프로세서가 필수 입력입니다.

tokenizer (`tokenizer_class`) : 토크나이저는 필수 입력값입니다.

XCLIPProcessor를 생성하여 이미지 프로세서와 토크나이저를 단일 프로세서로 래핑합니다.

[XCLIPProcessor](/docs/transformers/v5.24.0/ko/model_doc/xclip#transformers.XCLIPProcessor)는 `image_processor_class`과 `tokenizer_class`의 모든 기능을 제공합니다. 자세한 내용은 `~image_processor_class`와 `~tokenizer_class`를 참고하세요.

#### __call__[[transformers.XCLIPProcessor.__call__]]

```python
__call__(images = None, text = None, videos = None, **kwargs)
```

[소스](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/x_clip/processing_x_clip.py#L28)

## XCLIPConfig[[transformers.XCLIPConfig]]

#### transformers.XCLIPConfig[[transformers.XCLIPConfig]]

```python
transformers.XCLIPConfig(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, text_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, vision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, projection_dim: int = 512, prompt_layers: int = 2, prompt_alpha: float = 0.1, prompt_hidden_act: str = 'quick_gelu', prompt_num_attention_heads: int = 8, prompt_attention_dropout: float | int = 0.0, prompt_projection_dropout: float | int = 0.0, logit_scale_init_value: float = 2.6592, initializer_factor: float = 1.0)
```

[소스](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/x_clip/configuration_x_clip.py#L119)

**매개변수:**

text_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`, *선택*) : 텍스트 백본의 config 객체 또는 사전입니다.

vision_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`, *선택*) : 비전 백본의 config 객체 또는 사전 정의된 config 딕셔너리입니다.

projection_dim (`int`, *선택 사항*, 기본값 `512`) : 텍스트 및 비전 투영 레이어의 차원.

prompt_layers (`int`, *선택 사항*, 기본값 2) : 비디오 전용 프롬프트 생성기의 레이어 수.

prompt_alpha (`float`, *선택 사항*, 기본값 0.1) : 비디오 전용 프롬프트 생성기에 사용할 Alpha 값입니다.

prompt_hidden_act (`str` 또는 `function`, *선택 사항*, 기본값은 `"quick_gelu"`) : 비디오 전용 프롬프트 생성기에서 사용되는 비선형 활성화 함수(함수 또는 문자열). 문자열인 경우 `"gelu"`, `"relu"`, `"selu"`, `"gelu_new"`, `"quick_gelu"`가 지원됩니다.

prompt_num_attention_heads (`int`, *선택 사항*, 기본값 8) : 비디오 전용 프롬프트 생성기의 크로스 어텐션에서 사용할 어텐션 헤드 수입니다.

prompt_attention_dropout (`float`, *선택 사항*, 기본값 0.0) : 비디오 전용 프롬프트 생성기의 어텐션 레이어에 적용되는 드롭아웃 확률입니다.

prompt_projection_dropout (`float`, *선택 사항*, 기본값 0.0) : 비디오 전용 프롬프트 생성기의 투영 레이어에 적용되는 dropout 확률입니다.

logit_scale_init_value (`float`, *선택 사항*, 기본값 `2.6592`) : *logit_scale* 매개변수의 초기 값입니다.

initializer_factor (`float`, *선택 사항*, 기본값 `1.0`) : 모든 가중치 행렬을 초기화하는 계수입니다(1로 유지해야 하며, 초기화 테스트를 위해 내부적으로 사용됨).

이것은 X ClipModel의 구성을 저장하기 위한 구성 클래스입니다. 지정된 인자에 따라 X Clip 모델을 인스턴스화하여 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 구성을 인스턴스화하면 [microsoft/xclip-base-patch32](https://huggingface.co/microsoft/xclip-base-patch32)와 유사한 구성이 생성됩니다.

Configuration 객체는 [PreTrainedConfig](/docs/transformers/v5.24.0/ko/main_classes/configuration#transformers.PreTrainedConfig)를 상속하며, 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 [PreTrainedConfig](/docs/transformers/v5.24.0/ko/main_classes/configuration#transformers.PreTrainedConfig)의 문서를 참고하세요.

## XCLIPTextConfig[[transformers.XCLIPTextConfig]]

#### transformers.XCLIPTextConfig[[transformers.XCLIPTextConfig]]

```python
transformers.XCLIPTextConfig(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, vocab_size: int = 49408, hidden_size: int = 512, intermediate_size: int = 2048, num_hidden_layers: int = 12, num_attention_heads: int = 8, max_position_embeddings: int = 77, hidden_act: str = 'quick_gelu', layer_norm_eps: float = 1e-05, attention_dropout: float | int = 0.0, initializer_range: float = 0.02, initializer_factor: float = 1.0, pad_token_id: int | None = 1, bos_token_id: int | None = 0, eos_token_id: int | list[int] | None = 2)
```

[소스](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/x_clip/configuration_x_clip.py#L27)

**매개변수:**

vocab_size (`int`, *선택 사항*, 기본값 `49408`) : 모델의 어휘 크기입니다. `input_ids`로 표현할 수 있는 서로 다른 토큰의 수를 정의합니다.

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

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

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

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

max_position_embeddings (`int`, *선택 사항*, 기본값 `77`) : 이 모델이 사용될 수 있는 최대 시퀀스 길이입니다.

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

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

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

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

initializer_factor (`float`, *선택 사항*, 기본값 `1.0`) : 모든 가중치 행렬을 초기화하는 계수입니다(1로 유지해야 하며, 초기화 테스트를 위해 내부적으로 사용됨).

pad_token_id (`int`, *선택 사항*, 기본값 `1`) : 어휘에서 패딩에 사용되는 토큰 ID입니다.

bos_token_id (`int`, *선택 사항*, 기본값 `0`) : 어휘에서 스트림 시작에 사용되는 토큰 ID입니다.

eos_token_id (`Union[int, list[int]]`, *선택*, 기본값 `2`) : 어휘에서 스트림 종료에 사용되는 토큰 ID입니다.

이것은 X ClipModel의 구성을 저장하기 위한 구성 클래스입니다. 지정된 인자에 따라 X Clip 모델을 인스턴스화하여 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 구성을 인스턴스화하면 [microsoft/xclip-base-patch32](https://huggingface.co/microsoft/xclip-base-patch32)와 유사한 구성이 생성됩니다.

Configuration 객체는 [PreTrainedConfig](/docs/transformers/v5.24.0/ko/main_classes/configuration#transformers.PreTrainedConfig)를 상속하며, 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 [PreTrainedConfig](/docs/transformers/v5.24.0/ko/main_classes/configuration#transformers.PreTrainedConfig)의 문서를 참고하세요.

예:

```python
>>> from transformers import XCLIPTextModel, XCLIPTextConfig

>>> # Initializing a XCLIPTextModel with microsoft/xclip-base-patch32 style configuration
>>> configuration = XCLIPTextConfig()

>>> # Initializing a XCLIPTextConfig from the microsoft/xclip-base-patch32 style configuration
>>> model = XCLIPTextModel(configuration)

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

## XCLIPVisionConfig[[transformers.XCLIPVisionConfig]]

#### transformers.XCLIPVisionConfig[[transformers.XCLIPVisionConfig]]

```python
transformers.XCLIPVisionConfig(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, intermediate_size: int = 3072, num_hidden_layers: int = 12, num_attention_heads: int = 12, mit_hidden_size: int = 512, mit_intermediate_size: int = 2048, mit_num_hidden_layers: int = 1, mit_num_attention_heads: int = 8, num_channels: int = 3, image_size: int | list[int] | tuple[int, int] = 224, patch_size: int | list[int] | tuple[int, int] = 32, num_frames: int = 8, hidden_act: str = 'quick_gelu', layer_norm_eps: float = 1e-05, attention_dropout: float | int = 0.0, initializer_range: float = 0.02, initializer_factor: float = 1.0, drop_path_rate: float | int = 0.0)
```

[소스](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/x_clip/configuration_x_clip.py#L65)

**매개변수:**

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

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

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

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

mit_hidden_size (`int`, *선택 사항*, 기본값 512) : Multiframe Integration Transformer(MIT) 인코더 레이어의 차원입니다.

mit_intermediate_size (`int`, *선택 사항*, 기본값 2048) : Multiframe Integration Transformer(MIT)의 "중간"(즉, feed-forward) 레이어의 차원.

mit_num_hidden_layers (`int`, *선택 사항*, 기본값 1) : Multiframe Integration Transformer(MIT)의 숨겨진 레이어 수입니다.

mit_num_attention_heads (`int`, *선택 사항*, 기본값 8) : Multiframe Integration Transformer(MIT)의 각 attention layer에 사용할 attention head의 수입니다.

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

image_size (`Union[int, list[int], tuple[int, int]]`, *선택*, 기본값 `224`) : 각 이미지의 크기(해상도).

patch_size (`Union[int, list[int], tuple[int, int]]`, *선택*, 기본값 `32`) : 각 패치의 크기(해상도).

num_frames (`int`, *선택 사항*, 기본값 8) : 각 비디오의 프레임 수입니다.

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

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

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

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

initializer_factor (`float`, *선택 사항*, 기본값 `1.0`) : 모든 가중치 행렬을 초기화하는 계수입니다(1로 유지해야 하며, 초기화 테스트를 위해 내부적으로 사용됨).

drop_path_rate (`Union[float, int]`, *선택 사항*, 기본값 `0.0`) : 패치 퓨전용 드롭 패스 비율입니다.

이것은 X ClipModel의 구성을 저장하기 위한 구성 클래스입니다. 지정된 인자에 따라 X Clip 모델을 인스턴스화하여 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 구성을 인스턴스화하면 [microsoft/xclip-base-patch32](https://huggingface.co/microsoft/xclip-base-patch32)와 유사한 구성이 생성됩니다.

Configuration 객체는 [PreTrainedConfig](/docs/transformers/v5.24.0/ko/main_classes/configuration#transformers.PreTrainedConfig)를 상속하며, 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 [PreTrainedConfig](/docs/transformers/v5.24.0/ko/main_classes/configuration#transformers.PreTrainedConfig)의 문서를 참고하세요.

예:

```python
>>> from transformers import XCLIPVisionModel, XCLIPVisionConfig

>>> # Initializing a XCLIPVisionModel with microsoft/xclip-base-patch32 style configuration
>>> configuration = XCLIPVisionConfig()

>>> # Initializing a XCLIPVisionModel model from the microsoft/xclip-base-patch32 style configuration
>>> model = XCLIPVisionModel(configuration)

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

## XCLIPModel[[transformers.XCLIPModel]]

#### transformers.XCLIPModel[[transformers.XCLIPModel]]

```python
transformers.XCLIPModel(config: XCLIPConfig)
```

[소스](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/x_clip/modeling_x_clip.py#L913)

**매개변수:**

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

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

이 모델은 [PreTrainedModel](/docs/transformers/v5.24.0/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.XCLIPModel.forward]]

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

[소스](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/x_clip/modeling_x_clip.py#L980)

**매개변수:**

input_ids (`torch.LongTensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : 어휘(input sequence tokens)의 인덱스입니다. 기본적으로 패딩은 무시됩니다. [AutoTokenizer](/docs/transformers/v5.24.0/ko/model_doc/auto#transformers.AutoTokenizer)를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 [PreTrainedTokenizer.encode()](/docs/transformers/v5.24.0/ko/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 및 [PreTrainedTokenizer.__call__()](/docs/transformers/v5.24.0/ko/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)를 참조하세요. [입력 ID란 무엇인가요?](../glossary#input-ids)

pixel_values (`torch.Tensor`, shape `(batch_size, num_channels, image_size, image_size)`, *선택 사항*) : 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 `image_processor_class`를 사용하여 얻을 수 있습니다. 자세한 내용은 `image_processor_class.__call__`를 참조하세요 (`processor_class`는 이미지 처리에 `image_processor_class`를 사용합니다).

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

position_ids (`torch.LongTensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : 각 입력 시퀀스의 토큰 위치 인덱스입니다. `[0, config.n_positions - 1]` 범위에서 선택됩니다. [위치 ID란 무엇인가요?](../glossary#position-ids)

return_loss (`bool`, *선택 사항*) : 대조적 손실을 반환할지 여부.

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

**반환값:** `XCLIPOutput` 또는 `tuple(torch.Tensor)`

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

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

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

- **loss** (`torch.Tensor`, shape `(1,)`, *선택 사항*, `return_loss`가 `True`일 때 반환됨) -- 비디오-텍스트 유사도를 위한 Contrastive loss.
- **logits_per_text** (`torch.Tensor`, shape `(text_batch_size, video_batch_size)`) -- `text_embeds`와 `video_embeds` 사이의 스케일된 도트 프로덕트 점수입니다. 이는 텍스트-비디오 유사도 점수를 나타냅니다.
- **text_embeds** (`torch.Tensor`, shape `(batch_size, output_dim`) -- [XCLIPTextModel](/docs/transformers/v5.24.0/ko/model_doc/xclip#transformers.XCLIPTextModel)의 풀링된 출력에 투영 계층을 적용하여 얻은 텍스트 임베딩입니다.
- **text_model_output** (`~modeling_outputs.BaseModelOutputWithPooling`, *선택 사항*) -- [XCLIPTextModel](/docs/transformers/v5.24.0/ko/model_doc/xclip#transformers.XCLIPTextModel)의 출력입니다.
- **vision_model_output** (`~modeling_outputs.BaseModelOutputWithPooling`, *선택 사항*) -- [XCLIPVisionModel](/docs/transformers/v5.24.0/ko/model_doc/xclip#transformers.XCLIPVisionModel)의 출력입니다.
- **logits_per_video** (`torch.Tensor`, shape `(video_batch_size, text_batch_size)`) -- `video_embeds`와 `text_embeds` 사이의 스케일된 도트 프로덕트 점수입니다. 이는 비디오-텍스트 유사도 점수를 나타냅니다.
- **video_embeds** (`torch.Tensor`, shape `(batch_size, output_dim`) -- [XCLIPVisionModel](/docs/transformers/v5.24.0/ko/model_doc/xclip#transformers.XCLIPVisionModel)의 풀링된 출력에 투영 계층을 적용하여 얻은 비디오 임베딩입니다.
- **mit_output** (`~modeling_outputs.BaseModelOutputWithPooling`, *선택 사항*) -- `XCLIPMultiframeIntegrationTransformer`(MIT)의 출력입니다.

예:

```python
>>> import av
>>> import torch
>>> import numpy as np

>>> from transformers import AutoProcessor, AutoModel
>>> 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 8 frames
>>> indices = sample_frame_indices(clip_len=8, frame_sample_rate=1, seg_len=container.streams.video[0].frames)
>>> video = read_video_pyav(container, indices)

>>> processor = AutoProcessor.from_pretrained("microsoft/xclip-base-patch32")
>>> model = AutoModel.from_pretrained("microsoft/xclip-base-patch32")

>>> inputs = processor(
...     text=["playing sports", "eating spaghetti", "go shopping"],
...     videos=list(video),
...     return_tensors="pt",
...     padding=True,
... )

>>> # forward pass
>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> logits_per_video = outputs.logits_per_video  # this is the video-text similarity score
>>> probs = logits_per_video.softmax(dim=1)  # we can take the softmax to get the label probabilities
>>> print(probs)
tensor([[1.9496e-04, 9.9960e-01, 2.0825e-04]])
```

#### get_text_features[[transformers.XCLIPModel.get_text_features]]

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

[소스](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/x_clip/modeling_x_clip.py#L945)

**매개변수:**

input_ids (`torch.Tensor`, shape `(batch_size, sequence_length)`) : 어휘 사전에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다. [AutoTokenizer](/docs/transformers/v5.24.0/ko/model_doc/auto#transformers.AutoTokenizer)를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 [PreTrainedTokenizer.encode()](/docs/transformers/v5.24.0/ko/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 및 [PreTrainedTokenizer.__call__()](/docs/transformers/v5.24.0/ko/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)를 참조하세요. [입력 ID란 무엇인가요?](../glossary#input-ids)

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

position_ids (`torch.Tensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : 각 입력 시퀀스의 토큰 위치 인덱스입니다. `[0, config.n_positions - 1]` 범위에서 선택됩니다.  [위치 ID란 무엇인가요?](../glossary#position-ids)

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

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

- **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 torch
>>> from transformers import AutoTokenizer, AutoModel

>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/xclip-base-patch32")
>>> model = AutoModel.from_pretrained("microsoft/xclip-base-patch32")

>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
>>> with torch.inference_mode():
...     text_features = model.get_text_features(**inputs)
```

#### get_video_features[[transformers.XCLIPModel.get_video_features]]

```python
get_video_features(pixel_values: Tensor, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/x_clip/modeling_x_clip.py#L1140)

**매개변수:**

pixel_values (`torch.Tensor`, shape `(batch_size, num_channels, image_size, image_size)`) : 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 `image_processor_class`를 사용하여 얻을 수 있습니다. 자세한 내용은 `image_processor_class.__call__`를 참조하세요 (`processor_class`는 이미지 처리에 `image_processor_class`를 사용합니다).

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

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

- **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 torch
>>> import numpy as np

>>> from transformers import AutoProcessor, AutoModel
>>> 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 8 frames
>>> indices = sample_frame_indices(clip_len=8, frame_sample_rate=1, seg_len=container.streams.video[0].frames)
>>> video = read_video_pyav(container, indices)

>>> processor = AutoProcessor.from_pretrained("microsoft/xclip-base-patch32")
>>> model = AutoModel.from_pretrained("microsoft/xclip-base-patch32")

>>> inputs = processor(videos=list(video), return_tensors="pt")

>>> video_features = model.get_video_features(**inputs)
```

## XCLIPTextModel[[transformers.XCLIPTextModel]]

#### transformers.XCLIPTextModel[[transformers.XCLIPTextModel]]

```python
transformers.XCLIPTextModel(config: XCLIPTextConfig)
```

[소스](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/x_clip/modeling_x_clip.py#L548)

**매개변수:**

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

XCLIP의 텍스트 모델로, 상단에 헤드나 투영이 없는 모델입니다.

이 모델은 [PreTrainedModel](/docs/transformers/v5.24.0/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.XCLIPTextModel.forward]]

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

[소스](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/x_clip/modeling_x_clip.py#L562)

**매개변수:**

input_ids (`torch.Tensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : 어휘(input sequence tokens)의 인덱스입니다. 기본적으로 패딩은 무시됩니다. [AutoTokenizer](/docs/transformers/v5.24.0/ko/model_doc/auto#transformers.AutoTokenizer)를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 [PreTrainedTokenizer.encode()](/docs/transformers/v5.24.0/ko/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 및 [PreTrainedTokenizer.__call__()](/docs/transformers/v5.24.0/ko/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)를 참조하세요. [입력 ID란 무엇인가요?](../glossary#input-ids)

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

position_ids (`torch.Tensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : 각 입력 시퀀스의 토큰 위치 인덱스입니다. `[0, config.n_positions - 1]` 범위에서 선택됩니다.  [위치 ID란 무엇인가요?](../glossary#position-ids)

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

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

[XCLIPTextModel](/docs/transformers/v5.24.0/ko/model_doc/xclip#transformers.XCLIPTextModel)의 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
>>> from transformers import AutoTokenizer, XCLIPTextModel

>>> model = XCLIPTextModel.from_pretrained("microsoft/xclip-base-patch32")
>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/xclip-base-patch32")

>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")

>>> outputs = model(**inputs)
>>> last_hidden_state = outputs.last_hidden_state
>>> pooled_output = outputs.pooler_output  # pooled (EOS token) states
```

## XCLIPVisionModel[[transformers.XCLIPVisionModel]]

#### transformers.XCLIPVisionModel[[transformers.XCLIPVisionModel]]

```python
transformers.XCLIPVisionModel(config: XCLIPVisionConfig)
```

[소스](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/x_clip/modeling_x_clip.py#L646)

**매개변수:**

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

head나 projection이 없는 XCLIP의 비전 모델입니다.

이 모델은 [PreTrainedModel](/docs/transformers/v5.24.0/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.XCLIPVisionModel.forward]]

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

[소스](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/x_clip/modeling_x_clip.py#L662)

**매개변수:**

pixel_values (`torch.Tensor`, shape `(batch_size, num_channels, image_size, image_size)`, *선택 사항*) : 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 `image_processor_class`를 사용하여 얻을 수 있습니다. 자세한 내용은 `image_processor_class.__call__`를 참조하세요 (`processor_class`는 이미지 처리에 `image_processor_class`를 사용합니다).

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

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

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

[XCLIPVisionModel](/docs/transformers/v5.24.0/ko/model_doc/xclip#transformers.XCLIPVisionModel)의 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 torch
>>> import numpy as np

>>> from transformers import AutoProcessor, XCLIPVisionModel
>>> 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 16 frames
>>> indices = sample_frame_indices(clip_len=8, frame_sample_rate=1, seg_len=container.streams.video[0].frames)
>>> video = read_video_pyav(container, indices)

>>> processor = AutoProcessor.from_pretrained("microsoft/xclip-base-patch32")
>>> model = XCLIPVisionModel.from_pretrained("microsoft/xclip-base-patch32")

>>> pixel_values = processor(videos=list(video), return_tensors="pt").pixel_values

>>> batch_size, num_frames, num_channels, height, width = pixel_values.shape
>>> pixel_values = pixel_values.reshape(-1, num_channels, height, width)

>>> outputs = model(pixel_values)
>>> last_hidden_state = outputs.last_hidden_state
```

