# GIT

## 개요

GIT 모델은 Jianfeng Wang, Zhengyuan Yang, Xiaowei Hu, Linjie Li, Kevin Lin, Zhe Gan, Zicheng Liu, Ce Liu, Lijuan Wang이 [GIT: A Generative Image-to-text Transformer for Vision and Language](https://huggingface.co/papers/2205.14100)에서 제안했습니다. GIT는 텍스트 외에도 시각 입력으로 모델을 조건화하기 위해 [CLIP](clip)의 비전 인코더를 활용하는 decoder-only Transformer입니다. 이 모델은 이미지 캡셔닝 및 시각 질의 응답 벤치마크에서 최첨단 결과를 달성했습니다.

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

*본 논문에서는 이미지/비디오 캡셔닝 및 질의응답과 같은 비전-언어 작업을 통합하기 위해 생성형 이미지-텍스트 Transformer인 GIT를 설계하고 학습합니다. 생성형 모델은 사전 학습과 미세 조정 사이에 일관된 네트워크 아키텍처를 제공하지만, 기존 연구는 일반적으로 복잡한 구조(유니/멀티모달 인코더/디코더)를 포함하며 객체 감지기/태거 및 광학 문자 인식(OCR)과 같은 외부 모듈에 의존합니다. GIT에서는 단일 언어 모델링 작업 하에 하나의 이미지 인코더와 하나의 텍스트 디코더로 아키텍처를 단순화했습니다. 또한 모델 성능을 높이기 위해 사전 학습 데이터와 모델 크기를 확장했습니다. 복잡한 부가 기능 없이, 우리의 GIT는 12개의 도전적인 벤치마크에서 큰 격차로 새로운 최첨단 성능을 달성했습니다. 예를 들어, 우리의 모델은 TextCaps에서 처음으로 인간 성능을 초과했습니다(CIDEr 기준 138.2 대 125.5). 또한, 생성 기반 이미지 분류 및 장면 텍스트 인식의 새로운 스킴을 제시하여 표준 벤치마크에서 상당한 성능을 달성했습니다.*

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

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

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

## 사용 팁

- GIT은 GPT-2와 매우 유사한 방식으로 구현되어 있으며, 유일한 차이점은 모델이 `pixel_values`에도 조건부 입력을 받는다는 점입니다.

## 리소스

GIT 시작을 돕기 위한 공식 Hugging Face 및 커뮤니티(🌎로 표시) 리소스 목록입니다.

- 커스텀 데이터에서 GIT 추론 + 파인튜닝에 대한 데모 노트북은 [여기](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/GIT)에서 찾을 수 있습니다.
- 참고: [인과적 언어 모델링 작업 가이드](../tasks/language_modeling)

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

## GitVisionConfig[[transformers.GitVisionConfig]]

#### transformers.GitVisionConfig[[transformers.GitVisionConfig]]

```python
transformers.GitVisionConfig(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, num_channels: int = 3, image_size: int | list[int] | tuple[int, int] = 224, patch_size: int | list[int] | tuple[int, int] = 16, hidden_act: str = 'quick_gelu', layer_norm_eps: float = 1e-05, attention_dropout: float | int = 0.0, initializer_range: float = 0.02)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/git/configuration_git.py#L27)

**매개변수:**

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의 수입니다.

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

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

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

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의 표준 편차입니다.

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

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

예:

```python
>>> from transformers import GitVisionConfig, GitVisionModel

>>> # Initializing a GitVisionConfig with microsoft/git-base style configuration
>>> configuration = GitVisionConfig()

>>> # Initializing a GitVisionModel (with random weights) from the microsoft/git-base style configuration
>>> model = GitVisionModel(configuration)

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

## GitVisionModel[[transformers.GitVisionModel]]

#### transformers.GitVisionModel[[transformers.GitVisionModel]]

```python
transformers.GitVisionModel(config: GitVisionConfig)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/git/modeling_git.py#L634)

**매개변수:**

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

GIT에서 사용되며, 상단에 헤드나 투영이 없는 CLIP의 비전 모델입니다.

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

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

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/git/modeling_git.py#L652)

**매개변수:**

pixel_values (`torch.Tensor`, shape `(batch_size, num_channels, image_size, image_size)`, *선택 사항*) : 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 [CLIPImageProcessor](/docs/transformers/v5.23.0/ko/model_doc/clip#transformers.CLIPImageProcessor)를 사용하여 얻을 수 있습니다. 자세한 내용은 [CLIPImageProcessor.__call__()](/docs/transformers/v5.23.0/ko/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)를 참조하세요 ([GitProcessor](/docs/transformers/v5.23.0/ko/model_doc/git#transformers.GitProcessor)는 이미지 처리에 [CLIPImageProcessor](/docs/transformers/v5.23.0/ko/model_doc/clip#transformers.CLIPImageProcessor)를 사용합니다).

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

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

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

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

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

- **last_hidden_state** (`torch.Tensor`, shape `(batch_size, sequence_length, hidden_size)`) -- 모델의 마지막 레이어 출력에서 생성된 hidden-state 시퀀스입니다.
- **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 PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from transformers import AutoProcessor, GitVisionModel

>>> processor = AutoProcessor.from_pretrained("microsoft/git-base")
>>> model = GitVisionModel.from_pretrained("microsoft/git-base")

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> inputs = processor(images=image, return_tensors="pt")

>>> outputs = model(**inputs)
>>> last_hidden_state = outputs.last_hidden_state
```

## GitConfig[[transformers.GitConfig]]

#### transformers.GitConfig[[transformers.GitConfig]]

```python
transformers.GitConfig(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, vision_config: dict | transformers.models.git.configuration_git.GitVisionConfig | None = None, vocab_size: int = 30522, hidden_size: int = 768, num_hidden_layers: int = 6, num_attention_heads: int = 12, intermediate_size: int = 3072, hidden_act: str = 'gelu', hidden_dropout_prob: float | int = 0.1, attention_probs_dropout_prob: float | int = 0.1, max_position_embeddings: int = 1024, initializer_range: float = 0.02, layer_norm_eps: float = 1e-12, pad_token_id: int | None = 0, use_cache: bool = True, tie_word_embeddings: bool = False, bos_token_id: int | None = 101, eos_token_id: int | list[int] | None = 102, num_image_with_embedding: int | None = None)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/git/configuration_git.py#L62)

**매개변수:**

vision_config (`Union[dict, ~models.git.configuration_git.GitVisionConfig]`, *선택*) : 비전 백본의 config 객체 또는 사전입니다.

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

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

num_hidden_layers (`int`, *선택 사항*, 기본값 `6`) : Transformer 디코더의 숨겨진 레이어 수.

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

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

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

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

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

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

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

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

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

use_cache (`bool`, *선택 사항*, 기본값 `True`) : 모델이 마지막 key/values attention을 반환할지 여부입니다(모든 모델에서 사용되지 않음). `config.is_decoder=True`인 경우 또는 모델이 decoder-only 생성 모델인 경우에만 관련이 있습니다.

tie_word_embeddings (`bool`, *선택 사항*, 기본값 `False`) : 모델의 `tied_weights_keys` 매핑에 따라 가중치 임베딩을 묶을지 여부.

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

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

num_image_with_embedding (`int`, *선택 사항*) : 모델이 비디오 캡셔닝/VQA에 사용되는 경우 추가할 시간 임베딩의 수.

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

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

예:

```python
>>> from transformers import GitConfig, GitModel

>>> # Initializing a GIT microsoft/git-base style configuration
>>> configuration = GitConfig()

>>> # Initializing a model (with random weights) from the microsoft/git-base style configuration
>>> model = GitModel(configuration)

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

## GitProcessor[[transformers.GitProcessor]]

#### transformers.GitProcessor[[transformers.GitProcessor]]

```python
transformers.GitProcessor(image_processor, tokenizer)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/git/processing_git.py#L23)

**매개변수:**

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

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

이미지 프로세서와 토크나이저를 단일 프로세서로 묶는 GitProcessor를 생성합니다.

[GitProcessor](/docs/transformers/v5.23.0/ko/model_doc/git#transformers.GitProcessor)는 [CLIPImageProcessor](/docs/transformers/v5.23.0/ko/model_doc/clip#transformers.CLIPImageProcessor)와 [BertTokenizer](/docs/transformers/v5.23.0/ko/model_doc/lxmert#transformers.BertTokenizer)의 모든 기능을 제공합니다. 자세한 내용은 [~CLIPImageProcessor](/docs/transformers/v5.23.0/ko/model_doc/clip#transformers.CLIPImageProcessor)와 [~BertTokenizer](/docs/transformers/v5.23.0/ko/model_doc/lxmert#transformers.BertTokenizer)를 참고하세요.

#### __call__[[transformers.GitProcessor.__call__]]

```python
__call__(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, text: str | list[str] | list[list[str]] | None = None, 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]], NoneType] = None, audio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor'], NoneType] = None, **kwargs: *<class 'transformers.processing_utils.ProcessingKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/processing_utils.py#L670)

**매개변수:**

images (`Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]`, *선택*) : 전처리할 이미지. 픽셀 값이 0에서 255 범위로 이루어진 단일 이미지 또는 배치 이미지를 기대합니다. 픽셀 값이 0에서 1 범위로 이루어진 이미지를 전달하는 경우 `do_rescale=False`로 설정하세요.

text (`Union[str, list[str], list[list[str]]]`, *선택*) : 인코딩할 시퀀스 또는 시퀀스 배치입니다. 각 시퀀스는 문자열 또는 문자열 목록(사전 토큰화된 문자열)일 수 있습니다. 사전 토큰화된 입력을 전달하는 경우, 배치 입력과의 혼동을 피하기 위해 `is_split_into_words=True`를 설정하세요.

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`로 설정하세요.

audio (`Union[numpy.ndarray, torch.Tensor, collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence[torch.Tensor]]`, *선택 사항*) : 준비할 오디오 또는 오디오 배치입니다. 각 오디오는 NumPy 배열 또는 PyTorch 텐서일 수 있습니다. NumPy 배열/PyTorch 텐서의 경우, 각 오디오의 shape은 (C, T)여야 하며, 여기서 C는 채널 수, T는 오디오의 샘플 길이입니다.

return_mm_token_type_ids (`bool`, *kwargs*) : 멀티모달 플레이스홀더 토큰의 위치를 나타내는 멀티모달 토큰 타입 ID를 반환할지 여부.

return_text_replacement_offsets (`bool`, *kwargs*) : 각 멀티모달 플레이스홀더 및 그 대체 문자열의 문자 오프셋을 반환할지 여부.

return_tensors (`str` 또는 [TensorType](/docs/transformers/v5.23.0/ko/internal/file_utils#transformers.TensorType), *optional*) : 설정된 경우, 특정 프레임워크의 텐서를 반환합니다. 허용되는 값은 다음과 같습니다:  - `'pt'`: PyTorch `torch.Tensor` 객체를 반환합니다. - `'np'`: NumPy `np.ndarray` 객체를 반환합니다.

- ****kwargs** ([ProcessingKwargs](/docs/transformers/v5.23.0/ko/main_classes/processors#transformers.ProcessingKwargs), *optional*) : 각 모달리티(텍스트, 이미지, 비디오, 오디오)에 대한 추가 처리 옵션입니다. 모델별 매개변수는 위에 나열되어 있으며, 지원되는 인수의 전체 목록은 TypedDict 클래스를 참조하세요.

## GitModel[[transformers.GitModel]]

#### transformers.GitModel[[transformers.GitModel]]

```python
transformers.GitModel(config: GitConfig)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/git/modeling_git.py#L707)

**매개변수:**

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

CLIP 이미지 인코더와 텍스트 디코더로 구성되어 원시 hidden-states를 출력하는 기본 GIT Model transformer

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

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

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/git/modeling_git.py#L738)

**매개변수:**

input_ids (`torch.Tensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : 어휘(input sequence tokens)의 인덱스입니다. 기본적으로 패딩은 무시됩니다. [AutoTokenizer](/docs/transformers/v5.23.0/ko/model_doc/auto#transformers.AutoTokenizer)를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 [PreTrainedTokenizer.encode()](/docs/transformers/v5.23.0/ko/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 및 [PreTrainedTokenizer.__call__()](/docs/transformers/v5.23.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)

pixel_values (`torch.Tensor`, shape `(batch_size, num_channels, image_size, image_size)`, *선택 사항*) : 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 [CLIPImageProcessor](/docs/transformers/v5.23.0/ko/model_doc/clip#transformers.CLIPImageProcessor)를 사용하여 얻을 수 있습니다. 자세한 내용은 [CLIPImageProcessor.__call__()](/docs/transformers/v5.23.0/ko/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)를 참조하세요 ([GitProcessor](/docs/transformers/v5.23.0/ko/model_doc/git#transformers.GitProcessor)는 이미지 처리에 [CLIPImageProcessor](/docs/transformers/v5.23.0/ko/model_doc/clip#transformers.CLIPImageProcessor)를 사용합니다).

inputs_embeds (`torch.Tensor`, shape `(batch_size, sequence_length, hidden_size)`, *선택 사항*) : `input_ids`를 전달하는 대신 임베디드 표현을 직접 전달할 수 있습니다. 이는 모델의 내부 임베딩 조회 행렬보다 `input_ids` 인덱스를 관련 벡터로 변환하는 방식에 대해 더 많은 제어가 필요한 경우 유용합니다.

past_key_values (`~cache_utils.Cache`, *선택*) : 순차적 디코딩을 가속화할 수 있는 사전 계산된 hidden-states(셀프 어텐션 블록과 크로스 어텐션 블록의 key 및 value)입니다. 일반적으로 `use_cache=True` 또는 `config.use_cache=True`일 때 모델이 디코딩의 이전 단계에서 반환한 `past_key_values`로 구성됩니다. 입력으로 [Cache](/docs/transformers/v5.23.0/ko/internal/generation_utils#transformers.Cache) 인스턴스만 허용되며, [kv cache 가이드](https://huggingface.co/docs/transformers/en/kv_cache)를 참조하세요. `past_key_values`가 전달되지 않으면 기본적으로 [DynamicCache](/docs/transformers/v5.23.0/ko/internal/generation_utils#transformers.DynamicCache)가 초기화됩니다. 모델은 입력으로 제공된 것과 동일한 캐시 형식을 출력합니다. `past_key_values`를 사용하는 경우, 이 모델에 과거 key value 상태가 제공되지 않은 `input_ids`(처리되지 않은 항목)만 `(batch_size, unprocessed_length)` 형식으로 입력해야 하며, `(batch_size, sequence_length)` 형식의 모든 `input_ids`를 입력하지 않습니다.

use_cache (`bool`, *선택 사항*) : `True`로 설정하면 `past_key_values` 키 값 상태가 반환되며, 디코딩 속도를 높이는 데 사용할 수 있습니다(`past_key_values` 참조).

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

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

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

[GitModel](/docs/transformers/v5.23.0/ko/model_doc/git#transformers.GitModel)의 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 AutoProcessor, AutoModel
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from PIL import Image

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

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> text = "this is an image of two cats"

>>> inputs = processor(images=image, text=text, return_tensors="pt")

>>> outputs = model(**inputs)
>>> last_hidden_state = outputs.last_hidden_state
```

## GitForCausalLM[[transformers.GitForCausalLM]]

#### transformers.GitForCausalLM[[transformers.GitForCausalLM]]

```python
transformers.GitForCausalLM(config: GitConfig)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/git/modeling_git.py#L890)

**매개변수:**

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

`language modeling` 헤드를 위에 올려서 자기회귀 언어 모델링을 수행하는 GIT 모델.

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

```python
forward(input_ids: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.Tensor] = None, pixel_values: typing.Optional[torch.Tensor] = None, inputs_embeds: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.Tensor] = None, past_key_values: transformers.cache_utils.Cache | None = None, use_cache: bool | None = None, interpolate_pos_encoding: bool = False, logits_to_keep: typing.Union[int, torch.Tensor] = 0, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/git/modeling_git.py#L908)

**매개변수:**

input_ids (`torch.Tensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : 어휘(input sequence tokens)의 인덱스입니다. 기본적으로 패딩은 무시됩니다. [AutoTokenizer](/docs/transformers/v5.23.0/ko/model_doc/auto#transformers.AutoTokenizer)를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 [PreTrainedTokenizer.encode()](/docs/transformers/v5.23.0/ko/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 및 [PreTrainedTokenizer.__call__()](/docs/transformers/v5.23.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)

pixel_values (`torch.Tensor`, shape `(batch_size, num_channels, image_size, image_size)`, *선택 사항*) : 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 [CLIPImageProcessor](/docs/transformers/v5.23.0/ko/model_doc/clip#transformers.CLIPImageProcessor)를 사용하여 얻을 수 있습니다. 자세한 내용은 [CLIPImageProcessor.__call__()](/docs/transformers/v5.23.0/ko/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)를 참조하세요 ([GitProcessor](/docs/transformers/v5.23.0/ko/model_doc/git#transformers.GitProcessor)는 이미지 처리에 [CLIPImageProcessor](/docs/transformers/v5.23.0/ko/model_doc/clip#transformers.CLIPImageProcessor)를 사용합니다).

inputs_embeds (`torch.Tensor`, shape `(batch_size, sequence_length, hidden_size)`, *선택 사항*) : `input_ids`를 전달하는 대신 임베디드 표현을 직접 전달할 수 있습니다. 이는 모델의 내부 임베딩 조회 행렬보다 `input_ids` 인덱스를 관련 벡터로 변환하는 방식에 대해 더 많은 제어가 필요한 경우 유용합니다.

labels (`torch.LongTensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : 왼쪽에서 오른쪽으로 언어 모델링 손실(다음 단어 예측)을 계산하는 데 사용되는 라벨. 인덱스는 `[-100, 0, ..., config.vocab_size]` 범위여야 합니다(`input_ids` docstring 참조). 인덱스가 `-100`으로 설정된 토큰은 무시(마스크)되며, 손실은 라벨이 `[0, ..., config.vocab_size]` 범위에 있는 토큰에 대해서만 계산됩니다.

past_key_values (`~cache_utils.Cache`, *선택*) : 순차적 디코딩을 가속화할 수 있는 사전 계산된 hidden-states(셀프 어텐션 블록과 크로스 어텐션 블록의 key 및 value)입니다. 일반적으로 `use_cache=True` 또는 `config.use_cache=True`일 때 모델이 디코딩의 이전 단계에서 반환한 `past_key_values`로 구성됩니다. 입력으로 [Cache](/docs/transformers/v5.23.0/ko/internal/generation_utils#transformers.Cache) 인스턴스만 허용되며, [kv cache 가이드](https://huggingface.co/docs/transformers/en/kv_cache)를 참조하세요. `past_key_values`가 전달되지 않으면 기본적으로 [DynamicCache](/docs/transformers/v5.23.0/ko/internal/generation_utils#transformers.DynamicCache)가 초기화됩니다. 모델은 입력으로 제공된 것과 동일한 캐시 형식을 출력합니다. `past_key_values`를 사용하는 경우, 이 모델에 과거 key value 상태가 제공되지 않은 `input_ids`(처리되지 않은 항목)만 `(batch_size, unprocessed_length)` 형식으로 입력해야 하며, `(batch_size, sequence_length)` 형식의 모든 `input_ids`를 입력하지 않습니다.

use_cache (`bool`, *선택 사항*) : `True`로 설정하면 `past_key_values` 키 값 상태가 반환되며, 디코딩 속도를 높이는 데 사용할 수 있습니다(`past_key_values` 참조).

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

logits_to_keep (`Union[int, torch.Tensor]`, *선택 사항*, 기본값 `0`) : `int`인 경우, 마지막 `logits_to_keep` 토큰에 대한 logits를 계산합니다. `0`인 경우, 모든 `input_ids`에 대한 logits를 계산합니다(특수한 경우). 생성에는 마지막 토큰의 logits만 필요하며, 해당 토큰에 대해서만 계산하면 메모리를 절약할 수 있습니다. 이는 긴 시퀀스나 큰 어휘 크기의 경우 상당한 이점을 제공합니다. `torch.Tensor`인 경우, 시퀀스 길이 차원에서 유지할 인덱스에 해당하는 1차원 텐서여야 합니다. 이는 packed tensor 형식(배치와 시퀀스 길이를 단일 차원으로 사용하는 경우)을 사용할 때 유용합니다.

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

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

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

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

- **loss** (`torch.Tensor`, shape `(1,)`, *선택 사항*, `labels`가 제공될 때 반환됨) -- 언어 모델링 손실(다음 토큰 예측용).
- **logits** (`torch.Tensor`, shape `(batch_size, sequence_length, config.vocab_size)`) -- 언어 모델링 헤드에서 생성된 예측 점수(SoftMax 적용 전 각 어휘 토큰에 대한 점수).
- **past_key_values** (`Cache`, *선택 사항*, `use_cache=True`가 전달되었거나 `config.use_cache=True`인 경우 반환됨) -- [Cache](/docs/transformers/v5.23.0/ko/internal/generation_utils#transformers.Cache) 인스턴스입니다. 자세한 내용은 [kv cache 가이드](https://huggingface.co/docs/transformers/en/kv_cache)를 참조하세요.

  순차적 디코딩을 가속화하는 데 사용할 수 있는 사전 계산된 hidden-states(셀프 어텐션 블록의 key와 value)를 포함합니다(입력 `past_key_values` 참조).
- **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 AutoProcessor, AutoModelForCausalLM
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from PIL import Image

>>> processor = AutoProcessor.from_pretrained("microsoft/git-base-coco")
>>> model = AutoModelForCausalLM.from_pretrained("microsoft/git-base-coco")

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> pixel_values = processor(images=image, return_tensors="pt").pixel_values

>>> generated_ids = model.generate(pixel_values=pixel_values, max_length=50)
>>> generated_caption = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
>>> print(generated_caption)
two cats sleeping on a pink blanket next to remotes.
```

시각 질의응답(VQA) 예시:

```python
>>> from transformers import AutoProcessor, AutoModelForCausalLM
>>> from huggingface_hub import hf_hub_download
>>> from PIL import Image

>>> processor = AutoProcessor.from_pretrained("microsoft/git-base-textvqa")
>>> model = AutoModelForCausalLM.from_pretrained("microsoft/git-base-textvqa")

>>> file_path = hf_hub_download(repo_id="nielsr/textvqa-sample", filename="bus.png", repo_type="dataset")
>>> image = Image.open(file_path).convert("RGB")

>>> pixel_values = processor(images=image, return_tensors="pt").pixel_values

>>> question = "what does the front of the bus say at the top?"

>>> input_ids = processor(text=question, add_special_tokens=False).input_ids
>>> input_ids = [processor.tokenizer.cls_token_id] + input_ids
>>> input_ids = torch.tensor(input_ids).unsqueeze(0)

>>> generated_ids = model.generate(pixel_values=pixel_values, input_ids=input_ids, max_length=50)
>>> print(processor.batch_decode(generated_ids, skip_special_tokens=True))
['what does the front of the bus say at the top? special']
```

Video captioning example:

```python
>>> import av
>>> import numpy as np
>>> from PIL import Image
>>> from huggingface_hub import hf_hub_download
>>> from transformers import AutoProcessor, AutoModelForCausalLM

>>> processor = AutoProcessor.from_pretrained("microsoft/git-base-vatex")
>>> model = AutoModelForCausalLM.from_pretrained("microsoft/git-base-vatex")

>>> # set seed for reproducibility
>>> np.random.seed(45)

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

>>> # load video
>>> file_path = hf_hub_download(
...     repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
... )
>>> container = av.open(file_path)

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

>>> pixel_values = processor(images=list(frames), return_tensors="pt").pixel_values

>>> generated_ids = model.generate(pixel_values=pixel_values, max_length=50)

>>> print("Generated caption:", processor.batch_decode(generated_ids, skip_special_tokens=True))
Generated caption: ['a woman is sitting at a table and she is talking about the food she is holding.']
```

