# InstructBLIP

## 개요

InstructBLIP 모델은 Wenliang Dai, Junnan Li, Dongxu Li, Anthony Meng Huat Tiong, Junqi Zhao, Weisheng Wang, Boyang Li, Pascale Fung, Steven Hoi가 [InstructBLIP: Towards General-purpose Vision-Language Models with Instruction Tuning](https://huggingface.co/papers/2305.06500)에서 제안했습니다. InstructBLIP는 시각 지시 튜닝을 위해 [BLIP-2](blip-2) 아키텍처를 활용합니다.

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

*다양한 언어 도메인 작업을 해결할 수 있는 범용 언어 모델은 사전 학습 및 지시 튜닝 파이프라인에 의해 등장했습니다. 그러나 추가된 시각 입력으로 인해 작업 간 불일치가 증가하기 때문에 범용 시선-언어 모델을 구축하는 것은 도전적입니다. 시선-언어 사전 학습은 광범위하게 연구되어 왔지만, 시선-언어 지시 튜닝은 상대적으로 덜 탐구되었습니다. 본 논문에서는 사전 학습된 BLIP-2 모델을 기반으로 시선-언어 지시 튜닝에 대한 체계적이고 포괄적인 연구를 수행합니다. 26개의 공개 데이터셋을 수집하여 지시 튜닝 형식으로 변환하고, held-in 지시 튜닝과 held-out zero-shot 평가를 위해 두 클러스터로 분류합니다. 또한, 주어진 지시에 맞춰 정보적인 특징을 추출할 수 있도록 하는 핵심 방법인 지시 인식 시각 특징 추출(instruction-aware visual feature extraction)을 소개합니다. 그 결과, InstructBLIP 모델은 모든 13개의 held-out 데이터셋에서 최첨단 zero-shot 성능을 달성하여 BLIP-2 및 더 큰 Flamingo를 크게 능가합니다. 또한, 개별 하위 작업에 대해 fine-tune할 때도 최첨단 성능을 이끌어냅니다(예: ScienceQA IMG에서 90.7% 정확도). 마지막으로, 동시 다중 모드 모델에 비해 InstructBLIP의 이점을 정성적으로 입증합니다.*

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

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

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

## 사용 팁

InstructBLIP은 [BLIP-2](blip-2)와 동일한 아키텍처를 사용하지만, 작지만 중요한 차이가 있습니다. 텍스트 프롬프트(지시문)도 Q-Former에 입력합니다.

> [!NOTE]
> v4.46 릴리스 이후의 BLIP 모델은 `processor.num_query_tokens = {{num_query_tokens}}`를 추가하고 모델 임베딩 레이어를 확장하여 특수 `<image>` 토큰을 추가하는 것에 대한 경고를 발생시킵니다. 모델 체크포인트를 소유하고 있다면 프로세서에 해당 속성을 추가하는 것이 강력히 권장되며, 소유자가 아니라면 PR을 열어 주세요. 이러한 속성을 추가하면 BLIP는 이미지당 필요한 쿼리 토큰 수를 추가하고, 쿼리 토큰 수만큼 `<image>` 플레이스홀더로 텍스트를 확장합니다. 일반적으로 이미지당 약 500개의 토큰이 필요하므로, 텍스트가 잘리지 않도록 확인해야 합니다. 그렇지 않으면 임베딩 병합 시 실패가 발생합니다.
속성은 모델 구성에서 `model.config.num_query_tokens`와 같이 가져올 수 있으며, 모델 임베딩 확장은 [이 링크](https://gist.github.com/zucchini-nlp/e9f20b054fa322f84ac9311d9ab67042)를 참고하여 수행할 수 있습니다.

## InstructBlipConfig[[transformers.InstructBlipConfig]]

#### transformers.InstructBlipConfig[[transformers.InstructBlipConfig]]

```python
transformers.InstructBlipConfig(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.configuration_utils.PreTrainedConfig | None = None, qformer_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, text_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, num_query_tokens: int = 32, image_token_index: int | None = None, initializer_factor: float = 1.0, initializer_range: float = 0.02)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblip/configuration_instructblip.py#L106)

**매개변수:**

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

qformer_config (`dict`, *선택 사항*) : [InstructBlipQFormerConfig](/docs/transformers/main/ko/model_doc/instructblip#transformers.InstructBlipQFormerConfig)를 초기화하는 데 사용되는 구성 옵션의 사전입니다.

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

num_query_tokens (`int`, *선택 사항*, 기본값 32) : Transformer를 통과하는 쿼리 토큰의 수입니다.

image_token_index (`int`, *선택 사항*) : 입력 이미지의 자리표시자로 사용되는 이미지 토큰 인덱스입니다.

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

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

이것은 InstructBlipModel의 구성을 저장하기 위한 구성 클래스입니다. 지정된 인자에 따라 Instructblip 모델을 인스턴스화하고 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 구성을 인스턴스화하면 [Salesforce/instructblip-flan-t5-xl](https://huggingface.co/Salesforce/instructblip-flan-t5-xl)의 구성과 유사한 구성이 생성됩니다.

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 (
...     InstructBlipVisionConfig,
...     InstructBlipQFormerConfig,
...     OPTConfig,
...     InstructBlipConfig,
...     InstructBlipForConditionalGeneration,
... )

>>> # Initializing a InstructBlipConfig with Salesforce/instructblip-flan-t5-xl style configuration
>>> configuration = InstructBlipConfig()

>>> # Initializing a InstructBlipForConditionalGeneration (with random weights) from the Salesforce/instructblip-flan-t5-xl style configuration
>>> model = InstructBlipForConditionalGeneration(configuration)

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

>>> # We can also initialize a InstructBlipConfig from a InstructBlipVisionConfig, InstructBlipQFormerConfig and any PreTrainedConfig

>>> # Initializing InstructBLIP vision, InstructBLIP Q-Former and language model configurations
>>> vision_config = InstructBlipVisionConfig()
>>> qformer_config = InstructBlipQFormerConfig()
>>> text_config = OPTConfig()

>>> config = InstructBlipConfig(vision_config=vision_config, qformer_config=qformer_config, text_config=text_config)
```

## InstructBlipVisionConfig[[transformers.InstructBlipVisionConfig]]

#### transformers.InstructBlipVisionConfig[[transformers.InstructBlipVisionConfig]]

```python
transformers.InstructBlipVisionConfig(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 = 1408, intermediate_size: int = 6144, num_hidden_layers: int = 39, num_attention_heads: int = 16, image_size: int | list[int] | tuple[int, int] = 224, patch_size: int | list[int] | tuple[int, int] = 14, hidden_act: str = 'gelu', layer_norm_eps: float = 1e-06, attention_dropout: float | int = 0.0, initializer_range: float = 1e-10, qkv_bias: bool = True)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblip/configuration_instructblip.py#L29)

**매개변수:**

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

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

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

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

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

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

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

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

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

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

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

이것은 InstructBlipModel의 구성을 저장하기 위한 구성 클래스입니다. 지정된 인자에 따라 Instructblip 모델을 인스턴스화하고 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 구성을 인스턴스화하면 [Salesforce/instructblip-flan-t5-xl](https://huggingface.co/Salesforce/instructblip-flan-t5-xl)의 구성과 유사한 구성이 생성됩니다.

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 InstructBlipVisionConfig, InstructBlipVisionModel

>>> # Initializing a InstructBlipVisionConfig with Salesforce/instructblip-flan-t5-xl style configuration
>>> configuration = InstructBlipVisionConfig()

>>> # Initializing a InstructBlipVisionModel (with random weights) from the Salesforce/instructblip-flan-t5-xl style configuration
>>> model = InstructBlipVisionModel(configuration)

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

## InstructBlipQFormerConfig[[transformers.InstructBlipQFormerConfig]]

#### transformers.InstructBlipQFormerConfig[[transformers.InstructBlipQFormerConfig]]

```python
transformers.InstructBlipQFormerConfig(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 = 30522, hidden_size: int = 768, num_hidden_layers: int = 12, 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 = 512, initializer_range: float = 0.02, layer_norm_eps: float = 1e-12, pad_token_id: int | None = 0, cross_attention_frequency: int = 2, encoder_hidden_size: int = 1408)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblip/configuration_instructblip.py#L64)

**매개변수:**

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

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`) : 디코더에서 사용되는 비선형 활성화 함수(함수 또는 문자열). 예를 들어, `"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`, *선택 사항*, 기본값 `512`) : 이 모델이 사용될 수 있는 최대 시퀀스 길이입니다.

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

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

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

cross_attention_frequency (`int`, *선택 사항*, 기본값 2) : Transformer 레이어에 cross-attention을 추가하는 주기입니다.

encoder_hidden_size (`int`, *선택 사항*, 기본값 1408) : cross-attention의 hidden states에 대한 hidden size입니다.

이것은 InstructBlipModel의 구성을 저장하기 위한 구성 클래스입니다. 지정된 인자에 따라 Instructblip 모델을 인스턴스화하고 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 구성을 인스턴스화하면 [Salesforce/instructblip-flan-t5-xl](https://huggingface.co/Salesforce/instructblip-flan-t5-xl)의 구성과 유사한 구성이 생성됩니다.

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 InstructBlipQFormerConfig, InstructBlipQFormerModel

>>> # Initializing a InstructBLIP Salesforce/instructblip-flan-t5-xl style configuration
>>> configuration = InstructBlipQFormerConfig()

>>> # Initializing a model (with random weights) from the Salesforce/instructblip-flan-t5-xl style configuration
>>> model = InstructBlipQFormerModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```

## InstructBlipProcessor[[transformers.InstructBlipProcessor]]

#### transformers.InstructBlipProcessor[[transformers.InstructBlipProcessor]]

```python
transformers.InstructBlipProcessor(image_processor, tokenizer, qformer_tokenizer, num_query_tokens = None, **kwargs)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblip/processing_instructblip.py#L45)

**매개변수:**

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

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

qformer_tokenizer (`AutoTokenizer`) : ['PreTrainedTokenizer`']의 인스턴스입니다. Q-Former 토크나이저는 필수 입력입니다.

num_query_tokens (`int`, *선택 사항*) : Qformer가 쿼리로 사용하는 토큰의 수이며, 모델의 config와 동일해야 합니다.

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

[InstructBlipProcessor](/docs/transformers/main/ko/model_doc/instructblip#transformers.InstructBlipProcessor)는 [BlipImageProcessor](/docs/transformers/main/ko/model_doc/blip#transformers.BlipImageProcessor), [GPT2Tokenizer](/docs/transformers/main/ko/model_doc/gpt2#transformers.GPT2Tokenizer), `{qformer_tokenizer_class}`의 모든 기능을 제공합니다. 자세한 내용은 [~BlipImageProcessor](/docs/transformers/main/ko/model_doc/blip#transformers.BlipImageProcessor), [~GPT2Tokenizer](/docs/transformers/main/ko/model_doc/gpt2#transformers.GPT2Tokenizer), `~{qformer_tokenizer_class}`를 참고하세요.

#### __call__[[transformers.InstructBlipProcessor.__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, **kwargs: *<class 'transformers.models.instructblip.processing_instructblip.InstructBlipProcessorKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblip/processing_instructblip.py#L63)

**매개변수:**

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

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

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

**반환값:** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- __call__ 메서드가 반환하는 리스트/배열/텐서 딕셔너리('pixel_values' 등).
- **tensor_type** (`Union[None, str, TensorType]`, *선택 사항*) -- 초기화 시 PyTorch/Numpy 텐서에서 정수 목록을 변환하려면 여기에 tensor_type을 지정할 수 있습니다.

## InstructBlipVisionModel[[transformers.InstructBlipVisionModel]]

#### transformers.InstructBlipVisionModel[[transformers.InstructBlipVisionModel]]

```python
transformers.InstructBlipVisionModel(config: InstructBlipVisionConfig)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblip/modeling_instructblip.py#L392)

#### forward[[transformers.InstructBlipVisionModel.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/main/src/transformers/models/instructblip/modeling_instructblip.py#L412)

**매개변수:**

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

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

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

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

[InstructBlipVisionModel](/docs/transformers/main/ko/model_doc/instructblip#transformers.InstructBlipVisionModel)의 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 가중치입니다.

## InstructBlipQFormerModel[[transformers.InstructBlipQFormerModel]]

#### transformers.InstructBlipQFormerModel[[transformers.InstructBlipQFormerModel]]

```python
transformers.InstructBlipQFormerModel(config: InstructBlipQFormerConfig)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblip/modeling_instructblip.py#L760)

InstructBLIP에서 사용되는 Querying Transformer (Q-Former). 지시문도 입력으로 받으므로 BLIP-2에서 약간 수정되었습니다.

#### forward[[transformers.InstructBlipQFormerModel.forward]]

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

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblip/modeling_instructblip.py#L799)

**매개변수:**

input_ids (`torch.LongTensor`, shape `(batch_size, sequence_length)`) : 어휘 사전에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다. [AutoTokenizer](/docs/transformers/main/ko/model_doc/auto#transformers.AutoTokenizer)를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 [PreTrainedTokenizer.encode()](/docs/transformers/main/ko/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 및 [PreTrainedTokenizer.__call__()](/docs/transformers/main/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.LongTensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : 각 입력 시퀀스의 토큰 위치 인덱스입니다. `[0, config.n_positions - 1]` 범위에서 선택됩니다. [위치 ID란 무엇인가요?](../glossary#position-ids)

query_embeds (`torch.Tensor`, shape `(batch_size, sequence_length, hidden_size)`) : attention 계산에 사용되는 hidden states입니다. cross-attention인 경우 query로 사용되며(즉, key와 value는 encoder_hidden_states를 사용합니다).

encoder_hidden_states (`torch.Tensor`, shape `(batch_size, sequence_length, hidden_size)`, *선택 사항*) : 인코더의 마지막 레이어 출력에서 생성된 hidden-states 시퀀스입니다. 모델이 디코더로 구성된 경우 cross-attention에 사용됩니다.

encoder_attention_mask (`torch.Tensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : 인코더 입력의 패딩 토큰 인덱스에 대한 어텐션을 수행하지 않도록 하는 마스크입니다. 모델이 디코더로 구성된 경우 크로스 어텐션에서 이 마스크가 사용됩니다. `[0, 1]`에서 선택된 마스크 값: - **마스크되지 않은** 토큰은 1, - **마스크된** 토큰은 0.

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

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

[InstructBlipQFormerModel](/docs/transformers/main/ko/model_doc/instructblip#transformers.InstructBlipQFormerModel)의 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 가중치입니다.
- **cross_attentions** (`tuple(torch.Tensor)`, *선택*, `output_attentions=True` 또는 `config.add_cross_attention=True`가 전달되거나 `config.output_attentions=True`인 경우 반환) -- 각 레이어당 하나씩, shape가 `(batch_size, num_heads, sequence_length, sequence_length)`인 `torch.Tensor`의 튜플.

  decoder의 cross-attention 레이어에서 attention softmax를 적용한 후, cross-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention 가중치입니다.
- **past_key_values** (`Cache`, *선택 사항*, `use_cache=True`가 전달되었거나 `config.use_cache=True`인 경우 반환됨) -- [Cache](/docs/transformers/main/ko/internal/generation_utils#transformers.Cache) 인스턴스입니다. 자세한 내용은 [kv cache 가이드](https://huggingface.co/docs/transformers/en/kv_cache)를 참조하세요.

  순차적 디코딩을 가속화하는 데 사용할 수 있는 사전 계산된 hidden-states(셀프 어텐션 블록의 key와 value, 그리고 `config.is_encoder_decoder=True`인 경우 크로스 어텐션 블록의 key와 value)를 포함합니다(입력 `past_key_values` 참조).

## InstructBlipModel[[transformers.InstructBlipModel]]

#### transformers.InstructBlipModel[[transformers.InstructBlipModel]]

```python
transformers.InstructBlipModel(config: InstructBlipConfig)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblip/modeling_instructblip.py#L867)

**매개변수:**

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

InstructBLIP base 모델은 언어 모델, qformer, 비전 인코더로 구성됩니다.

이 모델은 [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.InstructBlipModel.forward]]

```python
forward(pixel_values: Tensor, qformer_input_ids: Tensor, qformer_attention_mask: typing.Optional[torch.LongTensor] = None, input_ids: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.LongTensor] = None, decoder_input_ids: typing.Optional[torch.LongTensor] = None, decoder_attention_mask: typing.Optional[torch.LongTensor] = None, inputs_embeds: typing.Optional[torch.Tensor] = None, interpolate_pos_encoding: bool = False, **kwargs: *<class 'transformers.modeling_flash_attention_utils.FlashAttentionKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblip/modeling_instructblip.py#L919)

**매개변수:**

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

qformer_input_ids (`torch.LongTensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : Q-Former 어휘 사전에서 입력 시퀀스 토큰의 인덱스입니다. 입력 토큰은 선택적으로 제공하여 텍스트 프롬프트로 사용할 수 있으며, Q-Former 모델이 이를 인코딩합니다. 인덱스는 [InstructBlipProcessor](/docs/transformers/main/ko/model_doc/instructblip#transformers.InstructBlipProcessor)를 사용하여 얻을 수 있습니다. 자세한 내용은 [InstructBlipProcessor.__call__()](/docs/transformers/main/ko/model_doc/instructblip#transformers.InstructBlipProcessor.__call__)를 참조하세요. [입력 ID란 무엇인가요?](../glossary#input-ids)

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

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

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

decoder_input_ids (`torch.LongTensor`, shape `(batch_size, target_sequence_length)`, *선택 사항*) : 어휘 내에서 디코더 입력 시퀀스 토큰의 인덱스입니다. [AutoTokenizer](/docs/transformers/main/ko/model_doc/auto#transformers.AutoTokenizer)를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 [PreTrainedTokenizer.encode()](/docs/transformers/main/ko/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 및 [PreTrainedTokenizer.__call__()](/docs/transformers/main/ko/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)를 참조하세요. [디코더 입력 ID란 무엇인가요?](../glossary#decoder-input-ids)

decoder_attention_mask (`torch.BoolTensor`, shape `(batch_size, target_sequence_length)`, *선택 사항*) : 기본 동작: `decoder_input_ids`의 pad 토큰을 무시하는 텐서를 생성합니다. 기본적으로 Causal mask도 사용됩니다. 인코더-디코더 언어 모델(T5 등)을 사용하는 경우에만 관련이 있습니다.

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

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

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

`InstructBlipForConditionalGenerationModelOutput` 또는 `torch.Tensor`의 튜플(`return_dict=False`가 전달되거나 `config.return_dict=False`인 경우)로, 구성([InstructBlipConfig](/docs/transformers/main/ko/model_doc/instructblip#transformers.InstructBlipConfig))과 입력에 따라 다양한 요소를 포함합니다.

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

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

- **loss** (`torch.Tensor`, *선택 사항*, `labels`이 제공될 때 반환되며, `torch.Tensor` 형상 `(1,)`) -- 언어 모델에서 산출된 언어 모델링 손실.
- **logits** (`torch.Tensor`, shape `(batch_size, sequence_length, config.vocab_size)`) -- 언어 모델의 언어 모델링 헤드에 대한 예측 점수입니다.
- **vision_outputs** (`~modeling_outputs.BaseModelOutputWithPooling`, *선택 사항*) -- 비전 인코더의 출력입니다.
- **qformer_outputs** (`~modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions`, *선택 사항*) -- Q-Former(Querying Transformer)의 출력입니다.
- **language_model_outputs** (`CausalLMOutputWithPast` 또는 `Seq2SeqLMOutput`) -- 언어 모델의 출력입니다.

#### get_placeholder_mask[[transformers.InstructBlipModel.get_placeholder_mask]]

```python
get_placeholder_mask(input_ids: LongTensor, inputs_embeds: Tensor)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblip/modeling_instructblip.py#L904)

`input_ids` 또는 `inputs_embeds`에서 멀티모달 플레이스홀더 마스크를 가져옵니다.

## InstructBlipForConditionalGeneration[[transformers.InstructBlipForConditionalGeneration]]

#### transformers.InstructBlipForConditionalGeneration[[transformers.InstructBlipForConditionalGeneration]]

```python
transformers.InstructBlipForConditionalGeneration(config: InstructBlipConfig)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblip/modeling_instructblip.py#L1028)

**매개변수:**

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

이미지와 선택적 텍스트 프롬프트를 입력받아 텍스트를 생성하는 InstructBLIP 모델입니다. 이 모델은 비전 인코더, Querying Transformer(Q-Former), 언어 모델로 구성됩니다.

모델에 `input_ids`를 선택적으로 전달할 수 있으며, 이는 텍스트 프롬프트 역할을 하여 언어 모델이 해당 프롬프트를 계속하도록 합니다. 그렇지 않으면 언어 모델은 [BOS](시퀀스 시작) 토큰부터 텍스트 생성을 시작합니다.

이 모델은 [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.InstructBlipForConditionalGeneration.forward]]

```python
forward(pixel_values: Tensor, qformer_input_ids: Tensor, qformer_attention_mask: typing.Optional[torch.LongTensor] = None, input_ids: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.LongTensor] = None, decoder_input_ids: typing.Optional[torch.LongTensor] = None, decoder_attention_mask: typing.Optional[torch.LongTensor] = None, inputs_embeds: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.LongTensor] = None, interpolate_pos_encoding: bool = False, mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblip/modeling_instructblip.py#L1174)

**매개변수:**

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

qformer_input_ids (`torch.LongTensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : Q-Former 어휘 사전에서 입력 시퀀스 토큰의 인덱스입니다. 입력 토큰은 선택적으로 제공하여 텍스트 프롬프트로 사용할 수 있으며, Q-Former 모델이 이를 인코딩합니다. 인덱스는 [InstructBlipProcessor](/docs/transformers/main/ko/model_doc/instructblip#transformers.InstructBlipProcessor)를 사용하여 얻을 수 있습니다. 자세한 내용은 [InstructBlipProcessor.__call__()](/docs/transformers/main/ko/model_doc/instructblip#transformers.InstructBlipProcessor.__call__)를 참조하세요. [입력 ID란 무엇인가요?](../glossary#input-ids)

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

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

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

decoder_input_ids (`torch.LongTensor`, shape `(batch_size, target_sequence_length)`, *선택 사항*) : 어휘 내에서 디코더 입력 시퀀스 토큰의 인덱스입니다. [AutoTokenizer](/docs/transformers/main/ko/model_doc/auto#transformers.AutoTokenizer)를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 [PreTrainedTokenizer.encode()](/docs/transformers/main/ko/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 및 [PreTrainedTokenizer.__call__()](/docs/transformers/main/ko/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)를 참조하세요. [디코더 입력 ID란 무엇인가요?](../glossary#decoder-input-ids)

decoder_attention_mask (`torch.BoolTensor`, shape `(batch_size, target_sequence_length)`, *선택 사항*) : 기본 동작: `decoder_input_ids`의 pad 토큰을 무시하는 텐서를 생성합니다. 기본적으로 Causal mask도 사용됩니다. 인코더-디코더 언어 모델(T5 등)을 사용하는 경우에만 관련이 있습니다.

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

labels (`torch.LongTensor`, shape `(batch_size,)`, *선택 사항*) : 언어 모델링 손실을 계산하기 위한 라벨. 인덱스는 `[-100, 0, ..., config.vocab_size - 1]` 범위여야 합니다. `-100`으로 설정된 모든 라벨은 무시(마스크)되며, 손실은 `[0, ..., config.vocab_size]` 범위의 라벨에 대해서만 계산됩니다.

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

mm_encoder_outputs (`dict[str, ~modeling_outputs.BaseModelOutputWithPooling]`, *선택 사항*) : 키가 지원되는 모달리티이고 값이 해당 모달리티의 인코딩된 출력인 Dict입니다. 각 인코딩된 출력은 (`pooler_output`, *선택 사항*: `last_hidden_states`, *선택 사항*: `hidden_states`, *선택 사항*: `attentions`)의 튜플로 구성되며, `pooler_output`의 shape은 `(batch_size, sequence_length, hidden_size)`, *선택 사항*)입니다. 이는 인코더의 멀티모달 특징을 텍스트 임베딩으로 병합한 시퀀스입니다.

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

`InstructBlipForConditionalGenerationModelOutput` 또는 `torch.Tensor`의 튜플(`return_dict=False`가 전달되거나 `config.return_dict=False`인 경우)로, 구성([InstructBlipConfig](/docs/transformers/main/ko/model_doc/instructblip#transformers.InstructBlipConfig))과 입력에 따라 다양한 요소를 포함합니다.

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

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

- **loss** (`torch.Tensor`, *선택 사항*, `labels`이 제공될 때 반환되며, `torch.Tensor` 형상 `(1,)`) -- 언어 모델에서 산출된 언어 모델링 손실.
- **logits** (`torch.Tensor`, shape `(batch_size, sequence_length, config.vocab_size)`) -- 언어 모델의 언어 모델링 헤드에 대한 예측 점수입니다.
- **vision_outputs** (`~modeling_outputs.BaseModelOutputWithPooling`, *선택 사항*) -- 비전 인코더의 출력입니다.
- **qformer_outputs** (`~modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions`, *선택 사항*) -- Q-Former(Querying Transformer)의 출력입니다.
- **language_model_outputs** (`CausalLMOutputWithPast` 또는 `Seq2SeqLMOutput`) -- 언어 모델의 출력입니다.

예:

```python
>>> from transformers import InstructBlipProcessor, InstructBlipForConditionalGeneration
>>> import torch
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> model = InstructBlipForConditionalGeneration.from_pretrained("Salesforce/instructblip-vicuna-7b")
>>> processor = InstructBlipProcessor.from_pretrained("Salesforce/instructblip-vicuna-7b")

>>> device = "cuda" if torch.cuda.is_available() else "cpu"
>>> model.to(device)
>>> url = "https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/lavis_confusing_pictures.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read())).convert("RGB")
>>> prompt = "What is unusual about this image?"
>>> inputs = processor(images=image, text=prompt, return_tensors="pt").to(device)

>>> outputs = model.generate(
...     **inputs,
...     do_sample=False,
...     num_beams=5,
...     max_length=256,
...     min_length=1,
...     top_p=0.9,
...     repetition_penalty=1.5,
...     length_penalty=1.0,
...     temperature=1,
... )
>>> generated_text = processor.batch_decode(outputs, skip_special_tokens=True)[0].strip()
>>> print(generated_text)
The unusual aspect of this image is that a man is ironing clothes on the back of a yellow SUV, which is parked in the middle of a busy city street. This is an unconventional approach to ironing clothes, as it requires the man to balance himself and his ironing equipment on top of the vehicle while navigating through traffic. Additionally, the presence of taxis and other vehicles in the scene further emphasizes the unusual nature of this situation.
```

#### generate[[transformers.InstructBlipForConditionalGeneration.generate]]

```python
generate(pixel_values: Tensor, qformer_input_ids: typing.Optional[torch.LongTensor] = None, qformer_attention_mask: typing.Optional[torch.LongTensor] = None, input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.LongTensor] = None, inputs_embeds: typing.Optional[torch.Tensor] = None, interpolate_pos_encoding: bool = False, **generate_kwargs)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblip/modeling_instructblip.py#L1313)

**매개변수:**

pixel_values (`torch.Tensor`, shape: (batch_size, num_channels, height, width)) : 처리할 입력 이미지.

qformer_input_ids (`torch.LongTensor`, shape (batch_size, sequence_length), *선택 사항*) : Q-Former 모듈에 입력되는 프롬프트로 사용되는 시퀀스.

qformer_attention_mask (`torch.LongTensor`, shape (batch_size, sequence_length), *선택 사항*) : 패딩 토큰 인덱스에 대한 어텐션 수행을 방지하기 위한 마스크.

input_ids (`torch.LongTensor`, shape (batch_size, sequence_length), *선택 사항*) : 생성을 위한 프롬프트로 사용되는 시퀀스.

attention_mask (`torch.LongTensor`, shape (batch_size, sequence_length), *선택 사항*) : 패딩 토큰 인덱스에 대한 어텐션 수행을 방지하기 위한 마스크.

inputs_embeds (`torch.Tensor`, shape `(batch_size, sequence_length, hidden_size)`) : 입력의 임베디드 표현입니다. int 토큰이 아닌 float여야 합니다.

interpolate_pos_encoding (`bool`, *선택 사항*, 기본값 `False`) : 이미지 임베딩의 위치 인코딩을 보간할지 여부입니다.

**반환값:** `captions (list)`

batch_size * num_captions 길이의 문자열 목록입니다.

`generate` 함수를 오버라이드하여 모델을 조건부 생성기로 사용할 수 있도록 합니다.

#### get_image_features[[transformers.InstructBlipForConditionalGeneration.get_image_features]]

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

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblip/modeling_instructblip.py#L1091)

**매개변수:**

pixel_values (`torch.Tensor`, shape `(batch_size, num_channels, image_size, image_size)`) : 입력 이미지에 해당하는 텐서.

qformer_input_ids (`torch.LongTensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : Q-Former 어휘 사전에서 입력 시퀀스 토큰의 인덱스입니다. 입력 토큰은 선택적으로 제공하여 텍스트 프롬프트로 사용할 수 있으며, Q-Former 모델이 이를 인코딩합니다. 인덱스는 [InstructBlipProcessor](/docs/transformers/main/ko/model_doc/instructblip#transformers.InstructBlipProcessor)를 사용하여 얻을 수 있습니다. 자세한 내용은 [InstructBlipProcessor.__call__()](/docs/transformers/main/ko/model_doc/instructblip#transformers.InstructBlipProcessor.__call__)를 참조하세요. [입력 ID란 무엇인가요?](../glossary#input-ids)

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

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

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

`BaseModelOutputWithVisionQformerOutputs` 또는 `torch.Tensor`의 튜플(`return_dict=False`가 전달되거나 `config.return_dict=False`인 경우)로, [InstructBlipConfig](/docs/transformers/main/ko/model_doc/instructblip#transformers.InstructBlipConfig) 및 입력에 따라 다양한 요소를 포함합니다.

- **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 가중치입니다.
- **vision_outputs** (`~modeling_outputs.BaseModelOutputWithPooling`, *선택 사항*) -- 비전 인코더의 출력입니다.
- **qformer_outputs** (`~modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions`, *선택 사항*) -- Q-Former(Querying Transformer)의 출력입니다.

예:

```python
>>> from PIL import Image
>>> from transformers import AutoProcessor, InstructBlipForConditionalGeneration

>>> model = InstructBlipForConditionalGeneration.from_pretrained("Salesforce/instructblip-flan-t5-xl")
>>> processor = AutoProcessor.from_pretrained("Salesforce/instructblip-flan-t5-xl")

>>> messages = [
...     {
...         "role": "user", "content": [
...             {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
...             {"type": "text", "text": "Where is the cat standing?"},
...         ]
...     },
... ]

>>> inputs = processor.apply_chat_template(
...     messages,
...     tokenize=True,
...     return_dict=True,
...     return_tensors="pt",
...     add_generation_prompt=True
... )
>>> # Generate
>>> generate_ids = model.generate(**inputs)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True)[0]
```

