# BEiT

## 개요

BEiT 모델은 Hangbo Bao, Li Dong, Furu Wei가 [BEiT: BERT Pre-Training of Image Transformers](https://huggingface.co/papers/2106.08254)에서 제안했습니다. BERT에서 영감을 받은 BEiT는 Vision Transformer(ViT)의 자기지도 사전 학습이 지도 사전 학습보다 우수한 성능을 내도록 한 최초의 논문입니다. [원본 ViT 논문](https://huggingface.co/papers/2010.11929)에서와 같이 이미지의 클래스를 예측하도록 모델을 사전 학습하는 대신, BEiT 모델은 마스킹된 패치를 입력으로 받아 OpenAI의 [DALL-E 모델](https://huggingface.co/papers/2102.12092) 코드북에서 시각 토큰을 예측하도록 사전 학습됩니다.

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

*이미지 Transformer 기반 양방향 인코더 표현(Bidirectional Encoder representation from Image Transformers)을 의미하는 BEiT라는 자기지도형 비전 표현 모델을 소개합니다. 자연어 처리 분야에서 개발된 BERT를 따라, 비전 Transformer를 사전 학습하기 위해 마스킹된 이미지 모델링 작업을 제안합니다. 구체적으로, 사전 학습에서 각 이미지는 두 가지 뷰, 즉 이미지 패치(예: 16x16 픽셀)와 시각 토큰(즉, 이산 토큰)을 가집니다. 먼저 원본 이미지를 시각 토큰으로 "토큰화"합니다. 그런 다음 일부 이미지 패치를 무작위로 마스킹하고 이를 백본 Transformer에 입력합니다. 사전 학습의 목표는 손상된 이미지 패치를 기반으로 원래의 시각 토큰을 복원하는 것입니다. BEiT의 사전 학습이 완료되면, 사전 학습된 인코더 위에 작업 레이어를 추가하여 모델 매개변수를 하위 작업에 대해 직접 미세 조정합니다. 이미지 분류 및 의미론적 분할에 대한 실험 결과는 이전의 사전 학습 방법과 경쟁력 있는 결과를 달성함을 보여줍니다. 예를 들어, base-size BEiT는 ImageNet-1K에서 83.2%의 top-1 정확도를 달성하여, 동일한 설정에서 처음부터 학습한 DeiT(81.8%)를 크게 능가합니다. 또한, large-size BEiT는 ImageNet-1K만 사용하여 86.3%를 달성하며, ImageNet-22K에서 지도형 사전 학습을 수행한 ViT-L(85.2%)조차 능가합니다.*

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

## 사용 팁

- BEiT 모델은 일반적인 Vision Transformer이지만, 지도 학습이 아닌 자기 지도 방식으로 사전 학습됩니다. ImageNet-1K와 CIFAR-100에서 미세 조정 시 [원본 모델(ViT)](vit)과 [Data-efficient Image Transformers(DeiT)](deit) 모두보다 우수한 성능을 보입니다. 추론 및 사용자 정의 데이터에 대한 미세 조정에 관한 데모 노트북은 [여기](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/VisionTransformer)에서 확인하실 수 있습니다([ViTImageProcessor](/docs/transformers/main/ko/model_doc/vit#transformers.ViTImageProcessor)를 [BeitImageProcessor](/docs/transformers/main/ko/model_doc/beit#transformers.BeitImageProcessor)로, [ViTForImageClassification](/docs/transformers/main/ko/model_doc/vit#transformers.ViTForImageClassification)를 [BeitForImageClassification](/docs/transformers/main/ko/model_doc/beit#transformers.BeitForImageClassification)로 교체하기만 하면 됩니다).
- DALL-E의 이미지 토크나이저를 BEiT와 결합하여 마스킹 이미지 모델링을 수행하는 방법을 보여주는 데모 노트북도 있습니다. [여기](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/BEiT)에서 확인하실 수 있습니다.
- BEiT 모델은 각 이미지가 동일한 크기(해상도)를 가질 것을 기대하므로, [BeitImageProcessor](/docs/transformers/main/ko/model_doc/beit#transformers.BeitImageProcessor)를 사용하여 모델에 맞게 이미지를 리사이즈(또는 리스케일)하고 정규화할 수 있습니다.
- 사전 학습 또는 파인튜닝 시 사용된 패치 해상도와 이미지 해상도는 각 체크포인트의 이름에 반영됩니다. 예를 들어, `microsoft/beit-base-patch16-224`는 패치 해상도가 16x16이고 파인튜닝 해상도가 224x224인 base 크기 아키텍처를 나타냅니다. 모든 체크포인트는 [hub](https://huggingface.co/models?search=microsoft/beit)에서 찾을 수 있습니다.
- 사용 가능한 체크포인트는 (1) [ImageNet-22k](http://www.image-net.org/)(1,400만 개의 이미지와 22k개의 클래스로 구성된 데이터셋)에서만 사전 학습된 경우, (2) ImageNet-22k에서 추가로 미세 조정된 경우, (3) [ImageNet-1k](http://www.image-net.org/challenges/LSVRC/2012/)(ILSVRC 2012라고도 불리며, 130만 개의 이미지와 1,000개의 클래스로 구성된 데이터셋)에서 추가로 미세 조정된 경우입니다.
- BEiT는 T5 모델에서 영감을 받은 상대 위치 임베딩을 사용합니다. 사전 학습 동안, 저자들은 여러 자기 주의(self-attention) 레이어 간에 상대 위치 편향을 공유했습니다. 미세 조정 동안, 각 레이어의 상대 위치 편향은 사전 학습 후 얻은 공유 상대 위치 편향으로 초기화됩니다. 참고로, 처음부터 모델을 사전 학습하려면 위치 임베딩을 추가하기 위해 [BeitConfig](/docs/transformers/main/ko/model_doc/beit#transformers.BeitConfig)의 `use_relative_position_bias` 또는 `use_relative_position_bias` 속성을 `True`로 설정해야 합니다.

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

 BEiT 사전 학습. 원 논문에서 가져왔습니다.

### Scaled Dot Product Attention(SDPA) 사용

PyTorch에는 `torch.nn.functional`의 일부로 네이티브 scaled dot-product attention(SDPA) 연산자가 포함되어 있습니다. 이 함수는 입력과 사용 중인 하드웨어에 따라 적용할 수 있는 여러 구현을 포함합니다. 자세한 내용은 [공식 문서](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html) 또는 [GPU Inference](https://huggingface.co/docs/transformers/main/en/perf_infer_gpu_one#pytorch-scaled-dot-product-attention) 페이지를 참고하세요.

구현이 사용 가능한 경우 `torch>=2.1.1`에서는 기본적으로 SDPA가 사용되지만, `from_pretrained()`에서 `attn_implementation="sdpa"`를 설정하여 SDPA 사용을 명시적으로 요청할 수도 있습니다.

```python
from transformers import BeitForImageClassification

model = BeitForImageClassification.from_pretrained("microsoft/beit-base-patch16-224", attn_implementation="sdpa", device_map="auto")
...
```

최고의 속도 향상을 위해 모델은 반정밀(half-precision, 예: `torch.float16` 또는 `torch.bfloat16`)로 로드하는 것을 권장합니다.

로컬 벤치마크(NVIDIA GeForce RTX 2060-8GB, PyTorch 2.5.1, OS Ubuntu 20.04)에서 `float16`와 `microsoft/beit-base-patch16-224` 모델을 사용하여 학습 및 추론 과정에서 다음과 같은 개선 사항을 확인했습니다:

#### 학습

| num_training_steps | batch_size | image_size   | is_cuda | 배치당 시간 (eager - s) | batch당 시간 (sdpa - s) | 속도 향상 (%) | Eager 피크 메모리 (MB) | SDPA 피크 메모리 (MB) | 메모리 절약 (%) |
|--------------------|------------|--------------|---------|----------------------------|---------------------------|-------------|----------------------|--------------------|----------------|
| 50                 | 2          | (1048, 640)  | True    | 0.984                      | 0.746                     | 31.975      | 6738.915            | 4319.886          | 55.998         |

#### 추론

|   이미지 배치 크기 |   Eager (초당 반복 횟수) | Eager CI, %   |   Eager 메모리(MB) |   SDPA (초당 반복 횟수) | SDPA CI, %   |   SDPA 메모리(MB) |   SDPA 속도 향상 | SDPA 메모리 절약 (%) |
|-------------------:|-----------------:|:--------------|--------------------:|----------------:|:-------------|-------------------:|---------------:|----------------------:|
|                  1 |            0.012 | ±0.3%         |         3.76657e+08 |           0.011 | ±0.5%        |        3.75739e+08 |          1.05  |                 0.244 |
|                  4 |            0.013 | ±0.1%         |         4.03147e+08 |           0.011 | ±0.2%        |        3.90554e+08 |          1.178 |                 3.225 |
|                 16 |            0.045 | ±0.1%         |         4.96697e+08 |           0.035 | ±0.1%        |        4.51232e+08 |          1.304 |                10.076 |
|                 32 |            0.088 | ±0.1%         |         6.24417e+08 |           0.066 | ±0.1%        |        5.33488e+08 |          1.325 |                17.044 |

## 리소스

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

- [BeitForImageClassification](/docs/transformers/main/ko/model_doc/beit#transformers.BeitForImageClassification)은 이 [노트북](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb)에서 지원됩니다.
- 참고: [이미지 분류 작업 가이드](../tasks/image_classification)

**의미 분할**

- [시맨틱 세분화 작업 가이드](../tasks/semantic_segmentation)

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

## BEiT 고유 출력[[transformers.models.beit.modeling_beit.BeitModelOutputWithPooling]]

#### transformers.models.beit.modeling_beit.BeitModelOutputWithPooling[[transformers.models.beit.modeling_beit.BeitModelOutputWithPooling]]

```python
transformers.models.beit.modeling_beit.BeitModelOutputWithPooling(last_hidden_state: typing.Optional[torch.Tensor] = None, pooler_output: typing.Optional[torch.Tensor] = None, hidden_states: tuple[torch.Tensor, ...] | None = None, attentions: tuple[torch.Tensor, ...] | None = None)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/beit/modeling_beit.py#L54)

**매개변수:**

last_hidden_state (`torch.Tensor`, shape `(batch_size, sequence_length, hidden_size)`) : 모델의 마지막 레이어 출력에서 생성된 hidden-states 시퀀스.

pooler_output (`torch.Tensor`, shape `(batch_size, hidden_size)`) : *config.use_mean_pooling*이 True로 설정된 경우, *[CLS]* 토큰을 제외한 패치 토큰의 마지막 레이어 hidden states의 평균입니다. False로 설정된 경우, *[CLS]* 토큰의 최종 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`의 튜플(레이어당 하나), shape은 `(batch_size, num_heads, sequence_length, sequence_length)`입니다. attention softmax 이후의 attention 가중치로, self-attention 헤드에서 가중 평균을 계산하는 데 사용됩니다.

[BeitModel](/docs/transformers/main/ko/model_doc/beit#transformers.BeitModel)의 출력에 대한 클래스입니다.

## BeitConfig[[transformers.BeitConfig]]

#### transformers.BeitConfig[[transformers.BeitConfig]]

```python
transformers.BeitConfig(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 = 8192, 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.0, attention_probs_dropout_prob: float | int = 0.0, initializer_range: float = 0.02, layer_norm_eps: float = 1e-12, image_size: int | list[int] | tuple[int, int] = 224, patch_size: int | list[int] | tuple[int, int] = 16, num_channels: int = 3, use_mask_token: bool = False, use_absolute_position_embeddings: bool = False, use_relative_position_bias: bool = False, use_shared_relative_position_bias: bool = False, layer_scale_init_value: float = 0.1, drop_path_rate: float | int = 0.1, use_mean_pooling: bool = True, pool_scales: list[int] | tuple[int, ...] = (1, 2, 3, 6), use_auxiliary_head: bool = True, auxiliary_loss_weight: float = 0.4, auxiliary_channels: int = 256, auxiliary_num_convs: int = 1, auxiliary_concat_input: bool = False, semantic_loss_ignore_index: int = 255, _out_features: list[str] | None = None, _out_indices: list[int] | None = None, add_fpn: bool = False, reshape_hidden_states: bool = True)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/beit/configuration_beit.py#L25)

**매개변수:**

vocab_size (`int`, *선택 사항*, 기본값 `8192`) : 모델의 어휘 크기입니다. `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.0`) : 임베딩, 인코더, 풀러의 모든 완전 연결 계층에 적용되는 dropout 확률입니다.

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

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

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

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

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

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

use_mask_token (`bool`, *선택 사항*, 기본값 `False`) : masked image modeling에 mask token을 사용할지 여부입니다.

use_absolute_position_embeddings (`bool`, *선택 사항*, 기본값 `False`) : 절대 위치 임베딩을 사용할지 여부.

use_relative_position_bias (`bool`, *선택 사항*, 기본값 `False`) : self-attention 레이어에서 T5 스타일의 상대 위치 임베딩을 사용할지 여부입니다.

use_shared_relative_position_bias (`bool`, *선택 사항*, 기본값 `False`) : Transformer의 모든 self-attention 레이어에서 동일한 상대 위치 임베딩을 사용할지 여부입니다.

layer_scale_init_value (`float`, *선택 사항*, 기본값 `0.1`) : self-attention 레이어에서 사용할 스케일입니다. base 모델은 0.1, large 모델은 1e-6을 사용합니다. 0으로 설정하면 layer scale을 비활성화합니다.

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

use_mean_pooling (`bool`, *선택 사항*, 기본값 `True`) : 분류 헤드를 적용하기 전에, CLS 토큰의 최종 숨겨진 상태를 사용하는 대신 패치의 최종 숨겨진 상태를 평균 풀링할지 여부.

pool_scales (`tuple[int]`, *선택 사항*, 기본값 `[1, 2, 3, 6]`) : 마지막 feature map에 적용되는 Pooling Pyramid Module에서 사용되는 pooling scale입니다.

use_auxiliary_head (`bool`, *선택 사항*, 기본값 `True`) : 학습 중에 보조 헤드를 사용할지 여부.

auxiliary_loss_weight (`float`, *선택 사항*, 기본값 0.4) : 보조 헤드의 교차 엔트로피 손실 가중치.

auxiliary_channels (`int`, *선택 사항*, 기본값 256) : 보조 헤드에 사용할 채널 수.

auxiliary_num_convs (`int`, *선택 사항*, 기본값 1) : 보조 헤드에 사용할 컨볼루션 레이어의 수.

auxiliary_concat_input (`bool`, *선택 사항*, 기본값 `False`) : 분류 레이어 전에 보조 헤드(auxiliary head)의 출력을 입력과 연결(concatenate)할지 여부.

semantic_loss_ignore_index (`int`, *선택 사항*, 기본값 `255`) : 시맨틱 세그멘테이션 모델의 손실 함수가 무시하는 인덱스입니다.

add_fpn (`bool`, *선택 사항*, 기본값 `False`) : 백본의 일부로 FPN을 추가할지 여부. `BeitBackbone`에만 관련이 있습니다.

reshape_hidden_states (`bool`, *선택 사항*, 기본값 `True`) : 모델이 백본으로 사용될 경우, 피처 맵을 `(batch_size, hidden_size, height, width)` 모양의 4D 텐서로 리사이즈할지 여부입니다. `False`인 경우, 피처 맵은 `(batch_size, seq_len, hidden_size)` 모양의 3D 텐서가 됩니다. `BeitBackbone`에만 관련이 있습니다.

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

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 BeitConfig, BeitModel

>>> # Initializing a BEiT beit-base-patch16-224-pt22k style configuration
>>> configuration = BeitConfig()

>>> # Initializing a model (with random weights) from the beit-base-patch16-224-pt22k style configuration
>>> model = BeitModel(configuration)

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

## BeitImageProcessor[[transformers.BeitImageProcessor]]

#### transformers.BeitImageProcessor[[transformers.BeitImageProcessor]]

```python
transformers.BeitImageProcessor(**kwargs: *<class 'transformers.models.beit.image_processing_beit.BeitImageProcessorKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/beit/image_processing_beit.py#L50)

**매개변수:**

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

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

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*, 기본값 `{'height' : 224, 'width': 224}`): 모델에 대한 최대 입력 차원을 설명합니다.

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

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*, 기본값 `{'height' : 224, 'width': 224}`): `center_crop`를 적용한 후 출력 이미지의 크기.

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

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

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

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

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

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

do_pad (`bool`, *kwargs*, *선택*) : 이미지를 패딩할지 여부입니다. 패딩은 배치 내 가장 큰 크기로 수행하거나, 이미지마다 고정된 정사각형 크기로 수행합니다. 정확한 패딩 전략은 모델에 따라 달라집니다.

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 이미지를 패딩할 `{"height": int, "width" int}` 크기를 지정합니다. 전처리용으로 제공된 모든 이미지 크기보다 커야 합니다. `pad_size`가 제공되지 않으면, 이미지는 배치 내 가장 큰 높이와 너비로 패딩됩니다. `do_pad=True.`일 때만 적용됩니다.

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

data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *선택*) : `ChannelDimension.FIRST`만 지원됩니다. 느린 프로세서와의 호환성을 위해 추가되었습니다.

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *선택*) : 입력 이미지의 채널 차원 형식입니다. 설정하지 않으면 입력 이미지에서 채널 차원 형식을 추론합니다. 다음 중 하나일 수 있습니다: - `"channels_first"` 또는 `ChannelDimension.FIRST`: (num_channels, height, width) 형식의 이미지. - `"channels_last"` 또는 `ChannelDimension.LAST`: (height, width, num_channels) 형식의 이미지. - `"none"` 또는 `ChannelDimension.NONE`: (height, width) 형식의 이미지.

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 비디오를 처리할 장치입니다. 설정되지 않은 경우, 입력 비디오에서 장치를 추론합니다.

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : `'pt'`로 설정된 경우 스택된 텐서를 반환하고, 그렇지 않으면 텐서 목록을 반환합니다.

disable_grouping (`bool`, *kwargs*, *선택*) : 이미지의 크기에 따른 그룹화를 비활성화하여 이미지를 배치 대신 개별적으로 처리할지 여부입니다. None인 경우, 이미지가 CPU에 있으면 True, 그렇지 않으면 False로 설정됩니다. 이 선택은 https://github.com/huggingface/transformers/pull/38157에 자세히 설명된 경험적 관찰에 기반합니다.

image_seq_length (`int`, *kwargs*, *선택*) : 입력의 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.

do_reduce_labels (`bool`, *kwargs*, *선택 사항*, 기본값은 `self.do_reduce_labels`) : 세그멘테이션 맵의 모든 라벨 값을 1만큼 줄일지 여부입니다. 일반적으로 0을 배경으로 사용하고 배경 자체가 데이터셋의 모든 클래스에 포함되지 않는 데이터셋(예: ADE20k)에서 사용됩니다. 배경 라벨은 255로 대체됩니다.

BeitImageProcessor 이미지 프로세서를 생성합니다.

#### preprocess[[transformers.BeitImageProcessor.preprocess]]

```python
preprocess(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']], segmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, **kwargs: *<class 'transformers.models.beit.image_processing_beit.BeitImageProcessorKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/beit/image_processing_beit.py#L70)

**매개변수:**

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

segmentation_maps (`ImageInput`, *선택 사항*) : 전처리할 분할 맵.

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

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

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

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

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : `center_crop`를 적용한 후의 출력 이미지 크기.

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

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

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

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

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

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

do_pad (`bool`, *kwargs*, *선택*) : 이미지를 패딩할지 여부입니다. 패딩은 배치 내 가장 큰 크기로 수행하거나, 이미지마다 고정된 정사각형 크기로 수행합니다. 정확한 패딩 전략은 모델에 따라 달라집니다.

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 이미지를 패딩할 `{"height": int, "width" int}` 크기를 지정합니다. 전처리용으로 제공된 모든 이미지 크기보다 커야 합니다. `pad_size`가 제공되지 않으면, 이미지는 배치 내 가장 큰 높이와 너비로 패딩됩니다. `do_pad=True.`일 때만 적용됩니다.

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

data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *선택*) : `ChannelDimension.FIRST`만 지원됩니다. 느린 프로세서와의 호환성을 위해 추가되었습니다.

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *선택*) : 입력 이미지의 채널 차원 형식입니다. 설정하지 않으면 입력 이미지에서 채널 차원 형식을 추론합니다. 다음 중 하나일 수 있습니다: - `"channels_first"` 또는 `ChannelDimension.FIRST`: (num_channels, height, width) 형식의 이미지. - `"channels_last"` 또는 `ChannelDimension.LAST`: (height, width, num_channels) 형식의 이미지. - `"none"` 또는 `ChannelDimension.NONE`: (height, width) 형식의 이미지.

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 비디오를 처리할 장치입니다. 설정되지 않은 경우, 입력 비디오에서 장치를 추론합니다.

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : `'pt'`로 설정된 경우 스택된 텐서를 반환하고, 그렇지 않으면 텐서 목록을 반환합니다.

disable_grouping (`bool`, *kwargs*, *선택*) : 이미지의 크기에 따른 그룹화를 비활성화하여 이미지를 배치 대신 개별적으로 처리할지 여부입니다. None인 경우, 이미지가 CPU에 있으면 True, 그렇지 않으면 False로 설정됩니다. 이 선택은 https://github.com/huggingface/transformers/pull/38157에 자세히 설명된 경험적 관찰에 기반합니다.

image_seq_length (`int`, *kwargs*, *선택*) : 입력의 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.

do_reduce_labels (`bool`, *kwargs*, *선택 사항*, 기본값은 `self.do_reduce_labels`) : 세그멘테이션 맵의 모든 라벨 값을 1만큼 줄일지 여부입니다. 일반적으로 0을 배경으로 사용하고 배경 자체가 데이터셋의 모든 클래스에 포함되지 않는 데이터셋(예: ADE20k)에서 사용됩니다. 배경 라벨은 255로 대체됩니다.

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

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

#### post_process_semantic_segmentation[[transformers.BeitImageProcessor.post_process_semantic_segmentation]]

```python
post_process_semantic_segmentation(outputs, target_sizes: list[tuple] | None = None, return_segmentation_scores: bool = False)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/beit/image_processing_beit.py#L183)

**매개변수:**

outputs ([BeitForSemanticSegmentation](/docs/transformers/main/ko/model_doc/beit#transformers.BeitForSemanticSegmentation)) : 모델의 원시 출력.

target_sizes (`list[Tuple]`, 길이 `batch_size`, *선택 사항*) : 각 예측의 요청된 최종 크기(높이, 너비)에 해당하는 튜플 목록. 설정되지 않으면 예측 이미지가 리사이즈되지 않습니다.

return_segmentation_scores (`bool`, *선택 사항*, 기본값 `False`) : 분할 맵과 함께 분할 점수를 반환할지 여부입니다. `True`인 경우, 반환된 리스트의 각 요소는 `segmentation` 필드(클래스 ID, shape `(height, width)`)와 `segmentation_scores` 필드(shape `(num_classes, height, width)`)를 가진 `SemanticSegmentationPostProcessorOutput`입니다.

**반환값:** `list[torch.Tensor]` 또는 `list[SemanticSegmentationPostProcessorOutput]`

`return_segmentation_scores=False`(기본값)인 경우, 각 항목이 클래스 ID를 가진 `(height, width)` 모양의 세그멘테이션 맵인 `batch_size` 길이의 리스트를 반환합니다. `return_segmentation_scores=True`인 경우, `segmentation`(클래스 ID, `(height, width)` 모양)와 `segmentation_scores`(`(num_classes, height, width)` 모양) 필드를 가진 `SemanticSegmentationPostProcessorOutput` 리스트를 반환합니다. 두 경우 모두 `(height, width)`는 대상 크기(`target_sizes`가 지정된 경우)에 해당합니다.

[BeitForSemanticSegmentation](/docs/transformers/main/ko/model_doc/beit#transformers.BeitForSemanticSegmentation)의 출력을 의미 분할 맵으로 변환합니다.

## BeitImageProcessorPil[[transformers.BeitImageProcessorPil]]

#### transformers.BeitImageProcessorPil[[transformers.BeitImageProcessorPil]]

```python
transformers.BeitImageProcessorPil(**kwargs: *<class 'transformers.models.beit.image_processing_pil_beit.BeitImageProcessorKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/beit/image_processing_pil_beit.py#L53)

**매개변수:**

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

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

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*, 기본값 `{'height' : 224, 'width': 224}`): 모델에 대한 최대 입력 차원을 설명합니다.

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

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*, 기본값 `{'height' : 224, 'width': 224}`): `center_crop`를 적용한 후 출력 이미지의 크기.

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

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

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

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

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

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

do_pad (`bool`, *kwargs*, *선택*) : 이미지를 패딩할지 여부입니다. 패딩은 배치 내 가장 큰 크기로 수행하거나, 이미지마다 고정된 정사각형 크기로 수행합니다. 정확한 패딩 전략은 모델에 따라 달라집니다.

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 이미지를 패딩할 `{"height": int, "width" int}` 크기를 지정합니다. 전처리용으로 제공된 모든 이미지 크기보다 커야 합니다. `pad_size`가 제공되지 않으면, 이미지는 배치 내 가장 큰 높이와 너비로 패딩됩니다. `do_pad=True.`일 때만 적용됩니다.

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

data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *선택*) : `ChannelDimension.FIRST`만 지원됩니다. 느린 프로세서와의 호환성을 위해 추가되었습니다.

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *선택*) : 입력 이미지의 채널 차원 형식입니다. 설정하지 않으면 입력 이미지에서 채널 차원 형식을 추론합니다. 다음 중 하나일 수 있습니다: - `"channels_first"` 또는 `ChannelDimension.FIRST`: (num_channels, height, width) 형식의 이미지. - `"channels_last"` 또는 `ChannelDimension.LAST`: (height, width, num_channels) 형식의 이미지. - `"none"` 또는 `ChannelDimension.NONE`: (height, width) 형식의 이미지.

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 비디오를 처리할 장치입니다. 설정되지 않은 경우, 입력 비디오에서 장치를 추론합니다.

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : `'pt'`로 설정된 경우 스택된 텐서를 반환하고, 그렇지 않으면 텐서 목록을 반환합니다.

disable_grouping (`bool`, *kwargs*, *선택*) : 이미지의 크기에 따른 그룹화를 비활성화하여 이미지를 배치 대신 개별적으로 처리할지 여부입니다. None인 경우, 이미지가 CPU에 있으면 True, 그렇지 않으면 False로 설정됩니다. 이 선택은 https://github.com/huggingface/transformers/pull/38157에 자세히 설명된 경험적 관찰에 기반합니다.

image_seq_length (`int`, *kwargs*, *선택*) : 입력의 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.

do_reduce_labels (`bool`, *kwargs*, *선택 사항*, 기본값은 `self.do_reduce_labels`) : 세그멘테이션 맵의 모든 라벨 값을 1만큼 줄일지 여부입니다. 일반적으로 0을 배경으로 사용하고 배경 자체가 데이터셋의 모든 클래스에 포함되지 않는 데이터셋(예: ADE20k)에서 사용됩니다. 배경 라벨은 255로 대체됩니다.

BeitImageProcessor 이미지 프로세서를 생성합니다.

#### preprocess[[transformers.BeitImageProcessorPil.preprocess]]

```python
preprocess(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']], segmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, **kwargs: *<class 'transformers.models.beit.image_processing_pil_beit.BeitImageProcessorKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/beit/image_processing_pil_beit.py#L73)

**매개변수:**

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

segmentation_maps (`ImageInput`, *선택 사항*) : 전처리할 분할 맵.

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

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

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

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

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : `center_crop`를 적용한 후의 출력 이미지 크기.

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

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

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

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

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

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

do_pad (`bool`, *kwargs*, *선택*) : 이미지를 패딩할지 여부입니다. 패딩은 배치 내 가장 큰 크기로 수행하거나, 이미지마다 고정된 정사각형 크기로 수행합니다. 정확한 패딩 전략은 모델에 따라 달라집니다.

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 이미지를 패딩할 `{"height": int, "width" int}` 크기를 지정합니다. 전처리용으로 제공된 모든 이미지 크기보다 커야 합니다. `pad_size`가 제공되지 않으면, 이미지는 배치 내 가장 큰 높이와 너비로 패딩됩니다. `do_pad=True.`일 때만 적용됩니다.

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

data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *선택*) : `ChannelDimension.FIRST`만 지원됩니다. 느린 프로세서와의 호환성을 위해 추가되었습니다.

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *선택*) : 입력 이미지의 채널 차원 형식입니다. 설정하지 않으면 입력 이미지에서 채널 차원 형식을 추론합니다. 다음 중 하나일 수 있습니다: - `"channels_first"` 또는 `ChannelDimension.FIRST`: (num_channels, height, width) 형식의 이미지. - `"channels_last"` 또는 `ChannelDimension.LAST`: (height, width, num_channels) 형식의 이미지. - `"none"` 또는 `ChannelDimension.NONE`: (height, width) 형식의 이미지.

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 비디오를 처리할 장치입니다. 설정되지 않은 경우, 입력 비디오에서 장치를 추론합니다.

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : `'pt'`로 설정된 경우 스택된 텐서를 반환하고, 그렇지 않으면 텐서 목록을 반환합니다.

disable_grouping (`bool`, *kwargs*, *선택*) : 이미지의 크기에 따른 그룹화를 비활성화하여 이미지를 배치 대신 개별적으로 처리할지 여부입니다. None인 경우, 이미지가 CPU에 있으면 True, 그렇지 않으면 False로 설정됩니다. 이 선택은 https://github.com/huggingface/transformers/pull/38157에 자세히 설명된 경험적 관찰에 기반합니다.

image_seq_length (`int`, *kwargs*, *선택*) : 입력의 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.

do_reduce_labels (`bool`, *kwargs*, *선택 사항*, 기본값은 `self.do_reduce_labels`) : 세그멘테이션 맵의 모든 라벨 값을 1만큼 줄일지 여부입니다. 일반적으로 0을 배경으로 사용하고 배경 자체가 데이터셋의 모든 클래스에 포함되지 않는 데이터셋(예: ADE20k)에서 사용됩니다. 배경 라벨은 255로 대체됩니다.

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

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

#### post_process_semantic_segmentation[[transformers.BeitImageProcessorPil.post_process_semantic_segmentation]]

```python
post_process_semantic_segmentation(outputs, target_sizes: list[tuple] | None = None, return_segmentation_scores: bool = False)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/beit/image_processing_pil_beit.py#L169)

**매개변수:**

outputs ([BeitForSemanticSegmentation](/docs/transformers/main/ko/model_doc/beit#transformers.BeitForSemanticSegmentation)) : 모델의 원시 출력.

target_sizes (`list[Tuple]`, 길이 `batch_size`, *선택 사항*) : 각 예측의 요청된 최종 크기(높이, 너비)에 해당하는 튜플 목록. 설정되지 않으면 예측 이미지가 리사이즈되지 않습니다.

return_segmentation_scores (`bool`, *선택 사항*, 기본값 `False`) : 분할 맵과 함께 분할 점수를 반환할지 여부입니다. `True`인 경우, 반환된 리스트의 각 요소는 `segmentation` 필드(클래스 ID, shape `(height, width)`)와 `segmentation_scores` 필드(shape `(num_classes, height, width)`)를 가진 `SemanticSegmentationPostProcessorOutput`입니다.

**반환값:** `list[torch.Tensor]` 또는 `list[SemanticSegmentationPostProcessorOutput]`

`return_segmentation_scores=False`(기본값)인 경우, 각 항목이 클래스 ID를 가진 `(height, width)` 모양의 세그멘테이션 맵인 `batch_size` 길이의 리스트를 반환합니다. `return_segmentation_scores=True`인 경우, `segmentation`(클래스 ID, `(height, width)` 모양)와 `segmentation_scores`(`(num_classes, height, width)` 모양) 필드를 가진 `SemanticSegmentationPostProcessorOutput` 리스트를 반환합니다. 두 경우 모두 `(height, width)`는 대상 크기(`target_sizes`가 지정된 경우)에 해당합니다.

[BeitForSemanticSegmentation](/docs/transformers/main/ko/model_doc/beit#transformers.BeitForSemanticSegmentation)의 출력을 의미 분할 맵으로 변환합니다.

## BeitModel[[transformers.BeitModel]]

#### transformers.BeitModel[[transformers.BeitModel]]

```python
transformers.BeitModel(config: BeitConfig, add_pooling_layer: bool = True)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/beit/modeling_beit.py#L486)

**매개변수:**

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

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

특정 헤드가 위에 없는 순수한 Beit 모델로, 원시 hidden-states를 출력합니다.

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

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

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/beit/modeling_beit.py#L512)

**매개변수:**

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

bool_masked_pos (`torch.BoolTensor`, shape `(batch_size, num_patches)`, *선택 사항*) : Boolean masked positions. 어떤 patch가 mask(1)되고 어떤 patch는 mask되지(0) 않았는지를 나타냅니다.

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

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

**반환값:** [BeitModelOutputWithPooling](/docs/transformers/main/ko/model_doc/beit#transformers.models.beit.modeling_beit.BeitModelOutputWithPooling) 또는 `tuple(torch.Tensor)`

[BeitModelOutputWithPooling](/docs/transformers/main/ko/model_doc/beit#transformers.models.beit.modeling_beit.BeitModelOutputWithPooling) 또는 `torch.Tensor` 튜플(`return_dict=False`이 전달되었거나 `config.return_dict=False`인 경우)이며, 구성([BeitConfig](/docs/transformers/main/ko/model_doc/beit#transformers.BeitConfig)) 및 입력에 따라 다양한 요소를 포함합니다.

[BeitModel](/docs/transformers/main/ko/model_doc/beit#transformers.BeitModel)의 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)`) -- *config.use_mean_pooling*이 True로 설정된 경우, *[CLS]* 토큰을 제외한 패치 토큰의 마지막 레이어 hidden states의 평균입니다. False로 설정된 경우, *[CLS]* 토큰의 최종 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
```

## BeitForMaskedImageModeling[[transformers.BeitForMaskedImageModeling]]

#### transformers.BeitForMaskedImageModeling[[transformers.BeitForMaskedImageModeling]]

```python
transformers.BeitForMaskedImageModeling(config: BeitConfig)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/beit/modeling_beit.py#L583)

**매개변수:**

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

Beit Model transformer with a 'language' modeling head on top. BEiT은 VQ-VAE의 시각 토큰을 예측하여 마스킹 이미지 모델링을 수행하는 반면, ViT와 DeiT와 같은 다른 비전 모델은 RGB 픽셀 값을 예측합니다. 따라서 이 클래스는 [AutoModelForMaskedImageModeling](/docs/transformers/main/ko/model_doc/auto#transformers.AutoModelForMaskedImageModeling)과 호환되지 않으므로, BEiT로 마스킹 이미지 모델링을 수행하려면 [BeitForMaskedImageModeling](/docs/transformers/main/ko/model_doc/beit#transformers.BeitForMaskedImageModeling)을 직접 사용해야 합니다.

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

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

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/beit/modeling_beit.py#L600)

**매개변수:**

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

bool_masked_pos (`torch.BoolTensor`, shape `(batch_size, num_patches)`) : Boolean masked positions. 어떤 patch가 mask되어 있는지(1) 아니면 그렇지 않은지(0)를 나타냅니다.

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

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

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

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

[MaskedLMOutput](/docs/transformers/main/ko/main_classes/output#transformers.modeling_outputs.MaskedLMOutput) 또는 `torch.Tensor`의 튜플(`return_dict=False`이 전달되거나 `config.return_dict=False`인 경우)로, 구성([BeitConfig](/docs/transformers/main/ko/model_doc/beit#transformers.BeitConfig)) 및 입력에 따라 다양한 요소를 포함합니다.

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

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

- **loss** (`torch.Tensor`, shape `(1,)`, *선택*, `labels`이 제공될 때 반환됨) -- Masked language modeling(MLM) loss.
- **logits** (`torch.Tensor`, shape `(batch_size, sequence_length, config.vocab_size)`) -- 언어 모델링 헤드에서 생성된 예측 점수(SoftMax 적용 전 각 어휘 토큰에 대한 점수).
- **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 AutoImageProcessor, BeitForMaskedImageModeling
>>> import torch
>>> from PIL import Image
>>> import requests

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)

>>> image_processor = AutoImageProcessor.from_pretrained("microsoft/beit-base-patch16-224-pt22k")
>>> model = BeitForMaskedImageModeling.from_pretrained("microsoft/beit-base-patch16-224-pt22k")

>>> num_patches = (model.config.image_size // model.config.patch_size) ** 2
>>> pixel_values = image_processor(images=image, return_tensors="pt").pixel_values
>>> # create random boolean mask of shape (batch_size, num_patches)
>>> bool_masked_pos = torch.randint(low=0, high=2, size=(1, num_patches)).bool()

>>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)
>>> loss, logits = outputs.loss, outputs.logits
>>> list(logits.shape)
[1, 196, 8192]
```

## BeitForImageClassification[[transformers.BeitForImageClassification]]

#### transformers.BeitForImageClassification[[transformers.BeitForImageClassification]]

```python
transformers.BeitForImageClassification(config: BeitConfig)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/beit/modeling_beit.py#L675)

**매개변수:**

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

이미지 분류 헤드가 위에 있는 Beit Model transformer(패치 토큰의 최종 숨겨진 상태 평균 위에 선형 레이어가 있는 형태)로, 예: ImageNet

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

```python
forward(pixel_values: typing.Optional[torch.Tensor] = None, labels: 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/beit/modeling_beit.py#L688)

**매개변수:**

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

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

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

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

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

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

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

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

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

예:

```python
>>> from transformers import AutoImageProcessor, BeitForImageClassification
>>> import torch
>>> from datasets import load_dataset

>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]

>>> image_processor = AutoImageProcessor.from_pretrained("microsoft/beit-base-patch16-224-pt22k")
>>> model = BeitForImageClassification.from_pretrained("microsoft/beit-base-patch16-224-pt22k")

>>> inputs = image_processor(image, return_tensors="pt")

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

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

## BeitForSemanticSegmentation[[transformers.BeitForSemanticSegmentation]]

#### transformers.BeitForSemanticSegmentation[[transformers.BeitForSemanticSegmentation]]

```python
transformers.BeitForSemanticSegmentation(config: BeitConfig)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/beit/modeling_beit.py#L978)

**매개변수:**

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

ADE20K, CityScapes와 같은 작업에 사용할 수 있도록 시맨틱 세그멘테이션 헤드가 위에 있는 Beit 모델.

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

```python
forward(pixel_values: typing.Optional[torch.Tensor] = None, labels: 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/beit/modeling_beit.py#L1000)

**매개변수:**

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

labels (`torch.LongTensor`, shape `(batch_size, height, width)`, *선택 사항*) : 손실을 계산하기 위한 ground truth semantic segmentation 맵입니다. 인덱스는 `[0, ..., config.num_labels - 1]` 범위에 있어야 합니다. `config.num_labels > 1`인 경우, 분류 손실(Cross-Entropy)이 계산됩니다.

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

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

[SemanticSegmenterOutput](/docs/transformers/main/ko/main_classes/output#transformers.modeling_outputs.SemanticSegmenterOutput) 또는 `torch.Tensor`의 튜플(`return_dict=False`이 전달되었거나 `config.return_dict=False`인 경우)로, 구성([BeitConfig](/docs/transformers/main/ko/model_doc/beit#transformers.BeitConfig)) 및 입력에 따라 다양한 요소를 포함합니다.

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

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

- **loss** (`torch.Tensor`, shape `(1,)`, *선택*, `labels`이 제공될 때 반환됨) -- 분류(또는 config.num_labels==1인 경우 회귀) 손실.
- **logits** (shape `(batch_size, config.num_labels, logits_height, logits_width)`의 `torch.Tensor`) -- 각 픽셀에 대한 분류 점수입니다.

  

  반환되는 logits는 입력으로 전달된 `pixel_values`와 반드시 동일한 크기를 갖지 않습니다. 이는 사용자가 후처리 단계에서 logits를 원본 이미지 크기로 리사이즈할 때 두 번의 보간을 수행하여 품질이 저하되는 것을 방지하기 위한 것입니다. 항상 logits의 shape을 확인하고 필요에 따라 리사이즈해야 합니다.

  
- **hidden_states** (`tuple(torch.Tensor)`, *선택*, `output_hidden_states=True`가 전달되거나 `config.output_hidden_states=True`일 때 반환) -- shape가 `(batch_size, patch_size, hidden_size)`인 `torch.Tensor`의 튜플 (모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개).

  각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.
- **attentions** (`tuple(torch.Tensor)`, *선택*, `output_attentions=True`가 전달되거나 `config.output_attentions=True`인 경우 반환) -- 각 레이어에 하나씩 해당하는 `torch.Tensor` 튜플이며, shape는 `(batch_size, num_heads, patch_size, sequence_length)`입니다.

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

예:

```python
>>> from transformers import AutoImageProcessor, BeitForSemanticSegmentation
>>> from PIL import Image
>>> import requests

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)

>>> image_processor = AutoImageProcessor.from_pretrained("microsoft/beit-base-finetuned-ade-640-640")
>>> model = BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640")

>>> inputs = image_processor(images=image, return_tensors="pt")
>>> outputs = model(**inputs)
>>> # logits are of shape (batch_size, num_labels, height, width)
>>> logits = outputs.logits
```

